よしたく blog

ほぼ週刊で記事を書いています

git rebaseでコミットを分割する

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'

コミットの粒度が合っていないので分割する。

現状の確認

現在の状態を確認しておく。

f:id:yoshitaku_jp:20201204214015p:plain

git rebaseでコミットを分割する

git rebase -i HEAD~6を実行するとエディタの画面に切り替わる。 今回は 6 個前までのコミットを表示している。

f:id:yoshitaku_jp:20201204214025p:plain

今回の場合は、ep4,ep5,ep6 を分割したい。 「season1 ep4,ep5,ep6」のpickeditに変更する。 終わったら保存する。

f:id:yoshitaku_jp:20201204214038p:plain

エディタ画面が終わって、普通の画面に戻ってくる。

f:id:yoshitaku_jp:20201204214050p:plain

もう一度、現在の状態を確認しておく。 すると、HEAD の位置が「season1 ep4,ep5,ep6」のコミットメッセージに移っている。

f:id:yoshitaku_jp:20201204214102p:plain

git statusをおこなっても何もファイルがない。

f:id:yoshitaku_jp:20201204214111p:plain

git reset HEAD~を実行し、1 つ前のコミットをステージングに戻す。

もう一度git statusを実行すると、「season1 ep4,ep5,ep6」のコミットがステージングに戻っているのがわかる。 f:id:yoshitaku_jp:20201204214121p:plain

これで、エピソードごとにコミットが可能になる。

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をおこない、編集状態から抜ける。

f:id:yoshitaku_jp:20201204214133p:plain

git logをすると無事に分割されていることがわかる。

f:id:yoshitaku_jp:20201204214141p:plain

yoshitaku-jp.hatenablog.com