2 from errbot
import BotPlugin
, botcmd
, webhook
3 from errbot
.backends
import xmpp
4 from errcron
.bot
import CrontabMixin
8 from Secret
import admin_token
10 # TODO: Add certificate verification to the gitlab API calls.
13 class Marge(BotPlugin
, CrontabMixin
):
15 I remind you about merge requests
19 Add a merge request webook of the form
20 'https://webookserver/margeboot/<rooms>'
21 to the projects you want tracked. <rooms> should be a
22 comma-separated list of short room names (anything before the '@')
23 that you want notified.
25 Add <roomname>@domain to the CHATROOM_PRESENCE list in config.py for
26 rooms margebot should join
29 # TODO: The rontab schedule should be part of the configuration
31 '0 11,17 * * * .crontab_hook' # 7:00AM and 1:00PM EST warnings
34 def __init__(self
, *args
, **kwargs
):
36 self
.chatroom_host
= None
37 super().__init
__(*args
, **kwargs
)
39 def get_configuration_template(self
):
40 return {'GIT_HOST': 'gitlab.example.com',
41 'CHATROOM_HOST': 'conference.jabber.example.com'}
43 def check_configuration(self
, configuration
):
44 super().check_configuration(configuration
)
48 self
.log
.info('Margebot is not configured. Forbid activation')
50 self
.git_host
= self
.config
['GIT_HOST']
51 self
.chatroom_host
= self
.config
['CHATROOM_HOST']
52 self
.gitlab
= gitlab
.Gitlab(self
.git_host
, admin_token
, verify_ssl
=False)
57 # TODO: Anything special for closing gitlab ?
60 @webhook('/margebot/<rooms>/')
61 def gitlab_hook(self
, request
, rooms
):
63 Webhook that listens on http://<server>:<port>/gitlab
66 self
.log
.info('margebot webhook request: {}'.format(request
))
67 self
.log
.info('margebot webhook rooms {}'.format(rooms
))
69 # TODO: Will errbot return a json struct or not ?
71 # verify it's a merge request
72 if request
['object_kind'] != 'merge_request':
73 self
.log
.error('expecting object_kind of merge_request but got {}'.format(request
['object_kind']))
74 self
.log
.error('request: {}'.format(request
))
75 elif request
['object_attributes']['state'] == 'opened':
78 # - check for reopened / request['object_attributes']['action'] == 'reopn'
79 # (there's no 'action': 'opened' for MRs are created...
80 # - pop open_mrs when MRs are closed (action == close / state == closed
82 if request
['object_attributes']['work_in_progress']:
86 url
= request
['project']['homepage']
87 state
= request
['object_attributes']['state']
88 title
= request
['object_attributes']['title']
90 author_id
= request
['object_attributes']['author_id'] # map this to user name ...
91 author
= self
.gitlab
.getuser(author_id
)
92 author_name
= author
['username']
94 target_project_id
= request
['object_attributes']['target_project_id']
95 iid
= request
['object_attributes']['iid']
97 user_name
= request
['user']['username'] # will this always be Administrator ?
99 msg_template
= "New Review: {} has opened a new {} MR: \"{}\"\n{}/merge_requests/{}"
100 msg
= msg_template
.format(author_name
, wip
, title
, url
, iid
)
102 for a_room
in rooms
.split(','):
104 self
.send(self
.build_identifier(a_room
+ '@' + self
.chatroom_host
), msg
)
106 if 'OPEN_MRS' not in self
.keys():
108 self
['OPEN_MRS'] = empty_dict
110 with self
.mutable('OPEN_MRS') as open_mrs
:
111 open_mrs
[(target_project_id
, iid
, rooms
)] = True
115 def crontab_hook(self
):
117 Send a scheduled message to the rooms margebot is watching
118 about open MRs the room cares about.
121 reminder_msg
= {} # Map of reminder_msg['roomname@domain'] = msg
123 # initialize the reminders
126 reminder_msg
[a_room
.node()] = ''
131 # Let's walk through the MRs we've seen already:
132 with self
.mutable('OPEN_MRS') as open_mrs
:
133 for (project
, iid
, notify_rooms
) in open_mrs
:
135 # Lookup the MR from the project/iid
136 a_mr
= self
.gitlab
.getmergerequest(project
, iid
)
138 # If the MR is no longer open, skip to the next MR,
139 # and don't include this MR in the next check
140 if a_mr
['state'] != 'open':
143 still_open_mrs
[(project
, iid
, notify_rooms
)] = True
145 # TODO: Warn if an open MR has has conflicts (merge_status == ??)
146 # TODO: Include the count of opened MR notes (does the API show resolved state ??)
148 # getapprovals is only available in GitLab 8.9 EE or greater (not the open source CE version)
149 # approvals = self.gitlab.getapprovals(a_mr['id'])
151 # for approved in approvals['approved_by']:
152 # also_approved += "," + approved['user']['name']
154 upvotes
= a_mr
['upvotes']
156 msg
= "\n{}: Has 2+ upvotes / Could be merged in now.".format(a_mr
['web_url'])
158 msg_template
= "\n{}: Waiting for another upvote."
159 msg
= msg_template
.format(a_mr
['web_url'])
161 msg
= '\n{}: Noo upvotes / Please Review.'.format(a_mr
['web_url'])
163 for a_room
in notify_rooms
.split(','):
164 reminder_msg
[a_room
] += msg
166 # Remind each of the rooms about open MRs
167 for a_room
, room_msg
in reminder_msg
.iteritems():
170 msg_template
= "Heads up these MRs need some attention:{}\n"
171 msg_template
+= "You can get an updated list with the '/msg MargeB !reviews' command."
172 msg
= msg_template
.format(room_msg
)
173 self
.send(self
.build_identifier(a_room
+ '@' + self
.config
['CHATROOM_HOST']), msg
)
175 self
['OPEN_MRS'] = still_open_mrs
178 def reviews(self
, msg
, args
): # a command callable with !mrs
180 Returns a list of MRs that are waiting for some luv.
181 Also returns a list of MRs that have had enough luv but aren't merged in yet.
183 sender
= msg
._from
._resource
184 self
.log
.info('juden: reviews: frm: {} nick: {}\n{}'.format(msg
.frm
, msg
.nick
, msg
._from
.__dict
__))
186 if 'OPEN_MRS' not in self
.keys():
187 return "No MRs to review"
189 sender_gitlab_id
= None
190 for user
in self
.gitlab
.getusers():
191 # self.log.info('juden: users: {} {}'.format(sender, user))
192 if user
['username'] == sender
:
193 sender_gitlab_id
= user
['id']
194 self
.log
.info('juden: sender_gitlab_id = {}'.format(sender_gitlab_id
))
197 if not sender_gitlab_id
:
198 self
.log
.error('problem mapping {} to a gitlab user'.format(sender
))
199 # self.send(self.build_identifier(msg.frm), "Sorry I couldn't find your gitlab ID")
200 return "Sorry, I couldn't find your gitlab account."
202 # TODO: how to get the room the message was sent from ? I'm assuming this will either be in msg.frm or msg.to
203 # TODO: weed out MRs the sender opened or otherwise indicate they've opened or have already +1'd
205 roomname
= msg
.to
.domain
# ???
207 # Let's walk through the MRs we've seen already:
210 with self
.mutable('OPEN_MRS') as open_mrs
:
211 for (project
, iid
, notify_rooms
) in open_mrs
:
213 # Lookup the MR from the project/iid
214 a_mr
= self
.gitlab
.getmergerequest(project
, iid
)
216 self
.log
.info('juden: a_mr: {} {} {} {}'.format(project
, iid
, notify_rooms
, a_mr
))
218 # If the MR is no longer open, skip to the next MR,
219 # and don't include this MR in the next check
220 if a_mr
['state'] != 'opened':
223 still_open_mrs
[(project
, iid
, notify_rooms
)] = True
225 authored
= (a_mr
['author']['id'] == sender_gitlab_id
)
226 already_approved
= False
228 # getapprovals is currently only available in GitLab >= 8.9 EE (not available in the CE yet)
229 # approvals = self.gitlab.getapprovals(a_mr['id'])
231 # for approved in approvals['approved_by']:
232 # if approved['user']['id'] == sender_gitlab_id:
233 # already_approved = True
235 # also_approved += "," + approved['user']['name']
237 upvotes
= a_mr
['upvotes']
239 msg
+= "\n{}: has 2+ upvotes and could be merged in now.".format(a_mr
['web_url'])
242 msg
+= "\n{}: is waiting for another upvote.".format(a_mr
['web_url'])
244 msg
+= "\n{}: Your MR is waiting for another upvote.".format(a_mr
['web_url'])
248 msg
+= '\n{}: Has no upvotes and needs your attention.'.format(a_mr
['web_url'])
250 msg
+= '\n{}: Your MR has no upvotes.'.format(a_mr
['web_url'])
253 response
= 'Hi {}\n{}'.format(sender
, 'I found no open MRs for you.')
255 response
= 'Hi {}\n{}'.format(sender
,msg
)
257 # self.send(self.build_identifier(msg.frm), response)
259 with self
.mutable('OPEN_MRS') as open_mrs
:
260 open_mrs
= still_open_mrs
265 def hello(self
, msg
, args
):
269 def xyzzy(self
, msg
, args
):
270 yield "/me whispers \"All open MRs have ben merged into master.\""
272 yield "(just kidding)"