注意:与 this one 类似的问题, 但有一些重要的变化。
我有以下函数来重写提交日期,给定提交 ID:
rewrite-commit-date () {
local commit="$1"
local newdate="$2"
newdate="$(date -R --date "$newdate")"
echo ">>>> Rewriting commit $commit date: $newdate"
git filter-branch --env-filter \
"if test \$GIT_COMMIT = '$commit'
then
export GIT_AUTHOR_DATE
export GIT_COMMITTER_DATE
GIT_AUTHOR_DATE='$newdate'
GIT_COMMITTER_DATE='$newdate'
fi" &&
rm -fr "$(git rev-parse --git-dir)/refs/original/"
}
我正在尝试实现一个类似的函数 rewrite-commit-message
来更改提交消息。我想要的是:
- 函数
rewrite-commit-message
接受两个参数:commit_id
和new_commit_message
- 不需要知道旧的提交信息:有
commit_id
就足以知道要更改哪个提交 - 没有
git commit --amend
,因为这与旧提交相关(不一定与最近的提交相关) - 不用担心重写历史和主仓库:我在一个特性分支工作,我被允许做
git push -f
- 我想使用
filter-branch
为此,但我不确定如何:- 将更改应用于特定提交:
rewrite-commit-date
函数中使用的test
用于env-filter
,但我不打算在这里执行env-filter
,因为我不想更改与提交环境相关的任何内容,而是更改提交消息。 - 如何强制提交信息?
--msg-filter
需要原始提交消息。我不关心原始提交消息。是否有--force-msg-filter
或类似的?
- 将更改应用于特定提交:
我要查找的内容类似于 this ,但有一些注意事项:
- 不要将更改应用于一系列提交,而是应用于特定的提交
- 我不关心原始提交消息,因为我想完全覆盖它
最佳答案
这个小脚本可以工作,但需要注意以下几点:
这将重写您从提交到分支顶端的历史记录。因为你在问题中说这不是问题,所以这符合条件。
您的提交包含在
master
中分支。您可以通过将分支名称作为另一个参数传递来轻松更改它,但是提交 更好 在分支中。您可能应该为此构建一些验证,也许使用git rev-parse --abbrev-ref HEAD
或者也许git branch --all --contains <commit>
事不宜迟:
#!/bin/bash
change-commit-msg(){
commit="$1"
newmsg="$2"
branch="master"
git checkout $commit
git commit --amend -m "$newmsg"
git cherry-pick $commit..$branch
git branch -f $branch
git checkout $branch
}
演示
git init
echo init > a && git add . && git commit -m "init"
echo another > a && git commit -am "another"
echo lastly > a && git commit -am "lastly"
git log --graph --oneline --all --decorate
* bca608c (HEAD -> master) lastly * 4577ab5 another * b3d018c init
change-commit-msg 4577ab5 "something else"
* c7d03bb (HEAD -> master) lastly * 3ec2c3e something else * b3d018c init
关于git - 更改特定提交的提交消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38892599/