0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gitリポジトリが破損して「error: object file」が出た時の復旧

Last updated at Posted at 2025-12-31

1. 事象:何が起きたか

VSCodeでコミットや同期中に強制終了・連打等を行うと、Gitの内部オブジェクトが空(0バイト)で書き込まれ、リポジトリが破損することがあります。

.git/fsck

を実行すると、どこが壊れているか確認できます。

主なエラーログ:

error: object file .git/objects/XX/XXXXXX is empty
fatal: loose object XXXXXX is corrupt
fatal: missing object XXXXXX for refs/heads/main

git loggit push が一切受け付けられない状態になります。

2. 解決策:リポジトリの再構築

破損が広範囲(missing blob が複数発生)な場合、一つずつファイルを修復するより、.git フォルダを再生成してリモートの歴史と紐付け直すのが最短です。

手順

※ 作業ディレクトリのソースコードは保持されます。

# 1. 破損したGit管理情報の削除
rm -rf .git

# 2. Gitの再初期化
git init

# 3. リモートリポジトリの再登録
git remote add origin https://github.com/ユーザー名/リポジトリ名.git

# 4. リモートの履歴を取得
git fetch

# 5. 現在のファイルを保持したまま、履歴だけをリモートのmainに合わせる
git reset --mixed origin/main

# 6. (必要なら) masterブランチが生成された場合はmainにリネーム
git branch -m master main

# 7. 全ファイルをステージングして再コミット
git add .
git commit -m "fix: restore corrupted repository"

# 8. リモートへ強制プッシュ(歴史を一本化)
git push -f origin main

3. なぜこれで直るのか

  • .git を消すことで、破損した「空のオブジェクト」や「壊れた履歴(reflog)」を完全に破棄できます。
  • git reset --mixed により、「ファイルの実体は今のまま、Gitの管理名簿だけをリモートの状態に戻す」 ことができます。
  • 足りなかったオブジェクト(missing blob)は、git add 時に現在のファイルから正しく再生成されます。

4. 教訓

  • Git操作中(特にネットワーク通信中)にプロセスを強制終了しない。
  • 万が一壊れたら、ソースコードが無事なうちにバックアップを取り、.git の再構築を検討する。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?