更新的答案
前段时间,新出了一个--fixup
参数被添加到git commit
它可以用来构造一个带有适合的日志消息的提交git rebase --interactive --autosquash
。因此,修复过去提交的最简单方法是:
$ git add ... # Stage a fix
$ git commit --fixup=a0b1c2d3 # Perform the commit to fix broken a0b1c2d3
$ git rebase -i --autosquash a0b1c2d3~1 # Now merge fixup commit into broken commit
原答案
这是我不久前写的一个Python小脚本,它实现了这个git fixup
我在最初的问题中希望得到的逻辑。该脚本假设您暂存了一些更改,然后将这些更改应用到给定的提交。
NOTE:此脚本是 Windows 特定的;它寻找git.exe
并设置GIT_EDITOR
环境变量使用set
。根据其他操作系统的需要调整此项。
使用此脚本,我可以精确地实现我要求的“修复损坏的源代码、阶段修复、运行 git fixup”工作流程:
#!/usr/bin/env python
from subprocess import call
import sys
# Taken from http://stackoverflow.com/questions/377017/test-if-executable-exists-in python
def which(program):
import os
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
if len(sys.argv) != 2:
print "Usage: git fixup <commit>"
sys.exit(1)
git = which("git.exe")
if not git:
print "git-fixup: failed to locate git executable"
sys.exit(2)
broken_commit = sys.argv[1]
if call([git, "rev-parse", "--verify", "--quiet", broken_commit]) != 0:
print "git-fixup: %s is not a valid commit" % broken_commit
sys.exit(3)
if call([git, "diff", "--staged", "--quiet"]) == 0:
print "git-fixup: cannot fixup past commit; no fix staged."
sys.exit(4)
if call([git, "diff", "--quiet"]) != 0:
print "git-fixup: cannot fixup past commit; working directory must be clean."
sys.exit(5)
call([git, "commit", "--fixup=" + broken_commit])
call(["set", "GIT_EDITOR=true", "&&", git, "rebase", "-i", "--autosquash", broken_commit + "~1"], shell=True)