Home > Back-end >  Why git doesn't clone all branches by default but clones all objects (commits, blobs, trees) th
Why git doesn't clone all branches by default but clones all objects (commits, blobs, trees) th

Time:12-09

By default when I clone git repo: git clone url git clones only the current branch (eg. the one pointed to by HEAD on the remote). But when I look into the .git/objects I see all objects in git database are there.

Why is that? Branches are just 41 bytes long (SHA1 LF), while git objects in .git/objects directory are usually much larger than that? I first thought it was because of optimizing the download size, but now it doesn't make sens because that branch sizes are negligible (even if there are hundreds of them) for mid or larger projects.

CodePudding user response:

Git by default tracks the branches from a remote during a clone or fetch as remote-tracking branches under refs/remotes instead of regular branches under refs/heads. This is because they're useful to have, but I may not want to have 50,000 regular branches in my local copy just because I cloned the repository, especially when you consider tab completion.

Additionally, you might clone or fetch someone's remote, but not care for their personal branches or naming scheme, and this prevents the remote owner from polluting your repository or overwriting your branches.

Assuming your remote is named origin, you can refer to branch foo as origin/foo, and if you run git checkout foo and there is no existing foo branch but there is exactly one remote with a remote-tracking branch with that name, foo will be created from it automatically. This is convenient enough for most people without being overly invasive.

CodePudding user response:

I'm going to go out on a limb here and guess this is a very simple misunderstanding. You ask:

Why git doesn't clone all branches by default

It actually does "copy" all branches by default when you clone. Perhaps after cloning, you are running the command:

git branch

and thinking that is the list of all the branches in the repo? Note git branch only shows your local branches, and after a clone you will only have one local branch which will be the default branch. But you do still have a copy of all the other branches on your machine too. To see all the remote tracking branches in the repo, use the command:

git branch -r

Or to see the combination of all of your local and remote branches, you can use:

git branch -a

All of those remote tracking branches are already sitting on your machine, and once you checkout (or switch) to any of the branches in the repo, you'll have a local copy of those branches too.

  • Related