#!/usr/bin/python2 import yaml import os import jinja2 import optparse from utils import filters, tests, globals class Renderer: def __init__(self, output_dir, format): template_dir = os.path.join( os.path.dirname(os.path.abspath(os.path.realpath(__file__))), 'templates') self.env = jinja2.Environment( trim_blocks = format == "dokuwiki", loader = jinja2.FileSystemLoader(template_dir)) self.env.filters.update(filters) self.env.tests.update(tests) self.env.globals.update(globals) self.output_dir = output_dir self.templates = {} self.format = format def _render(self, template, filename, **kwargs): if template not in self.templates: self.templates[template] = self.env.get_template(template) with open(os.path.join(self.output_dir, filename), "w+") as output: output.write(self.templates[template].render(**kwargs)) def host(self, host, hostdata): print("Rendering: %s" % (host)) hostdata['url'] = "%s.%s" % (host, self.format) self._render('host.%s' % (self.format), hostdata['url'], **hostdata) def index(self, data): indexpage = "index.%s" % (self.format) print("Rendering: index") self._render(indexpage, indexpage, hosts=data) def load_yaml(*args): with open(os.path.join(*args)) as infile: return yaml.load(infile) def main(): basename = os.path.dirname(os.path.realpath(__file__)) optparser = optparse.OptionParser() optparser.add_option( "-o", "--output", help="write rendered hostinfo files DEST_DIR", metavar="DEST_DIR", type="string", default=os.path.join(basename,"htdocs")) optparser.add_option( "-s", "--source", help="read yaml encoded hostinfo data from SRC_DIR", metavar="SRC_DIR", type="string", default=os.path.join(basename,"data")) optparser.add_option( "-f", "--format", help="output format that is produce: html or dokuwiki" "[default: %default]", type="choice", choices=["html", "dokuwiki"], default="html" ) (options, _ ) = optparser.parse_args() renderer = Renderer(options.output, options.format) hosts = load_yaml(options.source, "metadata", "hosts") data = [] for host in sorted(hosts['hosts']): hostdata = load_yaml(options.source, host) renderer.host(host, hostdata) data.append(hostdata) renderer.index(data) if __name__ == '__main__': main()