# -- mantis_tickets_link.py
#
# Author: Christian Boos <cboos@bct-technology.com>
# Modified: techtonik <techtonik@rainforce.org>
# Date:   2008-05-29
# License: Trac (modified BSD)
# ----------------------------------------------------------------------------

"""Link tickets referenced in commits to external Mantis bugtracker"""

from trac.core import *
from trac.wiki import IWikiSyntaxProvider, Formatter

MANTIS_FMT = "http://bugs.yourdomain.com/view.php?id=%d"

class MantisTicketSyntaxProvider(Component):
    """Link references like "Mantis #xxxxxx" in commits directly to Mantis"""

    implements(IWikiSyntaxProvider)

    def get_wiki_syntax(self):
        """Return an iterable that provides additional wiki syntax.

        Additional wiki syntax correspond to a pair of (regexp, cb),
        the `regexp` for the additional syntax and the callback `cb`
        which will be called if there's a match.
        That function is of the form cb(formatter, ns, match).
        """        
        yield (
            r"(?i)(?P<mbt_label>mantis *#)(?P<mbt_number>\d+)",
            lambda x, y, z: self._format_link(x, y, z.group("mbt_number"), z.group("mbt_label")))

    def get_link_resolvers(self):
        """Return an iterable over (namespace, formatter) tuples.

        Each formatter should be a function of the form
        fmt(formatter, ns, target, label), and should
        return some HTML fragment.
        The `label` is already HTML escaped, whereas the `target` is not.
        """
        return [('mantis', self._format_link)]

    def _format_link(self, formatter, ns, target, label, fullmatch=None):
        try:
            number = int(target)
            href = MANTIS_FMT % number
            text = target == label and "#%07d" % number or "%s%07d" % (label, number)
            return formatter._make_ext_link(href, text, 'Mantis Bug #%d' % number)
        except ValueError:
            return label
