Skip to content

Instantly share code, notes, and snippets.

@smudge
Last active March 30, 2022 14:18
Show Gist options
  • Save smudge/a269320bbc13446a8fb4188eb234fc55 to your computer and use it in GitHub Desktop.
Save smudge/a269320bbc13446a8fb4188eb234fc55 to your computer and use it in GitHub Desktop.
Switch a git repo to track a fork origin, with read-only upstream.
#### Switch a git repo to track a fork origin, with read-only upstream.
# Step 1: Press that "fork" button on github to fork a repo to your account.
# (Don't worry -- if it's a private repo, your fork will still be private
# and should be effectively owned by the original repo's organization.)
# Step 2: Update your local repo
# IMPORTANT: This assumes your local repo is a clone of the ORIGINAL/upstream repo.
## Add a new 'upstream' remote and add a bogus URL for push commands.
git remote add upstream $(git remote get-url origin)
git remote set-url upstream --push "You don't want to do that."
## Change your existing 'origin' branch to point to your fork.
## IMPORTANT: Get this right! Use `git remote -v` to confirm!
git remote set-url origin https://github.com/you/your-fork.git # << your fork's clone URL
## Optional: ignore upstream tags when fetching
git config remote.upstream.tagopt --no-tags
## Optional: ignore non-primary upstream branches when fetching (add multiple for multiple branches)
git config --unset-all remote.upstream.fetch
git config --add remote.upstream.fetch +refs/heads/main:refs/remotes/upstream/main
# Or if 'main' isn't your primary upstream, go with one that is:
git config --add remote.upstream.fetch +refs/heads/master:refs/remotes/upstream/master
git config --add remote.upstream.fetch +refs/heads/stage:refs/remotes/upstream/stage
## Optional: allow fetching PRs as local branches
git config --add remote.upstream.fetch +refs/pull/*/head:refs/remotes/upstream/pr/*
# Now you can do `git checkout -b pr/123 upstream/pr/123` and checkout pull requests.
# Now you can push to origin and pull/rebase from upstream:
git checkout main
git pull upstream main
git push origin main
# Or fetch from upstream and rebase your local branch:
git fetch upstream
git rebase upstream/main
# BONUS: Start from a clean slate!
# Remove all branches and tags on your fork. (BE CAREFUL!)
https://gist.github.com/smudge/5481a4225c2690a060f76c6a25826703
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment