Skip to content

Instantly share code, notes, and snippets.

@wch
Last active September 19, 2021 09:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wch/8bebdd3c04a551d1b001eb7c37fd63cf to your computer and use it in GitHub Desktop.
Save wch/8bebdd3c04a551d1b001eb7c37fd63cf to your computer and use it in GitHub Desktop.
How to fork a GitHub repo and work on your fork

This document shows how to fork a GitHub repo and work from your fork to create clean branches and pull requests. The key is to make sure you stay in sync with the upstream fork's master branch.

Setup

First, fork the repo by clicking the Fork button on GitHub. For example, you could fork the tidyverse/ggplot2 repo at https://github.com/tidyverse/ggplot2.

# Clone your copy of the repo on GitHub (replace `wch` below with your GitHub
# username)
git clone git@github.com:wch/ggplot2.git

# Enter the local repo directory
cd ggplot2

# Add the upstream remote repo
git remote add upstream git@github.com:tidyverse/ggplot2.git

#Fetch from the upstream remote
git fetch upstream

# Set your master branch to track upstream/master branch
git branch -u upstream/master

Keeping in sync

Once it's set up, you should do the following to keep up-to-date with the upstream repository.

git checkout master
# Fetch updated branches from upstream repo, then merge current branch (master)
git pull

That's it. Never work directly on your local master branch, because the pull is equivalent to a fetch plus merge, and the merge can mess things up if you've diverged from upstream/master.

Optional: If you did something weird on your master branch and want to just discard it and get in sync with upstream master, do this:

git checkout master
git reset --hard upstream/master

Optional: An alternative to git pull, which is slightly safer:

# Get your local master branch in sync with upstream/master
git fetch upstream
git checkout master
git merge upstream/master --ff

Optional: You can push the updated master branch to your personal GitHub repo:

git push origin master

Branching

If you want to make a pull request, you typically should branch off of upstream/master. Do the stuff in the above section to get your master branch in sync with upstream master. Then:

git checkout -b my-branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment