tags:

views:

175

answers:

2

I want to track a remote master branch from a new remote repository. Both do already exist.

How do I go about this in git? I can't seem to get it right. I tried:

git remote add otherRepo git://...
git branch -t myTrack otherRepo/master

However, I get the following error:

fatal: Not a valid object name: 'otherRepo/master'.

A: 

You could try

git checkout -b myTrack otherRepo/master 

This will create a new branch myTrack, which tracks the otherRepo/master branch.

Rouan van Dalen
Does not work, the error given is:fatal: git checkout: updating paths is incompatible with switching branches.Did you intend to checkout 'otherRepo/master' which can not be resolved as commit?`
Johannes Rudolph
+3  A: 

As covered in the comments: git remote add otherRepo … only configures the remote, it does not fetch anything from it. You will need to run git fetch otherRepo to fetch the branches of the remote repository before you can create local branches based on them.


(responding to further comment by OP)

If you only want to keep track of a single branch from the remote repository, you can reconfigure your remote's fetch property (remote.otherRepo.fetch).

# done as a shell function to avoid repeating the repository and branch names
configure-single-branch-fetch() {
    git config remote."$1".fetch +refs/heads/"$2":refs/remotes/"${1}/${2}"
}
configure-single-branch-fetch "$remoteName" "$branch"
# i.e. # configure-single-branch-fetch otherRepo master

After this, git fetch otherRepo will only fetch the remote repository's master branch into the otherRepo/master ‘remote tracking branch’ in your local repository.

To cleanup the other ‘remote tracking branches’, you could delete them all and re-fetch just the one you want, or you could selectively delete all of them except just the one you want:

git for-each-ref --shell --format='git branch -dr %(refname:short)' refs/remotes/otherRepo | sh -nv
# remove the -nv if the commands look OK, then
git fetch otherRepo

# OR

git for-each-ref --shell --format='test %(refname:short) != otherRepo/master && git branch -dr %(refname:short)' refs/remotes/otherRepo | sh -nv
# remove the -nv if the commands look OK

If you decide that you want to track more than one remote branch, but not all of them, you can have multiple fetch configurations (with git config --add remote."$remoteName".fetch … or by using git config --edit to directly duplicate and edit the line in your repository's config file).

If you also want to avoid fetching tags from the remote, configure your remote's tagopt property (remote.otherRepo.tagopt).

git config remote."$remoteName".tagopt --no-tags
# i.e. # git config remote.otherRepo.tagopt --no-tags
Chris Johnsen
thanks for this very complete answer. Seems awful such an easy operation is made so complex. Whatever
Johannes Rudolph