如果由于某种原因提交失败,git 提交消息是否可以恢复?

如果由于某种原因提交失败,git 提交消息是否可以恢复?

git commitgpg.commitsign = true可能会因&&失败(无论出于何种原因)等原因而失败gpg。重试该命令会打开一个空白编辑器;消息丢失。

发生这种情况时,是否有任何方法可以恢复写入的提交消息,以使用相同的消息重试提交?

答案1

man git-commit

FILES
       $GIT_DIR/COMMIT_EDITMSG
           This file contains the commit message of a commit in progress. If git commit exits due to an error before creating a commit, any commit message that has been provided
           by the user (e.g., in an editor session) will be available in this file, but will be overwritten by the next invocation of git commit.

git commit因此,可以使用以下命令重试上一条消息,而不是重复:

$ git commit -m "$(cat .git/COMMIT_EDITMSG)"

或者一般情况(例如适合别名):

$ git commit -m "$(cat "$(git rev-parse --git-dir)/COMMIT_EDITMSG)")"

答案2

使用与先前(失败)提交相同的提交消息再次提交:

git commit -F "$(git rev-parse --git-dir)/COMMIT_EDITMSG" 
  • 要在提交之前有机会在文本编辑器中编辑提交消息,请添加-e( --edit) 选项。
  • 如果失败的提交是详细提交(例如git commit --verbose),您可能需要进行添加--cleanup=strip,以便 Git 添加到详细提交的注释不会被视为提交消息的一部分。

组合示例 - 在文本编辑器中编辑失败提交的消息,然后让 Git 在提交之前清理已编辑的提交消息:

git commit -eF "$(git rev-parse --git-dir)/COMMIT_EDITMSG" --cleanup=strip

参考文献来自man git-commit

-F <file>, --file=<file>
    Take the commit message from the given file. Use - to read the
    message from the standard input.
-e, --edit
    The message taken from file with -F, command line with -m, and from
    commit object with -C are usually used as the commit log message
    unmodified. This option lets you further edit the message taken
    from these sources.
--cleanup=<mode>
    This option determines how the supplied commit message should be
    cleaned up before committing. The <mode> can be strip, whitespace,
    verbatim, scissors or default.

    strip
        Strip leading and trailing empty lines, trailing whitespace,
        commentary and collapse consecutive empty lines.
    ...
FILES
       $GIT_DIR/COMMIT_EDITMSG
           This file contains the commit message of a commit in progress. If
           git commit exits due to an error before creating a commit, any
           commit message that has been provided by the user (e.g., in an
           editor session) will be available in this file, but will be
           overwritten by the next invocation of git commit.

(在git版本2.39.2中测试)

相关内容