Edgewall Software

MacroBazaar: TicketBox.3.py

File TicketBox.3.py, 4.4 KB (added by Shun-ichi Goto <gotoh@…>, 7 years ago)

Enhanced version of supporting dynamic variables.

Line 
1"""
2Display a box with some ticket links onto right of the page.
3Tickts are sorted and uniq'ed.
4
5Example:
6{{{
7[[TicketBox(#1,#7,#31)]]               ... list of tickets
8[[TicketBox(1,7,31)]]                  ... '#' char can be omitted
9[[TicketBox({1})]]                     ... expand report result as ticket list
10[[TicketBox([report:1])]]              ... alternate format of report
11[[TicketBox([report:9?name=val])]]     ... report with dynamic variable
12[[TicketBox({1),#50,{2},100)]]         ... convination of above
13[[TicketBox(500pt,{1})]]               ... with box width as 50 point
14[[TicketBox(200px,{1})]]               ... with box width as 200 pixel
15[[TicketBox(25%,{1})]]                 ... with box width as 25%
16[[TicketBox('Different Title',#1,#2)]] ... Use different title
17[[TicketBox(\"Other Title\",#1,#2)]]     ... likewise
18}}}
19
20[wiki:TracReports#AdvancedReports:DynamicVariables Dynamic Vaiables]
21is supported for report. Other variables can be specified like
22{{{[report:9?PRIORITY=high&COMPONENT=ui]}}}. Of course, the special
23variable '{{{$USER}}}' is available.
24"""
25
26## NOTE: CSS2 defines 'max-width' but it seems that only few browser
27##       support it. So I use 'width'. Any idea?
28
29import re
30import string
31
32## default style values
33styles = { "float": "right",
34           "background": "#f7f7f0",
35           "width": "",
36           }
37
38args_pat = [r"#?(?P<tktnum>\d+)",
39            r"{(?P<rptnum>\d+)}",
40            r"\[report:(?P<rptnum2>\d+)(?P<dv>\?.*)?\]",
41            r"(?P<width>\d+(pt|px|%))",
42            r"(?P<title1>'.*')",
43            r'(?P<title2>".*")']
44
45def uniq(x):
46    y=[]
47    for i in x:
48        if not y.count(i):
49            y.append(i)
50    return y
51
52def execute(hdf, txt, env):
53    if not txt:
54        txt = ''
55    items = []
56    title = "Tickets"
57    args_re = re.compile("^(?:" + string.join(args_pat, "|") + ")$")
58    for arg in [string.strip(s) for s in txt.split(',')]:
59        match = args_re.match(arg)
60        if not match:
61            env.log.debug('TicketBox: unknown arg: %s' % arg)
62            continue
63        elif match.group('title1'):
64            title = match.group('title1')[1:-1]
65        elif match.group('title2'):
66            title = match.group('title2')[1:-1]
67        elif match.group('width'):
68            styles['width'] = match.group('width')
69        elif match.group('tktnum'):
70            items.append(int(match.group('tktnum')))
71        elif match.group('rptnum') or match.group('rptnum2'):
72            num = match.group('rptnum') or match.group('rptnum2')
73            dv = {}
74            # username
75            dv['USER'] = hdf.getValue('trac.authname', 'anonymous')
76            if match.group('dv'):
77                for expr in string.split(match.group('dv')[1:], '&'):
78                    k, v = string.split(expr, '=')
79                    dv[k] = v
80            #env.log.debug('dynamic variables = %s' % dv)
81            db = env.get_db_cnx()
82            curs = db.cursor()
83            try:
84                curs.execute('SELECT sql FROM report WHERE id=%s' % num)
85                (sql,) = curs.fetchone()
86                # replace dynamic variables
87                for k, v in dv.iteritems():
88                    sql = re.sub(r'\$%s\b' % k, v, sql)
89                #env.log.debug('sql = %s' % sql)
90                curs.execute(sql)
91                for row in curs.fetchall():
92                    items.append(row['ticket'])
93            finally:
94                if not hasattr(env, 'get_cnx_pool'):
95                    # without db connection pool, we should close db.
96                    curs.close()
97                    db.close()
98    items = uniq(items)
99    items.sort()
100    html = ''
101    try:
102        # for trac 0.9 or later
103        from trac.wiki.formatter import wiki_to_oneliner
104        html = wiki_to_oneliner(string.join(["#%d" % c for c in items], ", "),
105                               env, env.get_db_cnx())
106    except:
107        # for trac 0.8.x
108        from trac.WikiFormatter import wiki_to_oneliner
109        html = wiki_to_oneliner(string.join(["#%d" % c for c in items], ", "),
110                                hdf, env, env.get_db_cnx())
111    if html != '':
112        style = string.join(["%s:%s" % (k,v) for k,v in styles.items() if v <> ""], "; ")
113        return '<fieldset class="ticketbox" style="%s"><legend>%s</legend>%s</fieldset>' % \
114               (style, title, html)
115    else:
116        return ''