Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git command to programatically add a range of lines of a file to the index?

Tags:

git

I want a command that would let me do something like:

git manual-add some_file.txt 10..20

Which would be the equivalent of:

git add -p some_file.txt

and saying y to only the hunk containing lines 10 through 20.

Is there an internal git command that would let me do this? Is there any way it could be done?

like image 627
Jonah Avatar asked Oct 21 '16 06:10

Jonah


2 Answers

You can take advantage of the git add -e command and pass to it as an editor a script (in the example below, it is named filterpatch) that will edit the patch up to your requirements (see the "EDITING PATCHES" section in the documentation of git add):

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

For convenience you can add a git alias as follows:

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

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

#!/bin/bash -x

sed -i "$1 s/^+\([^+]\)/+foo \1/" "$2"

Usage example:

git manual-add some_file.txt 13,16

So the remaining part is about implementing the filterpatch script properly - it must parse the diff and unselect hunks that don't belong to the target range.

like image 120
Leon Avatar answered Oct 20 '22 03:10

Leon


Add alias to your config:

[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 could:

git addp a.txt 3,4

This sequence will:

  1. Do a temporary commit with file $1 only.
  2. Write patch ptc.patch for lines $2 in file $1 using solution from this question - Git: discover which commits ever touched a range of lines.
  3. Mixed reset temporary commit.
  4. Apply patch to index only, since working directory already contains changes.
like image 21
Mykhailo Kovalskyi Avatar answered Oct 20 '22 01:10

Mykhailo Kovalskyi