# -*- coding: utf-8 -*- """Kid Compiler Compile XML to Python byte-code. """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import os.path import imp import stat import struct import marshal import kid from kid.codewriter import raise_template_error __all__ = ['KID_EXT', 'compile', 'compile_file', 'compile_dir'] # kid filename extension KID_EXT = ".kid" def actualize(code, dict=None): """Run code with variables in dict, updating the dict.""" if dict is None: dict = {} exec code in dict return dict _py_compile = compile def py_compile(code, filename='', kind='exec'): """The Python built-in compile function with safeguard.""" if type(code) == unicode: # unicode strings may not have a PEP 0263 encoding declaration if code.startswith('# -*- coding: '): # we want the line numbering to match with the source file, # so we only remove the magic word in the comment line: code = '# -*-' + code[13:] return _py_compile(code, filename, 'exec') def compile(source, filename='', encoding=None, entity_map=None): """Compiles Kid XML source to a Python code object. source -- A file like object - must support read. filename -- An optional filename that is used """ # XXX all kinds of work to do here catching syntax errors and # adjusting line numbers... py = kid.codewriter.parse(source, encoding, filename, entity_map) return py_compile(py, filename) _timestamp = lambda filename : os.stat(filename)[stat.ST_MTIME] class KidFile(object): magic = imp.get_magic() def __init__(self, kid_file, force=False, encoding=None, strip_dest_dir=None, entity_map=None): self.kid_file = kid_file self.py_file = os.path.splitext(kid_file)[0] + '.py' self.strip_dest_dir = strip_dest_dir self.pyc_file = self.py_file + 'c' self.encoding = encoding self.entity_map = entity_map fp = None if force: stale = True else: stale = False try: fp = open(self.pyc_file, "rb") except IOError: stale = True else: if fp.read(4) != self.magic: stale = True else: mtime = struct.unpack(' 0 and name != os.curdir and name != os.pardir \ and os.path.isdir(fullname) and not os.path.islink(fullname): for res in compile_dir(fullname, maxlevels - 1, force, source, encoding, strip_dest_dir, entity_map): yield res