我的主分支和开发分支在GitHub上被远程跟踪。如何克隆这两个分支?


当前回答

我编写了这些小PowerShell函数,以便能够签出我的所有Git分支,这些分支位于源远程。

Function git-GetAllRemoteBranches {
     iex "git branch -r"                       <# get all remote branches #> `
     | % { $_ -Match "origin\/(?'name'\S+)" }  <# select only names of the branches #> `
     | % { Out-Null; $matches['name'] }        <# write does names #>
}


Function git-CheckoutAllBranches {
    git-GetAllRemoteBranches `
        | % { iex "git checkout $_" }          <# execute ' git checkout <branch>' #>
}

更多的Git函数可以在我的Git设置库中找到。

其他回答

只需执行以下操作:

$ git clone git://example.com/myproject

$ cd myproject

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

$ git pull
Already up-to-date.

$ git branch
* branchxyz
  master

$ git branch -a
* branchxyz
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/branchxyz
  remotes/origin/branch123

你看,gitclonegit://example.com/myprojectt获取所有内容,甚至是分支,您只需签出它们,就可以创建本地分支。

每当我需要推倒所有的树枝时,我都会这样做。来自Linkedin Learning的Ray Villalobos。尝试克隆所有分支,包括提交:

mkdir -p -- newproject_folder
cd newproject_folder
git clone --mirror https://github.com/USER_NAME/RepositoryName.git .git
git config --bool core.bare false
git reset --hard

这个解决方案使我能够将一个存储库“复制”到另一个:

git merge path/to/source.git --mirror
cd source.git
git remote remove origin
git remote add origin path/to/target.git
git push origin --all
git push origin --tags

在目标存储库中,我可以看到与原始存储库相同的分支和标记。

Git通常(如果未指定)从一个或多个其他存储库中获取所有分支和/或标记(refs,请参见:Git-ls-refs)以及完成其历史所需的对象。换句话说,它获取已经下载的对象可以访问的对象。看:git fetch真正做什么?

有时,您可能有一些分支/标记没有直接连接到当前的分支/标记,因此git pull-all/git fetch-all在这种情况下不会有帮助,但您可以通过以下方式列出它们:

git ls-remote -h -t origin

并通过知道引用名称手动获取它们。

因此,要获取所有信息,请尝试:

git fetch origin --depth=10000 $(git ls-remote -h -t origin)

如果您对存储库进行了浅处理,--depth=10000参数可能会有所帮助。

然后再次检查所有分支:

git branch -avv

如果上述方法无效,则需要手动将丢失的分支添加到跟踪列表中(因为它们不知何故丢失了):

$ git remote -v show origin

...
  Remote branches:
    master      tracked

通过git远程设置分支,如:

git remote set-branches --add origin missing_branch

因此在获取后,它可能出现在remotes/origin下:

$ git remote -v show origin

...
  Remote branches:
    missing_branch new (next fetch will store in remotes/origin)
$ git fetch
From github.com:Foo/Bar
 * [new branch]      missing_branch -> origin/missing_branch

故障排除

如果您仍然无法获得主分支以外的任何内容,请检查以下内容:

仔细检查遥控器(gitremote-v),例如。验证git-config-branch.master.remote是源代码。通过:git remote show origin检查origin是否指向正确的URL(参见本文)。

您正在执行的提取应该获取所有远程分支,但不会为它们创建本地分支。如果您使用gitk,您应该看到远程分支被描述为“remotes/origin/dev”或类似的名称。

要基于远程分支创建本地分支,请执行以下操作:

git checkout -b dev refs/remotes/origin/dev

应该返回如下内容:

Branch dev set up to track remote branch refs/remotes/origin/dev. Switched to a new branch "dev"

现在,当您在dev分支上时,“git pull”会将本地dev更新到与远程dev分支相同的位置。注意,它会取出所有的树枝,但只会将你所在的树枝拉到树的顶端。