Git for Web Developersという書籍のp118に記載されているgit rebaseコマンドの練習をしたのでまとめておく。
git rebaseで過去のコミットメッセージを変更する方法
rebase前のコミット履歴がこちら。

ファイルの状態はこちら。

まずは、rebaseコマンドで0b88cc2のコミットメッセージである「メソッドAのバグを修正」を変更する。

このコマンドを実行すると、エディタが開く。

そこで、変更したいコミットのpickをrewordにする。

これで保存して閉じると、以下のように再度エディタが開くので、コミットメッセージを修正する。


そして、変更後エディタを閉じる。
すると、rebaseが完了するので、git logで確認してみる。

狙い通り、コミットメッセージを変更できた。
ここで、変更したコミット以降のコミットIDが変化している点に注意すること。
なお、rebaseについては、コミットIDを直接指定することでも実行できる。
先ほどと同じく、HEADの一つ前のコミット906e3b1を修正する場合は、それより一つ前(その親)の2f8c16cを指定すればいい。




今後rebaseを使ったら、追記していく。
git rebaseでブランチを統合する方法
featureブランチで開発を進めつつも、masterの最新状況を取り込むことを想定して、rebaseでのブランチ統合を練習する。
まず、rebase前のmasterのコミット履歴がこちら。
そして、対象のファイルGit for Web Developers.txtの中身がこちら。

同様にrebase前のfeatureがこちら。


ここで、featureにて、masterをrebaseさせる。
まずは、rebaseコマンドを実行する。

ただし、コンフリクトが発生していて、エディタが開く。
First, rewinding head to replay your work on top of it.
Applying: feature-d
Using index info to reconstruct a base tree…
M Git for Web Developers.txt
Falling back to patching base and 3-way merge…
Auto-merging Git for Web Developers.txt
CONFLICT (content): Merge conflict in Git for Web Developers.txt
error: Failed to merge in the changes.
hint: Use ‘git am –show-current-patch’ to see the failed patch
Patch failed at 0001 feature-d
Resolve all conflicts manually, mark them as resolved with
“git add/rm <conflicted_files>”, then run “git rebase –continue”.
You can instead skip this commit: run “git rebase –skip”.
To abort and get back to the state before “git rebase”, run “git rebase –abort”.

そこで、コンフリクトを1つずつ解決していく。
まずは、以下の通りに解決して保存。

ここで、変更をaddして、エラーの指示通りcontinueで続ける。

すると、まだコンフリクトがあるのでエラーが出る。
Applying: feature-d
Applying: feature-e
Using index info to reconstruct a base tree…
M Git for Web Developers.txt
Falling back to patching base and 3-way merge…
Auto-merging Git for Web Developers.txt
CONFLICT (content): Merge conflict in Git for Web Developers.txt
error: Failed to merge in the changes.
hint: Use ‘git am –show-current-patch’ to see the failed patch
Patch failed at 0002 feature-e
Resolve all conflicts manually, mark them as resolved with
“git add/rm <conflicted_files>”, then run “git rebase –continue”.
You can instead skip this commit: run “git rebase –skip”.
To abort and get back to the state before “git rebase”, run “git rebase –abort”.
そこで、次の競合を解決する。


そして、保存して閉じたら、add,continueする。

リベースが完了したので、featureのコミット履歴を確認してみる。
すると、以下のようにmasterのコミットが取り込まれつつも、自分のコミット履歴も適切に反映されている。

続いて、念の為にmasterに切り替えて、masterの状態も確認しておく。

masterには変更はないので、問題なし。
次に、再度featureに戻って、diffでrebaseによる変更箇所を確認する。
rebase前のfeatureの最後のコミットIDと、rebase後の現在の最新コミットのIDを比較する。

その結果、No newline at end of fileという余計な内容が含まれていることがわかる。
これは、rebase前のmasterブランチにおけるGit for Web Developers.txtファイルにて、最後に改行がなかったためである。

そのため、rebase前のmasterブランチにおける最後のコミット時にNo newline at end of fileが含まれてしまった。
今後は、コミット前にdiffで追加されるファイル内容を必ず確認することとする。
なお、rebaseに失敗した場合は、featureの最後のコミットIDのを指定して、rebase前の状態に戻すことができる。
今回だと、03273d2がrebase前のfeatureの最後のコミットである。
上記のresetコマンドを実行すると、以下のようにfeatureがrebase前の状態に戻る。
