IT徒然草

IT関係のことを解説したり一人つらつら書いたり

Gitでコミットメッセージをやらかしたときに修正する方法

Gitではコミットメッセージを修正できる!

Gitでコミットメッセージを修正する方法は以下の3つあります。このうち、commit --amendは直前のコミット専用です。

  • commit --amend

  • rebase →edit+commit --amend

  • rebase →reword

直前のコミットの場合

以下のように入力して、コミットメッセージを修正します。なお、--amendは、「直前のコミットを上書き」という意味です。ですので、--amendは コミットメッセージの変更以外、例えば、ファイルを後から追加、などにも使えます。

git commit --amend  -m 変更後のメッセージ

2つ以上の前のコミットの場合

最初に、rebaseを行います。^は一つ前のコミットを表し、「~数」と指定すると、「数」の分だけのリベースができます。対話モードで起動させたいので、-iオプションをつけています。

git rebase -i HEAD^

この場合、1つ前のコミットをリベースしています。 すると、Vimが起動します。ここで、修正したいコミットの右側にある、「pick」を「reword」に修正します。今回は、36eaeafを修正したいので、「pick」から「reword」に修正します。

reword 36eaeaf Add Snapcraft files

# Rebase 7cb6b0b..36eaeaf onto 7cb6b0b (1 command)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

その後、またVimが起動するので、変更したいようにメッセージを修正します。

Add Snapcraft files ←ここを修正

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Author:    test <main@gmail.com>
# Date:      Sun Dec 15 18:00:10 2019 +0900
#
# interactive rebase in progress; onto 7cb6b0b
# Last command done (1 command done):
#    reword 36eaeaf Add Snapcraft files
# No commands remaining.
# You are currently editing a commit while rebasing branch 'master' on '7cb6b0b'.

編集が終わった後、ファイルを保存、Vimを終了させると正しくメッセージが更新されています。

git log
commit eac2057931af52250ed19ded050843c0a76eb1ec (HEAD -> master)
Author: test <main@gmail.com>
Date:   Sun Dec 15 18:00:10 2019 +0900

    Add Snapcraft

まとめ

まとめると以下のようになります。

  • 直前のコミット→git commit --amend 変更したいメッセージ

  • 2つ以上前→git rebaseした後、rewordを行う。

(C)2020 EnjoySoftware All rights reserved.