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


当前回答

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

创建一个与要克隆的存储库同名的文件夹,并将其放入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

哇!你有所有的树枝!

其他回答

您只需使用“gitclone”即可获得所有分支。

git clone <your_http_url>

即使您只看到主分支,也可以使用“gitbranch-a”查看所有分支。

git branch -a

你可以切换到你已经拥有的任何分支。

git checkout <your_branch_name>

不要担心,在“gitclone”之后,您不需要连接到远程存储库。当您没有Internet连接时,可以成功运行“git branch-a”和“git checkout<your_branch_name>”。因此,事实证明,当您执行“gitclone”时,它已经从远程存储库复制了所有分支。之后,您就不需要远程存储库了。您的本地已具有所有分支机构的代码。

git克隆应该复制整个存储库。尝试克隆它,然后运行gitbranch-a。它应该列出所有分支。如果您想切换到分支“foo”而不是“master”,请使用git checkout foo。

下面是根据前面的答案改编的跨平台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,它总是让您在尝试时感到困扰。

我无法编辑Bigfish的答案。他提出了一个bash脚本,我提供它来更新并提供更好的git集成。grep已经过时,应该用grep-E替换。

#!/bin/bash
for branch in $(git branch --all | grep '^\s*remotes' | grep -E --invert-match '(:?HEAD|master)$'); do
        git branch --track "${branch##*/}" "$branch"
done

您可以通过将此bash文件添加为git自定义子命令来扩展git:

$ mkdir ~/.gitbin; touch ~/.gitbin/git-fetchThemAll
$ chmod u+x ~/.gitbin/git-fetchThemAll

将bash脚本的内容放在gitfetchThemAll中。

$ echo 'export PATH="$HOME/.gitbin:$PATH"' >> ~/.bashrc
$ source ~/.bashrc # update PATH in your current shell
$ git fetchThemAll

如果您愿意,可以使用用户cfi为这个oneliner使用shell别名

aliasfetchThemAll=gitbranch-a|grep-vHEAD|perl-ne'chomp($_);s |^\*?\s*||;如果(m|(.+)/(.+)|&&not$d{$2}){print qq(git branch--track$2$1/$2\n)}否则{$d{$_}=1}‘|csh-xfs

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

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