Git Merge - Ignore Specific Lines

Let's say you want to merge a commit from another branch, but want to ignore specific lines from the commit. Here is an example, I want the commit https://github.com/kuscsik/piwik-python-api/commit/e2d179bfdf2d826869cb7ff9d99a0a253f62bd3b to be merged, but don't want this line:

494 -            id_cookie_name = 'id.%s.' % self.id_site
505 +            id_cookie_name = 'id.%s.' % self.d_site

There are a few ways to go about this.

New Commit to Undo or Revert Selected Lines

Simply create a new commit to make the changes that you want.


Cherry Pick To Staging

What if you do not want to create an unnecessary commit just to fix a mistake or undo a line change? Creating new commits just to fix a typo or a line is bad practice - you will clutter up your history with many trivial changes. The most straightforward way is to cherry-pick the commit onto your branch's staging area. You can then edit out the unwanted changes and create a new commit.

$ git checkout -b your-branch
$ git cherry-pick -n e2d179

Then de-select the changes you don't want.

$ git reset -p

Or use a graphic Git editor such as SourceTree



Finally create the new commit.

$ git commit -m "Your commit message"


This approach has the downside of creating a new commit, and attributing the commit's author to yourself instead of the original programmer.


Interactive Rebase to Edit Commit


Another option is to


  1. merge or rebase the commit into your branch, 
  2. create a new commit to fix the changes above, then 
  3. interactive rebase to squash and re-arrange the commit
After creating a new commit, start an interactive rebase session

$ git rebase --interactive HEAD~2

pick e2d179b Add variable tracking support
pick cb4d5a5 Fix typo in last commit

We don't want to keep cb4d5a5, so let's squash it

pick e2d179b Add variable tracking support
s cb4d5a5 Fix typo in last commit

Comment out the unnecessary git commit message

# This is a combination of 2 commits.
# This is the 1st commit message:

Add variable tracking support
# This is the commit message #2:
# Fix typo in last commit
#self.id_site accidentally changed to self.d_site
And there you have it, the commit was re-created with the changes that you want. 


$ git rebase --continue
[detached HEAD 1c0ec3f] Add variable tracking support
 Author: Zoltan Kuscsik <xxxxxxx@gmail.com>
 Date: Mon Oct 10 15:58:35 2016 +0200
 1 file changed, 15 insertions(+)
Successfully rebased and updated refs/heads/pure-python.
Hanxue-MBP:piwik-python-api hanxue$ git log


The advantage of this method is the original commit information, including the author, is preserved. However, git will need to create a new commit object. This means your git history is now inconsistent with the original upstream!

Caution: make sure you only rebase (rewrite history) on branches that are not pushed, or on branches that are not shared with others. 




No comments:

Post a Comment