かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

Git リモートブランチのチェックアウトがエラーになる時のメモ

PR確認でリモートのブランチにチェックアウトしようとしたらエラーになってチェックアウトできなくなった。

$ git checkout -b feature/foo origin/feature/foo
fatal: 'origin/feature/foo' is not a commit and a branch 'feature/foo' cannot be created from it

fatal: '<リモートブランチ>' is not a commit and a branch '<作成するブランチ>' cannot be created from it

リモートのブランチが表示されない

$ git branch -a
* develop
  remotes/origin/HEAD -> origin/develop
  remotes/origin/feature
  remotes/origin/develop
  remotes/origin/main

fetch するとエラーになっている

$ git fetch
error: cannot lock ref 'refs/remotes/origin/feature/foo': 'refs/remotes/origin/feature' exists; cannot create 'refs/remotes/origin/feature/foo'
 ! [new branch]      feature/foo           -> origin/feature/foo  (unable to update local ref)

remote に feature というブランチが有る事になっているせいで feature/foo のブランチが作れなくなってるっぽい。リモートの feature ブランチは既にマージ済みでブランチも削除しているのだけどローカルからの参照で残っているようになっているのが原因っぽい

git gc と prune でローカルに保存されている履歴をキレイにすれば OK

$ git gc --prune=now
$ git remote prune origin

確認

$ git fetch
 * [new branch]      feature/foo -> origin/feature/foo
$ git branch -a 
* develop
  remotes/origin/HEAD -> origin/develop
  remotes/origin/develop
  remotes/origin/feature/foo
  remotes/origin/main

リモートブランチが意図したとおりに取得できました!

$ git checkout -b feature/foo origin/feature/foo
Branch 'feature/foo' set up to track remote branch 'feature/foo' from 'origin'.
Switched to a new branch 'feature/foo'

解決!


[参考]

ポンポさんの円盤楽しみ〜