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

More than 3 years have passed since last update.

remoteにpushしているのにrebaseしちゃった時〜

1
Posted at

気づいたらgit rebaseしてしまっている時ありますよね。ない

ある時いつものように無意識にgit rebaseを打って作業、よしリモートに上げようと思ったらこんなエラーが出ました。

! [rejected]        branch-a -> branch-a (non-fast-forward)
error: failed to push some refs to 'https://github.com/hoge/git.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

そう。リモートブランチにプッシュしているのにrebaseしてしまっているのです。。。

もちろん一人で開発しているブランチならgit push --forceで強制的に上げてしまっても良いのですが、実はこれはあまりオススメされていません。rebaseは過去のコミット履歴を改変しているので共同開発をしているかつ同じブランチでコミットを上げていた場合にそのコミットが吹き飛ぶかもしれません。

仮に個人開発をしていても変な癖はつけたくない、そこでremoteにpushしているのにrebaseしちゃった時の対処法を2つ紹介します

1. --force-with-lease

一つ目の案はgit push --force-with-leaseです。
これは安全確認をした後にpush --forceをするといったニュアンスのもので他の誰もがリモートにプッシュしていないことを確認してpushすることができます。
ただ一つ注意点があり、git fetchなどで追跡ブランチを更新してしまうとリモートとの差分を検出できず--force-with-leaseでrejectされないということが起きます。
詳細🔽

2. rebaseを取り消し

もしrebaseをしてすぐ過ちに気づいたならばrebaseを取り消すことが良いかもしれません。
rebaseを取り消す方法はgit reflogを使えば良いです。
git reflogではgit logよりさらに細かいlog。操作を全て参照することができます。
ここでresetしてしまえばok
git reset --hard HEAD@{n}

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