クイック エンジニアリングブログ

株式会社クイック Web事業企画開発本部のエンジニアリングチームが運営する技術ブログです。

Gitで特定のコミットへrevertする方法

Gitで、あるコミットまでロールバックする方法が知りたかったので調べた。

結論

これでいいらしい。

# Reset the index and working tree to the desired tree
# Ensure you have no uncommitted changes that you want to keep
git reset --hard 56e05fced

# Move the branch pointer back to the previous HEAD
git reset --soft HEAD@{1}

git commit -m "Revert to 56e05fced"

参考:

Revert to a commit by a SHA hash in Git? - Stack Overflow

試したこと

真っ先に調べたのが

git revert 56e05fced

ですが、これは56e05fcedを取り消すという意味なので、今回やりたいこととは違います。

次に、よく検索で引っかかるのが、

git reset --hard 56e05fced
git push -f origin master

という方法。

単にgit push origin masterだと、先にgit pullしてと怒られる。まあresetしているので当然ですが。

GitHubで、masterブランチをprotectしていると使えないので、これはやりません。

ロールバック時だけprotectを外すという奥の手も考えましたが、そうするとproctectしている意味がないですよね・・・。副作用ありそうですし。

こちらの方法もよく引っかかります。

git checkout 56e05fced

確かにこれ、一時的に現在あるファイルは56e05fcedになるんですが、それをorigin/masterに反映できないんですよね。

git checkout -b rollback-56e05fced
git push origin rollback-56e05fced

とかやって、GitHub上でrollback-56e05fced => masterへのPull Request送っても、何も変更してないよって言われるだけです。まあ、これも当然ですが・・・。

一瞬、

git checkout 56e05fced
mkdir /tmp/my-project
cp -r . /tmp/my-project
git checkout master
cp -r /tmp/my-project/* .

が頭をよぎりましたが、さすがにダサすぎるのでやめました。

ならば、origin/masterにいながらファイルを変更すれば?と思い、次を試しました。

git checkout 56e05fced .
git add -A .
git commit -m 'Rollback to 56e05fced'

残念ながら、これは新しく追加されたファイルには適用できないみたいで、駄目でした。

結局、「git revert to a commit」でググり、結論にたどり着きました。

おまけ

弊社では、Gitに詳しいエンジニアを募集しています。

https://www.green-japan.com/job/40769

よろしければ、ご覧ください。