-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathUse-GitHubRepositoryBranchesManager.ps1
170 lines (162 loc) · 8.42 KB
/
Use-GitHubRepositoryBranchesManager.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#Requires -Version 5.1
Set-StrictMode -Version Latest -Verbose
Function Use-GitHubRepositoryBranchesManager {
<#
.SYNOPSIS
GitHub repository branches manager.
.DESCRIPTION
With this function you can manage branches of GitHub repository's.
.PARAMETER Action
Action to be performed on the branches, accepted values are "View", "Create", or "Delete".
.PARAMETER Repository
Repository URL, parameter is validated to accept only URLs starting with "https://github.com/".
.PARAMETER Token
Specifies the personal access token for authentication with GitHub.
.PARAMETER NewBranchName
Name of the new branch or branches to be created.
.PARAMETER DeleteBranchName
Names of the branche or branches to be deleted.
.EXAMPLE
"https://github.com/your_user/your_repo" | Use-GitHubRepositoryBranchesManager -Action View -Token "ghp_xyz"
Use-GitHubRepositoryBranchesManager -Action Create -Repository "https://github.com/your_user/your_repo" -Token "ghp_xyz" -NewBranchName "your_new_branch_1", "your_new_branch_2"
Use-GitHubRepositoryBranchesManager -Action Delete -Repository "https://github.com/your_user/your_repo" -Token "ghp_xyz" -DeleteBranchName "your_new_branch_1", "your_new_branch_2"
.NOTES
v0.0.6
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0, HelpMessage = "Enter 'View', 'Create' or 'Delete'")]
[ValidateSet("View", "Create", "Delete")]
[string]$Action,
[Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true, HelpMessage = "Enter the GitHub repository URL")]
[ValidatePattern('https://github.com/.+/.+')]
[string]$Repository,
[Parameter(Mandatory = $false, HelpMessage = "Token for auth with GitHub to be able to do actions/operation")]
[ValidateNotNullOrEmpty()]
[string]$Token,
[Parameter(Mandatory = $false, HelpMessage = "Enter the name of the branch to create (only for 'Create' action)")]
[ValidateNotNullOrEmpty()]
[string[]]$NewBranchName,
[Parameter(Mandatory = $false, HelpMessage = "Array of branch names to delete (only for 'Delete' action)")]
[ValidateNotNullOrEmpty()]
[string[]]$DeleteBranchName
)
BEGIN {
Write-Verbose -Message "Checking for Chocolatey..."
if (-not(Get-Command choco.exe -ErrorAction SilentlyContinue)) {
try {
Write-Verbose -Message "Installing Chocolatey..."
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
}
catch {
Write-Error "Failed to install Chocolatey: $($_.Exception.Message)"
return
}
}
Write-Verbose -Message "Installing Git and GitHub CLI using Chocolatey"
if (-not(Get-Command git -ErrorAction SilentlyContinue)) {
try {
choco install git -y
Write-Host "Git CLI installation successful" -ForegroundColor Green
}
catch {
Write-Error "Failed to install Git CLI: $($_.Exception.Message)"
}
}
if (-not(Get-Command gh -ErrorAction SilentlyContinue)) {
try {
choco install gh -y
Write-Host "GitHub CLI installation successful" -ForegroundColor Green
}
catch {
Write-Error "Failed to install GitHub CLI: $($_.Exception.Message)"
}
}
Write-Verbose -Message "checking if token is valid..."
Set-Content -Value $Token -Path "$env:USERPROFILE\Desktop\ght.txt" -Force -Verbose
Start-Process -FilePath "cmd" -ArgumentList "/c gh auth login --with-token < $env:USERPROFILE\Desktop\ght.txt" -WindowStyle Hidden -Wait
Write-Verbose -Message "logged in to GitHub, continuing with selected operation $($Action)..."
}
PROCESS {
Write-Verbose -Message "splitting the repository URL to get owner and repository name"
$Owner, $RepoName = ($Repository -split '/')[-2, -1]
Write-Verbose -Message "setting up API endpoints..."
$BaseApiEndpoint = "https://api.github.com"
$BranchesEndpoint = "$BaseApiEndpoint/repos/$Owner/$RepoName/branches"
$RefsEndpoint = "$BaseApiEndpoint/repos/$Owner/$RepoName/git/refs"
Write-Verbose -Message "set up authentication header..."
$Headers = @{
Authorization = "Bearer $Token"
'Content-Type' = 'application/json'
}
Write-Verbose -Message "perform requested action..."
switch ($Action) {
"View" {
Write-Verbose -Message "get list of branches"
$Response = Invoke-RestMethod -Uri $BranchesEndpoint -Method Get -Headers $Headers
Write-Host "Branches in the '$RepoName' repository:" -ForegroundColor Yellow
foreach ($Branch in $Response) {
Write-Host "- $($Branch.name)" -ForegroundColor Green
}
}
"Create" {
if (-not $NewBranchName) {
$NewBranchName = Read-Host "Enter a name for the new branch"
}
Write-Verbose -Message "get the default branch using the GitHub API"
$DefaultBranchUri = "https://api.github.com/repos/$Owner/$RepoName"
$DefaultBranch = Invoke-RestMethod -Uri $DefaultBranchUri -Method Get -Headers $Headers
$DefaultBranchName = $DefaultBranch.default_branch
$DefaultBranchRef = "heads/$defaultBranchName"
$ResponseUri = "https://api.github.com/repos/$Owner/$RepoName/git/ref/$DefaultBranchRef"
$Response = Invoke-RestMethod -Uri $ResponseUri -Method Get -Headers $Headers
$DefaultBranchSha = $Response.object.sha
$NewBranchName | ForEach-Object {
$BranchName = $_
Write-Verbose -Message "create new branch '$BranchName' using GitHub API..."
$HeadRef = "refs/heads/$BranchName"
$Payload = @{
ref = $HeadRef
sha = $DefaultBranchSha
} | ConvertTo-Json
Invoke-RestMethod -Uri $RefsEndpoint -Method Post -Headers $Headers -Body $Payload | Out-Null
Write-Host "New branch '$BranchName' created successfully" -ForegroundColor Green
}
}
"Delete" {
if (-not $DeleteBranchName) {
$DeleteBranchName = @((Read-Host "Enter the name of the branch to delete").Trim())
}
$BranchesEndpoint = "$BaseApiEndpoint/repos/$Owner/$RepoName/branches"
$Response = Invoke-RestMethod -Uri $BranchesEndpoint -Method Get -Headers $Headers
$BranchesToDelete = @()
foreach ($BranchName in $DeleteBranchName) {
if ($BranchName -notin $Response.name) {
Write-Error "Branch '$BranchName' not found in '$RepoName' repository"
}
else {
$BranchesToDelete += $BranchName
}
}
if ($BranchesToDelete.Count -eq 0) {
return
}
foreach ($BranchName in $BranchesToDelete) {
$ApiEndpoint = "$BaseApiEndpoint/repos/$Owner/$RepoName/git/refs/heads/$BranchName"
$Response = Invoke-RestMethod -Uri $ApiEndpoint -Method Delete -Headers $Headers
Write-Host "Branch '$BranchName' deleted successfully" -ForegroundColor Green
}
}
default {
Write-Error "Invalid action: '$Action'. Supported actions are: 'View', 'Create' or 'Delete'."
}
}
}
END {
Write-Verbose -Message "Cleaning up, closing connection and exiting..."
gh auth logout --hostname "github.com" ; Clear-History -Verbose -ErrorAction SilentlyContinue
Remove-Item -Path "$env:USERPROFILE\Desktop\ght.txt" -Force -Verbose -ErrorAction SilentlyContinue
Clear-Variable -Name Repository, Token, NewBranchName, DeleteBranchName -Scope Global -Force -Verbose -ErrorAction SilentlyContinue
Remove-Variable -Name Repository, Token, NewBranchName, DeleteBranchName -Scope Global -Force -Verbose -ErrorAction SilentlyContinue
}
}