关于git:一个批量清除Git分支的脚本

8次阅读

共计 1220 个字符,预计需要花费 4 分钟才能阅读完成。

每开发一个新性能,往往都会新建一个性能分支。

长此以往,我的项目的本地代码仓库上,就会累积较多的过期分支。

若要逐个手动清理这些过期分支,想想都感觉累。为了更高效的摸鱼,写了一个 python 脚本,用于批量清理过期分支。

假如 D:\rui\work\ 门路下,存在 repo-a 这一本地代码仓库。在 repo-a 上,存在着 masterfeature-afeature-b 等三个分支。当初,想要移除feature-b,可执行如下代码。

值得一提的是,若 feature-b 存在未 push 到远端仓库的 commit,则feature-b 不会被移除。若需强制移除,能够独自执行命令git branch -D feature-b

# 引入第三方库 GitPython
from git import Repo, GitCommandError

# 仓库名称
REPO_NAME = 'repo-a'

# 须要保留的分支,默认保留 mater 分支
# 留神:没有 push 新 commit 到远端仓库的分支,即便不在该汇合里,也不会被删除
REMAIN_BRANCH_TUPLE = ['feature-a']

# 工作门路
WORK_PATH = r'D:\rui\work\\'


def main():
    print('开始啦 0v0\n')

    # 创立版本库对象
    repo_path = WORK_PATH + REPO_NAME
    repo = Repo(repo_path)

    # 若以后分支存在未提交的批改,则停止操作
    if repo.is_dirty():
        print('请先提交以后分支的批改!!!')
        exit()

    # 切换到 master
    repo.heads.master.checkout()

    not_push_branch_list = []
    for head in repo.heads:
        # 分支名不在保留汇合中,则删除
        head_name = head.name
        if head_name == 'master' or head_name in REMAIN_BRANCH_TUPLE:
            continue

        try:
            # 移除分支
            # 实质上是执行命令 git branch -d feature-name
            repo.delete_head(head_name)
        except GitCommandError:
            # 未 push 新 commit 的分支,执行删除操作,将会抛出 GitCommandError 异样
            # 当然,如果呈现其余谬误,也可能会抛出 GitCommandError 异样。此处,只是简略解决
            not_push_branch_list.append(head_name)

    if not_push_branch_list:
        not_push_branch_str = ','.join(not_push_branch_list)
        print('没有 push 新 commit 的分支: {0}\n'.format(not_push_branch_str))

    print('完结啦 ^0^')


if __name__ == '__main__':
    main()

正文完
 0