2 Margebot: A Errbot Plugin for Gitlab MR reminders
4 from datetime
import datetime
, timezone
6 from dateutil
import parser
7 from dateutil
.tz
import tzutc
8 from dateutil
.relativedelta
import relativedelta
9 from errbot
import BotPlugin
, botcmd
, re_botcmd
, webhook
10 from errbot
.templating
import tenv
11 from errcron
.bot
import CrontabMixin
15 def deltastr(any_delta
):
17 Output a datetime delta in the format "x days, y hours, z minutes ago"
21 hours
= any_delta
.seconds
// 3600
22 mins
= (any_delta
.seconds
// 60) % 60
24 for (key
, val
) in [("day", days
), ("hour", hours
), ("minute", mins
)]:
26 l_delta
.append("1 " + key
)
28 l_delta
.append("{} {}s".format(val
, key
))
33 retval
= ", ".join(l_delta
) + " ago"
37 class Marge(BotPlugin
, CrontabMixin
):
39 I remind you about merge requests
43 Add a merge request webook of the form
44 'https://webookserver/margeboot/<rooms>'
45 to the projects you want tracked. <rooms> should be a
46 comma-separated list of short room names (anything before the '@')
47 that you want notified.
49 Add <roomname>@domain to the CHATROOM_PRESENCE list in config.py for
50 rooms margebot should join
54 # Set in config now: '0 11,17 * * * .crontab_hook' # 7:00AM and 1:00PM EST warnings
57 def __init__(self
, *args
, **kwargs
):
59 self
.chatroom_host
= None
61 self
.soak_delta
= None
62 super().__init
__(*args
, **kwargs
)
64 def get_configuration_template(self
):
66 GITLAB_HOST: Host name of your gitlab server
67 GITLAB_ADMIN_TOKEN: PAT from an admin's https://${GIT_HOST}/profile/personal_access_tokens.
68 CHATROOM_HOST: Chatroom host. Usually 'chatroom' + FQDN of Jabber server
69 CRONTAB: Schedule of automated merge request checks in '%M %H %d %m %w' format
70 VERIFY_SSL : True, False, or path to CA cert to verify cert
71 CRONTAB_SOAK_HOURS : Don't send out reminders about MRs opened less than this many hours
73 return {'GITLAB_HOST': 'gitlab.example.com',
74 'GITLAB_ADMIN_TOKEN': 'gitlab-admin-user-private-token',
75 'CHATROOM_HOST': 'conference.jabber.example.com',
76 'CRONTAB': '0 11,17 * * *',
78 'CRONTAB_SOAK_HOURS': 1}
80 def check_configuration(self
, configuration
):
82 Check that the plugin has been configured properly
84 super().check_configuration(configuration
)
88 Initialization done when the plugin is activated
91 self
.log
.info('Margebot is not configured. Forbid activation')
93 self
.git_host
= self
.config
['GITLAB_HOST']
94 self
.chatroom_host
= self
.config
['CHATROOM_HOST']
95 Marge
.CRONTAB
= ['{} .crontab_hook'.format(self
.config
['CRONTAB'])]
96 gitlab_auth_token
= self
.config
['GITLAB_ADMIN_TOKEN']
97 verify_ssl
= self
.config
['VERIFY_SSL']
98 self
.gitlab
= gitlab
.Gitlab(self
.git_host
, gitlab_auth_token
, verify_ssl
=verify_ssl
)
99 self
.activate_crontab()
101 self
.soak_delta
= relativedelta(hours
=self
.config
['CRONTAB_SOAK_HOURS'])
104 def deactivate(self
):
106 Anything that needs to be tore down when the plugin is deactivated goes here.
110 @webhook('/margebot/<rooms>/')
111 def gitlab_hook(self
, request
, rooms
):
113 Webhook that listens on http://<server>:<port>/gitlab
116 self
.log
.info("webhook: request: {}, rooms: {}".format(request
, rooms
))
117 self
.log
.info("state: {}".format(request
['object_attributes']['state']))
119 # verify it's a merge request
120 if request
['object_kind'] != 'merge_request':
121 self
.log
.error('unexpecting object_kind: {}'.format(request
['object_kind']))
122 elif 'opened' in request
['object_attributes']['state']:
124 if request
['object_attributes']['work_in_progress']:
128 url
= request
['project']['homepage']
129 title
= request
['object_attributes']['title']
131 author_id
= request
['object_attributes']['author_id'] # map this to user name ...
132 author
= self
.gitlab
.getuser(author_id
)
134 author_name
= author
['username']
136 self
.log
.info("unexpected author_id {}".format(author_id
))
137 author_name
= author_id
139 target_project_id
= request
['object_attributes']['target_project_id']
140 iid
= request
['object_attributes']['iid']
141 mr_id
= request
['object_attributes']['id']
143 msg_template
= "Hi there ! {} has opened a new {}MR: \"{}\"\n{}/merge_requests/{}"
144 msg
= msg_template
.format(author_name
, wip
, title
, url
, iid
)
146 if 'OPEN_MRS' not in self
.keys():
148 self
['OPEN_MRS'] = empty_dict
150 open_mrs
= self
['OPEN_MRS']
152 if (target_project_id
, mr_id
, rooms
) not in open_mrs
:
153 for a_room
in rooms
.split(','):
155 self
.send(self
.build_identifier(a_room
+ '@' + self
.chatroom_host
), msg
)
157 self
.log
.info("webhook: Saving ({}, {}, {})".format(target_project_id
, mr_id
, rooms
))
158 open_mrs
[(target_project_id
, mr_id
, rooms
)] = True
159 self
['OPEN_MRS'] = open_mrs
162 def mr_status_msg(self
, a_mr
, author
=None):
164 Create the merge request status message
166 self
.log
.info("mr_status_msg: a_mr: {}".format(a_mr
))
168 # Only weed out MRs less than the soak time for the crontab output (where author==None)
169 now
= datetime
.now(timezone
.utc
)
170 creation_time
= parser
.parse(a_mr
['created_at'], tzinfos
=tzutc
)
172 self
.log
.info("times: {}, {}, {}".format(creation_time
, self
.soak_delta
, now
))
173 if creation_time
+ self
.soak_delta
> now
:
174 project_id
= a_mr
['target_project_id']
176 soak_hours
= self
.config
['CRONTAB_SOAK_HOURS']
177 info_template
= "skipping: MR <{},{}> was opened less than {} hours ago"
178 info_msg
= info_template
.format(project_id
, mr_id
, soak_hours
)
179 self
.log
.info(info_msg
)
182 str_open_since
= deltastr(now
- creation_time
)
185 if a_mr
['work_in_progress']:
186 warning
= "still WIP"
187 elif a_mr
['merge_status'] != 'can_be_merged':
188 warning
= "there are merge conflicts"
191 authored
= (a_mr
['author']['id'] == author
)
195 # getapprovals is only available in GitLab 8.9 EE or greater
196 # (not the open source CE version)
197 # approvals = self.gitlab.getapprovals(a_mr['id'])
199 # for approved in approvals['approved_by']:
200 # also_approved += "," + approved['user']['name']
202 upvotes
= a_mr
['upvotes']
203 msg
= "{} (opened {})".format(a_mr
['web_url'], str_open_since
)
205 msg
+= ": Has 2+ upvotes and could be merged in now"
207 msg
+= " except {}.".format(warning
)
213 msg
+= ": Your MR is waiting for another upvote"
215 msg
+= ": Waiting for another upvote"
217 msg
+= " but {}.".format(warning
)
223 msg
+= ": Your MR has no upvotes"
225 msg
+= ": No upvotes, please review"
227 msg
+= " but {}.".format(warning
)
231 return {'creation_time': creation_time
, 'msg': msg
}
233 def crontab_hook(self
, polled_time
):
235 Send a scheduled message to the rooms margebot is watching
236 about open MRs the room cares about.
239 self
.log
.info("crontab_hook triggered at {}".format(polled_time
))
241 reminder_msg
= {} # Map of reminder_msg['roomname@domain'] = [(created_at,msg)]
243 # initialize the reminders
246 reminder_msg
[a_room
.node
] = []
250 # Let's walk through the MRs we've seen already:
251 open_mrs
= self
['OPEN_MRS']
253 for (project_id
, mr_id
, notify_rooms
) in open_mrs
:
255 # Lookup the MR from the project/id
256 a_mr
= self
.gitlab
.getmergerequest(project_id
, mr_id
)
258 self
.log
.debug("Couldn't find project: {}, id: {}".format(project_id
, mr_id
))
261 # If the MR is tagged 'never-close' ignore it
262 if 'labels' in a_mr
and 'never-close' in a_mr
['labels']:
265 self
.log
.info("a_mr: {} {} {} {}".format(project_id
, mr_id
, notify_rooms
, a_mr
['state']))
267 # If the MR is no longer open, skip to the next MR,
268 # and don't include this MR in the next check
269 if 'opened' not in a_mr
['state']:
272 still_open_mrs
[(project_id
, mr_id
, notify_rooms
)] = True
274 msg_dict
= self
.mr_status_msg(a_mr
)
278 for a_room
in notify_rooms
.split(','):
279 reminder_msg
[a_room
].append(msg_dict
)
281 self
['OPEN_MRS'] = open_mrs
283 # Remind each of the rooms about open MRs
284 for a_room
, room_msg_list
in reminder_msg
.items():
285 if room_msg_list
!= []:
287 to_room
= a_room
+ '@' + self
.config
['CHATROOM_HOST']
288 msg
= tenv().get_template('reviews.md').render(msg_list
=room_msg_list
)
289 self
.send(self
.build_identifier(to_room
), msg
)
291 self
['OPEN_MRS'] = still_open_mrs
293 @botcmd(template
="reviews")
294 def reviews(self
, msg
, args
):
296 Returns a list of MRs that are waiting for some luv.
297 Also returns a list of MRs that have had enough luv but aren't merged in yet.
299 # Sending directly to Margbot: sender in the form sender@....
300 # Sending to a chatroom: snder in the form room@rooms/sender
302 log_template
= 'reviews: msg: {}, args: {}, \nmsg.frm: {}, \nmsg.msg.frm: {}, chatroom_host: {}'
303 self
.log
.info(log_template
.format(msg
, args
, msg
.frm
.__dict
__, dir(msg
.frm
), self
.config
['CHATROOM_HOST']))
304 self
.log
.info('reviews: bot mode: {}'.format(self
._bot
.mode
))
306 if self
._bot
.mode
== "xmpp":
307 if msg
.frm
.domain
== self
.config
['CHATROOM_HOST']:
308 sender
= msg
.frm
.resource
310 sender
= msg
.frm
.node
312 sender
= str(msg
.frm
).split('@')[0]
315 if 'OPEN_MRS' not in keys
:
316 self
.log
.error('OPEN_MRS not in {}'.format(keys
))
317 return "No MRs to review"
319 sender_gitlab_id
= None
320 sender_users
= self
.gitlab
.getusers(search
=(('username', sender
)))
322 self
.log
.error('problem mapping {} to a gitlab user'.format(sender
))
323 sender_gitlab_id
= None
325 sender_gitlab_id
= sender_users
[0]['id']
327 # Walk through the MRs we've seen already:
331 open_mrs
= self
['OPEN_MRS']
332 for (project
, mr_id
, notify_rooms
) in open_mrs
:
334 # Lookup the MR from the project/id
335 a_mr
= self
.gitlab
.getmergerequest(project
, mr_id
)
337 self
.log
.debug("Couldn't find project: {}, id: {}".format(project
, id))
340 self
.log
.info('project: {}, id: {}, a_mr: {}'.format(project
, id, a_mr
))
342 # If the MR is tagged 'never-close' ignore it
343 if 'labels' in a_mr
and 'never-close' in a_mr
['labels']:
346 # If the MR is no longer open, skip to the next MR,
347 # and don't include this MR in the next check
348 if 'opened' not in a_mr
['state']:
351 still_open_mrs
[(project
, mr_id
, notify_rooms
)] = True
353 msg_dict
= self
.mr_status_msg(a_mr
, author
=sender_gitlab_id
)
357 msg_list
.append(msg_dict
)
359 self
['OPEN_MRS'] = still_open_mrs
361 return {'sender': sender
, 'msg_list': msg_list
}
363 # pragma pylint: disable=unused-argument
365 def hello(self
, msg
, args
):
367 A simple command to check if the bot is responding
372 def xyzzy(self
, msg
, args
):
374 Don't call this command...
376 yield "/me whispers \"All open MRs have been merged into master.\""
378 yield "(just kidding)"
380 @re_botcmd(pattern
=r
"I blame [Mm]arge([Bb]ot)?")
381 def dont_blame_margebot(self
, msg
, match
):
383 margebot is innocent.
385 yield "(」゚ロ゚)」NOOOooooo say it ain't so."
387 @re_botcmd(pattern
=r
"good bot")
388 def best_bot(self
, msg
, match
):
390 margebot is the best.
394 # pragma pylint: enable=unused-argument