我不确定是否可以在单个命令中完成,但几乎可以:
git reset -N HEAD~
git add --edit
git commit --reuse-message=ORIG_HEAD
一些解释:
git reset -N HEAD~
:撤销上一次提交但保留更改内容
git add --edit
允许您以补丁格式编辑更改内容
git commit --reuse-message=ORIG_HEAD
:使用 ORIG_HEAD 的提交消息提交缓存区的更改,ORIG_HEAD 是指 git reset
前所在的提交。
注意:由于只有 git add --edit
需要交互,如果需要,您甚至可以将这些命令链接在一行中并为其创建 Bash 或 Git 别名:
git reset -N HEAD~ && git add --edit && git commit --reuse-message=ORIG_HEAD
注意2:如果您编辑了提交内容,则此命令后,一些更改将保留在您的git存储库中。 您必须选择放弃所有更改(git checkout -- :/
)或提交它们或...
如果您不对这些更改做任何操作,则调用上述命令两次将始终向您显示从第一个提交开始的更改:
git commit -am "very first commit"
git reset -N HEAD~
git add --edit # edit very first commit as patch
git commit --reuse-message=ORIG_HEAD
# you now have some unstaged changes lying around.
git reset HEAD~ # undo second commit
# the unstaged changes that are lying around now
# are a combination of second commit and the unstaged changes
# that were still lying around.
# That combination = content of very first commit
git add --edit # edit that combination
git commit --reuse-message=ORIG_HEAD
如果您想要一个完整的命令,以便您可以继续应用;您可以包括放弃更改:
git reset -N HEAD~ && git add --edit && git commit --reuse-message=ORIG_HEAD && git checkout -- :/
请注意,这种方法是危险的,因为可能会丢失更改...
完整的脚本
您可以将此脚本保存为/usr/bin/git-edit-last-commit
,然后通过git edit-last-commit
运行它:
#!/bin/bash
set -e
if ! git diff-files --quiet
then
echo "Your git repository is not clean: you have unstaged changes."
exit 1
fi
if ! git diff-index --quiet --cached HEAD --
then
echo "Your git repository is not clean: you have staged changes."
exit 1
fi
git reset -N HEAD~
git add --edit
git commit --reuse-message=ORIG_HEAD
git checkout -- :/
git add --edit
只对新更改有效。 - wodow