6.4 Working with Forks and Pull Requests
When collaborating on repositories you don’t own, forking and pull requests (PRs) let you contribute safely and efficiently.
Creating a Fork
-
On GitHub, go to the original repository.
-
Click Fork in the top-right corner.
-
GitHub creates a copy under your account.
-
Clone your fork locally:
git clone git@github.com:USERNAME/FORKED-PROJECT.git
cd FORKED-PROJECT
Keeping Your Fork Up to Date
-
Add the original repository as an upstream remote:
git remote add upstream https://github.com/ORIGINAL-USER/ORIGINAL-PROJECT.git -
Verify remotes:
git remote -v -
Fetch and merge updates:
git fetch upstream
git checkout main
git merge upstream/main
Developing a Feature or Fix
-
Start from your updated main branch:
git checkout main -
Create and switch to a new branch:
git checkout -b new-feature -
Make your changes, then commit and push:
git add .
git commit -m "Add new feature"
git push origin new-feature
Submitting a Pull Request
- Go to your fork on GitHub.
- Switch to your new branch (e.g.,
new-feature). - Click Compare & pull request.
- Add a clear title and description.
- Submit for review.
Keeping Your Branch Clean (Optional)
-
Fetch the latest upstream changes:
git fetch upstream
git checkout main
git merge upstream/main -
Rebase your branch:
git checkout new-feature
git rebase main -
Push the updated branch:
git push --force origin new-feature
Reviewing and Merging Pull Requests (Repository Owner)
- Review PRs directly on the platform.
- If all checks pass, click Merge pull request.
- Optionally test locally before merging.
Checking Out a Pull Request Locally
# Fetch all pull requests
git fetch origin
# Checkout a specific PR by number
git checkout -b pr-42 pull/origin/42
Manual Merging (if needed)
git checkout main
git pull https://github.com/forkuser/forkedrepo.git new-feature
git merge new-feature
git push origin main
After merging, delete the feature branch:
git branch -d new-feature