Git command to programatically add a range of lines of a file to the index?
git
Solution
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.
Problem
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?