Debian Codegraph @

Cheetah/CheetahWrapper.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import codecs
4 import glob
5 import os
6 import pprint
7 import re
8 import shutil
9 import sys
10 import json
11 try:
12 import cPickle as pickle
13 except ImportError: # PY3
14 import pickle as pickle
15 from optparse import OptionParser
16
17 from .Compiler import DEFAULT_COMPILER_SETTINGS
18 from .Template import Template
19 from .Utils.Misc import mkdirsWithPyInitFiles
20 from .Version import Version
21 from .compat import PY2
22
23 optionDashesRE = re.compile(R"^-{1,2}")
24 moduleNameRE = re.compile(R"^[a-zA-Z_][a-zA-Z_0-9]*$")
25
26
27 def fprintfMessage(stream, format, *args):
28 if format[-1:] == '^':
29 format = format[:-1]
30 else:
31 format += '\n'
32 if args:
33 message = format % args
34 else:
35 message = format
36 stream.write(message)
37
38
39 class Error(Exception):
40 pass
41
42
43 class Bundle:
44 """Wrap the source, destination and backup paths in one neat little class.
45 Used by CheetahWrapper.getBundles().
46 """
47 def __init__(self, **kw):
48 self.__dict__.update(kw)
49
50 def __repr__(self):
51 return "<Bundle %r>" % self.__dict__
52
53
54 ##################################################
55 # USAGE FUNCTION & MESSAGES
56
57 def usage(usageMessage, errorMessage="", out=sys.stderr):
58 """Write help text, an optional error message, and abort the program.
59 """
60 out.write(WRAPPER_TOP)
61 out.write(usageMessage)
62 exitStatus = 0
63 if errorMessage:
64 out.write('\n')
65 out.write("*** USAGE ERROR ***: %s\n" % errorMessage)
66 exitStatus = 1
67 sys.exit(exitStatus)
68
69
70 WRAPPER_TOP = r"""\
71 __ ____________ __
72 \ \/ \/ /
73 \/ * * \/ CHEETAH %(Version)s Command-Line Tool
74 \ | /
75 \ ==----== / by Tavis Rudd <[email protected]>
76 \__________/ and Mike Orr <[email protected]>
77
78 """ % globals()
79
80
81 HELP_PAGE1 = """\
82 USAGE:
83 ------
84 cheetah compile [options] [FILES ...] : Compile template definitions
85 cheetah fill [options] [FILES ...] : Fill template definitions
86 cheetah help : Print this help message
87 cheetah options : Print options help message
88 cheetah test [options] : Run Cheetah's regression tests
89 : (same as for unittest)
90 cheetah version : Print Cheetah version number
91
92 You may abbreviate the command to the first letter; e.g., 'h' == 'help'.
93 If FILES is a single "-", read standard input and write standard output.
94 Run "cheetah options" for the list of valid options.
95 """
96
97 ##################################################
98 # CheetahWrapper CLASS
99
100
101 class CheetahWrapper(object):
102 MAKE_BACKUPS = True
103 BACKUP_SUFFIX = ".bak"
104 _templateClass = None
105 _compilerSettings = None
106
107 def __init__(self):
108 self.progName = None
109 self.command = None
110 self.opts = None
111 self.pathArgs = None
112 self.sourceFiles = []
113 self.searchList = []
114 self.parser = None
115
116 ##################################################
117 # MAIN ROUTINE
118
119 def main(self, argv=None):
120 """The main program controller."""
121
122 if argv is None:
123 argv = sys.argv
124
125 # Step 1: Determine the command and arguments.
126 try:
127 self.progName = os.path.basename(argv[0])
128 self.command = command = optionDashesRE.sub("", argv[1])
129 if command == 'test':
130 self.testOpts = argv[2:]
131 else:
132 self.parseOpts(argv[2:])
133 except IndexError:
134 usage(HELP_PAGE1, "not enough command-line arguments")
135
136 # Step 2: Call the command
137 meths = (self.compile, self.fill, self.help, self.options,
138 self.test, self.version)
139 for meth in meths:
140 methName = meth.__name__
141 # Or meth.__func__.__name__
142 # Or meth.__name__
143 methInitial = methName[0]
144 if command in (methName, methInitial):
145 sys.argv[0] += (" " + methName)
146 # @@MO: I don't necessarily agree sys.argv[0] should be
147 # modified.
148 meth()
149 return
150 # If none of the commands matched.
151 usage(HELP_PAGE1, "unknown command '%s'" % command)
152
153 def parseOpts(self, args):
154 D = self.debug
155 self.isCompile = isCompile = self.command[0] == 'c'
156 defaultOext = isCompile and ".py" or ".html"
157 self.parser = OptionParser()
158 pao = self.parser.add_option
159 pao("--idir", action="store", dest="idir", default='',
160 help='Input directory (defaults to current directory)')
161 pao("--odir", action="store", dest="odir", default="",
162 help='Output directory (defaults to current directory)')
163 pao("--iext", action="store", dest="iext", default=".tmpl",
164 help='File input extension '
165 '(defaults: compile: .tmpl, fill: .tmpl)')
166 pao("--oext", action="store", dest="oext", default=defaultOext,
167 help='File output extension (defaults: compile: .py, fill: .html)')
168 pao("-R", action="store_true", dest="recurse", default=False,
169 help='Recurse through subdirectories looking for input files')
170 pao("--stdout", "-p", action="store_true", dest="stdout",
171 default=False,
172 help='Send output to stdout instead of writing to a file')
173 pao("--quiet", action="store_false", dest="verbose", default=True,
174 help='Do not print informational messages to stdout')
175 pao("--debug", action="store_true", dest="debug", default=False,
176 help='Print diagnostic/debug information to stderr')
177 pao("--env", action="store_true", dest="env", default=False,
178 help='Pass the environment into the search list')
179 pao("--pickle", action="store", dest="pickle", default="",
180 help='Unpickle FILE and pass it through in the search list')
181 pao("--json", action="store", dest="json", default="",
182 help='Read from JSON FILE and pass it through in the search list')
183 pao("--flat", action="store_true", dest="flat", default=False,
184 help='Do not build destination subdirectories')
185 pao("--nobackup", action="store_true", dest="nobackup", default=False,
186 help='Do not make backup files when generating new ones')
187 pao("--settings", action="store", dest="compilerSettingsString",
188 default=None,
189 help='String of compiler settings to pass through, '
190 'e.g. --settings="useNameMapper=False,useFilters=False"')
191 pao('--print-settings', action='store_true', dest='print_settings',
192 help='Print out the list of available compiler settings')
193 pao("--templateAPIClass", action="store", dest="templateClassName",
194 default=None,
195 help='Name of a subclass of Cheetah.Template.Template '
196 'to use for compilation, e.g. MyTemplateClass')
197 pao("--parallel", action="store", type="int", dest="parallel",
198 default=1,
199 help='Compile/fill templates in parallel, e.g. --parallel=4')
200 pao('--shbang', dest='shbang', default='#!/usr/bin/env python',
201 help='Specify the shbang to place at the top '
202 'of compiled templates, e.g. --shbang="#!/usr/bin/python2.6"')
203 pao('--encoding', dest='encoding', default=None,
204 help='Specify the encoding of source files '
205 '(e.g. "utf-8" to force input files to be interpreted '
206 'as UTF-8)')
207
208 opts, files = self.parser.parse_args(args)
209 self.opts = opts
210 if sys.platform == "win32":
211 new_files = []
212 for spec in files:
213 file_list = glob.glob(spec)
214 if file_list:
215 new_files.extend(file_list)
216 else:
217 new_files.append(spec)
218 files = new_files
219 self.pathArgs = files
220
221 D("""\
222 cheetah compile %s
223 Options are
224 %s
225 Files are %s""", args, pprint.pformat(vars(opts)), files)
226
227 if opts.print_settings:
228 print()
229 print('>> Available Cheetah compiler settings:')
230 from .Compiler import _DEFAULT_COMPILER_SETTINGS
231 listing = _DEFAULT_COMPILER_SETTINGS
232 listing.sort(key=lambda _l: _l[0][0].lower())
233
234 for _l in listing:
235 print('\t%s (default: "%s")\t%s' % _l)
236 sys.exit(0)
237
238 # cleanup trailing path separators
239 seps = [sep for sep in [os.sep, os.altsep] if sep]
240 for attr in ['idir', 'odir']:
241 for sep in seps:
242 path = getattr(opts, attr, None)
243 if path and path.endswith(sep):
244 path = path[:-len(sep)]
245 setattr(opts, attr, path)
246 break
247
248 self._fixExts()
249 if opts.env:
250 self.searchList.insert(0, os.environ)
251 if opts.pickle:
252 f = open(opts.pickle, 'rb')
253 unpickled = pickle.load(f)
254 f.close()
255 self.searchList.insert(0, unpickled)
256 if opts.json:
257 f = open(opts.json, 'r')
258 unjsoned = json.load(f)
259 f.close()
260 self.searchList.insert(0, unjsoned)
261
262 ##################################################
263 # COMMAND METHODS
264
265 def compile(self):
266 self._compileOrFill()
267
268 def fill(self):
269 from .ImportHooks import install
270 install()
271 self._compileOrFill()
272
273 def help(self):
274 usage(HELP_PAGE1, "", sys.stdout)
275
276 def options(self):
277 return self.parser.print_help()
278
279 def test(self):
280 # @@MO: Ugly kludge.
281 TEST_WRITE_FILENAME = 'cheetah_test_file_creation_ability.tmp'
282 try:
283 f = open(TEST_WRITE_FILENAME, 'w')
284 except Exception:
285 sys.exit("""\
286 Cannot run the tests because you don't have write permission in the current
287 directory. The tests need to create temporary files. Change to a directory
288 you do have write permission to and re-run the tests.""")
289 else:
290 f.close()
291 os.remove(TEST_WRITE_FILENAME)
292 # @@MO: End ugly kludge.
293 import unittest
294 from .Tests import Test
295 verbosity = 1
296 if '-q' in self.testOpts:
297 verbosity = 0
298 if '-v' in self.testOpts:
299 verbosity = 2
300 runner = unittest.TextTestRunner(verbosity=verbosity)
301 results = runner.run(unittest.TestSuite(Test.suites))
302 exit(int(not results.wasSuccessful()))
303
304 def version(self):
305 print(Version)
306
307 # If you add a command, also add it to the 'meths' variable in main().
308 ##################################################
309 # LOGGING METHODS
310
311 def chatter(self, format, *args):
312 """Print a verbose message to stdout. But don't if .opts.stdout is
313 true or .opts.verbose is false.
314 """
315 if self.opts.stdout or not self.opts.verbose:
316 return
317 fprintfMessage(sys.stdout, format, *args)
318
319 def debug(self, format, *args):
320 """Print a debugging message to stderr, but don't if .debug is
321 false.
322 """
323 if self.opts.debug:
324 fprintfMessage(sys.stderr, format, *args)
325
326 def warn(self, format, *args):
327 """Always print a warning message to stderr.
328 """
329 fprintfMessage(sys.stderr, format, *args)
330
331 def error(self, format, *args):
332 """
333 Always print a warning message to stderr and exit with an error code.
334 """
335 fprintfMessage(sys.stderr, format, *args)
336 sys.exit(1)
337
338 ##################################################
339 # HELPER METHODS
340
341 def _fixExts(self):
342 assert self.opts.oext, "oext is empty!"
343 iext, oext = self.opts.iext, self.opts.oext
344 if iext and not iext.startswith("."):
345 self.opts.iext = "." + iext
346 if oext and not oext.startswith("."):
347 self.opts.oext = "." + oext
348
349 def _compileOrFill(self):
350 C, D = self.chatter, self.debug
351 opts, files = self.opts, self.pathArgs
352 if files == ["-"]:
353 self._compileOrFillStdin()
354 return
355 elif not files and opts.recurse:
356 which = opts.idir and "idir" or "current"
357 C("Drilling down recursively from %s directory.", which)
358 sourceFiles = []
359 iext = opts.iext
360 idir = os.path.join(opts.idir, os.curdir)
361 for root, dirs, _files in os.walk(idir):
362 for _f in _files:
363 _path = os.path.join(root, _f)
364 if _path.endswith(iext) and os.path.isfile(_path):
365 sourceFiles.append(_path)
366 elif not files:
367 usage(HELP_PAGE1, "Neither files nor -R specified!")
368 else:
369 sourceFiles = self._expandSourceFiles(files, opts.recurse, True)
370 sourceFiles = [os.path.normpath(x) for x in sourceFiles]
371 D("All source files found: %s", sourceFiles)
372 bundles = self._getBundles(sourceFiles)
373 D("All bundles: %s", pprint.pformat(bundles))
374 if self.opts.flat:
375 self._checkForCollisions(bundles)
376
377 # In parallel mode a new process is forked for each template
378 # compilation, out of a pool of size self.opts.parallel. This is not
379 # really optimal in all cases (e.g. probably wasteful for small
380 # templates), but seems to work well in real life for me.
381 #
382 # It also won't work for Windows users, but I'm not going to lose any
383 # sleep over that.
384 if self.opts.parallel > 1:
385 bad_child_exit = 0
386 pid_pool = set()
387
388 def child_wait():
389 pid, status = os.wait()
390 pid_pool.remove(pid)
391 return os.WEXITSTATUS(status)
392
393 while bundles:
394 b = bundles.pop()
395 pid = os.fork()
396 if pid:
397 pid_pool.add(pid)
398 else:
399 self._compileOrFillBundle(b)
400 sys.exit(0)
401
402 if len(pid_pool) == self.opts.parallel:
403 bad_child_exit = child_wait()
404 if bad_child_exit:
405 break
406
407 while pid_pool:
408 child_exit = child_wait()
409 if not bad_child_exit:
410 bad_child_exit = child_exit
411
412 if bad_child_exit:
413 sys.exit("Child process failed, exited with code %d"
414 % bad_child_exit)
415
416 else:
417 for b in bundles:
418 self._compileOrFillBundle(b)
419
420 def _checkForCollisions(self, bundles):
421 """Check for multiple source paths writing to the same destination
422 path.
423 """
424 W = self.warn
425 isError = False
426 dstSources = {}
427 for b in bundles:
428 if b.dst in dstSources:
429 dstSources[b.dst].append(b.src)
430 else:
431 dstSources[b.dst] = [b.src]
432 keys = sorted(dstSources.keys())
433 for dst in keys:
434 sources = dstSources[dst]
435 if len(sources) > 1:
436 isError = True
437 sources.sort()
438 fmt = "Collision: multiple source files %s " \
439 "map to one destination file %s"
440 W(fmt, sources, dst)
441 if isError:
442 what = self.isCompile and "Compilation" or "Filling"
443 sys.exit("%s aborted due to collisions" % what)
444
445 def _expandSourceFiles(self, files, recurse, addIextIfMissing):
446 """Calculate source paths from 'files' by applying the
447 command-line options.
448 """
449 D, W = self.debug, self.warn
450 idir = self.opts.idir
451 iext = self.opts.iext
452 files = []
453 for f in self.pathArgs:
454 oldFilesLen = len(files)
455 D("Expanding %s", f)
456 path = os.path.join(idir, f)
457 pathWithExt = path + iext # May or may not be valid.
458 if os.path.isdir(path):
459 if recurse:
460 for root, dirs, _files in os.walk(path):
461 for _f in _files:
462 _path = os.path.join(root, _f)
463 if _path.endswith(iext) and os.path.isfile(_path):
464 files.append(_path)
465 else:
466 raise Error("source file '%s' is a directory" % path)
467 elif os.path.isfile(path):
468 files.append(path)
469 elif (addIextIfMissing and not path.endswith(iext)
470 and os.path.isfile(pathWithExt)):
471 files.append(pathWithExt)
472 # Do not recurse directories discovered by iext appending.
473 elif os.path.exists(path):
474 W("Skipping source file '%s', not a plain file.", path)
475 else:
476 W("Skipping source file '%s', not found.", path)
477 if len(files) > oldFilesLen:
478 D(" ... found %s", files[oldFilesLen:])
479 return files
480
481 def _getBundles(self, sourceFiles):
482 flat = self.opts.flat
483 idir = self.opts.idir
484 iext = self.opts.iext
485 odir = self.opts.odir
486 oext = self.opts.oext
487 idirSlash = idir + os.sep
488 bundles = []
489 for src in sourceFiles:
490 # 'base' is the subdirectory plus basename.
491 base = src
492 if idir and src.startswith(idirSlash):
493 base = src[len(idirSlash):]
494 if iext and base.endswith(iext):
495 base = base[:-len(iext)]
496 basename = os.path.basename(base)
497 if flat:
498 dst = os.path.join(odir, basename + oext)
499 else:
500 dbn = basename
501 if odir and base.startswith(os.sep):
502 odd = odir
503 while odd != '':
504 idx = base.find(odd)
505 if idx == 0:
506 dbn = base[len(odd):]
507 if dbn[0] == '/':
508 dbn = dbn[1:]
509 break
510 odd = os.path.dirname(odd)
511 if odd == '/':
512 break
513 dst = os.path.join(odir, dbn + oext)
514 else:
515 dst = os.path.join(odir, base + oext)
516 bak = dst + self.BACKUP_SUFFIX
517 b = Bundle(src=src, dst=dst, bak=bak, base=base, basename=basename)
518 bundles.append(b)
519 return bundles
520
521 def _getTemplateClass(self):
522 C = self.chatter
523 modname = None
524 if self._templateClass:
525 return self._templateClass
526
527 modname = self.opts.templateClassName
528
529 if not modname:
530 return Template
531 p = modname.rfind('.')
532 if ':' not in modname:
533 self.error('The value of option --templateAPIClass is invalid\n'
534 'It must be in the form "module:class", '
535 'e.g. "Cheetah.Template:Template"')
536
537 modname, classname = modname.split(':')
538
539 C('using --templateAPIClass=%s:%s' % (modname, classname))
540
541 if p >= 0:
542 mod = getattr(
543 __import__(modname[:p], {}, {}, [modname[p+1:]]), # noqa: E226,E501 missing whitespace around operator
544 modname[p+1:]) # noqa: E226 missing whitespace around operator
545 else:
546 mod = __import__(modname, {}, {}, [])
547
548 klass = getattr(mod, classname, None)
549 if klass:
550 self._templateClass = klass
551 return klass
552 else:
553 self.error('**Template class specified '
554 'in option --templateAPIClass not found\n'
555 '**Falling back on Cheetah.Template:Template')
556
557 def _getCompilerSettings(self):
558 if self._compilerSettings:
559 return self._compilerSettings
560
561 def getkws(**kws):
562 return kws
563 if self.opts.compilerSettingsString:
564 try:
565 settings = eval('getkws(%s)'
566 % self.opts.compilerSettingsString)
567 except Exception:
568 self.error("There's an error in your --settings option."
569 "It must be valid Python syntax.\n"
570 + " --settings='%s'\n"
571 % self.opts.compilerSettingsString
572 + " %s: %s" % sys.exc_info()[:2]
573 )
574
575 validKeys = set(DEFAULT_COMPILER_SETTINGS.keys())
576 for k in settings:
577 if k not in validKeys:
578 self.error(
579 'The --setting "%s" '
580 'is not a valid compiler setting name.'
581 % k)
582
583 self._compilerSettings = settings
584 return settings
585 else:
586 return {}
587
588 def _compileOrFillStdin(self):
589 TemplateClass = self._getTemplateClass()
590 compilerSettings = self._getCompilerSettings()
591 if self.isCompile:
592 pysrc = TemplateClass.compile(file=sys.stdin,
593 compilerSettings=compilerSettings,
594 returnAClass=False)
595 output = pysrc if PY2 else pysrc.decode()
596 else:
597 output = str(TemplateClass(file=sys.stdin,
598 compilerSettings=compilerSettings))
599 sys.stdout.write(output)
600
601 def _compileOrFillBundle(self, b):
602 C = self.chatter
603 TemplateClass = self._getTemplateClass()
604 compilerSettings = self._getCompilerSettings()
605 src = b.src
606 dst = b.dst
607 basename = b.basename
608 dstDir = os.path.dirname(dst)
609 what = self.isCompile and "Compiling" or "Filling"
610 C("%s %s -> %s^", what, src, dst) # No trailing newline.
611 if os.path.exists(dst) and not self.opts.nobackup:
612 bak = b.bak
613 C(" (backup %s)", bak) # On same line as previous message.
614 else:
615 bak = None
616 C("")
617 if self.isCompile:
618 if not moduleNameRE.match(basename):
619 tup = basename, src
620 raise Error("""\
621 %s: base name %s contains invalid characters. It must
622 be named according to the same rules as Python modules.""" % tup)
623 pysrc = TemplateClass.compile(file=src, returnAClass=False,
624 moduleName=basename,
625 className=basename,
626 commandlineopts=self.opts,
627 compilerSettings=compilerSettings)
628 output = pysrc
629 else:
630 # output = str(TemplateClass(file=src, searchList=self.searchList))
631 tclass = TemplateClass.compile(file=src,
632 compilerSettings=compilerSettings)
633 output = str(tclass(searchList=self.searchList))
634
635 if bak:
636 shutil.copyfile(dst, bak)
637 if dstDir and not os.path.exists(dstDir):
638 if self.isCompile:
639 mkdirsWithPyInitFiles(dstDir)
640 else:
641 os.makedirs(dstDir)
642 if self.opts.stdout:
643 if not PY2:
644 encoding = self.opts.encoding
645 if encoding and isinstance(output, bytes):
646 output = output.decode(encoding)
647 sys.stdout.write(output)
648 else:
649 encoding = self.opts.encoding
650 if encoding:
651 if isinstance(output, bytes):
652 output = output.decode(encoding)
653 f = codecs.open(dst, 'w', encoding=encoding)
654 else:
655 if not PY2 and isinstance(output, bytes):
656 output = output.decode()
657 f = open(dst, 'w')
658 f.write(output)
659 f.close()
660
661
662 # Called when invoked as `cheetah`
663 def _cheetah():
664 CheetahWrapper().main()
665
666 # Called when invoked as `cheetah-compile`
667
668
669 def _cheetah_compile():
670 sys.argv.insert(1, "compile")
671 CheetahWrapper().main()
672
673
674 ##################################################
675 # if run from the command line
676 if __name__ == '__main__':
677 CheetahWrapper().main()