git rebaseの使い方をやっと理解したので忘備録を書いておこうっと。
他の人とのやりとりはgit mergeだけで十分
普段の作業はgit mergeだけで十分。ほぼすべての場合は、git mergeだけで十分。これを肝に命じておく。
git rebaseはコミット粒度を上げるためにgit branchとセットで使う
git rebaseとは、小さな多数のコミットを、ひとつのコミットにまとめたいときに使う。
少し修正して、commit、試験。少し修正して、commit、試験。少し修正して、commit、試験。普段の作業はこんな感じじゃないのかな。
でも、コミットのメッセージを書く単位よりも小さく、コミットしたいときはよくある。ここ一行だけ変えて、試験したいとかね。コミット粒度を小さくしておけば、間違った部分だけを、git revertで戻せるし、git resetで戻れるから。
git branchで作業
今やる作業をgit branchで作る。
git branch mywork
そしてチェックアウト
git checkout mywork
こうして、作業ブランチを作る。
そして何回も何回も小さくコミットする。
git add . git commit "remove part of memory pool" git push origin mywork git add . git commit "cleanup" git push origin mywork git add . git commit "cleanup2" git push origin mywork
リベース用のブランチの作成
git rebaseはコミット改変という危険な作業だ。だから、リベース用の特別なブランチを作成する
git branch mywork_rebase
そして、このブランチにチェックアウト。
git checkout mywork_rebase
リベースの作業
そして、意味のある単位で、ほかの人が見てもわかるようあ単位で、rebaseする。今いるブランチはmywork_rebaseで、基準のブランチはmasterだ。リベースすると、基準のブランチを元に、今あるブランチで伸びているコミットを一つにまとめてくれる。iオプションを使う
git rebase -i master
そうすると以下のようにviが立ち上がる。
pick 98ad9ee remove part of memory pool pick 681ff04 cleanup pick a9c8dd1 cleanup2 # Rebase 274bce5..a9c8dd1 onto 274bce5 # # 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 = like "squash", but discard this commit's log message # x, exec = run command (the rest of the line) using shell
今はpickと3行、表示されているけれど、2行目以降のpickをすべて「s」に変更する。こうすると一つのコミットにまとめられる。
pick 98ad9ee remove part of memory pool s 681ff04 cleanup s a9c8dd1 cleanup2 # Rebase 274bce5..a9c8dd1 onto 274bce5 # # 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 = like "squash", but discard this commit's log message # x, exec = run command (the rest of the line) using shell
こうして「wq」で保存。そうすると再びviが立ち上がるので、新しくコミットメッセージを書く。これで完了。
このブランチは最後にmasterにマージされるブランチになる。
git rebaseしていいのは、プライベートな作業ブランチだけ
git rebaseはプライベートな作業ブランチだけ
だから、git rebaseはプライベートな作業ブランチで、プライベートな小さなコミットを、ひとつのコミットにまとめるときに使うと。