使用GitPython如何删除远程分支(推送 origin ':')?

4

我找不到一种与以下命令等效的方法:

git push origin :branchName

这是一个删除远程分支的命令,能否使用gitpython执行此操作?

谢谢

3个回答

6
我自己找到了解决方案,大概是这样的:
# repo is a local repository previously checked-out
remote = repo.remote(name='origin')
remote.push(refspec=(':delete_me'))

我想它会在远程端删除远程仓库,但如果我想在本地删除远程仓库呢?就像 git remote remove origin 这样。更进一步,我想要使用 set-url 来改变远程仓库的地址。gitypthon 能做到这个吗? - undefined
@Timo 删除本地远程使用 repo.delete_remote("origin") - undefined
repo.remote().push() - undefined

5

我也曾遇到这个问题,所以现在在这里进行发布以供日后参考。我遗漏的一点是需要首先克隆下我的代码库。

import os, shutil
from git import *

def clone_repo (remote_url, local_path, branch):                               # Clone a remote repo
    print("Cloning repo %s" % remote_url)
    if os.path.isdir(local_path) is True:
        shutil.rmtree(local_path)
    Repo.clone_from(remote_url, local_path, branch=branch)

def delete_remote_branches(remote_url, branches):
    cur_dir = os.path.dirname(__file__)
    local_path="%s/%s" % (cur_dir,repo)

    clone_repo(
        remote_url=remote_url,                  # The clone url                                                           
        local_path=local_path,                  # Dir path where you want to clone to
        branch="master"                         # Branch to clone (Note: Cannot be on the same branch you want to delete)
    )
    repo = git.Repo(local_path)                 # Repo object set to cloned repo
    assert not repo.bare                        # Make sure repo isn't empty
    remote = repo.remote()                      # Set to a remote object (Defaults to 'origin') can override with name=...
    for repo_branch in repo.references:         # loop over the remote branches
        for branch in branches:                 
            if branch in repo_branch.name:      # does the branch you want to delete exist in the remote git repo? 
                print("deleting remote branch: %s" % repo_branch.remote_head)
                remote.push(refspec=(":%s" % repo_branch.remote_head)) # remote_head = the branch you want to delete Example: "origin/my-branch"

# Note: Could add some logic to delete your local cloned repo when you're done

感谢这个答案,再加上一点。分支应该是这样的 ['origin/test', 'origin/xxx']。必须包含 origin 才能被识别为远程分支。 - undefined

1
import git
git.Git(local_path).clone(remote_path)
repo = git.Repo(local_path)
remote = repo.remote(name='origin')
branch_attribute = repo.remotes.origin.fetch()
for branch in branch_attribute:
    rm_prefix_origin = branch.name.split('/')
    rm_prefix_origin .remove('origin')
    branch_name = '/'.join(rm_prefix_origin )    
    remote.push(refspec=(':' + branch_name​))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接