1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
|
__Author__ = 'lipenghui' __Date__ = '2021-12-30'
from datetime import datetime from datetime import timedelta from itertools import count import os import sys import time
reload(sys) sys.setdefaultencoding('utf8')
import gitlab import json import requests import re
class PingCode(): def __init__(self,url): self.STATE_TYPE_ING =0 self.STATE_TYPE_DONE =1 self.STATE_TYPE_CHECK =2
self.STATE_OPEN="61737417429e0dc6408d3211" self.STATE_NEW="61737417429e0dab368d320a" self.STATE_PENDING="6177cbd05108bc6c9ed202a3"
self.STATE_BUG_INPROGRESS="61737417429e0d5e638d320b" self.STATE_BUG_FIXED="61737417429e0d71ba8d320c"
self.STATE_TASK_INPROGRESS="61737417429e0d6b098d3212" self.STATE_INSCEPTION="6182336daffb9b86101e85ff" self.STATE_DONE="61737417429e0ddafb8d3213"
self.headers={'Content-Type':'application/Json'} self.url=url
self.openApi="https://open.pingcode.com" self.client_id="" self.client_secret="" self.token="{鉴权Token}" with open("pingcode.json",mode='r') as f: self.users=json.load(f) def getToken(self,userName=""): if False: body={ "grant_type":"client_credentials", "client_id":"gFsPGXQoxElx", "client_secret":"oDowultNitJJejutdLrqhRAc" } www=requests.get(self.openApi+"/v1/auth/token",headers=self.headers,params=body) response=json.loads(www.text) self.token=response["access_token"] if self.users.has_key(userName): return self.users[userName]["access_token"] else: return self.token def push(self,content,commit,item): response=self.Send(json.dumps(content)) response=json.loads(response.text) if response.has_key("code"): code=int(response["code"]) if code==200 and item != None: workTimes=gitOperation.Get_workTimes(commit.title+commit.message) if len(workTimes)>0: pingcode.registerManHours(commit.author_name,item["id"],workTimes[0].replace("$",""),commit.title) def merge(self,content,item,stateType,target): response=self.Send(json.dumps(content)) response=json.loads(response.text) if target=="develop" and response.has_key("code"): code=int(response["code"]) if code==200: pingcode.updateWorkItem(item["id"],item,stateType) def Send(self,gitData): response=requests.post(url=self.url,headers=self.headers,data=gitData) print(response.text) return response def getWorkItem(self,identifier): url=self.openApi+"/v1/agile/work_items" body={ "identifier":identifier, "access_token":self.token } www=requests.get(url,headers=self.headers,params=body) response=json.loads(www.text) if response : if response.has_key("values"): return response["values"][0] else: print(response["message"]) return None def updateWorkItem(self,id,item,stateType): itemState=item["state"]["id"] createById=item["created_by"]["id"] createByName=item["created_by"]["display_name"] if item["type"]=="bug": self.updateBug(id,item,stateType) elif item["type"]=="task": self.updateTask(id,item,stateType)
content="" if stateType==self.STATE_TYPE_DONE: pass elif stateType==self.STATE_TYPE_CHECK: content="[@"+createById+"|"+createByName+"] 已合并,请及时验收" if content!="": self.commentWorkItem(id,content) def updateBug(self,id,item,stateType): url=self.openApi+"/v1/agile/bugs/"+id state_id=self.STATE_BUG_INPROGRESS if stateType==self.STATE_TYPE_ING: state_id=self.STATE_BUG_INPROGRESS elif stateType==self.STATE_TYPE_DONE: state_id=self.STATE_BUG_FIXED elif stateType==self.STATE_TYPE_CHECK: state_id=self.STATE_INSCEPTION param={ "access_token":self.token } body={ "state_id":state_id } www=requests.patch(url,headers=self.headers,params=param,data=json.dumps(body)) def updateTask(self,id,item,stateType): url=self.openApi+"/v1/agile/tasks/"+id state_id=self.STATE_BUG_INPROGRESS if stateType==self.STATE_TYPE_ING: state_id=self.STATE_TASK_INPROGRESS elif stateType==self.STATE_TYPE_DONE: state_id=self.STATE_DONE elif stateType==self.STATE_TYPE_CHECK: state_id=self.STATE_INSCEPTION param={ "access_token":self.token } body={ "state_id":state_id } www=requests.patch(url,headers=self.headers,params=param, data=json.dumps(body)) def commentWorkItem(self,identerfi,content): url=self.openApi+"/v1/agile/work_items/"+identerfi+"/comments" body={ "content":content, "access_token":self.token } www=requests.post(url, headers=self.headers,data=json.dumps(body)) print("commentWorkItem:"+www.text) def registerManHours(self,userName,workItem,manHours,desp): """ 登记工时 """ userToken=self.getToken(userName) print(userName+" cost :"+" "+manHours +" hours on work item:"+workItem) url=self.openApi+"/v1/agile/workloads" manHours=float(manHours) param={ "access_token":userToken } body={ "work_item_id":workItem, "workload_type_id":"5cb7e7fffda1ce4ca0050002", "duration":manHours, "report_at":int(time.time()), "description":desp } www=requests.post(url,headers=self.headers,params=param, data=json.dumps(body)) class GitOperation(): def __init__(self,project): self.project={ "id": project.id, "name": project.name, "description": project.description, "web_url": project.web_url, "avatar_url": "", "git_ssh_url": project.web_url, "git_http_url": project.web_url, "namespace": project.namespace, "visibility_level": 0, "path_with_namespace": project.path_with_namespace, "default_branch": project.default_branch, "ci_config_path": "", "homepage": project.web_url, "url": project.web_url, "ssh_url": project.web_url, "http_url": project.web_url } self.repository= { "name": "rome", "url": project.web_url, "description": project.description, "homepage": project.web_url, "git_http_url": project.http_url_to_repo, "git_ssh_url": project.web_url, "visibility_level": 0 } def Get_workTimes(self,content): """ 获取提交说明中的工时信息 每次提交的工时记录需要低于10小时 """ pattern=re.compile(r'\$\d{,2}[\.\d{,1}]{,2}') workItems=pattern.findall(content) return workItems def Get_WorkItems(self,content): """ 获取提交说明中的任务编号""" pattern=re.compile(r'D-\d{,6}') workItems=pattern.findall(content) return workItems def Get_Git_Commit_Dict(self,commit): return { "id": commit.id, "parent":commit.parent_ids, "message": commit.message, "title": commit.title, "timestamp": commit.committed_date, "url": self.project["web_url"]+"/commit/"+commit.id, "author": { "name": commit.author_name, "email": commit.author_email }, "added": [], "modified": [], "removed": [] } def Get_Event_Merge(self,merge): """ 构建Merge_request的webhook格式请求json """ request={ "object_kind": "merge_request", "event_type": "merge_request", "user": { "id": merge.author["id"], "name": merge.author["name"], "username": merge.author["username"], "avatar_url": merge.author["avatar_url"], "email": "[REDACTED]" }, "project":self.project, "object_attributes": { "assignee_id": merge.assignee, "author_id": merge.author["id"], "created_at": merge.created_at, "description": merge.description, "head_pipeline_id": None, "id": merge.id, "iid": merge.iid, "last_edited_at": None, "last_edited_by_id": None, "merge_commit_sha": merge.merge_commit_sha, "merge_error": None, "merge_params": { "force_remove_source_branch": merge.force_remove_source_branch }, "merge_status": merge.merge_status, "merge_user_id":None, "merge_when_pipeline_succeeds": merge.merge_when_pipeline_succeeds, "milestone_id": None, "source_branch": merge.source_branch, "source_project_id": merge.source_project_id, "state_id": 1, "target_branch": merge.target_branch, "target_project_id": merge.target_project_id, "time_estimate": 0, "title": merge.title, "updated_at": merge.updated_at, "updated_by_id": None, "url": merge.web_url, "source": self.project, "target": self.project, "work_in_progress": merge.work_in_progress, "total_time_spent": 0, "time_change": 0, "human_total_time_spent": None, "human_time_change": None, "human_time_estimate": None, "assignee_ids": [], "state": merge.state, "action": "open" }, "labels": [ ], "changes": { "merge_status": { "previous": "unchecked", "current": merge.merge_status } }, "repository": self.repository } if merge.state=="opened": pass elif merge.state=="closed": pass elif merge.state=="merged": request["object_attributes"]["merge_user_id"]= merge.merged_by["id"] return request def Get_Event_Push(self,branchName,commit): """ 构建push的webhook格式请求json """ branchName=branchName.replace("优化","youhua") gitCommit=self.Get_Git_Commit_Dict(commit) commits=[] commits.append(gitCommit) return { "object_kind": "push", "event_name":"push", "before": commit.parent_ids[0], "after": commit.id, "ref": "refs/heads/"+branchName, "checkout_sha": commit.id,
"user_id": 35, "user_name": commit.author_name, "user_username": commit.author_name, "user_email": commit.author_email, "user_avatar": "https://www.gravatar.com/avatar/e96f394d1e9a973845ee60a6a73535de?s=80&d=identicon", "project": self.project, "repository": self.repository, "commits": commits, "total_commits_count": 1, "push_options": {} } class GitlabAPI(): def __init__(self, *args, **kwargs): if os.path.exists("python-gitlab.cfg"): self.gl = gitlab.Gitlab.from_config('lipenghui', ['python-gitlab.cfg']) else: print('You need to make sure there is a file named "/python-gitlab.cfg" or "~/.python-gitlab.cfg"') sys.exit(5) if __name__ == '__main__':
api="https://apps.pingcode.com/gitlab/api/webhooks/{PingCode侧GitLab的ClientId}" pingcode=PingCode(api)
gitApi = GitlabAPI() project = gitApi.gl.projects.get(1) gitOperation=GitOperation(project) tmpNow=datetime.now() if True: now=tmpNow+timedelta(hours=-8,minutes=-2) last=now.strftime('%Y-%m-%dT%H:%M') if True: branches=project.branches.list(per_page=100) print("["+last+"]=> ready to sync commits into pingcode...") for branch in branches: commits=project.commits.list(ref_name=branch.name,since=last) for commit in commits: identifiers=gitOperation.Get_WorkItems(commit.title) item=None for identifier in identifiers: item=pingcode.getWorkItem(identifier) print("identifier:"+identifier) if item and item.has_key("parent") and item["parent"]: commit.message=commit.message+" #"+item["parent"]["identifier"] pingcode.updateWorkItem(item["id"],item,pingcode.STATE_TYPE_ING) content=gitOperation.Get_Event_Push(branch.name,commit) pingcode.push(content,commit,item) if True : now=tmpNow+timedelta(hours=-8,minutes=-8) last=now.strftime('%Y-%m-%dT%H:%M') print("["+last+"]=> ready to sync merges into pingcode...") merges= gitApi.gl.mergerequests.list(scope="all",updated_after=last) for merge in merges: mrg=project.mergerequests.get(merge.iid) commits=mrg.commits() if len(commits)>1: for commit in commits: isPingcodeWorkItem=gitOperation.Get_WorkItems(commit.title) if len(isPingcodeWorkItem)>0: itemId=isPingcodeWorkItem[0] if merge.title.find(itemId)<0: merge.title+=" "+itemId merge.description+=" "+itemId stateType=pingcode.STATE_TYPE_ING if mrg.state=="merged": stateType=pingcode.STATE_TYPE_CHECK elif mrg.state=="closed": stateType=pingcode.STATE_TYPE_ING elif mrg.state=="opened": stateType=pingcode.STATE_TYPE_DONE identifiers=gitOperation.Get_WorkItems(merge.title) for identifier in identifiers: item=pingcode.getWorkItem(identifier) Content=gitOperation.Get_Event_Merge(merge) pingcode.merge(Content,item,stateType,merge.target_branch)
|