summaryrefslogtreecommitdiff
path: root/patchwork/templatetags/syntax.py
blob: 2a4164d6e9b244587bc09d13ca223f8479626593 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Patchwork - automated patch tracking system
# Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
#
# This file is part of the Patchwork package.
#
# Patchwork is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Patchwork is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Patchwork; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

from __future__ import absolute_import

import re

from django import template
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.six.moves import map


register = template.Library()


def _compile(t):
    (r, str) = t
    return (re.compile(r, re.M | re.I), str)

_patch_span_res = list(map(_compile, [
    ('^(Index:?|diff|\-\-\-|\+\+\+|\*\*\*) .*$', 'p_header'),
    ('^\+.*$', 'p_add'),
    ('^-.*$', 'p_del'),
    ('^!.*$', 'p_mod'),
]))

_patch_chunk_re = \
    re.compile('^(@@ \-\d+(?:,\d+)? \+\d+(?:,\d+)? @@)(.*)$', re.M | re.I)

_comment_span_res = list(map(_compile, [
    ('^\s*Signed-off-by: .*$', 'signed-off-by'),
    ('^\s*Acked-by: .*$', 'acked-by'),
    ('^\s*Nacked-by: .*$', 'nacked-by'),
    ('^\s*Tested-by: .*$', 'tested-by'),
    ('^\s*Reviewed-by: .*$', 'reviewed-by'),
    ('^\s*From: .*$', 'from'),
    ('^\s*&gt;.*$', 'quote'),
]))

_span = '<span class="%s">%s</span>'


@register.filter
def patchsyntax(patch):
    content = escape(patch.content).replace('\r\n', '\n')

    for (r, cls) in _patch_span_res:
        content = r.sub(lambda x: _span % (cls, x.group(0)), content)

    content = _patch_chunk_re.sub(
        lambda x:
        _span % ('p_chunk', x.group(1)) + ' ' +
        _span % ('p_context', x.group(2)),
        content)

    return mark_safe(content)


@register.filter
def commentsyntax(comment):
    content = escape(comment.content)

    for (r, cls) in _comment_span_res:
        content = r.sub(lambda x: _span % (cls, x.group(0)), content)

    return mark_safe(content)