以下記事の続き。
「commitをまとめたい」を見ていく。
やりたいこと
開発中は細かくcommitし、レビュワーに依頼する際にcommitをまとめたい。
やり方
git rebase -i
を使う
(準備)commit用のファイルを用意する
前回記事からc.txt
とd.txt
を増やした。
❯ ls
README.md a.txt b.txt c.txt d.txt
txtファイルの中身はファイル名が一文字書いてある。
例えばa.txt
ならa
とだけ書いてある。適当に用意しただけなので、意味はない。
❯ cat a.txt a
初期状態
以下の状態から始める1。
❯ git log --pretty=oneline f17ee3b566b60c4dad9250d9d67b7ae157c1d5e1 (HEAD -> master) Merge branch 'add-b' bceca8ee93f256fb1d4083798c1aed1e3b1c8c16 (add-b) add b.txt b1abe76c7f481cecf64934a98dcd1971a13496e6 (add-a) add a.txt 635c5d5570a6c0492be7a924dda3df314bfd13b8 first commit
add-c-and-d
ブランチ
add c.txt
とadd d.txt
で別々のcommitを行う。
❯ git checkout -b add-c-and-d ❯ git add c.txt ❯ git commit -m "add c.txt" ❯ git add d.txt ❯ git commit -m "add d.txt" ❯ git log --pretty=oneline 338cb6e2a328bebb420da2628fffa73f677da071 (HEAD -> add-c-and-d) add d.txt 2dfb9b998e3331cd1b6bf35badad9f362f04f6f1 add c.txt f17ee3b566b60c4dad9250d9d67b7ae157c1d5e1 (master) Merge branch 'add-b' bceca8ee93f256fb1d4083798c1aed1e3b1c8c16 (add-b) add b.txt b1abe76c7f481cecf64934a98dcd1971a13496e6 (add-a) add a.txt 635c5d5570a6c0492be7a924dda3df314bfd13b8 first commit
(本題)commitをまとめる
masterへマージするにあたり、上記2commit(add c.txt
とadd d.txt
)をまとめたくなった。
git rebase -i
で対応していく。add c.txt
の1つ前のcommitを指定していることに注意。
❯ git rebase -i f17ee3b566b60c4dad9250d9d67b7ae157c1d5e1
2つのcommitについて、それぞれreword
(commit messageの修正)とfixup
(まとめてしまうのでcommit messageは捨てる)にする。
reword 2dfb9b9 add c.txt fixup 338cb6e add d.txt
上記について:wq
すると、commit messageを修正するエディタが別途立ち上がるので、修正2。
add c.txt and d.txt # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # # Date: Sun Apr 26 16:10:59 2020 +0900 # # interactive rebase in progress; onto f17ee3b # Last command done (1 command done): # reword 2dfb9b9 add c.txt and d.txt # Next command to do (1 remaining command): # fixup 338cb6e add d.txt # You are currently editing a commit while rebasing branch 'add-c-and-d' on 'f17ee3b'. # # Changes to be committed: # new file: c.txt
結果(2つのcommitがまとめられている)
❯ git log --pretty=oneline e1db2b2b2082e379300d190faf634b015c6ba18c (HEAD -> add-c-and-d) add c.txt and d.txt f17ee3b566b60c4dad9250d9d67b7ae157c1d5e1 (master) Merge branch 'add-b' bceca8ee93f256fb1d4083798c1aed1e3b1c8c16 (add-b) add b.txt b1abe76c7f481cecf64934a98dcd1971a13496e6 (add-a) add a.txt 635c5d5570a6c0492be7a924dda3df314bfd13b8 first commit
最後にmasterにマージして終わり3。