LoginSignup
7
6

More than 5 years have passed since last update.

shallow clone したリポジトリのトピックブランチを後から fetch する

Posted at

TL;DR

.git/config
fetch = +refs/heads/cool-topic-branch:refs/remotes/origin/cool-topic-branch

shallow clone

git clone するときに巨大なリポジトリの全ての履歴を取得する必要はない, 最新版だけ取ってきたい, というような場合, --depth オプションを渡すことでそれを実現できます:

$ git clone --depth 1 https://github.com/pione30/example.git

--depth に指定する数字は取得したい最新 commit の数です.
このような clone を "shallow clone" と呼びます.

shallow clone した リポジトリでの fetch

古いバージョンの Git では禁止されていたようですが, Git 1.9.0 からは shallow clone したリポジトリに対する fetch ができるようになりました.
これでこそ通常どおり pull / push による開発ができるというものです.

しかし, 上記のように shallow clone を行った場合, リポジトリにトピックブランチが複数あったとしても, デフォルトではリモートの master ブランチしか追跡されません:

$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

なので, 例えば他の人が作成したトピックブランチを手元で検証したいというような場合, このまま単純に git pull してもそんなブランチは降ってこず, git checkout できなくて戸惑うことになります.

Refspec

このときの .git/config を見ると, 以下のようなセクションがあるはずです:

.git/config
[remote "origin"]
    url = https://github.com/pione30/example.git
    fetch = +refs/heads/master:refs/remotes/origin/master

これはどういう意味でしょうか? 公式ドキュメントを読んでみましょう:

.git/config ファイルにセクションを追加して、リモートの名前(origin)、リモートリポジトリのURL、そしてフェッチする対象のrefspecを指定します。

[remote "origin"]
  url = https://github.com/schacon/simplegit-progit
  fetch = +refs/heads/*:refs/remotes/origin/*

refspecの書式は <src>:<dst> で、その前にオプションとして + を指定できます。ここで <src> はリモート側の参照に対するパターンで、 <dst> はそれらの参照がローカルで書きこまれる場所を示します。 + は、fast-forwardでない場合でも参照を更新するようGitに指示しています。

(中略)

常にリモートサーバー上の master ブランチのみをプルして、それ以外のブランチはどれもプルしたくない場合は、fetchの行を以下のように変更します。

fetch = +refs/heads/master:refs/remotes/origin/master

(中略)

設定ファイルに、フェッチ用のrefspecを複数指定することもできます。 もし、常に master ブランチと experiment ブランチをフェッチしたいならば、以下のように2行追加します。

[remote "origin"]
  url = https://github.com/schacon/simplegit-progit
  fetch = +refs/heads/master:refs/remotes/origin/master
  fetch = +refs/heads/experiment:refs/remotes/origin/experiment

引用元: 10.5 Gitの内側 - Refspec

まさに "master ブランチのみをプルして、それ以外のブランチはどれもプルしたくない" ような状態になっていたのでした.
というわけで, 特定のブランチを pull の対象に含めたいときは

.git/config
fetch = +refs/heads/cool-topic-branch:refs/remotes/origin/cool-topic-branch

のような fetch の行を [remote "origin"] セクションに追加すれば良いことになります.

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