【问题标题】:Why can I clone the main repository but not a branch?为什么我可以克隆主存储库而不是分支?
【发布时间】:2024-01-04 05:35:01
【问题描述】:

我在 github 上有一个存储库的分支,我正在尝试克隆。我可以在 url https://github.com/pmyusername/myrepository 克隆主存储库(不是实际链接,因为数据是私有的)。但是,我无法克隆位于 https://github.com/myusername/myrepository/tree/branchname 的分支。要克隆存储库,我只需要运行:

git clone https://github.com/myusername/myrepository

但如果我尝试运行:

https://github.com/myusername/myrepository/tree/branchname

我收到错误:

fatal: repository 'https://github.com/myusername/myrepository/tree/branchname' not found

但我知道它存在,因为我从 url 复制和粘贴它。问题可能与我付费将其保密的事实有关,但我不这么认为。有人有什么想法吗?

【问题讨论】:

  • 既然已经有了整个仓库,为什么还要克隆分支?
  • 分支比存储库更远。存储库已过时。
  • 根据定义,存储库包含所有分支。 master 分支可能已过时,但您仍然可以签出有问题的分支(在 git fetch/pull 之后)。
  • 您需要克隆存储库,然后将本地工作存储库切换到所需的分支。您可以使用 git checkout 命令执行此操作。看看这本书 git-scm.com/book 这是一本关于 git 的整本书,为了您的利益而开源。
  • 在“git clone”拉下存储库后,运行“git fetch”,以便存储库的本地副本知道所有远程分支。然后,您可以运行 'git checkout -b branchname'(您可以输入 origin/branchname)来设置本地工作分支以跟踪远程分支。

标签: git git-branch git-clone


【解决方案1】:

我将尝试将所有 cmets 汇总成一个简洁的响应...
第 1 步:git clone https://github.com/myusername/myrepository
第 2 步:git fetch
第 3 步:git checkout -b desired_branch # 将 origin/desired_branch 添加到命令行末尾以设置远程跟踪

更新:
刚刚对 daniellarsson 的建议做了一个快速实验,它似乎有效:
i:work> git clone -b metro git@github.com:user/project.git
i:work> cd project
I:\work\project> git branch -a
* metro
remotes/origin/HEAD -> origin/master
remotes/origin/master
remotes/origin/metro

【讨论】:

    【解决方案2】:

    如果您使用像 GitEx 这样的 UI,您可以在出现的对话框中提及您要克隆的分支。这将克隆 repo 并自动签出分支。

    【讨论】: