かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

GitHubに間違ってpushしたcommitを消す。

リモートのpushを1つだけ戻したい時

$ git push -f origin HEAD^:ブランチ名

localのブランチを修正してGitHub上に反映する時

$ git rebase -i HEAD^

修正したいコミットが3つ前ならHEAD~3、2つ前ならHEAD~2などを指定
エディタが立ち上がるので、修正したい pick から始まるコミットを削除して保存

pick dad6fe7 コミット
pick 2bb1e85 間違ったコミット # ←消したいコミットを消して保存
pick de8687c コミット

# Rebase 4fd8f0d..de8687c onto 4fd8f0d
#
# 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
~

GitHubにpush

$ git push -f origin ブランチ名

上記の方法は -f オプションで強制的にpushしないとダメなので
複数の人がコミットしてるブランチではやらない方が良さそう。

複数の人がpullしてるブランチならgit revertを使って
元に戻したというコミットを行ってpushするのが良さそうだと思いました。

[参考にしました]
githubにgit pushした変更の取り消し - Hack Your Design!
【派閥別】Gitのコミットを間違えたときの対処法まとめ - 本当は怖い情報科学