git rebase でコミットの分割ができる。
今回は題材としてスターウォーズを取り上げて実践してみる。 想定のケースは「いくつかコミットをしたが、シーズンごとにファイルをまとめてコミットしてしまった箇所があり、その部分を分割する」というものにする。
準備
まずはファイルを作成する。
mkdir star-wars cd star-wars touch star-wars1.txt touch star-wars2.txt touch star-wars3.txt touch star-wars4.txt touch star-wars5.txt touch star-wars6.txt touch star-wars7.txt touch star-wars8.txt touch star-wars9.txt
次に git でコミットしていく。
ep4,ep5,ep6 だけseason1 ep4,ep5,ep6
というコミットメッセージになっている。
git init git add star-wars1.txt git commit -m 'ep1' git add star-wars2.txt git commit -m 'ep2' git add star-wars3.txt git commit -m 'ep3' git add star-wars4.txt star-wars5.txt star-wars6.txt git commit -m 'season1 ep4,ep5,ep6' git add star-wars7.txt git commit -m 'ep7' git add star-wars8.txt git commit -m 'ep8' git add star-wars9.txt git commit -m 'ep9'
コミットの粒度が合っていないので分割する。
現状の確認
現在の状態を確認しておく。
git rebase
でコミットを分割する
git rebase -i HEAD~6
を実行するとエディタの画面に切り替わる。
今回は 6 個前までのコミットを表示している。
今回の場合は、ep4,ep5,ep6 を分割したい。 「season1 ep4,ep5,ep6」のpickをeditに変更する。 終わったら保存する。
エディタ画面が終わって、普通の画面に戻ってくる。
もう一度、現在の状態を確認しておく。 すると、HEAD の位置が「season1 ep4,ep5,ep6」のコミットメッセージに移っている。
git status
をおこなっても何もファイルがない。
git reset HEAD~
を実行し、1 つ前のコミットをステージングに戻す。
もう一度git status
を実行すると、「season1 ep4,ep5,ep6」のコミットがステージングに戻っているのがわかる。
これで、エピソードごとにコミットが可能になる。
git commit -m 'ep4' git add star-wars5.txt git commit -m 'ep5' git add star-wars6.txt git commit -m 'ep6'
git rebase --continue
をおこない、編集状態から抜ける。
git log
をすると無事に分割されていることがわかる。