LoginSignup
3
0

More than 3 years have passed since last update.

リモートブランチをうまくローカルにcheckoutできない?

Last updated at Posted at 2020-11-15

Aさんは、Bさんのpull requestをレビューするために、Bさんがリモートレポジトリにpushしたfeature/Bブランチを自分のローカルに持ってきたい。
けれども、わざわざgit clone -b feature/B git@github.com:project-ab/git-sample.gitでレポジトリ全体をcloneしてくるのは時間がかかるし、避けたい。

リモートブランチをcheckoutしてみる

gitでリモートブランチをローカルにcheckoutするを参考に、Aさんはリモートブランチorigin/feature/Bをcheckoutしてみる1が、うまくいかない。

MINGW64 ~/git-sample (main)
$ git checkout -b feature/B origin/feature/B

fatal: 'origin/feature/B' is not a commit and a branch 'feature/B' cannot be created from it

追跡していないリモートブランチは、まずfetchしてくる必要がある

原因は、リモートブランチorigin/feature/Bをローカルで追跡できていないから。(下図だとリモート追跡ブランチはorigin/mainorigin/feature/Aのみ)

$ git branch -a

  feature/A
* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/feature/A
  remotes/origin/main

fetchしてからcheckoutするとうまくいく。

$ git fetch origin feature/B

remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (2/2), done.
Unpacking objects: 100% (3/3), 245 bytes | 30.00 KiB/s, done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
From github.com:project-ab/git-sample
 * branch            feature/B  -> FETCH_HEAD
 * [new branch]      feature/B  -> origin/feature/B
$ git checkout -b feature/B origin/feature/B

Switched to a new branch 'feature/B'
Branch 'feature/B' set up to track remote branch 'feature/B' from 'origin'.

成功👍

もっと楽な方法

リモートブランチを丸ごとすべて持ってくる。

$ git fetch

From github.com:project-ab/git-sample
 * [new branch]      feature/B  -> origin/feature/B

git checkout -b feature/B origin/feature/Bの代わりにgit checkout feature/Bとするだけで、リモート追跡ブランチからローカルブランチfeature/Bを作成し、そこへcheckoutしてくれる。

$ git checkout feature/B

Switched to a new branch 'feature/B'
Branch 'feature/B' set up to track remote branch 'feature/B' from 'origin'.

参考になる記事


  1. checkoutは主にブランチ間を行き来するコマンドなので、「リモートブランチをcheckoutする」という表現は本来あまりよろしくない。正しくは、「リモートブランチの最新コミットをfetchしてきて、リモート追跡ブランチからローカルブランチを作成し、そこへcheckoutする」と表現すべきでしょうか。しかしAtlassianの記事を見てみると、"checkout the remote branch"という表現があったり、ある程度この言い方は許容されているのかもしれません。 

3
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
3
0