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


当前回答

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

其他回答

您正在执行的提取应该获取所有远程分支,但不会为它们创建本地分支。如果您使用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分支相同的位置。注意,它会取出所有的树枝,但只会将你所在的树枝拉到树的顶端。

每当我需要推倒所有的树枝时,我都会这样做。来自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 checkout -b recreated-branch-name
git branch -a (to list remote branches)
git rebase remotes/remote-origin/recreated-branch-name

因此,如果我从gituser/master分支到sjp,然后将其分支到sjp/mynewbranch,则如下所示:

$ git checkout -b mynewbranch

$ git branch -a
  master
  remotes/sjp/master
  remotes/sjp/mynewbranch

$ git fetch (habit to always do before)

$ git rebase remotes/sjp/mynewbranch

看着问题的答案之一,我注意到可以缩短它:

for branch in  `git branch -r | grep -v 'HEAD\|master'`; do
    git branch --track ${branch##*/} $branch;
done

但是要注意,如果其中一个远程分支被命名,例如admin_master,它将不会被下载!

除了用户没有人走在正确的轨道上之外,这些答案都无法解决问题。

我在将存储库从一个服务器/系统移动到另一个服务器或系统时遇到了问题。当我克隆存储库时,它只为master创建了一个本地分支,所以当我推送到新的远程时,只推送了master分支。

所以我发现这两种方法非常有用。

方法1:

git clone --mirror OLD_REPO_URL
cd new-cloned-project
mkdir .git
mv * .git
git config --local --bool core.bare false
git reset --hard HEAD
git remote add newrepo NEW_REPO_URL
git push --all newrepo
git push --tags newrepo

方法2:

git config --global alias.clone-branches '! git branch -a | sed -n "/\/HEAD /d; /\/master$/d; /remotes/p;" | xargs -L1 git checkout -t'
git clone OLD_REPO_URL
cd new-cloned-project
git clone-branches
git remote add newrepo NEW_REPO_URL
git push --all newrepo
git push --tags newrepo