Git command to programmatically add a range of rows to an index?

I need a command that would allow me to do something like:

git manual-add some_file.txt 10..20 

Which would be equivalent:

 git add -p some_file.txt 

and saying y only for a line containing lines 10 through 20.

Is there an internal git command that would allow me to do this? Can this be done?

+6
source share
2 answers

You can use the git add -e command and pass it as a script editor (in the example below it is called filterpatch ), which will edit the patch to your requirements (see the "EDITING PATCHES" section in the git add documentation):

 EDITOR="filterpatch 10..20" git add -e some_file.txt 

For convenience, you can add the git alias as follows:

 git config alias.manual-add '!EDITOR="filterpatch $2" git add -e $1; :' 

An example of a silly filterpatch script that adds the foo prefix to all added lines in the specified patch range:

 #!/bin/bash -x sed -i "$1 s/^+\([^+]\)/+foo \1/" "$2" 

Usage example:

 git manual-add some_file.txt 13,16 

So, the rest is about the correct implementation of the filterpatch script - it should analyze the diff and cancel the selection that does not belong to the target range.

+3
source

Add an alias to your configuration:

 [alias] addp = "!sh -c 'git commit -m temp \"$1\" && git log -1 -u -L \"$2\":\"$1\" > ptc.patch && git reset HEAD^ && git apply --cached ptc.patch ' -" 

Now you can:

 git addp a.txt 3,4 

This sequence will be:

  • Make a temporary commit only with the $ 1 file.
  • We write the ptc.patch patch for lines $ 2 in the file $ 1, using the solution from this question - Git: we find out who ever made touches on a number of lines .
  • Mixed temporary commit reset.
  • Apply the patch only to the index, since the working directory already contains the changes.
+2
source

Source: https://habr.com/ru/post/1011535/


All Articles