1# -*- coding: utf-8 -*-
2#
3# Copyright (C) 2009-2021 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
38import re
39import textwrap
40
41from trac.config import BoolOption, Option
42from trac.core import Component, implements
43from trac.notification.api import NotificationSystem
44from trac.perm import PermissionCache
45from trac.resource import Resource
46from trac.ticket import Ticket
47from trac.ticket.notification import TicketChangeEvent
48from trac.util import as_int
49from trac.util.datefmt import datetime_now, utc
50from trac.util.html import tag
51from trac.util.text import exception_to_unicode
52from trac.util.translation import _, cleandoc_
53from trac.versioncontrol import IRepositoryChangeListener, RepositoryManager
54from trac.versioncontrol.web_ui.changeset import ChangesetModule
55from trac.wiki.formatter import format_to_html
56from trac.wiki.macros import WikiMacroBase
57
58
59class 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.items()
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            {{{#!CommitTicketReference repository="%s" revision="%s"
214            %s
215            }}}""") % (revstring, drev, repos.reponame, rev,
216                       changeset.message.strip())
217
218    def _update_tickets(self, tickets, changeset, comment, date):
219        """Update the tickets with the given comment."""
220        authname = self._authname(changeset)
221        perm = PermissionCache(self.env, authname)
222        for tkt_id, cmds in tickets.items():
223            self.log.debug("Updating ticket #%d", tkt_id)
224            save = False
225            try:
226                with self.env.db_transaction:
227                    ticket = Ticket(self.env, tkt_id)
228                    ticket_perm = perm(ticket.resource)
229                    for cmd in cmds:
230                        if cmd(ticket, changeset, ticket_perm) is not False:
231                            save = True
232                    if save:
233                        ticket.save_changes(authname, comment, date)
234                if save:
235                    self._notify(ticket, date, changeset.author, comment)
236            except Exception as e:
237                self.log.error("Unexpected error while processing ticket "
238                               "#%s: %s", tkt_id, exception_to_unicode(e))
239
240    def _notify(self, ticket, date, author, comment):
241        """Send a ticket update notification."""
242        if not self.notify:
243            return
244        event = TicketChangeEvent('changed', ticket, date, author, comment)
245        try:
246            NotificationSystem(self.env).notify(event)
247        except Exception as e:
248            self.log.error("Failure sending notification on change to "
249                           "ticket #%s: %s", ticket.id,
250                           exception_to_unicode(e))
251
252    def _get_functions(self):
253        """Create a mapping from commands to command functions."""
254        functions = {}
255        for each in dir(self):
256            if not each.startswith('cmd_'):
257                continue
258            func = getattr(self, each)
259            for cmd in getattr(self, 'commands_' + each[4:], '').split():
260                functions[cmd] = func
261        return functions
262
263    def _authname(self, changeset):
264        """Returns the author of the changeset, normalizing the casing if
265        [trac] ignore_author_case is true."""
266        return changeset.author.lower() \
267               if self.env.config.getbool('trac', 'ignore_auth_case') \
268               else changeset.author
269
270    # Command-specific behavior
271    # The ticket isn't updated if all extracted commands return False.
272
273    def cmd_close(self, ticket, changeset, perm):
274        authname = self._authname(changeset)
275        if self.check_perms and 'TICKET_MODIFY' not in perm:
276            self.log.info("%s doesn't have TICKET_MODIFY permission for #%d",
277                          authname, ticket.id)
278            return False
279        ticket['status'] = 'closed'
280        ticket['resolution'] = 'fixed'
281        if not ticket['owner']:
282            ticket['owner'] = authname
283
284    def cmd_refs(self, ticket, changeset, perm):
285        if self.check_perms and 'TICKET_APPEND' not in perm:
286            self.log.info("%s doesn't have TICKET_APPEND permission for #%d",
287                          self._authname(changeset), ticket.id)
288            return False
289
290
291class CommitTicketReferenceMacro(WikiMacroBase):
292    _domain = 'messages'
293    _description = cleandoc_(
294    """Insert a changeset message into the output.
295
296    This macro must be called using wiki processor syntax as follows:
297    {{{
298    {{{
299    #!CommitTicketReference repository="reponame" revision="rev"
300    }}}
301    }}}
302    where the arguments are the following:
303     - `repository`: the repository containing the changeset
304     - `revision`: the revision of the desired changeset
305    """)
306
307    ticket_re = CommitTicketUpdater.ticket_re
308
309    def expand_macro(self, formatter, name, content, args=None):
310        args = args or {}
311        reponame = args.get('repository') or ''
312        rev = args.get('revision')
313        repos = RepositoryManager(self.env).get_repository(reponame)
314        try:
315            changeset = repos.get_changeset(rev)
316        except Exception:
317            message = content
318            resource = Resource('repository', reponame)
319        else:
320            message = changeset.message
321            rev = changeset.rev
322            resource = repos.resource
323        if formatter.context.resource.realm == 'ticket':
324            resource_id = as_int(formatter.context.resource.id)
325            if not resource_id or not any(int(tkt_id) == resource_id
326                       for tkt_id in self.ticket_re.findall(message)):
327                return tag.p(_("(The changeset message doesn't reference "
328                               "this ticket)"), class_='hint')
329        if ChangesetModule(self.env).wiki_format_messages:
330            return tag.div(format_to_html(self.env,
331                formatter.context.child('changeset', rev, parent=resource),
332                message, escape_newlines=True), class_='message')
333        else:
334            return tag.pre(message, class_='message')
335