首页 > 解决方案 > How is a local tracking branch created for a remote tracking branch?

问题描述

remotes/origin/feature1 is a remote tracking branch without a local tracking branch:

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

When I check out a nonexistent branch feature1, why is a local tracking branch automatically created for the remote tracking branch remotes/origin/feature1? Is the correspondence between the remote tracking branch and the newly created local tracking branch configured or configurable and how?

When and how is a local tracking branch created for a remote tracking branch in general?

Is checking out a nonexistent branch with a name the same as the basename of a remote tracking branch the only way to create a local tracking branch for the remote tracking branch?

$ git checkout feature1
Branch 'feature1' set up to track remote branch 'feature1' from 'myremote'.
Switched to a new branch 'feature1'

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

标签: git

解决方案


There's an explicit passage about this built-in mechanism in the doc (in git checkout page) :

If no -b option is given, the name of the new branch will be derived from the remote-tracking branch, by looking at the local part of the refspec configured for the corresponding remote, and then stripping the initial part up to the "*". This would tell us to use "hack" as the local branch when branching off of "origin/hack" (or "remotes/origin/hack", or even "refs/remotes/origin/hack"). If the given name has no slash, or the above guessing results in an empty name, the guessing is aborted. You can explicitly give a name with -b in such a case.

Also, it's really convenient, and you're always free to use -b when you need it, as pointed out by jonrsharpe in his comment.

Finally, to answer your comment about configuration, this other passage in git branch page :

When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote and branch.<name>.merge configuration entries) so that git pull will appropriately merge from the remote-tracking branch. This behavior may be changed via the global branch.autoSetupMerge configuration flag. That setting can be overridden by using the --track and --no-track options, and changed later using git branch --set-upstream-to.


推荐阅读