How to create a single commit with the differences between the local and remote Git repositories?

StackOverflow https://stackoverflow.com/questions/21329224

  •  02-10-2022
  •  | 
  •  

Question

In Git, let's say I've been working on a local branch:

  Common ancestor      
        /\
       A  \
      /    X
     B      \
    /        Y
   C       remote
 local

I made local commits A, B and C and in the mean time the remote branch moved on with commits X and Y. So I do a pull and get:

  Common ancestor      
        /\
       A  \
      /    X
     B      \
    /        Y
   C        /remote
    \      /
     \    /
      \  /
       \/
       M
     local

If I now push, the remote history will include all my A, B, C and M commits... but this isn't what I want.

I want to just push a single commit with the differences from my local branch so the remote branch will just look like this with none of the merging complexity:

  Common ancestor      
         \
          \
           X
            \
             Y
              \
               N
             remote

How can I achieve this?

Was it helpful?

Solution

Do a

git pull --rebase

Which is equivalent to git fetch and a git rebase instead of a git merge.

OTHER TIPS

Just merge the local changes into the remove ones to get the N commit:

  1. Create, checout a branch remote_n locally, and pull all data from remote's master into the remote_n branch:

    git branch remote_n
    git checkout remote_n
    git pull origin master
    
  2. Do a merge of master's HEAD into remote_n, fix inconsisences, and commit changes, so you will get the single N commit (by using --squash option):

    git merge --squash master
    vim ...
    git add .
    git commit
    
  3. Push the result N commit into remote's master branch:

    git push remote master
    

NOTE: You will get the local remote_n branch as a new master branch for your repo.

If you really need to avoid the merge do manually something like:

  1. Get diff of Common, and C commits:

    git diff Common_sha C_sha > common_c.diff
    
  2. Reset tree down to Common commit, pull remote changes, apply the diff, and commit it:

    git reset --hard Common_sha
    git pull remote master
    git apply --ignore-space-change common_c.diff
    git commit
    
  3. Push the result N commit into remote's master branch:

    git push remote master
    

NOTE: this model don't take into account binary files that can't be displayed by git diff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top