PageRenderTime 21ms CodeModel.GetById 11ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/web/wiki/macros/__init__.py

https://bitbucket.org/prologic/circuits/
Python | 56 lines | 37 code | 15 blank | 4 comment | 12 complexity | 54a079e6b03a103fbe603d1a4c66a234 MD5 | raw file
 1"""Macro
 2
 3Macro support and dispatcher
 4"""
 5
 6import os
 7from inspect import getmembers, getmodule, isfunction
 8
 9from creoleparser import parse_args
10
11
12class Macro(object):
13
14    def __init__(self, name, arg_string, body, isblock):
15        super(Macro, self).__init__()
16
17        self.name = name
18        self.arg_string = arg_string
19        self.body = body
20        self.isblock = isblock
21
22
23def dispatcher(name, arg_string, body, isblock, environ):
24    if name in environ["macros"]:
25        macro = Macro(name, arg_string, body, isblock)
26        args, kwargs = parse_args(arg_string)
27        try:
28            return environ["macros"][name](macro, environ, *args, **kwargs)
29        except Exception, e:
30            return "ERROR: Error while executing macro %r (%s)" % (name, e)
31    else:
32        return "Macro not found!"
33
34
35def loadMacros():
36    path = os.path.abspath(os.path.dirname(__file__))
37    p = lambda x: os.path.splitext(x)[1] == ".py"
38    modules = [x for x in os.listdir(path) if p(x) and not x == "__init__.py"]
39
40    macros = {}
41
42    for module in modules:
43        name, _ = os.path.splitext(module)
44
45        moduleName = "%s.%s" % (__package__, name)
46        m = __import__(moduleName, globals(), locals(), __package__)
47
48        p = lambda x: isfunction(x) and getmodule(x) is m
49        for name, function in getmembers(m, p):
50            name = name.replace("_", "-")
51            try:
52                macros[name] = function
53            except Exception:
54                continue
55
56    return macros