1.需求:大批量的應用上線后合並到Master,其他的分支develop/test/uat等需要同步最新代碼的操作。
2.操作:可以通過傳參 ,列表 的方式把每個項目的id值填入,才能對相關項目進行批量操作。
3.代碼:
1 # -*- coding: utf-8 -*- 2 __Author__ = "jmmei" 3 __Date__ = '2019/9/22' 4 5 """ 6 刪除wjj_test develop 后,從master分支再創建的需求 7 pip3 install python-gitlab 8 """ 9 import gitlab 10 import os 11 import sys 12 13 class GitlabAPI(): 14 def __init__(self,url,token,projectid): 15 self.gl = gitlab.Gitlab(url,token) 16 self.project=self.gl.projects.get(projectid) 17 18 def get_all_projects(self): 19 result_list= self.gl.projects.list(all=True,as_list=False) 20 21 return result_list 22 23 def get_all_branches(self): 24 #branches = self.project.branches.list() #默認是第一頁的分支列表 25 branches = self.project.branches.list(all=True) 26 branches_list=[] 27 for i in branches: 28 branches_list.append(i.name) 29 30 return branches_list 31 32 33 def del_branches(self,branch): 34 self.project.branches.delete(branch) 35 36 37 38 39 def create_branches(self,branch): 40 branch_obj = self.project.branches.create({'branch': branch,'ref': 'master'}) 41 42 # 分支保護取消 43 #branch1.protect() 44 branch_obj.unprotect() 45 46 47 48 49 if __name__ == '__main__': 50 url = 'http://www.baidu.com" 51 token = = 'xxxxxxxx' 52 last_list=["develop","wjj_test","wjj_uat","wjj_uat_match"] 53 54 #通過輸入參數獲取第一個參數,僅限Linux環境中使用 55 #proid = sys.argv[1] 56 #通過列表,windows環境批處理 57 proid_list=["188","265"] 58 sum=0 59 60 for proid in proid_list: 61 py_git=GitlabAPI(url,token,proid) 62 return_list=py_git.get_all_branches() 63 for branch in last_list: 64 if branch not in return_list: 65 py_git.create_branches(branch) 66 print("創建%s分支成功."%branch) 67 else: 68 py_git.del_branches(branch) 69 py_git.create_branches(branch) 70 print("創建%s分支成功."%branch) 71 sum+=1 72 print("projectid:%s從Master拉取創建成功,第%s次------->>>>>>>>"%(proid,sum)) 73 74 ''' 75 all_projects=py_git.get_all_projects() 76 print(獲取所有項目的name 和id) 77 for p in all_projects: 78 print(p.name, p.id) 79 ''' 80 81 #py_git=GitlabAPI(url,token,x) 82 #判斷last_list是否在return_list中,刪除和創建分支
注意:另外還有python操作gitlab aip的其他操作,請參考官方文檔。