してはいけない例
pushしてしまったcommitを消すためのHackとして、リモートブランチを消して再度pushするという方法が推奨されていたりするんですが、これは絶対にやめてください。
# 不要なcommit1と不要なcommit2を消したい
$ git log --oneline
hash789 不要なcommit2
67hash8 不要なcommit1
ha567sh 正しいcommit
# 正しいcommitまで戻す
$ git reset --hard ha777sh
# リモートのブランチを消す
$ git push origin :develop
# ローカルをリモートにpushする
$ git push origin develop
確かに消すことはできるんですが、そのリモートのブランチに紐付いているPull Requestが全部closeされてしまいます。
していい例
なので、たとえ誰にもバレてなかったとしても、おとなしくrevertしてcommitに記録を残しましょう。
# 不要なcommitを打ち消す
$ git revert hash789
$ git revert 67hash8
# commitをまとめる
$ git rebase -i HEAD~2
rebaseコマンドを打つとcommitをどうするかのエディタが開きますので、一番上だけ残してsquashに書き換えます。
pick hash789 Revert "不要なcommit2"
- pick 67hash8 Revert "不要なcommit1"
+ squash 67hash8 Revert "不要なcommit1"
# Rebase hash789..67hash8 onto hash789
エディタを閉じるとメッセージをまとめるかどうか聞かれますので、まとめたメッセージを記入して閉じます。
- # This is a combination of 2 commits.
- # The first commit's message is:
-
- 不要なcommit2
- This reverts commit hash789hash789hash789hash789hash789.
-
- # This is the 2nd commit message:
-
- 不要なcommit1
- This reverts commit 67hash867hash867hash867hash867hash8.
+ 不要なcommitをRevert
# Please enter the commit message for your changes. Lines starting
あとはpushすればOKです。
$ git push origin master
シリーズと言いつつ続編は考えてません。