Customize "Stage this hunk" prompt in `git add -p`?

58 views Asked by At

I've started reusing git add -p as a building block for other situations where it's nice to have an interactive interface to accept/reject/edit changes.

It's profoundly useful! The biggest win for me is that I've implemented partial save/load in my text editor on top of this. But it also helps with other miscellaneous tasks.

The exact implementation doesn't matter, but here's one minimal way to do it (create a temporary directory, initialize it as a Git repo, copy one version of the file into it, stage it, copy the other version of the file over it, git add --patch to go through the differences, throw away anything that didn't stage, and that's our result):

#!/bin/sh -
cleanup()
{
    case ${directory+x} in x)
        rm -rf "$directory"
    esac
}
output=${3-"$1"}
directory=`mktemp -d` &&
trap cleanup EXIT TERM INT HUP &&
(cd "$directory" && git init --quiet) &&
cp "$1" "$directory"/contents &&
(cd "$directory" && git add contents) &&
cp "$2" "$directory"/contents &&
(cd "$directory" && git add --patch contents) &&
(cd "$directory" && git checkout --quiet contents) &&
cp "$directory"/contents "$output"

Anyway, there's just one UI/UX touch this needs: to change the "Stage this hunk [...]?" prompt to whatever is more appropriate for the use-case. For example, for partial save in my editor, I'd like it to say "Save this hunk [...]?"

Right now, I only know how to pick between one of the other built-in prompts by slightly re-arranging the script (for example, git reset -p will ask "Unstage this hunk [...]?"; git checkout -p will ask "Discard this hunk from worktree [...]?", and git stash -p will ask "Stash this hunk [...]?").

I'm hoping we can do something better than piping through a particularly cautious sed, but that's a low I'm willing to stoop to if we can get it really robust and preserve fancy color output (and not break diff-enhancing helpers like git-delta).

0

There are 0 answers