Skip to content

reflogと履歴の復元

Gitの操作履歴を確認し、失ったコミットを復元するreflogについて詳しく解説します。

なぜreflogを理解する必要があるのか

Section titled “なぜreflogを理解する必要があるのか”

問題のある状況:

開発者: 「間違ってreset --hardしてしまった...」
開発者: 「コミットが消えてしまった...どうしよう?」
// 問題点:
// - 失ったコミットを復元できない
// - 作業が失われる
// - データの損失

影響:

  • 作業の損失
  • データの損失
  • 開発時間の無駄

改善された状況:

reflogによる復元:
- すべての操作履歴が記録される
- 失ったコミットを復元できる
- データの損失を防ぐ

メリット:

  • 作業の復元が可能
  • データの損失を防止
  • 安全な操作

reflog(Reference Log):

  • Gitのすべての操作履歴を記録
  • HEADの移動履歴を保持
  • 失ったコミットを復元可能

特徴:

  • 自動的に記録される
  • 90日間保持(デフォルト)
  • ブランチごとに記録される

reflogの確認:

Terminal window
# reflogを表示
git reflog
# 出力例:
# abc1234 HEAD@{0}: checkout: moving from main to feature
# def5678 HEAD@{1}: commit: 最新のコミット
# ghi9012 HEAD@{2}: commit: 前のコミット
# jkl3456 HEAD@{3}: checkout: moving from feature to main
# 特定のブランチのreflogを表示
git reflog show <ブランチ名>
# 例:
git reflog show main
git reflog show feature/user-auth

reflogの詳細表示:

Terminal window
# 詳細情報を表示
git reflog show --all
# 特定のエントリの詳細を表示
git log -g --oneline HEAD@{5}

実践例:

Terminal window
# 1. 間違ってreset --hardを実行
git reset --hard HEAD~3
# コミットが失われた...
# 2. reflogで履歴を確認
git reflog
# abc1234 HEAD@{0}: reset: moving to HEAD~3
# def5678 HEAD@{1}: commit: 失ったコミット1
# ghi9012 HEAD@{2}: commit: 失ったコミット2
# jkl3456 HEAD@{3}: commit: 失ったコミット3
# 3. 失ったコミットを復元
git reset --hard def5678
# または
git reset --hard HEAD@{1}
# 4. 復元を確認
git log --oneline

実践例:

Terminal window
# 1. 間違ってブランチを削除
git branch -D feature/important-feature
# 2. reflogでブランチの履歴を確認
git reflog
# abc1234 HEAD@{0}: branch: deleted feature/important-feature
# def5678 HEAD@{1}: commit: 重要なコミット
# 3. ブランチを復元
git checkout -b feature/important-feature def5678
# または
git checkout -b feature/important-feature HEAD@{1}

実践例:

Terminal window
# 1. reflogでコミットを検索
git reflog | grep "重要な機能"
# 2. コミットハッシュを確認
# def5678 HEAD@{5}: commit: 重要な機能を実装
# 3. コミットを復元
git checkout def5678
# 4. 新しいブランチを作成
git checkout -b feature/restored-feature
# 5. または、現在のブランチに適用
git checkout main
git cherry-pick def5678

実践例:

Terminal window
# reflogの期限を確認
git reflog expire --dry-run --expire=90.days
# reflogを期限前に削除
git reflog expire --expire=now --all
# 特定のブランチのreflogを削除
git reflog expire --expire=now <ブランチ名>

実践例:

Terminal window
# reflogをバックアップ
cp .git/logs/HEAD .git/logs/HEAD.backup
# すべてのreflogをバックアップ
tar -czf reflog-backup.tar.gz .git/logs/

reflogと履歴の復元のポイント:

  • reflog: Gitの操作履歴を記録、失ったコミットを復元可能
  • 基本的な使い方: reflogの確認、詳細表示
  • 失ったコミットの復元: reset、checkout、cherry-pickを使用
  • ブランチの復元: 削除されたブランチの復元
  • reflogの管理: 期限の設定、バックアップ

適切にreflogを使用することで、失ったコミットを安全に復元できます。