- Factoring out common code between crontab/reviews commands
[margebot.git] / marge.py
index bf47aee..548eb04 100755 (executable)
--- a/marge.py
+++ b/marge.py
@@ -1,36 +1,67 @@
 import re
+from datetime import datetime, timezone
+from dateutil import parser
+from dateutil.tz import tzutc
+from dateutil.relativedelta import *
 from errbot import BotPlugin, botcmd, webhook
 from errbot.backends import xmpp
 from errcron.bot import CrontabMixin
+from time import sleep
 import gitlab
 
-from Secret import admin_token
+def deltastr(any_delta):
+    l_delta = []
+    (days, hours, mins) = (any_delta.days, any_delta.seconds//3600, (any_delta.seconds//60)%60)
+
+    for (k,v) in {"day": days, "hour": hours, "minute": mins}.items():
+        if v == 1:
+            l_delta.append("1 " + k)
+        elif v > 1:
+            l_delta.append("{} {}s".format(v, k))
+
+    return ",".join(l_delta) + " ago"
 
 
 class Marge(BotPlugin, CrontabMixin):
     """
     I remind you about merge requests
 
-    Use: 
-       In gitlab: 
-          Add a merge request webook of the form 'https://webookserver/margeboot/<rooms>' to the projects you want tracked.  
-          <rooms> should be a comma-separated list of rooms you want notified.
+    Use:
+       In gitlab:
+          Add a merge request webook of the form
+             'https://webookserver/margeboot/<rooms>'
+          to the projects you want tracked.  <rooms> should be a
+          comma-separated list of short room names (anything before the '@')
+          that you want notified.
        In errbot:
-          Add <roomname>@domain to the CHATROOM_PRESENCE list in config.py for rooms margebot should join
+          Add <roomname>@domain to the CHATROOM_PRESENCE list in config.py for
+          rooms margebot should join
     """
-    
+
     CRONTAB = [
-       '0 11,17 * * * .crontab_hook'    # 7:00AM and 1:00PM EST warnings
+        # Set in config now: '0 11,17 * * * .crontab_hook'    # 7:00AM and 1:00PM EST warnings
     ]
 
     def __init__(self, *args, **kwargs):
-         self.git_host = None
-         self.chatroom_host = None
-         super().__init__(*args, **kwargs)
+        self.git_host = None
+        self.chatroom_host = None
+        super().__init__(*args, **kwargs)
 
     def get_configuration_template(self):
-        return {'GIT_HOST': 'gitlab.example.com',
-                'CHATROOM_HOST': 'conference.jabber.example.com'}
+        """
+        GITLAB_HOST:      Host name of your gitlab server
+        GITLAB_ADMIN_TOKEN: PAT from an admin's https://${GIT_HOST}/profile/personal_access_tokens page.
+        CHATROOM_HOST: Chatroom host.  Usually 'chatroom' + FQDN of Jabber server
+        CRONTAB: Schedule of automated merge request checks in '%M %H %d %m %w' format
+        VERIFY_SSL : True, False, or path to CA cert to verify cert
+        CRONTAB_SOAK_HOURS : Don't send out reminders about MRs opened less than this many hours
+        """ 
+        return {'GITLAB_HOST': 'gitlab.example.com',
+                'GITLAB_ADMIN_TOKEN' : 'gitlab-admin-user-private-token',
+                'CHATROOM_HOST': 'conference.jabber.example.com',
+                'CRONTAB' : '0 11,17 * * *',
+                'VERIFY_SSL' : True,
+                'CRONTAB_SOAK_HOURS' : 1}
 
     def check_configuration(self, configuration):
         super().check_configuration(configuration)
@@ -39,115 +70,189 @@ class Marge(BotPlugin, CrontabMixin):
         if not self.config:
             self.log.info('Margebot is not configured. Forbid activation')
             return
-        self.git_host = self.config['GIT_HOST']
+        self.git_host = self.config['GITLAB_HOST']
         self.chatroom_host = self.config['CHATROOM_HOST']
-        self.gitlab = gitlab.Gitlab(self.git_host,admin_token,verify_ssl=False)
+        Marge.CRONTAB = ['{} .crontab_hook'.format(self.config['CRONTAB']) ]
+        self.gitlab = gitlab.Gitlab(self.git_host, self.config['GITLAB_ADMIN_TOKEN'], verify_ssl=self.config['VERIFY_SSL'])
+        self.activate_crontab()
 
+        self.soak_delta = relativedelta( hours = self.config['CRONTAB_SOAK_HOURS'])
         super().activate()
 
     def deactivate(self):
-        # TODO: Anything special for closing gitlab ?
         super().deactivate()
 
-#    def configure(self, configuration):
-#        ## TODO: set up a connection to the gitlab API
-#        if self.config:
-#            self.gitlab = gitlab.Gitlab(self.git_host,admin_token,verify_ssl=False)
-
     @webhook('/margebot/<rooms>/')
     def gitlab_hook(self, request, rooms):
         """
         Webhook that listens on http://<server>:<port>/gitlab
         """
 
-        # TODO: Will errbot return a json struct or not ?
+        self.log.info('margebot webhook request: {}'.format(request))
+        self.log.info('margebot webhook rooms {}'.format(rooms))
 
         # verify it's a merge request
         if request['object_kind'] != 'merge_request':
-           self.log.error('expecting object_kind of merge_request but got {}'.format(request['object_kind']))
-           self.log.error('request: {}'.format(request))
+            self.log.error('expecting object_kind of merge_request but got {}'.format(request['object_kind']))
+            self.log.error('request: {}'.format(request))
         elif request['object_attributes']['state'] == 'opened':
-           if request['object_attributes']['work_in_progress']:
-               wip = "WIP"
-           else:
-               wip = ""
-           url = request['object_attributes']['url']
-           state = request['object_attributes']['state']
-           title = request['object_attributes']['title']
-           
-           author_id = request['object_attributes']['author_id'] # map this to user name ...
-           author = self.gitlab.getuser(author_id)
-           author_name = author['username']
-
-           target_project_id = request['object_attributes']['target_project_id']
-           iid = request['object_attributes']['iid']
-
-           user_name = request['user']['username'] # will this always be Administrator ?
-
-           message = "Reviews: {} has opened a new {} MR: {}\n{}".format(author_name, wip, title, url)
-
-           # TODO: Maybe also check the notify_<room> labels assigned to the MR as well ?
-           #mr_rooms = self.get_mr_rooms(target_project_id)
-           for a_room in rooms.split(','):
-               if self.config:
-                   self.send( self.build_identifier(a_room + '@' + self.chatroom_host ), message)
-
-           with self.mutable('OPEN_MRS') as open_mrs:
-               open_mrs[(target_project_id,iid,rooms)] = True
-        
+
+            # TODO:
+            # - check for reopened / request['object_attributes']['action'] == 'reopn'
+            #   (there's no 'action': 'opened' for MRs are created...
+            # - pop open_mrs when MRs are closed (action == close / state == closed
+
+            if request['object_attributes']['work_in_progress']:
+                wip = "WIP"
+            else:
+                wip = ""
+            url = request['project']['homepage']
+            state = request['object_attributes']['state']
+            title = request['object_attributes']['title']
+
+            author_id = request['object_attributes']['author_id']  # map this to user name ...
+            author = self.gitlab.getuser(author_id)
+            author_name = author['username']
+
+            target_project_id = request['object_attributes']['target_project_id']
+            iid = request['object_attributes']['iid']
+
+            user_name = request['user']['username']  # will this always be Administrator ?
+
+            msg_template = "New Review: {} has opened a new {} MR: \"{}\"\n{}/merge_requests/{}"
+            msg = msg_template.format(author_name, wip, title, url, iid)
+
+            for a_room in rooms.split(','):
+                if self.config:
+                    self.send(self.build_identifier(a_room + '@' + self.chatroom_host), msg)
+
+            if 'OPEN_MRS' not in self.keys():
+                empty_dict = {}
+                self['OPEN_MRS'] = empty_dict
+
+            with self.mutable('OPEN_MRS') as open_mrs:
+                open_mrs[(target_project_id, iid, rooms)] = True
+
         return "OK"
 
-    def crontab_hook(self):
+    def mr_status_msg(self, a_mr, author=None):
+        self.log.info("mr_status_msg: a_mr: {}".format(a_mr))
+
+        now = datetime.now(timezone.utc)
+        creation_time = parser.parse(a_mr['created_at'], tzinfos=tzutc)
+        self.log.info("times: {}, {}, {}".format(creation_time, self.soak_delta, now))
+        if creation_time + self.soak_delta > now:
+            info_msg = "skipping: MR <{},{}> was opened less than {} hours ago".format(project, iid, soak_hours)
+            self.log.info(info_msg)   
+            return None
+
+        str_open_since = deltastr(now - creation_time)
+
+        warning = ""
+        if a_mr['work_in_progress']:
+            warning = "still WIP"
+        elif a_mr['merge_status'] != 'can_be_merged':
+            warning = "there are merge conflicts"
+
+        if author:
+            authored = (a_mr['author']['id'] == author)
+        else:
+            authored = False
+
+        # TODO: Include the count of opened MR notes (does the API show resolved state ??)
+
+        # getapprovals is only available in GitLab 8.9 EE or greater (not the open source CE version)
+        # approvals = self.gitlab.getapprovals(a_mr['id'])
+        # also_approved = ""
+        # for approved in approvals['approved_by']:
+        #    also_approved += "," + approved['user']['name']
+
+        upvotes = a_mr['upvotes']
+        msg = "{} (opened {})".format(a_mr['web_url'], str_open_since)
+        if upvotes >= 2:
+            msg += ": Has 2+ upvotes / Could be merge in now"
+            if warning != "":
+                msg += " except {}".format(a_mr['web_url'], str_open_since, warning)
+            else:
+                 msg += "."
+
+        elif upvotes == 1:
+            if authored:
+                msg += ": Your MR is waiting for another upvote"
+            else:
+                msg += ": Waiting for another upvote"
+            if warning != "":
+                msg += "but {}.".format(warning)
+            else:
+                msg += "."
+
+        else:
+            if authored:
+                msg += ": Your MR has no upvotes"
+            else:
+                msg += ": No upvotes, please review"
+            if warning != "":
+                msg += "but {}".format(warning)
+            else:
+                msg += "."
+
+        return((creation_time, msg))
+
+
+    def crontab_hook(self, polled_time):
         """
-        Send a scheduled message to the rooms margebot is watching about open MRs the room cares about.
+        Send a scheduled message to the rooms margebot is watching
+        about open MRs the room cares about.
         """
 
-        reminder_msg = {}  # Map of reminder_msg['roomname@domain'] = msg
+        self.log.info("crontab_hook triggered at {}".format(polled_time))
+
+        reminder_msg = {}  # Map of reminder_msg['roomname@domain'] = [(created_at,msg)]
+
         # initialize the reminders
-        rooms = xmpp.rooms()
+        rooms = self.rooms()
         for a_room in rooms:
-            reminder_msg[a_room.node()] = ''
+            reminder_msg[a_room.node] = []
 
+        msgs = ""  
         still_open_mrs = {}
 
         # Let's walk through the MRs we've seen already:
-        for (project,iid,notify_rooms) in self['OPEM_MRS']:
+        with self.mutable('OPEN_MRS') as open_mrs:
+            for (project, iid, notify_rooms) in open_mrs:
 
-            # Lookup the MR from the project/iid
-            a_mr = self.gitlab.getmergerequest(project, iid)
+                # Lookup the MR from the project/iid
+                a_mr = self.gitlab.getmergerequest(project, iid)
 
-            # If the MR is no longer open, skip to the next MR,
-            # and don't include this MR in the next check
-            if a_mr['state'] != 'open':
-                continue
-            else:
-                still_open_mrs[(project, iid, notify_rooms)] = True
+                self.log.info("a_mr: {} {} {} {}".format(project, iid, notify_rooms, a_mr['state']))
 
-            # TODO: Warn if an open MR has has conflicts (merge_status == ??)
-            # TODO: Include the count of opened MR notes (does the API show resolved state ??)
+                # If the MR is no longer open, skip to the next MR,
+                # and don't include this MR in the next check
+                if a_mr['state'] != 'opened':
+                    continue
+                else:
+                     still_open_mrs[(project, iid, notify_rooms)] = True
 
-            approvals = self.gitlab.getapprovals(a_mr['id'])
-            also_approved = ""
-            for approved in approvals['approved_by']:
-                also_approved += "," + approved['user']['name']
+                msg_tuple = self.mr_status_msg(a_mr)
+                if msg_tuple is None:
+                    continue
 
-            upvotes = a_mr['upvotes']
-            if upvotes >= 2:
-                msg = "\n{}: Has 2+ upvotes and could be merged in now.".format(a_mr['web_url'])
-            elif upvotes == 1:
-                msg = "\n{}: {} already approved and is waiting for another upvote.".format(a_mr['web_url'], also_approved[1:])
-            else:
-                msg = '\n{}: Has no upvotes.'.format(a_mr['web_url'])
-               
-            for a_room in notify_rooms.split(','):
-                reminder_msg[a_room] += msg
+                for a_room in notify_rooms.split(','):
+                    reminder_msg[a_room].append(msg_tuple)
 
         # Remind each of the rooms about open MRs
-        for a_room, room_msg in reminder_msg.iteritems():
-            if room_msg != "":
+        for a_room, room_msg_list in reminder_msg.items():
+            if room_msg != []:
+
+                sorted_room_msg_list = sorted(room_msg_list, key=lambda x: x[0])  # sort by the creation time
+                msgs = [x[1] for x in sorted_room_msg_list]                       # extract the msgs from the tuple list
+                room_msg = "\n".join(msgs)                                        # join those msgs together.
+
                 if self.config:
-                    self.send(self.build_identifier(a_room + '@' + self.config['CHATROOM_HOST'] ), "Heads up these MRs need some luv:{}\n You can get a list of open reviews I know about by sending me a 'Marge, reviews' command.".format(room_msg))
+                    msg_template = "These MRs need some attention:{}\n"
+                    msg_template += "You can get an updated list with the  '/msg MargeB !reviews' command."
+                    msg = msg_template.format(room_msg)
+                    self.send(self.build_identifier(a_room + '@' + self.config['CHATROOM_HOST']), msg)
 
         self['OPEN_MRS'] = still_open_mrs
 
@@ -157,80 +262,69 @@ class Marge(BotPlugin, CrontabMixin):
         Returns a list of MRs that are waiting for some luv.
         Also returns a list of MRs that have had enough luv but aren't merged in yet.
         """
-        sender = msg.frm
+        ## Sending directly to Margbot:  sender in the form sender@....
+        ## Sending to a chatroom:  snder in the form room@rooms/sender
+
+        if msg.frm.domain == self.config['CHATROOM_HOST']:
+           sender = msg.frm.resource
+        else:
+           sender = msg.frm.node
 
-        send_gitlab_id = None
+        if 'OPEN_MRS' not in self.keys():
+            return "No MRs to review"
+
+        sender_gitlab_id = None
         for user in self.gitlab.getusers():
-            if user['username'] == sender.node:
+            if user['username'] == sender:
                 sender_gitlab_id = user['id']
                 break
 
-        if not send_gitlab_id:
-            self.log.error('problem mapping {} to a gitlab user'.format(sender.node))
-            self.send(self.build_identifier(msg.frm), "Sorry I couldn't find your gitlab ID")
-            return
-
-        # TODO:  how to get the room the message was sent from ?  I'm assuming this will either be in msg.frm or msg.to
-        # TODO:  weed out MRs the sender opened or otherwise indicate they've opened or have already +1'd
-
-        roomname = msg.to.domain #???
+        if not sender_gitlab_id:
+            self.log.error('problem mapping {} to a gitlab user'.format(sender))
+            return "Sorry, I couldn't find your gitlab account."
 
-        # Let's walk through the MRs we've seen already:
+        # Walk through the MRs we've seen already:
+        msg_list = []
         msg = ""
         still_open_mrs = {}
-        for (project,iid,notify_rooms) in self['OPEM_MRS']:
-
-            # Lookup the MR from the project/iid
-            a_mr = self.gitlab.getmergerequest(project, iid)
+        with self.mutable('OPEN_MRS') as open_mrs:
+            for (project, iid, notify_rooms) in open_mrs:
 
-            # If the MR is no longer open, skip to the next MR,
-            # and don't include this MR in the next check
-            if a_mr['state'] != 'open':
-                continue
-            else:
-                still_open_mrs[(project, iid, notify_rooms)] = True
-
-            authored = (a_mr['author_id'] == sender_gitlab_id)
-            already_approved = False
-
-            approvals = self.gitlab.getapprovals(a_mr['id'])
-            also_approved = ""
-            for approved in approvals['approved_by']:
-               if approved['user']['id'] == sender_gitlab_id:
-                  already_approved = True
-               else:
-                   also_approved += "," + approved['user']['name']
-
-            upvotes = a_mr['upvotes']
-            if upvotes >= 2:
-                msg = "\n{}: has 2+ upvotes from {} and could be merged in now.".format(a_mr['web_url'], also_approved[1:])
-            elif upvotes == 1:
-                if not authored:
-                    if already_approved:
-                        msg = "\n{}: has already been approved by you and is waiting for another upvote.".format(a_mr['web_url'])
-                    else:
-                        msg = "\n{}: has been approved by {} and is waiting for your upvote.".format(a_mr['web_url'], also_approved[1:])
+                # Lookup the MR from the project/iid
+                a_mr = self.gitlab.getmergerequest(project, iid)
+                # If the MR is no longer open, skip to the next MR,
+                # and don't include this MR in the next check
+                if a_mr['state'] != 'opened':
+                    continue
                 else:
-                    msg = "\n{}: Your MR has approved by {} and is waiting for another upvote.".format(a_mr['web_url'], also_approved[1:])
+                    still_open_mrs[(project, iid, notify_rooms)] = True
 
-            else:
-                if not authored:
-                    msg = '\n{}: Has no upvotes and needs your attention.'.format(a_mr['web_url'])
-                else:   
-                    msg = '\n{}: Your MR has no upvotes.'.format(a_mr['web_url'])
-            
-
-        if msg == "":
-            response = 'I found no open merge requests for you.'
+                msg_tuple = self.mr_status_msg(a_mr, author=sender_gitlab_id)
+                if msg_tuple is None:
+                    continue
+
+                msg_list.append(msg_tuple)
+
+        if msg_list == []:
+            response = 'Hi {}: {}'.format(sender, 'I found no open MRs for you.')
         else:
-            response = msg
-            
-        self.send(self.build_identifier(msg.frm), response)
+            sorted_msg_list = sorted(msg_list, key=lambda x: x[0])  # sort by the creation time
+            msgs = [x[1] for x in sorted_msg_list]                  # extract the msgs from the tuple list
+            msg = "\n".join(msgs)                                   # join those msgs together.
+            response = 'Hi {}: These MRs need some attention:\n{}'.format(sender,msg)
 
-        self['OPEN_MRS'] = still_open_mrs
+        with self.mutable('OPEN_MRS') as open_mrs:
+            open_mrs = still_open_mrs
 
-        return
+        return response
 
     @botcmd()
-    def hello(self,msg, args):
+    def hello(self, msg, args):
         return "Hi there"
+
+    @botcmd()
+    def xyzzy(self, msg, args):
+        yield "/me whispers \"All open MRs have ben merged into master.\""
+        sleep(5)
+        yield "(just kidding)"