Skip to main content
 首页 » 编程设计

python之GitPython 如何克隆所有分支

2025年02月15日11haluo1

我找到了这个 Bash脚本,它完成相同的任务,但在 Bash 中。

使用 GitPython 创建存储库的完整备份,似乎无法弄清楚如何在无需手动检查的情况下显示所有分支。

Repo.clone_from(repo, folder) 

我在循环中使用这一行来复制存储库中的所有文件。

请您参考如下方法:

我最近偶然发现了这个线程,但没有找到任何解决方案,所以我自己酿造了。它总比没有好,既不是最优的也不是漂亮的,但至少它有效:

# Clone master 
repo = Repo.clone_from('https://github.com/user/stuff.git', 'work_dir', branch='master') 
 
# Clone the other branches as needed and setup them tracking the remote 
for b in repo.remote().fetch(): 
    repo.git.checkout('-B', b.name.split('/')[1], b.name) 

解释:

  1. 克隆主分支
  2. 获取远程分支名称
  3. 检查分支并根据需要创建它们

PS:我认为 Gitpython 没有内置的方法来使用 clone_from 执行此操作。

更新:

GitPyhton 中的

no_single_branch=True 选项等于 git CLI 中的 --no-single-branch (其他“无值”参数也可以与 True 一起提供 值)

repo = Repo.clone_from('https://github.com/user/stuff.git', 'work_dir', branch='master', no_single_branch=True)