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
For those who use Git Extensions:
In the Commit window, select the file you want to partially commit, then select the text you want to commit in the right pane, then right-click on the selection and choose 'Stage selected lines' from the context menu.
Tried out git add -p filename.x
, but on a mac, I found gitx (http://gitx.frim.nl/ or https://github.com/pieter/gitx) to be much easier to commit exactly the lines I wanted to.
git gui provides this functionality under the diff view. Just right click the line(s) you're interested in and you should see a "stage this line to commit" menu item.
git-meld-index -- quoting from the website:
git-meld-index runs meld -- or any other git difftool (kdiff3, diffuse, etc.) -- to allow you to interactively stage changes to the git index (also known as the git staging area).
This is similar to the functionality of git add -p, and git add --interactive. In some cases meld is easier / quicker to use than git add -p. That's because meld allows you, for example, to:
Usage
In a git repository, run:
git meld-index
You'll see meld (or your configured git difftool) pop up with:
LEFT: temporary directory contining files copied from your working tree
RIGHT: temporary directory with the contents of the index. This also includes files that are not yet in the index but are modified or untracked in the working copy -- in this case you'll see the file contents from HEAD.
Edit the index (right hand side) until happy. Remember to save when needed.
When you're done, close meld, and git-meld-index will update the index to match the contents of the temporary directory on the right hand side of meld that you just edited.
When I have a lot of changes, and will end up creating a few commits from the changes, then I want to save my starting point temporarily before staging things.
Like this:
$ git stash -u
Saved working directory and index state WIP on master: 47a1413 ...
$ git checkout -p stash
... step through patch hunks
$ git commit -m "message for 1st commit"
$ git checkout -p stash
... step through patch hunks
$ git commit -m "message for 2nd commit"
$ git stash pop
Whymarrh's answer is what I usually do, except sometimes there are lots of changes and I can tell I might make a mistake while staging things, and I want a committed state I can fall back on for a second pass.
git-cola is a great GUI and also has this feature built-in. Just select the lines to stage and press S. If no selection is made, the complete hunk is staged.