Skip to content

Instantly share code, notes, and snippets.

@indirect
Created June 27, 2020 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indirect/c57bf721bc8dc0b90a4d584c39d4d113 to your computer and use it in GitHub Desktop.
Save indirect/c57bf721bc8dc0b90a4d584c39d4d113 to your computer and use it in GitHub Desktop.
Update the default branch name for every repo in a user/org
#!/bin/bash
NAME="$1"
BRANCH="${2:-main}"
HUB=$(which hub || echo /usr/local/bin/hub)
# get repos that belong to the given user/org, are not archived, and are not forks
repos=($($HUB api --paginate --obey-ratelimit --flat graphql -f query='
query($endCursor: String) {
repositoryOwner(login: "'"$NAME"'") {
repositories(isLocked: false, isFork: false, first: 100, after: $endCursor) {
nodes { nameWithOwner }
pageInfo { hasNextPage, endCursor }
}
}
}
' | grep nameWithOwner | cut -f2 | grep "$NAME/"))
count=$(echo $(echo "${repos[*]}" | wc -w))
echo "found $count repos belonging to $NAME"
for repo in ${repos[@]}; do
echo "$repo"
# look for a branch with the right name
if $HUB api --flat "repos/$repo/git/refs/heads/$BRANCH" | grep ".object.sha" 1> /dev/null; then
echo " found branch $BRANCH"
else
# create the branch we need if it doesn't exist
SHA=$($HUB api --flat "repos/$repo/git/refs/heads/master" | grep ".object.sha" | cut -f2)
$HUB api "repos/$repo/git/refs" -F "ref=refs/heads/$BRANCH" -F "sha=$SHA" 1> /dev/null
echo " created branch $BRANCH"
fi
# now that the branch exists, update the repo default branch
$HUB api "repos/$repo" -X PATCH -F default_branch="$BRANCH" --flat 1> /dev/null
echo " set default branch to $BRANCH"
# check how close we are to the rate limit
ratelimit=$($HUB api rate_limit --flat | grep .core)
if [[ $(echo "$ratelimit" | grep .remaining | cut -f2) < 4 ]]; then
# if we have less than 4 API calls left, sleep until the limit resets
sleep $(expr $(echo "$ratelimit" | grep .reset | cut -f2) - $(date +%s))
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment