AI Hints
Home›Git & GitHub Tutorial›Project: Teamwork
Git & GitHub · Lesson 123 of 144

Project: Keeping a Branch Fresh

Rebase before the pull request.

⏱ 2 min read▶ Video at 2:14:05🎓 Free
Watch this lesson in the Git & GitHub courseWatch on YouTube ↗Full Git & GitHub course

Alex starts a bigger feature, a photo gallery, that takes a few days. Meanwhile, Sam keeps merging other work into main. Before opening a pull request, Alex brings the branch up to date, so it's easy to review and merge.

Project: Keeping a Branch Fresh
From the video: Project: Keeping a Branch Fresh
  • A feature that takes days
  • main keeps moving
  • Update the branch before the PR

Catching up with main

Alex's gallery branch has one commit. First, git fetch, to see what's new on GitHub. Then git rebase origin slash main. Alex's commit is replayed on top of Sam's latest work. The graph is a clean, straight line, ready for a pull request.

Alex
git log --oneline -n 1
fb648ef (HEAD -> gallery) Add gallery page
git fetch
From https://github.com/sam/my-site
   f63a17a..6a7b3d7  main       -> origin/main
git rebase origin/main
Successfully rebased and updated refs/heads/gallery.
git log --oneline --graph -n 3
* ca6338f (HEAD -> gallery) Add gallery page
* 6a7b3d7 (origin/main, origin/HEAD) Style the footer
* f63a17a (main) Link to about page

Pushing a rebased branch

If the branch was already pushed before, the rebase gave its commits new hashes, so a normal push would be rejected. Because this branch is Alex's alone, it's safe to use force with lease. It only overwrites the branch if nobody else has pushed to it in the meantime. Never use it on main.

Alex
git push --force-with-lease
To https://github.com/sam/my-site.git
 + fb648ef...103e5b3 gallery -> gallery (forced update)

Summary

Fetch, rebase onto origin slash main, and push your own branch with force with lease. Your pull request stays fresh and easy to merge. Next, a rescue mission.

Key takeaways
  • git fetch
  • git rebase origin/main
  • --force-with-lease, own branch only
Next up: Project: Rescue Mission — fixing a messy repository