TracZephyrPlugin: Display the priority of new tickets.
[snippets/.git] / TracZephyrPlugin / ZephyrPlugin.py
1 # -*- coding: utf-8 -*-
2
3 from trac.core import *
4 from trac.ticket import ITicketChangeListener
5 import subprocess
6 import re
7 import textwrap
8 import shlex
9
10 quoted_re = re.compile('^(?:> ?\n)*> .+\n(?:>(?: .*)?\n)*', re.MULTILINE)
11
12 class ZephyrPlugin(Component):
13     implements(ITicketChangeListener)
14     
15     def zwrite(self, id, message):
16         zclass = self.config.get('ZephyrPlugin', 'class')
17         if zclass == '':
18             return
19         command = shlex.split(self.config.get('ZephyrPlugin', 'command').encode('utf-8'))
20         if not command:
21             command = ['zwrite', '-q', '-l', '-d']
22         p = subprocess.Popen(command +
23                              ['-c', zclass,
24                               '-i', 'trac-#%s' % id],
25                              stdin=subprocess.PIPE)
26         p.stdin.write(message.replace('@', '@@').encode('utf-8', 'replace'))
27         p.stdin.close()
28         p.wait()
29
30     def format_text(self, text):
31         text = re.sub(quoted_re, u'> […]\n', text)
32         lines = textwrap.fill(text).split('\n')
33         if len(lines) > 5:
34             lines = lines[:5] + [u'[…]']
35         return '\n'.join(lines)
36     
37     def ticket_created(self, ticket):
38         message = "%s filed a new %s ticket:\n%s\n\n%s" % (ticket['reporter'],
39                                                            ticket['priority'],
40                                                            ticket['summary'],
41                                                            self.format_text(ticket['description']))
42         self.zwrite(ticket.id, message)
43     
44     def ticket_changed(self, ticket, comment, author, old_values):
45         message = "(%s)\n" % ticket['summary']
46         for field in ticket.fields:
47             name = field['name']
48             if name not in old_values:
49                 pass
50             elif field['type'] == 'textarea':
51                 message += "%s changed %s to:\n%s\n" % (author, name, self.format_text(ticket[name]))
52             elif ticket[name] and old_values[name]:
53                 message += "%s changed %s from %s to %s.\n" % (author, name, old_values[name], ticket[name])
54             elif ticket[name]:
55                 message += "%s set %s to %s.\n" % (author, name, ticket[name])
56             elif old_values[name]:
57                 message += "%s deleted %s.\n" % (author, name)
58             else:
59                 message += "%s changed %s.\n" % (author, name)
60         if comment:
61             message += "%s commented:\n%s\n" % (author, self.format_text(comment))
62         self.zwrite(ticket.id, message)
63     
64     def ticket_deleted(self, ticket):
65         message = "%s deleted ticket %d" % (author, ticket.id)
66         self.zwrite(ticket.id, message)