2つ以上前のコミットをamendで修正する方法
2つ以上前のコミットをamendで修正するにはrebaseコマンドを使用します。
例として以下のように"1st commit"、"2nd commit"、"3rd commit"の3つのコミットをしたレポジトリを使用します。
$ git log -p --oneline db32787 (HEAD -> main) 3rd commit diff --git a/c.txt b/c.txt new file mode 100644 index 0000000..f2ad6c7 --- /dev/null +++ b/c.txt @@ -0,0 +1 @@ +c 7f24aa7 2nd commit diff --git a/b.txt b/b.txt new file mode 100644 index 0000000..6178079 --- /dev/null +++ b/b.txt @@ -0,0 +1 @@ +b 31e0598 1st commit diff --git a/a.txt b/a.txt new file mode 100644 index 0000000..7898192 --- /dev/null +++ b/a.txt @@ -0,0 +1 @@ +a
今回は2つ前の"2nd commit"を修正したいので下記コマンドを実行します。
$ git rebase -i HEAD~2
そうするとエディタが立ち上がります。
"2nd commit"を修正したいので"pick"となっている部分を"edit"に修正してエディタを終了します。
# 2nd commitの行の先頭のpickをeditに修正してエディタを終了する pick 7f24aa7 2nd commit pick 918c18d 3rd commit # Rebase 31e0598..918c18d onto 31e0598 (2 commands) # # 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 [-C | -c] = like "squash" but keep only the previous # commit's log message, unless -C is used, in which case # keep only this commit's message; -c is same as -C but # opens the editor # x, exec= run command (the rest of the line) using shell # b, break = stop here (continue rebase later with 'git rebase --continue') # d, drop = remove commit # l, label
エディタを終了するとコマンドラインには以下のようなメッセージが表示されます。
$ git rebase -i HEAD~2 Stopped at 7f24aa7... 2nd commit You can amend the commit now, with git commit --amend Once you are satisfied with your changes, run git rebase --continue
"2nd commit"コミット後の状態になっているので修正を行います。
$ git log --oneline # 2nd commit後の状態になっている 7f24aa7 2nd commit 31e0598 1st commit $ echo "d" > d.txt $ git add d.txt # d.txtというファイルをadd $ git commit --amend # amendすると2nd commitのメッセージが表示されるのでメッセージの変更も可能 [detached HEAD 5290a77] 2nd commit edited Date: Sun Jan 23 21:24:14 2022 +0900 2 files changed, 2 insertions(+) create mode 100644 b.txt create mode 100644 d.txt $ git rebase --continue # 最後にrebase --continueで元に戻す Successfully rebased and updated refs/heads/main. $ git log -p --oneline # 2nd commitにd.txtが追加され、コミットメッセージも変更できている 7adf0ce (HEAD -> main) 3rd commit diff --git a/c.txt b/c.txt new file mode 100644 index 0000000..f2ad6c7 --- /dev/null +++ b/c.txt @@ -0,0 +1 @@ +c 5290a77 2nd commit edited diff --git a/b.txt b/b.txt new file mode 100644 index 0000000..6178079 --- /dev/null +++ b/b.txt @@ -0,0 +1 @@ +b diff --git a/d.txt b/d.txt new file mode 100644 index 0000000..4bcfe98 --- /dev/null +++ b/d.txt @@ -0,0 +1 @@ +d 31e0598 1st commit diff --git a/a.txt b/a.txt new file mode 100644 index 0000000..7898192 --- /dev/null +++ b/a.txt @@ -0,0 +1 @@ +a