Refactor a bit the label methods for tracker
authorFrederic Massart <fred@moodle.com>
Wed, 17 Dec 2014 07:09:37 +0000 (15:09 +0800)
committerFrederic Massart <fred@moodle.com>
Wed, 17 Dec 2014 07:16:33 +0000 (15:16 +0800)
mdk/commands/tracker.py
mdk/jira.py

index 5153973..3bc3408 100644 (file)
@@ -51,22 +51,24 @@ class TrackerCommand(Command):
             ['--add-labels'],
             {
                 'action': 'store',
-                'help': 'Add the specified labels to the issue',
+                'dest':  'addlabels',
+                'help': 'add the specified labels to the issue',
+                'metavar':  'labels',
                 'nargs': '+',
-                'dest':  'addlabels'
             }
         ),
         (
             ['--remove-labels'],
             {
                 'action': 'store',
-                'help': 'Remove the specified labels from the issue',
+                'dest':  'removelabels',
+                'help': 'remove the specified labels from the issue',
+                'metavar':  'labels',
                 'nargs': '+',
-                'dest':  'removelabels'
             }
         )
     ]
-    _description = 'Retrieve information from the tracker'
+    _description = 'Interact with Moodle tracker'
 
     Jira = None
     mdl = None
@@ -89,53 +91,14 @@ class TrackerCommand(Command):
         self.Jira = Jira()
         self.mdl = 'MDL-' + re.sub(r'(MDL|mdl)(-|_)?', '', issue)
 
-        changesMade = False
-        labelChanges = {
-            'added': [],
-            'removed': [],
-            'nochange': []
-        }
-
         if args.addlabels:
-            result = self.Jira.addLabels(self.mdl, args.addlabels)
-            labelChanges['added'].extend(result['added'])
-            labelChanges['nochange'].extend(result['nochange'])
-
-            if len(result['added']):
-                changesMade = True
+            self.Jira.addLabels(self.mdl, args.addlabels)
 
         if args.removelabels:
-            result = self.Jira.removeLabels(self.mdl, args.removelabels)
-            labelChanges['removed'].extend(result['removed'])
-            labelChanges['nochange'].extend(result['nochange'])
-
-            if len(result['removed']):
-                changesMade = True
+            self.Jira.removeLabels(self.mdl, args.removelabels)
 
         self.info(args)
 
-        if changesMade or len(labelChanges['nochange']):
-            if changesMade:
-                print u'Changes were made to this issue:'
-
-            if len(labelChanges['added']):
-                labels = u'{0}: {1}'.format('Labels added', ', '.join(labelChanges['added']))
-                for l in textwrap.wrap(labels, 68, initial_indent='* ', subsequent_indent='    '):
-                    print l
-
-            if len(labelChanges['removed']):
-                labels = u'{0}: {1}'.format('Labels removed', ', '.join(labelChanges['removed']))
-                for l in textwrap.wrap(labels, 68, initial_indent='* ', subsequent_indent='    '):
-                    print l
-
-            if len(labelChanges['nochange']):
-                print u'Some changes were not made to this issue:'
-                labels = u'{0}: {1}'.format('Labels unchanged', ', '.join(labelChanges['nochange']))
-                for l in textwrap.wrap(labels, 68, initial_indent='* ', subsequent_indent='    '):
-                    print l
-
-            print u'-' * 72
-
     def info(self, args):
         """Display classic information about an issue"""
         issue = self.Jira.getIssue(self.mdl)
@@ -153,9 +116,13 @@ class TrackerCommand(Command):
         status = u'{0} {1} {2}'.format(issue['fields']['status']['name'], resolution, resolutiondate).strip()
         print u'  {0}'.format(status)
 
+        print u'-' * 72
+        components = u'{0}: {1}'.format('Components', ', '.join([c['name'] for c in issue['fields']['components']]))
+        for l in textwrap.wrap(components, 68, initial_indent='  ', subsequent_indent='              '):
+            print l
         if issue['fields']['labels']:
             labels = u'{0}: {1}'.format('Labels', ', '.join(issue['fields']['labels']))
-            for l in textwrap.wrap(labels, 68, initial_indent='  ', subsequent_indent='    '):
+            for l in textwrap.wrap(labels, 68, initial_indent='  ', subsequent_indent='          '):
                 print l
 
         vw = u'[ V: %d - W: %d ]' % (issue['fields']['votes']['votes'], issue['fields']['watches']['watchCount'])
index 00194c2..1108453 100644 (file)
@@ -67,6 +67,20 @@ class Jira(object):
         self.version = {}
         self._load()
 
+
+    def addLabels(self, key, labels):
+        """Add labels to an issue"""
+
+        assert isinstance(labels, list), "Expected a list of labels"
+
+        data = []
+        for label in labels:
+            data.append({'add': label})
+
+        self.updateIssue(key, {'update': {'labels': data}})
+
+        return True
+
     def deleteAttachment(self, attachmentId):
         """Deletes an attachment"""
         resp = self.request('attachment/%s' % str(attachmentId), method='DELETE')
@@ -290,6 +304,17 @@ class Jira(object):
         value = re.sub(r'[+-]\d+$', '', value)
         return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
 
+    def removeLabels(self, key, labels):
+        """Remove labels from an issue"""
+
+        assert isinstance(labels, list), "Expected a list of labels"
+
+        data = []
+        for label in labels:
+            data.append({'remove': label})
+
+        self.updateIssue(key, {'update': {'labels': data}})
+
     def search(self, query):
         return self.request('search', params={'jql': query, 'fields': 'id'})
 
@@ -330,6 +355,15 @@ class Jira(object):
 
         return True
 
+    def updateIssue(self, key, data):
+        """Update an issue, the data must be well formatted"""
+        resp = self.request('issue/%s' % (str(key)), method='PUT', data=json.dumps(data))
+
+        if resp['status'] != 204:
+            raise JiraException('Could not update the issue')
+
+        return True
+
     def upload(self, key, filepath):
         """Uploads a new attachment to the issue"""
 
@@ -353,59 +387,6 @@ class Jira(object):
 
         return True
 
-    def getLabels(self, key):
-        """Get a dict of labels
-        """
-        issueInfo = self.getIssue(key, fields='labels')
-        return issueInfo.get('fields').get('labels', [])
-
-    def addLabels(self, key, newLabels):
-        labels = self.getLabels(key)
-
-        results = {
-            'added': [],
-            'nochange': []
-        }
-
-        for label in newLabels:
-            label = unicode(label)
-            if label not in labels:
-                labels.append(label)
-                results['added'].append(label)
-            else:
-                results['nochange'].append(label)
-
-        update = {'fields': {'labels': labels}}
-        resp = self.request('issue/%s' % (str(key)), method='PUT', data=json.dumps(update))
-
-        if resp['status'] != 204:
-            raise JiraException('Issue was not updated: %s' % (str(resp['status'])))
-
-        return results
-
-    def removeLabels(self, key, oldLabels):
-        labels = self.getLabels(key)
-
-        results = {
-            'removed': [],
-            'nochange': []
-        }
-
-        for label in oldLabels:
-            label = unicode(label)
-            if label in labels:
-                labels.remove(label)
-                results['removed'].append(label)
-            else:
-                results['nochange'].append(label)
-
-        update = {'fields': {'labels': labels}}
-        resp = self.request('issue/%s' % (str(key)), method='PUT', data=json.dumps(update))
-
-        if resp['status'] != 204:
-            raise JiraException('Issue was not updated: %s' % (str(resp['status'])))
-
-        return results
 
 class JiraException(Exception):
     pass