1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 import re
39 import textwrap
40
41 from genshi.builder import tag
42
43 from trac.config import BoolOption, Option
44 from trac.core import Component, implements
45 from trac.notification.api import NotificationSystem
46 from trac.perm import PermissionCache
47 from trac.resource import Resource
48 from trac.ticket import Ticket
49 from trac.ticket.notification import TicketChangeEvent
50 from trac.util.datefmt import datetime_now, utc
51 from trac.util.text import exception_to_unicode
52 from trac.util.translation import _, cleandoc_
53 from trac.versioncontrol import IRepositoryChangeListener, RepositoryManager
54 from trac.versioncontrol.web_ui.changeset import ChangesetModule
55 from trac.wiki.formatter import format_to_html
56 from trac.wiki.macros import WikiMacroBase
60 """Update tickets based on commit messages.
61
62 This component hooks into changeset notifications and searches commit
63 messages for text in the form of:
64 {{{
65 command #1
66 command #1, #2
67 command #1 & #2
68 command #1 and #2
69 }}}
70
71 Instead of the short-hand syntax "#1", "ticket:1" can be used as well,
72 e.g.:
73 {{{
74 command ticket:1
75 command ticket:1, ticket:2
76 command ticket:1 & ticket:2
77 command ticket:1 and ticket:2
78 }}}
79
80 Using the long-form syntax allows a comment to be included in the
81 reference, e.g.:
82 {{{
83 command ticket:1#comment:1
84 command ticket:1#comment:description
85 }}}
86
87 In addition, the ':' character can be omitted and issue or bug can be used
88 instead of ticket.
89
90 You can have more than one command in a message. The following commands
91 are supported. There is more than one spelling for each command, to make
92 this as user-friendly as possible.
93
94 close, closed, closes, fix, fixed, fixes::
95 The specified tickets are closed, and the commit message is added to
96 them as a comment.
97
98 references, refs, addresses, re, see::
99 The specified tickets are left in their current status, and the commit
100 message is added to them as a comment.
101
102 A fairly complicated example of what you can do is with a commit message
103 of:
104
105 Changed blah and foo to do this or that. Fixes #10 and #12,
106 and refs #12.
107
108 This will close #10 and #12, and add a note to #12.
109 """
110
111 implements(IRepositoryChangeListener)
112
113 envelope = Option('ticket', 'commit_ticket_update_envelope', '',
114 """Require commands to be enclosed in an envelope.
115
116 Must be empty or contain two characters. For example, if set to `[]`,
117 then commands must be in the form of `[closes #4]`.""")
118
119 commands_close = Option('ticket', 'commit_ticket_update_commands.close',
120 'close closed closes fix fixed fixes',
121 """Commands that close tickets, as a space-separated list.""")
122
123 commands_refs = Option('ticket', 'commit_ticket_update_commands.refs',
124 'addresses re references refs see',
125 """Commands that add a reference, as a space-separated list.
126
127 If set to the special value `<ALL>`, all tickets referenced by the
128 message will get a reference to the changeset.""")
129
130 check_perms = BoolOption('ticket', 'commit_ticket_update_check_perms',
131 'true',
132 """Check that the committer has permission to perform the requested
133 operations on the referenced tickets.
134
135 This requires that the user names be the same for Trac and repository
136 operations.""")
137
138 notify = BoolOption('ticket', 'commit_ticket_update_notify', 'true',
139 """Send ticket change notification when updating a ticket.""")
140
141 ticket_prefix = '(?:#|(?:ticket|issue|bug)[: ]?)'
142 ticket_reference = ticket_prefix + \
143 '[0-9]+(?:#comment:([0-9]+|description))?'
144 ticket_command = (r'(?P<action>[A-Za-z]*)\s*.?\s*'
145 r'(?P<ticket>%s(?:(?:[, &]*|[ ]?and[ ]?)%s)*)' %
146 (ticket_reference, ticket_reference))
147
148 @property
153
154 ticket_re = re.compile(ticket_prefix + '([0-9]+)')
155
156 _last_cset_id = None
157
158
159
166
168 if self._is_duplicate(changeset):
169 return
170 tickets = self._parse_message(changeset.message)
171 old_tickets = {}
172 if old_changeset is not None:
173 old_tickets = self._parse_message(old_changeset.message)
174 tickets = dict(each for each in tickets.iteritems()
175 if each[0] not in old_tickets)
176 comment = self.make_ticket_comment(repos, changeset)
177 self._update_tickets(tickets, changeset, comment, datetime_now(utc))
178
187
189 """Parse the commit message and return the ticket references."""
190 cmd_groups = self.command_re.finditer(message)
191 functions = self._get_functions()
192 tickets = {}
193 for m in cmd_groups:
194 cmd, tkts = m.group('action', 'ticket')
195 func = functions.get(cmd.lower())
196 if not func and self.commands_refs.strip() == '<ALL>':
197 func = self.cmd_refs
198 if func:
199 for tkt_id in self.ticket_re.findall(tkts):
200 tickets.setdefault(int(tkt_id), []).append(func)
201 return tickets
202
218
220 """Update the tickets with the given comment."""
221 authname = self._authname(changeset)
222 perm = PermissionCache(self.env, authname)
223 for tkt_id, cmds in tickets.iteritems():
224 try:
225 self.log.debug("Updating ticket #%d", tkt_id)
226 save = False
227 with self.env.db_transaction:
228 ticket = Ticket(self.env, tkt_id)
229 ticket_perm = perm(ticket.resource)
230 for cmd in cmds:
231 if cmd(ticket, changeset, ticket_perm) is not False:
232 save = True
233 if save:
234 ticket.save_changes(authname, comment, date)
235 if save:
236 self._notify(ticket, date, changeset.author, comment)
237 except Exception as e:
238 self.log.error("Unexpected error while processing ticket "
239 "#%s: %s", tkt_id, exception_to_unicode(e))
240
241 - def _notify(self, ticket, date, author, comment):
252
254 """Create a mapping from commands to command functions."""
255 functions = {}
256 for each in dir(self):
257 if not each.startswith('cmd_'):
258 continue
259 func = getattr(self, each)
260 for cmd in getattr(self, 'commands_' + each[4:], '').split():
261 functions[cmd] = func
262 return functions
263
265 """Returns the author of the changeset, normalizing the casing if
266 [trac] ignore_author_case is true."""
267 return changeset.author.lower() \
268 if self.env.config.getbool('trac', 'ignore_auth_case') \
269 else changeset.author
270
271
272
273
274 - def cmd_close(self, ticket, changeset, perm):
275 authname = self._authname(changeset)
276 if self.check_perms and not 'TICKET_MODIFY' in perm:
277 self.log.info("%s doesn't have TICKET_MODIFY permission for #%d",
278 authname, ticket.id)
279 return False
280 ticket['status'] = 'closed'
281 ticket['resolution'] = 'fixed'
282 if not ticket['owner']:
283 ticket['owner'] = authname
284
285 - def cmd_refs(self, ticket, changeset, perm):
286 if self.check_perms and not 'TICKET_APPEND' in perm:
287 self.log.info("%s doesn't have TICKET_APPEND permission for #%d",
288 self._authname(changeset), ticket.id)
289 return False
290
293 _domain = 'messages'
294 _description = cleandoc_(
295 """Insert a changeset message into the output.
296
297 This macro must be called using wiki processor syntax as follows:
298 {{{
299 {{{
300 #!CommitTicketReference repository="reponame" revision="rev"
301 }}}
302 }}}
303 where the arguments are the following:
304 - `repository`: the repository containing the changeset
305 - `revision`: the revision of the desired changeset
306 """)
307
308 - def expand_macro(self, formatter, name, content, args=None):
333