Skip to content

Instantly share code, notes, and snippets.

@kymmt90
Last active December 28, 2022 11:42
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kymmt90/9c997726b638b316f9be07aa4e3eea5e to your computer and use it in GitHub Desktop.
Save kymmt90/9c997726b638b316f9be07aa4e3eea5e to your computer and use it in GitHub Desktop.
`git reflog` についてまとめてみる

git reflog についてまとめてみる

reflog とは

  • reflog(参照ログ)とは HEAD やブランチ先端の動きの履歴
    • 各個人のローカルリポジトリに存在
    • ブランチの切り替え、新たに加えられた変更のプル、履歴の書き換え、あるいは単なる新規コミットの実行などを記録
  • git reflog で HEAD の移動履歴を、git reflog <ブランチ名> でそのブランチ先端が指していたコミットの一覧を確認可能
    • HEAD@{5}: HEAD の五つ前の状態を示す
$ git reflog
d22bfa0 HEAD@{0}: commit (amend): Add the contens of poem-c
8c9300c HEAD@{1}: commit: Add the contens of poem-c
6a67f31 HEAD@{2}: commit: Add empty poem-c
f7c3605 HEAD@{3}: reset: moving to @^
...
  • git log -ggit log 風の出力で reflog が見られる
  • git show HEAD@{5} でも確認可能

reflog をデータリカバリに使う

  • 間違えて意図と異なるコミットへ git reset --hard して、必要なコミットを失った場合
    • git refloggit log -g で reflog を見る
    • 失ったコミットがあれば、git reset --hard HEAD@{<n>} でそのコミットへ HEAD を移動できる
    • git branch recover-branch HEAD@{<n>} すれば、そのコミットが先端のブランチを作成できる

かんたんなデータリカバリをやってみる

現在、master が次のようなログだとする。

af3cfdd Add d.txt
d8441e3 Add c.txt
aefb89f Add b.txt
2dace69 Add a.txt

間違えて git reset --hard @^^ しちゃう。さらにターミナルとかをすべて閉じてしまって、もとの HEAD のハッシュ値もわからない。すると、ログは次のようになる。

aefb89f Add b.txt
2dace69 Add a.txt

そのままでは d8441e3 より先に戻れないので、reflog を使う。

$ git reflog
aefb89f HEAD@{0}: reset: moving to @^^
af3cfdd HEAD@{1}: commit: Add d.txt
d8441e3 HEAD@{2}: commit: Add c.txt
aefb89f HEAD@{3}: commit: Add b.txt
2dace69 HEAD@{4}: commit (initial): Add a.txt

直前に reset したことや、それ以前に commit していたことがわかる。

af3cfdd に戻りたいので、次のコマンドを叩く。

$ git reset --hard HEAD@{1}

すると、HEAD がaf3cfdd に戻る。

$ git log
af3cfdd Add d.txt
d8441e3 Add c.txt
aefb89f Add b.txt
2dace69 Add a.txt

参考文献

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment