Skip to content

Instantly share code, notes, and snippets.

@nyanhp
Last active July 2, 2020 08:57
Show Gist options
  • Save nyanhp/c3600d278c20e04ebc8d2ce92abbba8d to your computer and use it in GitHub Desktop.
Save nyanhp/c3600d278c20e04ebc8d2ce92abbba8d to your computer and use it in GitHub Desktop.
Update local clone and default branch on GitHub
function Update-GitDefaultBranch
{
[CmdletBinding()]
param
(
# Base path where you store all your repos...
[Parameter(Mandatory)]
[string]
$Path,
# your GitHub Username and a Personal Access Token
[Parameter(Mandatory)]
[pscredential]
$Credential,
# a filtering script block to filter on specific repos, e.g. $_.name -like '*thing*'
[Parameter()]
[scriptblock]
$RepoFilter = { -not $_.fork },
[Parameter()]
[string]
$OldBranchName = 'master',
[Parameter(Mandatory)]
[string]
$NewBranchName,
# Indicate that the default branch should only be changed if the local clone has been updated first
[switch]
$RequireLocalUpdate
)
if ($RequireLocalUpdate.IsPresent -and -not (Get-Command git))
{
Write-Warning -Message 'No git binary found while RequireLocalUpdate is used.'
return
}
$tokenString = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $credential.UserName, $credential.GetNetworkCredential().Password)))
# The header is simply a hashtable with whatever headers you need
$header = @{
Authorization = 'Basic {0}' -f $tokenString
}
$repos = Invoke-RestMethod -Method Get -Uri "https://api.github.com/users/$($credential.UserName)/repos?type=owner&per_page=1000" -ErrorVariable octoError -Headers $header
if ($octoError)
{
return
}
foreach ($repo in $repos.Where($RepoFilter))
{
if (Test-Path -Path (Join-Path -Path $Path -ChildPath $repo.name))
{
Push-Location
Set-Location -Path (Join-Path -Path $Path -ChildPath $repo.name)
$localUpdateOk = $true
$stuff = git branch -m $OldBranchName $NewBranchName 2>&1
if ($LASTEXITCODE -ne 0)
{
Write-Error -Message ('Unable to update {0} to {1}. Git output {2}' -f $OldBranchName, $NewBranchName, $stuff )
$localUpdateOk = $false
}
$stuff = git push -u origin $NewBranchName 2>&1
if ($LASTEXITCODE -ne 0)
{
Write-Error -Message ('Unable to push change to origin. Git output {0}' -f $stuff )
$localUpdateOk = $false
}
Pop-Location
}
if ($repo.default_branch -eq $OldBranchName -and (-not $RequireLocalUpdate.IsPresent -or $RequireLocalUpdate.IsPresent -and $localUpdateOk))
{
$patchParam = @{
default_branch = $NewBranchName
} | ConvertTo-Json
Invoke-RestMethod -Method Patch -Uri $repo.url -Body $patchParam -ContentType application/json -Headers $header
}
}
}
Update-GitDefaultBranch -Path $Home/source/repos -Credential (Get-Credential) -OldBranchName master -NewBranchName mimir -RequireLocalUpdate -RepoFilter {$_.name -ne 'ExeWrapper' -and -not $_.fork}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment