気ままに気ままのエンジニアブログ

定期的に得た知見を気ままに発信中

【Git】git rebase -f で複数commitをまとめる

こんにちは。

夏に近づいてきました。
夏といえば、夏だ!プールだ!サマーランドだ!
こんなキャッチーな命名の付け方を教えてほしい...

どうもハチマキです。

はじめに

PRのルールとして、1 function, 1commitを原則とした開発チームで開発をしております。
そのため、不要なcommitをまとめる必要があり、その際に初めてgit rebaseを活用しました。

やりたいこと

複数のcommitを1つにまとめたい

実行コマンド

% git log #まとめるコミット数を確認する
% git rebase -i HEAD~3 #まとめたいcommit数をHEAD~の数字に記述
※こちらを実行すると、以下のようなテキストが現れます。まとめたいcommitを「pick」から「squashに修正(sでもOK)」→保存

修正前
pick aaaaaa テストの追加
pick bbbbbb タイポ修正
pick cccccc 一覧画面改修

↓↓↓↓

修正後
pick aaaaaa テストの追加
s bbbbbb タイポ修正
s cccccc 一覧画面改修

※「bbbbbb」と「cccccc」を「aaaaaa」にまとめる

#
# 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
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

------------------------------------------------

% git log #commitが一つにまとまったことを確認

% git push origin ブランチ名 #既にcommitしているものがあると、rejectedが発生します。
To https://github.com/.......
 ! [rejected]            
error: failed to push some refs to 'https://github.com/.......
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

#rejectedが発生した場合は、オプションの-fをつける(強制的に書き換える)
% git push -f  origin ブランチ名 

これだけです。