##
## Copyright (c) 2006 Jason Dillon
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
##     http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##

##
## $Id: jiralinker.py 22 2006-04-15 04:49:47Z user57 $
##

import re

from p4spam import config

JIRA_ISSUE_ID_RE = re.compile(r'([^-_.]?)\b([a-zA-Z0-9]+-[0-9]+)\b([^-_.]?)')

INVALID_PREFIXES = ('_', '.')
INVALID_SUFFIXES = ('_', '.')

# JIRA_BROWSE_URL is pulled from config

def makelink(match):
    (before, jid, after) = match.groups()
    
    # Detect invalid prefixes
    s = match.start(0)
    if s > 0:
        if match.string[s - 1] in INVALID_PREFIXES:
            return "%s%s%s" % (before, jid, after)
    
    # Detect invalid suffixes
    l = len(match.string)
    e = match.end(0)
    if e < l:
        if match.string[e] in INVALID_SUFFIXES:
            return "%s%s%s" % (before, jid, after)
    
    url = config.JIRA_BROWSE_URL % jid
    return '%s<a href="%s">%s</a>%s' % (before, url, jid, after)
    
def render(line):
    if config.JIRA_BROWSE_URL != None:
        line = JIRA_ISSUE_ID_RE.sub(makelink, line)
    return line