git - 更改特定提交的提交消息

标签 git git-commit git-rewrite-history git-amend

注意:与 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 来更改提交消息。我想要的是:

  1. 函数 rewrite-commit-message 接受两个参数:commit_idnew_commit_message
  2. 不需要知道旧的提交信息:有 commit_id 就足以知道要更改哪个提交
  3. 没有 git commit --amend,因为这与旧提交相关(不一定与最近的提交相关)
  4. 不用担心重写历史和主仓库:我在一个特性分支工作,我被允许做 git push -f
  5. 我想使用 filter-branch为此,但我不确定如何:
    • 将更改应用于特定提交:rewrite-commit-date 函数中使用的test 用于env-filter,但我不打算在这里执行 env-filter,因为我不想更改与提交环境相关的任何内容,而是更改提交消息。
    • 如何强制提交信息? --msg-filter 需要原始提交消息。我不关心原始提交消息。是否有 --force-msg-filter 或类似的?

我要查找的内容类似于 this ,但有一些注意事项:

  1. 不要将更改应用于一系列提交,而是应用于特定的提交
  2. 我不关心原始提交消息,因为我想完全覆盖它

最佳答案

这个小脚本可以工作,但需要注意以下几点:

  1. 这将重写您从提交到分支顶端的历史记录。因为你在问题中说这不是问题,所以这符合条件。

  2. 您的提交包含在 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/

相关文章:

git - 当我使用参数化分支 : fatal: Couldn't find remote ref refs/heads/${BUILD_BRANCH} 时,Jenkins 无法构建

git - 使用git,如何在冲突期间执行 'use theirs'?

git - 何时从 Docker 存储库中提取,何时从 Git 存储库中提取然后构建?

intellij-idea - IntelliJ IDEA - git log 中作者姓名后的星号

git - SVN 到 Git 迁移 : Only import certain branches and history

git - 我可以重写整个 git 存储库的历史以包含我们忘记的东西吗?

git - 在本地从 Detached HEAD 进行一系列提交后,如何更新远程分支?

git - 如何拆分包含重构的 Git 提交?

混帐庆典 : stuck after writing the message for commit

git - git rebase --onto 分支后的 ~ 是什么意思?