Git - Working with forks

Pulling from or into a fork

How to pull from a common origin into a forked repo?

  1. In terminal, in your computer, go to the repo.

  2. Add a new remote (say, upstream) in your own repo.

    git remote add upstream <upstream-repo-url>  # add a new remote with upstream's repo URL
    
  3. Remove a remote (say, upstream) in your own repo.

    Git man page: https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-remote.html

    git remote remove <name>
    e.g.
    git remote remove upstream
    git remote remove origin
    
    git branch --unset-upstream  # This command will also remove the tracking stream branch, hence if you want to rebase from repository you have use
    git rebase origin main
    
  4. Look at the possible remote references

    git remote -v
    
  5. Fetch latest code from upstream

    git fetch upstream         # sync/update local with upstream's repo
    
  6. Pull if you want to.

    git pull upstream main
    
    or
    
    git pull upstream develop
    
  7. Create a new branch in your computer

    git checkout -b add-upstream-changes       # create a new branch named 'add-upstream-changes'
    
  8. Pull upstream/<branch> changes into your local branch (say, add-upstream-changes). Or, you could just merge the changes from upstream into a branch in your current repo.

    git pull upstream <specific-branch-name>   # pull upstream/<branch> changes
    
  9. Push to your own forked repo

    git push origin HEAD    # push changes to your own (origin) forked repo. Set the name of the feature branch before running this command.
    
  10. Push to local changes to upstream. Set the name of the feature branch before running this command. This will create a feature branch with the same name as the feature branch in local computer. git push -u will set the HEAD of the remote repository.

    git push -u upstream
    
  11. After that, we can create a pull request from the feature branch to the main branch in the original repository.


Links to this note