rodarmor rodarmor - 2 months ago 44
Git Question

How to clone a single branch in git?

I have a local git repository called 'skeleton' that I use for storing project skeletons. It has a few branches, for different kinds of projects:

casey@agave [~/Projects/skeleton] git branch
* master
rails
c
c++


If I want to check out the master branch for a new project, I can do

casey@agave [~/Projects] git clone skeleton new
Initialized empty Git repository in /Users/casey/Projects/new/.git/


and everything is how I want it. Specifically, the new master branch points to skeleton master branch, and I can push and pull to move around changes to the basic project setup.

What doesn't work, however, is if I want to clone another branch. I can't get it so that I only pull the branch I want, for instance the rails branch, and then the new repo has a 'master' branch that pushes to and pulls from the skeleton repo's 'rails' branch, by default.

Is there a good way to go about doing this? Or, maybe this isn't the way that git wants me to structure things, and I'm certainly open to that. Perhaps I should have multiple repos, with the rails skeleton repo tracking the master skeleton repo? And any individual project cloning the rails skeleton repo.

Any thoughts and suggestions are appreciated!

Answer

Note: the git1.7.10 (April 2012) actually allows you to clone only one branch:

# clone only the remote primary HEAD (default: origin/master)
git clone --single-branch

as in:
git clone <url> --branch <branch> --single-branch [<folder>]

You can see it in t5500-fetch-pack.sh:

test_expect_success 'single branch clone' '
  git clone --single-branch "file://$(pwd)/." singlebranch
'

Tobu comments that:

This is implicit when doing a shallow clone.
This makes git clone --depth 1 the easiest way to save bandwidth.

And since Git 1.9.0 (February 2014), shallow clones support data transfer (push/pull), so that option is even more useful now.
See more at "Is git clone --depth 1 (shallow clone) more useful than it makes out?".


"Undoing" a shallow clone is detailed at "Convert shallow clone to full clone" (git 1.8.3+)

# unshallow the current branch
git fetch --unshallow

# for getting back all the branches (see Peter Cordes' comment)
git config remote.origin.fetch refs/heads/*:refs/remotes/origin/*
git fetch --unshallow
Comments