Search code examples
gitcherry-pick

Cherry picking bug fixes correctly


So from my understanding cherry-picking a commit from one branch to another creates a completely new hash signature although the actual code changes are the same. I believe this is because the commit hash signature depends upon the branch name and commit time among other things.

Because of this I have been led to believe that if a bug fix has been made in a feature branch and another developer needs this fix, the correct solution is to cherry pick this fix into its own branch, and merge that branch into the common branch both the feature branches branched from. Then the original bufix commit in the feature branch should be deleted and finally both feature branches simply re-base on-top of the common branch which now contains the bugfix.

However, it seems this is not how others interpret using cherry-pick. I thought that if a commit is cherry-picked from one feature branch into another and both are merged back into common, then these separate commits cause one of three things to happen;

  • 'duplicate' commits in the history which introduce the same code changes
  • a merge conflict that has to be handled manually
  • introduction of duplicated lines of code.

Have I interpreted cherry pick incorrectly?


Solution

  • No, if you cherry-pick a commit from one branch into another, it will get a different hash, yes. Not because of the branch name, a branch is just a post-it that is stuck to a commit. But the whole history of a commit is part of the hash calculation so two commits that introduce the same changes but on top of a different history are essentially two different commits that introduce the same changes.

    If you rebase one branch onto another and both have commits that introduce the same changes (cherry-picked from one to the other) the rebased branch will not contain both commits, but the commit that is rebased onto the history where the change is already introduced will be left out like it was never done.

    If you merge the branches, there will be no conflict due to the cherry-picking because both branches did the same changes and Git sees and correctly handles this. If you do other changes on the same files, those changes might produce conflicts that need to be resolved.