When I make changes to a file in Git, how can I commit only some of the changes?
For example, how could I commit only 15 lines out of 30 lines that have been changed
With TortoiseGit:
right click on the file and use
Context Menu → Restore after commit
. This will create a copy of the file as it is. Then you can edit the file, e.g. in TortoiseGitMerge and undo all the changes you don't want to commit. After saving those changes you can commit the file.
Should you use emacs, take a look at Magit, which provides a git interface for emacs. It supports staging hunks (parts of files) quite well.
Intellij IDEA (and I guess all other products of the series) has built in support for partial commits since v2018.1
I would strongly recommend using SourceTree from Atlassian. (It's free.) It makes this trivial. You can stage individual hunks of code or individual lines of code quickly and easily.
Adding on a previous answer, if you prefer using the command line, entering git add -e myfile
gives you the choice to choose line by line what you want to commit because this command will open an editor with the differences, like so:
As you may known lines that start with +
are addtions, lines that start with -
are deletions. So:
-
with space
.This is what git add -h
says about adding files this way (patching files):
added content Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them.
removed content: Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).
modified content: Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+" lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index.
Caution: do not change the content of the file, this is not a good place to do so. Just change the operators of deleted or added lines.
Much like jdsumsion's answer you can also stash your current work but then use a difftool like meld to pull selected changes from the stash. That way you can even edit the hunks manually very easy, which is a bit of a pain when in git add -p
:
$ git stash -u
$ git difftool -d -t meld stash
$ git commit -a -m "some message"
$ git stash pop
Using the stash method gives you the opportunity to test, if your code still works, before you commit it.