git CLI commands for stage/unstage hunks/lines like sourcetree

1.6k views Asked by At

Sourcetree makes it easy to stage and unstage hunks. And also easy to select particular lines from within a hunk and stage or unstage them. I am trying to figure out how to do the same from the command line.

I tried doing each operation in sourcetree with the command history panel showing. It doesn't show any commands when I perform these operations. For other operations it works fine.

On the command line, I use git add in interactive mode, choose the patch option and then select a file with a multiline change in it. The prompt is: "Stage this hunk [y,n,q,a,d,/,e,?]?". If I choose the '?' option it outputs this help text:

y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk or any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk or any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

The 's' option looks like the right one for staging individual lines out of the hunk. However, when I enter it, git just outputs the help text again.

Can anyone tell me where in the docs I should be looking?

1

There are 1 answers

0
flaky On BEST ANSWER

late to the party, but it might help others looking for a solution.

git tends to add lines in close proximity to the same hunk - if you want to stage code line by line, you can edit the hunks in interactive mode.

Once the file is modified, type:

git add -p

And now, instead of s you can type e.

Which brings you into an edit mode to change the hunk.

If you find a particular line you want to keep for staging in this particular hunk, make sure to leave its + and - in there and edit the others as described in the quick guide.

Example time

Let's say I have following changes:

-  allScriptsTimeout: 60000,
-  getPageTimeout: 60000
+  allScriptsTimeout: 180000,
+  getPageTimeout: 180000

However I only want to stage the first changed line. As explained above type git add -p and select e

Within the editor, change the - to a space and remove the lines you do not want staged.

Let's say I want only + allScriptsTimeout: 180000, to be staged, I change the file to this:

-  allScriptsTimeout: 60000,
   getPageTimeout: 60000
+  allScriptsTimeout: 180000,

And there we go, just one line staged, ready to be committed.

Albeit cumbersome, it is definitely possible to add individual lines within git CLI :)