I'm looking to selectively merge parts of a file with git.
I've got two branches -- call them master and changed -- that are one commit apart; if I merge master into changed, it would just fast-forward.
However, I just want to incorporate a number of parts -- within one file -- from changed to master.
Is there a clean way to do this -- e.g. git asking before making each change? Or am I stuck doing it by hand? (Not the end of the world, but I'd prefer not to, and -- yes -- this could have been avoided with more planning on my part -- such is life.)
Roughly speaking, you use git rebase -i to get the original commit to edit, then git reset HEAD^ to selectively revert changes, then git commit to commit that bit as a new commit in the history.
Git merging combines sequences of commits into one unified history of commits. There are two main ways Git will merge: Fast Forward and Three way. Git can automatically merge commits unless there are changes that conflict in both commit sequences.
In Conclusion. We can use git checkout for far more than simply changing branches. If we supply it with a branch name and a file, we can replace a corrupted or broken file. Instead, if we want to pass some of the changed content we can use the --patch flag to manually merge an individual file.
Try this:
git merge --no-ff --no-commit changed # Merge in 'changed' but don't commit
git reset <path/to/your/file> # Reset the stage state but not
# the working version of the file
git add -p <path/to/your/file> # Start adding in interactive mode
(Git will prompt you for each hunk; you can split hunks up if necessary.)
git commit # Finally commit the merge with only
# the bits you chose to stage
Note, however, that doing this will make Git think that the file is fully merged, so if someone were to then merge in the same branch again, the other changes from that commit would still not be merged in. This may or may not be what you want.
If you need help with the meanings of the various options in git add
's interactive mode, see the output of git help add
in the "INTERACTIVE MODE" section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With