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?
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.
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:
ptc.patch
for lines $2 in file $1 using solution from this question - Git: discover which commits ever touched a range of lines.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With