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

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

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

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

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

# 引入第三方库 GitPythonfrom 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()