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で失敗した変更を全て取り消して特定のコミットに戻す方法

Posted at

はじめに

Gitで開発していると、複数のブランチで作業したり、実験的な変更を加えたりした後に「あ、これ全部失敗だった...」となることがあります。

  • 複数のブランチで色々試したけど、どれも上手くいかなかった
  • コミットしていない変更がたくさんある
  • スタッシュに退避したものも含めて全部なかったことにしたい
  • 特定のコミットの状態に完全に戻したい

こんな時の対処法をまとめました。

TL;DR

# 1. メインブランチの特定のコミットに強制的に戻す
git checkout -f main
git reset --hard <commit-hash>

# 2. 不要なブランチを全て削除
git branch -D branch1 branch2 branch3

# 3. スタッシュを全てクリア
git stash clear

詳しい手順

1. 現在の状況を確認

まず、現在の状況を把握します。

# 現在のブランチと変更状況を確認
git status

# 全てのブランチを確認
git branch -a

# スタッシュの一覧を確認
git stash list

# 最新のコミット履歴を確認
git log --oneline -10

2. 戻りたいコミットを特定

# メインブランチの履歴を確認
git log main --oneline -10

出力例:

abc1234 docs: add release notes for v0.2.1
def5678 chore: bump version to 0.2.1
ghi9012 fix: ナビゲーションバーの修正
...

この中から戻りたいコミットのハッシュ値(例:abc1234)を控えます。

3. 全ての変更を破棄して特定のコミットに戻る

コミットされていない変更がある場合

# 強制的にメインブランチに切り替えて、特定のコミットに戻す
git checkout -f main
git reset --hard abc1234

-fオプションを使うことで、保存されていない変更があっても強制的に切り替えます。

既にメインブランチにいる場合

# 特定のコミットに強制的にリセット
git reset --hard abc1234

4. 不要なブランチを削除

# ローカルブランチを一つずつ削除
git branch -D feature/failed-feature-1
git branch -D fix/failed-fix-1

# または、main以外の全てのブランチを一括削除(Bash)
git branch | grep -v "main" | xargs git branch -D

-Dオプションは、マージされていないブランチも強制的に削除します。

5. スタッシュをクリア

# 全てのスタッシュを削除
git stash clear

# または、特定のスタッシュだけを削除
git stash drop stash@{0}

6. 最終確認

# クリーンな状態になったか確認
git status
git branch -a
git stash list

期待される出力:

On branch main
Your branch is up to date with 'origin/main'.

nothing to commit, working tree clean

注意事項

⚠️ データの復旧は困難

これらのコマンドを実行すると、以下のデータは基本的に復旧できません:

  • コミットされていない変更
  • 削除したブランチのコミット(参照がなくなるため)
  • クリアしたスタッシュ

💡 より安全な方法

完全に削除する前に、バックアップを取ることをおすすめします:

# 現在の状態をバックアップブランチに保存
git checkout -b backup/before-reset

# または、現在の作業をスタッシュに保存
git stash save "backup before reset"

リモートリポジトリとの同期

リモートにプッシュ済みのブランチがある場合:

# リモートブランチも削除したい場合
git push origin --delete feature/failed-feature-1

# ローカルの状態をリモートに強制的に反映(危険!)
git push --force-with-lease origin main

--force-with-lease--forceより安全で、他の人がプッシュしていた場合は失敗します。

まとめ

Gitで失敗した変更を全て取り消したい時は:

  1. git checkout -fgit reset --hardで特定のコミットに戻る
  2. git branch -Dで不要なブランチを削除
  3. git stash clearでスタッシュをクリア

これらは破壊的な操作なので、実行前に本当に必要か確認し、可能であればバックアップを取ることをおすすめします。

参考

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?