Created
January 13, 2025 13:25
-
-
Save 1ARdotNO/0ca22c9d6398de3e37cd007e50f4071f to your computer and use it in GitHub Desktop.
Set the default branch for all repos for a particular team
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Set your GitHub API token and team details | |
$GitHubToken = $env:GH_PAT | |
$Organization = "orgname" # Replace with your GitHub Organization name | |
$TeamSlug = "team-slug" # Replace with your GitHub Team slug (e.g., "dev-team") | |
$DefaultBranch = "master" | |
# GitHub API URL | |
$GitHubApiBaseUrl = "https://api.github.com" | |
# Headers for the GitHub API request | |
$headers = @{ | |
"Authorization" = "Bearer $GitHubToken" | |
"Accept" = "application/vnd.github.v3+json" | |
} | |
# Function to get all repositories for a specific GitHub team | |
function Get-TeamRepositories { | |
param ( | |
[string]$Organization, | |
[string]$TeamSlug | |
) | |
# Set initial variables for pagination | |
$repos = @() | |
$page = 1 | |
$per_page = 100 | |
do { | |
# Fetch the repositories from the current page | |
$url = "$GitHubApiBaseUrl/orgs/$Organization/teams/$TeamSlug/repos?per_page=$per_page&page=$page" | |
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Get | |
# Append the current page of repos to the list | |
$repos += $response | |
# Check if the current page has less than $per_page repos, meaning it's the last page | |
if ($response.Count -lt $per_page) { | |
break | |
} | |
# Otherwise, move to the next page | |
$page++ | |
} while ($response.Count -eq $per_page) | |
return $repos | |
} | |
# Function to set default branch to 'master' for a repository | |
function Set-DefaultBranchToMaster { | |
param ( | |
[string]$Organization, | |
[string]$RepoName | |
) | |
$url = "$GitHubApiBaseUrl/repos/$Organization/$RepoName" | |
# Prepare the body to update the default branch | |
$body = @{ | |
"default_branch" = $DefaultBranch | |
} | ConvertTo-Json | |
# Make the request to set the default branch | |
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Patch -Body $body | |
return $response | |
} | |
# Main logic: Get repositories and set the default branch | |
$repos = Get-TeamRepositories -Organization $Organization -TeamSlug $TeamSlug | |
# Iterate over each repository and update the default branch | |
foreach ($repo in $repos) { | |
$repoName = $repo.name | |
Write-Host "Updating default branch for repository: $repoName" | |
$result = Set-DefaultBranchToMaster -Organization $Organization -RepoName $repoName | |
Write-Host "Updated default branch for $repoName to 'master'" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment