1# mako/cmd.py 2# Copyright (C) 2006-2015 the Mako authors and contributors <see AUTHORS file> 3# 4# This module is part of Mako and is released under 5# the MIT License: http://www.opensource.org/licenses/mit-license.php 6from argparse import ArgumentParser 7from os.path import isfile, dirname 8import sys 9from mako.template import Template 10from mako.lookup import TemplateLookup 11from mako import exceptions 12 13def varsplit(var): 14 if "=" not in var: 15 return (var, "") 16 return var.split("=", 1) 17 18def _exit(): 19 sys.stderr.write(exceptions.text_error_template().render()) 20 sys.exit(1) 21 22def cmdline(argv=None): 23 24 parser = ArgumentParser("usage: %prog [FILENAME]") 25 parser.add_argument("--var", default=[], action="append", 26 help="variable (can be used multiple times, use name=value)") 27 parser.add_argument("--template-dir", default=[], action="append", 28 help="Directory to use for template lookup (multiple " 29 "directories may be provided). If not given then if the " 30 "template is read from stdin, the value defaults to be " 31 "the current directory, otherwise it defaults to be the " 32 "parent directory of the file provided.") 33 parser.add_argument('input', nargs='?', default='-') 34 35 options = parser.parse_args(argv) 36 if options.input == '-': 37 lookup_dirs = options.template_dir or ["."] 38 lookup = TemplateLookup(lookup_dirs) 39 try: 40 template = Template(sys.stdin.read(), lookup=lookup) 41 except: 42 _exit() 43 else: 44 filename = options.input 45 if not isfile(filename): 46 raise SystemExit("error: can't find %s" % filename) 47 lookup_dirs = options.template_dir or [dirname(filename)] 48 lookup = TemplateLookup(lookup_dirs) 49 try: 50 template = Template(filename=filename, lookup=lookup) 51 except: 52 _exit() 53 54 kw = dict([varsplit(var) for var in options.var]) 55 try: 56 print(template.render(**kw)) 57 except: 58 _exit() 59 60 61if __name__ == "__main__": 62 cmdline() 63