-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgira.py
executable file
·1173 lines (1006 loc) · 35.5 KB
/
gira.py
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import giturlparse
import os
import sys
import platform
import json
import re
import urllib
import click
import subprocess
import requests
import toml
from retrying import retry
from git import Repo
from git.exc import GitCommandError
import git
from jira import JIRA
_conf = None
_version = "2020-11-10"
def _open_url(url):
cmd = ""
s = platform.system()
if s == "Darwin":
cmd = "open"
elif s == "Windows":
cmd = "start"
elif s == "Linux":
cmd = "xdg-open"
else:
print("Warning: f{s} is not supported yet.")
subprocess.run([cmd, url])
class GiteeError(Exception):
pass
class Gitee():
api_root = "https://gitee.com/api/v5/repos/{}/{}"
web_root = "https://www.gitee.com/"
allowed_permissions = ("push", "pull", "admin")
def __init__(self, user, token):
self.user = user
self.token = token
# git rev-parse --show-toplevel
# git command is not available before Repo()
search = [".", "..", "../..", "../../..", "../../../..", "/you-will-never-find-me///"]
for s in search:
try:
self.git = Git(os.path.abspath(s))
self.owner, self.repo = self.git.info()
break
except git.exc.NoSuchPathError:
raise GiteeError("You should run this from within a git repo")
except git.exc.InvalidGitRepositoryError:
pass # continue
self._root = Gitee.api_root.format(self.owner, self.repo)
def _url(self, urls, params):
if params is not None: # this is for GET
params["access_token"] = self.token
return (
os.path.join(self._root, *urls) + "?" + urllib.parse.urlencode(params)
)
else: # for PUT and POST, FIXME: this is very confusing
return os.path.join(self._root, *urls)
def _good_perm(self, perm):
return perm in Gitee.allowed_permissions
def get(self, url, params):
return requests.get(self._url(url, params))
def put(self, url, _data):
d = {"access_token": self.token, "owner": self.owner, "repo": self.repo}
d.update(_data)
return requests.put(url, data=d)
def patch(self, url, _data):
d = {"access_token": self.token, "owner": self.owner, "repo": self.repo}
d.update(_data)
return requests.patch(url, data=d)
def post(self, url, _data):
d = {"access_token": self.token, "owner": self.owner, "repo": self.repo}
d.update(_data)
return requests.post(url, data=d)
def delete(self, url):
return requests.delete(url)
def get_pr(self, pr):
res = self.get(("pulls", pr), {})
if not res.status_code == 200:
raise GiteeError("RES %d" % res.status_code)
return res.text
def close_pr(self, pr):
res = self.patch(self._url(("pulls", pr), None), {"state": "closed"})
if not res.status_code == 200:
raise GiteeError(res.text)
def create_pr(self, title, head, body, base="master", reviewer="", tester=""):
res = self.post(self._url(("pulls", ""), None), {
"title": title,
"head": head,
"base": base,
"body": body,
"assignee": reviewer,
"tester": tester,
})
if not res.status_code == 201:
raise GiteeError(res)
return res
def get_branch(self, br):
res = self.get(("branches", br), {})
if not res.status_code == 200:
raise GiteeError(res.text)
return res
def merge(self, pr):
res = self.put(self._url(("pulls", pr, "merge"), None), {"number": pr})
if not res.status_code == 200:
raise GiteeError(res.text)
def lock_branch(self, branch):
res = self.put(
self._url(("branches", branch, "protection"), None), {"branch": branch}
)
if not res.status_code == 200:
raise GiteeError(res.text)
def list_branch(self):
res = self.get(("branches",), {})
if not res.status_code == 200:
raise GiteeError(res.text)
return res
def list_member(self):
res = self.get(("collaborators",), {})
if not res.status_code == 200:
raise GiteeError(res.text)
return res
def list_prs(self):
res = self.get(("pulls",), {})
if not res.status_code == 200:
raise GiteeError(res.text)
return res
def add_user(self, username, permission="push"):
if not self._good_perm(permission):
raise ValueError("invalid permission: {permission}")
res = self.put(
self._url(("collaborators", username), None), {"permission": permission}
)
if not res.status_code == 200:
raise GiteeError(res.text)
def del_user(self, username):
res = self.delete(self._url(("collaborators", username), {}))
if not res.status_code == 200:
raise GiteeError(res.text)
def print_user(self, u):
adm = "\tadmin" if u["permissions"]["admin"] else ""
print(f"{u['name']} ({u['login']}){adm}")
def set_reviewer(self, assignees, testers, no_assignees=1, no_testers=1):
res = self.put(
self._url(("reviwer", ""), None),
{
"assignees": assignees,
"testers": testers,
"assignees_number": no_assignees,
"testers_number": no_testers,
}
)
if not res.status_code == 200:
raise GiteeError(res.text)
pass
def print_branch(self, br):
prot = ", protected" if br["protected"] else ""
print(f"{br['name']}{prot}")
def print_prs(self, pr):
print(f"{pr['number']}: {pr['title']}")
def goto_web(self):
url = os.path.join(Gitee.web_root, self.owner, self.repo)
_open_url(url)
def goto_pull(self, id=None):
if id is None:
url = os.path.join(Gitee.web_root, self.owner, self.repo, "pulls")
else:
url = os.path.join(Gitee.web_root, self.owner, self.repo, "pulls", id)
_open_url(url)
class PR():
def __init__(self, jsn):
self.raw = jsn
# TODO: handle exceptions
self.data = json.loads(jsn)
def good(self):
try:
_ = self.issue_id # make sure it's valid
except ValueError:
return False
return len(self.data["assignees"]) >= 1 and len(self.data["testers"]) >= 1
def merged(self):
return self.data["state"] == "merged"
def dump(self):
print(self.raw)
def _get_jira_issue_id(self):
pat = re.compile("^\s*([A-Z]*-\d*)\s+")
mo = re.match(pat, self.title)
if not mo:
raise ValueError(f"Invalid PR title: {self.title}")
return mo.group(1)
def __getattr__(self, att):
if att == "issue_id":
return self._get_jira_issue_id()
elif att == "reviwer":
return self.data["assignees"][0]["name"]
elif att == "tester":
return self.data["testers"][0]["name"]
return self.data[att]
class Git():
def __init__(self, path="."):
self.path = path
self.repo = Repo(self.path)
self.origin = self.repo.remotes["origin"].url
def info(self):
p = giturlparse.parse(self.origin)
if not p.valid:
return None, None
return p.owner, p.repo
"""get what to cherry pick from master latest commits,
assuming that sandbox is pulled and have the latest code"""
def get_head_parents(self, branch="master"):
head = self.repo.heads[branch]
return [p.hexsha for p in head.commit.parents]
def current_branch(self):
return self.repo.active_branch.name
def needs_rebase(self, head, base="master"):
"Assume that git pull has been done"
# intentionally not handling exception here
# rebase logic has to be done locally so
current = self.current_branch()
self.repo.git.checkout(base)
self.repo.git.checkout(current)
bb = self.repo.merge_base(base, head)[0] # FIXME: not sure why this is a list
base_head = self.repo.refs[base].commit
return bb.hexsha != base_head.hexsha
def remote_branches(self):
for ref in self.repo.refs:
prefix = "refs/remotes/origin/"
if ref.path.startswith(prefix):
yield ref.path.partition(prefix)[2]
class ReleaseVersion():
def __init__(self, rel):
self.release = rel
self.is_semver = True
self.major = ""
self.minor = ""
self.fix = ""
self.project = ""
self._parse_release(rel)
def _parse_release(self, rel):
pat = re.compile("^v(\d+)\.(\d+)\.(\d+)(-[a-zA-Z0-9]+)?$")
mobj = re.match(pat, rel)
if not mobj:
self.is_semver = False
return
self.major = mobj.group(1)
self.minor = mobj.group(2)
self.fix = mobj.group(3)
self.project = mobj.group(4) or ""
if self.project:
self.project = self.project[1:]
def previous(self):
ver = f"v{self.major}.{self.minor-1}.self.fix"
if self.project:
ver += "-" + self.project
def __str__(self):
return self.release
class MyJiraError(Exception):
pass
class MyJira():
def __init__(self, url, user, passwd):
self.jira = JIRA(
_conf["jira"]["url"], auth=(_conf["jira"]["user"], _conf["jira"]["passwd"])
)
self.url = url
def update_issue(self, issue_id, comment, transition):
issue = self.jira.issue(issue_id)
project, _ = issue_id.split("-") # assuming format
self.jira.add_comment(issue_id, comment)
if transition:
self.jira.transition_issue(issue.key, _conf[project][transition])
def start_on_issue(self, issue_id, component, transition):
issue = self.jira.issue(issue_id)
issue.update(fields={"components": [{ "name": component }]})
self.jira.transition_issue(issue.key, transition)
def finish_issue(self, issue_id, comment):
self.update_issue(issue_id, comment, "ready_for_test")
def get_fix_versions(self, issue_id):
issue = self.jira.issue(issue_id)
return [fv.name for fv in issue.fields.fixVersions]
def get_issue_status(self, issue_id):
issue = self.jira.issue(issue_id)
return issue.fields.status.name
def get_trunk_fix_version(self, issue_id):
fv = self.get_fix_versions(issue_id)
for f in fv:
rv = ReleaseVersion(f)
if rv.fix == "0": # '0' means trunk
return f # Assuming there is only one
return None
def get_trunk_branch(self, issue_id):
fv = self.get_trunk_fix_version(issue_id)
if not fv:
return ""
rv = ReleaseVersion(fv)
return f"release-{rv.major}.{rv.minor}"
def _target_br(self, fvs):
master = False
rv = None
for fv in fvs:
rv = ReleaseVersion(fv)
if rv.fix == "0": # '0' means trunk
master = True
break
if not master:
return f"release-{rv.major}.{rv.minor}"
return "master"
def get_target_branch(self, issue_id):
"Returns PR target branch. There is bug when more than 2 fixVersions"
return self._target_br(self.get_fix_versions(issue_id))
def trunk_required(self, issue_id):
return self.get_trunk_fix_version(issue_id) is not None
def get_cherry_pick_branches(self, issue_id, ignore_trunk=True):
fv = self.get_fix_versions(issue_id)
branches = []
for f in fv:
rv = ReleaseVersion(f)
if not rv.is_semver or rv.fix == "0": # '0' means trunk
continue
rel = f"release-{rv.major}.{rv.minor}"
if rv.project:
rel += f"-{rv.project}"
branches.append(rel)
return branches
def list_transitions(self, issue_id):
jra = JIRA(
_conf["jira"]["url"], auth=(_conf["jira"]["user"], _conf["jira"]["passwd"])
)
trs = jra.transitions(issue_id)
for tr in trs:
print(f"ID: {tr['id']}, Name: {tr['name']}")
def _get_field(self, issue_id, field):
isu = self.jira.issue(issue_id)
return getattr(isu.fields, field)
def get_summary(self, issue_id):
return self._get_field(issue_id, "summary")
def get_assignee(self, issue_id):
assignee = self._get_field(issue_id, "assignee")
return assignee.name if assignee is not None else ""
def get_issue_url(self, issue_id):
return os.path.join(self.url, "browse", issue_id)
def push_off(self, issue_id, frm, to):
issue = self.jira.issue(issue_id)
newfv = []
for fv in issue.fields.fixVersions:
if fv.name == frm:
newfv.append({"name": to})
else:
newfv.append({"name": fv.name})
issue.update(fields={"fixVersions": newfv})
def include(self, issue_id, version):
issue = self.jira.issue(issue_id)
newfv = []
for fv in issue.fields.fixVersions:
if fv.name == version:
return
newfv.append({"name": fv.name})
newfv.append({"name": version})
issue.update(fields={"fixVersions": newfv})
def exclude(self, issue_id, version):
issue = self.jira.issue(issue_id)
newfv = []
for fv in issue.fields.fixVersions:
if fv.name != version:
newfv.append({"name": fv.name})
issue.update(fields={"fixVersions": newfv})
def has_children(self, issue_id):
issue = self.jira.issue(issue_id)
return len(issue.fields.subtasks) > 0
def is_epic(self, issue_id):
issue = self.jira.issue(issue_id)
return issue.fields.issuetype.name == "Epic"
def goto_issue(self, issue_id):
_open_url(self.get_issue_url(issue_id))
@click.group()
def main():
pass
def _good_jira_issue(jira, issue_id, force=False):
st = jira.get_issue_status(issue_id)
if st in ["Resolved", "Closed"]:
print("Jira issue {0} already Resolved or Closed. Giving up.".format(issue_id))
return False
vers = jira.get_fix_versions(issue_id)
if len(vers) == 0:
print("Invalid Jira issue: no fixVersion")
return False
if jira.has_children(issue_id) or jira.is_epic(issue_id):
print("Refusing to merge issue with subtask or Epic")
return False
# fixVersion can be:
# 1. x.y.0 for trunk
# 2. x.y.z for product bug fix
# 3. x.y.z-proj for project bug fix
trunk = bug_fix = proj_fix = 0
for v in vers:
rel = ReleaseVersion(v)
if not rel.is_semver:
print(f"{rel} is not semver. Skipped.")
continue
if rel.fix == "0": # 1
trunk += 1
major_rel = rel
elif rel.project: # 3
proj_fix += 1
else: # has to be 2
bug_fix += 1
if trunk > 1:
print("Jira issue assigned assigned to multiple major version. Giving up.")
return False
if not trunk and bug_fix and not force:
print("Bug fixes has to go to master. Giving up.")
return False
if not trunk and proj_fix and not force:
print("Bug fixes has to go to master. Giving up.")
return False
return True
def all_is_well(gitee, pr, jira, force):
if not pr.good():
print("Invalid PR. Possible causes are:")
print(" 1. PR not assigned to both reviwer and tester.")
print(" 2. PR title doesn't start with jira issue ID. e.g. CLOUD-1234")
print(" 3. PR title doesn't have summary.")
print(f"\n{pr.html_url}")
return False
return _good_jira_issue(jira, pr.issue_id, force)
def cherry_pick_real(git, branches, frm, to):
git.checkout("master")
git.pull()
for br in branches:
print(f"switching to {br}...")
git.checkout(br)
print(f"pulling from remote repo...")
git.pull()
print(f"cherry picking {frm}..{to}...")
git.cherry_pick(f"{frm}..{to}")
print(f"pushing to remote repo...")
git.push()
print(f"switching to master...")
git.checkout("master")
def cherry_pick(git, branches, frm, to, doit=True):
"""tries to automatically cherry-pick to the correct release branch from
master"""
if not branches:
return
if doit:
cherry_pick_real(git, branches, frm, to)
return
print()
print("1. Run the following commands")
print("2. Examine the result")
print("3. If everything looks OK, PUSH!\n")
print("git checkout master && git pull")
for b in branches:
print(f"# Updating release branch {b}...")
print(f"git checkout {b} && git pull")
print(f"git cherry-pick {frm}..{to}")
@main.command()
@click.option(
"--force/--no-force",
default=False,
help="Force merging of PR. Useful for project specific changes.",
)
@click.option(
"--autocp/--no-autocp",
default=True,
help="Automatically cherry pick to various release branches",
)
@click.argument("no")
def merge(no, force, autocp):
"Merge PR and resolve JIRA issue"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
if gitee.git.repo.is_dirty():
print("Working directory seems to be dirty. Refusing to continue.")
return 1
pr = PR(gitee.get_pr(no))
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
print(f"===> Processing PR for: {pr.issue_id} {jira.get_summary(pr.issue_id)}")
except GiteeError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
if not all_is_well(gitee, pr, jira, force):
return 0
if pr.head == "master" and force:
print("'force' only allowed for project specific bug fixes. Giving up.")
return 4
# used to be pr.head but there seems to be problem with gitee API
if pr.base['label'] != "master" and jira.trunk_required(pr.issue_id):
print("Jira fix version includes trunk but only merging to branch.")
print("Perhaps you should split the Jira issue. Giving up.")
print(f"\n\n\nbase: {pr.base}, issue: {pr.issue_id}")
return 5
try:
if not pr.merged():
print(f"===> Merging PR {no}...")
gitee.merge(no)
comment = "PR %d signed off by %s and %s.\n%s" % (
pr.number,
pr.reviwer,
pr.tester,
pr.html_url,
)
print(f"===> Updating jira issue status...")
jira.update_issue(pr.issue_id, comment, "done")
fv = jira.get_fix_versions(pr.issue_id)
if fv:
print(f"fixVersions: {', '.join(fv)}")
else:
print("Issue has no fixVersion!!!")
except GiteeError as e:
pr.dump()
print(f"\n\nFailed to merge PR: {e}", file=sys.stderr)
return 2
# TODO: catch JIRA exception
if force: # FIXME: this is leaky but let's assume it's OK
return 0
# this has to be done to make sure that local clone has the latest commit
try:
print(f"===> Updating to latest master...")
gitee.git.repo.git.checkout("master")
gitee.git.repo.git.pull()
except git.exc.GitCommandError as e:
print(e)
print("Unable to switch to master. Perhaps you have an dirty sandbox.")
return 11
try:
frm, to = gitee.git.get_head_parents()
except ValueError:
print("Something wrong with HEAD. It's not a merge commit.")
return 3
# When release branch is cut early, we have to include trunk fixVersion in
# cherry pick gargets. Like v1.100.0
branches = jira.get_cherry_pick_branches(pr.issue_id)
tbr = jira.get_trunk_branch(pr.issue_id)
if tbr in gitee.git.remote_branches():
branches.append(tbr)
if not branches:
return 0
print(f"===> Cherry picking to branches: {', '.join(branches)}...")
try:
cherry_pick(gitee.git.repo.git, branches, frm, to, autocp)
jira.update_issue(pr.issue_id, f"Cherry-picked to {', '.join(branches)}", "")
except git.exc.GitCommandError as e:
print(e)
print("===> Something went wrong. Re-opending jira issue")
jira.update_issue(pr.issue_id, "Cherry picking failed", "reopen")
return 0
@main.command()
@click.argument("branch")
def lockbr(branch):
"Lock branch"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
gitee.lock_branch(branch)
except Exception as e:
print(e)
def show_branches(full):
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
res = gitee.list_branch()
if full:
print(res.text)
return
for br in json.loads(res.text):
gitee.print_branch(br)
except Exception as e:
print(e)
def show_team(full):
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
res = gitee.list_member()
if full:
print(res.text)
return
for u in json.loads(res.text):
gitee.print_user(u)
except Exception as e:
print(e)
def show_prs(full):
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
res = gitee.list_prs()
if full:
print(res.text)
return
for pr in json.loads(res.text):
gitee.print_prs(pr)
except Exception as e:
print(e)
@main.command()
@click.option(
"--full/--no-full",
default=False,
help="Display full JSON. what can be <branch, team, pr>",
)
@click.argument("what")
def show(full, what):
"Show stuff"
if what == "branch" or what == "branches":
show_branches(full)
elif what == "team":
show_team(full)
elif what == "pr" or what =="prs":
show_prs(full)
@main.command()
@click.argument("user")
@click.argument("permission", default="push")
def adduser(user, permission):
"Add gitee user"
me = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(me, token)
gitee.add_user(user, permission)
except Exception as e:
print(e)
@main.command()
@click.argument("user")
def deluser(user):
"Delete gitee user"
me = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(me, token)
gitee.del_user(user)
except Exception as e:
print(e)
@main.command()
def gitee():
"Open gitee project page"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
gitee.goto_pull()
except Exception as e:
print(e)
@main.command()
@click.argument("pr_no")
def jira(pr_no):
"Open JIRA issue page for PR"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
gitee = Gitee(user, token)
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
pr = PR(gitee.get_pr(pr_no))
jira.goto_issue(pr.issue_id)
@main.command()
@click.argument("no")
def review(no):
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
pr = PR(gitee.get_pr(no))
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
except GiteeError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
print(f"===> Reviewing PR for: {pr.issue_id} {jira.get_summary(pr.issue_id)}")
gitee.goto_pull(no)
gitee.git.repo.git.checkout("master")
gitee.git.repo.git.pull()
print(f"===> Switching to branch:\t{pr.issue_id}")
gitee.git.repo.git.checkout(pr.issue_id)
gitee.git.repo.git.pull()
print(f"===> Trying to run unit tests...")
if os.system("make test") != 0:
print(f"===> ❌ Unit tests failed!!!")
print(f"===> Trying to build image...")
if os.system("make docker") != 0:
print(f"===> ❌ Building docker image failed!!!")
@main.command()
@click.argument("no")
def switch(no):
"Switch to PR branch"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
pr = PR(gitee.get_pr(no))
except GiteeError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
print(f"===> Switching to branch: {pr.issue_id}")
gitee.git.repo.git.checkout("master")
gitee.git.repo.git.pull()
gitee.git.repo.git.checkout(pr.issue_id)
gitee.git.repo.git.pull()
@main.command()
@click.argument("issue_no")
def start(issue_no):
"Start progress for JIRA issue"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
except MyJiraError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
def issue_ready_to_start():
return jira.get_assignee(issue_no) and len(jira.get_fix_versions(issue_no))
@retry(stop_max_attempt_number=10)
def branch_ready():
try:
gitee.get_branch(issue_no)
return True
except GiteeError as e:
raise e
if not issue_ready_to_start():
print("Issue has no fix versions or not assigned to someone. Aborting...")
return False
print("===> Updating JIRA issue status...")
jira.update_issue(issue_no, "Starting...", "in_progress")
print("===> Waiting for remote branch to be created...")
# wait for webhook to create remote branch
try:
branch_ready()
except GiteeError as e:
print("Something went wrong with jira webhook. Aborting...")
print("Possible reasons includes:")
print("1. JIRA issue doesn't have a valid component.")
print("2. JIRA issue isn't assigned to.")
print("3. JIRA issue status isn't *In Progress*.")
print("4. JIRA issue is an Epic or has subtasks.")
print("5. 你的JIRA是中文的UI.")
print("6. You have invalid gitee token.")
print(e)
return
# checkout to new branch
gitee.git.repo.git.checkout("master")
gitee.git.repo.git.pull()
print("===> Switching to PR branch...")
gitee.git.repo.git.checkout(issue_no)
print("\n\nYou're all set. 请开始你的表演...")
@main.command()
@click.argument("issue_no", nargs=-1)
def finish(issue_no):
"Finish JIRA issue"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
try:
gitee = Gitee(user, token)
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
except MyJiraError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
try:
if gitee.git.repo.is_dirty():
print("Working directory seems to be dirty. Refusing to continue.")
return 2
br = gitee.git.current_branch()
if br == "master":
print("You have to be on your PR branch to create a PR.")
return 3
print(f"===> Pushing to remote repo...")
gitee.git.repo.git.push()
if not issue_no:
issue_no = gitee.git.current_branch()
else:
issue_no = issue_no[0]
target_br = jira.get_target_branch(issue_no)
if gitee.git.needs_rebase(br, target_br):
print("!!! It looks like your branch needs rebasing.")
return 4
print(f"===> Creating PR for {issue_no}...")
title = f"{issue_no} {jira.get_summary(issue_no)}" # causes exception
body = "%s\nFix Version/s: %s" % (
jira.get_issue_url(issue_no), ",".join(jira.get_fix_versions(issue_no)))
res = gitee.create_pr(title, br, body, target_br) # TODO: automatically fill in assignee
jira.finish_issue(issue_no, f'PR created: {res.json()["html_url"]}')
print("===> Navigating to PR. 请手动分配reviewer和tester。并按语雀项目规定配置PR。")
print("同时请记得将JIRA issue assign给测试人员。")
gitee.goto_pull(str(res.json()["number"]))
except GiteeError as e:
print("Failed to create PR.")
print(e)
print(e.args[0].text)
# TODO: catch git and jira exceptions
@main.command()
@click.argument("pr_no")
def close_pr(pr_no):
"Close gitee PR"
user = _conf["gitee"]["user"]
token = _conf["gitee"]["token"]
gitee = Gitee(user, token)
gitee.close_pr(pr_no)
@main.command()
@click.argument("frm")
@click.argument("to")
@click.argument("issue_no")
def pushoff(issue_no, frm, to):
try:
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
jira.push_off(issue_no, frm, to)
except MyJiraError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
@main.command()
@click.argument("version")
@click.argument("issue_no")
def include(issue_no, version):
"Add issue to a release"
try:
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
print(f"Adding {issue_no} to release {version}...")
jira.include(issue_no, version)
except MyJiraError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
@main.command()
@click.argument("version")
@click.argument("issue_no")
def exclude(issue_no, version):
"Remove issue from a release"
try:
jira = MyJira(
_conf["jira"]["url"], _conf["jira"]["user"], _conf["jira"]["passwd"]
)
print(f"Removing {issue_no} from release {version}...")
jira.exclude(issue_no, version)
except MyJiraError as e:
print(f"Error: {e}", file=sys.stderr)
return 1