Edgewall Software

MacroBazaar: autonav-trac-0.11.py

File autonav-trac-0.11.py, 2.1 KB (added by cboos, 5 years ago)

AutoNav? macro as an example of "new style macro" (i.e. single file plugin), for Trac 0.11

Line 
1# -*- coding: utf-8 -*-
2#
3# AutoNav macro for Trac 0.11
4#
5# Author: Anders Jansson <anders dot jansson at kastanj dot net>
6# License: BSD
7# Modified by:
8#   Andrew Stromnov <stromnov at gmail dot com>
9#   Christian Boos <cboos at neuf fr>
10
11from genshi.builder import tag
12
13from trac.core import *
14from trac.wiki.api import parse_args
15from trac.wiki.macros import WikiMacroBase
16from StringIO import StringIO
17
18__all__ = ['AutoNavMacro']
19
20
21class AutoNavMacro(WikiMacroBase):
22    """AutoNav finds all references in the wiki section to this Document
23
24    It then shows them in a sorted list.
25
26    Used with no arguments only produces a list from the database. Arguments
27    sent to AutoNav will be merged inside the list too. Separate the
28    arguments with comma.
29   
30    Example:
31    `[[AutoNav()]]`     -> only references
32   
33    `[[AutoNav(MyPage)]]` -> references merged and sorted with MyPage
34         
35    `[[AutoNav(MyPage, MyPageToo, MyPageThree)]]` -> references merged with MyPage, MyPageToo and MyPageThree
36    """
37   
38    def render_macro(self, formatter, name, args):
39        if formatter.context.resource != 'wiki':
40            return ''
41       
42        cursor = formatter.db.cursor()
43       
44        # get the refere page name
45        thispage = formatter.context.id
46       
47        # process arguments
48        pages, kw = parse_args(args)
49       
50        # query to get the latest version of a page
51        query = """
52            SELECT w1.name
53            FROM wiki w1,
54                (
55                    SELECT name, MAX(version) AS version
56                    FROM wiki
57                    GROUP BY name
58                ) w2
59            WHERE
60                w1.version = w2.version AND
61                w1.name = w2.name AND
62                w1.text LIKE \'%%%s%%\' 
63            ORDER BY w1.name""" % thispage
64       
65        # TODO: use named parameters
66        cursor.execute(query)
67       
68        # for each answer store in page
69        for page, in cursor:
70            if page == thispage:
71                continue
72            pages.append(page)
73       
74        pages.sort()
75       
76        # get the references to each list
77        def link(page):
78            return tag.a(page, href=formatter.href.wiki(page))
79       
80        return tag(tag.strong('Navigation:'), '(',
81                   [[link(page), ', '] for page in pages[:-2]],
82                   link(page), ')')