How do I merge the latest master changes, including a hotfix, into my feature branch without duplicating commits?

I’m working on a feature branch and a hotfix was recently merged into master. I want to bring that fix into my branch, but I’d prefer not to clutter the history with unrelated commits. What’s the cleanest way to git merge master into a branch, ensuring the hotfix is applied without introducing duplicate or unnecessary commits?

I’ve been dealing with this kind of scenario for a while, and what works best for me is rebasing my feature branch onto the updated master. So, first, I’d run git checkout feature-branch, then git rebase master. This will replay your commits on top of the latest master, including the hotfix, ensuring your feature branch is up to date without any unnecessary duplicates in the history. However, if your branch has already been pushed and shared with others, be cautious, rebasing can create conflicts if other team members have based work off your branch.

That’s a solid approach! I usually go for a different method. If you’re not too worried about the history getting a bit bulkier, you can just git merge master into branch. Git is pretty smart, so it won’t duplicate the hotfix commits if they’re already in master. However, the merge will still bring those commits into your feature branch’s log. So, if you’re aiming to keep your pull request clean and focused, git merge master into branch is fine but may add a few extra commits. If you want to keep it neater, rebasing is a cleaner option.

Absolutely, @emma-crepeau ! But if you’re looking to keep your branch really clean and avoid cluttering it with anything unnecessary, there’s a more surgical option: cherry-picking. Let’s say the hotfix is really small and you don’t want all of master’s recent changes. You can find the hotfix commit hash (run git log master), then run git cherry-pick <hash> in your feature branch. This way, you just bring in that one fix without any unrelated commits. It’s a bit more manual, but sometimes it’s the best choice when you want to minimize disruptions to your branch’s history while still applying the hotfix.