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で派生元ブランチを間違えたときの修正方法

0
Posted at

結論

作業ブランチの派生元を間違えた場合は rebase --onto で付け替えできます。

git checkout feature-auth
git rebase --onto develop main feature-auth
git push origin feature-auth --force-with-lease

想定している状況

今回の例

役割 ブランチ
誤った派生元 main
正しい派生元 develop
作業ブランチ feature-auth

さらに

  • developmain から派生
  • main , develop には別の変更が追加されている
  • feature-auth誤って main から作成
  • すでに push 済み

修正前のブランチ構造

この状態では

feature-auth → main から派生

しかし本来は

feature-auth → develop から派生

にしたい状態です。


修正後(理想)

feature-authdevelop の上に移動させます。


修正手順

① 作業ブランチへ移動

git checkout feature-auth

② 派生元を付け替える

git rebase --onto develop main feature-auth

コマンドの意味

git rebase --onto <新しい親> <古い親> <対象ブランチ>

今回の意味

main 以降の feature-auth のコミットを
develop の上に付け替える

つまり

F → G

のコミットを

develop の先頭

へ移動します。


rebase後のイメージ

Before

main
A---B---C
         \
          F---G  feature-auth

develop
A---B---C---D---E

After

main
A---B---C

develop
A---B---C---D---E
                 \
                  F'---G'  feature-auth

ポイント

rebaseではコミットがコピーされるため
commit hash は変わる

リモートへ反映

履歴を書き換えているため通常 push は失敗します。

git push origin feature-auth --force-with-lease

--force--force-with-lease

--force

リモート履歴を無条件で上書き

問題

他人のpushを消してしまう可能性

--force-with-lease(推奨)

自分が最後に取得した状態と
リモートが一致している場合のみ上書き

つまり

他の人がpushしていたら失敗する

安全な force push


別の解決方法

① cherry-pick

必要なコミットだけ取り込む。

git checkout develop
git checkout -b feature-auth2
git cherry-pick <commit>

メリット

履歴を書き換えない

デメリット

コミットが多いと面倒

② merge

main の変更も含めて問題ない場合。

git checkout develop
git merge feature-auth

デメリット

不要な履歴も取り込む

方法の使い分け

方法 用途
rebase --onto 派生元の付け替え
cherry-pick 必要なコミットだけ
merge 変更をすべて取り込む

今回のような

派生元を間違えた

ケースでは

rebase --onto

が最もきれいに修正できます。


rebase使用時の注意

rebase

履歴を書き換える操作

注意点

  • 共有ブランチでは慎重に
  • 他の人が pull 済みだと履歴が壊れる

安全なケース

自分だけが触っている作業ブランチ
PR作成前

rebase --onto の覚え方

覚え方はシンプルです。

git rebase --onto 新しい親 古い親 ブランチ

つまり

「古い親から生えたコミットを
 新しい親へ移動する」

と覚えると理解しやすいです。


まとめ

派生元を間違えた場合は

git rebase --onto <正しい親> <誤った親> <ブランチ>

git checkout feature-auth
git rebase --onto develop main feature-auth
git push origin feature-auth --force-with-lease

ポイント

  • rebase --onto親ブランチを付け替え
  • push は --force-with-lease
  • 共有ブランチでは注意
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?