You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义git add -p中的“Stage this hunk”提示语?

基于git add -p实现交互式内容选择方案

我现在把git add -p当作核心组件,用来适配各种需要交互式选择(接受、拒绝或编辑变更)的场景,实用性拉满!对我来说最有用的是用它在编辑器里实现了部分保存/加载功能,同时它还能搞定各种杂活。

具体实现逻辑不用太纠结,这里给一个极简方案:创建临时目录并初始化为Git仓库,把文件的一个版本复制进去并暂存,再用另一个版本覆盖,通过git add --patch遍历差异,最后丢弃未暂存内容得到结果。代码如下:

#!/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"

不过这个方案还有个UI/UX细节要优化:默认的提示语“Stage this hunk [...]?”需要改成贴合场景的内容。比如在编辑器部分保存功能里,我希望提示变成**“Save this hunk [...]?”**。

目前我只知道可以微调脚本,选用Git内置的其他提示语——比如git reset -p会问“Unstage this hunk [...]?”;git checkout -p是“Discard this hunk from worktree [...]?”;git stash -p则是“Stash this hunk [...]?”。

我想找比用严谨的sed管道替换更好的方法,但如果替换方法能保证鲁棒性、保留彩色输出,还不破坏git-delta这类差异增强工具,我也愿意用。

内容的提问来源于stack exchange,提问作者mtraceur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:35:07