在 `git rebase` 中通过提交消息删除提交

Drop commits by commit message in `git rebase`

我想做一个 git rebase 并删除其提交消息与特定正则表达式匹配的提交。例如,它可能像

git rebase --drop="deletme|temporary" master

这将对 master 进行变基,同时删除所有包含字符串 deletemetemporary.

的提交

是否可以使用标准 Git 工具执行此操作?如果没有,是否可以使用第三方 Git 工具?特别是,我希望它是一个单一的非交互式命令。

你可以。 G。使用交互式变基。 git rebase -i <first commit that should not be touched> 也是如此,然后在有提交列表的 vim 中,您可以执行 :%s/^[^ ]* \([^ ]* issue\)/d /g 以对提交消息以 issue 开头的所有提交使用 drop 节。但请注意 git rebase 不能以最佳方式处理合并提交。默认情况下它们被跳过并且历史被展平,但您可以尝试使用参数保留它们。

这可以使用我在 this answer 中使用的相同方法来完成。

首先,我们需要找到相关的提交。你可以用类似的东西来做到这一点:

git log --format=format:"%H %s" master..HEAD | grep -E "deleteme|temporary"

这将为您提供包含 deletemetemporary 的提交消息的提交列表,它们位于 master 和您当前的分支之间。这些是需要删除的提交。

将此 脚本保存在您可以访问的地方:

#!/bin/bash

for sha in $(git log --format=format:"%H %s" master..HEAD | grep -E "deleteme|temporary" | cut -d " " -f 1)
do
  sha=${sha:0:7}
  sed -i "s/pick $sha/drop $sha/" $@
done

然后 运行 变基为:

GIT_SEQUENCE_EDITOR=/path/to/script.sh git rebase -i

这将自动删除所有在其提交消息中包含 deletemetemporary 的提交。

正如我在另一个回答中提到的:

[This script won't allow] you to customize what command is run to calculate which commits to use, but if this is an issue, you could probably pass in an environment variable to allow such customization.

强制性警告:由于变基重写历史,这对于在此分支上工作的任何其他人来说可能是危险的/破坏性的。确保您清楚地与合作的任何人交流您所做的事情。