def render_template(template_file,data): from htmltmpl import TemplateManager, TemplateProcessor mgr = TemplateManager() template = mgr.prepare(template_file) tproc = TemplateProcessor(global_vars=1) for key in data.keys(): tproc.set(key,data[key]) print tproc.process(template)
def status_connections(root, which): connections = honeyd.status_connections(which.lower()) if not len(connections): return "There are currently no active %s connections." % which.upper() for connection in connections: id = "%s,%s,%d,%s,%d" % (which.lower(), connection['src'], connection['sport'], connection['dst'], connection['dport']) connection['id'] = urllib.quote(id) template = TemplateManager().prepare(root + "/templates/status_connections.tmpl") tproc = TemplateProcessor(0) tproc.set("title", "Active %s Connections" % which.upper()) tproc.set( "explanation", "This table shows the currently active %s connections" % which.upper()) tproc.set("Connections", connections) content = tproc.process(template) return content
def stats_table(root): raw_stats = honeyd.stats_network() stats = [] # Convert the dictionary into something that the template manager # can understand. for key in raw_stats.keys(): minute = humanize(raw_stats[key][0], '/s') hour = humanize(raw_stats[key][1], '/s') day = humanize(raw_stats[key][2], '/s') stats.append({"name": key, "minute": minute, "hour": hour, "day": day}) template = TemplateManager().prepare(root + "/templates/status_stats.tmpl") tproc = TemplateProcessor(0) tproc.set("title", "Honeyd Statistics") tproc.set("explanation", ("This table shows current statistics collected " "by Honeyd.")) tproc.set("Stats", stats) content = tproc.process(template) return content
def stats_table(root): raw_stats = honeyd.stats_network() stats = [] # Convert the dictionary into something that the template manager # can understand. for key in raw_stats.keys(): minute = humanize(raw_stats[key][0], '/s') hour = humanize(raw_stats[key][1], '/s') day = humanize(raw_stats[key][2], '/s') stats.append({ "name" : key, "minute" : minute, "hour" : hour, "day" : day }) template = TemplateManager().prepare(root + "/templates/status_stats.tmpl") tproc = TemplateProcessor(0) tproc.set("title", "Honeyd Statistics") tproc.set("explanation",("This table shows current statistics collected " "by Honeyd.")) tproc.set("Stats", stats) content = tproc.process(template) return content
def template(self, file='setup.html'): """ overwrite the template function in cgi_app """ proc = TemplateProcessor() temp = TemplateManager(precompile=0).prepare("templates/%s" % file) for key in self.globals.keys(): proc.set(key,self.globals[key]) body = proc.process(temp) return body
def html_template(self,compiled_template,data={}): """ replaces a mode in htmltmpl """ from htmltmpl import TemplateManager, TemplateProcessor mgr = TemplateManager() tproc = TemplateProcessor(html_escape=0) for key in self.__globals__.keys(): tproc.set(key,self.__globals__[key]) for key in data.keys(): tproc.set(key,data[key]) return tproc.process(compiled_template)
def config_ips(root): ips = honeyd.config_ips() template = TemplateManager().prepare(root + "/templates/config_ip.tmpl") tproc = TemplateProcessor(0) tproc.set("title", "Bound IP addresses") tproc.set("explanation", "This table shows the IP addresses of the " + "currently configured virtual honeypots.") tproc.set("Ips", ips) content = tproc.process(template) return content
def config_ips(root): ips = honeyd.config_ips() template = TemplateManager().prepare(root + "/templates/config_ip.tmpl") tproc = TemplateProcessor(0) tproc.set("title", "Bound IP addresses") tproc.set( "explanation", "This table shows the IP addresses of the " + "currently configured virtual honeypots.") tproc.set("Ips", ips) content = tproc.process(template) return content
def main(self): while True: while self.dataReady("channels-inbox"): data = self.recv("channels-inbox") self.channels.append(data) while self.dataReady("feeds-inbox"): data = self.recv("feeds-inbox") self.feeds.append(data) while self.dataReady("posts-inbox"): data = self.recv("posts-inbox") self.posts.append(data) while self.dataReady("config-inbox"): data = self.recv("config-inbox") self.config = data mustStop, providerFinished = self.checkControl() if mustStop: self.send(mustStop,"signal") return if providerFinished is not None and self.config is not None: tproc = TemplateProcessor(html_escape=0) template = self.prepareTemplate() yield 1 self.fillTemplate(tproc) result = tproc.process(template) yield 1 self.send(self.getOutputFileName(), 'create-output') yield 1 self.send(result, "outbox") yield 1 self.send(producerFinished(self), "signal") if self.VERBOSE: print "File written %s" % self.getOutputFileName() return if not self.anyReady(): self.pause() yield 1
def main(self): while True: while self.dataReady("channels-inbox"): data = self.recv("channels-inbox") self.channels.append(data) while self.dataReady("feeds-inbox"): data = self.recv("feeds-inbox") self.feeds.append(data) while self.dataReady("posts-inbox"): data = self.recv("posts-inbox") self.posts.append(data) while self.dataReady("config-inbox"): data = self.recv("config-inbox") self.config = data mustStop, providerFinished = self.checkControl() if mustStop: self.send(mustStop, "signal") return if providerFinished is not None and self.config is not None: tproc = TemplateProcessor(html_escape=0) template = self.prepareTemplate() yield 1 self.fillTemplate(tproc) result = tproc.process(template) yield 1 self.send(self.getOutputFileName(), 'create-output') yield 1 self.send(result, "outbox") yield 1 self.send(producerFinished(self), "signal") if self.VERBOSE: print "File written %s" % self.getOutputFileName() return if not self.anyReady(): self.pause() yield 1
def html_template(self,template_file,data={}): """ replaces the variables in the template with values specified in a dictionary. uses the htmltmpl module. see the documentation for htmltmpl for more info. """ from htmltmpl import TemplateManager, TemplateProcessor mgr = TemplateManager() template = mgr.prepare("%s/%s" % (self.template_dir,template_file)) tproc = TemplateProcessor(html_escape=0) for key in self.__globals__.keys(): tproc.set(key,self.__globals__[key]) for key in data.keys(): tproc.set(key,data[key]) return tproc.process(template)
def template(self, template_file, data={}, nav=True): """ overwrite the template function in cgi_app """ from htmltmpl import TemplateCompiler, TemplateProcessor, TemplateManager # get the configuration self.GetConfigs(data) # get the navigation self.GetNavs(data) # set compilers, processors, and managers temp = TemplateManager(precompile=0).prepare("%s/%s" % (self.template_dir, template_file)) proc = TemplateProcessor() cmpl = TemplateCompiler() # set keys for key in self.__globals__.keys(): proc.set(key,self.__globals__[key]) # set vars for key in data.keys(): proc.set(key,data[key]) # make body to be put in to the string to be compiled try: body = proc.process(temp) except: body = '' # make string to compile tempStr = '' # add nav bars tempStr += open("%s/%s" % (self.template_dir, "inc/header.html")).read() tempStr += body tempStr += open("%s/%s" % (self.template_dir, "inc/footer.html")).read() # return a TemplateManager object return self.html_template(cmpl.compile_string(tempStr), data)
def status_connections(root, which): connections = honeyd.status_connections(which.lower()) if not len(connections): return "There are currently no active %s connections." % which.upper() for connection in connections: id = "%s,%s,%d,%s,%d" % (which.lower(), connection['src'], connection['sport'], connection['dst'], connection['dport']) connection['id'] = urllib.quote(id) template = TemplateManager().prepare(root + "/templates/status_connections.tmpl") tproc = TemplateProcessor(0) tproc.set("title", "Active %s Connections" % which.upper()) tproc.set("explanation", "This table shows the currently active %s connections" % which.upper()) tproc.set("Connections", connections) content = tproc.process(template) return content
{ "name" : "Janek", "age" : 67 }, { "name" : "Martin", "age" : 43 }, { "name" : "Viktor", "age" : 78 }, { "name" : "Marian", "age" : 90 }, { "name" : "Prokop", "age" : 23 }, { "name" : "Honzik", "age" : 46 }, { "name" : "Brudra", "age" : 64 }, { "name" : "Marek", "age" : 54 }, { "name" : "Peter", "age" : 42 }, { "name" : "Beda", "age" : 87 } ]) ####################################################### fill(tproc) tproc.process(template) tproc.reset() fill(tproc) tproc.process(template) tproc.reset() fill(tproc) output = tproc.process(template) if "out" in sys.argv: sys.stdout.write(output) sys.exit(0) res = open("%s.res" % TEST).read()
#!/usr/bin/env python import sys import gettext import locale sys.path.insert(0, "../..") from htmltmpl import TemplateManager, TemplateProcessor locale.setlocale(locale.LC_MESSAGES, "en_US") gettext.bindtextdomain("test", "./locale") gettext.textdomain("test") man = TemplateManager(precompile = 0, gettext = 1, debug = 1) tmpl = man.prepare("gettext.tmpl") tproc = TemplateProcessor(debug = 1) tproc.set("title", "Gettext test page") print(tproc.process(tmpl))
#mo = re.compile(r'(\w+)-(\w+)-(\w+)-(\w+)-(\w+)',re.I) #uuid = article_uuid[index_article_path].strip() #if mo.match(uuid): # tproc.set("uuid",uuid) #else: # print "UUID Not Match,please check" # sys.exit() updatetime = float(article_lastmodify[index_article_path].strip()) updatetime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(updatetime)) tproc.set("updatetime",updatetime) # save to file filename = "%s/index.html" % (out_html_dir) FILE = open(filename,"w") FILE.writelines(tproc.process(template)) FILE.close() #========== guestbook 留言板 ===============================# template = TemplateManager().prepare(guestbook_html_template) tproc = TemplateProcessor(html_escape=0) # template replace tproc.set("Menuitem", Menuitems) # save to file filename = "%s/guestbook.html" % (out_html_dir) FILE = open(filename,"w") FILE.writelines(tproc.process(template)) FILE.close()
class Easydoc: """ Autogenerate documentation from docstrings. This class provides all the functionality of easydoc. You can subclass it and override its processing methods module(), mclass() and method() to customize its behaviour. You also can easily use your own template to modify the output in any way you need. Output colors can be customized via parameters. """ def __init__(self, template, debug=0): """ Constructor. @header __init__(template, debug=0) @param template String containing template data. @param debug Enable or disable debugging messages. This optional parameter can be used to enable or disable debugging messages which are printed to stderr. By default debugging messages are disabled. """ self._debug = debug self._classes = [] self._functions = [] self._class = {} self._template = TemplateCompiler().compile_string(template) self._tproc = TemplateProcessor(html_escape=0) def process(self, module, bgcolor, textcolor, linkcolor, methodbg, with_hidden=0): """ Create documentation for a module. @header process(module, bgcolor, textcolor, linkcolor, with_hidden=0) @return String containing the resulting HTML documentation. @param module Filename of the module to document. The module must be specified as filename. The module is not imported nor executed, only parsed. @param bgcolor Set background color. Accepts any valid CSS color value. @param textcolor Set text color. Accepts any valid CSS color value. @param linkcolor Set color of hyperlinks. Accepts any valid CSS color value. @param with_hidden Do not exclude hidden sections from output. This optional parameter can be used to force inclusion of hidden sections in the resulting documentation. Hidden sections are by default not included. """ mdict = {} self._tproc.set("bgcolor", bgcolor) self._tproc.set("textcolor", textcolor) self._tproc.set("linkcolor", linkcolor) self._tproc.set("methodbg", methodbg) # Parse the module. ast = parser.suite(open(module).read()) module_info = easydocp.ModuleInfo(ast.totuple()) self.module(module_info.get_docstring()) # Class info. for mclass in module_info.get_class_names(): class_info = module_info.get_class_info(mclass) if self.mclass(mclass, class_info.get_docstring(), with_hidden): # The class should be included in the output. self._class["Methods"] = [] for method in class_info.get_method_names(): method_info = class_info.get_method_info(method) self.method(mclass, method, method_info.get_docstring(), with_hidden) self.DEB("Finished class: " + mclass) self._classes.append(copy.copy(self._class)) self._class.clear() self._tproc.set("Classes", self._classes) # Functions info. for function in module_info.get_function_names(): function_info = module_info.get_function_info(function) self.method("", function, function_info.get_docstring(), with_hidden) self._tproc.set("Functions", self._functions) return self._tproc.process(self._template) ############################################## # PRIVATE METHODS # ############################################## def module(self, doc): """ Process docstring of a module. @hidden """ short, detailed, statements = self.parse(doc) self.DEB("Module: short: " + short) self.DEB("Module: statements: " + pprint.pformat(statements)) self._tproc.set("short", short.strip()) self._tproc.set("Detailed", self.detailed(detailed)) # Statements. requires = [] for statement in statements: param, data = statement if param == "name": self._tproc.set("name", data.strip()) self.DEB("Module: name: " + data) elif param == "version": self._tproc.set("version", data.strip()) elif param == "website": self._tproc.set("website", data.strip()) elif param == "author-name": self._tproc.set("author-name", self.mangle(data)) elif param == "author-email": self._tproc.set("author-email", data.strip()) elif param == "license-name": self._tproc.set("license-name", data.strip()) elif param == "license-url": self._tproc.set("license-url", data.strip()) elif param == "require": requires.append({"require": self.mangle(data)}) else: self.warn("Unknown statement: " + param) self._tproc.set("Requires", requires) def mclass(self, name, doc, with_hidden=0): """ Process docstring of a class. @hidden """ short, detailed, statements = self.parse(doc) self.DEB("Class: " + name + ": short: " + short) self.DEB("Class: " + name + ": statements: " + \ pprint.pformat(statements)) self._class["name"] = name self._class["short"] = short.strip() self._class["Detailed"] = self.detailed(detailed) for statement in statements: param, data = statement if param == "hidden": if not with_hidden: self.DEB("Class: " + name + ": HIDDEN") return 0 else: self.warn("Unknown statement: " + param) else: return 1 def method(self, mclass, name, doc, with_hidden=0): """ Process docstring of a method. @hidden """ method = {} short, detailed, statements = self.parse(doc) if mclass: self.DEB("Method: " + name + ": short: " + short) self.DEB("Method: " + name + ": statements: " + \ pprint.pformat(statements)) else: self.DEB("Function: " + name + ": short: " + short) self.DEB("Function: " + name + ": statements: " + \ pprint.pformat(statements)) method["name"] = name method["class"] = mclass method["short"] = short.strip() method["Detailed"] = self.detailed(detailed) parameters = [] for statement in statements: param, data = statement if param == "hidden": if not with_hidden: self.DEB("Method: " + name + ": HIDDEN") return 0 elif param == "header": header = data.strip() header = re.sub(r"\s+", " ", header) method["header"] = header elif param == "return": method["return"] = self.mangle(data) elif param == "param": parameter = {} # Split the data into first line and rest. lines = data.splitlines(KEEP_NEWLINES) first_line = lines[0].strip() # Split the first line into name and short description # of the parameter. fsplit = first_line.split(" ", 1) if len(fsplit) == 2: pname, pshort = fsplit elif len(fsplit) == 1: pname = fsplit[0] pshort = "" else: pname = "" pshort = "" if len(lines) > 1: pdetailed = string.join(lines[1:]) else: pdetailed = "" self.DEB("Parameter: " + pname.strip()) parameter["name"] = pname.strip() parameter["short"] = pshort.strip() parameter["Detailed"] = self.detailed(pdetailed) parameters.append(parameter) else: self.warn("Unknown statement: " + param) else: method["Parameters"] = parameters if mclass: self._class["Methods"].append(method) else: self._functions.append(method) return 1 def parse(self, doc): """ Parse a docstring. Split the docstring into short description, detailed description and a list containing a tuple for every statement. The first element of the tuple is name of the statement, the second is the data of the statement. @hidden """ short = "" detailed = "" statements = [] if not doc: return short, detailed, statements doc = doc.replace("\"\"\"", "") rc = re.compile(r""" ^\s*(@)([-\w]+) """, re.VERBOSE | re.MULTILINE) tokens = rc.split(doc) len_tokens = len(tokens) i = 0 skip_param = 0 while 1: if i == len_tokens: break if skip_param: skip_param = 0 i += 2 continue token = tokens[i] if token == "@": skip_param = 1 param = tokens[i + 1] data = tokens[i + 2] statements.append((param, data)) else: if not short: lines = token.splitlines(KEEP_NEWLINES) short = lines[0] if len(lines) > 1: detailed = string.join(lines[1:]) i += 1 return short, detailed, statements def DEB(self, str): """ Print debugging message to stderr if debugging is enabled. @hidden """ if self._debug: print >> sys.stderr, str def warn(self, warning): """ Print a warning to stderr. @hidden """ print >> sys.stderr, warning def mangle(self, str): """ Strip leading and trailing whitespace. Convert URL to hyperlink. @hidden """ str = str.strip() return re.sub(r"\[ (http://.*?) \]", r'<a href="\1">\1</a>', str) def detailed(self, str): """ Process detailed descritpion. Split it into paragraphs at empty lines. Return list of the paragraphs. @hidden """ paragraphs = [] rc = re.compile(r"^\s*$", re.MULTILINE) # allow any whitespace for p in rc.split(str): if re.search(r"\S", p): paragraphs.append({"paragraph": self.mangle(p)}) return paragraphs
def summarize(): global success_counter, failure_counter, blow_counter, skip_counter global cur_name global report_entry_set, map_stats_entry_set print print 'Test Script: %s' % cur_name print 'Succeeded: %d' % success_counter print 'Failed: %d (%d blew exceptions)' \ % (failure_counter+blow_counter, blow_counter) print 'Skipped: %d' % skip_counter print # find whether we are in test root dir or one level up if os.path.exists(os.path.join("..", "SummaryReport.tmpl")): os.chdir("..") elif not os.path.exists("SummaryReport.tmpl"): raise "Could not find HTML template files." # Compile or load already precompiled template. template = TemplateManager().prepare("SummaryReport.tmpl") tproc = TemplateProcessor() # Set the title. mod = om.OpenModeller() tproc.set("om_version", mod.getVersion()) tproc.set("om_num_algs", mod.numAvailableAlgorithms()) # htmltmpl requires var name starting with uppercase (!?!) Entries = report_entry_set tproc.set("Entries", Entries) # get list of algorithms Algorithms = [] algList = mod.availableAlgorithms() for i in range(0, len(algList)): alg = {} alg["class"] = "a" alg["id"] = algList[i].id alg["name"] = algList[i].name Algorithms.append(alg) tproc.set("Algorithms", Algorithms) # write the processed template to disk summary_file = file("index.html", "w") summary_file.write(tproc.process(template)) summary_file.close() # Compile or load already precompiled template. template = TemplateManager().prepare("MapReport.tmpl") tproc = TemplateProcessor() # htmltmpl requires var name starting with uppercase (!?!) Mapstats = map_stats_entry_set tproc.set("Mapstats", Mapstats) # write the processed template to disk map_file = file("MapReport.html", "w") map_file.write(tproc.process(template)) map_file.close()
try: counter += 1 except: counter = 1 greeting = ("Welcome to the Honeyd Administration Interface." "You are visitor %d.<p>") % counter content = support.interface_table() content += "<p>" + support.stats_table(self.root) + "</p>\n" content += "<p>" + support.status_connections(self.root, "tcp") + "</p>\n" content += "<p>" + support.status_connections(self.root, "udp") + "</p>\n" side_content = ("<div class=graphs>" "<img height=155 width=484 src=/graphs/traffic_hourly.gif><br>" "<img height=155 width=484 src=/graphs/traffic_daily.gif>" "</div>") support.security_check(tproc) if message: tproc.set("message", message) tproc.set("greeting", greeting) tproc.set("content", content) tproc.set("side_content", side_content) tproc.set("uptime", support.uptime()) # Print the processed template. self.wfile.write(tproc.process(template))
"name": "Conner" }, { "name": "Maxtor" }]) insert_cur.close() # Select the products. products_cur = db.cursor() products_cur.execute(""" SELECT id, name FROM Products """) # Append product data in form of mappings (dictionaries) to the # products list. products = [] for i in range(products_cur.rowcount): products.append(products_cur.fetchone()) products_cur.close() db.close() # Assign the products list to template loop identifier 'Products'. # NOTE: htmltmpl automatically converts all the values # to strings using str(). tproc.set("Products", products) # Process the template and print the result. print(tproc.process(template))
#mo = re.compile(r'(\w+)-(\w+)-(\w+)-(\w+)-(\w+)',re.I) #uuid = article_uuid[index_article_path].strip() #if mo.match(uuid): # tproc.set("uuid",uuid) #else: # print "UUID Not Match,please check" # sys.exit() updatetime = float(article_lastmodify[index_article_path].strip()) updatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(updatetime)) tproc.set("updatetime", updatetime) # save to file filename = "%s/index.html" % (out_html_dir) FILE = open(filename, "w") FILE.writelines(tproc.process(template)) FILE.close() #========== guestbook 留言板 ===============================# template = TemplateManager().prepare(guestbook_html_template) tproc = TemplateProcessor(html_escape=0) # template replace tproc.set("Menuitem", Menuitems) # save to file filename = "%s/guestbook.html" % (out_html_dir) FILE = open(filename, "w") FILE.writelines(tproc.process(template)) FILE.close()
class Easydoc: """ Autogenerate documentation from docstrings. This class provides all the functionality of easydoc. You can subclass it and override its processing methods module(), mclass() and method() to customize its behaviour. You also can easily use your own template to modify the output in any way you need. Output colors can be customized via parameters. """ def __init__(self, template, debug=0): """ Constructor. @header __init__(template, debug=0) @param template String containing template data. @param debug Enable or disable debugging messages. This optional parameter can be used to enable or disable debugging messages which are printed to stderr. By default debugging messages are disabled. """ self._debug = debug self._classes = [] self._functions = [] self._class = {} self._template = TemplateCompiler().compile_string(template) self._tproc = TemplateProcessor(html_escape=0) def process(self, module, bgcolor, textcolor, linkcolor, methodbg, with_hidden=0): """ Create documentation for a module. @header process(module, bgcolor, textcolor, linkcolor, with_hidden=0) @return String containing the resulting HTML documentation. @param module Filename of the module to document. The module must be specified as filename. The module is not imported nor executed, only parsed. @param bgcolor Set background color. Accepts any valid CSS color value. @param textcolor Set text color. Accepts any valid CSS color value. @param linkcolor Set color of hyperlinks. Accepts any valid CSS color value. @param with_hidden Do not exclude hidden sections from output. This optional parameter can be used to force inclusion of hidden sections in the resulting documentation. Hidden sections are by default not included. """ mdict = {} self._tproc.set("bgcolor", bgcolor) self._tproc.set("textcolor", textcolor) self._tproc.set("linkcolor", linkcolor) self._tproc.set("methodbg", methodbg) # Parse the module. ast = parser.suite(open(module).read()) module_info = easydocp.ModuleInfo(ast.totuple()) self.module(module_info.get_docstring()) # Class info. for mclass in module_info.get_class_names(): class_info = module_info.get_class_info(mclass) if self.mclass(mclass, class_info.get_docstring(), with_hidden): # The class should be included in the output. self._class["Methods"] = [] for method in class_info.get_method_names(): method_info = class_info.get_method_info(method) self.method(mclass, method, method_info.get_docstring(), with_hidden) self.DEB("Finished class: " + mclass) self._classes.append(copy.copy(self._class)) self._class.clear() self._tproc.set("Classes", self._classes) # Functions info. for function in module_info.get_function_names(): function_info = module_info.get_function_info(function) self.method("", function, function_info.get_docstring(), with_hidden) self._tproc.set("Functions", self._functions) return self._tproc.process(self._template) ############################################## # PRIVATE METHODS # ############################################## def module(self, doc): """ Process docstring of a module. @hidden """ short, detailed, statements = self.parse(doc) self.DEB("Module: short: " + short) self.DEB("Module: statements: " + pprint.pformat(statements)) self._tproc.set("short", short.strip()) self._tproc.set("Detailed", self.detailed(detailed)) # Statements. requires = [] for statement in statements: param, data = statement if param == "name": self._tproc.set("name", data.strip()) self.DEB("Module: name: " + data) elif param == "version": self._tproc.set("version", data.strip()) elif param == "website": self._tproc.set("website", data.strip()) elif param == "author-name": self._tproc.set("author-name", self.mangle(data)) elif param == "author-email": self._tproc.set("author-email", data.strip()) elif param == "license-name": self._tproc.set("license-name", data.strip()) elif param == "license-url": self._tproc.set("license-url", data.strip()) elif param == "require": requires.append( {"require": self.mangle(data)} ) else: self.warn("Unknown statement: " + param) self._tproc.set("Requires", requires) def mclass(self, name, doc, with_hidden=0): """ Process docstring of a class. @hidden """ short, detailed, statements = self.parse(doc) self.DEB("Class: " + name + ": short: " + short) self.DEB("Class: " + name + ": statements: " + \ pprint.pformat(statements)) self._class["name"] = name self._class["short"] = short.strip() self._class["Detailed"] = self.detailed(detailed) for statement in statements: param, data = statement if param == "hidden": if not with_hidden: self.DEB("Class: " + name + ": HIDDEN") return 0 else: self.warn("Unknown statement: " + param) else: return 1 def method(self, mclass, name, doc, with_hidden=0): """ Process docstring of a method. @hidden """ method = {} short, detailed, statements = self.parse(doc) if mclass: self.DEB("Method: " + name + ": short: " + short) self.DEB("Method: " + name + ": statements: " + \ pprint.pformat(statements)) else: self.DEB("Function: " + name + ": short: " + short) self.DEB("Function: " + name + ": statements: " + \ pprint.pformat(statements)) method["name"] = name method["class"] = mclass method["short"] = short.strip() method["Detailed"] = self.detailed(detailed) parameters = [] for statement in statements: param, data = statement if param == "hidden": if not with_hidden: self.DEB("Method: " + name + ": HIDDEN") return 0 elif param == "header": header = data.strip() header = re.sub(r"\s+", " ", header) method["header"] = header elif param == "return": method["return"] = self.mangle(data) elif param == "param": parameter = {} # Split the data into first line and rest. lines = data.splitlines(KEEP_NEWLINES) first_line = lines[0].strip() # Split the first line into name and short description # of the parameter. fsplit = first_line.split(" ", 1) if len(fsplit) == 2: pname, pshort = fsplit elif len(fsplit) == 1: pname = fsplit[0] pshort = "" else: pname = "" pshort = "" if len(lines) > 1: pdetailed = string.join(lines[1:]) else: pdetailed = "" self.DEB("Parameter: " + pname.strip()) parameter["name"] = pname.strip() parameter["short"] = pshort.strip() parameter["Detailed"] = self.detailed(pdetailed) parameters.append(parameter) else: self.warn("Unknown statement: " + param) else: method["Parameters"] = parameters if mclass: self._class["Methods"].append(method) else: self._functions.append(method) return 1 def parse(self, doc): """ Parse a docstring. Split the docstring into short description, detailed description and a list containing a tuple for every statement. The first element of the tuple is name of the statement, the second is the data of the statement. @hidden """ short = "" detailed = "" statements = [] if not doc: return short, detailed, statements doc = doc.replace("\"\"\"", "") rc = re.compile(r""" ^\s*(@)([-\w]+) """, re.VERBOSE | re.MULTILINE) tokens = rc.split(doc) len_tokens = len(tokens) i = 0 skip_param = 0 while 1: if i == len_tokens: break if skip_param: skip_param = 0 i += 2 continue token = tokens[i] if token == "@": skip_param = 1 param = tokens[i + 1] data = tokens[i + 2] statements.append((param, data)) else: if not short: lines = token.splitlines(KEEP_NEWLINES) short = lines[0] if len(lines) > 1: detailed = string.join(lines[1:]) i += 1 return short, detailed, statements def DEB(self, str): """ Print debugging message to stderr if debugging is enabled. @hidden """ if self._debug: print >> sys.stderr, str def warn(self, warning): """ Print a warning to stderr. @hidden """ print >> sys.stderr, warning def mangle(self, str): """ Strip leading and trailing whitespace. Convert URL to hyperlink. @hidden """ str = str.strip() return re.sub(r"\[ (http://.*?) \]", r'<a href="\1">\1</a>', str) def detailed(self, str): """ Process detailed descritpion. Split it into paragraphs at empty lines. Return list of the paragraphs. @hidden """ paragraphs = [] rc = re.compile(r"^\s*$", re.MULTILINE) # allow any whitespace for p in rc.split(str): if re.search(r"\S", p): paragraphs.append( {"paragraph": self.mangle(p)} ) return paragraphs