Jay
Jay

Reputation: 329

git can't checkout branch for the first time without the remote name

I have cloned a repo and added my fork as another remote but I cannot check out a branch for the first time (in this case master, which is not their default branch) without specifying which remote.

git clone https://github.com/facebook/zstd.git
cd zstd
git remote add jay https://github.com/jay/zstd.git
git fetch jay
git checkout master

error: pathspec 'master' did not match any file(s) known to git.

If I specify the remote it works:

git checkout -b master origin/master

Branch master set up to track remote branch master from origin.
Switched to a new branch 'master'

I'm curious why I need to specify the remote in this case. I must be remembering this wrong but I'm pretty sure that wasn't always necessary. This is true of any branch that's in both repos, for example, git checkout zstd_help would also fail the first time unless I explicitly specified origin remote.

Git version: git version 2.7.4

Upvotes: 3

Views: 2617

Answers (1)

Mureinik
Mureinik

Reputation: 311438

The key here is the second remote you've added. If you just clone the repo and immediately try to checkout master, it will work:

mureinik@computer ~/src/git
$ git clone https://github.com/facebook/zstd.git
Cloning into 'zstd'...
remote: Enumerating objects: 9, done.
remote: Counting objects: 100% (9/9), done.
remote: Compressing objects: 100% (8/8), done.
remote: Total 43954 (delta 1), reused 0 (delta 0), pack-reused 43945
Receiving objects: 100% (43954/43954), 23.29 MiB | 682.00 KiB/s, done.
Resolving deltas: 100% (32256/32256), done.

mureinik@computer ~/src/git
$ cd zstd

mureinik@computer ~/src/git/zstd (dev)
$ git checkout master
Switched to a new branch 'master'
Branch 'master' set up to track remote branch 'master' from 'origin'.

once you add jay, the remote branch name master becomes ambiguous (it could refer to origin/master or jay/master), and thus when you try to check it out it fails.

I'm not sure when exactly this happened, but newer versions of git (I'm using 2.28) will give a clearer error message in this situation:

# After adding the second "jay" remote

mureinik@computer ~/src/git/zstd (master)
$ git checkout verbose
hint: If you meant to check out a remote tracking branch on, e.g. 'origin',
hint: you can do so by fully qualifying the name with the --track option:
hint:
hint:     git checkout --track origin/<name>
hint:
hint: If you'd like to always have checkouts of an ambiguous <name> prefer
hint: one remote, e.g. the 'origin' remote, consider setting
hint: checkout.defaultRemote=origin in your config.
fatal: 'verbose' matched multiple (2) remote tracking branches

Upvotes: 3

Related Questions