LoginSignup
8
6

More than 5 years have passed since last update.

git で single-branch を使用した後に別ブランチを fetch する方法

Last updated at Posted at 2017-09-26

はじめに

前回投稿した 「容量の大きいリポジトリを必要最低限の情報だけ clone する方法」 という記事の続きです。
前回は容量を抑えるために --single-branch で master ブランチを指定して、よけいなブランチは落としてこないようにしていました。
しかし、今回他のブランチを落として来たくなった時にちょっと困ったので、今回も備忘録を残しておくことにします。

追跡できない理由

通常 clone 時に何も指定していなければ、下記のようにワイルドカードが指定されているため、全てのブランチに対応できます。

[remote "origin"]
    url = https://foobar.com/test.git
    fetch = +refs/heads/*:refs/remotes/origin/*

しかし、single-branch を指定して clone して来た場合は .git/config の中身が変わります。
下記のように fetch の設定値が master 指定になっています。

[remote "origin"]
    url = ssh://foobar.com/test.git
    fetch = +refs/heads/master:refs/remotes/origin/master

そのため、master 以外を指定すると下記のように origin/develop ブランチ(追跡ブランチ)を作成しません。


$ git fetch origin develop
remote: Counting objects: 1, done.
remote: Compressing objects: 100% (1/1), done.
remote: Total 8393 (delta 1), reused 1 (delta 1)
Receiving objects: 100% (1/1), 2.90 MiB | 0 bytes/s, done.
Resolving deltas: 100% (1/1), completed with 1 local objects.
From ssh://foobar.com/test.git
 * branch            develop    -> FETCH_HEAD
# * [new branch]      develop    -> origin/develop ←本来はこのようにorigin/developが作成される

$ git branch -r
origin/master

解決策

.git/config を修正する

解決策として、一番簡単な方法は .git/config を編集することです。
編集方法は 2通りあります。

(1) single-branch はやめてワイルドカードに戻す

手っ取り早く下記のように、通常 clone して来た時と同じ状態に修正してしまう方法があります。

[remote "origin"]
    url = https://foobar.com/test.git
    fetch = +refs/heads/*:refs/remotes/origin/*

(2) fetch 先を追加する

fetch を追加する方法もあります。
余計なブランチはいらないので、自分はこちらの方法で対処しました。

[remote "origin"]
    url = https://foobar.com/test.git
    fetch = +refs/heads/master:refs/remotes/origin/master
    fetch = +refs/heads/develop:refs/remotes/origin/develop

コマンド時に fetch 先まで指定する

リモートブランチの追跡が1回きりでも良い場合は、fetch コマンド時に fetch 先を指定する方法もあります。

$ git fetch origin develop:refs/remotes/origin/develop

最後に

この辺りを詳しく知りたい場合は、 gitドキュメントのRefspec に書かれているので、こちらを参考にしています。

8
6
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
8
6