LoginSignup
29
24

More than 1 year has passed since last update.

Git push後のコミットメッセージを変更する方法

Last updated at Posted at 2023-01-21

はじめに

これまで色々なプロジェクトに参加してきましたが、コミットメッセージが指定されている案件が意外とあります。
しかし、開発しているとコミットメッセージに意識が回らずフォーマットを無視してcommitしてしまいそのままpushしてしまうということが多々ありました。
最悪ブランチを作り直したりすれば良いのですが、それは面倒なので今回はpush後のコミットメッセージを変更する方法を紹介します。

push後のコミットメッセージを変更する方法 

git logで現状を確認

$ git log --oneline
61776cf (HEAD -> master, origin/master) readme修正2
33c682d readmeを変更1
33eaec9 initialize repozitory

今回は1つ前のreadme修正2と2つ前のreadmeを変更1のコミットメッセージを修正していきます。

該当コミットを指定

# HEAD~3で遡るコミット数を指定
$ git rebase -i HEAD~3
# 上記でエラーが出る場合は
$ git rebase -i --root

以下のような画面になるはずです。

pick 33eaec9 initialize repozitory
pick 33c682d readmeを変更1
pick 61776cf readme修正2

# Rebase 61776cf onto 0fc52ae (3 commands)
# 以下省略

修正したいコミットのpickの部分をeoreditに変更します

pick 33eaec9 initialize repozitory
e 33c682d readmeを変更1
e 61776cf readme修正2

# Rebase 61776cf onto 0fc52ae (3 commands)
# 以下省略

この状態で保存:wq

amendでコミットを修正

$ git commit --amend

以下のような画面になるのでメッセージを修正します

readmeを変更1修正

# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# Date:      Sun Jan 22 04:27:17 2023 +0900
#

修正したら:wq
以下のようなメッセージが出ればOK

[detached HEAD fbd1503] readmeを変更1修正
 Date: Sun Jan 22 04:27:17 2023 +0900
 1 file changed, 1 insertion(+), 24 deletions(-)

次のコマンドで、1つ目の修正を終了

$ git rebase --continue

今回は複数のコミットを修正しているのでもう一度

$ git commit --amend

これによって2つ目のコミットの修正画面になるので同様に修正して保存:wq
次のコマンドで、2つ目の修正を終了

$ git rebase --continue
Successfully rebased and updated refs/heads/master.

上記のようなメッセージが出れば変更完了!

pushする

$ git push --force-with-lease origin master

普通にpushすると通らないので--force-with-leaseオプションをつけます。
普通の-fオプションは使わないようにします(*説明は省略)

確認

最後にコミットメッセージが変更されたか確認しましょう

$ git log --oneline
6b8f1c2 (HEAD -> master, origin/master) readme修正2修正
310e3cf readmeを変更1修正
33eaec9 initialize repozitory

これで完了です🎉

最後に

この方法は最終的に強制的なpushしているのでチーム開発などをしている場合には利用には十分に注意してください。
mergeされていない、自分の作業ブランチなどで行うのは大丈夫です!
何か間違いなどありましたらご指摘ください!

29
24
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
24