Advertisement
olemis

CTU

Jan 15th, 2014
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.33 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009 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 http://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 http://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. from __future__ import with_statement
  39.  
  40. from datetime import datetime
  41. import re
  42.  
  43. from genshi.builder import tag
  44.  
  45. from trac.config import BoolOption, Option
  46. from trac.core import Component, implements
  47. from trac.perm import PermissionCache
  48. from trac.resource import Resource
  49. from trac.ticket import Ticket
  50. from trac.ticket.notification import TicketNotifyEmail
  51. from trac.util.datefmt import utc
  52. from trac.util.text import exception_to_unicode
  53. from trac.util.translation import cleandoc_
  54. from trac.versioncontrol import IRepositoryChangeListener, RepositoryManager
  55. from trac.versioncontrol.web_ui.changeset import ChangesetModule
  56. from trac.wiki.formatter import format_to_html
  57. from trac.wiki.macros import WikiMacroBase
  58.  
  59. from multiproduct.env import ProductEnvironment
  60.  
  61.  
  62. class CommitTicketUpdater(Component):
  63.     """Update tickets based on commit messages.
  64.  
  65.    This component hooks into changeset notifications and searches commit
  66.    messages for text in the form of:
  67.    {{{
  68.    command PREFIX-1
  69.    command PREFIX-1, PREFIX-2
  70.    command PREFIX-1 & PREFIX-2
  71.    command PREFIX-1 and PREFIX-2
  72.    }}}
  73.  
  74.    Instead of the short-hand syntax "PREFIX-1", "product:PREFIX:ticket:1" and
  75.    PREFIX->ticket:1 can be used as well,
  76.    e.g.:
  77.    {{{
  78.    command product:PREFIX:ticket:1
  79.    command product:PREFIX:ticket:1, product:PREFIX:ticket:2
  80.    command product:PREFIX:ticket:1 & product:PREFIX:ticket:2
  81.    command product:PREFIX:ticket:1 and product:PREFIX:ticket:2
  82.    command PREFIX->ticket:1
  83.    command PREFIX->ticket:1, PREFIX->ticket:2
  84.    command PREFIX->ticket:1 & PREFIX->ticket:2
  85.    command PREFIX->ticket:1 and PREFIX->ticket:2
  86.    }}}
  87.  
  88.    In addition, issue or bug can be used 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 = r'(?:ticket|issue|bug):'
  142.     product_prefix = r'\w+' # FIXME : Relax alphanumeric prefix constraint ?
  143.     # Note: _ marks locations where group might be needed (depends on context)
  144.     local_ticket_ref = ticket_prefix + r'(_[0-9]+)'
  145.     jira_ticket_ref = r'(_%s)-(_[0-9]+)' % (product_prefix,)
  146.     short_ticket_ref = r'(_%s)->%s' % (product_prefix, local_ticket_ref)
  147.     long_ticket_ref = r'product:(_%s):%s|' \
  148.                        'product:"(_[^:"]+):%s"' % (product_prefix,
  149.                                                    local_ticket_ref,
  150.                                                    local_ticket_ref)
  151.     ticket_reference = r'(?:%s)|(?:%s)|(?:%s)' % (jira_ticket_ref.replace('_',
  152.                                                                           '?:'),
  153.                                                   short_ticket_ref.replace('_',
  154.                                                                            '?:'),
  155.                                                   long_ticket_ref.replace('_',
  156.                                                                           '?:'))
  157.     ticket_command = (r'(?P<action>[A-Za-z]+)\s*'
  158.                       r'(?P<ticket>(?:%s)(?:(?:[, &]*|[ ]?and[ ]?)(?:%s))*)' %
  159.                       (ticket_reference, ticket_reference))
  160.  
  161.     @property
  162.     def command_re(self):
  163.         (begin, end) = (re.escape(self.envelope[0:1]),
  164.                         re.escape(self.envelope[1:2]))
  165.         return re.compile(begin + self.ticket_command + end)
  166.  
  167.     ticket_re = r'(?:%s)|(?:%s)|(?:%s)' % (jira_ticket_ref.replace('_', ''),
  168.                                            short_ticket_ref.replace('_', ''),
  169.                                            long_ticket_ref.replace('_', ''))
  170.  
  171.     ticket_re = re.compile(ticket_re)
  172.     _last_cset_id = None
  173.  
  174.     # IRepositoryChangeListener methods
  175.  
  176.     def changeset_added(self, repos, changeset):
  177.         self.log.debug('CommitTicketUpdater : Added %s in %s',
  178.                        changeset.rev, repos.name)
  179.         if self._is_duplicate(changeset):
  180.             return
  181.         tickets = self._parse_message(changeset.message)
  182.         self.log.debug('CommitTicketUpdater : %d tickets adding %s in %s',
  183.                        len(tickets), changeset.rev, repos.name)
  184.         comment = self.make_ticket_comment(repos, changeset)
  185.         self.log.debug('CommitTicketUpdater : Processing %d tickets : %s',
  186.                        len(tickets), tickets.keys())
  187.         self._update_tickets(tickets, changeset, comment,
  188.                              datetime.now(utc))
  189.         self.log.debug('CommitTicketUpdater : Added %s in %s ... ok',
  190.                        changeset.rev, repos.name)
  191.  
  192.     def changeset_modified(self, repos, changeset, old_changeset):
  193.         self.log.debug('CommitTicketUpdater : Modified %s in %s',
  194.                        changeset.rev, repos.name)
  195.         if self._is_duplicate(changeset):
  196.             return
  197.         tickets = self._parse_message(changeset.message)
  198.         old_tickets = {}
  199.         if old_changeset is not None:
  200.             old_tickets = self._parse_message(old_changeset.message)
  201.         tickets = dict(each for each in tickets.iteritems()
  202.                        if each[0] not in old_tickets)
  203.         self.log.debug('CommitTicketUpdater : %d tickets modifying %s in %s',
  204.                        len(tickets), len(tickets), changeset.rev, repos.name)
  205.         comment = self.make_ticket_comment(repos, changeset)
  206.         self._update_tickets(tickets, changeset, comment,
  207.                              datetime.now(utc))
  208.         self.log.debug('CommitTicketUpdater : Modified %s in %s ... ok',
  209.                        changeset.rev, repos.name)
  210.  
  211.     def _is_duplicate(self, changeset):
  212.         # Avoid duplicate changes with multiple scoped repositories
  213.         cset_id = (changeset.rev, changeset.message, changeset.author,
  214.                    changeset.date)
  215.         if cset_id != self._last_cset_id:
  216.             self._last_cset_id = cset_id
  217.             return False
  218.         return True
  219.  
  220.     def _parse_message(self, message):
  221.         """Parse the commit message and return the ticket references."""
  222.         cmd_groups = self.command_re.findall(message)
  223.         functions = self._get_functions()
  224.         tickets = {}
  225.         for cmd, tkts in cmd_groups:
  226.             cmd = cmd.lower()
  227.             func = functions.get(cmd)
  228.             if not func and self.commands_refs.strip() == '<ALL>':
  229.                 func = self.cmd_refs
  230.             if func:
  231.                 _tkts = (filter(None, match)
  232.                          for match in self.ticket_re.findall(tkts))
  233.                 for pid, tkt_id in _tkts:
  234.                     tickets.setdefault((pid, int(tkt_id)), {})[func.__name__] = func
  235.         return dict([k, v.values()] for k,v in tickets.iteritems())
  236.  
  237.     def make_ticket_comment(self, repos, changeset):
  238.         """Create the ticket comment from the changeset data."""
  239.         revstring = str(changeset.rev)
  240.         if repos.reponame:
  241.             revstring += '/' + repos.reponame
  242.         return """\
  243. In [changeset:"%s"]:
  244. {{{
  245. #!CommitTicketReference repository="%s" revision="%s"
  246. %s
  247. }}}""" % (revstring, repos.reponame, changeset.rev, changeset.message.strip())
  248.  
  249.     def _update_tickets(self, tickets, changeset, comment, date):
  250.         """Update the tickets with the given comment."""
  251.         perms_pool = {}
  252.         for (pid, tkt_id), cmds in tickets.iteritems():
  253.             try:
  254.                 save = False
  255.                 try:
  256.                     env = ProductEnvironment(self.env, pid)
  257.                 except LookupError:
  258.                     self.env.log.warning("Changeset %s: skip #%d in unknown "
  259.                                          "product '%s'.", changeset.rev,
  260.                                          tkt_id, pid)
  261.                     continue
  262.                 env.log.debug("Updating ticket #%d (%s)", tkt_id, pid)
  263.                 author = changeset.author
  264.                 with env.db_transaction:
  265.                     ticket = Ticket(env, tkt_id)
  266.                     if pid not in perms_pool:
  267.                         perms_pool[pid] = perm = PermissionCache(env, author)
  268.                     else:
  269.                         perm = perms_pool[pid]
  270.                     ticket_perm = perm(ticket.resource)
  271.                     for cmd in cmds:
  272.                         if cmd(ticket, changeset, ticket_perm) is not False:
  273.                             save = True
  274.                     if save:
  275.                         ticket.save_changes(author, comment, date)
  276.                 if save:
  277.                     self._notify(ticket, date)
  278.             except Exception, e:
  279.                 self.log.error("Unexpected error while processing ticket "
  280.                                "#%s: %s", tkt_id, exception_to_unicode(e))
  281.  
  282.     def _notify(self, ticket, date):
  283.         """Send a ticket update notification."""
  284.         do_notify = self.notify if ticket.env is self.env \
  285.                                 else CommitTicketUpdater(ticket.env).notify
  286.  
  287.         if not do_notify:
  288.             return
  289.         try:
  290.             tn = TicketNotifyEmail(ticket.env)
  291.             tn.notify(ticket, newticket=False, modtime=date)
  292.         except Exception, e:
  293.             ticket.env.log.error("Failure sending notification on change to "
  294.                                  "ticket #%s: %s", ticket.id,
  295.                                  exception_to_unicode(e))
  296.  
  297.     def _get_functions(self):
  298.         """Create a mapping from commands to command functions."""
  299.         functions = {}
  300.         for each in dir(self):
  301.             if not each.startswith('cmd_'):
  302.                 continue
  303.             func = getattr(self, each)
  304.             for cmd in getattr(self, 'commands_' + each[4:], '').split():
  305.                 functions[cmd] = func
  306.         return functions
  307.  
  308.     # Command-specific behavior
  309.     # The ticket isn't updated if all extracted commands return False.
  310.  
  311.     def cmd_close(self, ticket, changeset, perm):
  312.         if self.check_perms and not 'TICKET_MODIFY' in perm:
  313.             self.log.info("%s doesn't have TICKET_MODIFY permission for #%d",
  314.                           changeset.author, ticket.id)
  315.             return False
  316.         ticket['status'] = 'closed'
  317.         ticket['resolution'] = 'fixed'
  318.         if not ticket['owner']:
  319.             ticket['owner'] = changeset.author
  320.  
  321.     def cmd_refs(self, ticket, changeset, perm):
  322.         if self.check_perms and not 'TICKET_APPEND' in perm:
  323.             self.log.info("%s doesn't have TICKET_APPEND permission for #%d",
  324.                           changeset.author, ticket.id)
  325.             return False
  326.  
  327.  
  328. class CommitTicketReferenceMacro(WikiMacroBase):
  329.     _domain = 'messages'
  330.     _description = cleandoc_(
  331.     """Insert a changeset message into the output.
  332.  
  333.    This macro must be called using wiki processor syntax as follows:
  334.    {{{
  335.    {{{
  336.    #!CommitTicketReference repository="reponame" revision="rev"
  337.    }}}
  338.    }}}
  339.    where the arguments are the following:
  340.     - `repository`: the repository containing the changeset
  341.     - `revision`: the revision of the desired changeset
  342.    """)
  343.  
  344.     def expand_macro(self, formatter, name, content, args={}):
  345.         reponame = args.get('repository') or ''
  346.         rev = args.get('revision')
  347.         repos = RepositoryManager(self.env).get_repository(reponame)
  348.         try:
  349.             changeset = repos.get_changeset(rev)
  350.             message = changeset.message
  351.             rev = changeset.rev
  352.             resource = repos.resource
  353.         except Exception:
  354.             message = content
  355.             resource = Resource('repository', reponame)
  356.         if formatter.context.resource.realm == 'ticket':
  357.             try:
  358.                 product = self.env.product
  359.             except AttributeError:
  360.                 # Skip silently on global environment
  361.                 pass
  362.             else:
  363.                 # ... and enforce constraint in product context
  364.                 cur_tkt = (product.prefix, int(formatter.context.resource.id))
  365.                 ticket_re = CommitTicketUpdater.ticket_re
  366.                 _tkts = (filter(None, match)
  367.                          for match in ticket_re.findall(message))
  368.                 if not any((pid, int(tkt_id)) == cur_tkt
  369.                            for pid, tkt_id in _tkts):
  370.                     return tag.p("(The changeset message doesn't reference this "
  371.                                  "ticket)", class_='hint')
  372.         if ChangesetModule(self.env).wiki_format_messages:
  373.             return tag.div(format_to_html(self.env,
  374.                 formatter.context.child('changeset', rev, parent=resource),
  375.                 message, escape_newlines=True), class_='message')
  376.         else:
  377.             return tag.pre(message, class_='message')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement