Package tracopt :: Package ticket :: Module commit_updater

Source Code for Module tracopt.ticket.commit_updater

  1  # -*- coding: utf-8 -*- 
  2  # 
  3  # Copyright (C) 2009-2020 Edgewall Software 
  4  # All rights reserved. 
  5  # 
  6  # This software is licensed as described in the file COPYING, which 
  7  # you should have received as part of this distribution. The terms 
  8  # are also available at https://trac.edgewall.org/wiki/TracLicense. 
  9  # 
 10  # This software consists of voluntary contributions made by many 
 11  # individuals. For the exact contribution history, see the revision 
 12  # history and logs, available at https://trac.edgewall.org/log/. 
 13   
 14  # This plugin was based on the contrib/trac-post-commit-hook script, which 
 15  # had the following copyright notice: 
 16  # ---------------------------------------------------------------------------- 
 17  # Copyright (c) 2004 Stephen Hansen 
 18  # 
 19  # Permission is hereby granted, free of charge, to any person obtaining a copy 
 20  # of this software and associated documentation files (the "Software"), to 
 21  # deal in the Software without restriction, including without limitation the 
 22  # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 
 23  # sell copies of the Software, and to permit persons to whom the Software is 
 24  # furnished to do so, subject to the following conditions: 
 25  # 
 26  #   The above copyright notice and this permission notice shall be included in 
 27  #   all copies or substantial portions of the Software. 
 28  # 
 29  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 30  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 31  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 32  # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 33  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 34  # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
 35  # IN THE SOFTWARE. 
 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 
57 58 59 -class CommitTicketUpdater(Component):
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
149 - def command_re(self):
150 begin, end = (re.escape(self.envelope[0:1]), 151 re.escape(self.envelope[1:2])) 152 return re.compile(begin + self.ticket_command + end)
153 154 ticket_re = re.compile(ticket_prefix + '([0-9]+)') 155 156 _last_cset_id = None 157 158 # IRepositoryChangeListener methods 159
160 - def changeset_added(self, repos, changeset):
161 if self._is_duplicate(changeset): 162 return 163 tickets = self._parse_message(changeset.message) 164 comment = self.make_ticket_comment(repos, changeset) 165 self._update_tickets(tickets, changeset, comment, datetime_now(utc))
166
167 - def changeset_modified(self, repos, changeset, old_changeset):
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
179 - def _is_duplicate(self, changeset):
180 # Avoid duplicate changes with multiple scoped repositories 181 cset_id = (changeset.rev, changeset.message, changeset.author, 182 changeset.date) 183 if cset_id != self._last_cset_id: 184 self._last_cset_id = cset_id 185 return False 186 return True
187
188 - def _parse_message(self, message):
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
203 - def make_ticket_comment(self, repos, changeset):
204 """Create the ticket comment from the changeset data.""" 205 rev = changeset.rev 206 revstring = str(rev) 207 drev = str(repos.display_rev(rev)) 208 if repos.reponame: 209 revstring += '/' + repos.reponame 210 drev += '/' + repos.reponame 211 return textwrap.dedent("""\ 212 In [changeset:"%s" %s]: 213 {{{ 214 #!CommitTicketReference repository="%s" revision="%s" 215 %s 216 }}}""") % (revstring, drev, repos.reponame, rev, 217 changeset.message.strip())
218
219 - def _update_tickets(self, tickets, changeset, comment, date):
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):
242 """Send a ticket update notification.""" 243 if not self.notify: 244 return 245 event = TicketChangeEvent('changed', ticket, date, author, comment) 246 try: 247 NotificationSystem(self.env).notify(event) 248 except Exception as e: 249 self.log.error("Failure sending notification on change to " 250 "ticket #%s: %s", ticket.id, 251 exception_to_unicode(e))
252
253 - def _get_functions(self):
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
264 - def _authname(self, changeset):
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 # Command-specific behavior 272 # The ticket isn't updated if all extracted commands return False. 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
291 292 -class CommitTicketReferenceMacro(WikiMacroBase):
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):
309 args = args or {} 310 reponame = args.get('repository') or '' 311 rev = args.get('revision') 312 repos = RepositoryManager(self.env).get_repository(reponame) 313 try: 314 changeset = repos.get_changeset(rev) 315 message = changeset.message 316 rev = changeset.rev 317 resource = repos.resource 318 except Exception: 319 message = content 320 resource = Resource('repository', reponame) 321 if formatter.context.resource.realm == 'ticket': 322 ticket_re = CommitTicketUpdater.ticket_re 323 if not any(int(tkt_id) == int(formatter.context.resource.id) 324 for tkt_id in ticket_re.findall(message)): 325 return tag.p(_("(The changeset message doesn't reference this " 326 "ticket)"), class_='hint') 327 if ChangesetModule(self.env).wiki_format_messages: 328 return tag.div(format_to_html(self.env, 329 formatter.context.child('changeset', rev, parent=resource), 330 message, escape_newlines=True), class_='message') 331 else: 332 return tag.pre(message, class_='message')
333