d23344d0 by Marcos Cano

minified version of templar using String template

1 parent 7dee8c20
this a template file
var = [[{variable}]]
otra_variable= [[{var}]]
\ No newline at end of file
variable=hello world
#!/usr/bin/python
import string, re, sys
import getopt,os.path
debug = False
ifile = ''
ofile = ifile
printit = False
vars=os.environ
class MyTemplate(string.Template):
#delimiter = '{{'
pattern = r'''
\[\[\{(?:
(?P<escaped>\[\[\{)|
(?P<named>[_a-z][_a-z0-9]*)\}\]\]|
(?P<braced>[_a-z][_a-z0-9]*)\}\]\]|
(?P<invalid>)
)
'''
def usage():
print """ usage: %s [OPTIONS]
OPTIONS:
-i, --ifile=ABSOLUTE_INPUT_FILE_PATH
input template file
by default it will replace in file
-v, --vars=JSON_VARS_FILE
json of variables file to replace in,
by default it loads the environment variables
-o, --ofile=ABS_OUTPUT_FILE_PATH
provide an output file,
override the input file default behaviour
-p, --print
print to stdout instead of replacing the file,
it will do replace in file.
it will override the output file and input file default behaviour
"""%sys.argv[0]
sys.exit(2)
def engine(ifile,ofile,vars):
template_content = open(ifile, "r").read()
template= MyTemplate(template_content)
#print 'MATCHES:', t.pattern.findall(t.template)
outputText = template.safe_substitute(vars)
print 'MATCHES:', template.pattern.findall(template.template)
if printit:
print "AFTER TEMPLATE:"
#print outputText
print outputText.encode('ascii', 'ignore')
else:
f = open(ofile,'w')
f.write(outputText.encode('ascii', 'ignore'))
f.close()
def main(argv):
try:
options, remainder = getopt.getopt(sys.argv[1:], 'o:f:i:v:dph', ['ofile=','o=',
'ifile=','i=',
'vars=','v=',
'print','p',
'help','h'
])
except getopt.GetoptError:
usage()
sys.exit(2)
global debug, vars, ifile, ofile,printit
for opt, arg in options:
if opt in ('-v','--vars','--v'):
if os.path.isfile(arg):
with open(arg) as data_file:
print "using file"
vars = json.load(data_file)
else:
print "using environment"
vars=os.environ
elif opt in ('-f','--ifile','--i','-i'):
if os.path.isfile(arg):
ifile=arg
ofile=ifile
else:
print "file provided [%s] does not exist" %arg
usage()
elif opt in ("-o" ,"--ofile",'--o') :
ofile = arg
elif opt in ('-p','--print'):
printit=True
elif opt in ('-h','--help'):
usage()
else:
usage()
if debug:
print 'OPTIONS :', options
print 'VARS :', pprint(vars)
print 'DEBUG :', debug
print 'OUTPUT :', ofile
print 'INPUT :', ifile
print 'PRINTIT :', printit
print 'REMAINING :', remainder
engine(ifile, ofile, vars )
if __name__ == "__main__":
if len(sys.argv) > 1:
main(sys.argv[1:])
else:
usage()
sys.exit()