
from genshi.builder import tag

from trac.core import *
from trac.util.text import shorten_line
from trac.wiki.api import IWikiSyntaxProvider


#This is a combination of the revision_links sample plugin and ChangesetModule from web_ui/changeset.py

class ViewMTNRevisionLinks(Component):
    """Adds a few more ways to refer to changesets."""

    implements(IWikiSyntaxProvider)

    KEYWORDS = ['[Rr]ev(?:ision)?', '[Cc]hangeset']

    CHANGESET_ID = r"(?:[a-fA-F\d]{40})" # only hexa ids with the right length

    # IWikiSyntaxProvider methods

    def get_wiki_syntax(self):

        yield (
            r"r?%s" % (self.CHANGESET_ID),
            lambda x, y, z:
            self._format_revision_link(x, 'changeset',
                y[0] == 'r' and y[1:] or y, y, z))

        def revlink(f, match, fullmatch):
            rev = match.split(' ', 1)[1] # ignore keyword
            return self._format_revision_link(f, 'changeset', rev, rev,
                                              fullmatch)
        yield (r"!?(?:%s)\s+%s" % ("|".join(self.KEYWORDS),
                                   self.CHANGESET_ID),
               revlink)

    def get_link_resolvers(self):
        yield ('revision', self._format_revision_link)


    def _get_viewmtn_url(self, rev):
        return "/viewmtn/revision/info/%s" % rev

    def _format_revision_link(self, formatter, ns, rev, label, fullmatch=None):
        return tag.a(label, class_="changeset",
		 title=shorten_line(rev),
		 href=self._get_viewmtn_url(rev))

