python 删除git Jenkinsfile文件

背景:在做ci集成的发现分支超过100个之后,pipline activity列表中前期的分支会被隐藏,这导致master分支在活动视图中不可见

解决方案:删除历史分支的Jenkinsfile

分支太多了,写了个脚本处理,具体如下

from git import Repo
import os
import time

# vi .git/config
# lb = !"for k in `git branch -r|perl -pe s/^..//`;do echo `git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" $k|head -n 1`\	$k;done|sort"

'''通过git for-each-ref --sort=-committerdate命令获得需要删除文件的分支名,按提交时间倒叙''' x = """
origin/test1 origin/test2 origin/test3
"""
# 获得需要删除Jenkinsfile的分支列表 list_branch = [_.split("origin/")[1].strip() for _ in x.split(" ") if _]
# 源代码存放的本地路径 cdir = "/Users/test/Documents/code/test" repo = Repo(cdir) remote = repo.remote() gt = remote.repo.git list_branch_err = [] for branch in list_branch: # 切换分支 gt.checkout(branch) print(repo.active_branch) index = repo.index try:
     # 如果分支上存在Jenkinsfile则删除并提交git if "Jenkinsfile" in os.listdir(cdir): index.remove(['Jenkinsfile']) index.commit('remove Jenkinsfile') remote.push()
     # 本地的源文件可能并没有删除,删除本地Jenkinsfile源文件 if "Jenkinsfile" in os.listdir(cdir): os.remove(cdir+"/Jenkinsfile") except Exception as e: list_branch_err.append(branch) print("failed to remove jenkins file on these branches", list_branch_err)

 

原文地址:https://www.cnblogs.com/smileyes/p/9706896.html