Comment by reificator
7 years ago
> committing single lines from hunks that can't be split.
Could you elaborate here? Personally I've always been able to commit just the pieces I need via `git add -p`. Never had problems staging a single line before.
Since this is text I should say: I'm not doubting you, I just like to know the limitations of the tools I'm using.
`git add -p` adds by the hunk, which is a unit of quantization bigger than a line.
E.g. if you have two consecutive lines changed, it's not possible to split them, they are one "hunk".
(Waiting for someone to chime in with how to split a hunk and change my life).
You use the 'e' option which allows you to edit the hunk. Remove the minus sign or the entire line with a '+'
Within 'git add -p' when you get to the hunk that you want to edit (split down to single lines), press 'e'. This will open an editor (vim in my case) which lets you edit the diff manually.
In there you can remove added lines (prefixed by '+') by removing them, and re-adding removed lines (prefixed by '-') by replacing the '-' with a space ' '.
And how is this faster/better than selecting a line with the mouse and pressing s without opening any other editor?
2 replies →
You can use 's' to split a hunk but it would indeed not work if you want to split two consecutive lines.
You can also use 'e' option to edit the hunk to e.g. remove one of the added line.
Nothing as easy as clicking a line in a GUI though.
Say you have 3 sequential lines, but you only want to stage the middle one. You can’t split it into smaller hunks by hitting ‘s’ during ‘git add -p’. I’m sure there’s a way I’m just not familiar with but I just use Sourcetree for this on the rare occasion it occurs.
You can split hunks manually by editing (hit “e” instead of “s” during staging). I end up doing this fairly regularly.
i think that’s his point? there’s a huge amount of useful, but advanced functionality in the git CLI
As mentioned before, manual edits can be made at that point. However I'll add that for this use case, a tool integrated in your editor will often be more adapted to manual staging. I have Tim Pope's vim-fugitive plugin in mind which is a quite wonderful way of using Git.
You can also manually edit the hunk to remove the 2 lines you don't want to stage and use the recountdiff utility to update the hunk header.