templar.min.py 3.83 KB
#!/usr/bin/python
import string, re, sys
import getopt,os.path, json
from pprint import pprint



debug = False
ifile = ''
folder = ''
ofile = ifile
printit = False
vars=os.environ
recursive = False


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 
	-r, --r
	        recursively templates all files included in a folder given, 
	        use with -p to only debug/test, use it without -p and it will 
	        replace all files with the templated values

		"""%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)

	matches = template.pattern.findall(template.template)

	if len(matches):
		#print '[ MATCHES ] - ', matches
		outputText = template.safe_substitute(vars)
		#print "[ TEMPLATING ] - %s "%ifile

		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:r:dph', ['ofile=','o=', 
															 'ifile=','i=',
															 'vars=','v=',
	                                                         'print','p', 
	                                                         'help','h',
	                                                         'r='                                                        
	                                                         ])
	except getopt.GetoptError:
		usage()
		sys.exit(2)

	global debug, vars, ifile, ofile,printit, recursive


	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 ('-r','--r'):
			if os.path.isdir(arg):
				recursive= True
				folder = arg
			else:
				print "folder provided [%s] does not exist" %arg
				usage()

		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(str(vars))
		print 'DEBUG   :', debug
		print 'OUTPUT  :', ofile
		print 'INPUT   :', ifile
		print 'PRINTIT :', printit
		print 'REMAINING :', remainder


	if recursive :
		count=0
		for  path, dirs, files in os.walk(folder):
			for filename in files:
				fullpath = os.path.join(path, filename)
				if os.path.isfile(fullpath):
					
					engine(fullpath, fullpath, vars)
					count+=1
				else: 
					print "file %s does not exists"%fullpath
		#print "successfully templated %s files"%str(count)
			
	elif ifile != '': 
		engine(ifile, ofile, vars )
	else:
		print "nothing provided"
		sys.exit(1)


if __name__ == "__main__":
	if len(sys.argv) > 1:
		main(sys.argv[1:])	
	else:
		usage()
sys.exit()