Debian Codegraph @

test/gitlab.com/reviews-email

raw
1 #!/usr/bin/env python3
2
3 # This script e-mails an outstanding MR review request.
4 #
5 # Configuration is via environment variables:
6 #
7 # In addition to sending the e-mail (or instead of if --to is not given), it
8 # prints the message body to stdout.
9 #
10 # Caveats/gotchas:
11 #
12 # 1. The error handling is pretty loose because we can just look at the
13 # exception in the CI job log.
14 #
15 # 2. 1998 called and wants its HTML back.
16 #
17 # 3. The python-gitlab docs [1] have decent examples, but the API reference
18 # is nearly useless. Many objects do have a pprint() method that helps. The
19 # Gitlab REST API docs [2] do not appear to be comprehensive.
20 #
21 # [1]: https://python-gitlab.readthedocs.io/en/stable
22 # [2]: https://docs.gitlab.com/ee/api
23
24
25 import argparse
26 import email
27 import io
28 import os
29 import smtplib
30 import sys
31
32 import gitlab # a.k.a. python-gitlab
33
34
35 ### Constants ###
36
37 PAGE_LENGTH = 100 # max 100
38 PROJECT_ID = os.environ.get("CI_PROJECT_ID", "charliecloud/charliecloud")
39
40 # Review request states appear to be undocumented; there is an example [1] but
41 # nothing about what the possible values are. There is an open issue
42 # requesting documentation for this [2], and a comment there points to GraphQL
43 # docs [3] that list the values below (in all caps).
44 #
45 # [1]: https://docs.gitlab.com/ee/api/merge_requests.html#get-single-merge-request-reviewers
46 # [2]: https://gitlab.com/gitlab-org/gitlab/-/issues/440445
47 # [3]: https://docs.gitlab.com/ee/api/graphql/reference/#mergerequestreviewstate
48 RR_STATES_OK = { "approved", "requested_changes", "reviewed" }
49 RR_STATES_DELINQUENT = { "review_started", "unapproved", "unreviewed" }
50 RR_STATES_ALL = RR_STATES_DELINQUENT | RR_STATES_OK
51
52 ### Globals ###
53
54 body = io.StringIO()
55
56
57 ### Main ###
58
59 def main():
60
61 ap = argparse.ArgumentParser(
62 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
63 ap.add_argument("--to", metavar="ADDR",
64 help="recipient e-mail address")
65 ap.add_argument("--from", metavar="ADDR", dest="from_",
66 default="[email protected]",
67 help="sender address")
68 ap.add_argument("--host", metavar="HOST",
69 default="localhost",
70 help="SMTP server to use")
71 ap.add_argument("--port", metavar="PORT", type=int,
72 default=smtplib.SMTP_PORT,
73 help="TCP port on SMTP server")
74 ap.add_argument("--user", metavar="NAME",
75 help="username for SMTP login")
76 ap.add_argument("--pass", metavar="WORD", dest="pass_",
77 help="password for SMTP login")
78 ap.add_argument("--verbose", "-v", action="store_true",
79 help="log SMTP transaction")
80 args = ap.parse_args()
81 if ((args.user is None) + (args.pass_ is None) == 1):
82 ap.error("both --user and --pass must be given together")
83
84 gl = gitlab.Gitlab("https://gitlab.com", per_page=PAGE_LENGTH)
85 pj = gl.projects.get(PROJECT_ID)
86 OUT("<!DOCTYPE html>")
87 OUT("<html><body>")
88
89 OUT("<p><table>")
90 OUT("<tr><td>project:</td><td><a href='%s'>%s</a> %d</td>"
91 % (pj.web_url, pj.path_with_namespace, pj.id))
92
93 # analyze projects
94 mrs = pj.mergerequests.list(state="opened", get_all=True,
95 order_by="created_at", sort="asc")
96 delinquents = dict()
97 OUT("<tr><td>MRs open:&nbsp;</td> <td>%d</td>" % len(mrs))
98 OUT("<tr><td>job:</td> <td>%s</td></tr>" % os.environ.get("CI_JOB_URL"))
99 OUT("</table></p>")
100 for (n, mr) in enumerate(mrs, 1):
101 revs = mr.reviewer_details.list()
102 LOG("%d. MR !%d:" % (n, mr.iid))
103 delinquents_p = False
104 for rev in revs:
105 LOG("%s: %s" % (rev.user["username"], rev.state))
106 if (rev.state not in RR_STATES_ALL):
107 LOG("bad state: %s" % rev.state)
108 sys.exit(1)
109 if (rev.state in RR_STATES_DELINQUENT):
110 delinquents_p = True
111 if (not delinquents_p):
112 LOG("no delinquents")
113 continue
114 # at least one delinquent, so include MR in the e-mail
115 OUT()
116 OUT("<p>")
117 OUT("<strong>%d. MR <a href='%s'>!%d</a>: %s</strong><br/>"
118 % (n, mr.web_url, mr.iid, mr.title))
119 OUT("<table>")
120 for d in mr.reviewer_details.list():
121 OUT("<tr> <td><strong>%s:</strong>&nbsp;</td> <td>%s"
122 % (d.user["username"], d.state))
123 if (d.state not in RR_STATES_DELINQUENT):
124 OUT(" ok")
125 else:
126 OUT(" <font color=red><blink>DELINQUENT</blink></font>")
127 delinquents[d.user["username"]] = d.user
128 OUT("</td></tr>")
129 for i in mr.closes_issues():
130 OUT("<tr> <td>closes:</td> <td><a href='%s'>#%d</a>: %s</td> </tr>"
131 % (i.web_url, i.iid, i.title))
132 OUT("</table></p>")
133
134 # call out delinquents by name
135 OUT()
136 OUT("<p>")
137 OUT("<strong>found %d delinquents:</strong><br/>" % len(delinquents))
138 OUT("<table>")
139 for u in sorted(delinquents.values(), key=lambda x: x["username"]):
140 OUT("<tr> <td>%s&nbsp;</td> <td>%s</td> </tr>"
141 % (u["username"], u["name"]))
142 OUT("</table></p>")
143
144 OUT("</body></html>")
145
146 # send e-mail
147 LOG()
148 if (not args.to):
149 LOG("--to not given, skipping e-mail")
150 elif (len(delinquents) == 0):
151 LOG("no delinquents, skipping e-mail")
152 else:
153 LOG("sending e-mail to %s ..." % args.to)
154 msg = email.message.EmailMessage()
155 # Use a boring subject line rather than the fancy one because the latter
156 # is silently not delivered by at least one provider, I guess because it
157 # looks too spammy?
158 msg["Subject"] = "delinquent reviews report"
159 #msg["Subject"] = "🤯🤯🤯 You WON’T BELIEVE who is DeLiNqUeNt!! CLICK HERE to find out!!! 🤯🤯🤯"
160 msg["From"] = args.from_
161 msg["To"] = args.to
162 msg.set_content("no plain text, only HTML, sorry")
163 msg.add_alternative(body.getvalue(), subtype="html")
164 smtp = smtplib.SMTP(args.host) # https://github.com/python/cpython/issues/80275
165 if (args.verbose):
166 smtp.set_debuglevel(1)
167 LOG("SMTP: connecting to %s:%s" % (args.host, args.port))
168 smtp.connect(args.host, args.port)
169 smtp.ehlo()
170 smtp.starttls()
171 smtp.ehlo()
172 if (args.user):
173 smtp.login(args.user, args.pass_)
174 refused = smtp.send_message(msg)
175 if (len(refused) > 0):
176 LOG("SMTP: %d recipients refused: %s" % (len(refused), refused))
177 quit = smtp.quit()
178 LOG("SMTP: session closed: %d %s" % (quit[0], quit[1].decode("utf8")))
179
180 LOG("done")
181
182
183
184 ### Functions ###
185
186 def LOG(*args, **kwargs):
187 print(*args, **kwargs, file=sys.stderr)
188
189 def OUT(*args, **kwargs):
190 print(*args, **kwargs, file=sys.stdout)
191 print(*args, **kwargs, file=body)
192
193 ### Bootstrap ###
194
195 if (__name__ == "__main__"):
196 main()