PK ²Ð4³ú’–Ö=Ö= kid/pull.py"""Pull-style interface for ElementTree.""" from __future__ import generators __revision__ = "$Rev$" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from kid.et import * # ElementTree from kid.util import open_resource, QuickTextReader from xml.parsers import expat # This is the default entity map. import htmlentitydefs default_entity_map = {} default_external_dtd = [] for k, v in htmlentitydefs.name2codepoint.items(): default_entity_map[k] = unichr(v) default_external_dtd.append('' % (k, v)) default_external_dtd = '\n'.join(default_external_dtd) # Bring common ElementTree objects into scope class InvalidStreamState(Exception): def __init__(self, msg="Invalid stream state."): Exception.__init__(self, msg) def XML(text, fragment=1, encoding=None, xmlns=None): """Element generator that reads from a string""" if text.startswith('%s' % (xmlns,text) else: text = '%s' % text if isinstance(text, unicode): encoding = 'utf-16' text = text.encode(encoding) p = Parser(QuickTextReader(text), encoding) p._sourcetext = text return ElementStream(_coalesce(p, encoding=encoding)).strip() else: if isinstance(text, unicode): encoding = 'utf-16' text = text.encode(encoding) p = Parser(QuickTextReader(text), encoding) p._sourcetext = text return ElementStream(_coalesce(p, encoding=encoding)) def document(file, encoding=None, filename=None): if not hasattr(file, 'read'): if filename is None: filename = file file = open_resource(file, 'rb') else: if filename is None: filename = '' p = Parser(file, encoding) p._filename = filename return ElementStream(_coalesce(p, encoding=encoding)) class ElementStream(object): """Provides a pull/streaming interface to ElementTree. Instances of this class are iterable. Most methods of the class act on the Element that is currently being visited. """ def __init__(self, stream, current=None): """Create an ElementStream. stream - an iterator that returns ElementStream events. current - If an Element is provided in this parameter than it is yielded as the first element in the stream. """ if hasattr(stream, 'tag') and hasattr(stream, 'attrib'): stream = self._pull(stream, tail=1) self.current = None self._iter = self._track(iter(stream), current) def __iter__(self): return self._iter def expand(self): """Expand the current item in the stream as an Element.""" current = self.current if current is None: current = [] stack = [current] last = None for ev, item in self._iter: if ev == START: current = item if len(stack) > 0: stack[-1].append(current) last = None stack.append(current) elif ev == END: last = stack.pop() assert last is item if len(stack) == 0: break elif ev == TEXT: if last is not None: last.tail = item else: current.text = item if isinstance(last, list): return last[0] else: return last def strip(self, levels=1): depth = self.current is not None and 1 or 0 for (ev, item) in self._iter: if ev == START: depth += 1 if depth > levels or (depth == levels and ev not in (START, END)): yield (ev, item) if ev == END: depth -= 1 if depth == 0: break elif depth < 0: raise InvalidStreamState() def eat(self): """Eat the current element and all decendant items.""" depth = self.current is not None and 1 or 0 for (ev, item) in self._iter: if ev == START: depth += 1 elif ev == END: depth -= 1 if depth == 0: break return self def _pull(self, elem, tail=0): orig = elem elem = Element(orig.tag, dict(orig.attrib)) ## XXX: find a better way if elem.tag in (Comment, ProcessingInstruction): elem.text = orig.text orig.text = None yield (START, elem) if orig.text: yield (TEXT, orig.text) for child in orig.getchildren(): for event in self._pull(child, tail=1): yield event yield (END, elem) if tail and orig.tail: yield (TEXT, orig.tail) def _track(self, stream, current=None): if current is not None: self.current = current yield (START, current) for p in stream: ev, item = p if ev == START: self.current = item elif ev == END: self.current = None yield (ev, item) def ensure(cls, stream, current=None): if isinstance(stream, cls): return stream else: return cls(stream, current) ensure = classmethod(ensure) def to_unicode(value, encoding): if isinstance(value, unicode): return value if hasattr(value, '__unicode__'): return unicode(value) if not isinstance(value, str): value = str(value) return unicode(value, encoding) def _coalesce(stream, encoding, extended=1): """Coalesces TEXT events and namespace events. Fold multiple sequential TEXT events into a single event. The 'encoding' attribute is for the source strings. """ textbuf = [] namespaces = [] last_ev = None last = None current = None stack = [None] for ev, item in stream: if ev == TEXT: textbuf.append(item) last_ev = TEXT continue if last_ev == TEXT: text = u"" for value in textbuf: text += to_unicode(value, encoding) textbuf = [] if text: yield (TEXT, text) if ev == START: attrib = item.attrib for prefix, uri in namespaces: if prefix: attrib['xmlns:%s' % prefix] = uri else: attrib['xmlns'] = uri namespaces = [] current = item stack.append(item) elif ev == END: current = stack.pop() elif ev == START_NS: prefix, uri = item namespaces.append( (prefix, uri) ) continue elif ev == END_NS: continue yield ev, item if last_ev == TEXT: text = u"" for value in textbuf: text += to_unicode(value, encoding) if text: yield (TEXT, text) # Common Events START = 1 END = 2 TEXT = 3 DOCTYPE = 4 XML_DECL = 5 # These events aren't used after initial parsing START_NS = 10 END_NS = 11 PI = 12 COMMENT = 13 def Parser(source, encoding=None): return ExpatParser(source) # Most of the following copied from ElementTree.XMLTreeBuilder # Differences from ET implementation: # # * Specialized for generator based processing. Elements are built # using a iterator approach instead of the TreeBuilder approach. # # * Support for DOCTYPE, Comment, and Processing Instruction nodes. class ExpatParser(object): def __init__(self, source, encoding=None): if not hasattr(source, 'read'): filename = source source = open(source, 'rb') else: filename = '' self._filename = filename self._source = source self._parser = parser = expat.ParserCreate(encoding, "}") self._queue = [] # callbacks parser.DefaultHandler = self._default parser.StartElementHandler = self._start parser.EndElementHandler = self._end parser.CharacterDataHandler = self._data parser.ProcessingInstructionHandler = self._pi parser.CommentHandler = self._comment parser.StartNamespaceDeclHandler = self._start_ns parser.EndNamespaceDeclHandler = self._end_ns parser.XmlDeclHandler = self._xmldecl_handler parser.StartDoctypeDeclHandler = self._doctype_handler # let expat do the buffering, if supported try: self._parser.buffer_text = 1 except AttributeError: pass # use new-style attribute handling, if supported try: self._parser.ordered_attributes = 1 self._parser.specified_attributes = 1 parser.StartElementHandler = self._start_list except AttributeError: pass self._doctype = None # these should be come customizable at some point self.entity = default_entity_map self.external_dtd = default_external_dtd # setup entity handling self._parser.SetParamEntityParsing( expat.XML_PARAM_ENTITY_PARSING_ALWAYS) self._parser.ExternalEntityRefHandler = self._buildForeign self._parser.UseForeignDTD() def _buildForeign(self, context, base, systemId, publicId): import StringIO parseableFile = StringIO.StringIO(default_external_dtd) original_parser = self._parser self._parser = self._parser.ExternalEntityParserCreate(context) self._parser.ParseFile(parseableFile) self._parser = original_parser return 1 def push(self, ev, stuff): self._queue.append( (ev, stuff) ) def _expat_stream(self): bufsize = 4 * 1024 # 4K feed = self.feed read = self._source.read done = 0 while 1: while not done and len(self._queue) == 0: data = read(bufsize) if data == '': self.close() done = 1 else: feed(data) for i in self._queue: yield i self._queue = [] if done: break def __iter__(self): names = {} # XXX: hack to enable old namespace. This should be removed for 0.7 old_ns = 'http://naeblis.cx/ns/kid#' new_ns = 'http://purl.org/kid/ns#' def fixname(key): if key.startswith(old_ns): key = ''.join([new_ns, key[len(old_ns):]]) try: name = names[key] except KeyError: name = key if "}" in name: name = "{" + name names[key] = name return name stack = [] parent = None current = None for (ev, stuff) in self._expat_stream(): if ev == TEXT: yield (TEXT, stuff) elif ev == START: tag, attrib_in = stuff tag = fixname(tag) attrib = {} if attrib_in: for key, value in attrib_in.items(): attrib[fixname(key)] = value parent = current current = Element(tag, attrib) stack.append(current) yield (START, current) elif ev == END: current = stack.pop() assert fixname(stuff) == current.tag parent = len(stack) and stack[-1] or None yield (END, current) elif ev == COMMENT: current = Comment(stuff) yield (START, current) yield (END, current) elif ev == PI: current = ProcessingInstruction(stuff[0], stuff[1]) yield (START, current) yield (END, current) else: yield (ev, stuff) def feed(self, data): try: self._parser.Parse(data, 0) except expat.ExpatError, e: e.filename = self._filename if hasattr(self, '_sourcetext'): line = e.lineno e.source = self._sourcetext.split('\n', line)[-1] else: e.source = '???' raise e def close(self): if hasattr(self, '_parser'): self._parser.Parse('', 1) # end of data del self._parser # get rid of circular references def _start(self, tag, attrib_in): self._queue.append((START, (tag, attrib_in))) def _start_list(self, tag, attrib_in): attrib = None if attrib_in: attrib = {} for i in range(0, len(attrib_in), 2): attrib[attrib_in[i]] = attrib_in[i+1] self._queue.append((START, (tag, attrib))) def _data(self, text): self._queue.append((TEXT, text)) def _end(self, tag): self._queue.append((END, tag)) def _default(self, text): prefix = text[:1] if prefix == "&": # deal with undefined entities try: self._queue.append((TEXT, self.entity[text[1:-1]])) except KeyError: from xml.parsers import expat raise expat.error( "undefined entity %s: line %d, column %d" % (text, self._parser.ErrorLineNumber, self._parser.ErrorColumnNumber) ) else: # XXX not sure what should happen here. # This gets: \n at the end of documents?, " import re from kid.pull import * from kid.et import namespaces from kid import Namespace # the kid xml namespace KID_XMLNS = "http://purl.org/kid/ns#" KID_PREFIX = 'py' kidns = Namespace(KID_XMLNS) QNAME_FOR = kidns['for'] QNAME_IF = kidns['if'] QNAME_DEF = kidns['def'] QNAME_SLOT = kidns['slot'] QNAME_CONTENT = kidns['content'] QNAME_REPLACE = kidns['replace'] QNAME_MATCH = kidns['match'] QNAME_STRIP = kidns['strip'] QNAME_ATTRIBUTES = kidns['attrs'] QNAME_EXTENDS = kidns['extends'] QNAME_LAYOUT = kidns['layout'] # deprectaed QNAME_OMIT = kidns['omit'] QNAME_REPEAT = kidns['repeat'] # the kid processing instruction name KID_PI = 'python' KID_ALT_PI = 'py' KID_OLD_PI = 'kid' def parse(source, encoding=None, filename=None): parser = KidParser(document(source, encoding=encoding, filename=filename), encoding) return parser.parse() def parse_file(filename, encoding=None): """Parse the file specified. filename -- the name of a file. fp -- an optional file like object to read from. If not specified, filename is opened. """ source = open(filename, 'rb') try: return parse(source, encoding, filename=filename) finally: source.close() class KidParser(object): def __init__(self, stream, encoding=None): self.stream = stream self.encoding = encoding or 'utf-8' self.depth = 0 self.module_code = CodeGenerator() self.class_code = CodeGenerator() self.expand_code = CodeGenerator(level=1) self.end_module_code = CodeGenerator() self.module_defs = [] self.inst_defs = [] def parse(self): self.begin() self.proc_stream(self.module_code) self.end() parts = [] parts += self.module_code.code for c in self.module_defs: parts += c.code parts += self.class_code.code parts += self.expand_code.code for c in self.inst_defs: parts += c.code parts += self.end_module_code.code return '\n'.join(parts) def begin(self): code = self.module_code code.line('from __future__ import generators') code.line('import kid') code.line('from kid.template_util import *') code.line('import kid.template_util as template_util') code.line('_def_names = []') # default variables. can be overridden by template code.line('encoding = "%s"' % self.encoding) code.line('doctype = None') code.line('omit_namespaces = [kid.KID_XMLNS]') code.line('layout_params = {}') # module methods. code.line('def pull(**kw): return Template(**kw).pull()') code.line("def generate(encoding=encoding, fragment=0, output=None, **kw): " "return Template(**kw).generate(encoding=encoding, fragment=fragment, output=output)") code.line("def serialize(encoding=encoding, fragment=0, output=None, **kw): " "return Template(**kw).serialize(encoding=encoding, fragment=fragment, output=output)") code.line("def write(file, encoding=encoding, fragment=0, output=None, **kw): " "return Template(**kw).write(file, encoding=encoding, fragment=fragment, output=output)") code.line('BaseTemplate = kid.BaseTemplate') code.line('def initialize(template): pass') # expand code code = self.expand_code code.start_block('def initialize(self):') code.line('rslt = initialize(self)') code.line('if rslt != 0: super(Template, self).initialize()') code.end_block() code.start_block('def _pull(self):') # XXX hack: nasty kluge for making kwargs locals code.line("exec template_util.get_locals(self, locals())") code.line('current, ancestors = None, []') code.line('if doctype: yield (DOCTYPE, doctype)') code = self.end_module_code code.line('') def end(self): self.expand_code.end_block() def proc_stream(self, code): for (ev, item) in self.stream: if ev == START: if item.tag == Comment: text = item.text.lstrip() if text.startswith('!'): continue line = code.line if text.startswith('<') or text.startswith('['): sub = interpolate(item.text) if isinstance(sub, list): text = "''.join(%r)" % sub else: text = repr(sub) else: text = repr(item.text) line('_e = Comment(%s)' % text) line('yield (START, _e); yield (END, _e); del _e') elif item.tag == ProcessingInstruction: if ' ' in item.text.strip(): (name, data) = item.text.split(' ', 1) else: (name, data) = (item.text, '') if name in (KID_PI, KID_ALT_PI, KID_OLD_PI): if data: code.insert_block(data) else: c = self.depth and code or self.expand_code c.line('_e = ProcessingInstruction(%r, %r)' \ % (name, data) ) c.line('yield (START, _e); yield (END, _e); del _e') del c else: layout = None if code is self.module_code: layout = item.get(QNAME_LAYOUT) if layout is not None: del item.attrib[QNAME_LAYOUT] decl = ['class Template('] extends = item.get(QNAME_EXTENDS) parts = [] if extends is not None: del item.attrib[QNAME_EXTENDS] for c in extends.split(','): parts.append('template_util.get_base_class(%s, __file__)' % c) parts.append('BaseTemplate') decl.append(','.join(parts)) decl.append('):') code = self.class_code code.start_block(''.join(decl)) code.line('_match_templates = []') code = self.expand_code del decl, parts self.def_proc(item, item.attrib, code) if layout is not None: old_code = code code = CodeGenerator(level=1) code.start_block("def _pull(self):") code.line('exec template_util.get_locals(self, locals())') code.line('kw = dict(layout_params)') code.line('kw.update(dict([(name, getattr(self, name)) for name in _def_names]))') code.line('kw.update(self.__dict__)') # XXX hack: this could be avoided if template args were not stored in self.__dict__ # Note: these names cannot be passed to the layout template via layout_params code.line('kw.pop("assume_encoding", None)') code.line('kw.pop("_layout_classes", None)') code.line('temp = template_util.get_base_class(%s, __file__)(**kw)' % layout) code.line('temp._match_templates = self._match_templates + temp._match_templates') code.line('return temp._pull()') code.end_block() self.inst_defs.append(code) code = old_code elif ev == END and not item.tag in (ProcessingInstruction, Comment): break elif ev == TEXT: self.text_interpolate(item, code) elif ev == XML_DECL and item[1] is not None: self.module_code.line('encoding = %r' % item[1]) elif ev == DOCTYPE: self.module_code.line('doctype = (%r, %r, %r)' % item) def def_proc(self, item, attrib, code): attr_name = QNAME_DEF decl = attrib.get(attr_name) if decl is None: attr_name = QNAME_SLOT decl = attrib.get(attr_name) if decl is not None: del attrib[attr_name] old_code = code if '(' not in decl: decl = decl + '()' name, args = decl.split('(', 1) pos = args.rfind(')') args = args[0:pos].strip() self_ = args and 'self, ' or 'self' class_decl = '%s(%s%s)' % (name, self_, args) # module function code code = CodeGenerator() code.start_block('def %s(*args, **kw):' % name) code.line('return Template().%s(*args, **kw)' % name) code.end_block() code.line('_def_names.append("%s")' % name) self.module_defs.append(code) # instance method code code = CodeGenerator(level=1) code.start_block('def %s:' % class_decl) code.line('exec template_util.get_locals(self, locals())') code.line('current, ancestors = None, []') self.inst_defs.append(code) self.match_proc(item, attrib, code) code.end_block() if attr_name == QNAME_SLOT: old_code.line('for _e in template_util.generate_content(self.%s()): yield _e' % name) else: self.match_proc(item, attrib, code) def match_proc(self, item, attrib, code): expr = attrib.get(QNAME_MATCH) if expr is not None: del attrib[QNAME_MATCH] old_code = code code = CodeGenerator(level=1) code.start_block('def _match_func(self, item, apply):') code.line('exec template_util.get_locals(self, locals())') code.line('current, ancestors = None, []') self.for_proc(item, attrib, code) code.end_block() code.line('_match_templates.append((lambda item: %s, _match_func))' \ % expr) self.inst_defs.append(code) else: self.for_proc(item, attrib, code) def for_proc(self, item, attrib, code): expr = attrib.get(QNAME_FOR) if expr is not None: code.start_block('for %s:' % expr) del attrib[QNAME_FOR] self.if_proc(item, attrib, code) code.end_block() else: self.if_proc(item, attrib, code) def if_proc(self, item, attrib, code): expr = attrib.get(QNAME_IF) if expr is not None: code.start_block('if %s:' % expr) del attrib[QNAME_IF] self.replace_proc(item, attrib, code) code.end_block() else: self.replace_proc(item, attrib, code) def replace_proc(self, item, attrib, code): expr = attrib.get(QNAME_REPLACE) if expr is not None: del attrib[QNAME_REPLACE] attrib[QNAME_STRIP] = "" attrib[QNAME_CONTENT] = expr self.strip_proc(item, attrib, code) def strip_proc(self, item, attrib, code): has_content = self.content_proc(item, attrib, code) expr, attr = (attrib.get(QNAME_STRIP), QNAME_STRIP) if expr is None: # XXX py:omit is deprecated equivalent of py:strip expr, attr = (attrib.get(QNAME_OMIT), QNAME_OMIT) start_block, end_block = (code.start_block, code.end_block) line = code.line if expr is not None: del attrib[attr] if expr != '': start_block("if not (%s):" % expr) self.attrib_proc(item, attrib, code) end_block() else: pass # element is always stripped else: self.attrib_proc(item, attrib, code) if has_content: code.start_block( 'for _e in template_util.generate_content(_cont, current):') line('yield _e') line('del _e') code.end_block() self.stream.eat() else: self.depth += 1 self.proc_stream(code) self.depth -= 1 if expr: start_block("if not (%s):" % expr) line('yield (END, current)') line('current = ancestors.pop(0)') end_block() elif expr != '': line('yield (END, current)') line('current = ancestors.pop(0)') def attrib_proc(self, item, attrib, code): interp = 0 line = code.line need_interpolation = 0 names = namespaces(item, remove=1) for (k,v) in attrib.items(): sub = interpolate(v) if id(sub) != id(v): attrib[k] = sub if isinstance(sub, list): need_interpolation = 1 expr = attrib.get(QNAME_ATTRIBUTES) if expr is not None: del attrib[QNAME_ATTRIBUTES] attr_text = 'template_util.update_dict(%r, "%s", globals(), locals())' \ % (attrib, expr.replace('"', '\\\"')) attr_text = 'template_util.make_attrib(%s,self._get_assume_encoding())' % attr_text else: if attrib: if need_interpolation: attr_text = 'template_util.make_attrib(%r,self._get_assume_encoding())' % attrib else: attr_text = repr(attrib) else: attr_text = '{}' line('ancestors.insert(0, current)') line('current = Element(%r, %s)' % (item.tag, attr_text)) if len(names): code.start_block('for _p, _u in %r.items():' % names) line('if not _u in omit_namespaces: yield (START_NS, (_p,_u))') code.end_block() line('yield (START, current)') def content_proc(self, item, attrib, code): expr = attrib.get(QNAME_CONTENT) if expr is not None: del attrib[QNAME_CONTENT] code.line('_cont = %s' % expr) return 1 def text_interpolate(self, text, code): interp = 0 line = code.line sub = interpolate(text) if isinstance(sub, list): code.start_block('for _e in %r:' % sub) code.line('for _e2 in template_util.generate_content(_e): yield _e2') code.end_block() else: line('yield (TEXT, %r)' % sub) class SubExpression(list): def __repr__(self): return "[%s]" % ', '.join(self) _sub_expr = re.compile(r"(?= last_checked: more_parts = _sub_expr_short.split(part) parts[i:i+1] = more_parts last_checked = i + len(more_parts) continue else: new_parts.append(repr(part.replace('$$', '$'))) i += 1 return new_parts class CodeGenerator: """A simple Python code generator.""" level = 0 tab = '\t' def __init__(self, code=None, level=0, tab='\t'): self.code = code or [] if level != self.level: self.level = level if tab != self.tab: self.tab = tab def line(self, text): self.code.append('%s%s' % (self.tab * self.level, text)) def start_block(self, text): self.line(text) self.level+=1 def end_block(self, nblocks=1, with_pass=False): for n in range(nblocks): if with_pass: self.line('pass') self.level-=1 def insert_block(self, block): output_line = self.line lines = block.splitlines() if len(lines) == 1: # special case single lines output_line(lines[0].strip()) else: # adjust the block for line in _adjust_python_block(lines, self.tab): output_line(line) def __str__(self): self.code.append('') return '\n'.join(self.code) # Auxiliary function def _adjust_python_block(lines, tab='\t'): """Adjust the indentation of a Python block.""" lines = [lines[0].strip()] + [line.rstrip() for line in lines[1:]] ind = None # find least index for line in lines[1:]: if line != '': s = line.lstrip() if s[0] != '#': i = len(line) - len(s) if ind is None or i < ind: ind = i if i == 0: break if ind is not None or ind != 0: # remove indentation lines[1:] = [line[:ind].lstrip() + line[ind:] for line in lines[1:]] if lines[0] and not lines[0][0] == '#': # the first line contains code try: # try to compile it compile(lines[0], '', 'exec') # if it works, line does not start new block except SyntaxError: # unexpected EOF while parsing? try: # try to compile the whole block block = '\n'.join(lines) + '\n' compile(block, '', 'exec') # if it works, line does not start new block except IndentationError: # expected an indented block? # so try to add some indentation: lines2 = lines[:1] + [tab + line for line in lines[1:]] block = '\n'.join(lines2) + '\n' # try again to compile the whole block: compile(block, '', 'exec') lines = lines2 # if it works, keep the indentation except: pass # leave it as it is except: pass # leave it as it is return lines # Python < 2.3 compatibility try: enumerate except NameError: def enumerate(seq): for i, elem in zip(range(len(seq)), seq): yield (i, elem) PK ²Ð4™‰õŽkkkid/release.pyversion = "0.9.2" author = "Ryan Tomayko" email = "rtomayko@gmail.com" copyright = "Copyright 2004-2006, Ryan Tomayko, David Stanek, Christoph Zwerschke, Daniel Miller" license = "MIT" # http://www.opensource.org/licenses/mit-license.php long_description = """Pythonic, XML Templating Kid is a simple, Python-based template language for generating and transforming XML vocabularies. Kid was spawned as a result of a kinky love triangle between XSLT, TAL, and PHP. We believe many of the best features of these languages live on in Kid with much of the limitations and complexity stamped out (well, eventually :). """ PKY´Ð4§ØRÅRÅRkid/parser.pyc;ò º-“Dc@s¿dZdklZdZdZdZdZdZdkZdk Td k l Z d k l Z d Zd Ze eƒZed ZedZedZedZedZedZedZedZedZedZedZedZedZdZd ZdZ e!e!d„Z"e!d„Z#de$fd„ƒYZ%d e&fd!„ƒYZ'ei(d"ƒZ)ei(d#ƒZ*d$„Z+d%fd&„ƒYZ,d'd(„Z-ye.Wne/j od)„Z.nXdS(*s;Kid Parser Parses Kid embedded XML to Python source code. (s generatorss $Rev: 338 $s5$Date: 2006-06-08 01:33:55 +0000 (Thu, 08 Jun 2006) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(s*(s namespaces(s Namespaceshttp://purl.org/kid/ns#spysforsifsdefsslotscontentsreplacesmatchsstripsattrssextendsslayoutsomitsrepeatspythonskidcCs/tt|d|d|ƒ|ƒ}|iƒSdS(Nsencodingsfilename(s KidParsersdocumentssourcesencodingsfilenamesparsersparse(ssourcesencodingsfilenamesparser((s(build/bdist.linux-i686/egg/kid/parser.pysparse,s!cCs8t|dƒ}zt||d|ƒSWd|iƒXdS(sµParse the file specified. filename -- the name of a file. fp -- an optional file like object to read from. If not specified, filename is opened. srbsfilenameN(sopensfilenamessourcesparsesencodingsclose(sfilenamesencodingssource((s(build/bdist.linux-i686/egg/kid/parser.pys parse_file0s s KidParsercBs‰tZed„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „Zd „Zd„ZRS(NcCsn||_|pd|_d|_tƒ|_tƒ|_tddƒ|_tƒ|_g|_ g|_ dS(Nsutf-8isleveli( sstreamsselfsencodingsdepths CodeGenerators module_codes class_codes expand_codesend_module_codes module_defss inst_defs(sselfsstreamsencoding((s(build/bdist.linux-i686/egg/kid/parser.pys__init__?s      cCs½|iƒ|i|iƒ|iƒg}||ii7}x|iD]}||i7}qDW||i i7}||i i7}x|i D]}||i7}q…W||i i7}di |ƒSdS(Ns (sselfsbegins proc_streams module_codesendspartsscodes module_defsscs class_codes expand_codes inst_defssend_module_codesjoin(sselfspartssc((s(build/bdist.linux-i686/egg/kid/parser.pysparseJs    cCs[|i}|idƒ|idƒ|idƒ|idƒ|idƒ|id|iƒ|idƒ|idƒ|id ƒ|id ƒ|id ƒ|id ƒ|id ƒ|idƒ|idƒ|i}|idƒ|idƒ|idƒ|iƒ|idƒ|idƒ|idƒ|idƒ|i}|idƒdS(Ns!from __future__ import generatorss import kidsfrom kid.template_util import *s)import kid.template_util as template_utils_def_names = []sencoding = "%s"sdoctype = Nones!omit_namespaces = [kid.KID_XMLNS]slayout_params = {}s,def pull(**kw): return Template(**kw).pull()s“def generate(encoding=encoding, fragment=0, output=None, **kw): return Template(**kw).generate(encoding=encoding, fragment=fragment, output=output)s•def serialize(encoding=encoding, fragment=0, output=None, **kw): return Template(**kw).serialize(encoding=encoding, fragment=fragment, output=output)s™def write(file, encoding=encoding, fragment=0, output=None, **kw): return Template(**kw).write(file, encoding=encoding, fragment=fragment, output=output)sBaseTemplate = kid.BaseTemplatesdef initialize(template): passsdef initialize(self):srslt = initialize(self)s0if rslt != 0: super(Template, self).initialize()sdef _pull(self):s-exec template_util.get_locals(self, locals())scurrent, ancestors = None, []s$if doctype: yield (DOCTYPE, doctype)s( sselfs module_codescodeslinesencodings expand_codes start_blocks end_blocksend_module_code(sselfscode((s(build/bdist.linux-i686/egg/kid/parser.pysbeginYs6                         cCs|iiƒdS(N(sselfs expand_codes end_block(sself((s(build/bdist.linux-i686/egg/kid/parser.pysendscCsex^|iD]S\}}|tjo‘|itjo·|iiƒ}|i dƒoq n|i } |i dƒp |i dƒo=t |iƒ}t|tƒod|}qÎt|ƒ}nt|iƒ}| d|ƒ| dƒq]|itjoÁd|iiƒjo|iiddƒ\} } n|id f\} } | tttfjo| o|i| ƒq·q°|io|p|i} | i d | | fƒ| i dƒ~ q]t}||ijoý|i t!ƒ}|tj o|i"t!=nd g}|i t$ƒ} g}| tj o9|i"t$=x,| id ƒD]} |i'd | ƒq@Wn|i'dƒ|i'd i(|ƒƒ|i'dƒ|i)}|i*d i(|ƒƒ|i dƒ|i}~~n|i+||i"|ƒ|tj o¿|}t-ddƒ}|i*dƒ|i dƒ|i dƒ|i dƒ|i dƒ|i dƒ|i dƒ|i d|ƒ|i dƒ|i dƒ|i.ƒ|i/i'|ƒ|}q]q |t0jo|ittfj oPq |t1jo|i2||ƒq |t3jo|dtj o|ii d|dƒq |t4jo|ii d|ƒq q WdS(Ns!s         cCs¸|itƒ}|tj o…|t=|}tddƒ}|idƒ|i dƒ|i dƒ|i |||ƒ|i ƒ|i d|ƒ|ii|ƒn|i |||ƒdS(Nslevelis#def _match_func(self, item, apply):s-exec template_util.get_locals(self, locals())scurrent, ancestors = None, []s7_match_templates.append((lambda item: %s, _match_func))(sattribsgets QNAME_MATCHsexprsNonescodesold_codes CodeGenerators start_blockslinesselfsfor_procsitems end_blocks inst_defssappend(sselfsitemsattribscodesold_codesexpr((s(build/bdist.linux-i686/egg/kid/parser.pys match_procûs     cCsl|itƒ}|tj o9|id|ƒ|t=|i|||ƒ|i ƒn|i|||ƒdS(Nsfor %s:( sattribsgets QNAME_FORsexprsNonescodes start_blocksselfsif_procsitems end_block(sselfsitemsattribscodesexpr((s(build/bdist.linux-i686/egg/kid/parser.pysfor_proc s cCsl|itƒ}|tj o9|id|ƒ|t=|i|||ƒ|i ƒn|i|||ƒdS(Nsif %s:( sattribsgetsQNAME_IFsexprsNonescodes start_blocksselfs replace_procsitems end_block(sselfsitemsattribscodesexpr((s(build/bdist.linux-i686/egg/kid/parser.pysif_procs cCsR|itƒ}|tj o|t=d|t<||t               c Csud}|i} d} t|ddƒ}xg|iƒD]Y\} }t |ƒ}t |ƒt |ƒjo(||| s  (  Q &   & " s SubExpressioncBstZd„ZRS(NcCsddi|ƒSdS(Ns[%s]s, (sjoinsself(sself((s(build/bdist.linux-i686/egg/kid/parser.pys__repr__ƒs(s__name__s __module__s__repr__(((s(build/bdist.linux-i686/egg/kid/parser.pys SubExpression‚ss(?|diƒggi}|dD]}||iƒƒq"~}t}x|dD]„}|djoq|iƒ}|ddjoPt |ƒt |ƒ}|tjp ||jo|}|djoPqÏqÓq×qSqSW|tj p |djoEgi}|dD]"}||| iƒ||ƒq~|d)n|do|dddj oÛyt |dddƒWq6t j oªy'di|ƒd}t |ddƒWq2tj og|d gi}|dD]}|||ƒqÕ~}di|ƒd}t |ddƒ|}q2q2Xq6q6Xn|SdS( s)Adjust the indentation of a Python block.iiss#ssexecs N(slinessstripsappends_[1]slinesrstripsNonesindslstripssslensiscompiles SyntaxErrorsjoinsblocksIndentationErrorstabslines2( slinesstabsislines2s_[1]sssindslinesblock((s(build/bdist.linux-i686/egg/kid/parser.pys_adjust_python_blockÒs@B    E!7 ccs:x3ttt|ƒƒ|ƒD]\}}||fVqWdS(N(szipsrangeslensseqsiselem(sseqsiselem((s(build/bdist.linux-i686/egg/kid/parser.pys enumerateýs (0s__doc__s __future__s generatorss __revision__s__date__s __author__s __copyright__s __license__sreskid.pullskid.ets namespacesskids Namespaces KID_XMLNSs KID_PREFIXskidnss QNAME_FORsQNAME_IFs QNAME_DEFs QNAME_SLOTs QNAME_CONTENTs QNAME_REPLACEs QNAME_MATCHs QNAME_STRIPsQNAME_ATTRIBUTESs QNAME_EXTENDSs QNAME_LAYOUTs QNAME_OMITs QNAME_REPEATsKID_PIs KID_ALT_PIs KID_OLD_PIsNonesparses parse_filesobjects KidParserslists SubExpressionscompiles _sub_exprs_sub_expr_shorts interpolates CodeGenerators_adjust_python_blocks enumerates NameError(&s QNAME_STRIPsQNAME_ATTRIBUTESs Namespaces SubExpressions KID_PREFIXsparses QNAME_REPEATs QNAME_LAYOUTs enumerateskidnss QNAME_OMITs QNAME_SLOTs __revision__s QNAME_REPLACEs QNAME_DEFsres _sub_exprs generatorss QNAME_EXTENDSs parse_files QNAME_FORs_sub_expr_shortsKID_PIs __license__s interpolates __author__s KidParsers_adjust_python_blocks namespacessQNAME_IFs QNAME_CONTENTs __copyright__s KID_XMLNSs CodeGenerators QNAME_MATCHs__date__s KID_ALT_PIs KID_OLD_PI((s(build/bdist.linux-i686/egg/kid/parser.pys?sV                   ÿE + (PK ²Ð4IbÚÅí í kid/et.py"""ElementTree extensions.""" __revision__ = "$Rev$" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os # If allowed and possible, import all objects from CElementTree: try: if os.environ.get('KID_NOCET'): raise ImportError else: try: if os.environ.get('KID_NOET'): raise ImportError else: import cElementTree as CET from cElementTree import * except ImportError: # you must have Python 2.5 or newer import xml.etree.cElementTree as CET from xml.etree.cElementTree import * except: CET = None # Otherwise, import all objects from ElementTree: try: if os.environ.get('KID_NOET'): raise ImportError else: import elementtree.ElementTree as ET if not CET: from elementtree.ElementTree import * except ImportError: # you must have Python 2.5 or newer import xml.etree.ElementTree as ET if not CET: from xml.etree.ElementTree import * # These functions exist only in ET, not in CET: encode_entity = ET._encode_entity raise_serialization_error = ET._raise_serialization_error # We take the Comment factory from ET, not from CET, # because this guarantees that Comment().tag = Comment # (another possibile solution would have been to set # CommentTag = Comment().tag and then later compare tags # against CommentTag). Same for ProcessingInstructions. Comment = ET.Comment ProcessingInstruction = ET.ProcessingInstruction # The fragment factory does not exist in ElementTree: def Fragment(text=''): """XML fragment factory. Fragments hold TEXT and children but do not have a tag or attributes. """ elem = Element(Fragment) elem.text = text return elem def namespaces(elem, remove=0): """Get the namespace declarations for an Element. This function looks for attributes on the Element provided that have the following characteristics: * Begin with 'xmlns:' and have no namespace URI. * Are named 'xmlns' and have no namespace URI. The result is a dictionary containing namespace prefix -> URI mappings. Default namespace attributes result in a key of ''. If remove is truthful, namespace declaration attributes are removed from the passed in Element. """ names = {} for k in elem.keys(): if k.startswith('xmlns:'): names[k[6:]] = elem.get(k) if remove: del elem.attrib[k] elif k == 'xmlns': names[''] = elem.get(k) if remove: del elem.attrib[k] return names __all__ = ['Element', 'SubElement', 'Comment', 'ProcessingInstruction', 'Fragment', 'ElementTree', 'QName', 'dump', 'parse', 'tostring', 'namespaces', 'encode_entity', 'raise_serialization_error'] PKY´Ð41rôA*L*L kid/pull.pyc;ò º-“Dc@s·dZdklZdZdZdZdZdZdkTdk l Z l Z d k l Z d kZhZgZxDeiiƒD]3\ZZeeƒee(s*(s open_resourcesQuickTextReader(sexpatNss sInvalidStreamStatecBstZdd„ZRS(NsInvalid stream state.cCsti||ƒdS(N(s Exceptions__init__sselfsmsg(sselfsmsg((s&build/bdist.linux-i686/egg/kid/pull.pys__init__s(s__name__s __module__s__init__(((s&build/bdist.linux-i686/egg/kid/pull.pysInvalidStreamStatesicCs|idƒp |idƒo d}n|oŒ|od||f}n d|}t|tƒod}|i|ƒ}ntt |ƒ|ƒ}||_ t t |d|ƒƒiƒSn^t|tƒod}|i|ƒ}ntt |ƒ|ƒ}||_ t t |d|ƒƒSdS( s*Element generator that reads from a strings%ss %ssutf-16sencodingN(stexts startswithsfragmentsxmlnss isinstancesunicodesencodingsencodesParsersQuickTextReadersps _sourcetexts ElementStreams _coalescesstrip(stextsfragmentsencodingsxmlnssp((s&build/bdist.linux-i686/egg/kid/pull.pysXMLs&      cCs„t|dƒ o*|tjo |}nt|dƒ}n|tjo d}nt||ƒ}||_t t |d|ƒƒSdS(Nsreadsrbssencoding( shasattrsfilesfilenamesNones open_resourcesParsersencodingsps _filenames ElementStreams _coalesce(sfilesencodingsfilenamesp((s&build/bdist.linux-i686/egg/kid/pull.pysdocument6s     s ElementStreamcBsqtZdZed„Zd„Zd„Zdd„Zd„Zdd„Z ed „Z ed „Z e e ƒZ RS( s¾Provides a pull/streaming interface to ElementTree. Instances of this class are iterable. Most methods of the class act on the Element that is currently being visited. cCsat|dƒo t|dƒo|i|ddƒ}nt|_|it|ƒ|ƒ|_dS(sòCreate an ElementStream. stream - an iterator that returns ElementStream events. current - If an Element is provided in this parameter than it is yielded as the first element in the stream. stagsattribstailiN( shasattrsstreamsselfs_pullsNonescurrents_tracksiters_iter(sselfsstreamscurrent((s&build/bdist.linux-i686/egg/kid/pull.pys__init__Ks   cCs |iSdS(N(sselfs_iter(sself((s&build/bdist.linux-i686/egg/kid/pull.pys__iter__XscCs<|i}|tjo g}n|g}t}xæ|iD]Û\}}|tjoE|}t |ƒdjo|di |ƒnt}|i |ƒq9|t jo<|i ƒ}||jpt ‚t |ƒdjoPqq9|tjo'|tj o ||_q||_q9q9Wt|tƒo |dSn|SdS(s4Expand the current item in the stream as an Element.iiÿÿÿÿN(sselfscurrentsNonesstackslasts_itersevsitemsSTARTslensappendsENDspopsAssertionErrorsTEXTstailstexts isinstanceslist(sselfslastscurrentsitemsevsstack((s&build/bdist.linux-i686/egg/kid/pull.pysexpand[s4             iccsØ|itj odpd}x´|iD]©\}}|tjo|d7}n||jp||jo|tt fjo||fVn|t jo:|d8}|djoPqÐ|djo t ƒ‚qÐq'q'WdS(Nii( sselfscurrentsNonesdepths_itersevsitemsSTARTslevelssENDsInvalidStreamState(sselfslevelssitemsdepthsev((s&build/bdist.linux-i686/egg/kid/pull.pysstripys  -    cCs‡|itj odpd}x_|iD]T\}}|tjo|d7}q'|tjo |d8}|djoPq{q'q'W|SdS(s0Eat the current element and all decendant items.iiN( sselfscurrentsNonesdepths_itersevsitemsSTARTsEND(sselfsitemsdepthsev((s&build/bdist.linux-i686/egg/kid/pull.pyseat‡s      iccsà|}t|it|iƒƒ}|ittfjo|i|_t |_nt |fV|iot |ifVnx8|i ƒD]*}x!|i|ddƒD] }|VqžWq‚Wt|fV|o|iot |ifVndS(Nstaili(selemsorigsElementstagsdictsattribsCommentsProcessingInstructionstextsNonesSTARTsTEXTs getchildrenschildsselfs_pullseventsENDstail(sselfselemstailschildseventsorig((s&build/bdist.linux-i686/egg/kid/pull.pys_pull“s        ccsƒ|tj o||_t|fVnxX|D]P}|\}}|tjo ||_n|tjo t|_n||fVq+WdS(N( scurrentsNonesselfsSTARTsstreamspsevsitemsEND(sselfsstreamscurrentspsitemsev((s&build/bdist.linux-i686/egg/kid/pull.pys_track¤s       cCs)t||ƒo|Sn|||ƒSdS(N(s isinstancesstreamsclsscurrent(sclssstreamscurrent((s&build/bdist.linux-i686/egg/kid/pull.pysensure°s( s__name__s __module__s__doc__sNones__init__s__iter__sexpandsstripseats_pulls_tracksensures classmethod(((s&build/bdist.linux-i686/egg/kid/pull.pys ElementStreamBs      cCsht|tƒo|Snt|dƒot|ƒSnt|tƒ ot|ƒ}nt||ƒSdS(Ns __unicode__(s isinstancesvaluesunicodeshasattrsstrsencoding(svaluesencoding((s&build/bdist.linux-i686/egg/kid/pull.pys to_unicode¸sccsêg}g}t}t} t}tg} xl|D]d\}} |t jo|i | ƒt }q.n|t joId}x!|D]} |t| |ƒ7}q{Wg}|ot |fVq·n|tjo`| i}x7|D]/\}} |o| |d|s}i(1shasattrssourcesfilenamesopensselfs _filenames_sourcesexpats ParserCreatesencodings_parsersparsers_queues_defaultsDefaultHandlers_startsStartElementHandlers_endsEndElementHandlers_datasCharacterDataHandlers_pisProcessingInstructionHandlers_commentsCommentHandlers _start_nssStartNamespaceDeclHandlers_end_nssEndNamespaceDeclHandlers_xmldecl_handlersXmlDeclHandlers_doctype_handlersStartDoctypeDeclHandlers buffer_textsAttributeErrorsordered_attributessspecified_attributess _start_listsNones_doctypesdefault_entity_mapsentitysdefault_external_dtds external_dtdsSetParamEntityParsingsXML_PARAM_ENTITY_PARSING_ALWAYSs _buildForeignsExternalEntityRefHandlers UseForeignDTD(sselfssourcesencodingsparsersfilename((s&build/bdist.linux-i686/egg/kid/pull.pys__init__sD                  cCsWdk}|itƒ}|i}|ii|ƒ|_|ii|ƒ||_dSdS(Ni( sStringIOsdefault_external_dtds parseableFilesselfs_parsersoriginal_parsersExternalEntityParserCreatescontexts ParseFile(sselfscontextsbasessystemIdspublicIdsoriginal_parsersStringIOs parseableFile((s&build/bdist.linux-i686/egg/kid/pull.pys _buildForeignBs   cCs|ii||fƒdS(N(sselfs_queuesappendsevsstuff(sselfsevsstuff((s&build/bdist.linux-i686/egg/kid/pull.pyspushKsccsÂdd}|i}|ii}d}x–noŽxZ| ot|iƒdjo;||ƒ}|djo|i ƒd}q2||ƒq2Wx|iD] }|Vq–Wg|_|oPq(q/WdS(Niiiis( sbufsizesselfsfeeds_sourcesreadsdoneslens_queuesdatasclosesi(sselfsfeedsreadsisdonesbufsizesdata((s&build/bdist.linux-i686/egg/kid/pull.pys _expat_streamNs&         c #sÞh‰d‰d‰‡‡‡d†} g} t}t}x¡|i ƒD]“\}} |t jot | fVqC|t jo†| \}}| |ƒ}h}|o1x.|iƒD]\} } | || | ƒtj o2|}d|jod|}n|ˆ| Strips the supplied path from the beginning of source filenames stored for error messages in the generated .pyc files The file list may have files and/or directories. If a directory is specified, all .kid files found in the directory and any sub-directories are compiled. s $Rev: 139 $s5$Date: 2005-03-14 19:28:22 -0500 (Mon, 14 Mar 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sisdir(sgetopts GetoptErrorc Cs y/ttiddddddgƒ\} }WnLtj o@}tiit t ƒdƒti it ƒti dƒnXd }d }t}xŸ| D]—\} }| d d fjo t}q—| d d fjo t}q—| ddfjo!ti it ƒti d ƒq—| ddfjo |}q—q—W|}| o1tiidƒtiidƒti dƒnd„}xŠ|D]‚}t|ƒo=xltii|d|d|d|ƒD]} || ƒq¹Wqtii|d|d|d|ƒ|t|fƒqWdS(Nisfshd=sforcessourceshelpsstrip-dest-dir=s iis-fs--forces-ss--sources-hs--helps-ds--strip-dest-dirs!kidc: No kid template specified. s/ Try 'kidc --help' for usage information. cCsf|\}}|tjod|}n,|tjod|}nd||f}tii|ƒdS(Ns compile: %s s fresh: %s serror: %s (%s) (srsltsfilesTruesmsgsFalsessyssstderrswrite(srsltsfilesmsg((s)build/bdist.linux-i686/egg/kid/compile.pys print_resultAs   sstrip_dest_dir(sgetoptssyssargvsoptssargssgerrorsmsgsstderrswritesstrsesstdouts__doc__sexitsforcessourcesNonesstrip_dest_dirsosasTruesfiless print_resultsfsisdirskidscompilers compile_dirsrslts compile_file( sforcesstrip_dest_dirs print_resultssourcesmsgsfilessargssasfsosrsltsopts((s)build/bdist.linux-i686/egg/kid/compile.pysmain$sD/     %"s__main__(s__doc__s __revision__s__date__s __author__s __copyright__s __license__ssyssos.pathsisdirsgetopts GetoptErrorsgerrors kid.compilerskidsmains__name__( sisdirssyss __copyright__s __revision__s __license__sgerrors __author__s__date__sgetoptsmainskid((s)build/bdist.linux-i686/egg/kid/compile.pys?s    0 PK ²Ð4@@–~~kid/compiler.py"""Kid Compiler Compile XML to Python byte-code. """ from __future__ import generators __revision__ = "$Rev: 262 $" __date__ = "$Date: 2006-01-28 16:38:09 +0000 (Sat, 28 Jan 2006) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys import re import os import os.path import imp import stat import struct import marshal import new import kid.parser __all__ = ['KID_EXT', 'compile', 'compile_file', 'compile_dir'] # kid filename extension KID_EXT = ".kid" py_compile = compile def actualize(code, dict=None): if dict is None: dict = {} exec code in dict return dict def compile(source, filename='', encoding=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.parser.parse(source, encoding, filename=filename) return py_compile(py, filename, 'exec') _timestamp = lambda filename : os.stat(filename)[stat.ST_MTIME] class KidFile(object): magic = imp.get_magic() def __init__(self, kid_file, force=0, encoding=None, strip_dest_dir=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 or 'utf-8' fp = None if force: stale = 1 else: stale = 0 try: fp = open(self.pyc_file, "rb") except IOError: stale = 1 else: if fp.read(4) != self.magic: stale = 1 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 rslt in compile_dir(fullname, maxlevels - 1, force, source, strip_dest_dir): yield rslt return PK ²Ð4+}`ù¹ ¹ kid/filter.py"""Kid tranformations""" from __future__ import generators __revision__ = "$Rev: 53 $" __date__ = "$Date: 2005-02-15 08:10:35 -0500 (Tue, 15 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from types import GeneratorType from kid.pull import ElementStream, START, XML_DECL, _coalesce from kid.namespace import Namespace from template_util import generate_content def transform_filter(stream, template): templates = template._get_match_templates() def apply_func(item): return transform_filter(generate_content(item), template) stream = ElementStream.ensure(stream) for ev, item in apply_matches(stream, template, templates, apply_func): yield ev, item def apply_matches(stream, template, templates, apply_func): for ev, item in stream: if ev == START: matched = 0 for i in range(0, len(templates)): (match, call) = templates[i] if match(item): item = stream.expand() newstream = _coalesce(call(template, item, apply_func), template._get_assume_encoding()) if len(templates) < 2: for ev, item in newstream: yield (ev, item) else: for ev, item in apply_matches(ElementStream(newstream), template, templates[:i] + templates[i+1:], apply_func): yield ev, item matched = 1 break if matched: continue yield (ev, item) # XXX haven't tested this yet.. def xinclude_filter(stream, template): xi = Namespace('http://www.w3.org/2001/XInclude') include = xi.include fallback = xi.fallback for ev, item in stream: if ev == START and item.tag == xi.include: item = item.expand() href = item.get('href') try: doc = document(href, template._get_assume_encoding()) except: fallback_elm = item.find(fallback) for ev, item in ElementStream(fallback_elm).strip(1): yield ev, item else: for ev, item in doc: if ev != XML_DECL: yield ev PK ²Ð4 ·1¯t"t" kid/server.py"""Kid-savvy HTTP Server. Written by Christoph Zwerschke based on CGIHTTPServer 0.4. This module builds on SimpleHTTPServer by implementing GET and POST requests to Kid templates. In all cases, the implementation is intentionally naive -- all requests are executed by the same process and sychronously. Code to create and run the server looks like this: from kid.server import HTTPServer host, port = 'localhost', 8000 HTTPServer((host, port)).serve_forever() This serves files and kid templates from the current directory and any of its subdirectories. If you want the server to be accessible via the network, use your local host name or an empty string as the host. (Security warning: Don't do this unless you are inside a firewall.) You can also call the test() function to run the server, or run this module as a script, providing host and port as command line arguments. The Kid templates have access to the following predefined objects: FieldStorage (access to GET/POST variables) environ (CGI environment) request (the request handler object) Here is a simple Kid template you can use to test the server: Python Expression Evaluator

${FieldStorage.getvalue('expr')} = ${eval(FieldStorage.getvalue('expr'))}

Enter a Python expression:

""" __revision__ = "$Rev: 1 $" __date__ = "$Date: 2005-01-01 00:00:00 +0000 (Mon, 1 Jan 2005) $" __author__ = "Christoph Zwerschke (cito@online.de)" __copyright__ = "Copyright 2005, Christoph Zwerschke" __license__ = "MIT " __all__ = ["HTTPServer", "HTTPRequestHandler"] import os.path from urllib import unquote from BaseHTTPServer import HTTPServer as BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler from cgi import FieldStorage from kid import load_template default_host = 'localhost' default_port = 8000 class HTTPRequestHandler(SimpleHTTPRequestHandler): """Complete HTTP server with GET, HEAD and POST commands. GET and HEAD also support running Kid templates. The POST command is *only* implemented for Kid templates.""" def do_POST(self): """Serve a POST request implemented for Kid templates.""" if self.is_kid(): self.run_kid() else: self.send_error(501, "Can only POST to Kid templates") def send_head(self): """Version of send_head that supports Kid templates.""" if self.is_kid(): return self.run_kid() else: return SimpleHTTPRequestHandler.send_head(self) def is_kid(self): """Test whether self.path corresponds to a Kid template. The default implementation tests whether the path ends with one of the strings in the list self.kid_extensions. """ path = self.path i = path.rfind('?') if i >= 0: path, query = path[:i], path[i+1:] else: query = '' for x in self.kid_extensions: if path.endswith(x): self.cgi_info = path, query return True return False kid_extensions = ['.kid', '.kid.html'] def run_kid(self): """Execute a Kid template.""" scriptname, query = self.cgi_info scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such Kid template (%r)" % scriptname) return if not os.path.isfile(scriptfile): self.send_error(403, "Kid template is not a plain file (%r)" % scriptname) return env = {} env['SERVER_SOFTWARE'] = self.version_string() env['SERVER_NAME'] = self.server.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PROTOCOL'] = self.protocol_version env['SERVER_PORT'] = str(self.server.server_port) env['REQUEST_METHOD'] = self.command uqpath = unquote(scriptname) env['PATH_INFO'] = uqpath env['PATH_TRANSLATED'] = self.translate_path(uqpath) env['SCRIPT_NAME'] = scriptname if query: env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] authorization = self.headers.getheader("authorization") if authorization: authorization = authorization.split() if len(authorization) == 2: import base64, binascii env['AUTH_TYPE'] = authorization[0] if authorization[0].lower() == "basic": try: authorization = base64.decodestring(authorization[1]) except binascii.Error: pass else: authorization = authorization.split(':') if len(authorization) == 2: env['REMOTE_USER'] = authorization[0] if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length accept = [] for line in self.headers.getallmatchingheaders('accept'): if line[:1] in "\t\n\r ": accept.append(line.strip()) else: accept = accept + line[7:].split(',') env['HTTP_ACCEPT'] = ','.join(accept) ua = self.headers.getheader('user-agent') if ua: env['HTTP_USER_AGENT'] = ua co = filter(None, self.headers.getheaders('cookie')) if co: env['HTTP_COOKIE'] = ', '.join(co) self.send_response(200, "Script output follows") # Execute template in this process try: template_module = load_template(scriptfile, cache=1) template = template_module.Template( request=self, environ=env, FieldStorage=FieldStorage(self.rfile, environ=env)) s = str(template) self.send_header("Content-type", "text/html") self.send_header("Content-Length", str(len(s))) self.end_headers() self.wfile.write(s) except Exception, e: self.log_error("Kid template exception: %s", str(e)) else: self.log_message("Kid template exited OK") class HTTPServer(BaseHTTPServer): def __init__(self, server_address = None, RequestHandlerClass = HTTPRequestHandler): if server_address is None: server_address = (default_host, default_port) BaseHTTPServer.__init__(self, server_address, HTTPRequestHandler) def test(server_address = None, HandlerClass = HTTPRequestHandler, ServerClass = HTTPServer, protocol = "HTTP/1.0"): """Test the HTTP request handler class.""" HandlerClass.protocol_version = protocol server = ServerClass(server_address, HandlerClass) sa = server.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." server.serve_forever() def main(): """This runs the Kid-savvy HTTP server. Provide host and port as command line arguments. The current directory serves as the root directory. """ from sys import argv, exit if len(argv) > 3: print "Usage:", argv[0], "[host]:[port]" exit(2) if len(argv) < 2: server_address = (default_host, default_port) else: if len(argv) == 3: host = argv[1] port = argv[2] else: host = argv[1].split(':', 1) if len(host) < 2: host = host[0] if host.isdigit(): port = host host = '' else: port = None else: host, port = host if port: if port.isdigit(): port = int(port) else: print "Bad port number." exit(1) else: port = default_port server_address = (host, port) test(server_address) if __name__ == '__main__': main() PKY´Ð4jëýÊkid/template_util.pyc;ò º-“Dc@s‰dZdklZdZdZdZdZdZdkZdk Z dk l Z l Z d k lZlZlZlZdkZd klZlZlZlZlZlZlZlZlZlZlZlZl Z l!Z!l"Z"l#Z#d e$fd „ƒYZ%d dddddgZ&e'd„Z(d„Z)e'd„Z*e'd„Z+d„Z,d„Z-dddddddd d!d"d#d$d%d&d'gZ.dS((s1Utility functions used by generated kid modules. (s generatorss $Rev: 314 $s5$Date: 2006-04-18 00:37:38 +0000 (Tue, 18 Apr 2006) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sTypeTypes ModuleType(sjoinsnormpathsabspathsdirname(sXMLsdocuments ElementStreamsElements SubElementsCommentsProcessingInstructionsSTARTsENDsTEXTsSTART_NSsCOMMENTsPIsDOCTYPEsXML_DECLs to_unicodesTemplateNotFoundcBstZRS(N(s__name__s __module__(((s/build/bdist.linux-i686/egg/kid/template_util.pysTemplateNotFoundssgeneratesmodulespulls serializes transformswritecCs›|tjo h}ng}t}xdti|ƒD]S\}}|i dƒ o||j o ||jo|i d||fƒq3q3Wdi |ƒSdS(Ns_s %s=self.%ss;( s_localssNoneslss_local_excludesslocal_excludessinspects getmemberssinstsvarsvalues startswithsappendsjoin(sinsts_localsslocal_excludessvalueslssvar((s/build/bdist.linux-i686/egg/kid/template_util.pys get_localss   ,cCs´|tjp |tijo ti}nƒt|tƒo+tii||ƒ}ti |ƒi }nHt|t ƒo |}n.t|t ƒo |i }ntd|ƒ‚|SdS(NsCould not find template: %r(sthingsNoneskids BaseTemplatesclss isinstances basestringspathsfinds from_files load_templatesTemplatesTypeTypes ModuleTypesTemplateNotFound(sthings from_filespathscls((s/build/bdist.linux-i686/egg/kid/template_util.pysget_base_class&s   cCså|tjohSn|tjotiƒ}nx¨|iƒD]š\}}t|t ƒokgi }|D]*}|tj o|t ||ƒƒqiqi~}| o ||=qÙdi|ƒ|| %ss%s in %sN($sNonesstringssevalsssglobalsslocalssbs TypeErrors SyntaxErrors cStringIOsStringIOs ImportErrorstokenizesgenerate_tokensstokensNAMEsOPsdepthstypessreadlinestype_sstringslensjoinsappends Exceptionssyssexc_infosexc_typesexc_objstbscodeskeyssksasupdate(sasssglobalsslocalsscodesexc_typestokensexc_objsgenerate_tokensstbsstringstypessbsNAMEsStringIOskstype_sdepthsstringssOP((s/build/bdist.linux-i686/egg/kid/template_util.pys update_dictbsZ    /Q"  (     sXMLsdocuments ElementStreamsElements SubElementsCommentsProcessingInstructionsSTARTsENDsTEXTsSTART_NSsCOMMENTsPIsDOCTYPEsXML_DECL(/s__doc__s __future__s generatorss __revision__s__date__s __author__s __copyright__s __license__sinspectssysstypessTypeTypes ModuleTypesos.pathsjoinsnormpathsabspathsdirnameskidskid.pullsXMLsdocuments ElementStreamsElements SubElementsCommentsProcessingInstructionsSTARTsENDsTEXTsSTART_NSsCOMMENTsPIsDOCTYPEsXML_DECLs to_unicodes ExceptionsTemplateNotFounds_local_excludessNones get_localssget_base_classs make_attribsgenerate_contents filter_namess update_dicts__all__((s to_unicodesget_base_classsTypeTypesTEXTsDOCTYPEs ElementStreamsXML_DECLsdirnames_local_excludessCOMMENTs __revision__s__all__sgenerate_contentsSTART_NSs generatorss ModuleTypesdocumentsXMLsENDs __license__sabspathsinspects __author__ssyssSTARTsTemplateNotFounds get_localssElements make_attribskidsComments __copyright__sPIsjoinsProcessingInstructions update_dicts filter_namessnormpaths__date__s SubElement((s/build/bdist.linux-i686/egg/kid/template_util.pys?s*    g     8PK ²Ð40>ý· · kid/compile.py#!/usr/bin/python # This module provides the "kidc" command """Usage: kidc [OPTIONS] [file...] Compile kid templates into Python byte-code (.pyc) files. OPTIONS: -f, --force Force compilation even if .pyc file already exists. -s, --source Generate .py source files along with .pyc files. This is sometimes useful for debugging. -d, --strip-dest-dir Strips the supplied path from the beginning of source filenames stored for error messages in the generated .pyc files The file list may have files and/or directories. If a directory is specified, all .kid files found in the directory and any sub-directories are compiled. """ __revision__ = "$Rev: 139 $" __date__ = "$Date: 2005-03-14 19:28:22 -0500 (Mon, 14 Mar 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys from os.path import isdir from getopt import getopt, GetoptError as gerror import kid.compiler def main(): # get options try: opts, args = getopt(sys.argv[1:], 'fshd=', ['force', 'source', 'help', 'strip-dest-dir=']) except gerror, msg: sys.stderr.write(str(e) + '\n') sys.stdout.write(__doc__) sys.exit(2) force = 0 source = 0 strip_dest_dir = None for o, a in opts: if o in ('-f', '--force'): force = True elif o in ('-s', '--source'): source = True elif o in ('-h', '--help'): sys.stdout.write(__doc__) sys.exit(0) elif o in ('-d', '--strip-dest-dir'): strip_dest_dir = a files = args if not files: sys.stderr.write('kidc: No kid template specified.\n') sys.stderr.write(" Try 'kidc --help' for usage information.\n") sys.exit(2) # a quick function for printing results def print_result(rslt): (rslt, file) = rslt if rslt == True: msg = 'compile: %s\n' % file elif rslt == False: msg = 'fresh: %s\n' % file else: msg = 'error: %s (%s)\n' % (file, rslt) sys.stderr.write(msg) # run through files and compile for f in files: if isdir(f): for rslt in kid.compiler.compile_dir(f, force=force, source=source, strip_dest_dir=strip_dest_dir): print_result(rslt) else: kid.compiler.compile_file(f, force=force, source=source, strip_dest_dir=strip_dest_dir) print_result((True, f)) if __name__ == '__main__': main() PKZ´Ð4œØPÅÅ kid/run.pyc;ò º-“Dc@sdZdZdZdZdZdZdkZdklZl Z dk l Z l Z dk Z d „Zed jo eƒndS( s÷Usage: kid [options] file [args] Expand a Kid template file. OPTIONS: -e enc, --encoding=enc Specify the output character encoding. Default: utf-8 -o outfile, --output=outfile Specify the output file. Default: standard output -s host:port, --server=host:port Specify the server address if you want to start the HTTP server. Instead of the Kid template, you can specify a base directory. -h, --help Print this help message and exit. -V, --version Print the Kid version number and exit. file: filename of the Kid template to be processed or "-" for reading the template from stdin. args: key=value or other arguments passed to the template. s $Rev: 139 $s5$Date: 2005-03-14 19:28:22 -0500 (Mon, 14 Mar 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sdirnamesabspath(sgetopts GetoptErrorcCsay2ttidddddddgƒ\}}WnLtj o@} tiit | ƒdƒti it ƒti d ƒnXd }t} }xä|D]Ü\}} |d d fjo | }q˜|d dfjo | } q˜|ddfjo | }q˜|ddfjo!ti it ƒti dƒq˜|ddfjo2dkl}ti id|ƒti dƒq˜q˜W|tjoˆ|oP|idƒ}|gt_|djo>tt|ƒƒ}|tij otiid|ƒqntiiƒ}h}xd|o\|idƒiddƒ} t| ƒdjo| d|| dNsKID_EXTscompiles compile_files compile_dirs.kidcBs'|ejo h}n||U|SdS(N(sdictsNonescode(scodesdict((s*build/bdist.linux-i686/egg/kid/compiler.pys actualize!s  scCs/tii||d|ƒ}t||dƒSdS(s¡Compiles kid xml source to a Python code object. source -- A file like object - must support read. filename -- An optional filename that is used sfilenamesexecN(skidsparsersparsessourcesencodingsfilenamespys py_compile(ssourcesfilenamesencodingspy((s*build/bdist.linux-i686/egg/kid/compiler.pyscompile'scCsti|ƒtiS(N(sossstatsfilenamesST_MTIME(sfilename((s*build/bdist.linux-i686/egg/kid/compiler.pys3ssKidFilecBswtZeiƒZdeed„Zddd„Zd„Ze eƒZd„Z e e ƒZ ed„Z ed„Z RS( Nic Cs8||_tii|ƒdd|_||_|id|_|pd|_t }|o d}n«d}yt |idƒ}Wntj o d}ntX|idƒ|ijo d}nPtid|idƒƒd}t|ƒ}|t jp ||jo d}n||_ ||_t |_t |_dS( Nis.pyscsutf-8isrbist j o2yt i |ƒWnt j onXdSnXdSdS(Nswbs# -*- coding: utf-8 -*- sutf-8ii( sselfspythonspysfilespy_files _maybe_opensfpswritesencodesIOErrorsossunlinksOSError(sselfsfilesfpspy((s*build/bdist.linux-i686/egg/kid/compiler.pys dump_sourceqs   cCsÿ|i}|p|i}yt|dƒ}|ioti|iƒti }nd}|i dƒ|i t i d|ƒƒti||ƒ|iƒ|idƒ|i |iƒWn>tj o2yti|ƒWntj onXdSnXdSdS(NswbissNi±sneed Python 2.0b1 or latercCs#t otd|ƒtandS(Nssuffixes(s _installeds _install_hookssuffixessTrue(ssuffixes((s*build/bdist.linux-i686/egg/kid/importer.pysinstalls cCstotƒtandS(N(s _installeds_uninstall_hooksFalse(((s*build/bdist.linux-i686/egg/kid/importer.pys uninstallsicCs{| o|otii|ƒoti|Sntii|ƒ}|i dt i i dƒƒ}t|||ƒ}|SdS(Ns dump_sources KID_OUTPUT_PY(sforcesnamessyssmodulesshas_keyskidscompilersKidFilesfilenamestemplatescompilesossenvironsgetscodes_create_modulesmodule(snamesfilenamesforcescodesmodulestemplate((s*build/bdist.linux-i686/egg/kid/importer.pysimport_template$s "cCs,|o|Sndt|ƒtidSdS(Nskid.util.template_%xi(snameshashsfilenamessyssmaxint(snamesfilename((s*build/bdist.linux-i686/egg/kid/importer.pysget_template_name,sicBsqe||ƒ}ei|ƒ}||_eiƒ|_|i i |ƒ||i U|o|ei||ttƒjo*t|tjo t|=q |d7}q WtiiƒdS(Nii(sislens path_hookss KIDLoaderssysspath_importer_cachesclear(si((s*build/bdist.linux-i686/egg/kid/importer.pys_uninstall_hook_s sKIDHookscBs#tZeied„Zd„ZRS(NcCs'tii||ƒ|pg|_dS(N(sihookssHookss__init__sselfsverbosessuffixes(sselfsverbosessuffixes((s*build/bdist.linux-i686/egg/kid/importer.pys__init__nscCsFgi}tg|iD]}||dtfƒq~tiƒSdS(Nsr( sappends_[1]sKID_EXTsselfssuffixesssuffixsKID_FILEsimps get_suffixes(sselfs_[1]ssuffix((s*build/bdist.linux-i686/egg/kid/importer.pys get_suffixesrs(s__name__s __module__sihookssVERBOSEsNones__init__s get_suffixes(((s*build/bdist.linux-i686/egg/kid/importer.pysKIDHookslscBstZd„ZRS(Nc Cs\|\}}}|\}}}|tjot||ddƒSnt i i |||ƒSdS(Nsforcei(sstuffsfilesfilenamesinfossuffsmodestypesKID_FILEsimport_templatesnamesihookss ModuleLoaders load_modulesself( sselfsnamesstuffsinfossuffsfilenamesmodesfilestype((s*build/bdist.linux-i686/egg/kid/importer.pys load_modulexs  (s__name__s __module__s load_module(((s*build/bdist.linux-i686/egg/kid/importer.pys KIDLoadervscCs;td|ƒ}t|ƒ}ti|ƒ}ti|ƒdS(Nssuffixes( sKIDHooksssuffixesshookss KIDLoadersloadersihookssModuleImportersimportersinstall(ssuffixesshookssloadersimporter((s*build/bdist.linux-i686/egg/kid/importer.pys _install_hook€s cCstiƒdS(N(sihookss uninstall(((s*build/bdist.linux-i686/egg/kid/importer.pys_uninstall_hook†s(&s__doc__s __revision__s__date__s __author__s __copyright__s __license__sosssysstimesnews __builtin__s kid.compilerskidscompilersKID_EXTs hexversionsAssertionErrorsFalses _installedsNonesinstalls uninstallsimport_templatesget_template_names_create_modulesobjectsKID_FILEs path_hooksspath_importer_caches ImportErrors KIDLoaders _install_hooks_uninstall_hooksihookssimpsHookssKIDHookss ModuleLoader(sKID_FILEs __builtin__spath_importer_cachesget_template_names __revision__s path_hookssKID_EXTsimpstimesnews_create_modules __license__s_uninstall_hooks __author__ssyss _install_hooks KIDLoaderskids __copyright__sKIDHookss__date__sihookssinstallsimport_templatesoss uninstall((s*build/bdist.linux-i686/egg/kid/importer.pys?s<$              PKZ´Ð4{ÃZ:ÃSÃSkid/serialization.pyc;ò º-“Dc@s¾dZdklZdZdZdZdZdZdkZdk Tdk Td k l Z dk i Z d d d d gZhddddf<ddddf<ddddf<ddddfN(s*(s _coalescesdoctypess Serializers XMLSerializersHTMLSerializers html-strictsHTMLs-//W3C//DTD HTML 4.01//ENs%http://www.w3.org/TR/html4/strict.dtdshtmls&-//W3C//DTD HTML 4.01 Transitional//ENs$http://www.w3.org/TR/html4/loose.dtds xhtml-stricts -//W3C//DTD XHTML 1.0 Strict//ENs1http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtdsxhtmls&-//W3C//DTD XHTML 1.0 Transitional//ENs7http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdcBsƒtZeiZdZdZdZedd„Zd„Z edd„Z edd„Z edd„Z d „Z d „Zd „ZRS( Nsutf-8iicCs'|tj o ||_n||_dS(N(sencodingsNonesselfs src_encoding(sselfsencodings src_encoding((s/build/bdist.linux-i686/egg/kid/serialization.pys__init__*s  cCstSdS(N(sFalse(sselfstagname((s/build/bdist.linux-i686/egg/kid/serialization.pyshas_only_pcdata/scCs,t|i|||ƒƒ}di|ƒSdS(Ns(slistsselfsgeneratesstreamsencodingsfragmentstextsjoin(sselfsstreamsencodingsfragmentstext((s/build/bdist.linux-i686/egg/kid/serialization.pys serialize2scCs„t}t|dƒ ot}t|dƒ}nz7|i}x'|i|||ƒD]}||ƒqRWWd|o|i ƒnXdS(Nswriteswb(sFalses needs_closedshasattrsfilesTruesopenswritesselfsgeneratesstreamsencodingsfragmentstextsclose(sselfsstreamsfilesencodingsfragmentswrites needs_closedstext((s/build/bdist.linux-i686/egg/kid/serialization.pyswrite6s cCsdS(N((sselfsstreamsencodingsfragment((s/build/bdist.linux-i686/egg/kid/serialization.pysgenerateDscCsTt||iƒ}|io|i|ƒ}n|io|i|ƒ}n|SdS(N(s _coalescesstreamsselfs src_encodingsstrip_whitespaceswhitespace_filtersbalanced_blockssbalancing_filter(sselfsstream((s/build/bdist.linux-i686/egg/kid/serialization.pys apply_filtersGs   ccsYtidƒ}d}d}x7|D]/\}}|tjo|}d}q"|t t fjo |i t joÙ|djo8|o|i ƒdjot|id|ƒfVqõnC|o;|i ƒdjot|id|ƒfVqõt|fVn||fV|d7}|t jo |i|i ƒp |i tjo d}qQq"||fVq"WdS(Ns {2,}sis i(srescompiles line_collapsestextshopssstreamsevsitemsTEXTsSTARTsENDstagsFragmentsstripssubsselfshas_only_pcdatasComment(sselfsstreams line_collapsesitemshopsstextsev((s/build/bdist.linux-i686/egg/kid/serialization.pysbalancing_filterPs*   #   0ccsFx?|D]7\}}|tjot|iƒfVq||fVqWdS(N(sstreamsevsitemsTEXTsstrip(sselfsstreamsitemsev((s/build/bdist.linux-i686/egg/kid/serialization.pyswhitespace_filterks   (s__name__s __module__s namespaces namespacessencodingsbalanced_blockssstrip_whitespacesNones__init__shas_only_pcdatas serializeswritesgenerates apply_filterssbalancing_filterswhitespace_filter(((s/build/bdist.linux-i686/egg/kid/serialization.pys Serializer#s   cBswtZdZeZgZeeeed„Zd„Zedd„Zed„Z e e ƒZ ed„Z e e ƒZ RS(NicCsƒti||ƒ|tj o ||_n|tj o ||_nt|itƒot |i|_n|o ||_ ndS(N( s Serializers__init__sselfsencodingsdeclsNonesdoctypes isinstances basestringsdoctypess namespaces(sselfsencodingsdeclsdoctypes namespaces((s/build/bdist.linux-i686/egg/kid/serialization.pys__init__xs    cCstSdS(N(sTrue(sselfsns_stacks item_name((s/build/bdist.linux-i686/egg/kid/serialization.pyscan_be_empty_element…siccs™|p|ipd}ti} ti}t}t|ƒ}t |i ƒ}| o?|i o d|Vn|itj ot|iƒdVq‘nt}x÷|i|ƒD]æ\} } | ttfjo | itjoq§nA| tjo3|tj odi|| gƒ}q§| }q§n|tjob| tjo)| p |iƒ o|i|| iƒo!dVt}t}|iƒq§ndVn|o| ||ƒVt}n| tjov| itjo!d| ii|ƒVt}q§q‡| it jo!d| ii|ƒVt!}q§q‡| i}|i"t | d d ƒƒ|i#|d d ƒ} d | i|ƒV| i$i%ƒ}|oPxM|D]A\} }|i#| d d ƒ} d| i|ƒ|||ƒfVq~Wnx½|i)i%ƒD]N\}}|djod|||ƒVq×d|i|ƒ|||ƒfVq×Wn[| tjo| itt fjo7|i#| id d ƒ} d| i|ƒV|iƒn| }q§WdSdS(s­Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. sutf-8s$ s us />s>s ssremoveisdefaultsN(,sencodingsselfs XMLSerializers escape_cdatas escape_attribsNoneslastevsitersstreamsNamespaceStacks namespacessnamessfragmentsdeclsdoctypesserialize_doctypestexts apply_filterssevsitemsSTARTsENDstagsFragmentsTEXTsjoinsstripscan_be_empty_elementspopsCommentsencodesCOMMENTsProcessingInstructionsPIspushsqnamesattribsitemssattrssksvscurrentsprefixsuri(sselfsstreamsencodingsfragmentstextsurisprefixstagsnamessevs escape_cdatasksqnamesitemsvslastevsattrss escape_attrib((s/build/bdist.linux-i686/egg/kid/serialization.pysgenerateˆs~      #   9      (  (# cCs”yj|o7y|i|ƒ}WqAtj ot|ƒSqAXn|iddƒ}|iddƒ}|SWn#ttfj ot|ƒnXdS(sEscape character data.s&s&sssremoveissheadsmetas1<%s %s="text/html; charset=%s" %s="Content-Type">siÿÿÿÿN(8sencodingsselfsHTMLSerializers escape_cdatas escape_attribsnoescape_elementssboolean_attributessempty_elementssNamespaceStacks namespacessnamess grok_namesattr_http_equivs attr_contents transposesNonescurrentsstacksitersstreamsfragmentsdoctypesserialize_doctypes apply_filterssevsitemsTEXTsescapesSTARTstagsCommentstextsencodesCOMMENTslastevsProcessingInstructionsPIsFragmentspushsuris localnamesqnameslowersappendsattribsitemssattrssksvsuslsqslqs inject_typesENDspop(sselfsstreamsencodingsfragmentsnoescape_elementssboolean_attributesstags escape_attribsescapes localnamesevsattr_http_equivs escape_cdatasempty_elementsscurrentslqs grok_names attr_contentsvsstackslsksurisqsitemsusqnameslastevsattrssnames((sselfsnamess/build/bdist.linux-i686/egg/kid/serialization.pysgenerates„                   (  )&    cCsŸyu|o7y|i|ƒ}WqAtj ot|ƒSqAXn|o(|iddƒ}|iddƒ}n|SWn#ttfj ot |ƒnXdS(sEscape character data.s&s&sq>Wq+W|o |djodSn|o|SntSdS(sFigure out prefix given a URI.s$http://www.w3.org/XML/1998/namespacesxmliÿÿÿÿsiN( suris is_defaultsNonesprefixsselfsstacksnamessitemssksvsdefault(sselfsurisdefaults is_defaultsprefixsnamessvsk((s/build/bdist.linux-i686/egg/kid/serialization.pysresolve_prefixÎs,   !   cCsO|djodSnx/|iD]$}|i|ƒ}|o|SqqWtSdS(sFigure out URI given a prefix.sxmls$http://www.w3.org/XML/1998/namespaceN(sprefixsselfsstacksnamessgetsurisNone(sselfsprefixsurisnames((s/build/bdist.linux-i686/egg/kid/serialization.pys resolve_uriès   icCs't|tƒo |i}n|ddjo|Sn|diddƒ\}}|i||ƒ}|t jo|i i |ƒ}|t j o||i|(sdoctype(sdoctype((s/build/bdist.linux-i686/egg/kid/serialization.pysserialize_doctypes( s__doc__s __future__s generatorss __revision__s__date__s __author__s __copyright__s __license__sreskid.etskid.pulls _coalesces kid.namespaces namespaces__all__sdoctypessobjects Serializers XMLSerializerssets NameErrorssetssSets ImportErrorsxhtmlsurisstringsHTMLSerializersXHTMLSerializersPlainSerializersNamespaceStacksserialize_doctype(ssetsXHTMLSerializersNamespaceStacksPlainSerializers XMLSerializersdoctypess __revision__s__all__s namespacesHTMLSerializersres generatorssxhtmls _coalescesstrings __license__sserialize_doctypes __author__s Serializers __copyright__s__date__((s/build/bdist.linux-i686/egg/kid/serialization.pys?s<    N O   ¥  ZPKY´Ð4áœÁ¹ß ß kid/et.pyc;ò º-“Dc @s dZdZdZdZdZdZdkZy~eiidƒo e ‚n^y1eiidƒo e ‚ndk Z d k TWn)e j odk i i Z d k TnXWn eZ nXy@eiidƒo e ‚n dkiZe o d kTnWn5e j o)dki iZe o d kTq3nXeiZeiZeiZeiZd d „Zd d „Zdddddddddddddg ZdS(sElementTree extensions.s$Rev$s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT Ns KID_NOCETsKID_NOET(s*scCsttƒ}||_|SdS(sfXML fragment factory. Fragments hold TEXT and children but do not have a tag or attributes. N(sElementsFragmentselemstext(stextselem((s$build/bdist.linux-i686/egg/kid/et.pysFragment=s  icCsžh}x|iƒD]}|idƒo0|i|ƒ||d<|o|i|=q’q|djo,|i|ƒ|d<|o|i|=q’qqW|SdS(sþGet the namespace declarations for an Element. This function looks for attributes on the Element provided that have the following characteristics: * Begin with 'xmlns:' and have no namespace URI. * Are named 'xmlns' and have no namespace URI. The result is a dictionary containing namespace prefix -> URI mappings. Default namespace attributes result in a key of ''. If remove is truthful, namespace declaration attributes are removed from the passed in Element. sxmlns:isxmlnssN(snamesselemskeyssks startswithsgetsremovesattrib(selemsremovesksnames((s$build/bdist.linux-i686/egg/kid/et.pys namespacesGs  sElements SubElementsCommentsProcessingInstructionsFragments ElementTreesQNamesdumpsparsestostrings namespacess encode_entitysraise_serialization_error(s__doc__s __revision__s__date__s __author__s __copyright__s __license__sossenvironsgets ImportErrors cElementTreesCETsxml.etree.cElementTreesetreesNoneselementtree.ElementTrees ElementTreesETsxml.etree.ElementTrees_encode_entitys encode_entitys_raise_serialization_errorsraise_serialization_errorsCommentsProcessingInstructionsFragments namespacess__all__(sComments __copyright__s __revision__s encode_entitys __license__sFragments __author__s__date__sProcessingInstructionsCETs namespacessraise_serialization_errorsETsoss__all__((s$build/bdist.linux-i686/egg/kid/et.pys?sH             PK ²Ð4€üE __kid/namespace.py namespaces = {} class Namespace(object): def __init__(self, uri, prefix=None): self.uri = uri self.prefix = prefix if prefix: namespaces[uri] = prefix def qname(self, name): if self.prefix: return self.prefix + ':' + name else: return name def clarkname(self, name): if self.uri: return '{%s}%s' % (self.uri, name) else: return name __getattr__ = clarkname __getitem__ = clarkname def __str__(self): return self.uri def __unicode__(self): return unicode(self.uri) def __repr__(self): return 'Namespace(%r, %r)' % (self.uri, self.prefix) def __equals__(self, other): if isinstance(other, basestring): return self.uri == other elif isinstance(other, Namespace): return self.uri == other.uri else: return 0 xml = Namespace('http://www.w3.org/XML/1998/namespace', 'xml') xhtml = Namespace('http://www.w3.org/1999/xhtml', 'html') atom = Namespace('http://purl.org/atom/ns#', 'atom') rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdf') rss = Namespace('http://purl.org/rss/1.0/', 'rss') nons = Namespace(None, None) __all__ = ['xml', 'xhtml', 'atom', 'rdf', 'rss', 'nons', 'Namespace'] PKY´Ð4‡}ˆ33kid/filter.pyc;ò º-“Dc@s–dZdklZdZdZdZdZdZdkl Z dk l Z l Z l Z lZd klZd klZd „Zd „Zd „ZdS(sKid tranformations(s generatorss $Rev: 53 $s5$Date: 2005-02-15 08:10:35 -0500 (Tue, 15 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT (s GeneratorType(s ElementStreamsSTARTsXML_DECLs _coalesce(s Namespace(sgenerate_contentc#s[ˆiƒ}‡d†}ti|ƒ}x-t|ˆ||ƒD]\}}||fVq=WdS(Ncstt|ƒˆƒSdS(N(stransform_filtersgenerate_contentsitemstemplate(sitem(stemplate(s(build/bdist.linux-i686/egg/kid/filter.pys apply_funcs( stemplates_get_match_templatess templatess apply_funcs ElementStreamsensuresstreams apply_matchessevsitem(sstreamstemplates templatess apply_funcsitemsev((stemplates(build/bdist.linux-i686/egg/kid/filter.pystransform_filters    c cs=x6|D].\}}|tjo d} xðtdt|ƒƒD]Ù}||\} }| |ƒo¶|i ƒ}t ||||ƒ|iƒƒ}t|ƒdjo%xh|D]\}}||fVq¦WnGxCtt|ƒ||| ||d|ƒD]\}}||fVqðWd} Pq<q<W| oqq+n||fVqWdS(Niii(sstreamsevsitemsSTARTsmatchedsrangeslens templatessismatchscallsexpands _coalescestemplates apply_funcs_get_assume_encodings newstreams apply_matchess ElementStream( sstreamstemplates templatess apply_funcsisitems newstreamscallsevsmatchsmatched((s(build/bdist.linux-i686/egg/kid/filter.pys apply_matchess0        c cstdƒ}|i} |i}xá|D]Ù\}}|tjo|i|ijo­|i ƒ}|i dƒ}yt ||iƒƒ}WnF|i|ƒ}x]t|ƒidƒD]\}}||fVq°WqþXx-|D]!\}}|tjo|VqÕqÕWq%q%WdS(Nshttp://www.w3.org/2001/XIncludeshrefi(s NamespacesxisincludesfallbacksstreamsevsitemsSTARTstagsexpandsgetshrefsdocumentstemplates_get_assume_encodingsdocsfinds fallback_elms ElementStreamsstripsXML_DECL( sstreamstemplates fallback_elmsxisevsdocsitemshrefsfallbacksinclude((s(build/bdist.linux-i686/egg/kid/filter.pysxinclude_filter0s&         N(s__doc__s __future__s generatorss __revision__s__date__s __author__s __copyright__s __license__stypess GeneratorTypeskid.pulls ElementStreamsSTARTsXML_DECLs _coalesces kid.namespaces Namespaces template_utilsgenerate_contentstransform_filters apply_matchessxinclude_filter(s __copyright__s __revision__sxinclude_filters __license__sgenerate_contents Namespaces __author__s__date__sSTARTs apply_matchess generatorss ElementStreamsXML_DECLstransform_filters GeneratorTypes _coalesce((s(build/bdist.linux-i686/egg/kid/filter.pys?s      PK ²Ð4¤ @þþkid/template_util.py"""Utility functions used by generated kid modules. """ from __future__ import generators __revision__ = "$Rev: 314 $" __date__ = "$Date: 2006-04-18 00:37:38 +0000 (Tue, 18 Apr 2006) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import inspect import sys from types import TypeType, ModuleType from os.path import join, normpath, abspath, dirname # these are for use by template code import kid from kid.pull import XML, document, ElementStream, \ Element, SubElement, Comment, ProcessingInstruction, \ START, END, TEXT, START_NS, COMMENT, PI, DOCTYPE, \ XML_DECL, to_unicode class TemplateNotFound(Exception): pass _local_excludes = ['generate', 'module', 'pull', 'serialize', 'transform', 'write'] def get_locals(inst, _locals=None): if _locals is None: _locals = {} ls = [] local_excludes = _local_excludes # local copy for var, value in inspect.getmembers(inst): if not var.startswith('_') and not var in local_excludes \ and var not in _locals: ls.append('%s=self.%s' % (var, var)) return ';'.join(ls) def get_base_class(thing, from_file): if thing is None or thing is kid.BaseTemplate: cls = kid.BaseTemplate elif isinstance(thing, basestring): path = kid.path.find(thing, from_file) cls = kid.load_template(path).Template elif isinstance(thing, TypeType): cls = thing elif isinstance(thing, ModuleType): cls = thing.Template else: raise TemplateNotFound("Could not find template: %r" % thing) return cls def make_attrib(attrib, encoding=None): if attrib is None: return {} if encoding is None: encoding = sys.getdefaultencoding() for (k, v) in attrib.items(): if isinstance(v, list): ls = [to_unicode(i, encoding) for i in v if i is not None] if not ls: del attrib[k] else: attrib[k] = ''.join(ls) else: attrib[k] = to_unicode(v, encoding) return attrib def generate_content(content, parent=None): if content is None: return [] if isinstance(content, basestring): return [(TEXT, content)] elif hasattr(content, 'tag') and hasattr(content, 'attrib'): # if we get an Element back, make it an ElementStream return ElementStream(content) elif hasattr(content, '__iter__'): # if we get an iterable back, there are two cases: if hasattr(content, '__getitem__'): # if we get a sequence back, we simply flatten it def flatten(seq): for i in seq: for ev, item in generate_content(i): yield ev, item return flatten(content) else: # if we get a generator back, pray it's an ElementStream return content else: return [(TEXT, unicode(content))] def filter_names(names, omit_list): for ns in names.keys(): if ns in omit_list: del names[ns] return names def update_dict(a, s, globals, locals): """Update dictionary a from keyword argument string s.""" try: strings = None try: b = eval('dict(%s)' % s, globals, locals) except (TypeError, SyntaxError): # TypeErrror happens with Python <2.3, because building # dictionaries from keyword arguments was not supported. # SyntaxError can happen if one of the keyword arguments # is the same as a Python keyword (e.g. "class") or if it is a # qualified name containing a namespace prefixed with a colon. # So in these cases we parse the keyword arguments manually: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from tokenize import generate_tokens from token import NAME, OP depth, types, strings = 0, [], [] for token in generate_tokens(StringIO(s).readline): type_, string = token[:2] if type_ == OP: if string == '=': if depth == 0: if len(types) > 0 \ and types[-1] == NAME and strings[-1]: if len(types) > 2 \ and types[-2] == OP and strings[-2] == ':' \ and types[-3] == NAME and strings[-3]: strings[-3:] = ["'%s'" % ''.join(strings[-3:])] else: strings[-1] = "'%s'" % strings[-1] string = ':' elif string in '([{': depth += 1 elif depth > 0 and string in ')]}': depth -= 1 types.append(type_) strings.append(string) b = eval('{%s}' % ''.join(strings), globals, locals) except Exception: exc_type, exc_obj, tb = sys.exc_info() if strings is None: code = s else: code = "%s -> %s" % (s, ''.join(strings)) raise exc_type("%s in %s" % (exc_obj, code)) for k in b.keys(): if b[k] is None: del b[k] if k in a: del a[k] a.update(b) return a __all__ = ['XML', 'document', 'ElementStream', 'Element', 'SubElement', 'Comment', 'ProcessingInstruction', 'START', 'END', 'TEXT', 'START_NS', 'COMMENT', 'PI', 'DOCTYPE', 'XML_DECL'] PKY´Ð4«ò}²'²'kid/server.pyc;ò º-“Dc@sìdZdZdZdZdZdZddgZdkZd k l Z d k l Z d k lZd klZd klZdZdZdefd„ƒYZde fd„ƒYZ eee dd„Zd„Zedjo eƒndS(sŽKid-savvy HTTP Server. Written by Christoph Zwerschke based on CGIHTTPServer 0.4. This module builds on SimpleHTTPServer by implementing GET and POST requests to Kid templates. In all cases, the implementation is intentionally naive -- all requests are executed by the same process and sychronously. Code to create and run the server looks like this: from kid.server import HTTPServer host, port = 'localhost', 8000 HTTPServer((host, port)).serve_forever() This serves files and kid templates from the current directory and any of its subdirectories. If you want the server to be accessible via the network, use your local host name or an empty string as the host. (Security warning: Don't do this unless you are inside a firewall.) You can also call the test() function to run the server, or run this module as a script, providing host and port as command line arguments. The Kid templates have access to the following predefined objects: FieldStorage (access to GET/POST variables) environ (CGI environment) request (the request handler object) Here is a simple Kid template you can use to test the server: Python Expression Evaluator

${FieldStorage.getvalue('expr')} = ${eval(FieldStorage.getvalue('expr'))}

Enter a Python expression:

s $Rev: 1 $s4$Date: 2005-01-01 00:00:00 +0000 (Mon, 1 Jan 2005) $s$Christoph Zwerschke (cito@online.de)s#Copyright 2005, Christoph Zwerschkes8MIT s HTTPServersHTTPRequestHandlerN(sunquote(s HTTPServer(sSimpleHTTPRequestHandler(s FieldStorage(s load_templates localhosti@cBs>tZdZd„Zd„Zd„ZddgZd„ZRS(s©Complete HTTP server with GET, HEAD and POST commands. GET and HEAD also support running Kid templates. The POST command is *only* implemented for Kid templates.cCs/|iƒo|iƒn|iddƒdS(s3Serve a POST request implemented for Kid templates.iõsCan only POST to Kid templatesN(sselfsis_kidsrun_kids send_error(sself((s(build/bdist.linux-i686/egg/kid/server.pysdo_POSTNs cCs,|iƒo|iƒSnti|ƒSdS(s1Version of send_head that supports Kid templates.N(sselfsis_kidsrun_kidsSimpleHTTPRequestHandlers send_head(sself((s(build/bdist.linux-i686/egg/kid/server.pys send_headUs cCs|i}|idƒ}|djo"|| ||df\}}nd}x8|iD]-}|i|ƒo||f|_t SqWqWWt SdS(sÀTest whether self.path corresponds to a Kid template. The default implementation tests whether the path ends with one of the strings in the list self.kid_extensions. s?iisN( sselfspathsrfindsisqueryskid_extensionssxsendswithscgi_infosTruesFalse(sselfsisquerysxspath((s(build/bdist.linux-i686/egg/kid/server.pysis_kid\s  "  s.kids .kid.htmlc Cs[|i\}}|i|ƒ}tii|ƒ o|i dd|ƒdSntii |ƒ o|i dd|ƒdSnh} |i ƒ| d<|i i| dd1t|ƒƒnX|i?d2ƒdS(3sExecute a Kid template.i”sNo such Kid template (%r)Ni“s%Kid template is not a plain file (%r)sSERVER_SOFTWAREs SERVER_NAMEsCGI/1.1sGATEWAY_INTERFACEsSERVER_PROTOCOLs SERVER_PORTsREQUEST_METHODs PATH_INFOsPATH_TRANSLATEDs SCRIPT_NAMEs QUERY_STRINGis REMOTE_HOSTs REMOTE_ADDRs authorizationis AUTH_TYPEsbasicis:s REMOTE_USERs CONTENT_TYPEscontent-lengthsCONTENT_LENGTHsaccepts is,s HTTP_ACCEPTs user-agentsHTTP_USER_AGENTscookies, s HTTP_COOKIEiÈsScript output followsscachesrequestsenvirons FieldStorages Content-types text/htmlsContent-LengthsKid template exception: %ssKid template exited OK(@sselfscgi_infos scriptnamesquerystranslate_paths scriptfilesosspathsexistss send_errorsisfilesenvsversion_stringsservers server_namesprotocol_versionsstrs server_portscommandsunquotesuqpathsaddress_stringshostsclient_addresssheaderss getheaders authorizationssplitslensbase64sbinasciislowers decodestringsErrors typeheadersNonestypeslengthsacceptsgetallmatchingheadersslinesappendsstripsjoinsuasfilters getheadersscos send_responses load_templatestemplate_modulesTemplates FieldStoragesrfilestemplatesss send_headers end_headersswfileswrites Exceptionses log_errors log_message(sselfscosaccepts scriptnamestemplate_modulesquerysuqpathsbase64sbinasciisssenvs authorizationstemplateshostslineseslengths scriptfilesua((s(build/bdist.linux-i686/egg/kid/server.pysrun_kidqs          (s__name__s __module__s__doc__sdo_POSTs send_headsis_kidskid_extensionssrun_kid(((s(build/bdist.linux-i686/egg/kid/server.pysHTTPRequestHandlerHs     cBstZeed„ZRS(NcCs4|tjottf}nti||tƒdS(N(sserver_addresssNones default_hosts default_portsBaseHTTPServers__init__sselfsHTTPRequestHandler(sselfsserver_addresssRequestHandlerClass((s(build/bdist.linux-i686/egg/kid/server.pys__init__Ès  (s__name__s __module__sNonesHTTPRequestHandlers__init__(((s(build/bdist.linux-i686/egg/kid/server.pys HTTPServerÆssHTTP/1.0cCsR||_|||ƒ}|iiƒ}dG|dGdG|dGdGH|i ƒdS(s$Test the HTTP request handler class.sServing HTTP onisportis...N( sprotocols HandlerClasssprotocol_versions ServerClasssserver_addresssserverssockets getsocknamessas serve_forever(sserver_addresss HandlerClasss ServerClasssprotocolsserverssa((s(build/bdist.linux-i686/egg/kid/server.pystestÑs  cCsPdkl}l}t|ƒdjodG|dGdGH|dƒnt|ƒdjottf}nÛt|ƒdjo|d}|d}ng|di ddƒ}t|ƒdjo1|d}|i ƒo|}d }qùt }n |\}}|o0|i ƒot |ƒ}q6d GH|dƒnt}||f}t |ƒd S( s˜This runs the Kid-savvy HTTP server. Provide host and port as command line arguments. The current directory serves as the root directory. (sargvsexitisUsage:is [host]:[port]iis:ssBad port number.N(ssyssargvsexitslens default_hosts default_portsserver_addressshostsportssplitsisdigitsNonesintstest(sserver_addressshostsexitsargvsport((s(build/bdist.linux-i686/egg/kid/server.pysmainÞs4        s__main__(s__doc__s __revision__s__date__s __author__s __copyright__s __license__s__all__sos.pathsossurllibsunquotesBaseHTTPServers HTTPServersSimpleHTTPServersSimpleHTTPRequestHandlerscgis FieldStorageskids load_templates default_hosts default_portsHTTPRequestHandlersNonestestsmains__name__(sunquotesmains __copyright__s __revision__s __license__s__all__s load_templates default_hostsSimpleHTTPRequestHandlers __author__s__date__stests HTTPServers default_portsBaseHTTPServers FieldStoragesHTTPRequestHandlersos((s(build/bdist.linux-i686/egg/kid/server.pys?1s(       ~  , PKZ´Ð4˜%8MJMJkid/__init__.pyc;ò º-“Dc@szdZdZdZdkZeiZeiZeiZ ei Z ei Z dkZdkZdklZlZdklZdklZlZlZlZlZlZlZdklZlZl Z dk!l"Z"d k#l$Z$l%Z%l&Z&l'Z'l(Z(ei)ƒa*e+d „Z,ei-i.d e+ƒe+j o e,ƒnd „Z/d de+hd„Z0hde%ddƒ<de(ddddƒ<de(ddddƒ<de&ddƒ<de&ddƒ<de'ƒNsTemplate not found: %s (in %s)s, is dump_codes dump_sources KID_OUTPUT_PYsstoresns(#s isinstancesfiles basestrings xml_sniffsQuickTextReadersfosfilenamesNones kid.importersimporterspathsfinds abs_filenames Exceptionsjoinspathssget_template_namesnamessyssmodulesshas_keysgets kid.compilerscompilerscompilesencodingscodesKidFilestemplatescachesossenvirons_create_modulesnssmod( sfilesnamescachesencodingsnsscodesfosmodsfilenamesimporterstemplates abs_filenamescompiler((s*build/bdist.linux-i686/egg/kid/__init__.pys load_templateQs2      #  $!sxmlsdeclsxhtmlisdoctypes xhtml-strictshtmls html-strictsplaincKs|ot|ƒ}n\|tj ot|ƒ}n?|tj o%tt|ƒtt |ƒƒƒ}n t dƒ‚||i _ |i |SdS(s¿Get a Template class quickly given a module name, file, or string. This is a convenience function for getting a template in a variety of ways. One and only one of the arguments name or file must be specified. file:string The template module is loaded by calling ``load_template(file, name='', cache=1)`` name:string The kid import hook is enabled and the template module is located using the normal Python import mechanisms. source:string string containing the templates source. Once the template module is obtained, a new instance of the module's Template class is created with the keyword arguments passed to this function. s*Must specify one of name, file, or source.N(snamesimport_templatesmodsfilesNones load_templatessourcesQuickTextReadershexsids ExceptionsTemplatesmoduleskw(sfilessourcesnameskwsmod((s*build/bdist.linux-i686/egg/kid/__init__.pysTemplate‰s  %  (stransform_filters BaseTemplatecBsÞtZdZedZegZd„Zeded„Z eded„Z eded„Z d„Z d„Z d „Zd „Zd „Zd „Zd „Zegd„Zd„Zd„Zd„Zd„Zed„ZRS(s Base class for compiled Templates. All kid template modules expose a class named ``Template`` that extends from this class making the methods defined here available on all Template subclasses. This class should not be instantiated directly. sxmlcOs|ii|ƒg|_dS(sÍ Initialize a template with instance attributes specified by keyword arguments. Keyword arguments are available to the template using self.var notation. N(sselfs__dict__supdateskws_layout_classes(sselfsargsskw((s*build/bdist.linux-i686/egg/kid/__init__.pys__init__¸sicCs)|i|ƒ}|i||||ƒSdS(sd Execute template and write output to file. file:file A filename or a file like object (must support write()). encoding:string The output encoding. Default: utf-8. fragment:bool Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to 1 when generating fragments meant to be inserted into existing XML documents. output:string,`Serializer` A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. N(sselfs_get_serializersoutputs serializerswritesfilesencodingsfragment(sselfsfilesencodingsfragmentsoutputs serializer((s*build/bdist.linux-i686/egg/kid/__init__.pyswriteÃscCs&|i|ƒ}|i|||ƒSdS(s” Execute a template and return a single string. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to 1 when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. This is a convienence method, roughly equivalent to:: ''.join([x for x in obj.generate(encoding, fragment, output)] N(sselfs_get_serializersoutputs serializers serializesencodingsfragment(sselfsencodingsfragmentsoutputs serializer((s*build/bdist.linux-i686/egg/kid/__init__.pys serialize×scCs&|i|ƒ}|i|||ƒSdS(s® Execute template and generate serialized output incrementally. This method returns an iterator that yields an encoded string for each iteration. The iteration ends when the template is done executing. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to 1 when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. N(sselfs_get_serializersoutputs serializersgeneratesencodingsfragment(sselfsencodingsfragmentsoutputs serializer((s*build/bdist.linux-i686/egg/kid/__init__.pysgenerateîscCst|iƒƒSdS(N(sitersselfs transform(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys__iter__scCs|iƒSdS(N(sselfs serialize(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys__str__scCst|iddƒdƒSdS(Nsencodingsutf-16(sunicodesselfs serialize(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys __unicode__ scCsdS(N((sself((s*build/bdist.linux-i686/egg/kid/__init__.pys initialize scCs3|iƒtt|iƒ|iƒƒƒ}|SdS(s4Returns an iterator over the items in this template.N(sselfs initializes ElementStreams _coalescescontents_get_assume_encodingsstream(sselfsstream((s*build/bdist.linux-i686/egg/kid/__init__.pyspulls !cCsgSdS(sfGenerate events for this template. Compiled templates implement this method. N((sself((s*build/bdist.linux-i686/egg/kid/__init__.pys_pullscCs™dkl}|i}t||iƒƒ}|iƒxS|D]K}|i i dƒo ||jo%|i d|ƒ|i d|ƒSq<q<W|i ƒSdS(N(sgetmroslayouti(sinspectsgetmrosselfs_layout_classessvisitedslists __class__smrosreversescs__dict__shas_keysinserts_pull(sselfscsmrosvisitedsgetmro((s*build/bdist.linux-i686/egg/kid/__init__.pyscontents    cCs¾|tjo|iƒ}nst|tƒo3t|ƒot|ddƒ}qt|ƒ}n0t |dƒot |ƒ}nt i |ƒ}x$||i D]}|||ƒ}qW|SdS(sG Execute the template and apply any match transformations. If stream is specified, it must be one of the following: Element An ElementTree Element. ElementStream An `pull.ElementStream` instance or other iterator that yields stream events. string A file or URL unless the string starts with '<' in which case it is considered an XML document and processed as if it had been an Element. By default, the `pull` method is called to obtain the stream. sfragmentistagN(sstreamsNonesselfspulls isinstances basestrings xml_sniffsXMLsdocumentshasattrs ElementStreamsensuresfilterss_filterssf(sselfsstreamsfilterssf((s*build/bdist.linux-i686/egg/kid/__init__.pys transform)s  cCs‡y |i}Wnotj ocg}|ii}x>|D]6}y |i}Wntj o q7nX||7}q7W||_nX|SdS(N( sselfs_match_templates_cachedsrsltsAttributeErrors __class__s__mro__smrosCs_match_templatess templates(sselfs templatessCsmrosrslt((s*build/bdist.linux-i686/egg/kid/__init__.pys_get_match_templatesJs   cCs<|tjo |iSn!t|tƒo t|Sn|SdS(N(s serializersNonesselfs isinstances basestringsoutput_methods(sselfs serializer((s*build/bdist.linux-i686/egg/kid/__init__.pys_get_serializerZs    cCs#t|dƒo |iSntSdS(Nsassume_encoding(shasattrsselfsassume_encoding(sself((s*build/bdist.linux-i686/egg/kid/__init__.pys_get_assume_encodingbs cCst||ƒSdS(N(shasattrsselfsname(sselfsname((s*build/bdist.linux-i686/egg/kid/__init__.pysdefinedjscCst|||ƒSdS(N(sgetattrsselfsnamesdefault(sselfsnamesdefault((s*build/bdist.linux-i686/egg/kid/__init__.pysvalue_ofms(s__name__s __module__s__doc__soutput_methodss serializerstransform_filters_filterss__init__sNoneswrites serializesgenerates__iter__s__str__s __unicode__s initializespulls_pullscontents transforms_get_match_templatess_get_serializers_get_assume_encodingsdefinedsvalue_of(((s*build/bdist.linux-i686/egg/kid/__init__.pys BaseTemplate©s(           !    s TemplatePathcBs>tZed„Zd„Zdd„Zd„Zdd„ZRS(NcCst|tƒo |g}n|tjo g}n|tiƒdg7}gi}|D]}||i |ƒƒqX~|_dS(Ns/( s isinstancespathss basestringsNonesossgetcwdsappends_[1]spsselfs _cleanse_path(sselfspathss_[1]sp((s*build/bdist.linux-i686/egg/kid/__init__.pys__init__qs    cCs3dkl}l}l}||||ƒƒƒSdS(N(snormpaths expandusersabspath(sos.pathsnormpaths expandusersabspathspath(sselfspaths expandusersabspathsnormpath((s*build/bdist.linux-i686/egg/kid/__init__.pys _cleanse_pathysicCs |ii||i|ƒƒdS(N(sselfspathssinsertsposs _cleanse_pathspath(sselfspathspos((s*build/bdist.linux-i686/egg/kid/__init__.pysinsert}scCs|ii|i|ƒƒdS(N(sselfspathssappends _cleanse_pathspath(sselfspath((s*build/bdist.linux-i686/egg/kid/__init__.pysappend€ss/cCstdkl}l}l}l}||ƒ}xB|i||ƒgD]*}|||ƒ}||ƒo|SqBqBWdS(N(snormpathsjoinsexistssdirname( sos.pathsnormpathsjoinsexistssdirnamespathsselfspathssrelsp(sselfspathsrelsjoinsexistssnormpathspsdirname((s*build/bdist.linux-i686/egg/kid/__init__.pysfindƒs  (s__name__s __module__sNones__init__s _cleanse_pathsinsertsappendsfind(((s*build/bdist.linux-i686/egg/kid/__init__.pys TemplatePathps     s KID_XMLNSsTemplates enable_importsimport_templates load_templatesElements SubElementsXMLsdocuments Namespaces Serializers XMLSerializersHTMLSerializersXHTMLSerializersoutput_methodssfilters namespaces serializationsutils properties(=s__doc__s __revision__s__date__sreleasesversions __version__sauthors __author__semails __email__s copyrights __copyright__slicenses __license__ssyssosskid.utils xml_sniffsQuickTextReaders kid.namespaces Namespaceskid.pulls ElementStreamsElements SubElementsFragmentsXMLsdocuments _coalesceskid.ets ElementTreesCommentsProcessingInstructions kid.parsers KID_XMLNSskid.serializations Serializers XMLSerializersHTMLSerializersPlainSerializersXHTMLSerializersgetdefaultencodingsassume_encodingsNones enable_importsenvironsgetsimport_templates load_templatesoutput_methodssTemplates kid.filterstransform_filtersobjects BaseTemplates TemplatePathspathskid.propertiesskids propertiess__all__()sXHTMLSerializers load_templates Namespaces __email__s ElementStreamsTemplatesPlainSerializerstransform_filters XMLSerializers ElementTreesQuickTextReaders _coalesces __revision__s__all__sFragmentsHTMLSerializers propertiess xml_sniffsXMLsoutput_methodss __license__s enable_importsElementssysskidspaths __author__sdocuments Serializers BaseTemplatesComments __copyright__s __version__s KID_XMLNSsProcessingInstructions__date__s SubElementsimport_templatesreleasesoss TemplatePath((s*build/bdist.linux-i686/egg/kid/__init__.pys? s>         1 %    0x Ç   PK ²Ð4­u2´´ kid/run.py#!/usr/bin/python # This module provides the "kid" command """Usage: kid [options] file [args] Expand a Kid template file. OPTIONS: -e enc, --encoding=enc Specify the output character encoding. Default: utf-8 -o outfile, --output=outfile Specify the output file. Default: standard output -s host:port, --server=host:port Specify the server address if you want to start the HTTP server. Instead of the Kid template, you can specify a base directory. -h, --help Print this help message and exit. -V, --version Print the Kid version number and exit. file: filename of the Kid template to be processed or "-" for reading the template from stdin. args: key=value or other arguments passed to the template. """ __revision__ = "$Rev: 139 $" __date__ = "$Date: 2005-03-14 19:28:22 -0500 (Mon, 14 Mar 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys from os.path import dirname, abspath from getopt import getopt, GetoptError as gerror import kid def main(): # get options try: opts, args = getopt(sys.argv[1:], 'e:o:s:hV', ['encoding=', 'output=', 'server=', 'help', 'version']) except gerror, e: sys.stderr.write(str(e) + '\n') sys.stdout.write(__doc__) sys.exit(2) enc = 'utf-8' outfile = server = None for o, a in opts: if o in ('-e', '--encoding'): enc = a elif o in ('-o', '--output'): outfile = a elif o in ('-s', '--server'): server = a elif o in ('-h', '--help'): sys.stdout.write(__doc__) sys.exit(0) elif o in ('-V', '--version'): from kid import __version__ sys.stdout.write('Kid %s\n' % __version__) sys.exit(0) if server is None: if args: # get template file f = args.pop(0) sys.argv = [f] if f != '-': # make sure template dir is on sys.path path = abspath(dirname(f)) if not path in sys.path: sys.path.insert(0, path) else: f = sys.stdin.read() # get arguments for the template file kw = {} while args: a = args.pop(0).split('=', 1) if len(a) > 1: kw[a[0]] = a[1] else: sys.argv.append(a[0]) # do not run as __main__ module sys.modules['__kid_main__'] = sys.modules['__main__'] __name__ = '__kid_main__' del sys.modules['__main__'] # load kid template as __main__ module module = kid.load_template(f, name='__main__', cache=0) # execute the template and write output if not outfile: outfile = sys.stdout module.write(outfile, encoding=enc, **kw) else: sys.stderr.write('kid: No template file specified.\n') sys.stderr.write(" Try 'kid --help' for usage information.\n") sys.exit(2) else: if len(args) < 2: if outfile: stderr = file(outfile, 'a', 1) sys.stderr = stderr sys.stdout.write('Starting HTTP server ...\n') if args: # get base directory basedir = args.pop(0) from os import chdir chdir(basedir) from os import getcwd basedir = getcwd() sys.stdout.write('Base directory: %s\n' % basedir) if outfile: sys.stdout.write('Server log: %s\n' % outfile) if server == '-': server = 'localhost' sys.argv[1:] = [server] from kid.server import main main() if outfile: sys.stderr = sys.__stderr__ out.close() else: sys.stderr.write('kid: Server does not need additional arguments.\n') sys.stderr.write(" Try 'kid --help' for usage information.\n") sys.exit(2) if __name__ == '__main__': main() PK ²Ð4P2¬\\kid/importer.py"""Kid Import Hooks. When installed, these hooks allow importing .kid files as if they were Python modules. """ __revision__ = "$Rev: 317 $" __date__ = "$Date: 2006-04-21 08:51:24 +0000 (Fri, 21 Apr 2006) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os, sys, time, new import __builtin__ import kid.compiler KID_EXT = kid.compiler.KID_EXT assert sys.hexversion >= 0x20000b1, "need Python 2.0b1 or later" _installed = False def install(suffixes=None): global _installed if not _installed: _install_hook(suffixes=suffixes) _installed = True def uninstall(): global _installed if _installed: _uninstall_hook() _installed = False def import_template(name, filename, force=0): if not force and name and sys.modules.has_key(name): return sys.modules[name] template = kid.compiler.KidFile(filename) code = template.compile(dump_source=os.environ.get('KID_OUTPUT_PY')) module = _create_module(code, name, filename) return module def get_template_name(name, filename): if name: return name else: return 'kid.util.template_%x' % (hash(filename) + sys.maxint + 1) def _create_module(code, name, filename, store=1, ns={}): name = get_template_name(name, filename) mod = new.module(name) mod.__file__ = filename mod.__ctime__ = time.time() mod.__dict__.update(ns) exec code in mod.__dict__ if store: sys.modules[name] = mod return mod # this is put in a pyc file to signal that it is a kid file KID_FILE = object() try: # if possible, use new (PEP 302) import hooks from sys import path_hooks, path_importer_cache except ImportError: path_hooks = None if path_hooks is not None: class KIDLoader(object): def __init__(self, path=None): if path and os.path.isdir(path): self.path = path else: raise ImportError def find_module(self, fullname): path = os.path.join(self.path, fullname.split('.')[-1]) for ext in [KID_EXT] + self.suffixes: if os.path.exists(path + ext): self.filename = path + ext return self return None def load_module(self, fullname): return import_template(fullname, self.filename, force=1) def _install_hook(suffixes=None): KIDLoader.suffixes = suffixes or [] path_hooks.append(KIDLoader) sys.path_importer_cache.clear() def _uninstall_hook(): i = 0 while i < len(path_hooks): if path_hooks[i] is KIDLoader: del path_hooks[i] else: i += 1 sys.path_importer_cache.clear() else: # Python < 2.3, fall back to using the old ihooks module import ihooks, imp class KIDHooks(ihooks.Hooks): def __init__(self, verbose=ihooks.VERBOSE, suffixes=None): ihooks.Hooks.__init__(self, verbose) self.suffixes = suffixes or [] def get_suffixes(self): return [(suffix, 'r', KID_FILE) for suffix in [KID_EXT] + self.suffixes] + imp.get_suffixes() class KIDLoader(ihooks.ModuleLoader): def load_module(self, name, stuff): file, filename, info = stuff (suff, mode, type) = info if type is KID_FILE: return import_template(name, filename, force=1) else: return ihooks.ModuleLoader.load_module(self, name, stuff) def _install_hook(suffixes=None): hooks = KIDHooks(suffixes=suffixes) loader = KIDLoader(hooks) importer = ihooks.ModuleImporter(loader) ihooks.install(importer) def _uninstall_hook(): ihooks.uninstall() PK ²Ð4ÂZ kid/util.pyclass QuickTextReader(object): def __init__(self, text): self.text = text def read(self, amount): t = self.text self.text = '' return t def xml_sniff(text): """Sniff text to see if it looks like XML. Return 1 if text looks like XML, otherwise return 0. """ for x in text: if x in '\t\r\n ': continue elif x == '<': return 1 else: return 0 from urllib import splittype def open_resource(uri, mode='rb'): """Generic resource opener.""" (scheme, rest) = splittype(uri) if not scheme or (len(scheme) == 1 and rest.startswith('\\')): return open(uri, mode) else: import urllib2 return urllib2.urlopen(uri) PKY´Ð4³p´fO O kid/namespace.pyc;ò º-“Dc@s•hZdefd„ƒYZeddƒZeddƒZeddƒZedd ƒZed d ƒZeeeƒZ dd dd d d dgZ dS(s NamespacecBsVtZed„Zd„Zd„ZeZeZd„Zd„Z d„Z d„Z RS(NcCs+||_||_|o|t| 0: if text and text.strip() == '': yield (TEXT, line_collapse.sub('\n', text)) elif text: if text.strip() == '': yield (TEXT, line_collapse.sub('\n', text)) else: yield (TEXT, text) yield (ev, item) hops+=1 # pre-tag indentation was used. # Make sure it's not used again for #PCDATA-sensitive elements if ev == START and (self.has_only_pcdata(item.tag) or item.tag == Comment): text = '' else: yield (ev, item) def whitespace_filter(self, stream): for ev, item in stream: if ev == TEXT: yield (TEXT, item.strip()) else: yield (ev, item) class XMLSerializer(Serializer): decl = 1 doctype = None cdata_elements = [] def __init__(self, encoding=None, decl=None, doctype=None, namespaces=None): Serializer.__init__(self, encoding) if decl is not None: self.decl = decl if doctype is not None: self.doctype = doctype if isinstance(self.doctype, basestring): # allow doctype strings self.doctype = doctypes[self.doctype] if namespaces: self.namespaces = namespaces def can_be_empty_element(self, ns_stack, item_name): return True def generate(self, stream, encoding=None, fragment=0): """Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. """ encoding = encoding or self.encoding or 'utf-8' escape_cdata = XMLSerializer.escape_cdata escape_attrib = XMLSerializer.escape_attrib lastev = None stream = iter(stream) names = NamespaceStack(self.namespaces) if not fragment: if self.decl: yield '\n' % encoding if self.doctype is not None: yield serialize_doctype(self.doctype) + '\n' text = None for ev, item in self.apply_filters(stream): if ev in (START, END) and item.tag == Fragment: continue elif ev == TEXT: if text is not None: text = u''.join([text, item]) else: text = item continue if lastev == START: if ev == END and (not text or not text.strip()) and self.can_be_empty_element(names, item.tag): yield ' />' lastev = END text = None names.pop() continue yield ">" if text: yield escape_cdata(text, encoding) text = None if ev == START: if item.tag == Comment: yield "" % item.text.encode(encoding) lastev = COMMENT continue elif item.tag == ProcessingInstruction: yield "" % item.text.encode(encoding) lastev = PI continue else: tag = item.tag names.push(namespaces(item, remove=1)) qname = names.qname(tag, default=1) yield "<" + qname.encode(encoding) attrs = item.attrib.items() if attrs: for k, v in attrs: qname = names.qname(k, default=0) yield ' %s="%s"' % (qname.encode(encoding), escape_attrib(v, encoding)) for prefix, uri in names.current.items(): if prefix == '': yield ' xmlns="%s"' % escape_attrib(uri, encoding) else: yield ' xmlns:%s="%s"' % (prefix.encode(encoding), escape_attrib(uri, encoding)) elif ev == END and item.tag not in (Comment, ProcessingInstruction): qname = names.qname(item.tag, default=1) yield "" % qname.encode(encoding) names.pop() lastev = ev return def escape_cdata(text, encoding=None): """Escape character data.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text) text = text.replace("&", "&") text = text.replace("<", "<") return text except (TypeError, AttributeError): raise_serialization_error(text) escape_cdata = staticmethod(escape_cdata) def escape_attrib(text, encoding=None): """Escape attribute value.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text) text = text.replace("&", "&") text = text.replace("<", "<") text = text.replace("\"", """) return text except (TypeError, AttributeError): raise_serialization_error(text) escape_attrib = staticmethod(escape_attrib) # sets try: set except NameError: try: from sets import Set as set except ImportError: def set(seq): return seq import kid.namespace as namespace xhtml = namespace.xhtml.uri import string class HTMLSerializer(Serializer): doctype = doctypes['html'] transpose = string.upper transpose = staticmethod(transpose) inject_type = 1 empty_elements = set(['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param']) # These element tags should not be indented elements_with_pcdata = set(['option', 'textarea', 'fieldset', 'title']) noescape_elements = set(['script', 'style']) boolean_attributes = set(['selected', 'checked', 'compact', 'declare', 'defer', 'disabled', 'ismap', 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap']) def __init__(self, encoding='utf-8', doctype=None, transpose=None): Serializer.__init__(self, encoding) if doctype: self.doctype = doctype if isinstance(self.doctype, basestring): # allow doctype strings self.doctype = doctypes[self.doctype] if transpose: self.transpose = transpose def has_only_pcdata(self, tagname): if isinstance(tagname, basestring) and tagname[0] == '{': tagname = tagname.split('}')[1] return tagname in self.elements_with_pcdata def generate(self, stream, encoding=None, fragment=0): """Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. """ encoding = encoding or self.encoding or 'utf-8' escape_cdata = HTMLSerializer.escape_cdata escape_attrib = HTMLSerializer.escape_attrib noescape_elements = self.noescape_elements boolean_attributes = self.boolean_attributes empty_elements = self.empty_elements names = NamespaceStack(self.namespaces) def grok_name(tag): if tag[0] == '{': uri, localname = tag[1:].split('}', 1) else: uri, localname = None, tag if uri and uri != xhtml: qname = names.qname(tag, default=0) else: qname = localname if self.transpose is not None: qname = self.transpose(qname) return (uri, localname, qname) attr_http_equiv = 'http-equiv' attr_content = 'content' if self.transpose: attr_http_equiv = self.transpose('http-equiv') attr_content = self.transpose('content') current = None stack = [current] stream = iter(stream) if not fragment and self.doctype is not None: yield serialize_doctype(self.doctype) + '\n' for ev, item in self.apply_filters(stream): if ev == TEXT and item: escape = current not in noescape_elements yield escape_cdata(item, encoding, escape) elif ev == START: if item.tag == Comment: yield "" % item.text.encode(encoding) lastev = COMMENT continue elif item.tag == ProcessingInstruction: yield "" % item.text.encode(encoding) lastev = PI continue elif item.tag == Fragment: continue else: names.push(namespaces(item, remove=1)) tag = item.tag (uri, localname, qname) = grok_name(tag) # push this name on the stack so we know where we are current = qname.lower() stack.append(current) yield "<" + qname.encode(encoding) attrs = item.attrib.items() if attrs: for k, v in attrs: (u, l, q) = grok_name(k) lq = q.lower() if lq == 'xml:lang': continue if lq in boolean_attributes: # XXX: what if v is 0, false, or no. # should we omit the attribute? yield ' %s' % q.encode(encoding) else: yield ' %s="%s"' % (q.encode(encoding), escape_attrib(v, encoding)) yield ">" if self.inject_type: if current == 'head': (uri, localname, qname) = grok_name("meta") yield '<%s %s="text/html; charset=%s"' \ ' %s="Content-Type">' \ % (qname.encode(encoding), attr_content, encoding, attr_http_equiv) elif ev == END and item.tag not in (Comment, ProcessingInstruction, Fragment): current = stack.pop() if current not in empty_elements: tag = item.tag (uri, localname, qname) = grok_name(tag) yield "" % qname.encode(encoding) current = stack[-1] names.pop() return def escape_cdata(text, encoding=None, escape=1): """Escape character data.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text) if escape: text = text.replace("&", "&") text = text.replace("<", "<") return text except (TypeError, AttributeError): raise_serialization_error(text) escape_cdata = staticmethod(escape_cdata) def escape_attrib(text, encoding=None): """Escape attribute value.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text) text = text.replace("&", "&") text = text.replace("\"", """) return text except (TypeError, AttributeError): raise_serialization_error(text) escape_attrib = staticmethod(escape_attrib) class XHTMLSerializer(XMLSerializer): empty_elements = [namespace.xhtml.clarkname(name) for name in HTMLSerializer.empty_elements] elements_with_pcdata = [namespace.xhtml.clarkname(name) for name in HTMLSerializer.elements_with_pcdata] def can_be_empty_element(self, ns_stack, tagname): return tagname in self.empty_elements def has_only_pcdata(self, tagname): return tagname in self.elements_with_pcdata class PlainSerializer(Serializer): def generate(self, stream, encoding=None, fragment=0): # XXX: Should this be ASCII? encoding = encoding or self.encoding or 'utf-8' for ev, item in self.apply_filters(stream): if ev == TEXT: yield item class NamespaceStack: """Maintains a stack of namespace prefix to URI mappings.""" def __init__(self, default_map=namespace.namespaces): self.stack = [] self.default_map = default_map self.push() self.ns_count = 0 def push(self, names=None): if names is None: names = {} self.current = names self.stack.insert(0, self.current) def pop(self): del self.stack[0] if len(self.stack): self.current = self.stack[0] def resolve_prefix(self, uri, default=1): """Figure out prefix given a URI.""" if uri == 'http://www.w3.org/XML/1998/namespace': return 'xml' # first check if the default is correct is_default = -1 prefix = None for names in self.stack: for k, v in names.items(): # (k,v) = (prefix, uri) if default and is_default == -1 and k == '': # this is the current default namespace is_default = (v == uri) if (default and is_default) or prefix: break if v == uri and k != '': prefix = k if is_default > -1: break if default and is_default == 1: return '' elif prefix: return prefix else: return None def resolve_uri(self, prefix): """Figure out URI given a prefix.""" if prefix == 'xml': return 'http://www.w3.org/XML/1998/namespace' for names in self.stack: uri = names.get(prefix) if uri: return uri return None def qname(self, cname, default=0): if isinstance(cname, QName): cname = cname.text if cname[0] != '{': # XXX: need to make sure default namespace is "no-namespace" return cname uri, localname = cname[1:].split('}', 1) prefix = self.resolve_prefix(uri, default) if prefix is None: # see if we have it in our default map prefix = self.default_map.get(uri) if prefix is not None: self.current[prefix] = uri else: if default and not self.current.has_key(''): prefix = '' self.current[prefix] = uri else: self.ns_count += 1 # XXX : need to check for collisions here. prefix = 'ns%d' % self.ns_count self.current[prefix] = uri if prefix != '': return '%s:%s' % (prefix, localname) else: return localname def set(self, prefix, uri): if prefix is None: prefix = '' self.current[prefix] = uri def serialize_doctype(doctype): return '' % doctype PK ²Ð4ßR+ÙÙkid/properties.py"""Configuration API.""" import release __revision__ = "$Rev: 332 $" __date__ = "$Date: 2006-05-20 22:26:35 +0000 (Sat, 20 May 2006) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = release.license _properties = { } def get(name, default=None): """Get the property identified by name if it exists or return default. name: the name of the property to retrieve default: the value returned for non-existing properties, defaults to None """ return _properties.get(name, default) def set(name, value): """The the property identified by name with the value identified by value. Returns the value passed in. """ _properties[name] = value return value def isset(name): """Returns True if a property exists or False if it doesn't.""" return _properties.has_key(name) def remove(name): """Remove a property.""" if name in _properties: del _properties[name] PK ²Ð4òP¿1•5•5kid/__init__.py"""Pythonic, XML Templating Kid is a simple, Python-based template language for generating and transforming XML vocabularies. Kid was spawned as a result of a kinky love triangle between XSLT, TAL, and PHP. We believe many of the best features of these languages live on in Kid with much of the limitations and complexity stamped out (well, eventually :). """ __revision__ = "$Rev: 332 $" __date__ = "$Date: 2006-05-20 22:26:35 +0000 (Sat, 20 May 2006) $" import release __version__ = release.version __author__ = release.author __email__ = release.email __copyright__ = release.copyright __license__ = release.license import sys import os from kid.util import xml_sniff, QuickTextReader from kid.namespace import Namespace from kid.pull import ElementStream, Element, SubElement, Fragment, \ XML, document, _coalesce from kid.et import ElementTree, Comment, ProcessingInstruction from kid.parser import KID_XMLNS from kid.serialization import Serializer, XMLSerializer, HTMLSerializer, PlainSerializer, XHTMLSerializer assume_encoding = sys.getdefaultencoding() def enable_import(suffixes=None): """Enable the kid module loader and import hooks. This function must be called before importing kid templates if templates are not pre-compiled. Note that if your application uses ZODB, you will need to import ZODB before calling this function as ZODB's import hooks have some issues if installed after the kid import hooks. """ import kid.importer kid.importer.install(suffixes) # # Turn on import hook if KID_IMPORT is set # if os.environ.get('KID_IMPORT', None) is not None: enable_import() def import_template(name): """Import template by name. This is identical to calling `enable_import` followed by an import statement. For example, importing a template named foo using the normal import mechanism looks like this:: import kid kid.enable_import() import foo This function can be used to achieve the same result as follows:: import kid foo = kid.import_template('foo') This is sometimes useful when the name of the template is available only as a string. """ enable_import() mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def load_template(file, name='', cache=1, encoding=None, ns={}): """Bypass import machinery and load a template module directly. This can be used as an alternative to accessing templates using the native python import mechanisms. file Can be a filename, a kid template string, or an open file object. name Optionally specifies the module name to use for this template. This is a hack to enable relative imports in templates. cache Whether to look for a byte-compiled version of the template. If no byte-compiled version is found, an attempt is made to dump a byte-compiled version after compiling. This argument is ignored if file is not a filename. """ if isinstance(file, basestring): if xml_sniff(file): fo = QuickTextReader(file) filename = '' else: fo = None filename = file else: fo = file filename = '' import kid.importer as importer if filename != '': abs_filename = path.find(filename) if not abs_filename: raise Exception, "Template not found: %s (in %s)" % ( filename, ', '.join(path.paths)) filename = abs_filename name = importer.get_template_name(name, filename) if sys.modules.has_key(name): return sys.modules.get(name) import kid.compiler as compiler if filename == '': code = compiler.compile(fo, filename, encoding) else: template = compiler.KidFile(filename, 0, encoding) code = template.compile(dump_code=cache, dump_source=os.environ.get('KID_OUTPUT_PY')) mod = importer._create_module(code, name, filename, store=cache, ns=ns) return mod # create some default serializers.. output_methods = { 'xml' : XMLSerializer(decl=1), 'xhtml' : XHTMLSerializer(decl=0, doctype='xhtml'), 'xhtml-strict' : XHTMLSerializer(decl=0, doctype='xhtml-strict'), 'html' : HTMLSerializer(doctype='html'), 'html-strict' : HTMLSerializer(doctype='html-strict'), 'plain': PlainSerializer()} def Template(file=None, source=None, name=None, **kw): """Get a Template class quickly given a module name, file, or string. This is a convenience function for getting a template in a variety of ways. One and only one of the arguments name or file must be specified. file:string The template module is loaded by calling ``load_template(file, name='', cache=1)`` name:string The kid import hook is enabled and the template module is located using the normal Python import mechanisms. source:string string containing the templates source. Once the template module is obtained, a new instance of the module's Template class is created with the keyword arguments passed to this function. """ if name: mod = import_template(name) elif file is not None: mod = load_template(file) elif source is not None: mod = load_template(QuickTextReader(source), hex(id(source))) else: raise Exception("Must specify one of name, file, or source.") mod.Template.module = mod return mod.Template(**kw) from kid.filter import transform_filter class BaseTemplate(object): """Base class for compiled Templates. All kid template modules expose a class named ``Template`` that extends from this class making the methods defined here available on all Template subclasses. This class should not be instantiated directly. """ # the serializer to use when writing output serializer = output_methods['xml'] _filters = [transform_filter] def __init__(self, *args, **kw): """ Initialize a template with instance attributes specified by keyword arguments. Keyword arguments are available to the template using self.var notation. """ self.__dict__.update(kw) self._layout_classes = [] def write(self, file, encoding=None, fragment=0, output=None): """ Execute template and write output to file. file:file A filename or a file like object (must support write()). encoding:string The output encoding. Default: utf-8. fragment:bool Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to 1 when generating fragments meant to be inserted into existing XML documents. output:string,`Serializer` A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. """ serializer = self._get_serializer(output) return serializer.write(self, file, encoding, fragment) def serialize(self, encoding=None, fragment=0, output=None): """ Execute a template and return a single string. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to 1 when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. This is a convienence method, roughly equivalent to:: ''.join([x for x in obj.generate(encoding, fragment, output)] """ serializer = self._get_serializer(output) return serializer.serialize(self, encoding, fragment) def generate(self, encoding=None, fragment=0, output=None): """ Execute template and generate serialized output incrementally. This method returns an iterator that yields an encoded string for each iteration. The iteration ends when the template is done executing. encoding The output encoding. Default: utf-8. fragment Controls whether prologue information (such as declaration and DOCTYPE should be written). Set to 1 when generating fragments meant to be inserted into existing XML documents. output A string specifying an output method ('xml', 'html', 'xhtml') or a Serializer object. """ serializer = self._get_serializer(output) return serializer.generate(self, encoding, fragment) def __iter__(self): return iter(self.transform()) def __str__(self): return self.serialize() def __unicode__(self): return unicode(self.serialize(encoding='utf-16'), 'utf-16') def initialize(self): pass def pull(self): """Returns an iterator over the items in this template.""" # create stream and apply filters self.initialize() stream = ElementStream(_coalesce(self.content(), self._get_assume_encoding())) return stream def _pull(self): """Generate events for this template. Compiled templates implement this method. """ return [] def content(self): from inspect import getmro visited = self._layout_classes mro = list(getmro(self.__class__)) mro.reverse() for c in mro: if c.__dict__.has_key('layout') and c not in visited: visited.insert(0, c) return c.__dict__['layout'](self) return self._pull() def transform(self, stream=None, filters=[]): """ Execute the template and apply any match transformations. If stream is specified, it must be one of the following: Element An ElementTree Element. ElementStream An `pull.ElementStream` instance or other iterator that yields stream events. string A file or URL unless the string starts with '<' in which case it is considered an XML document and processed as if it had been an Element. By default, the `pull` method is called to obtain the stream. """ if stream is None: stream = self.pull() elif isinstance(stream, basestring): if xml_sniff(stream): stream = XML(stream, fragment=0) else: stream = document(stream) elif hasattr(stream, 'tag'): stream = ElementStream(stream) else: stream = ElementStream.ensure(stream) for f in filters + self._filters: stream = f(stream, self) return stream def _get_match_templates(self): # XXX: use inspect instead of accessing __mro__ directly try: rslt = self._match_templates_cached except AttributeError: rslt = [] mro = self.__class__.__mro__ for C in mro: try: templates = C._match_templates except AttributeError: continue rslt += templates self._match_templates_cached = rslt return rslt def _get_serializer(self, serializer): if serializer is None: return self.serializer elif isinstance(serializer, basestring): return output_methods[serializer] else: return serializer def _get_assume_encoding(self): global assume_encoding if hasattr(self, "assume_encoding"): return self.assume_encoding else: return assume_encoding def defined(self, name): return hasattr(self, name) def value_of(self, name, default=None): return getattr(self, name, default) class TemplatePath(object): def __init__(self, paths=None): if isinstance(paths, basestring): paths = [paths] elif paths is None: paths = [] paths += [os.getcwd(), '/'] self.paths = [self._cleanse_path(p) for p in paths] def _cleanse_path(self, path): from os.path import normpath, expanduser, abspath return abspath(normpath(expanduser(path))) def insert(self, path, pos=0): self.paths.insert(pos, self._cleanse_path(path)) def append(self, path): self.paths.append(self._cleanse_path(path)) def find(self, path, rel="/"): from os.path import normpath, join, exists, dirname path = normpath(path) for p in self.paths + [dirname(rel)]: p = join(p, path) if exists(p): return p path = TemplatePath() import kid.properties properties = kid.properties __all__ = ['KID_XMLNS', 'BaseTemplate', 'Template', 'enable_import', 'import_template', 'load_template', 'Element', 'SubElement', 'XML', 'document', 'Namespace', 'Serializer', 'XMLSerializer', 'HTMLSerializer', 'XHTMLSerializer', 'output_methods', 'filter', 'namespace', 'serialization', 'util', 'properties'] PKZ´Ð4©”ÿ¿ kid/util.pyc;ò º-“Dc@s<defd„ƒYZd„ZdklZdd„ZdS(sQuickTextReadercBstZd„Zd„ZRS(NcCs ||_dS(N(stextsself(sselfstext((s&build/bdist.linux-i686/egg/kid/util.pys__init__scCs|i}d|_|SdS(Ns(sselfstextst(sselfsamountst((s&build/bdist.linux-i686/egg/kid/util.pysreads  (s__name__s __module__s__init__sread(((s&build/bdist.linux-i686/egg/kid/util.pysQuickTextReaders cCsBx;|D]3}|djoqq|djodSqdSqWdS(seSniff text to see if it looks like XML. Return 1 if text looks like XML, otherwise return 0. s ssCopyright 2006, David StanekcCsti||ƒSdS(sÇGet the property identified by name if it exists or return default. name: the name of the property to retrieve default: the value returned for non-existing properties, defaults to None N(s _propertiessgetsnamesdefault(snamesdefault((s,build/bdist.linux-i686/egg/kid/properties.pysget scCs|t|<|SdS(snThe the property identified by name with the value identified by value. Returns the value passed in. N(svalues _propertiessname(snamesvalue((s,build/bdist.linux-i686/egg/kid/properties.pyssets cCsti|ƒSdS(s9Returns True if a property exists or False if it doesn't.N(s _propertiesshas_keysname(sname((s,build/bdist.linux-i686/egg/kid/properties.pysissetscCs|tjo t|=ndS(sRemove a property.N(snames _properties(sname((s,build/bdist.linux-i686/egg/kid/properties.pysremove"s (s__doc__sreleases __revision__s__date__s __author__s __copyright__slicenses __license__s _propertiessNonesgetssetsissetsremove( s __copyright__s __revision__s __license__sgetsremoves __author__s__date__ssets _propertiessreleasesisset((s,build/bdist.linux-i686/egg/kid/properties.pys?s    PKY´Ð4÷«)<5<5kid/test/test_kid.pyc;ò ¹-“Dc@s[dZdZdZdZdZdZdkZdkZdkl Z l Z l Z dk l Z d klZdkZdkZd kTdkiZd „Zd „Zd „Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z!d„Z"d„Z#d„Z$d„Z%d„Z&d„Z'dd „Z(d!„Z)dS("skid package tests.s $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sdirnamesabspathsjoin(sglob(sStringIO(s*cCsjddg}x*tttdƒƒD]}ti|ƒq"Wx*tttdƒƒD]}ti|ƒqOWdS(Ns __init__.pys blocks.pys*.outs*.pyc(s dont_cleansglobsjoinpaths output_dirsfsossunlinks template_dir(sfs dont_clean((s/build/bdist.linux-i686/egg/kid/test/test_kid.pyscleanups cCs tƒdS(N(scleanup(smodule((s/build/bdist.linux-i686/egg/kid/test/test_kid.pys setup_modulescCs#tiidƒ o tƒndS(Ns KID_NOCLEANUP(sossenvironsgetscleanup(smodule((s/build/bdist.linux-i686/egg/kid/test/test_kid.pysteardown_module scCs`t|dƒpt‚t|dƒpt‚t|dƒpt‚t|dƒpt‚dS(Nspullsgenerateswrites serialize(shasattrstsAssertionError(st((s/build/bdist.linux-i686/egg/kid/test/test_kid.pysassert_template_interface$scCs{tiƒdki}|i}ttdƒ}|ddddƒ}|i ƒ}x|D]}qVW|i|ƒt|ƒdS(Ns context.outsfooi sbarsbla bla(skids enable_imports test.contextscontextscsTemplatesCsjoinpaths output_dirsoutstspullsitseswritescheck_test_file(scsesCstsitsout((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_import_and_expand*s     cCs^tiitdƒ pt‚titdƒ}t|ƒtiitdƒpt‚dS(Nstest_def( ssyssmodulesshas_keystemplate_packagesAssertionErrorskidsimport_templatestsassert_template_interface(st((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_import_template_func6s cCs«tittdƒddddƒ}t|ƒtittdƒdtdddƒ}||j pt‚tittdƒdtdddƒ}||jpt‚dS(Ns test_if.kidsnamesscacheistest_ifi( skids load_templatesjoinpaths template_dirstsassert_template_interfacestemplate_packagest2sAssertionErrorst3(st2st3st((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_load_template_func<s     c Csrtittdƒddddƒ}d}ti|dtdhd|<ƒ}|iƒ}d |jpt ‚dS( Ns templates.kidsnamesscacheisƒ snsstsThis is a test( skids load_templatesjoinpaths template_dirstsssFalsest2s serializesxmlsAssertionError(sxmlst2ssst((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_load_template_func_with_nsIs $ cCs>tidtdƒ}t|ƒt|tiƒpt‚dS(Nsnamestest_if(skidsTemplatestemplate_packagestsassert_template_interfaces isinstances BaseTemplatesAssertionError(st((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_template_funcUs cCsCd„}|tidtdƒƒ|tittdƒƒƒdS(NcCsHxA|iddƒD]-}|tj ot|ƒdjpt‚qWdS(Nsencodingsasciii(sosgeneratesssNoneslensAssertionError(soss((s/build/bdist.linux-i686/egg/kid/test/test_kid.pysrun_test[ssnamestest_ifs test_if.kid(srun_testskidsTemplatestemplate_packages load_templatesjoinpaths template_dir(srun_test((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_generate_funcZs cCsedfd„ƒY}tidtdƒid|ƒƒtittdƒƒ}|id|ƒƒdS(NsFOcBstZd„ZRS(NcCsdS(N((sselfstext((s/build/bdist.linux-i686/egg/kid/test/test_kid.pyswritecs(s__name__s __module__swrite(((s/build/bdist.linux-i686/egg/kid/test/test_kid.pysFObssnamestest_ifsfiles test_if.kid( sFOskidsTemplatestemplate_packageswrites load_templatesjoinpaths template_dirsm(smsFO((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_write_funcas#cCsCd„}|tidtdƒƒ|tittdƒƒƒdS(NcCsv|iddƒ}|tj ot|ƒdjpt‚|iddƒ}|tj ot|ƒdjpt‚dS(Nsencodingsutf-8isascii(sos serializesoutsNoneslensAssertionError(sosout((s/build/bdist.linux-i686/egg/kid/test/test_kid.pysrun_testjs'snamestest_ifs test_if.kid(srun_testskidsTemplatestemplate_packages load_templatesjoinpaths template_dir(srun_test((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_serialize_funcis cCsOd}tid|ƒ}|iƒiƒ}||jptd||f‚dS(Ns= sfiles%r != %r(stextskidsTemplatestemplates serializesstripsactualsAssertionError(stextsactualstemplate((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_short_formrscCsŸd}tiddd|ƒ}|iddƒ}|djpt‚d}tiddd|ƒ}|iddƒ}d }||jptd ||f‚dS( Nu&some plain "text" with & entities.ssources

${XML(text)}

stextsfragmentis-

some plain "text" with & entities.

ssomething

something else

s&

something

something else

s%r != %r( stextskidsTemplatests serializesrsltsAssertionErrorsactualsexpected(sactualstextstsexpectedsrslt((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_XML_func_fragment{scCs[d}tiddd|ƒ}|iddƒ}d}||jptd||f‚dS( Nssomething

something else

ssources

${XML(text,xmlns="foo")}

stextsfragmentis2

something

something else

s%r != %r(stextskidsTemplatests serializesactualsexpectedsAssertionError(sexpectedstextsactualst((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_XML_ns_fragment‡s cCs3d}tiddd|ƒ}t|iƒƒGHdS(Nu asdf ― qwerssources

${XML(s)}

ss(ssskidsTemplatestsreprs serialize(ssst((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_XML_func_unicodeŽscCstiddƒ}tidƒ|_d}|iddƒ|jpt‚ti |iƒGH|iddƒ|jpt‚dS(Nssources $xmls somenestedelementss'somenestedelementssfragmenti( skidsTemplatests ElementTrees fromstringsxmlsexpecteds serializesAssertionErrorsdump(sexpectedst((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_dont_modify_trees“s  cCsAtiddƒ}|iddƒ}|GH|djpt‚dS(Nssourcessfragmenti(skidsTemplatests serializesrsltsAssertionError(srsltst((s/build/bdist.linux-i686/egg/kid/test/test_kid.pys test_comments›scCstttdƒƒ}xq|D]i}yM|dd!d}tid|ddƒ}d|_ |i |ƒt |ƒWqd |GH‚qXqWdS( Ns test_*.kidiiüÿÿÿs.outsfilescacheisutf-8s Template: %s( sglobsjoinpaths template_dirs test_filessfsoutskidsTemplatestemplatesassume_encodingswritescheck_test_file(sfstemplates test_filessout((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_kid_files¡s   cCsÿtii}ti|ƒiƒ}|idjpt ‚xÀ|i dƒD]¯}|i dƒ}|i dƒ}|idƒdjo,ti|iƒ}|i|ƒd|_nyt||dd ƒWnt j o ‚n X|ƒtiid 7_qHWdS( Nstestdocstestsattemptsexpectstypestextss diff_thisii(skidstestsdots ElementTreesparsesfilesgetrootsdocstagsAssertionErrorsfindallstsfindsattemptsexpectsgetsXMLstextsappendsdiff_elmsadditional_tests(sfilesattemptsdocsexpectstsdot((s/build/bdist.linux-i686/egg/kid/test/test_kid.pyscheck_test_file®s"   icCsRxZ||gD]L}|io |iiƒpt|_|io |iiƒpt|_q W|oR|i|ijpt ‚|i |i jpt ‚|i|ijpt ‚n|i}|i}||jpt d||f‚|i ƒ}|i ƒ}t|ƒt|ƒjpt ‚x*t||ƒD]\}}t||ƒq1WdS(Ns%r != %r(selm1selm2sestailsstripsNonestexts diff_thisstagsAssertionErrorsattribsexpectedsactuals getchildrensch1sch2slenszipsdiff_elm(selm1selm2s diff_thissesch1sch2sactualsexpected((s/build/bdist.linux-i686/egg/kid/test/test_kid.pysdiff_elmÁs" #'  !    cCs\tiddƒ}tiddƒ}t|ƒdjpt‚t|ƒdjpt‚dS(siTest for bug reported it ticket #70 where collisions occured in templates created with a string. ssourcesss- s- N(skidsTemplatest1st2sstrsAssertionError(st2st1((s/build/bdist.linux-i686/egg/kid/test/test_kid.pystest_string_templatesÒs (*s__doc__s __revision__s__date__s __author__s __copyright__s __license__sosssyssos.pathsdirnamesabspathsjoinsjoinpathsglobsStringIOskidskid.testskid.etsets ElementTreescleanups setup_modulesteardown_modulesassert_template_interfacestest_import_and_expandstest_import_template_funcstest_load_template_funcstest_load_template_func_with_nsstest_template_funcstest_generate_funcstest_write_funcstest_serialize_funcstest_short_formstest_XML_func_fragmentstest_XML_ns_fragmentstest_XML_func_unicodestest_dont_modify_treess test_commentsstest_kid_filesscheck_test_filesdiff_elmstest_string_templates($stest_short_formsdirnamestest_dont_modify_treessglobstest_load_template_funcstest_serialize_funcstest_load_template_func_with_nss ElementTreestest_XML_func_unicodes __revision__scheck_test_filescleanupstest_XML_func_fragmentsjoinpathstest_import_template_funcstest_template_funcstest_kid_filess test_commentssabspathstest_write_funcs __license__steardown_modules setup_modules __author__ssysstest_XML_ns_fragmentskids __copyright__sStringIOstest_import_and_expands__date__stest_generate_funcsdiff_elmstest_string_templatessossassert_template_interface((s/build/bdist.linux-i686/egg/kid/test/test_kid.pys?sF                  PK ²Ð4 ¥û¸X X kid/test/test_parser.py"""kid.parser tests.""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import kid def test_interpolate_expr(): from kid.parser import interpolate tests = [ ('foo ${bar} baz', ["'foo '", "bar", "' baz'"]), ('foo $bar baz', ["'foo '", "bar", "' baz'"]), ('foo $${bar} baz', 'foo ${bar} baz'), ('foo $$bar baz', 'foo $bar baz'), ('${foo} bar baz', ["foo", "' bar baz'"]), ('$foo bar baz', ["foo", "' bar baz'"]), ('foo bar ${baz}', ["'foo bar '", "baz"]), ('foo bar $baz', ["'foo bar '", "baz"]), ('foo $${bar}${baz}', ["'foo ${bar}'", "baz"]), ('foo $$bar$baz', ["'foo $bar'", "baz"]), ('${foo} bar ${baz}', ["foo", "' bar '", "baz"]), ('$foo bar $baz', ["foo", "' bar '", "baz"]), ('${foo}$${bar}${baz}', ["foo", "'${bar}'", "baz"]), ('$foo$$bar$baz', ["foo", "'$bar'", "baz"]), ('foo $object.attr bar', ["'foo '", "object.attr", "' bar'"]), ('$ foo ${bar baz}', ["'$ foo '", 'bar baz']), ('foo$ ${bar.baz}', ["'foo$ '", 'bar.baz']), ('$foo $100 $bar', ["foo", "' $100 '", "bar"]), ('$foo $$100 $bar', ["foo", "' $100 '", "bar"]), ('$$foo', '$foo'), ('', '')] for test, expect in tests: actual = interpolate(test) assert actual == expect def test_interpolate_object(): from kid.parser import interpolate expr = interpolate("foo ${bar} baz") assert repr(expr) == "['foo ', bar, ' baz']" # test for ticket #79 assert repr(interpolate('$foo')) == '[foo]' def test_adjust_block(): from test.blocks import blocks from kid.parser import _adjust_python_block for test, expect in blocks: rslt = list(_adjust_python_block(test.splitlines())) rslt = '\n'.join(rslt) if expect != rslt: print 'Expected: %r' % expect print 'Got: %r' % rslt raise "test_adjust_block failed." def test_exec_hack(): """Guido may break this some day..""" exec('x = 10') assert x == 10 PK ²Ð4]ôt§kid/test/test_namespace.py"""kid.namespace tests.""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " def test_namespace_module(): from kid.namespace import Namespace ns = Namespace(uri='urn:test', prefix='test') assert ns.name == '{urn:test}name' assert ns['name'] == '{urn:test}name' assert ns.qname('name') == 'test:name' ns = Namespace(uri=None) assert ns.name == 'name' assert ns['name'] == 'name' assert ns.qname('name') == 'name' PK ²Ð4=@팉‰kid/test/test_compiler.py"""kid package tests.""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import sys from os.path import join, dirname, exists import kid import kid.compiler import kid.test.test_kid check_test_file = kid.test.test_kid.check_test_file def setup_module(module): kid.test.test_kid.setup_module(module) def teardown_module(module): kid.test.test_kid.teardown_module(module) def assert_template_interface(t): assert hasattr(t, 'pull') assert hasattr(t, 'generate') assert hasattr(t, 'write') assert hasattr(t, 'serialize') def test_import_hook(): kid.enable_import() import test.test_if assert_template_interface(test.test_if) assert sys.modules.has_key('test.test_if') def test_pyc_generation(): # if this exists, the test is worthless. make sure this test runs before # anything else import test_content from kid.test import template_dir kid.enable_import() assert not exists(join(template_dir, 'test_content.pyc')) import test.test_content assert exists(join(template_dir, 'test_content.pyc')) assert sys.modules.has_key('test.test_content') def test_import_and_expand(): from kid.test import template_dir, output_dir kid.enable_import() import test.context as c C = c.Template out = join(output_dir, 'context.out') t = C(foo=10, bar='bla bla') it = t.pull() for e in it: pass t.write(out) check_test_file(out) PK ²Ð4á —#hhkid/test/test_unicode.py"""Unicode tests""" from kid.pull import to_unicode astr = '\xe2\x80\xa0\xc2\xa9\xe2\x80\x94' ustr = astr.decode('utf-8') def test_to_unicode(): assert to_unicode(ustr, 'utf-8') == ustr assert to_unicode(astr, 'utf-8') == ustr class C(object): def __unicode__(self): return ustr assert to_unicode(C(), 'utf-8') == ustr PKY´Ð4þŽkid/test/test_properties.pyc;ò ¹-“Dc@sUdZdZdZdZdZdZdkZeiZd„Z d„Z d „Z dS( sKid properties tests.s$Rev: $s$Date: $s"David Stanek sCopyright 2006, David Staneks8MIT NcCsˆd}ti|ƒtjpt‚ti|dƒdjpt‚tƒ}ti||ƒ|jpt‚ti|ƒ pt‚dS(Nsdoes_not_exist:propertyiÿÿÿÿ(spropertyspropsgetsNonesAssertionErrorsobjectsosisset(spropertyso((s6build/bdist.linux-i686/egg/kid/test/test_properties.pystest_api_nonexisting_property s    cCsgd}d}ti||ƒ|jpt‚ti|dƒ|jpt‚ti|ƒpt‚dS(Nsunittest:propertys it workedsit didn't worked(spropertysexpectedspropssetsAssertionErrorsgetsisset(sexpectedsproperty((s6build/bdist.linux-i686/egg/kid/test/test_properties.pystest_api_existing_propertys   cCstd}ti|dƒti|ƒdjpt‚ti|ƒti|ƒ pt‚ti|ƒ pt‚dS(Nsunittest:propertystest(spropertyspropssetsgetsAssertionErrorsremovesisset(sproperty((s6build/bdist.linux-i686/egg/kid/test/test_properties.pystest_api_remove_propertys  ( s__doc__s __revision__s__date__s __author__s __copyright__s __license__skids propertiesspropstest_api_nonexisting_propertystest_api_existing_propertystest_api_remove_property( s __copyright__s __revision__stest_api_remove_propertys __license__stest_api_nonexisting_propertys __author__s__date__spropstest_api_existing_propertyskid((s6build/bdist.linux-i686/egg/kid/test/test_properties.pys?s    PKY´Ð4Òì&--kid/test/test_pull.pyc;ò ¹-“Dc@s?dZdZdZdZdZdZdkTdkTd„ZdS( skid.pull testss $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT (s*cCsotdddƒ}|iƒ}|idjpt‚|didjpt‚|didjpt‚dS(Nsworldsfragmentisdocshellosworld(sXMLsdocsexpandstagsAssertionErrorstext(sdoc((s0build/bdist.linux-i686/egg/kid/test/test_pull.pys test_expand s  N( s__doc__s __revision__s__date__s __author__s __copyright__s __license__skid.etskid.pulls test_expand(s __copyright__s __revision__s __license__s test_expands __author__s__date__((s0build/bdist.linux-i686/egg/kid/test/test_pull.pys?sPKY´Ð4ˆm m kid/test/test_parser.pyc;ò ¹-“Dc@sUdZdZdZdZdZdZdkZd„Zd„Zd „Z d „Z dS( skid.parser tests.s $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT NcCsŒdkl}ddddgfddddgfddfddfd d d gfd d d gfd ddgfdddgfdddgfdddgfdd ddgfdd ddgfdd ddgfdd ddgfddddgfdd d!gfd"d#d$gfd%d d&dgfd'd d&dgfd(d)fd*d*fg}x4|D],\}}||ƒ}||jpt‚qXWdS(+N(s interpolatesfoo ${bar} bazs'foo 'sbars' baz's foo $bar bazsfoo $${bar} bazs foo $$bar bazs${foo} bar bazsfoos ' bar baz's $foo bar bazsfoo bar ${baz}s 'foo bar 'sbazs foo bar $bazsfoo $${bar}${baz}s 'foo ${bar}'s foo $$bar$bazs 'foo $bar's${foo} bar ${baz}s' bar 's $foo bar $bazs${foo}$${bar}${baz}s'${bar}'s $foo$$bar$bazs'$bar'sfoo $object.attr bars object.attrs' bar's$ foo ${bar baz}s'$ foo 'sbar bazsfoo$ ${bar.baz}s'foo$ 'sbar.bazs$foo $100 $bars' $100 's$foo $$100 $bars$$foos$foos(s kid.parsers interpolatestestsstestsexpectsactualsAssertionError(steststestssactualsexpects interpolate((s2build/bdist.linux-i686/egg/kid/test/test_parser.pystest_interpolate_expr s ÿE  cCsWdkl}|dƒ}t|ƒdjpt‚t|dƒƒdjpt‚dS(N(s interpolatesfoo ${bar} bazs['foo ', bar, ' baz']s$foos[foo](s kid.parsers interpolatesexprsreprsAssertionError(sexprs interpolate((s2build/bdist.linux-i686/egg/kid/test/test_parser.pystest_interpolate_object&s  cCs…dkl}dkl}xd|D]\\}}t||iƒƒƒ}di |ƒ}||jod|GHd|GHd‚q!q!WdS(N(sblocks(s_adjust_python_blocks s Expected: %rsGot: %rstest_adjust_block failed.( s test.blockssblockss kid.parsers_adjust_python_blockstestsexpectslists splitlinessrsltsjoin(sblockss_adjust_python_blockstestsrsltsexpect((s2build/bdist.linux-i686/egg/kid/test/test_parser.pystest_adjust_block.s      cBs ddUedjpt‚dS(sGuido may break this some day..sx = 10Ni (sxsAssertionError(((s2build/bdist.linux-i686/egg/kid/test/test_parser.pystest_exec_hack9s( s__doc__s __revision__s__date__s __author__s __copyright__s __license__skidstest_interpolate_exprstest_interpolate_objectstest_adjust_blockstest_exec_hack( s __copyright__s __revision__stest_interpolate_objects __license__stest_adjust_blockstest_interpolate_exprs __author__s__date__stest_exec_hackskid((s2build/bdist.linux-i686/egg/kid/test/test_parser.pys?s    PKY´Ð4oÉ%ÄÄkid/test/test_namespace.pyc;ò ¹-“Dc@s1dZdZdZdZdZdZd„ZdS(skid.namespace tests.s $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT cCsÍdkl}|ddddƒ}|idjpt‚|ddjpt‚|idƒdjpt‚|dtƒ}|idjpt‚|ddjpt‚|idƒdjpt‚dS( N(s Namespacesurisurn:testsprefixstests{urn:test}namesnames test:name(s kid.namespaces NamespacesnssnamesAssertionErrorsqnamesNone(snss Namespace((s5build/bdist.linux-i686/egg/kid/test/test_namespace.pystest_namespace_module s N(s__doc__s __revision__s__date__s __author__s __copyright__s __license__stest_namespace_module(s __copyright__s __revision__s __license__stest_namespace_modules __author__s__date__((s5build/bdist.linux-i686/egg/kid/test/test_namespace.pys?s PK ²Ð4]ã kid/test/test_properties.py"""Kid properties tests.""" __revision__ = "$Rev: $" __date__ = "$Date: $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = "MIT " import kid prop = kid.properties def test_api_nonexisting_property(): property = 'does_not_exist:property' assert prop.get(property) == None assert prop.get(property, -1) == -1 o = object() assert prop.get(property, o) is o assert not prop.isset(property) def test_api_existing_property(): property = 'unittest:property' expected = 'it worked' assert prop.set(property, expected) == expected assert prop.get(property, "it didn't worked") == expected assert prop.isset(property) def test_api_remove_property(): property = 'unittest:property' prop.set(property, 'test') assert prop.get(property) == 'test' prop.remove(property) assert not prop.isset(property) assert not prop.isset(property) # should not exist here PKY´Ð4)f>Skid/test/test_match.pyc;ò ¹-“Dc@sŠdZdZdZdZdkZdkZdklZlZei i dƒZ ei i idee ƒƒd„Zd „Zd „ZdS( s%Unit Tests for the template matching.s $Rev: 331 $s"David Stanek sCopyright 2005, David StanekN(sserialize_doctypesdoctypess test_matchingicCs‚tidƒ}|idƒtidƒ}|idƒtiddƒ}|iƒ}d|jpt ‚d|jpt ‚dS(Nsmatch0_base.kids( Your title goes here

smatch0_page.kidsÊ Welcome to TurboGears

My Main page with bold text

sfiles$Welcome to TurboGearssBOLD( stmpdirsjoinstfile0swritestfile1skidsTemplatests serializeshtmlsAssertionError(shtmlststfile0stfile1((s1build/bdist.linux-i686/egg/kid/test/test_match.pys test_match0s   cCs¾tidƒ}|idƒtidƒ}|idƒtiddƒ}|iƒ}d|jpt ‚d|jpt ‚d|jpt ‚d |jpt ‚d |jpt ‚dS( Nsmatch1_base.kids* Some title here
Real content would go here.
smatch1_page.kidsÐ

This is a test link, or an e-mail address.

sfilessPtest linksPe-mail addressss&
Real content would go here.
( stmpdirsjoinstfile0swritestfile1skidsTemplatests serializeshtmlsAssertionError(shtmlststfile0stfile1((s1build/bdist.linux-i686/egg/kid/test/test_match.pys test_match1@s   cCs»tidƒ}|idƒtidƒ}|idƒtidƒ}|idƒtiddƒ}d|_|iƒ}d|jpt ‚d |jpt ‚d |jpt ‚d S( s\Test for a know bad case in the apply_matches function. This was rewritten in #142. smatch142_master.kids~
smatch142_userform.kidså
smatch142_edit.kidsì sfiles THIS IS THEs MASTER MATCHsseasources:userformN( stmpdirsjoinstfileswriteskidsTemplatestsactions serializeshtmlsAssertionError(stfileshtmlst((s1build/bdist.linux-i686/egg/kid/test/test_match.pysXtest_match_142ms     (s__doc__s __revision__s __author__s __copyright__spyskidskid.serializationsserialize_doctypesdoctypesstests ensuretempstmpdirspathspathssinsertsstrs test_match0s test_match1sXtest_match_142( s test_match1s test_match0s __copyright__s __revision__sdoctypesspysserialize_doctypes __author__sXtest_match_142stmpdirskid((s1build/bdist.linux-i686/egg/kid/test/test_match.pys?s   2 -PK ²Ð4†qk~ë ë kid/test/test_kid_lang.py __revision__ = "$Rev: 331 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import kid def test_strip_no_expr(): """A py:strip without an expression will strip that element.""" source = """ stuff """ data = kid.Template(source=source).serialize() assert "wrapper" not in data assert "present" in data def test_strip_with_boolean_expression__or(): """Test for the bug that was reported in ticket #97.""" source_template = """ content content """ t = kid.Template(source=source_template % (True, True)) assert "" not in t.serialize() t = kid.Template(source=source_template % (True, False)) assert "" not in t.serialize() t = kid.Template(source=source_template % (False, True)) assert "" not in t.serialize() t = kid.Template(source=source_template % (False, False)) assert t.serialize().count("") == 2 def test_strip_with_boolean_expression__eq(): source = """ """ data = kid.Template(source=source).serialize() assert " you will never see this """ data = kid.Template(source=source).serialize() assert "wrapper" not in data assert "x" in data def test_replace_with_strip(): """py:strip as ignored if py:replace exists in the same element.""" source = """ content """ data = kid.Template(source=source).serialize() assert "wrapper" not in data assert "x" in data def test_attr(): source = """ """ data = kid.Template(source=source).serialize() assert data.count('') == 4 def test_attr_with_strip(): source = """ """ data = kid.Template(source=source).serialize() print data assert 'a="1"' in data assert 'b="2"' in data PK ²Ð4ÁÈÝ kid/test/test_scope.py"""Unit Tests for Python scope.""" __revision__ = "$Rev: 227 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import py import kid tmpdir = py.test.ensuretemp("test_scope") kid.path.paths.insert(0, str(tmpdir)) def test_scope_101(): """Test for scoping issue reported in ticket #101. Parameters passed into the Template constructor override the parameters of functions created with py:def. """ tfile = tmpdir.join("scope.kid") tfile.write(""" """) t = kid.Template(file="scope.kid", bar=1) assert "0" in t.serialize() PK ²Ð4>0Qn  kid/test/test_suffixes.py"""Unit Tests for the import suffix functionality.""" __revision__ = "$Rev: 219 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import sys import ihooks import py import kid import kid.importer tmpdir = py.test.ensuretemp("test_suffixes") sys.path = [str(tmpdir)] + sys.path tfile = tmpdir.join("test_suffixes0.kid") tfile.write(py.code.Source("""

my content

""")) def test_enable_import_empty(): """By default *.kid files are imported.""" kid.enable_import() import test_suffixes0 py.test.raises(ImportError, "import test_suffixes1") kid.importer.uninstall() def test_enable_import_with_suffixes(): """Using suffixes any file extension can be importable.""" kid.enable_import(suffixes=[".html", ".kid.html"]) import test_suffixes0 # *.kid files are always importable dest = tmpdir.join("test_suffixes1.html") tfile.copy(dest) import test_suffixes1 dest = tmpdir.join("test_suffixes2.kid.html") tfile.copy(dest) import test_suffixes2 dest = tmpdir.join("test_suffixes3.xhtml") tfile.copy(dest) py.test.raises(ImportError, "import test_suffixes3") kid.importer.uninstall() PKY´Ð4à÷6ffkid/test/test_scope.pyc;ò ¹-“Dc@sedZdZdZdZdkZdkZeiidƒZei i i de eƒƒd„Z dS(sUnit Tests for Python scope.s $Rev: 227 $s"David Stanek sCopyright 2005, David StanekNs test_scopeicCsRtidƒ}|idƒtiddddƒ}d|iƒjpt‚dS(s«Test for scoping issue reported in ticket #101. Parameters passed into the Template constructor override the parameters of functions created with py:def. s scope.kids£ sfilesbaris 0N( stmpdirsjoinstfileswriteskidsTemplatests serializesAssertionError(stfilest((s1build/bdist.linux-i686/egg/kid/test/test_scope.pystest_scope_101 s  (s__doc__s __revision__s __author__s __copyright__spyskidstests ensuretempstmpdirspathspathssinsertsstrstest_scope_101(s __copyright__s __revision__stest_scope_101spys __author__stmpdirskid((s1build/bdist.linux-i686/egg/kid/test/test_scope.pys?s  PK ²Ð4™åά¬kid/test/test_match.py"""Unit Tests for the template matching.""" __revision__ = "$Rev: 331 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import py import kid from kid.serialization import serialize_doctype, doctypes tmpdir = py.test.ensuretemp("test_matching") kid.path.paths.insert(0, str(tmpdir)) def test_match0(): tfile0 = tmpdir.join("match0_base.kid") tfile0.write(""" Your title goes here

""") tfile1 = tmpdir.join("match0_page.kid") tfile1.write(""" Welcome to TurboGears

My Main page with bold text

""") t = kid.Template(file="match0_page.kid") html = t.serialize() assert 'Welcome to TurboGears' in html assert 'BOLD' in html def test_match1(): tfile0 = tmpdir.join("match1_base.kid") tfile0.write(""" Some title here
Real content would go here.
""") tfile1 = tmpdir.join("match1_page.kid") tfile1.write("""

This is a test link, or an e-mail address.

""") t = kid.Template(file="match1_page.kid") html = t.serialize() assert '' in html assert 'test link' in html assert 'e-mail address' in html assert '' in html assert '
Real content would go here.
' not in html def Xtest_match_142(): """Test for a know bad case in the apply_matches function. This was rewritten in #142. """ tfile = tmpdir.join("match142_master.kid") tfile.write("""
""") tfile = tmpdir.join("match142_userform.kid") tfile.write("""
""") tfile = tmpdir.join("match142_edit.kid") tfile.write(""" """) t = kid.Template(file='match142_edit.kid') t.action = 'match142_edit.kid' html = t.serialize() assert 'THIS IS THE' in html # text from main template assert 'MASTER MATCH' in html # text from master template assert 'seasources:userform' not in html # text from userform template PKY´Ð4&sø»~&~&kid/test/test_serialization.pyc;ò ¹-“Dc@sdZdZdZdZdZdZdkZdklZdk l Z l Z e eƒZ d „Zd „Zd „Zd „Zd k lZlZeƒZee_de_d„Zd„Zd„Zd„Zd„Zd„ZdkZd„Zd„Z d„Z!d„Z"dS(skid.serialization tests.s $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sxhtml(sserialize_doctypesdoctypescCsRtidƒ}|iddƒ}ttdƒd}|GH||jpt‚dS(Ns

test


soutputshtmls

test


( skidsTemplatests serializesrsltsserialize_doctypesdoctypessexpectedsAssertionError(stsexpectedsrslt((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_html_output_methods cCsVtidƒ}|iddƒ}ttdƒdd}|GH||jpt‚dS(NsY

test


soutputsxhtmls7

test

s#
( skidsTemplatests serializesrsltsserialize_doctypesdoctypessexpectedsAssertionError(stsexpectedsrslt((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_xhtml_output_methods cCsRtidƒ}|iddƒ}ttdƒd}|GH||jpt‚dS(Ns

test


soutputs html-stricts

test


( skidsTemplatests serializesrsltsserialize_doctypesdoctypessexpectedsAssertionError(stsexpectedsrslt((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_html_strict_output_method$s cCsDtidƒ}|iddƒ}d}|GH||jpt‚dS(Ns

test


soutputsxmlsE

test


(skidsTemplatests serializesrsltsexpectedsAssertionError(sexpectedsrsltst((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_xml_output_method-s (sHTMLSerializers XMLSerializericKs&tid||}t|_|SdS(Nssource(skidsTemplatestextskwsts serializer(stextskwst((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pys HTMLTemplate;s cCs9tdtƒ}|iƒ}|GH|djpt‚dS(Ns
s
(s HTMLTemplatesxhtml_namespacests serializesrsltsAssertionError(srsltst((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_html_empty_elements@s cCs;tdƒ}d}|iƒ}|GH||jpt‚dS(NsNsB(s HTMLTemplatestsexpecteds serializesrsltsAssertionError(sexpectedsrsltst((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_html_noescape_elementsFs   cCs?tdtƒ}d}|iƒ}|GH||jpt‚dS(Ns9s*(s HTMLTemplatesxhtml_namespacestsexpecteds serializesrsltsAssertionError(sexpectedsrsltst((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_html_boolean_attributesOs  cCsntƒ}td|_d|_tiddƒ}||_d}|GH|i ƒ}|GH||jpt ‚dS(Ns html-strictissourcess¸ ( sHTMLSerializers serializersdoctypessdoctypes inject_typeskidsTemplatestsexpecteds serializesrsltsAssertionError(stsexpectedsrslts serializer((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_doctype_and_injectionWs     cCsetƒ}td|_tiddƒ}||_d}|GH|iƒ}|GH||jpt ‚dS(Ns html-strictssources sr ( sHTMLSerializers serializersdoctypessdoctypeskidsTemplatestsexpecteds serializesrsltsAssertionError(stsexpectedsrslts serializer((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_strip_langfs    cCsltƒ}t|_d|_ti|_ti ddƒ}||_d}|i ƒ}||jpt‚dS(Nissourcess(sHTMLSerializers serializersNonesdoctypes inject_typesstringslowers transposeskidsTemplatestsexpecteds serializesrsltsAssertionError(stsexpectedsrslts serializer((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_transpose_lowerss      cCsitƒ}t|_d|_t|_tiddƒ}||_d}|i ƒ}||jpt ‚dS(Nissourcess( sHTMLSerializers serializersNonesdoctypes inject_types transposeskidsTemplatestsexpecteds serializesrsltsAssertionError(stsexpectedsrslts serializer((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_transpose_off~s      cCs—xttfD]‚}xy|i|ifD]e}|dƒdjpt‚|dƒdjpt‚|ddƒdjpt‚|ddƒdjpt‚|dƒdjpt‚d}||ƒ}|tjp ||ijo d}n||jpt‚d }||ƒ}||ijo d }n||jpt‚y|d ƒpt‚Wq&t j o#}t |ƒd jpt‚q&Xq&Wq WdS( Nsstrsk„sesutf-8s k„ses&s&s soutputsxmlshtmls7 sxhtmls7 N(sexpectedskidsTemplates serializesAssertionErrorsserialize_doctypesdoctypes(sexpected((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pystest_comment_whitespace s))(#s__doc__s __revision__s__date__s __author__s __copyright__s __license__skids kid.namespacesxhtmlskid.serializationsserialize_doctypesdoctypessstrsxhtml_namespacestest_html_output_methodstest_xhtml_output_methodstest_html_strict_output_methodstest_xml_output_methodsHTMLSerializers XMLSerializers serializersNonesdoctypes inject_types HTMLTemplatestest_html_empty_elementsstest_html_noescape_elementsstest_html_boolean_attributesstest_doctype_and_injectionstest_strip_langsstringstest_transpose_lowerstest_transpose_offs test_escapestest_comment_whitespace(stest_transpose_offstest_html_output_methods XMLSerializerstest_doctype_and_injectionsstringstest_comment_whitespaces __revision__s __license__sHTMLSerializerstest_html_noescape_elementssxhtml_namespacesxhtmlskidstest_xml_output_methodsdoctypesstest_xhtml_output_methodsserialize_doctypes test_escapes __author__stest_transpose_lowers HTMLTemplatestest_strip_langs __copyright__stest_html_boolean_attributesstest_html_strict_output_methods__date__stest_html_empty_elementss serializer((s9build/bdist.linux-i686/egg/kid/test/test_serialization.pys?s8             PKY´Ð4M"ikid/test/test_kid_lang.pyc;ò ¹-“Dc@s^dZdZdZdkZd„Zd„Zd„Zd„Zd„Zd „Z d „Z dS( s $Rev: 331 $s"David Stanek sCopyright 2005, David StanekNcCsJd}tid|ƒiƒ}d|jpt‚d|jpt‚dS(s9A py:strip without an expression will strip that element.s© stuff ssourceswrapperspresentN(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s4build/bdist.linux-i686/egg/kid/test/test_kid_lang.pystest_strip_no_expr s cCsëd}tid|ttfƒ}d|iƒjpt‚tid|ttfƒ}d|iƒjpt‚tid|ttfƒ}d|iƒjpt‚tid|ttfƒ}|iƒidƒdjpt‚dS(s1Test for the bug that was reported in ticket #97.sá content content ssourcesiN( ssource_templateskidsTemplatesTruests serializesAssertionErrorsFalsescount(stssource_template((s4build/bdist.linux-i686/egg/kid/test/test_kid_lang.pys&test_strip_with_boolean_expression__ors cCsJd}tid|ƒiƒ}d|jpt‚d|jpt‚dS(Ns ssources you will never see this ssourceswrappersx(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s4build/bdist.linux-i686/egg/kid/test/test_kid_lang.pys test_replace6scCsJd}tid|ƒiƒ}d|jpt‚d|jpt‚dS(s=py:strip as ignored if py:replace exists in the same element.s© content ssourceswrappersxN(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s4build/bdist.linux-i686/egg/kid/test/test_kid_lang.pystest_replace_with_stripBs cCs?d}tid|ƒiƒ}|idƒdjpt‚dS(Ns  ssourcesi(ssourceskidsTemplates serializesdatascountsAssertionError(ssourcesdata((s4build/bdist.linux-i686/egg/kid/test/test_kid_lang.pys test_attrOscCsOd}tid|ƒiƒ}|GHd|jpt‚d|jpt‚dS(Nsƒ ssourcesa="1"sb="2"(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s4build/bdist.linux-i686/egg/kid/test/test_kid_lang.pystest_attr_with_strip[s ( s __revision__s __author__s __copyright__skidstest_strip_no_exprs&test_strip_with_boolean_expression__ors&test_strip_with_boolean_expression__eqs test_replacestest_replace_with_strips test_attrstest_attr_with_strip( stest_strip_no_exprs __copyright__s __revision__s test_attrs test_replaces&test_strip_with_boolean_expression__eqs __author__stest_attr_with_strips&test_strip_with_boolean_expression__orstest_replace_with_stripskid((s4build/bdist.linux-i686/egg/kid/test/test_kid_lang.pys?s   PK ²Ð4F”8kid/test/test_kid.py"""kid package tests.""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import sys from os.path import dirname, abspath, join as joinpath from glob import glob from StringIO import StringIO import kid, kid.test from kid.test import * import kid.et as ElementTree def cleanup(): dont_clean = ['__init__.py', 'blocks.py'] for f in glob(joinpath(output_dir, '*.out')): os.unlink(f) for f in glob(joinpath(template_dir, '*.pyc')): os.unlink(f) # for f in glob(joinpath(output_dir, '*.py')): # if f not in [joinpath(output_dir, p) for p in dont_clean]: # os.unlink(f) def setup_module(module): cleanup() def teardown_module(module): if not os.environ.get('KID_NOCLEANUP'): cleanup() def assert_template_interface(t): assert hasattr(t, 'pull') assert hasattr(t, 'generate') assert hasattr(t, 'write') assert hasattr(t, 'serialize') def test_import_and_expand(): kid.enable_import() import test.context as c C = c.Template out = joinpath(output_dir, 'context.out') t = C(foo=10, bar='bla bla') it = t.pull() for e in it: pass t.write(out) check_test_file(out) def test_import_template_func(): assert not sys.modules.has_key(template_package + 'test_def') t = kid.import_template(template_package + 'test_def') assert_template_interface(t) assert sys.modules.has_key(template_package + 'test_def') def test_load_template_func(): t = kid.load_template(joinpath(template_dir, 'test_if.kid'), name='', cache=0) assert_template_interface(t) t2 = kid.load_template(joinpath(template_dir, 'test_if.kid'), name=template_package + 'test_if', cache=1) assert not t is t2 t3 = kid.load_template(joinpath(template_dir, 'test_if.kid'), name=template_package + 'test_if', cache=1) assert t3 is t2 def test_load_template_func_with_ns(): t = kid.load_template(joinpath(template_dir, 'templates.kid'), name='', cache=0) s = """ """ t2 = kid.load_template(s, cache=False, ns={'t': t}) xml = t2.serialize() assert "This is a test" in xml def test_template_func(): t = kid.Template(name=template_package + 'test_if') assert_template_interface(t) assert isinstance(t, kid.BaseTemplate) def test_generate_func(): def run_test(o): for s in o.generate(encoding='ascii'): assert s is not None and len(s) > 0 run_test(kid.Template(name=template_package + 'test_if')) run_test(kid.load_template(joinpath(template_dir, 'test_if.kid'))) def test_write_func(): class FO: def write(self, text): pass kid.Template(name=template_package+'test_if').write(file=FO()) m = kid.load_template(joinpath(template_dir, 'test_if.kid')) m.write(file=FO()) def test_serialize_func(): def run_test(o): out = o.serialize(encoding='utf-8') assert out is not None and len(out) > 0 out = o.serialize(encoding='ascii') assert out is not None and len(out) > 0 run_test(kid.Template(name=template_package + 'test_if')) run_test(kid.load_template(joinpath(template_dir, 'test_if.kid'))) def test_short_form(): # check that the serializer is outputting short-form elements when # no character data is present text = """ """ template = kid.Template(file=text) #mod.Template() actual = template.serialize().strip() assert actual == text, '%r != %r' % (actual, text) def test_XML_func_fragment(): text = u"""some plain "text" with & entities.""" t = kid.Template(source="

${XML(text)}

", text=text) rslt = t.serialize(fragment=1) assert rslt == '''

some plain "text" with & entities.

''' # another one text = """something

something else

""" t = kid.Template(source="

${XML(text)}

", text=text) actual = t.serialize(fragment=1) expected = '''

something

something else

''' assert actual == expected, '%r != %r' % (actual, expected) def test_XML_ns_fragment(): text = """something

something else

""" t = kid.Template(source='

${XML(text,xmlns="foo")}

', text=text) actual = t.serialize(fragment=1) expected = '''

something

something else

''' assert actual == expected, '%r != %r' % (actual, expected) def test_XML_func_unicode(): s = u"""asdf \u2015 qwer""" t = kid.Template(source="""

${XML(s)}

""", s=s) print repr(t.serialize()) def test_dont_modify_trees(): t = kid.Template(source="$xml") t.xml = ElementTree.fromstring("somenestedelements") expected = "somenestedelements" assert t.serialize(fragment=1) == expected print ElementTree.dump(t.xml) assert t.serialize(fragment=1) == expected def test_comments(): t = kid.Template(source="") rslt = t.serialize(fragment=1) print rslt assert rslt == "" def test_kid_files(): test_files = glob(joinpath(template_dir, 'test_*.kid')) for f in test_files: try: out = f[0:-4] + '.out' template = kid.Template(file=f, cache=1) template.assume_encoding = "utf-8" template.write(out) check_test_file(out) except: print '\nTemplate: %s' % f raise def check_test_file(file): dot = kid.test.dot doc = ElementTree.parse(file).getroot() assert doc.tag == 'testdoc' for t in doc.findall('test'): attempt = t.find('attempt') expect = t.find('expect') if expect.get('type') == 'text': doc = ElementTree.XML(expect.text) expect.append(doc) expect.text = '' try: diff_elm(attempt, expect, diff_this=0) except AssertionError: raise else: dot() kid.test.additional_tests+= 1 def diff_elm(elm1, elm2, diff_this=1): for e in [elm1, elm2]: e.tail = e.tail and e.tail.strip() or None e.text = e.text and e.text.strip() or None if diff_this: assert elm1.tag == elm2.tag assert elm1.attrib == elm2.attrib assert elm1.tail == elm2.tail expected = elm2.text actual = elm1.text assert actual == expected, '%r != %r' % (actual, expected) ch1 = elm1.getchildren() ch2 = elm2.getchildren() assert len(ch1) == len(ch2) for elm1, elm2 in zip(ch1, ch2): diff_elm(elm1, elm2) def test_string_templates(): """Test for bug reported it ticket #70 where collisions occured in templates created with a string. """ t1 = kid.Template(source="") t2 = kid.Template(source="") assert str(t1) == '\n' assert str(t2) == '\n' PKY´Ð4a\M66kid/test/test_unicode.pyc;ò ¹-“Dc@s5dZdklZdZeidƒZd„ZdS(s Unicode tests(s to_unicodes†©—sutf-8cCstttdƒtjpt‚ttdƒtjpt‚dtfd„ƒY}t|ƒdƒtjpt‚dS(Nsutf-8sCcBstZd„ZRS(NcCstSdS(N(sustr(sself((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pys __unicode__ s(s__name__s __module__s __unicode__(((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pysC s(s to_unicodesustrsAssertionErrorsastrsobjectsC(sC((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pystest_to_unicodesN(s__doc__skid.pulls to_unicodesastrsdecodesustrstest_to_unicode(sastrs to_unicodesustrstest_to_unicode((s3build/bdist.linux-i686/egg/kid/test/test_unicode.pys?s PK ²Ð4Ý‰Ž½ÊÊkid/test/test_serialization.py"""kid.serialization tests.""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import kid from kid.namespace import xhtml from kid.serialization import serialize_doctype, doctypes xhtml_namespace = str(xhtml) def test_html_output_method(): t = kid.Template('

test


') rslt = t.serialize(output='html') expected = serialize_doctype(doctypes['html']) + \ '\n

test


' print rslt assert rslt == expected def test_xhtml_output_method(): t = kid.Template('' '

test


') rslt = t.serialize(output='xhtml') expected = serialize_doctype(doctypes['xhtml']) \ + '\n

test

' \ + '
' print rslt assert rslt == expected def test_html_strict_output_method(): t = kid.Template('

test


') rslt = t.serialize(output='html-strict') expected = serialize_doctype(doctypes['html-strict']) + \ '\n

test


' print rslt assert rslt == expected def test_xml_output_method(): t = kid.Template('

test


') rslt = t.serialize(output='xml') expected = '\n' \ '

test


' print rslt assert rslt == expected from kid.serialization import HTMLSerializer, XMLSerializer serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = 0 def HTMLTemplate(text, **kw): t = kid.Template(source=text, **kw) t.serializer = serializer return t def test_html_empty_elements(): t = HTMLTemplate("
" % xhtml_namespace) rslt = t.serialize() print rslt assert rslt == '
' def test_html_noescape_elements(): t = HTMLTemplate("") expected = '' rslt = t.serialize() print rslt assert rslt == expected def test_html_boolean_attributes(): t = HTMLTemplate("" % xhtml_namespace ) expected = '' rslt = t.serialize() print rslt assert rslt == expected def test_doctype_and_injection(): serializer = HTMLSerializer() serializer.doctype = doctypes['html-strict'] serializer.inject_type = 1 t = kid.Template(source="") t.serializer = serializer expected = '\n'\ ''\ ''\ '' print expected rslt = t.serialize() print rslt assert rslt == expected def test_strip_lang(): serializer = HTMLSerializer() serializer.doctype = doctypes['html-strict'] t = kid.Template(source="") t.serializer = serializer expected = '\n'\ '' print expected rslt = t.serialize() print rslt assert rslt == expected import string def test_transpose_lower(): serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = 0 serializer.transpose = string.lower t = kid.Template(source="") t.serializer = serializer expected = '' rslt = t.serialize() assert rslt == expected def test_transpose_off(): serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = 0 serializer.transpose = None t = kid.Template(source="") t.serializer = serializer expected = '' rslt = t.serialize() assert rslt == expected def test_escape(): for serializer in XMLSerializer, HTMLSerializer: for escape in serializer.escape_cdata, serializer.escape_attrib: assert escape('str') == 'str' assert escape('k\204se') == 'k\204se' assert escape('str', 'utf-8') == 'str' assert escape('k\204se', 'utf-8') == 'k„se' assert escape('&') == '&' t = '<' s = escape(t) if serializer != HTMLSerializer or escape != serializer.escape_attrib: t = '<' assert s == t t = '"' s = escape(t) if escape == serializer.escape_attrib: t = '"' assert s == t try: assert escape(1) except TypeError, e: assert str(e) == 'cannot serialize 1 (type int)' def test_comment_whitespace(): """Ticket #107 reported an issue where comments add an additional newline. """ expected = '\n\n' \ '\n\n' assert kid.Template(expected).serialize(output='xml') == expected expected = serialize_doctype(doctypes['html']) + '\n\n' \ '\n\n\n' assert kid.Template(expected).serialize(output='html') == expected expected = serialize_doctype(doctypes['xhtml']) + '\n\n' \ '\n\n\n' assert kid.Template(expected).serialize(output='xhtml') == expected PK ²Ð4ÈúNÅç ç kid/test/test_templatepath.py""" Unit tests for the kid.TemplatePath class. The testing directory structure looks something like this: :: test_templatepath0/ /index.kid /members/ /index.kid /stuff.kid /master.kid /nonmembers/ /index.kid /garbage.kid /master.kid /shared/ /message.kid /error.kid /errors/ /error1.kid /error2.kid /error3.kid test_templatepath1/ /index.kid /master.kid /members/ /master.kid /stuff.kid """ from os.path import join import py import kid kfind = kid.path.find tmpdir0 = None tmpdir1 = None files = {} def setup_module(m): """Create a testing directory structure.""" global files, tmpdir0, tmpdir1 def _create(dir, files): """Create files.""" for file in files: dir.join(file).write("nothing") # create the directory structure tmpdir0 = py.test.ensuretemp("test_templatepath0") _create(tmpdir0, ["index.kid"]) members = tmpdir0.mkdir("members") _create(members, ["index.kid", "stuff.kid", "master.kid"]) nonmembers = tmpdir0.mkdir("nonmembers") _create(nonmembers, ["index.kid", "garbage.kid", "master.kid"]) shared = tmpdir0.mkdir("shared") _create(shared, ["message.kid", "error.kid"]) errors = shared.mkdir("errors") _create(errors, ["error1.kid", "error2.kid", "error3.kid"]) tmpdir1 = py.test.ensuretemp("test_templatepath1") _create(tmpdir1, ["index.kid", "indexz.kid", "master.kid"]) members = tmpdir1.mkdir("members") _create(members, ["stuff.kid", "master.kid"]) tmpdir0 = str(tmpdir0) kid.path.append(tmpdir0) tmpdir1 = str(tmpdir1) kid.path.append(tmpdir1) def test_simple_file_in_root(): assert kfind("index.kid") == join(tmpdir0, "index.kid") assert kfind("indexz.kid") == join(tmpdir1, "indexz.kid") def test_file_in_directory(): assert kfind("members/index.kid") == join(tmpdir0, "members/index.kid") path = "shared/errors/error1.kid" assert kfind(path) == join(tmpdir0, path) def test_no_exist(): assert kfind("noexist.kid") == None def test_find_relative(): rel = join(tmpdir0, "shared/error.kid") expected = join(tmpdir0, "shared/message.kid") assert kfind("message.kid", rel=rel) == expected def test_crawl_path(): rel = join(tmpdir0, "nonmembers/stuff.kid") expected = join(tmpdir1, "master.kid") assert kfind("master.kid", rel=rel) == expected def test_mod_python_bug(): """This recreates the problem reported in tickit #110.""" tmpdir = py.test.ensuretemp("test_templatepath") tmpdir.join("test.kid").write("nothing") tmpdir.join("base.kid").write("nothing") assert kfind("base.kid", rel=join(str(tmpdir), "test.kid")) \ == join(str(tmpdir), "base.kid") PKY´Ð4¬Ž?îîkid/test/test_suffixes.pyc;ò ¹-“Dc@s®dZdZdZdZdkZdkZdkZdkZdkZei i dƒZ e e ƒgei e_ e idƒZeieiidƒƒd„Zd „ZdS( s/Unit Tests for the import suffix functionality.s $Rev: 219 $s"David Stanek sCopyright 2005, David StanekNs test_suffixesstest_suffixes0.kidsd

my content

cCs7tiƒdk}tiitdƒtiiƒdS(s$By default *.kid files are imported.Nsimport test_suffixes1( skids enable_importstest_suffixes0spystestsraisess ImportErrorsimporters uninstall(stest_suffixes0((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pystest_enable_import_emptys   cCs©tidddgƒdk}tidƒ}ti|ƒdk}tidƒ}ti|ƒdk }tidƒ}ti|ƒt i i t dƒtiiƒdS( s4Using suffixes any file extension can be importable.ssuffixess.htmls .kid.htmlNstest_suffixes1.htmlstest_suffixes2.kid.htmlstest_suffixes3.xhtmlsimport test_suffixes3(skids enable_importstest_suffixes0stmpdirsjoinsdeststfilescopystest_suffixes1stest_suffixes2spystestsraisess ImportErrorsimporters uninstall(stest_suffixes1sdeststest_suffixes0stest_suffixes2((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pys test_enable_import_with_suffixes s      (s__doc__s __revision__s __author__s __copyright__ssyssihooksspyskids kid.importerstests ensuretempstmpdirsstrspathsjoinstfileswritescodesSourcestest_enable_import_emptys test_enable_import_with_suffixes( s test_enable_import_with_suffixess __copyright__s __revision__stfilespys __author__ssyssihooksstest_enable_import_emptystmpdirskid((s4build/bdist.linux-i686/egg/kid/test/test_suffixes.pys?s      PK ²Ð4cmÃx x kid/test/test_layout.py"""Unit Tests for layout templates.""" __revision__ = "$Rev: 257 $" __author__ = "Daniel Miller " __copyright__ = "Copyright 2006, David Stanek" import os import kid def test_dynamic_layout(): layout = kid.Template(source=""" ${body_content()} """) child = kid.Template(source=""" body content """, dynamic_layout=type(layout)) output = child.serialize() assert output.find("body content") > -1, "body_content function was not executed" def test_match_locals(): layout = kid.Template(source="""
""") child = kid.Template(source=""" test_var=${test_var} """, layout=type(layout), test_var="test value") output = child.serialize() assert output.find("test_var=test value") > -1, "match template was not executed" def test_def_locals(): layout = kid.Template(source=""" ${child_content()} """) child = kid.Template(source=""" test_var=${test_var} """, layout=type(layout), test_var="test value") output = child.serialize() assert output.find("test_var=test value") > -1, "child_content function was not executed" PKY´Ð4ôB8T——kid/test/__init__.pyc;ò ¹-“Dc@sdZdZdZdZdZdZdkZdkZdkl Z l Z l Z l Z e e e e ƒƒƒdZed ZeZd ZgiZeied ƒD]Zee eƒd ƒq¢[Zd Zd Zd„ZdklZdddddgZedjo eƒndS(sKid test package.s $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sdirnamesbasenamesjoinsabspaths/../../steststest.skid/test/test*.pyiýÿÿÿicCsFdkl}gi}tD]}|d|ƒq~}||ƒdS(N(s run_testss kid.test.%s(s kid.test.utils run_testssappends_[1]s test_modulessmstests(s_[1]smstestss run_tests((s/build/bdist.linux-i686/egg/kid/test/__init__.pys run_testss +(sdotsdots run_testsstemplate_packages output_dirs template_dirs__main__(s__doc__s __revision__s__date__s __author__s __copyright__s __license__sossglobsos.pathsdirnamesbasenamesjoinsabspaths__file__s_mydirs template_dirs output_dirstemplate_packagesappends_[1]sfs test_modulessadditional_testss basic_testss run_testss kid.test.utilsdots__all__s__name__(stemplate_packagesbasenames run_testssadditional_testssdirnames__date__s __revision__s__all__s_mydirs output_dirsglobs __license__s basic_testssabspaths __author__s __copyright__sjoins template_dirsfs_[1]s test_modulessossdot((s/build/bdist.linux-i686/egg/kid/test/__init__.pys?s(   >   PKY´Ð49Ο”ˆˆkid/test/test_comment.pyc;ò ¹-“Dc@s\dZdZdZdZdkZdkZdklZlZd„Z d„Z d„Z dS( s Unit Tests for the XML comments.s $Rev: 340 $s"David Stanek sCopyright 2005, David StanekN(sserialize_doctypesdoctypescCsdk}|iidƒ}tiiidt|ƒƒ|i dƒ}|i dƒ|i dƒ}|i dƒti ddƒ}|iƒdS( s¨Test for the bug that was reported in ticket #66. I wanted to make two tests one using the KID_NOCET variable and one without. # XXX: get that to work Ns test_commentsis layout.kids* parent

... content will be inserted here ...

spage.kidsÍ

my content

sfile(spystests ensuretempstmpdirskidspathspathssinsertsstrsjoinstfile0swritestfile1sTemplatests serialize(spyststfile0stfile1stmpdir((s3build/bdist.linux-i686/egg/kid/test/test_comment.pysXtest_comments_in_extend s   cCstidƒ}|iddƒttdƒdjpt‚|iddƒttdƒdjpt‚|iddƒdjpt‚tid ƒ}|iddƒttdƒdjpt‚|iddƒttdƒdjpt‚|iddƒdjpt‚d S( s?Comments that start with an '!' character should not be output.ssoutputshtmls sxhtmls sxmls/ sN(skidsTemplatests serializesserialize_doctypesdoctypessAssertionError(st((s3build/bdist.linux-i686/egg/kid/test/test_comment.pystest_comment_removal,s.. ..cCsIxBddfD]4}x+dD]#}d||f}|djod||f}n|djo d}n|}d|}ti|d d ƒ}x­d d d fD]œ}|d jod|}n)|d jp|od|}nd}|d jod|}nt t |ƒd|}|i d|ƒ|jpt ‚qWqWq WdS(sKComments starting with an '<' or '[' character should be interpolated. ss s!?->]<[ss<[ss!s%ssbeforesaftershtmlsxhtmlsxmls%sss' s soutputN(sbscsbefore_comments after_commentsbeforeskidsTemplatestsoutputsaftersserialize_doctypesdoctypess serializesAssertionError(scsbsaftersbefore_comments after_commentstsoutputsbefore((s3build/bdist.linux-i686/egg/kid/test/test_comment.pystest_comment_interpolation>s0       ( s__doc__s __revision__s __author__s __copyright__sosskidskid.serializationsserialize_doctypesdoctypessXtest_comments_in_extendstest_comment_removalstest_comment_interpolation( s __copyright__s __revision__sdoctypessXtest_comments_in_extendsserialize_doctypes __author__stest_comment_removalsosstest_comment_interpolationskid((s3build/bdist.linux-i686/egg/kid/test/test_comment.pys?s   ! PK ²Ð4gFÝÝkid/test/util.py"""Utility stuff for tests..""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys import os import traceback import kid.test try: from cStringIO import StringIO except ImportError: from StringIO import StringIO class stdold: """Original sys.stderr and sys.stdout.""" out = sys.stdout err = sys.stderr def dot(): stdold.err.write('.') def skip(): stdold.err.write('s') def come_on_guido_this_is_just_wrong(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def test_funcs(mod): """Return a list of test functions for the given module object.""" funcs = [] for name in dir(mod): if name[:4] == 'test': attr = getattr(mod, name) if callable(attr): funcs.append(attr) return funcs def run_tests(tests, stop_first=1): """Run tests given a list of modules that export __test__ variables.""" try: os.mkdir(kid.test.output_dir) except OSError: e = sys.exc_info()[1] if int(e.errno) != 17: raise bad = [] kid.test.basic_tests = 1 test_cnt = 0 from time import time start = time() # run over modules.. for module_name in tests: try: mod = come_on_guido_this_is_just_wrong(module_name) except ImportError, e: if 'No module named py' not in str(e): raise skip() continue # you don't have pylib - so i won't run these tests #if not hasattr(mod, '__tests__'): # raise '%r does not export a __tests__ variable.' % module_name if hasattr(mod, 'setup_module'): mod.setup_module(mod) # run each test... for test in test_funcs(mod): test_cnt += 1 sys.stdout, sys.stderr = StringIO(), StringIO() try: test() except: asserr = isinstance(sys.exc_info()[0], AssertionError) ftype = asserr and 'F' or 'E' buf = StringIO() traceback.print_exc(file=buf) stdold.err.write(ftype) bad.append( (test, ftype, sys.exc_info(), \ (sys.stdout.getvalue(), sys.stderr.getvalue()))) if stop_first: sys.stdout, sys.stderr = (stdold.out, stdold.err) sys.stderr.write(' *(bailing after %d tests)*\n' \ % test_cnt) o, e = bad[-1][3][0], bad[-1][3][1] if o: sys.stderr.write('-- sys.stdout:\n%s\n' % o) if e: sys.stderr.write('-- sys.stderr:\n%s\n' % e) raise else: dot() sys.stdout, sys.stderr = stdold.out, stdold.err if hasattr(mod, 'teardown_module'): mod.teardown_module(mod) done = time() for test, ftype, exc_info, (o, e) in bad: sys.stderr.write('%s: %s\n' % ({'F':'Failure','E':'Error'}[ftype], test.__doc__)) traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], 15, sys.stderr) if o: sys.stderr.write('-- sys.stdout:\n %s\n' % o) if e: sys.stderr.write('-- sys.stderr:\n %s\n' % e) sys.stderr.write('=========================\n') sys.stderr.write('\n%d Tests (+%d extended) OK (%f seconds)\n' % (test_cnt, kid.test.additional_tests, done - start)) PKY´Ð4þ·ÆXXkid/test/test_templatepath.pyc;ò ¹-“Dc@s†dZdklZdkZdkZeiiZea ea ha d„Z d„Z d„Zd„Zd„Zd„Zd „ZdS( sà Unit tests for the kid.TemplatePath class. The testing directory structure looks something like this: :: test_templatepath0/ /index.kid /members/ /index.kid /stuff.kid /master.kid /nonmembers/ /index.kid /garbage.kid /master.kid /shared/ /message.kid /error.kid /errors/ /error1.kid /error2.kid /error3.kid test_templatepath1/ /index.kid /master.kid /members/ /master.kid /stuff.kid (sjoinNcCsBd„}tiidƒa|tdgƒtidƒ}||dddgƒtidƒ}||dddgƒtid ƒ}||d d gƒ|id ƒ}||d ddgƒtiidƒa |t dddgƒt idƒ}||ddgƒt tƒat i itƒt t ƒa t i it ƒdS(s%Create a testing directory structure.cCs+x$|D]}|i|ƒidƒqWdS(s Create files.snothingN(sfilessfilesdirsjoinswrite(sdirsfilessfile((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys_create.sstest_templatepath0s index.kidsmemberss stuff.kids master.kids nonmemberss garbage.kidsshareds message.kids error.kidserrorss error1.kids error2.kids error3.kidstest_templatepath1s indexz.kidN(s_createspystests ensuretempstmpdir0smkdirsmemberss nonmembersssharedserrorsstmpdir1sstrskidspathsappend(sms_createserrorss nonmemberssmemberssshared((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys setup_module*s*   cCsJtdƒttdƒjpt‚tdƒttdƒjpt‚dS(Ns index.kids indexz.kid(skfindsjoinstmpdir0sAssertionErrorstmpdir1(((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_simple_file_in_rootNs#cCsPtdƒttdƒjpt‚d}t|ƒtt|ƒjpt‚dS(Nsmembers/index.kidsshared/errors/error1.kid(skfindsjoinstmpdir0sAssertionErrorspath(spath((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_file_in_directoryRs#cCstdƒtjpt‚dS(Ns noexist.kid(skfindsNonesAssertionError(((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys test_no_existXscCsBttdƒ}ttdƒ}tdd|ƒ|jpt‚dS(Nsshared/error.kidsshared/message.kids message.kidsrel(sjoinstmpdir0srelsexpectedskfindsAssertionError(sexpectedsrel((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_find_relative[scCsBttdƒ}ttdƒ}tdd|ƒ|jpt‚dS(Nsnonmembers/stuff.kids master.kidsrel(sjoinstmpdir0srelstmpdir1sexpectedskfindsAssertionError(srelsexpected((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_crawl_path`scCs€tiidƒ}|idƒidƒ|idƒidƒtddtt|ƒdƒƒtt|ƒdƒjpt‚dS(s3This recreates the problem reported in tickit #110.stest_templatepathstest.kidsnothingsbase.kidsrelN( spystests ensuretempstmpdirsjoinswriteskfindsstrsAssertionError(stmpdir((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pystest_mod_python_buges (s__doc__sos.pathsjoinspyskidspathsfindskfindsNonestmpdir0stmpdir1sfiless setup_modulestest_simple_file_in_rootstest_file_in_directorys test_no_existstest_find_relativestest_crawl_pathstest_mod_python_bug( stest_find_relativesjoins test_no_exists setup_modulespystest_mod_python_bugskfindstest_crawl_pathstest_simple_file_in_rootskidstest_file_in_directory((s8build/bdist.linux-i686/egg/kid/test/test_templatepath.pys?s     $     PKY´Ð4ñ Ä55kid/test/test_compiler.pyc;ò ¹-“Dc@s³dZdZdZdZdZdZdkZdkZdkl Z l Z l Z dk Z dk Z dkZ e iiiZd„Zd „Zd „Zd „Zd „Zd „ZdS(skid package tests.s $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sjoinsdirnamesexistscCstiii|ƒdS(N(skidsteststest_kids setup_modulesmodule(smodule((s4build/bdist.linux-i686/egg/kid/test/test_compiler.pys setup_modulescCstiii|ƒdS(N(skidsteststest_kidsteardown_modulesmodule(smodule((s4build/bdist.linux-i686/egg/kid/test/test_compiler.pysteardown_modulescCs`t|dƒpt‚t|dƒpt‚t|dƒpt‚t|dƒpt‚dS(Nspullsgenerateswrites serialize(shasattrstsAssertionError(st((s4build/bdist.linux-i686/egg/kid/test/test_compiler.pysassert_template_interfacescCs>tiƒdk}t|iƒtiidƒpt ‚dS(Ns test.test_if( skids enable_imports test.test_ifstestsassert_template_interfacestest_ifssyssmodulesshas_keysAssertionError(stest((s4build/bdist.linux-i686/egg/kid/test/test_compiler.pystest_import_hooks   cCsydkl}tiƒtt|dƒƒ pt‚dk}tt|dƒƒpt‚t i i dƒpt‚dS(N(s template_dirstest_content.pycstest.test_content( skid.tests template_dirskids enable_importsexistssjoinsAssertionErrorstest.test_contentstestssyssmodulesshas_key(s template_dirstest((s4build/bdist.linux-i686/egg/kid/test/test_compiler.pystest_pyc_generation$s    cCsŽdkl}l}tiƒdki}|i}t |dƒ}|ddddƒ}|i ƒ}x|D]}qiW|i|ƒt|ƒdS(N(s template_dirs output_dirs context.outsfooi sbarsbla bla(skid.tests template_dirs output_dirskids enable_imports test.contextscontextscsTemplatesCsjoinsoutstspullsitseswritescheck_test_file(sCs template_dirscsts output_dirsitsesout((s4build/bdist.linux-i686/egg/kid/test/test_compiler.pystest_import_and_expand.s     (s__doc__s __revision__s__date__s __author__s __copyright__s __license__sosssyssos.pathsjoinsdirnamesexistsskids kid.compilerskid.test.test_kidsteststest_kidscheck_test_files setup_modulesteardown_modulesassert_template_interfacestest_import_hookstest_pyc_generationstest_import_and_expand(ssyss __copyright__s __revision__sjoinsexistss __license__scheck_test_filesteardown_modules setup_modulestest_import_and_expandstest_import_hooks __author__s__date__stest_pyc_generationsdirnamesossassert_template_interfaceskid((s4build/bdist.linux-i686/egg/kid/test/test_compiler.pys?s$          PK ²Ð4À÷\H©©kid/test/__init__.py"""Kid test package.""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import glob from os.path import dirname, basename, join, abspath _mydir = abspath(join(dirname(__file__))) + '/../../' template_dir = _mydir + 'test' output_dir = template_dir template_package = 'test.' test_modules = [basename(f)[:-3] for f in glob.glob(_mydir + 'kid/test/test*.py')] additional_tests = 0 basic_tests = 0 def run_tests(): from kid.test.util import run_tests tests = ['kid.test.%s' % m for m in test_modules] run_tests(tests) from kid.test.util import dot __all__ = ['dot', 'run_tests', 'template_package', 'output_dir', 'template_dir'] if __name__ == '__main__': run_tests() PK ²Ð4ežoÐ Ð kid/test/test_comment.py"""Unit Tests for the XML comments.""" __revision__ = "$Rev: 340 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" import os import kid from kid.serialization import serialize_doctype, doctypes def Xtest_comments_in_extend(): """Test for the bug that was reported in ticket #66. I wanted to make two tests one using the KID_NOCET variable and one without. # XXX: get that to work """ import py tmpdir = py.test.ensuretemp("test_comments") kid.path.paths.insert(0, str(tmpdir)) tfile0 = tmpdir.join("layout.kid") tfile0.write(""" parent

... content will be inserted here ...

""") tfile1 = tmpdir.join("page.kid") tfile1.write("""

my content

""") t = kid.Template(file="page.kid") t.serialize() def test_comment_removal(): """Comments that start with an '!' character should not be output.""" t = kid.Template('') assert t.serialize(output='html') == \ serialize_doctype(doctypes['html']) + '\n' assert t.serialize(output='xhtml') == \ serialize_doctype(doctypes['xhtml']) + '\n' assert t.serialize(output='xml') == \ '\n' t = kid.Template('') assert t.serialize(output='html') == \ serialize_doctype(doctypes['html']) + '\n' assert t.serialize(output='xhtml') == \ serialize_doctype(doctypes['xhtml']) + '\n' assert t.serialize(output='xml') == \ '\n' def test_comment_interpolation(): """Comments starting with an '<' or '[' character should be interpolated. """ for b in ('', ' '): for c in '!?->]<[': before_comment = '' % (b, c) if c in '<[': after_comment = '' % (b, c) elif c == '!': after_comment = '' else: after_comment = before_comment before= '%s' % before_comment t = kid.Template(before, before='after') for output in ('html', 'xhtml', 'xml'): if output == 'html': after = '%s' % after_comment elif output == 'xhtml' or after_comment: after = '%s' % after_comment else: after = '' if output == 'xml': after = '\n' + after else: after = serialize_doctype(doctypes[output]) + '\n' + after assert t.serialize(output=output) == after PK ²Ð4”²¥²kid/test/test_pull.py"""kid.pull tests""" __revision__ = "$Rev: 59 $" __date__ = "$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from kid.et import * from kid.pull import * def test_expand(): doc = XML("world", fragment=0) doc = doc.expand() assert doc.tag == 'doc' assert doc[0].tag == 'hello' assert doc[0].text == 'world' PKY´Ð4=%‰ßŽŽkid/test/test_layout.pyc;ò ¹-“Dc@sIdZdZdZdZdkZdkZd„Zd„Zd„ZdS(s Unit Tests for layout templates.s $Rev: 257 $s#Daniel Miller sCopyright 2006, David StanekNcCs`tiddƒ}tidddt|ƒƒ}|iƒ}|idƒdjp td‚dS(Nssourcesg ${body_content()} s¢ body content sdynamic_layouts body contentiÿÿÿÿs&body_content function was not executed( skidsTemplateslayoutstypeschilds serializesoutputsfindsAssertionError(soutputschildslayout((s2build/bdist.linux-i686/egg/kid/test/test_layout.pystest_dynamic_layout s   cCsftiddƒ}tidddt|ƒddƒ}|iƒ}|idƒdjp td ‚dS( Nssources–
s test_var=${test_var} slayoutstest_vars test valuestest_var=test valueiÿÿÿÿsmatch template was not executed( skidsTemplateslayoutstypeschilds serializesoutputsfindsAssertionError(soutputschildslayout((s2build/bdist.linux-i686/egg/kid/test/test_layout.pystest_match_localss   cCsftiddƒ}tidddt|ƒddƒ}|iƒ}|idƒdjp td ‚dS( Nssources¡ ${child_content()} s test_var=${test_var} slayoutstest_vars test valuestest_var=test valueiÿÿÿÿs'child_content function was not executed( skidsTemplateslayoutstypeschilds serializesoutputsfindsAssertionError(soutputschildslayout((s2build/bdist.linux-i686/egg/kid/test/test_layout.pystest_def_locals8s   ( s__doc__s __revision__s __author__s __copyright__sosskidstest_dynamic_layoutstest_match_localsstest_def_locals(s __copyright__s __revision__stest_dynamic_layoutstest_match_localss __author__stest_def_localssosskid((s2build/bdist.linux-i686/egg/kid/test/test_layout.pys?s    PKY´Ð4³e^±ggkid/test/util.pyc;ò ¹-“Dc@sÃdZdZdZdZdZdZdkZdkZdkZdk Z ydk l Z Wn e j odk l Z nXdfd „ƒYZd „Zd „Zd „Zd „Zdd„ZdS(sUtility stuff for tests..s $Rev: 59 $s5$Date: 2005-02-16 15:43:38 -0500 (Wed, 16 Feb 2005) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sStringIOsstdoldcBs tZdZeiZeiZRS(s#Original sys.stderr and sys.stdout.(s__name__s __module__s__doc__ssyssstdoutsoutsstderrserr(((s+build/bdist.linux-i686/egg/kid/test/util.pysstdolds  cCstiidƒdS(Ns.(sstdoldserrswrite(((s+build/bdist.linux-i686/egg/kid/test/util.pysdotscCstiidƒdS(Nss(sstdoldserrswrite(((s+build/bdist.linux-i686/egg/kid/test/util.pysskipscCsGt|ƒ}|idƒ}x!|dD]}t||ƒ}q&W|SdS(Ns.i(s __import__snamesmodssplits componentsscompsgetattr(snames componentsscompsmod((s+build/bdist.linux-i686/egg/kid/test/util.pys come_on_guido_this_is_just_wrongs   cCsgg}xVt|ƒD]H}|d djo1t||ƒ}t|ƒo|i|ƒq[qqW|SdS(s<Return a list of test functions for the given module object.istestN(sfuncssdirsmodsnamesgetattrsattrscallablesappend(smodsfuncssattrsname((s+build/bdist.linux-i686/egg/kid/test/util.pys test_funcs%s  icCsÕytitiiƒWn@tj o4tiƒd} t | i ƒdjo‚qZnXg} dti_ d}dkl}|ƒ}xJ|D]B}yt|ƒ} Wn9tj o-} dt| ƒjo‚ntƒqnXt| dƒo| i| ƒnxt| ƒD]}|d7}tƒtƒf\t_t_y |ƒWn<ttiƒdtƒ}|odpd}tƒ} t"i#d | ƒt$i%i&|ƒ| i'||tiƒtii(ƒtii(ƒffƒ|o¡t$i*t$i%f\t_t_tii&d |ƒ| d d d| d d df\} } | otii&d | ƒn| otii&d| ƒn‚qŽqXt,ƒqWt$i*t$i%f\t_t_t| dƒo| i-| ƒqqW|ƒ}xÉ| D]Á\}}}\} } tii&dhdd<dd<||i/fƒt"i0|d|d|ddtiƒ| otii&d| ƒn| otii&d| ƒntii&dƒqåWtii&d|tii1||fƒdS(sARun tests given a list of modules that export __test__ variables.iii(stimesNo module named pys setup_modulesFsEsfiles *(bailing after %d tests)* iÿÿÿÿis-- sys.stdout: %s s-- sys.stderr: %s steardown_modules%s: %s sFailuresErroriis-- sys.stdout: %s s-- sys.stderr: %s s========================= s) %d Tests (+%d extended) OK (%f seconds) N(2sossmkdirskidstests output_dirsOSErrorssyssexc_infosesintserrnosbads basic_testsstest_cntstimesstartstestss module_names come_on_guido_this_is_just_wrongsmods ImportErrorsstrsskipshasattrs setup_modules test_funcssStringIOsstdoutsstderrs isinstancesAssertionErrorsasserrsftypesbufs tracebacks print_excsstdoldserrswritesappendsgetvalues stop_firstsoutsosdotsteardown_modulesdones__doc__sprint_exceptionsadditional_tests(stestss stop_firstsdonestest_cntsstartsftypestestsasserrsexc_infosbufsmodsesosbadstimes module_name((s+build/bdist.linux-i686/egg/kid/test/util.pys run_tests/sz        7*   3 (s__doc__s __revision__s__date__s __author__s __copyright__s __license__ssyssoss tracebackskid.testskids cStringIOsStringIOs ImportErrorsstdoldsdotsskips come_on_guido_this_is_just_wrongs test_funcss run_tests(s come_on_guido_this_is_just_wrongssyss __copyright__s __revision__s __license__sStringIOsskips tracebacks run_testss test_funcss __author__s__date__sstdoldsossdotskid((s+build/bdist.linux-i686/egg/kid/test/util.pys?s&        PKY´Ð4ÝwÈ>>EGG-INFO/entry_points.txt[console_scripts] kidc = kid.compile:main kid = kid.run:main PKY´Ð4‡8GÌÌEGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: kid Version: 0.9.2 Summary: A simple and pythonic XML template language Home-page: http://kid.lesscode.org/ Author: Ryan Tomayko Author-email: rtomayko@gmail.com License: MIT Download-URL: http://kid.lesscode.org/dist/0.9.2/kid-0.9.2.tar.gz Description: Kid is a simple, Python-based template language for generating and transforming XML vocabularies. Kid was spawned as a result of a kinky love triangle between XSLT, TAL, and PHP. We believe many of the best features of these languages live on in Kid with much of the limitations and complexity stamped out (well, eventually :). Keywords: xml template html web Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Environment :: Console Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Text Processing :: Markup :: XML PKY´Ð4¿˜È^ŠŠEGG-INFO/SOURCES.txtCOPYING ChangeLog HISTORY MANIFEST.in README RELEASING ez_setup.py makefile setup.cfg setup.py test_kid.py work.sh bin/kid bin/kidc doc/custom.css doc/default.css doc/guide.txt doc/index.txt doc/language.txt doc/makefile doc/notes.txt examples/basic/README examples/basic/self.kid examples/basic/sysinfo.kid examples/basic/tutorial.kid examples/basic/tutorial2.kid examples/cgi/README examples/cgi/kid_handler.cgi examples/cgi/sysinfo.kid kid/__init__.py kid/compile.py kid/compiler.py kid/et.py kid/filter.py kid/importer.py kid/namespace.py kid/parser.py kid/properties.py kid/pull.py kid/release.py kid/run.py kid/serialization.py kid/server.py kid/template_util.py kid/util.py kid.egg-info/PKG-INFO kid.egg-info/SOURCES.txt kid.egg-info/entry_points.txt kid.egg-info/requires.txt kid.egg-info/top_level.txt kid/test/__init__.py kid/test/test_comment.py kid/test/test_compiler.py kid/test/test_kid.py kid/test/test_kid_lang.py kid/test/test_layout.py kid/test/test_match.py kid/test/test_namespace.py kid/test/test_parser.py kid/test/test_properties.py kid/test/test_pull.py kid/test/test_scope.py kid/test/test_serialization.py kid/test/test_suffixes.py kid/test/test_templatepath.py kid/test/test_unicode.py kid/test/util.py misc/upgrade-0.6.py test/__init__.py test/basic-test.html.kid test/blocks.py test/context.kid test/include-me.xml test/layout.kid test/serialization.kid test/template-test.html.kid test/templates.kid test/test_attribute_interpolation.kid test/test_attrs.kid test/test_backward.kid test/test_comment_pi.kid test/test_content.kid test/test_content_interpolation.kid test/test_content_structure.kid test/test_def.kid test/test_encoding.kid test/test_entities.kid test/test_extends.kid test/test_if.kid test/test_kid_pi.kid test/test_layout_page.kid test/test_match.kid test/test_match_parent.kid test/test_namespaces.kid test/test_omit.kid test/test_repeat.kid test/test_replace.kid test/test_strip.kid PKY´Ð4 !kEGG-INFO/top_level.txtkid PKZ´Ð4EGG-INFO/not-zip-safePKY´Ð4NÔ­ EGG-INFO/requires.txtelementtreePK ²Ð4³ú’–Ö=Ö= ¤kid/pull.pyPK ²Ð4¹[Ü&K&K ¤ÿ=kid/parser.pyPK ²Ð4™‰õŽkk¤P‰kid/release.pyPKY´Ð4§ØRÅRÅR¤ç‹kid/parser.pycPK ²Ð4IbÚÅí í ¤ØÞkid/et.pyPKY´Ð41rôA*L*L ¤ìêkid/pull.pycPKY´Ð4ÚN|Ïñ ñ ¤@7kid/compile.pycPK ²Ð4@@–~~¤^Dkid/compiler.pyPK ²Ð4+}`ù¹ ¹ ¤ ]kid/filter.pyPK ²Ð4 ·1¯t"t" ¤ífkid/server.pyPKY´Ð4jëýʤŒ‰kid/template_util.pycPK ²Ð40>ý· · ¤Î¦kid/compile.pyPKZ´Ð4œØPÅÅ ¤±±kid/run.pycPKY´Ð4,Îù°AA¤ŸÂkid/release.pycPKY´Ð4sÇ5« « ¤ Ækid/compiler.pycPKZ´Ð4Q ’¥--¤æækid/importer.pycPKZ´Ð4{ÃZ:ÃSÃS¤Akid/serialization.pycPKY´Ð4áœÁ¹ß ß ¤7Xkid/et.pycPK ²Ð4€üE __¤>dkid/namespace.pyPKY´Ð4‡}ˆ33¤Ëikid/filter.pycPK ²Ð4¤ @þþ¤*xkid/template_util.pyPKY´Ð4«ò}²'²'¤Zkid/server.pycPKZ´Ð4˜%8MJMJ¤8·kid/__init__.pycPK ²Ð4­u2´´ ¤³kid/run.pyPK ²Ð4P2¬\\¤kid/importer.pyPK ²Ð4ÂZ ¤#kid/util.pyPKY´Ð4³p´fO O ¤F&kid/namespace.pycPK ²Ð4à_ñyTKTK¤Ä0kid/serialization.pyPK ²Ð4ßR+ÙÙ¤J|kid/properties.pyPK ²Ð4òP¿1•5•5¤R€kid/__init__.pyPKZ´Ð4©”ÿ¿ ¤¶kid/util.pycPKZ´Ð4”¹Ðii¤ý¼kid/properties.pycPKY´Ð4÷«)<5<5¤–Äkid/test/test_kid.pycPK ²Ð4 ¥û¸X X ¤úkid/test/test_parser.pyPK ²Ð4]ôt§¤’kid/test/test_namespace.pyPK ²Ð4=@팉‰¤gkid/test/test_compiler.pyPK ²Ð4á —#hh¤' kid/test/test_unicode.pyPKY´Ð4þޤÅkid/test/test_properties.pycPKY´Ð4Òì&--¤kid/test/test_pull.pycPKY´Ð4ˆm m ¤kid/test/test_parser.pycPKY´Ð4oÉ%ÄĤ")kid/test/test_namespace.pycPK ²Ð4]ã ¤.kid/test/test_properties.pyPKY´Ð4)f>S¤`2kid/test/test_match.pycPK ²Ð4†qk~ë ë ¤£Pkid/test/test_kid_lang.pyPK ²Ð4ÁÈÝ ¤Å\kid/test/test_scope.pyPK ²Ð4>0Qn  ¤ `kid/test/test_suffixes.pyPKY´Ð4à÷6ff¤Qekid/test/test_scope.pycPK ²Ð4™åά¬¤ìjkid/test/test_match.pyPKY´Ð4&sø»~&~&¤Ì„kid/test/test_serialization.pycPKY´Ð4M"i¤‡«kid/test/test_kid_lang.pycPK ²Ð4F”8¤@¿kid/test/test_kid.pyPKY´Ð4a\M66¤yÜkid/test/test_unicode.pycPK ²Ð4Ý‰Ž½Êʤæàkid/test/test_serialization.pyPK ²Ð4ÈúNÅç ç ¤ìøkid/test/test_templatepath.pyPKY´Ð4¬Ž?îî¤kid/test/test_suffixes.pycPK ²Ð4cmÃx x ¤4kid/test/test_layout.pyPKY´Ð4ôB8T——¤ákid/test/__init__.pycPKY´Ð49Ο”ˆˆ¤«#kid/test/test_comment.pycPK ²Ð4gFÝݤj3kid/test/util.pyPKY´Ð4þ·ÆXX¤uBkid/test/test_templatepath.pycPKY´Ð4ñ Ä55¤ Wkid/test/test_compiler.pycPK ²Ð4À÷\H©©¤vekid/test/__init__.pyPK ²Ð4ežoÐ Ð ¤Qikid/test/test_comment.pyPK ²Ð4”²¥²¤Wvkid/test/test_pull.pyPKY´Ð4=%‰ßŽŽ¤¡xkid/test/test_layout.pycPKY´Ð4³e^±gg¤e‰kid/test/util.pycPKY´Ð4ÝwÈ>>¤ûœEGG-INFO/entry_points.txtPKY´Ð4‡8GÌ̤pEGG-INFO/PKG-INFOPKY´Ð4¿˜È^ŠŠ¤k¢EGG-INFO/SOURCES.txtPKY´Ð4 !k¤'ªEGG-INFO/top_level.txtPKZ´Ð4¤_ªEGG-INFO/not-zip-safePKY´Ð4NÔ­ ¤’ªEGG-INFO/requires.txtPKHHwЪ