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


当前回答

从本地回购中克隆不能与gitclone和gitfetch一起使用:许多分支/标签将保持不匹配。

获取包含所有分支和标记的克隆。

git clone --mirror git://example.com/myproject myproject-local-bare-repo.git

要获取包含所有分支和标记但也包含工作副本的克隆,请执行以下操作:

git clone --mirror git://example.com/myproject myproject/.git
cd myproject
git config --unset core.bare
git config receive.denyCurrentBranch updateInstead
git checkout master

其他回答

此变体将克隆具有本地可用的所有分支的远程回购,而无需逐个签出每个分支。不需要花哨的脚本。

创建一个与要克隆的存储库同名的文件夹,并将其放入cd中,例如:

mkdir somerepo
cd somerepo

现在执行这些命令,但使用实际的repo用户名/reportname

git clone --bare git@github.com:someuser/somerepo.git .git
git config --bool core.bare false
git reset --hard
git branch

哇!你有所有的树枝!

截至2017年初,该评论中的答案有效:

gitfetch<origin name><branch name>为您关闭分支。虽然这不会同时拉动所有分支,但您可以对每个分支单独执行此操作。

下面是根据前面的答案改编的跨平台PowerShell 7函数。

function Invoke-GitCloneAll($url) {
    $repo = $url.Split('/')[-1].Replace('.git', '')
    $repo_d = Join-Path $pwd $repo
    if (Test-Path $repo_d) {
        Write-Error "fatal: destination path '$repo_d' already exists and is not an empty directory." -ErrorAction Continue
    } else {
        Write-Host "`nCloning all branches of $repo..."
        git -c fetch.prune=false clone $url -q --progress &&
        git -c fetch.prune=false --git-dir="$(Join-Path $repo_d '.git')" --work-tree="$repo_d" pull --all
        Write-Host "" #newline
    }
}

注意:-c fetch.sprune=false使其包含通常会被排除的过时分支。如果你对它不感兴趣,就去掉它。


通过从函数中删除&&,可以在PowerShell 5.1(Windows 10中的默认值)中实现这一点,但这使得它即使在上一个命令失败时也会尝试git pull。因此,我强烈建议您只使用跨平台PowerShell,它总是让您在尝试时感到困扰。

这是一个使用awk的答案。如果在新的回购协议中使用,这种方法就足够了。

git branch -r | awk -F/ '{ system("git checkout " $NF) }'

现有的分支将被简单地签出,或者声明为已经在其中,但是可以添加过滤器以避免冲突。

还可以修改它,以便调用显式git checkout-b<branch>-t<remote>/<branch>命令。

这个答案符合尼科斯·C的想法。


或者,我们可以指定远程分支。这是基于murphytalk的答案。

git branch -r | awk '{ system("git checkout -t " $NF) }'

它会对冲突发出致命的错误消息,但我认为它们是无害的。


这两个命令都可以别名。

使用nobody的答案作为参考,我们可以使用以下命令来创建别名:

git config --global alias.clone-branches '! git branch -r | awk -F/ "{ system(\"git checkout \" \$NF) }"'
git config --global alias.clone-branches '! git branch -r | awk "{ system(\"git checkout -t \" \$NF) }"'

就我个人而言,我会使用跟踪所有分支或跟踪所有分支。

对于使用Visual Studio代码的开发人员来说,一个更好的替代解决方案是使用Git Shadow Extension。

此Visual Studio代码扩展允许克隆存储库内容和目录,这些内容和目录可以通过分支名称或提交哈希进行筛选。这样,分支或提交可以用作新项目的样板/模板。