gitgit-mergecherry-pick

How to make git cherry pick use fast forward technique


By using git cherry-pick, I've been trying to specifically merge the last commit from one branch to another. But it always results in a merge conflict, when it actually shouldn't. Following is what I've been doing, and it always results in conflicts.

  1. Initiate a new repository, and commit a fresh new file on master branch. The file would have the following content -
MASTER - 1st commit
  1. Checkout to a new branch called testing, and make the following changes to the file, and commit again.
MASTER - 1st commit : TESTING 1st commit

3.) Make further changes, on the same line of the file and commit again. So at the end, the file contents would look like the following.

MASTER - 1st commit : TESTING 1st commit : TESTING 2nd commit

Now, this would leave us with 1 commit on master branch, and 2 commits on testing. So if we were to checkout master and do a git merge testing, then since, there's a direct path between the last commit from master and the last commit to testing, therefore, git will use the fast forward technique, and without any merge conflicts, it will directly incorporate changes from testing to master. So my question is why this isn't the case when I try git cherry-pick testing (i.e merging the last commit from testing to master, which in turn has a direct path to it). If I'm being wrong here, then please suggest, what would be the correct way to do this.


Solution

  • The patch that gets applied is different in both cases.
    Additionally, git merge has this "fast forward" feature, where, if it determines that one way to produce the correct merge is to simply move branch A to where branch B stands, it just does this and this always results in a conflict free resolution.

    In the example you describe :


    In the example you describe :

    this would produce the same end result as running git merge testing : all the changes on testing would be added on top of master.

    A more systematic way to apply all commits on a branch using cherry-pick is :

    # you don't have to name the commits one by one :
    # let git compute that for you
    git cherry-pick master..testing
    

    <2nd commit> has a diff which says :

    # replace the line that says 'MASTER ... 1st commit'
    # with a line that says 'MASTER ... 2nd commit'
    -MASTER - 1st commit : TESTING 1st commit
    +MASTER - 1st commit : TESTING 1st commit : TESTING 2nd commit
    

    you try to apply it on a branch where that file's content is :

    # uh oh, no line saying 'MASTER - 1st commit : TESTING 1st commit'
    MASTER - 1st commit
    

    so you're bound to have a conflict.