一个批量清除Git分支的脚本

每开发一个新功能,每每都会新建一个功能分支。python

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

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

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

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

# 引入第三方库 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()
相关文章
相关标签/搜索