2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ブランチ切る前にコミットしちゃった場合の対処法

Posted at

目次


状況

開発ブランチ develop でうっかりコミットしてしまい、そのコミットを別ブランチに分離したいケース。
リモートリポジトリへは未プッシュ前提で、コミットは残しておきつつ develop を元の状態に戻したい。

直し方

以下は未プッシュの場合の最小手順です。

現在のコミットを指す作業ブランチを作る

# いまいる develop の先頭コミットを新ブランチに退避
git branch fix/your-topic

# 以下でもOK
git checkout -b fix/your-topic

# すでに切り替え先ブランチがある場合は以下でもOK
git switch -b fix/your-topic

develop を元に戻す

git checkout develop
git reset --hard HEAD~1   # 直前のコミットを戻す
# もしくは安全に origin/develop に戻す
# git reset --hard origin/develop

状態確認

git status
git log --oneline --decorate --graph --all | head

これで:

  • fix/your-topic はコミットを保持
  • develop は元の状態に戻る

プッシュ済みの場合は運用ルールに従い、revertforce push を検討してください。

なぜ上のやり方で直せるか

  • コミットは「スナップショット」、ブランチはそれを指す「ポインタ」。ブランチを切った時点で、そのコミットを指す参照が新ブランチに残る。
  • reset --hard は「そのブランチのポインタを巻き戻す」操作であり、他ブランチには影響しない。ゆえに、develop を戻しても新ブランチはコミットを保持する。
  • git log --all で見えるのは「参照されているコミット」。新ブランチが参照を持つ限り、コミットはGCされず安全に残る。

以上の手順で、うっかりコミットを安全に退避しつつ、develop をクリーンに戻せます。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?