Skip to content

Instantly share code, notes, and snippets.

@mark-raymond
Created June 24, 2020 16:40
Show Gist options
  • Select an option

  • Save mark-raymond/83a840163b49fc906746e54af2c688d5 to your computer and use it in GitHub Desktop.

Select an option

Save mark-raymond/83a840163b49fc906746e54af2c688d5 to your computer and use it in GitHub Desktop.
Script to reset the default branch
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 GITHUB_TOKEN" >&2
exit 1
fi
TOKEN="$1"
ORIGIN="$(git remote get-url origin)"
if [ $? -ne 0 ]; then
echo "Could not get origin url in $(pwd)" >&2
exit 1
fi
if ! grep '^\(git@github.com:\|https://github.com/\)\([^/]\+/[^/]\+\)\.git$' <<< "$ORIGIN" >/dev/null 2>/dev/null; then
echo "origin url $ORIGIN is not a recognzied GitHub repository url" >&2
exit 1
fi
REPO="$(sed -e 's#^\(git@github.com:\|https://github.com/\)\([^/]\+/[^/]\+\)\.git$#\2#' <<< "$ORIGIN")"
DEFAULT_BRANCH="$(curl -s -L -H "Authorization: token $TOKEN" -H 'Accept: application/vnd.github.v3+json' "https://api.github.com/repos/$REPO" | grep 'default_branch' | sed -e 's/.*"default_branch"\s*:\s*"\([^"\]\+\)".*/\1/')"
git symbolic-ref refs/remotes/origin/HEAD "refs/remotes/origin/$DEFAULT_BRANCH"
@mark-raymond

mark-raymond commented Jun 24, 2020

Copy link
Copy Markdown
Author

You can run this in all repos in a folder using:

find . -maxdepth 2 -type d -name .git -execdir /path/to/reset-default-branch "your github token" \;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment