PK+C8lMJEGG-INFO/SOURCES.txtCOPYING ChangeLog HISTORY MANIFEST.in README RELEASING ez_setup.py kid-env.sh makefile run_tests.py setup.cfg setup.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 doc/html/almodovar.css doc/html/class-kid.BaseTemplate.html doc/html/class-kid.HTMLSerializer.html doc/html/class-kid.Namespace.html doc/html/class-kid.Serializer.html doc/html/class-kid.XHTMLSerializer.html doc/html/class-kid.XMLSerializer.html doc/html/class-kid.namespace.Namespace.html doc/html/class-kid.serialization.HTMLSerializer.html doc/html/class-kid.serialization.Serializer.html doc/html/class-kid.serialization.XMLSerializer.html doc/html/class-kid.util.QuickTextReader.html doc/html/gnu.html doc/html/guide.html doc/html/index.html doc/html/language.html doc/html/layout.css doc/html/module-index.html doc/html/module-kid-index.html doc/html/module-kid.filter-index.html doc/html/module-kid.filter.html doc/html/module-kid.html doc/html/module-kid.namespace-index.html doc/html/module-kid.namespace.html doc/html/module-kid.properties-index.html doc/html/module-kid.properties.html doc/html/module-kid.serialization-index.html doc/html/module-kid.serialization.html doc/html/module-kid.util-index.html doc/html/module-kid.util.html doc/html/notes.html doc/html/pudge.css doc/html/rst.css doc/html/kid/__init__.py.html doc/html/kid/compile.py.html doc/html/kid/compiler.py.html doc/html/kid/et.py.html doc/html/kid/filter.py.html doc/html/kid/importer.py.html doc/html/kid/namespace.py.html doc/html/kid/parser.py.html doc/html/kid/properties.py.html doc/html/kid/pull.py.html doc/html/kid/release.py.html doc/html/kid/run.py.html doc/html/kid/serialization.py.html doc/html/kid/server.py.html doc/html/kid/template_util.py.html doc/html/kid/util.py.html doc/html/kid/test/__init__.py.html doc/usr/local/share/doc/py-kid/COPYING doc/usr/local/share/doc/py-kid/HISTORY doc/usr/local/share/doc/py-kid/README doc/usr/local/share/doc/py-kid/upgrade-0.6.py 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/codewriter.py kid/compile.py kid/compiler.py kid/element.py kid/filter.py kid/format.py kid/importer.py kid/namespace.py kid/options.py kid/parser.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/dependency_links.txt kid.egg-info/entry_points.txt kid.egg-info/top_level.txt kid/test/__init__.py kid/test/test_attribute_interpolation.py kid/test/test_codewriter.py kid/test/test_comment.py kid/test/test_compiler.py kid/test/test_element.py kid/test/test_error.py kid/test/test_extended_layout.py kid/test/test_extends.py kid/test/test_format.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_options.py kid/test/test_parser.py kid/test/test_scope.py kid/test/test_serialization.py kid/test/test_serialization_escaping.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 test/test_xml_encoding.kid test/test_xml_func.kid PK+C8w>>EGG-INFO/entry_points.txt[console_scripts] kidc = kid.compile:main kid = kid.run:main PK+C82EGG-INFO/dependency_links.txt PK*C8؋HEGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: kid Version: 0.9.6 Summary: A simple and pythonic XML template language Home-page: http://www.kid-templating.org Author: Ryan Tomayko Author-email: rtomayko@gmail.com License: MIT Download-URL: http://www.kid-templating.org/dist/0.9.6/kid-0.9.6.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 PK*C8 !kEGG-INFO/top_level.txtkid PK4C82EGG-INFO/not-zip-safe PK0C8~G$`"`"kid/importer.pyc; \PFc@sdZdZdZdZdZdZdkZdkZdkZdk l Z l Z l Z dk lZlZlZd klZd klZd klZlZd klZd dddgZeedZedZedZ dZ!e"hedZ#de$fdYZ%dS(sKid Import Hooks. When installed, these hooks allow importing .kid files as if they were Python modules. Notes: We use new import hooks instead of the old ihooks module, because ihooks is incompatible with Python eggs. We allow importing from one or more specified paths for Kid templates, or importing from sys.path. In the latter case, we use an importer on meta_path because importers on path_hook do not fall back to the built-in import in Python >= 2.5 (this worked in Python 2.3 and 2.4). s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $sGRyan Tomayko (rtomayko@gmail.com); Christoph Zwerschke (cito@online.de)s;Copyright 2004-2005, Ryan Tomayko; 2006 Christoph Zwerschkes8MIT N(senvironsextsepspathsep(sexistssjoinsisdir(s __version__(sraise_template_error(sKidFilesKID_EXT(sTemplateImportErrorsinstalls uninstallsimport_templatesget_template_namec Cs|ot|to|id}n t|}x0|D](}|it otd|q=q=Wt |jo|i t qng}|i dt |ot|to|it }n t|}di|}g}ti }xe|D]]}d|}gi}|D]%}|i| o||qq~}|i||qW||t_ |o,ttij otii dtqqnUxQtiD]$}t|to||_PqqWtd|}tii d|dS(sInstall importer for Kid templates. ext can be one or more extensions as list or comma separated string path can be one or more paths as list or pathsep separated string s,sIllegal exception: is kid::%s::sextN(sexts isinstances basestringssplitsextsslists startswithsextseps ExceptionsKID_EXTsremovesinsertspathspathsepspathssjoinskidpathsssysssyspathskidpathsappends_[1]s KidImporters path_hookss meta_pathsimporter( sextspathsimporterspathssextsssyspathskidpathss_[1]skidpath((s0build/bdist.darwin-8.0.1-x86/egg/kid/importer.pysinstall&sH     <    cCs|oLt|to|it}n t|}g}t}xt iD]}|id}t |djo&|ddjo|d o |d o.di |dd!|joqLnt}n|i|qLW|t _|octt ijoOgi}t iD]!}|tjo||q q ~t _t iiqOqnCgi}t iD]%}t|t o||qdqd~t _dS( srUninstall importer for Kid templates. path can be one or more paths as list or pathsep separated string s:iiskidiiiN(spaths isinstances basestringssplitspathsepspathsslistssyspathsTrues remove_hookssysspslensjoinsFalsesappends KidImporters path_hookss_[1]shookspath_importer_cachesclears meta_pathsimporter(spathspathsssyspathspsimporters_[1]s remove_hookshook((s0build/bdist.darwin-8.0.1-x86/egg/kid/importer.pys uninstallVs*  <  >cCsr| o|otii|oti|Snt|}|idt i d}t |||}|SdS(Ns dump_sources KID_OUTPUT_PY(sforcesnamessyssmodulesshas_keysKidFilesfilenamestemplatescompilesenvironsgetscodes_create_modulesmodule(snamesfilenamesforcescodesmodulestemplate((s0build/bdist.darwin-8.0.1-x86/egg/kid/importer.pysimport_templateus " cCs,|o|Sndt|tidSdS(Nskid.util.template_%xi(snameshashsfilenamessyssmaxint(snamesfilename((s0build/bdist.darwin-8.0.1-x86/egg/kid/importer.pysget_template_name}sc BsdxAedD]3}e||}ei|}||_e i |_ |i i |y'|o|||n ||i UWn>ej o2|o|ei|': raise if not encoding: encoding = 'utf-8' py_file = splitext(filename)[0] + '.py' exc_type, exc_value = sys.exc_info()[:2] if exc_type == SyntaxError: tb = [(py_file, exc_value.lineno)] else: tb = extract_tb(sys.exc_info()[2]) tb.reverse() for t in tb: if py_file != t[0] or not t[1]: continue location = error_location(filename, encoding, lineno=t[1]) if not location: continue (start_line, start_col), (end_line, end_col) = location if start_line > end_line: continue s = [] if not end_col and end_line > start_line: end_line -= 1 end_col = -1 if start_line == end_line: s.append('on line %d' % start_line) if start_col == end_col: s.append(', column %d' % start_col) elif start_col: if end_col > start_col: s.append(' between columns %d and %d' % (start_col, end_col)) else: s.append(' after column %d' % start_col) elif end_col > 0: s.append(' before column %d' % end_col) else: s.append('between line %d' % start_line) if start_col: s.append(', column %d' % start_col) s.append(' and line %d' % end_line) if end_col > 0: s.append(', column %d' % end_col) if s: s = ''.join(s) try: start_line -= 1 end_line -= 1 error_line, error_text = [], [] for line, text in enumerate(open(filename)): if line < start_line: continue text = text.rstrip() if text: if line == start_line and start_col: if text[:start_col].rstrip(): text = text[start_col:].lstrip() if text: text = '... ' + text if line == end_line and end_col > 0: if text[end_col:].lstrip(): if end_col > 75: end_col = 75 text = text[:end_col].rstrip() if text: text += ' ...' else: text = text[:end_col].rstrip() if len(text) > 79: text = text[:75].rstrip() + ' ...' if text: if len(error_line) < 3: error_line.append(line) error_text.append(text) else: error_line[2] = line error_text[2] = text if line >= end_line: break if not error_line: raise LookupError, 'error line not found' if len(error_line) == 2: if error_line[1] - error_line[0] > 1: error_text.insert(1, '...') elif len(error_line) == 3: if error_line[2] - error_line[0] > 2: error_text[1] = '...' s = [s + ':'] + error_text except Exception, e: s = [s, '(cannot acquire source text: %s)' % str(e)] s.insert(0, 'Error location in template file %r' % filename) break else: s = ['Error in code generated from template file %r' % filename] s = ''.join(format_exception_only(exc_type, exc_value)[:-1]) + '\n'.join(s) if isinstance(exc_type, str): exc_type += '\n' + s else: exc_value = TemplateExceptionError(exc_value, s) exc_type = exc_value.__class__ raise exc_type, exc_value, sys.exc_info()[2] class KidWriter(object): def __init__(self, stream, encoding=None, filename=None, lineno=None): self.stream = stream self.encoding = encoding or 'utf-8' self.filename = filename self.depth = 0 self.lineno = lineno self.location = None self.locations = [] self.module_code = self.codegen() self.class_code = self.codegen() self.expand_code = self.codegen(level=1) self.end_module_code = self.codegen() self.module_defs = [] self.inst_defs = [] def codegen(self, code=None, level=0, tab='\t'): if self.lineno: return LocationGenerator(code, self.getloc) else: return CodeGenerator(code, level, tab) def getloc(self): return self.location 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 if self.lineno: lineno = self.lineno - 1 if not 0 <= lineno < len(parts): return None pos = parts[lineno] if not pos: return None pos, is_start = pos if not 0 <= pos < len(self.locations): return None start_loc = self.locations[pos] pos += is_start and 1 or -1 if 0 <= pos < len(self.locations): end_loc = self.locations[pos] else: end_line = start_loc[0] if is_start: end_line += 1 end_loc = (end_line, 0) if not is_start: start_loc, end_loc = end_loc, start_loc return start_loc, end_loc return '\n'.join(parts) def begin(self): code = self.module_code # Start with PEP 0263 encoding declaration code.line('# -*- coding: %s -*-' % self.encoding, '# Kid template module', # version against which the file has been compiled 'kid_version = %r' % __version__, # source from which the file has been compiled 'kid_file = %r' % self.filename, # imports 'import kid', 'from kid.template_util import *', 'import kid.template_util as template_util', '_def_names = []', # default variables (can be overridden by template) 'encoding = "%s"' % self.encoding, 'doctype = None', 'omit_namespaces = [kid.KID_XMLNS]', 'layout_params = {}', # module methods 'def pull(**kw): return Template(**kw).pull()', "def generate(encoding=encoding, fragment=False," " output=None, format=None, **kw):" " return Template(**kw).generate(encoding=encoding," " fragment=fragment, output=output, format=format)", "def serialize(encoding=encoding, fragment=False," " output=None, format=None, **kw):" " return Template(**kw).serialize(encoding=encoding," " fragment=fragment, output=output, format=format)", "def write(file, encoding=encoding, fragment=False," " output=None, format=None, **kw):" " return Template(**kw).write(file, encoding=encoding," " fragment=fragment, output=output, format=format)", 'def initialize(template): pass', 'BaseTemplate = kid.BaseTemplate') # expand code code = self.expand_code code.start_block('def initialize(self):') code.line('rslt = initialize(self)', '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())", 'current, ancestors = None, []', '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.strip() if text.startswith('!'): continue # swallow comment if code is self.module_code: line = self.expand_code.line else: line = code.line if text.startswith('[') or text.startswith('', '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 PK1C8+MMNMNkid/parser.pyc; \PFc @sdZdZdZdZdZdZdkZdklZdk l Z l Z l Z d k lZlZlZd d d d dddddddddg ZhZgZxDeiiD]3\ZZeeeeN(sexpat(sElementsCommentsProcessingInstruction(s open_resourcesQuickTextReadersget_expat_errors ElementStreamsXMLsdocumentsParsers ExpatParsersSTARTsENDsTEXTsCOMMENTsPIsXML_DECLsDOCTYPEsLOCATIONss sInvalidStreamStatecBstZddZRS(NsInvalid stream state.cCsti||dS(N(s Exceptions__init__sselfsmsg(sselfsmsg((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys__init__s(s__name__s __module__s__init__(((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysInvalidStreamStatescCs|idp |ido t}n|o|od||f}n d|}t|tod}|i|}nt t |||}t t|d|iSnXt|tod}|i|}nt t |||}t t|d|SdS(s)Convert XML string into an ElementStream.s%ss %ssutf-16sencodingN(stexts startswithsFalsesfragmentsxmlnss isinstancesunicodesencodingsencodesParsersQuickTextReaders entity_mapsps ElementStreams _coalescesstrip(stextsfragmentsencodingsxmlnss entity_mapsp((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysXML#s"    cCst|d o*|tjo |}nt|d}n|tjo d}nt||||}||_ t t |d|SdS(s,Convert XML document into an Element stream.sreadsrbssencodingN( shasattrsfilesfilenamesNones open_resourcesParsersencodings entity_mapsdebugsps _filenames ElementStreams _coalesce(sfilesencodingsfilenames entity_mapsdebugsp((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysdocument:s     cBsqtZdZedZdZdZddZdZe dZ edZ ed Z e e Z RS( sProvides 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|do t|do|i|dt}nt|_|it|||_ dS(sCreate 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. stagsattribstailN( shasattrsstreamsselfs_pullsTruesNonescurrents_tracksiters_iter(sselfsstreamscurrent((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys__init__Ps   cCs |iSdS(N(sselfs_iter(sself((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys__iter__]scCsV|i}|tjo g}n|g}|tf\}}x|iD]\}}|t jo4|tf\}}|di ||i |qE|t jo1|i }||jpt | oPqqE|tjo<|tj o ||_qt|t o ||_qqEqEWt|tot|djo|d}n|SdS(sExpand the current item in the stream as an Element. In the case where there is no current element and no single root element, this will return a list of Elements. iiiN(sselfscurrentsNonesstacksthisslasts_itersevsitemsSTARTsappendsENDspopsAssertionErrorsTEXTstails isinstancesliststextslen(sselfslaststhisscurrentsitemsevsstack((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysexpand`s2            #ics@d}itj odpd}t||SdS(s>Return new ElementStream with first element level(s) stripped.c#sxiD]\}}|tjo:|d8}|djoPq]|djo tq]n|jo||fVn|tjo|d7}q q WdS(Nii( sselfs_itersevsitemsENDsdepthsInvalidStreamStateslevelssSTART(sdepthsitemsev(sselfslevels(s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysstrips       iiN(sstripsselfscurrentsNonesdepths ElementStream(sselfslevelssdepthsstrip((sselfslevelss.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysstrips 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.darwin-8.0.1-x86/egg/kid/parser.pyseats      ccs|}t|it|i}|ittfjo|i|_t |_nt |fV|iot |ifVnx8|i D]*}x!|i|dtD] }|VqWqWt|fV|o|iot |ifVndS(sMake a stream from an Element.stailN(selemsorigsElementstagsdictsattribsCommentsProcessingInstructionstextsNonesSTARTsTEXTs getchildrenschildsselfs_pullsTrueseventsENDstail(sselfselemstailschildseventsorig((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_pulls"       ccs|tj o||_t|fVnxX|D]P}|\}}|tjo ||_n|tjo t|_n||fVq+WdS(sTrack current item in stream.N( scurrentsNonesselfsSTARTsstreamspsevsitemsEND(sselfsstreamscurrentspsitemsev((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_tracks       cCs)t||o|Sn|||SdS(s&Ensure the stream is an ElementStream.N(s isinstancesstreamsclsscurrent(sclssstreamscurrent((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysensures(s__name__s __module__s__doc__sNones__init__s__iter__sexpandsstripseatsFalses_pulls_tracksensures classmethod(((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys ElementStreamHs      cCsht|to|Snt|dot|Snt|t ot|}nt||SdS(Ns __unicode__(s isinstancesvaluesunicodeshasattrsstrsencoding(svaluesencoding((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys to_unicodesccsg}g}t} tg} xl|D]d\} }| tjo|i |t} q"n| tjoId} x!|D]}| t ||7} qoWg}| ot| fVqn| tjo`|i} x7|D]/\}}|o|| d|srbs}(9shasattrssourcesfilenamesopensselfs _filenames_sourcesencodings _encodingsexpats ParserCreates_parsersparsers_queuesCurrentLineNumbersAttributeErrorsFalsesdebugs_push_locationspushs_pushs_defaultsDefaultHandlers_startsStartElementHandlers_endsEndElementHandlers_datasCharacterDataHandlers_pisProcessingInstructionHandlers_commentsCommentHandlers _start_nssStartNamespaceDeclHandlers_end_nssEndNamespaceDeclHandlers_xmldecl_handlersXmlDeclHandlers_doctype_handlersStartDoctypeDeclHandlersTrues buffer_textsordered_attributessspecified_attributessNones_doctypes entity_mapsentitysdefault_entity_mapsdefault_external_dtds external_dtdsSetParamEntityParsingsXML_PARAM_ENTITY_PARSING_ALWAYSs _buildForeignsExternalEntityRefHandlers UseForeignDTD(sselfssourcesencodings entity_mapsdebugsparsersfilename((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys__init__#sL                          cCsWdk}|it}|i}|ii||_|ii|||_t SdS(N( sStringIOsdefault_external_dtds parseableFilesselfs_parsersoriginal_parsersExternalEntityParserCreatescontexts ParseFilesTrue(sselfscontextsbasessystemIdspublicIdsoriginal_parsersStringIOs parseableFile((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys _buildForeignWs   cCs|ii||fdS(N(sselfs_queuesappendsevsstuff(sselfsevsstuff((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_push`scCs6|it|ii|iif|i||dS(N(sselfs_pushsLOCATIONs_parsersCurrentLineNumbersCurrentColumnNumbersevsstuff(sselfsevsstuff((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_push_locationcs"ccsdd}|i}|ii}t}x~|ovxN|o|i o;||}|djo|i t }q2||q2Wx|iD] }|VqWg|_q(WdS(Niis( sbufsizesselfsfeeds_sourcesreadsTruesmores_queuesdatasclosesFalsesitem(sselfsfeedsreadsdatasitemsbufsizesmore((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys _expat_streamhs"        c #shd}g}t}x|iD]\}} |t jot | fVq+|t jo| \}} ||}t gi} | iD]"\}} | ||| fq~ } |}t|| }|i|t |fVq+|tjoU|i}|| |i jptt|o|dpt}t|fVq+|tjo$t| }t |fVt|fVq+|tjo$t| }t |fVt|fVq+|| fVq+WdS(NcsWy|}Wn>tj o2d|jod|}n|}||s file %rs(sselfs_parsersParsesdatasisfinalsexpats ExpatErrorses _filenamesfilenames_sourcessourcesget_expat_errorsstrs Exception(sselfsdatasisfinalse((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pysfeeds  KcCs6t|do"z|idtWd|`XndS(Ns_parsers(shasattrsselfsfeedsTrues_parser(sself((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pyscloses cCs|it||fdS(N(sselfspushsSTARTstagsattrib(sselfstagsattrib((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_startscCs|it|dS(N(sselfspushsTEXTstext(sselfstext((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_datascCs|it|dS(N(sselfspushsENDstag(sselfstag((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_endscCsx|idody"|it|i|dd!Wqttj o/tid||i i |i i fqtXndS(Ns&iis'undefined entity %s: line %d, column %d( stexts startswithsselfspushsTEXTsentitysKeyErrorsexpatserrors_parsersErrorLineNumbersErrorColumnNumber(sselfstext((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_defaults "1cCs|it||fdS(N(sselfspushsPIstargetsdata(sselfstargetsdata((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_piscCs|it|dS(N(sselfspushsCOMMENTstext(sselfstext((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_commentscCs!|it|pd|fdS(Ns(sselfspushsSTART_NSsprefixsuri(sselfsprefixsuri((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys _start_nsscCs|it|pddS(Ns(sselfspushsEND_NSsprefix(sselfsprefix((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_end_nsscCs|it|||fdS(N(sselfspushsXML_DECLsversionsencodings standalone(sselfsversionsencodings standalone((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_xmldecl_handlerscCs|it|||fdS(N(sselfspushsDOCTYPEsnamespubidssysid(sselfsnamessysidspubidshas_internal_subset((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys_doctype_handlers(s__name__s __module__sNonesFalses__init__s _buildForeigns_pushs_push_locations _expat_streams__iter__sfeedscloses_starts_datas_ends_defaults_pis_comments _start_nss_end_nss_xmldecl_handlers_doctype_handler(((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys ExpatParser!s$4    ,           (2s__doc__s __revision__s__date__s __author__s __copyright__s __license__shtmlentitydefss xml.parserssexpats kid.elementsElementsCommentsProcessingInstructionskid.utils open_resourcesQuickTextReadersget_expat_errors__all__sdefault_entity_mapsdefault_external_dtdsname2codepointsitemssksvsunichrsappendsjoins ExceptionsInvalidStreamStatesTruesNonesXMLsFalsesdocumentsobjects ElementStreams to_unicodes _coalescesSTARTsENDsTEXTsDOCTYPEsXML_DECLsSTART_NSsEND_NSsPIsCOMMENTsLOCATIONsParsers ExpatParser($s to_unicodesTEXTsexpatsDOCTYPEs ElementStreamsXML_DECLsQuickTextReaders _coalescesCOMMENTs __revision__s__all__sSTART_NSsget_expat_errorsLOCATIONsdocumentsInvalidStreamStatesXMLsENDs __license__shtmlentitydefssdefault_external_dtds __author__sSTARTs ExpatParsersdefault_entity_mapsElementsComments __copyright__sPIsEND_NSsProcessingInstructionsksParsers__date__svs open_resource((s.build/bdist.darwin-8.0.1-x86/egg/kid/parser.pys?sF  - | 4 PKZ86v9AAkid/__init__.py# -*- coding: utf-8 -*- """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: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" from kid import release __version__ = release.version __author__ = release.author __email__ = release.email __copyright__ = release.copyright __license__ = release.license import sys, os assert sys.hexversion >= 0x02030000, "Kid templates need Python 2.3 or later" from kid.util import xml_sniff, QuickTextReader from kid.namespace import Namespace from kid.codewriter import KID_XMLNS, raise_template_error from kid.compiler import KID_EXT from kid.element import Element, SubElement, Comment, \ ProcessingInstruction, Fragment from kid.parser import ElementStream, XML, document, _coalesce from kid.filter import transform_filter from kid.serialization import Serializer, PlainSerializer, \ XMLSerializer, HTMLSerializer, XHTMLSerializer from kid.format import Format, output_formats import kid.template_util as template_util __all__ = ['KID_XMLNS', 'BaseTemplate', 'Template', 'enable_import', 'import_template', 'load_template', 'Element', 'SubElement', 'XML', 'document', 'Namespace', 'Serializer', 'XMLSerializer', 'HTMLSerializer', 'XHTMLSerializer', 'output_methods', 'Format', 'output_formats', 'filter', 'format', 'namespace', 'serialization', 'util'] assume_encoding = sys.getdefaultencoding() def enable_import(ext=None, path=None): """Enable the kid module loader and import hooks. This function must be called before importing kid templates if templates are not pre-compiled. """ import kid.importer kid.importer.install(ext, path) def disable_import(path=None): """Disable the kid module loader and import hooks again.""" import kid.importer kid.importer.uninstall(path) # Turn on import hooks if KID_IMPORT variables are set if os.environ.get('KID_IMPORT'): enable_import(os.environ.get('KID_IMPORT_EXT')) if os.environ.get('KID_IMPORT_PATH'): enable_import(os.environ.get('KID_IMPORT_EXT'), os.environ['KID_IMPORT_PATH']) def import_template(name, encoding=None): """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) if encoding: mod.encoding = encoding return mod def load_template(file, name='', cache=True, encoding=None, ns={}, entity_map=None, exec_module=None): """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. entity_map Entity map to be used when parsing the template. exec_module If you want full control over how the template module is executed, you can provide this callable that will be called with the template module and the code to be executed as parameters, after the code has been compiled and the module has been created. """ 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 template_util.TemplateNotFound( "%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, entity_map) else: template = compiler.KidFile(filename, force=False, encoding=encoding, entity_map=entity_map) 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, exec_module=exec_module) return mod # create some default serializers... output_methods = { 'xml': XMLSerializer(decl=True), 'wml': XMLSerializer(decl=True, doctype='wml'), 'xhtml-strict': XHTMLSerializer(decl=False, doctype='xhtml-strict'), 'xhtml': XHTMLSerializer(decl=False, doctype='xhtml'), 'xhtml-frameset': XHTMLSerializer(decl=False, doctype='xhtml-frameset'), 'html-strict': HTMLSerializer(doctype='html-strict'), 'html': HTMLSerializer(doctype='html'), 'html-frameset': HTMLSerializer(doctype='html-frameset'), 'html-quirks': HTMLSerializer(doctype='html-quirks'), 'html-frameset-quirks': HTMLSerializer(doctype='html-frameset-quirks'), 'HTML-strict': HTMLSerializer(doctype='html-strict', transpose=True), 'HTML': HTMLSerializer(doctype='html', transpose=True), 'HTML-frameset': HTMLSerializer(doctype='html-frameset', transpose=True), 'HTML-quirks': HTMLSerializer(doctype='html-quirks', transpose=True), 'HTML-frameset-quirks': HTMLSerializer(doctype='html-frameset-quirks', transpose=True), 'plain': PlainSerializer()} def Template(file=None, source=None, name=None, encoding=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=True)`` 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, encoding=encoding) elif file is not None: mod = load_template(file, name=name, encoding=encoding) elif source is not None: mod = load_template(QuickTextReader(source), name=name or hex(id(source)), encoding=encoding) else: raise template_util.TemplateError( "Must specify one of name, file, or source.") try: mod.Template.module = mod except Exception: raise template_util.TemplateImportError( "Template could not be initialized.") return mod.Template(**kw) 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'] 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. """ for k in kw: # check that reserved keywords such as 'content' are not used if hasattr(BaseTemplate, k): raise template_util.TemplateAttrsError( "Keyword argument %r is a reserved name." % k) self.__dict__.update(kw) self._filters = [transform_filter] self._layout_classes = [] def write(self, file, encoding=None, fragment=False, output=None, format=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 True 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) try: return serializer.write(self, file, encoding, fragment, format) except Exception: raise_template_error(module=self.__module__) def serialize(self, encoding=None, fragment=False, output=None, format=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 True 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) try: return serializer.serialize(self, encoding, fragment, format) except Exception: raise_template_error(module=self.__module__) def generate(self, encoding=None, fragment=False, output=None, format=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 True 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) try: return serializer.generate(self, encoding, fragment, format) except Exception: raise_template_error(module=self.__module__) 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 A kid.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=False) 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): """Finding templates on a list of paths.""" def __init__(self, paths=None): """Initialize with path list.""" if isinstance(paths, basestring): paths = paths.split(os.pathsep) elif paths is None: paths = [] paths.append(os.getcwd()) self.paths = [] for path in paths: self.append(path) def _cleanse_path(self, path): """Normalize path.""" return os.path.abspath(os.path.normpath(os.path.expanduser(path))) def insert(self, path, pos=0): """Insert path to list if not already there.""" path = self._cleanse_path(path) if path not in self.paths: self.paths.insert(pos, path) def append(self, path): """Append path to list if not already there.""" path = self._cleanse_path(path) if path not in self.paths: self.paths.append(path) def remove(self, path): """Remove path from list.""" path = self._cleanse_path(path) self.paths = [p for p in self.paths if p != path] def find(self, path, rel=None): """Find file relative to path list and rel.""" path = os.path.normpath(path) if rel: rel = [os.path.dirname(rel)] else: rel = [] for p in self.paths + rel: p = os.path.join(p, path) if os.path.exists(p): return p if not p.endswith(KID_EXT): p += KID_EXT if os.path.exists(p): return p path = TemplatePath() PK0C8JdL&L&kid/compiler.pyc; \PFc@s#dZdZdZdZdZdZdkZdkZdkZdk Z dk Z dk Z dk Z dk lZdd d d gZd Zed ZeZdddZdeedZdZdefdYZdZdZeeeeedZdeeeeedZdS(s0Kid Compiler Compile XML to Python byte-code. s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sraise_template_errorsKID_EXTscompiles compile_files compile_dirs.kidcBs'|ejo h}n||U|SdS(s3Run code with variables in dict, updating the dict.N(sdictsNonescode(scodesdict((s0build/bdist.darwin-8.0.1-x86/egg/kid/compiler.pys actualizes   ssexeccCsMt|tjo&|idod|d}q9nt||dSdS(s4The Python built-in compile function with safeguard.s# -*- coding: s# -*-i sexecN(stypescodesunicodes startswiths _py_compilesfilename(scodesfilenameskind((s0build/bdist.darwin-8.0.1-x86/egg/kid/compiler.pys py_compile&s cCs,tii||||}t||SdS(sCompiles Kid XML source to a Python code object. source -- A file like object - must support read. filename -- An optional filename that is used N( skids codewritersparsessourcesencodingsfilenames entity_mapspys py_compile(ssourcesfilenamesencodings entity_mapspy((s0build/bdist.darwin-8.0.1-x86/egg/kid/compiler.pyscompile0scCsti|tiS(N(sossstatsfilenamesST_MTIME(sfilename((s0build/bdist.darwin-8.0.1-x86/egg/kid/compiler.pys=ssKidFilecBsztZeiZeeeedZeedZ dZ e e Z dZ e e Z edZ edZRS(Nc Cs:||_tii|dd|_||_|id|_||_||_ t }|o t }nt}yt|id}Wntj o t }ntX|id|ijo t }nPtid|idd}t|} | t jp || jo t }n||_||_t |_t |_dS(Nis.pyscsrbisN(sdirnamesabspath(sgetopts GetoptError(sEX_OKs EX_DATAERRsEX_USAGEiiicCsay2ttidddddddg\}}WnLtj o@} tiit | dti it ti t nXd }t} }x|D]\}} |d d fjo | }q|d d fjo | } q|ddfjo | }q|ddfjo!ti it ti tq|ddfjo2dkl}ti id|ti tqqW|tjo|oP|id}|gt_|djo>tt|} | tij otiid| qntii}h}xd|o\|idi dd} t!| djo| d|| d self.len: self.pos = self.len return self.text[pos:self.pos] def seek(self, offset, whence=0): if whence: if whence == 2: self.pos = self.len - offset else: self.pos += offset else: self.pos = offset self.lines = None if self.pos < 0: self.pos = 0 elif self.pos > self.len: self.pos = self.len def tell(self): return self.pos def next(self): if not self.lineno: self.lines = self.splitlines(True) self.lineno += 1 if not self.lines: raise StopIteration return self.lines.pop(0) def xml_sniff(text): """Sniff text to see if it looks like XML. Return True if text looks like XML, otherwise return False. """ for x in text: if x in '\t\r\n ': continue elif x == '<': return True else: return False 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) def get_expat_error(error): """Return text showing the position of an Expat error.""" source, lineno, offset = error.source, error.lineno, error.offset if lineno < 1: lineno = 1 offset = 0 source.seek(0) nlines = 0 for line in source: lineno -= 1 nlines += 1 if not lineno: break else: offset = 0 if nlines: if nlines == 1: if line.startswith('\xef\xbb\xbf'): line = line[3:] if line: if offset < 0: offset = 0 elif offset > len(line): offset = len(line) if offset > 75: if len(line) - offset > 37: line = line[offset-38:offset+38] offset = 38 else: offset -= len(line) - 76 line = line[-76:] else: line = line[:76] if line: line = '%s\n%%%ds\n' % (line.rstrip(), offset + 1) line = line % '^' return line PKZ86.p"" kid/server.py# -*- coding: utf-8 -*- """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: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Christoph Zwerschke (cito@online.de)" __copyright__ = "Copyright 2005, Christoph Zwerschke" __license__ = "MIT " 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 __all__ = ["HTTPServer", "HTTPRequestHandler"] 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=True) 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() PK1C8yy77kid/release.pyc; RFc@sSdZdZdZdZdZdZdZdZdiei d i Z d S( scPythonic, 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 :). s $Rev: 497 $s5$Date: 2007-07-16 14:48:50 -0400 (Mon, 16 Jul 2007) $s0.9.6s Ryan Tomaykosrtomayko@gmail.comsSCopyright 2004-2006, Ryan Tomayko, David Stanek, Christoph Zwerschke, Daniel MillersMITs iN( s__doc__s __revision__s__date__sversionsauthorsemails copyrightslicensesjoins splitlinessstripslong_description(s __revision__slicenses copyrightsauthorslong_descriptions__date__sversionsemail((s/build/bdist.darwin-8.0.1-x86/egg/kid/release.pys? sPKZ86_1RRkid/importer.py# -*- coding: utf-8 -*- """Kid Import Hooks. When installed, these hooks allow importing .kid files as if they were Python modules. Notes: We use new import hooks instead of the old ihooks module, because ihooks is incompatible with Python eggs. We allow importing from one or more specified paths for Kid templates, or importing from sys.path. In the latter case, we use an importer on meta_path because importers on path_hook do not fall back to the built-in import in Python >= 2.5 (this worked in Python 2.3 and 2.4). """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com); Christoph Zwerschke (cito@online.de)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko; 2006 Christoph Zwerschke" __license__ = "MIT " import sys import time import new from os import environ, extsep, pathsep from os.path import exists, join as joinpath, isdir from kid import __version__ from kid.codewriter import raise_template_error from kid.compiler import KidFile, KID_EXT from kid.template_util import TemplateImportError __all__ = ['install', 'uninstall', 'import_template', 'get_template_name'] def install(ext=None, path=None): """Install importer for Kid templates. ext can be one or more extensions as list or comma separated string path can be one or more paths as list or pathsep separated string """ if ext: if isinstance(ext, basestring): exts = ext.split(',') else: exts = list(ext) for ext in exts: if not ext.startswith(extsep): raise Exception, "Illegal exception: " + ext if KID_EXT in exts: exts.remove(KID_EXT) else: exts = [] exts.insert(0, KID_EXT) if path: # install path hook if isinstance(path, basestring): paths = path.split(pathsep) else: paths = list(path) # Install special Kid template paths, because since Python 2.5, # path hooks do not fall back to the built-in import any more. ext = ','.join(exts) kidpaths = [] syspath = sys.path for path in paths: kidpath = 'kid::%s::' % path syspath = [path for path in syspath if not path.startswith(kidpath)] kidpaths.append(kidpath + ext) sys.path = kidpaths + syspath if kidpaths: if not KidImporter in sys.path_hooks: sys.path_hooks.insert(0, KidImporter) else: # install meta hook for all sys paths for importer in sys.meta_path: if isinstance(importer, KidImporter): importer.exts = exts break else: importer = KidImporter(ext=exts) sys.meta_path.insert(0, importer) def uninstall(path=None): """Uninstall importer for Kid templates. path can be one or more paths as list or pathsep separated string """ if path: # uninstall path hook if isinstance(path, basestring): paths = path.split(pathsep) else: paths = list(path) syspath = [] remove_hook = True for path in sys.path: p = path.split(':') if len(p) >= 5 and \ p[0] == 'kid' and not p[1] and not p[-2]: if ':'.join(p[2:-2]) in paths: continue remove_hook = False syspath.append(path) sys.path = syspath if remove_hook: if KidImporter in sys.path_hooks: sys.path_hooks = [hook for hook in sys.path_hooks if hook != KidImporter] sys.path_importer_cache.clear() else: # uninstall meta hook for all sys paths sys.meta_path = [importer for importer in sys.meta_path if not isinstance(importer, KidImporter)] def import_template(name, filename, force=False): if not force and name and sys.modules.has_key(name): return sys.modules[name] template = KidFile(filename) code = template.compile(dump_source=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=True, ns={}, exec_module=None): for recompiled in range(2): name = get_template_name(name, filename) mod = new.module(name) mod.__file__ = filename mod.__ctime__ = time.time() mod.__dict__.update(ns) try: if exec_module: exec_module(mod, code) else: exec code in mod.__dict__ except Exception: if store: sys.modules[name] = mod raise_template_error(module=name, filename=filename) if getattr(mod, 'kid_version', None) == __version__: break # the module has been compiled against an old Kid version, # recompile to ensure compatibility and best performance if recompiled: # already tried recompiling, to no avail raise TemplateImportError('Cannot recompile template file' ' %r for Kid version %s' % (filename, __version__)) template = KidFile(filename) template.stale = True template._python = template._code = None code = template.compile(dump_source=environ.get('KID_OUTPUT_PY')) if store: sys.modules[name] = mod return mod class KidImporter(object): """Importer for Kid templates via sys.path_hooks or sys.meta_path.""" def __init__(self, path=None, ext=None): if path: # initialized via sys.path_hooks # check for special path format: # path = kid::/path/to/templates::.ext1,.ext2 p = path.split(':') if len(p) >= 5 and \ p[0] == 'kid' and not p[1] and not p[-2]: path = ':'.join(p[2:-2]) exts = p[-1].split(',') if exts: for ext in exts: if not ext.startswith(extsep): break else: if isdir(path): self.path = path self.exts = exts return raise ImportError else: # initialize for use via sys.meta_path if ext: if isinstance(ext, basestring): exts = ext.split(',') else: exts = list(ext) for ext in exts: if not ext.startswith(extsep): raise ImportError else: raise ImportError self.path = None self.exts = exts def find_module(self, fullname, path=None): name = fullname.split('.')[-1] if self.path: if path: raise ImportError else: paths = [self.path] else: paths = sys.path if path: paths = path + paths for path in paths: if isdir(path): path = joinpath(path, name) for ext in self.exts: if exists(path + ext): self.filename = path + ext return self return None def load_module(self, fullname): return import_template(fullname, self.filename, force=True) PKZ86 \zzkid/compiler.py# -*- coding: utf-8 -*- """Kid Compiler Compile XML to Python byte-code. """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import os.path import imp import stat import struct import marshal import kid from kid.codewriter import raise_template_error __all__ = ['KID_EXT', 'compile', 'compile_file', 'compile_dir'] # kid filename extension KID_EXT = ".kid" def actualize(code, dict=None): """Run code with variables in dict, updating the dict.""" if dict is None: dict = {} exec code in dict return dict _py_compile = compile def py_compile(code, filename='', kind='exec'): """The Python built-in compile function with safeguard.""" if type(code) == unicode: # unicode strings may not have a PEP 0263 encoding declaration if code.startswith('# -*- coding: '): # we want the line numbering to match with the source file, # so we only remove the magic word in the comment line: code = '# -*-' + code[13:] return _py_compile(code, filename, 'exec') def compile(source, filename='', encoding=None, entity_map=None): """Compiles Kid XML source to a Python code object. source -- A file like object - must support read. filename -- An optional filename that is used """ # XXX all kinds of work to do here catching syntax errors and # adjusting line numbers... py = kid.codewriter.parse(source, encoding, filename, entity_map) return py_compile(py, filename) _timestamp = lambda filename : os.stat(filename)[stat.ST_MTIME] class KidFile(object): magic = imp.get_magic() def __init__(self, kid_file, force=False, encoding=None, strip_dest_dir=None, entity_map=None): self.kid_file = kid_file self.py_file = os.path.splitext(kid_file)[0] + '.py' self.strip_dest_dir = strip_dest_dir self.pyc_file = self.py_file + 'c' self.encoding = encoding self.entity_map = entity_map fp = None if force: stale = True else: stale = False try: fp = open(self.pyc_file, "rb") except IOError: stale = True else: if fp.read(4) != self.magic: stale = True else: mtime = struct.unpack(' 0 and name != os.curdir and name != os.pardir \ and os.path.isdir(fullname) and not os.path.islink(fullname): for res in compile_dir(fullname, maxlevels - 1, force, source, encoding, strip_dest_dir, entity_map): yield res PK1C8@((kid/element.pyc; [PFc @sdZdZdZdZdZdZdkZddd d d d d dddg ZdefdYZ hdZ e dZ e dZ ddZd fdYZedZhdd<dd<dd<dd NsElements SubElementsCommentsProcessingInstructionsFragmentsQNames namespacess escape_maps encode_entitysraise_serialization_errorcBstZdZeZeZhdZdZdZdZ dZ dZ dZ dZ d Zd Zd Zd Zd ZdZedZdZdZdZRS(s$A class representing an XML element.cKs8|i}|i|||_||_g|_dS(N(sattribscopysupdatesextrastagsselfs _children(sselfstagsattribsextra((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pys__init__s     cCsd|it|fSdS(Ns(sselfstagsid(sself((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pys__repr__scCst|iSdS(N(slensselfs _children(sself((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pys__len__$scCs|i|SdS(N(sselfs _childrensindex(sselfsindex((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pys __getitem__'scCs(t|tpt||i| 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.darwin-8.0.1-x86/egg/kid/element.pys namespacess  s&s&ss>s"s"su"[&<>\"\u0080-\uffff]+"cCsd|tjo t}n|d}y|i||idSWntj ot |nXdS(NcCskg}xQ|iD]C}|i|}|tjodt|}n|i |qWdi |SdS(Ns&#%d;s( soutsmsgroupscharsentitiessgetstextsNonesordsappendsjoin(smsentitiesstextscharsout((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pysescape_entitiess  sascii( sentitiessNones escape_mapsescape_entitiesspatternssubstextsencodes TypeErrorsraise_serialization_error(stextspatternsentitiessescape_entities((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pys encode_entitys   cCs#td|t|ifdS(Nscannot serialize %r (type %s)(s TypeErrorstextstypes__name__(stext((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pysraise_serialization_errors(s__doc__s __revision__s__date__s __author__s __copyright__s __license__sres__all__sobjectsElements SubElementsNonesCommentsProcessingInstructionsFragmentsQNamesFalses namespacess escape_mapscompilesevals re_escapes encode_entitysraise_serialization_error(s re_escapesraise_serialization_errors encode_entitys __revision__s__all__sFragmentsres escape_maps __license__s __author__s namespacessElementsComments __copyright__sProcessingInstructionsQNames__date__s SubElement((s/build/bdist.darwin-8.0.1-x86/egg/kid/element.pys?s$ $L     *PKY86zkid/options.py# -*- coding: utf-8 -*- """Configuration API.""" import release __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = release.license __all__ = ['Options'] _prefix = "kid:" class Options(object): def __init__(self, options={}, **extra): self._options = {} for name, value in options.items(): self.set(name, value) for name, value in extra.items(): self.set(name, value) def isset(self, name): """Returns True if a option exists or False if it doesn't. name: the option to check """ return self._options.has_key(self.__prefix(name)) def get(self, name, default=None): """Get the value of an option. name: the option to retrieve default: returned for non-existing properties, defaults to None """ return self._options.get(self.__prefix(name), default) def set(self, name, value): """Set the value of an option. name: the option to set value: the value to be set for the option Returns the value passed in. """ self._options[self.__prefix(name)] = value return value def remove(self, name): """Remove an option.""" if self.isset(name): del self._options[self.__prefix(name)] def __getitem__(self, name): if not self.isset(name): raise KeyError, "no option %s" % name return self.get(name) def __setitem__(self, name, value): self.set(name, value) def __delitem__(self, name): if not self.isset(name): raise KeyError, "no option %s" % name self.remove(name) def __prefix(self, name): """Add the prefix if it does not already exist.""" if not name.startswith(_prefix): name = _prefix + name return name PKZ86k"-((kid/template_util.py# -*- coding: utf-8 -*- """Utility functions used by generated kid modules.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import inspect import sys from types import TypeType, ModuleType, ClassType, GeneratorType import itertools # these are for use by template code import kid from kid.parser import XML, document, ElementStream, START, END, TEXT, \ START_NS, COMMENT, PI, DOCTYPE, XML_DECL, to_unicode from kid.element import Element, SubElement, Comment, ProcessingInstruction __all__ = ['XML', 'document', 'ElementStream', 'Element', 'SubElement', 'Comment', 'ProcessingInstruction', 'START', 'END', 'TEXT', 'START_NS', 'COMMENT', 'PI', 'DOCTYPE', 'XML_DECL'] class TemplateError(Exception): pass class TemplateNotFound(TemplateError): pass class TemplateImportError(TemplateError): pass class TemplateDictError(TemplateError): pass class TemplateAttrsError(TemplateError): pass class TemplateExtendsError(TemplateError): pass class TemplateLayoutError(TemplateError): pass _local_excludes = ['generate', 'module', 'parser', '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=None, arg=None): """Get template base class for thing, raising an exception on error.""" if thing is None: return kid.BaseTemplate if isinstance(thing, TypeType): return thing elif isinstance(thing, ModuleType): try: cls = thing.Template except AttributeError: cls = None if (isinstance(cls, TypeType) and issubclass(cls, kid.BaseTemplate) and cls != kid.Template): return cls thing = repr(thing) if arg: thing = arg else: try: thing = thing.__name__ except AttributeError: thing = repr(thing) raise TemplateNotFound( '%s is a module without Template class' % thing) elif isinstance(thing, basestring): try: path = kid.path.find(thing, from_file) except Exception: path = None if not path: if arg: thing = arg raise TemplateNotFound('Template file %r not found' % thing) try: mod = kid.load_template(path) except Exception: mod = None if not mod: raise TemplateNotFound('Could not open %r' % path) try: cls = mod.Template except AttributeError: cls = None if (isinstance(cls, TypeType) and issubclass(cls, kid.BaseTemplate) and cls != kid.Template): return cls raise TemplateNotFound('%r does not contain a template class' % path) thing = repr(thing) if arg: thing = '%s (%s)' % (arg, thing) raise TemplateNotFound('%s is not a Template class' % thing) def base_class(arg, globals, locals): """Get base class for argument with graceful exception handling.""" try: from_file = globals['__file__'] thing = eval(arg, globals, locals) return get_base_class(thing, from_file, arg) except Exception, e: errors = [str(e)] # try again without evaluating the argument (forgotten quotes etc.) try: return get_base_class(arg, from_file, arg) except Exception, e: errors.append(str(e)) # reraise the original problem when we tried to evaluate the thing errors = '\n'.join(filter(bool, errors)) or arg raise TemplateNotFound, errors def base_class_extends(extends, globals, locals, all_extends=None): """Get Template base class for 'extends'.""" try: return base_class(extends, globals, locals) except Exception, e: raise TemplateExtendsError((str(e) + '\nwhile processing extends=%r' % (all_extends or extends)).lstrip()) def base_class_layout(layout, globals, locals): """Get Template base class for 'layout'.""" try: return base_class(layout, globals, locals) except Exception, e: raise TemplateLayoutError((str(e) + '\nwhile processing layout=%r' % layout).lstrip()) def make_attrib(attrib, encoding=None): """Generate unicode strings in dictionary.""" if attrib is None: return {} if encoding is None: encoding = sys.getdefaultencoding() for (k, v) in attrib.items(): if v is not None: try: v = generate_attrib(v, encoding) except TemplateAttrsError: raise TemplateAttrsError('Illegal value for attribute "%s"' % k.encode('raw_unicode_escape')) if v is None: del attrib[k] else: attrib[k] = v return attrib def generate_attrib(attrib, encoding): """Generate unicode string from attribute.""" if attrib is None: return None elif isinstance(attrib, basestring): return to_unicode(attrib, encoding) elif isinstance(attrib, ElementStream): text = [] for ev, item in attrib: if ev == TEXT: text.append(to_unicode(item, encoding)) else: raise TemplateAttrsError if text: return ''.join(text) else: return None elif hasattr(attrib, '__iter__'): # if we get any other iterable, join the strings together: text = [] for item in attrib: if item is not None: item = generate_attrib(item, encoding) if item is not None: text.append(item) if text: return ''.join(text) else: return None else: return to_unicode(attrib, encoding) def generate_content(content): """Generate ElementStream from content.""" if content is None: return [] elif isinstance(content, basestring): return [(TEXT, content)] elif isinstance(content, (ElementStream, kid.BaseTemplate)): return content elif isinstance(content, GeneratorType): return ElementStream(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 any other iterable, chain the contents together: return itertools.chain(*itertools.imap(generate_content, 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, args, globals, locals): """Update dictionary a from keyword argument string args.""" try: b = eval('%s' % args, globals, locals) if not isinstance(b, dict): b = dict(b) except Exception: try: b = eval('dict(%s)' % args, globals, locals) except SyntaxError: # TypeErrror could happen with Python versions < 2.3, because # building dictionaries from keyword arguments was not supported. # Kid requires a newer Python version, so we do not catch this. # 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. # In these cases we parse the keyword arguments manually: try: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from tokenize import generate_tokens from token import NAME, OP depth, types, parts = 0, [], [] for token in generate_tokens(StringIO(args).readline): type_, string = token[:2] if type_ == OP: if string == '=': if depth == 0: if len(types) > 0 \ and types[-1] == NAME and parts[-1]: if len(types) > 2 \ and types[-2] == OP and parts[-2] == ':' \ and types[-3] == NAME and parts[-3]: parts[-3:] = ["'%s'" % ''.join(parts[-3:])] else: parts[-1] = "'%s'" % parts[-1] string = ':' elif string in '([{': depth += 1 elif depth > 0 and string in ')]}': depth -= 1 types.append(type_) parts.append(string) b = eval('{%s}' % ''.join(parts), globals, locals) except Exception: b = None if not isinstance(b, dict): raise 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 def update_attrs(attrib, attrs, globals, locals): """Update attributes from attrs string args.""" try: return update_dict(attrib, attrs, globals, locals) except Exception, e: raise TemplateAttrsError((str(e) + '\nwhile processing attrs=%r' % attrs).lstrip()) def make_updated_attrib(attrib, attrs, globals, locals, encoding=None): """"Generate unicode strings in updated dictionary.""" return make_attrib(update_attrs(attrib, attrs, globals, locals), encoding) PK1C8Akid/compile.pyc; [PFc@sdZdZdZdZdZdZdkZdklZdk l Z l Z yd k l Z lZlZWn+ej od d d f\Z ZZnXdkZd Zedjo endS(s}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. s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sisdir(sgetopts GetoptError(sEX_OKs EX_DATAERRsEX_USAGEiiic Cs{y/ttiddddddg\} }WnLtj o@}tiit |dti it ti t nXt}}t}x| D]\} }| dd fjo t}q| d d fjo t}q| d d fjo!ti it ti tq| ddfjo |}qqW|}| o1tiidtiidti t nd}t} x|D]} t| o^xtii| d|d|d|D]1}|dttfjo t} n||qWqy(tii | d|d|d|} Wn't"j o}|tf\} } nX|| | fqWti | ot#ptdS(Nisfshd=sforcessourceshelpsstrip-dest-dir=s s-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) ( sressstatsfilenamesTruesmsgsFalsessyssstderrswrite(sressstatsfilenamesmsg((s/build/bdist.darwin-8.0.1-x86/egg/kid/compile.pys print_resultGs   sstrip_dest_diri($sgetoptssyssargvsoptssargssgerrorsesstderrswritesstrsstdouts__doc__sexitsEX_USAGEsFalsesforcessourcesNonesstrip_dest_dirsosasTruesEX_OKsfiless print_resultserrsfsisdirskidscompilers compile_dirsress compile_filesstats Exceptions EX_DATAERR(sforcesstrip_dest_dirs print_resultsresssourcesfilessargssesasstatserrsfsosopts((s/build/bdist.darwin-8.0.1-x86/egg/kid/compile.pysmain*sV "       s__main__(s__doc__s __revision__s__date__s __author__s __copyright__s __license__ssyssos.pathsisdirsgetopts GetoptErrorsgerrorsossEX_OKs EX_DATAERRsEX_USAGEs ImportErrors kid.compilerskidsmains__name__(sisdirssyss __copyright__s __revision__s __license__s EX_DATAERRsgerrors __author__s__date__smainsEX_OKsgetoptsEX_USAGEskid((s/build/bdist.darwin-8.0.1-x86/egg/kid/compile.pys?s     ; PKZ869 < < kid/parser.py# -*- coding: utf-8 -*- """Pull-style interface for ElementTree.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import htmlentitydefs from xml.parsers import expat from kid.element import Element, Comment, ProcessingInstruction from kid.util import open_resource, QuickTextReader, get_expat_error __all__ = ['ElementStream', 'XML', 'document', 'Parser', 'ExpatParser', 'START', 'END', 'TEXT', 'COMMENT', 'PI', 'XML_DECL', 'DOCTYPE', 'LOCATION'] # This is the default entity map: 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) class InvalidStreamState(Exception): def __init__(self, msg="Invalid stream state."): Exception.__init__(self, msg) def XML(text, fragment=True, encoding=None, xmlns=None, entity_map=None): """Convert XML string into an ElementStream.""" 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, entity_map) return ElementStream(_coalesce(p, encoding=encoding)).strip() else: if isinstance(text, unicode): encoding = 'utf-16' text = text.encode(encoding) p = Parser(QuickTextReader(text), encoding, entity_map) return ElementStream(_coalesce(p, encoding=encoding)) def document(file, encoding=None, filename=None, entity_map=None, debug=False): """Convert XML document into an Element stream.""" 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, entity_map, debug) 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=True) 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. In the case where there is no current element and no single root element, this will return a list of Elements. """ current = self.current if current is None: current = [] stack = [current] this, last = current, None for ev, item in self._iter: if ev == START: current, last = item, None stack[-1].append(current) stack.append(current) elif ev == END: last = stack.pop() assert last is item if not stack: break elif ev == TEXT: if last is not None: last.tail = item elif not isinstance(current, list): current.text = item if isinstance(this, list) and len(this) == 1: this = this[0] return this def strip(self, levels=1): """Return new ElementStream with first element level(s) stripped.""" def strip(depth): for ev, item in self._iter: if ev == END: depth -= 1 if depth == 0: break elif depth < 0: raise InvalidStreamState() if depth >= levels: yield ev, item if ev == START: depth += 1 depth = self.current is not None and 1 or 0 return ElementStream(strip(depth)) 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=False): """Make a stream from an Element.""" 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=True): yield event yield END, elem if tail and orig.tail: yield TEXT, orig.tail def _track(self, stream, current=None): """Track current item in stream.""" 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): """Ensure the stream is an ElementStream.""" 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): """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 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 # This is for forwarding the location in the XML document LOCATION = 20 def Parser(source, encoding=None, entity_map=None, debug=False): return ExpatParser(source, encoding, entity_map, debug) # Most of the following copied from ElementTree.XMLTreeBuilder. # Differences from ElementTree 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, entity_map=None, debug=False): if hasattr(source, 'read'): filename = '' else: filename = source source = open(source, 'rb') self._filename = filename self._source = source self._encoding = encoding self._parser = parser = expat.ParserCreate(encoding, "}") self._queue = [] try: self._parser.CurrentLineNumber except AttributeError: # Expat in Python < 2.4 does not provide the location, # silently switch off the debug mode in this case debug = False if debug: self.push = self._push_location else: self.push = self._push self.debug = debug # 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 # attributes # (these should all become customizable at some point) parser.buffer_text = True parser.ordered_attributes = False parser.specified_attributes = True self._doctype = None if entity_map: self.entity = entity_map else: self.entity = default_entity_map self.external_dtd = default_external_dtd # setup entity handling parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) parser.ExternalEntityRefHandler = self._buildForeign 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 True def _push(self, ev, stuff): self._queue.append((ev, stuff)) def _push_location(self, ev, stuff): self._push(LOCATION, (self._parser.CurrentLineNumber, self._parser.CurrentColumnNumber)) self._push(ev, stuff) def _expat_stream(self): bufsize = 4 * 1024 # 4K feed = self.feed read = self._source.read more = True while more: while more and not self._queue: data = read(bufsize) if data == '': self.close() more = False else: feed(data) for item in self._queue: yield item self._queue = [] def __iter__(self): clarknames = {} def clarkname(key): try: name = clarknames[key] except KeyError: if "}" in key: name = "{" + key else: name = key clarknames[key] = name return name stack = [] current = None for ev, stuff in self._expat_stream(): if ev == TEXT: yield TEXT, stuff elif ev == START: tag, attrib = stuff tag = clarkname(tag) attrib = dict([(clarkname(key), value) for key, value in attrib.items()]) parent = current current = Element(tag, attrib) stack.append(current) yield START, current elif ev == END: current = stack.pop() assert clarkname(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) yield START, current yield END, current else: yield ev, stuff def feed(self, data, isfinal=False): try: self._parser.Parse(data, isfinal) except expat.ExpatError, e: e.filename = self._filename e.source = self._source try: e = 'Error parsing XML%s:\n%s%s' % ( e.filename and e.filename != '' and (' file %r' % e.filename) or '', get_expat_error(e), str(e)) except Exception: pass raise expat.ExpatError(e) def close(self): if hasattr(self, '_parser'): try: self.feed('', True) # end of data finally: del self._parser # get rid of circular references def _start(self, tag, attrib): self.push(START, (tag, attrib)) def _data(self, text): self.push(TEXT, text) def _end(self, tag): self.push(END, tag) def _default(self, text): if text.startswith('&'): # deal with undefined entities try: self.push(TEXT, self.entity[text[1:-1]]) except KeyError: 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?, 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: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys from os.path import isdir from getopt import getopt, GetoptError as gerror try: from os import EX_OK, EX_DATAERR, EX_USAGE except ImportError: EX_OK, EX_DATAERR, EX_USAGE = 0, 1, 2 import kid.compiler def main(): # get options try: opts, args = getopt(sys.argv[1:], 'fshd=', ['force', 'source', 'help', 'strip-dest-dir=']) except gerror, e: sys.stderr.write(str(e) + '\n') sys.stdout.write(__doc__) sys.exit(EX_USAGE) force = source = False 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(EX_OK) 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(EX_USAGE) # a quick function for printing results def print_result(res): stat, filename = res if stat == True: msg = 'compile: %s\n' % filename elif stat == False: msg = 'fresh: %s\n' % filename else: msg = 'error: %s (%s)\n' % (filename, stat) sys.stderr.write(msg) # run through files and compile err = False for f in files: if isdir(f): for res in kid.compiler.compile_dir(f, force=force, source=source, strip_dest_dir=strip_dest_dir): if res[0] not in (True, False): err = True print_result(res) else: try: stat = kid.compiler.compile_file(f, force=force, source=source, strip_dest_dir=strip_dest_dir) except Exception, e: stat, err = e, True print_result((stat, f)) # exit with error status if one compilation failed sys.exit(err and EX_DATAERR or EX_OK) if __name__ == '__main__': main() PK1C8-33kid/template_util.pyc; \PFc@s<dZdZdZdZdZdZdkZdkZdkl Z l Z l Z l Z dk Z dkZdklZlZlZlZlZlZlZlZlZlZlZlZd klZlZlZl Z d d d d dddddddddddgZ!de"fdYZ#de#fdYZ$de#fdYZ%de#fd YZ&d!e#fd"YZ'd#e#fd$YZ(d%e#fd&YZ)d'd(d)d*d+d,gZ*e+d-Z,e+e+d.Z-d/Z.e+d0Z/d1Z0e+d2Z1d3Z2d4Z3d5Z4d6Z5d7Z6e+d8Z7dS(9s0Utility functions used by generated kid modules.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(sTypeTypes ModuleTypes ClassTypes GeneratorType( sXMLsdocuments ElementStreamsSTARTsENDsTEXTsSTART_NSsCOMMENTsPIsDOCTYPEsXML_DECLs to_unicode(sElements SubElementsCommentsProcessingInstructionsXMLsdocuments ElementStreamsElements SubElementsCommentsProcessingInstructionsSTARTsENDsTEXTsSTART_NSsCOMMENTsPIsDOCTYPEsXML_DECLs TemplateErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pys TemplateErrorssTemplateNotFoundcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysTemplateNotFoundssTemplateImportErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysTemplateImportErrorssTemplateDictErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysTemplateDictErrorssTemplateAttrsErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysTemplateAttrsError ssTemplateExtendsErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysTemplateExtendsError!ssTemplateLayoutErrorcBstZRS(N(s__name__s __module__(((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysTemplateLayoutError"ssgeneratesmodulesparsers serializes transformswritecCs|tjo h}ng}t}xdti|D]S\}}|i d o||j o ||jo|i d||fq3q3Wdi |SdS(Ns_s %s=self.%ss;( s_localssNoneslss_local_excludesslocal_excludessinspects getmemberssinstsvarsvalues startswithsappendsjoin(sinsts_localsslocal_excludessvalueslssvar((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pys get_locals&s   ,cCst|tjo tiSnt|to|Sn t|toy |i}Wnt j o t}nXt|to t |tio |tijo|Snt |}|o |}n0y |i }Wnt j ot |}nXtd|n6t|to%ytii||}Wntj o t}nX| o%|o |}ntd|nyti|}Wntj o t}nX| otd|ny |i}Wnt j o t}nXt|to t |tio |tijo|Sntd|nt |}|od||f}ntd|dS(sAGet template base class for thing, raising an exception on error.s%%s is a module without Template classsTemplate file %r not foundsCould not open %rs$%r does not contain a template classs%s (%s)s%s is not a Template classN(sthingsNoneskids BaseTemplates isinstancesTypeTypes ModuleTypesTemplatesclssAttributeErrors issubclasssreprsargs__name__sTemplateNotFounds basestringspathsfinds from_files Exceptions load_templatesmod(sthings from_filesargsmodsclsspath((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysget_base_class1s\    3        3 cCsy0|d}t|||}t|||SWntj o}t |g}yt|||SWn(tj o}|i t |nXdi t t|p|}t|nXdS(s=Get base class for argument with graceful exception handling.s__file__s N(sglobalss from_filesevalsargslocalssthingsget_base_classs ExceptionsesstrserrorssappendsjoinsfiltersboolsTemplateNotFound(sargsglobalsslocalss from_fileserrorssesthing((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pys base_classgs cCsWyt|||SWn<tj o0}tt|d|p|i nXdS(s&Get Template base class for 'extends'.s while processing extends=%rN( s base_classsextendssglobalsslocalss ExceptionsesTemplateExtendsErrorsstrs all_extendsslstrip(sextendssglobalsslocalss all_extendsse((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysbase_class_extendsxs cCsPyt|||SWn5tj o)}tt|d|inXdS(s%Get Template base class for 'layout'.s while processing layout=%rN( s base_classslayoutsglobalsslocalss ExceptionsesTemplateLayoutErrorsstrslstrip(slayoutsglobalsslocalsse((s5build/bdist.darwin-8.0.1-x86/egg/kid/template_util.pysbase_class_layouts cCs|tjohSn|tjoti}nx|iD]\}}|tj oFyt||}Wqt j o t d|i dqXn|tjo ||=q?|||" % (self.tag, id(self)) # Methods for dealing with children - a list interface def __len__(self): return len(self._children) def __getitem__(self, index): return self._children[index] def __setitem__(self, index, element): assert isinstance(element, Element) self._children[index] = element def __delitem__(self, index): del self._children[index] def __getslice__(self, start, stop): return self._children[start:stop] def __setslice__(self, start, stop, elements): for element in elements: assert isinstance(element, Element) self._children[start:stop] = list(elements) def __delslice__(self, start, stop): del self._children[start:stop] def append(self, element): assert isinstance(element, Element) self._children.append(element) def insert(self, index, element): assert isinstance(element, Element) self._children.insert(index, element) def remove(self, element): assert isinstance(element, Element) self._children.remove(element) def getchildren(self): return self._children def clear(self): self.attrib.clear() self._children = [] self.text = self.tail = None # Methods for dealing with attributes - a dictionary like interface def get(self, key, value=None): return self.attrib.get(key, value) def set(self, key, value): self.attrib[key] = value def keys(self): return self.attrib.keys() def items(self): return self.attrib.items() def SubElement(parent, tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) element = Element(tag, attrib) parent.append(element) return element def Comment(text=None): """Comment element factory.""" elem = Element(Comment) elem.text = text return elem def ProcessingInstruction(target, text=None): """PI element factory.""" elem = Element(ProcessingInstruction) elem.text = target if text: elem.text += " " + text return elem 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 class QName: def __init__(self, text_or_uri, tag=None): if tag: text_or_uri = "{%s}%s" % (text_or_uri, tag) self.text = text_or_uri def __str__(self): return self.text def namespaces(elem, remove=False): """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 escape_map = { "&": "&", "<": "<", ">": ">", '"': """, } re_escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"')) def encode_entity(text, pattern=re_escape, entities=None): if entities is None: entities = escape_map # map reserved and non-ascii characters to XML entities def escape_entities(m, entities=entities): out = [] for char in m.group(): text = entities.get(char) if text is None: text = "&#%d;" % ord(char) out.append(text) return ''.join(out) try: return pattern.sub(escape_entities, text).encode('ascii') except TypeError: raise_serialization_error(text) def raise_serialization_error(text): raise TypeError( "cannot serialize %r (type %s)" % (text, type(text).__name__) ) PKY86]dUdU kid/format.py# -*- coding: utf-8 -*- """Infoset serialization format styles. This modules provides methods assisting the serialization module in formatting the text content of serialized infosets. The methods for "educating" and "stupefying" typographic characters have been inspired by John Gruber's "SmartyPants" project (http://daringfireball.net/projects/smartypants/, see also http://web.chad.org/projects/smartypants.py/). """ __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Christoph Zwerschke (cito@online.de)" __copyright__ = "Copyright 2006, Christoph Zwerschke" __license__ = "MIT " import re __all__ = ['Format', 'output_formats'] class Format(object): """Formatting details for Serializers.""" # Default values for some parameters: wrap = 80 indent = '\t' min_level, max_level = 1, 8 tabsize = 8 apostrophe = u'\u2019' squotes = u'\u2018\u2019' dquotes = u'\u201c\u201d' dashes = u'\u2013\u2014' ellipsis = u'\u2026' # Regular expressions used by the Format class: re_whitespace = re.compile(r'[ \t\n\r]+') re_leading_blanks = re.compile(r'^[ \t]+', re.MULTILINE) re_trailing_blanks = re.compile(r'[ \t]+$', re.MULTILINE) re_duplicate_blanks = re.compile(r'[ \t]{2,}') re_duplicate_newlines = re.compile(r'\n[ \t\n\r]*\n') re_whitespace_with_newline = re.compile(r'[ \t]*\n[ \t\n\r]*') re_indentation = re.compile(r'\n[ \t]*') re_squotes = re.compile(r"'") re_dquotes = re.compile(r'"') re_sbackticks = re.compile(r"`") re_dbackticks = re.compile(r"(? width > 0: t.append('\n') offset = indent + len(word) t.append(word) for word in s: offset += len(word) + 1 if offset <= width: t.append(' ') else: t.append('\n') offset = indent + len(word) t.append(word) return ''.join(t) # Auxiliary functions for indentation and word wrapping def indent_width(indent, tabsize=tabsize): """Calculate width of indentation.""" if indent.startswith('\t'): width = len(indent) indent = indent.lstrip('\t') width -= len(indent) width *= tabsize width += len(indent) else: width = len(indent) return width indent_width = staticmethod(indent_width) def new_offset(s, offset=0): """Calculate new offset after appending a string.""" n = s.rfind('\n') if n < 0: offset += len(s) else: offset = Format.indent_width(s[n+1:]) return offset new_offset = staticmethod(new_offset) # create some predefined serialization formats... output_formats = { 'default': Format(no_empty_lines=True), 'straight': Format(), 'compact': Format(simple_whitespace=True), 'newlines': Format(simple_whitespace=True, indent=''), 'pretty': Format(simple_whitespace=True, indent='\t'), 'wrap': Format(wrap=True, indent=''), 'nice': Format(no_empty_lines=True, nice=True), 'ugly': Format(no_empty_lines=True, ugly=True), 'named': Format(no_empty_lines=True, named=True), 'compact+named': Format(simple_whitespace=True, named=True), 'newlines+named': Format(simple_whitespace=True, indent='', named=True), 'pretty+named': Format(simple_whitespace=True, indent='\t', named=True), 'wrap+named': Format(wrap=True, indent='', named=True), 'compact+nice': Format(simple_whitespace=True, nice=True), 'newlines+nice': Format(simple_whitespace=True, indent='', nice=True), 'pretty+nice': Format(simple_whitespace=True, indent='\t', nice=True), 'wrap+nice': Format(wrap=True, indent='', nice=True), 'nice+named': Format(no_empty_lines=True, nice=True, named=True), 'compact+named+nice': Format(simple_whitespace=True, nice=True, named=True), 'newlines+named+nice': Format(simple_whitespace=True, indent='', nice=True), 'pretty+named+nice': Format(simple_whitespace=True, indent='\t', nice=True, named=True), 'wrap+named+nice': Format(wrap=True, indent='', nice=True, named=True), } PK0C8qW kid/util.pyc; ]PFc@sidZdZdZdZdZdZdklZdefdYZ d Z d d Z d Z d S(sUtility functions for Kid.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT (s splittypesQuickTextReadercBs;tZdZdZdZedZddZRS(NcCs1||_t|i|_d|_t|_dS(Ni(stextsselfslenspossNoneslines(sselfstext((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pys__init__s  ccs\xUnoM|itjo|iit|_n|i oPn|iidVq WdS(Nii(sselfslinessNonestexts splitlinessTruespop(sself((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pys__iter__s cCs&t|_d|_|_t|_dS(Ni(sNonesselfstextsposslenslines(sself((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pyscloses cCs|tj oPyt|}Wn t}q]Xd|jo |ijn o t}q]n|i}|tjo|i|_|i|SnD|i|7_|i|ijo|i|_n|i||i!SdS(Ni(ssizesNonesintsselfslensposstext(sselfssizespos((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pysread$s  "   icCs|o4|djo|i||_qM|i|7_n||_t|_|idjo d|_n$|i|ijo|i|_nd}d}dS(NiicCs |iSdS(N(sselfspos(sself((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pystellEscCsY|i o|it|_n|id7_|i o tn|iidSdS(Nii(sselfslinenos splitlinessTruesliness StopIterationspop(sself((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pysnextHs    ( swhencesselfslensoffsetspossNoneslinesstellsnext(sselfsoffsetswhencesnextstell((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pysseek7s     (s__name__s __module__s__init__s__iter__sclosesNonesreadsseek(((s,build/bdist.darwin-8.0.1-x86/egg/kid/util.pysQuickTextReaders     cCsBx;|D]3}|djoqq|djotSqtSqWdS(snSniff text to see if it looks like XML. Return True if text looks like XML, otherwise return False. s s 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=False) # 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(EX_USAGE) 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__ stderr.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(EX_USAGE) if __name__ == '__main__': main() PK0C83''kid/server.pyc; \PFc@sdZdZdZdZdZdZdkZdkl Z dk l Z d k l Z d klZd klZd d gZdZdZd e fdYZd e fdYZ eee ddZdZedjo endS(sKid-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: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s$Christoph Zwerschke (cito@online.de)s#Copyright 2005, Christoph Zwerschkes8MIT N(sunquote(s HTTPServer(sSimpleHTTPRequestHandler(s FieldStorage(s load_templates HTTPServersHTTPRequestHandlers localhosti@cBs>tZdZdZdZdZddgZdZRS(sComplete 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/|io|in|idddS(s3Serve a POST request implemented for Kid templates.isCan only POST to Kid templatesN(sselfsis_kidsrun_kids send_error(sself((s.build/bdist.darwin-8.0.1-x86/egg/kid/server.pysdo_POSTPs cCs,|io|iSnti|SdS(s1Version of send_head that supports Kid templates.N(sselfsis_kidsrun_kidsSimpleHTTPRequestHandlers send_head(sself((s.build/bdist.darwin-8.0.1-x86/egg/kid/server.pys send_headWs cCs|i}|id}|djo"|| ||df\}}nd}x8|iD]-}|i|o||f|_t SqWqWWt SdS(sTest 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.darwin-8.0.1-x86/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| dNs*kid.pull has been superseded by kid.parser(s*( s__doc__s __revision__s__date__s __author__s __copyright__s __license__swarningsswarnsDeprecationWarnings kid.parser(s __copyright__s __revision__s __license__swarningss __author__s__date__((s,build/bdist.darwin-8.0.1-x86/egg/kid/pull.pys?s PK96ce"11kid/release.py#!/usr/bin/env python # -*- coding: utf-8 -*- """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: 497 $" __date__ = "$Date: 2007-07-16 14:48:50 -0400 (Mon, 16 Jul 2007) $" version = "0.9.6" 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 = '\n'.join(__doc__.splitlines()[1:]).strip() PK1C8?;))kid/serialization.pyc; ]PFc@sdZdZdZdZdZdZdkZyeWn ej odk l ZnXdk l Z l Z lZlZlZlZlZlZdkiZd klZlZlZlZlZlZd klZlZd d d dgZ ei!i"Z#ei$i"Z%hZ&x1ei'i(D] \Z)Z*de*e&e+e)N(sSet(sElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitysraise_serialization_error(sSTARTsENDsTEXTsCOMMENTsPIs _coalesce(sFormatsoutput_formatssdoctypess Serializers XMLSerializersHTMLSerializers&%s;swmls-//WAPFORUM//DTD WML 1.1//ENs'http://www.wapforum.org/DTD/wml_1.1.xmls xhtml-strictshtmls -//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.dtdsxhtml-framesets"-//W3C//DTD XHTML 1.0 Frameset//ENs3http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtds html-strictsHTMLs-//W3C//DTD HTML 4.01//ENs%http://www.w3.org/TR/html4/strict.dtds&-//W3C//DTD HTML 4.01 Transitional//ENs$http://www.w3.org/TR/html4/loose.dtds html-framesets"-//W3C//DTD HTML 4.01 Frameset//ENs'http://www.w3.org/TR/html4/frameset.dtds html-quirksshtml-frameset-quirkscBstZeiZdZZedZeZ eZ e e e e e dZ dZ dZdZe ee dZe ee dZe ee d Ze d Zd ZRS( Nsutf-8sdefaultcCs|tj o ||_n|tj o ||_n|tj o ||_n|tj o ||_n|tj o ||_n|i||_dS(sgInitialize Serializer. You can change the following parameters: encoding: the output encoding src_encoding: the source encoding formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) N(sencodingsNonesselfs src_encodings formattedsinlinesformats _get_format(sselfsencodings src_encodings formattedsinlinesformat((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys__init__As           cCs<|tjo |iSn!t|to t|Sn|SdS(N(sformatsNonesselfs isinstances basestringsoutput_formats(sselfsformat((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys _get_formatZs    cCs |iSdS(N(sselfs formatted(sselfstagname((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys is_formattedbscCs |iSdS(N(sselfsinline(sselfstagname((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys is_inlineescCsy%di|i||||}Wn:tj o.dit |i||||}nX| ot i |}n|SdS(Ns( sjoinsselfsgeneratesstreamsencodingsfragmentsformatstexts TypeErrorstuplesFormatsstrip(sselfsstreamsencodingsfragmentsformatstext((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys serializehs%,c Cst}t|d ot}t|d}nz:|i}x*|i||||D]}||qUWWd|o|inXdS(Nswriteswb(sFalses needs_closedshasattrsfilesTruesopenswritesselfsgeneratesstreamsencodingsfragmentsformatstextsclose( sselfsstreamsfilesencodingsfragmentsformatswrites needs_closedstext((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pyswritess cCsdS(N((sselfsstreamsencodingsfragmentsformat((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pysgeneratescCs7t||i}|o|i||}n|SdS(N(s _coalescesstreamsselfs src_encodingsformats format_stream(sselfsstreamsformat((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys apply_filterssccs|i}|i|if\}}|tj oL|i} |i}|i} |i } |i |i f\}}g}t }n|tj o+|i}|i|if\}}d}nd} d}} x|D]\}}|tjo||7}q|ttfjo|i}| o||| }|tjo'|tj o||||}qqt|}|o ||jo |}n|o%||8}|djo d}qn|tj o#|||||||}nd|jo|ot|d| o(||| }|tj o||||}n|tjo'|tj o||||}qqt|}|o ||jo |}n|o%||8}|djo d}qn|tj o#|||||||}n| |ddjo|d }n| |||}nt|fVndS(s)Apply format to stream. Note that this method is unaware of the serialization of the tags and does only take into account the text inside the stream. So the results may sometimes differ from what you expect when formatting the complete serialized output. iss iiN(&sformatsfilters filter_textsindentswrapsNones indent_liness lstrip_blankss rstrip_blankss lstrip_liness min_levels max_levels indent_levelsFalsesnew_lines wrap_liness indent_widths new_offsetsoffsets formattedstexts last_charsstreamsevsitemsTEXTsSTARTsENDstagslenslevelsTruesCommentsselfs is_inlines is_formattedsappendspop(sselfsstreamsformatstexts filter_texts lstrip_blanksstagswrapsevs last_chars lstrip_liness rstrip_blankss formatteds indent_liness indent_widths wrap_liness max_levelsoffsetsindentsnew_lines min_levels indent_levelslevelsitems new_offset((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys format_streams                                               (s__name__s __module__s namespaces namespacess src_encodingsencodingsoutput_formatssformatsFalses formattedsinlinesNones__init__s _get_formats is_formatteds is_inlines serializeswritesgenerates apply_filterss format_stream(((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys Serializer9s        c BstZeZeZeZeeeeeeeedZdZee edZ eedZ e e Z eedZ e e Z RS(Nc Csti|d|d|d|d||tj o ||_n|tj o ||_ n|tj o ||_ n|tj o ||_ ndS(s'Initialize XMLSerializer. You can change the following parameters: encoding: the output encoding decl: add xml declaration at the beginning (True/False) doctype: add doctype (None, string, tuple) entity_map: use named entities for output (True/False or mapping) namespaces: mapping of namespaces formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) sencodingsformats formattedsinlineN( s Serializers__init__sselfsencodingsformats formattedsinlinesdeclsNonesdoctypes entity_maps namespaces( sselfsencodingsdeclsdoctypes entity_maps namespacess formattedsinlinesformat((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys__init__s       cCstSdS(N(sTrue(sselfs item_name((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pyscan_be_empty_element*sccs|i}|i}|p|ipd}|i}|i|}|o[|itj o |i}n|itj o |i}n|itj o |i}qn|tjo t }n|t jo t}nt |t ot |i}nti} ti}t}t|}t|i} | o6|o d|Vn|tj ot|dVqcnt}x)|i||D]\} }| ttfjo |it joq|nA| t!jo3|tj odi"||g}q||}q|n|tjou| tjo<| p!t#i$|p|i%|i o|i&|io!dVt}t}| i'q|ndVn|o| |||Vt}n| tjo|it(jo!d|ii)|Vt*}q|q|it+jo!d|ii)|Vt,}q|q| i-} | i/t|d t| i0|id t}d |i)|VxX|i1i2D]G\}}| i0|d t i)|}|||}d ||fVq_Wx| i-i2D]o\} }| | jp| | |joE|||}| od | i)|}nd}d ||fVqqWn[| tjo|it(t+fjo7| i0|id t}d|i)|V| i'n| }q|W|o|o| |||VndSdS(sSerializes 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 ssremovesdefaultsN(7sselfsdeclsdoctypesencodings entity_maps _get_formatsformatsNonesTruesdefault_entity_mapsFalses isinstances basestringsdoctypess XMLSerializers escape_cdatas escape_attribslastevsitersstreamsNamespaceStacks namespacessnamessfragmentsserialize_doctypestexts apply_filterssevsitemsSTARTsENDstagsFragmentsTEXTsjoinsFormatsstrips is_formattedscan_be_empty_elementspopsCommentsencodesCOMMENTsProcessingInstructionsPIscurrents current_namesspushsqnamesattribsitemssksvsprefixsuri(sselfsstreamsencodingsfragmentsformatsdeclstextsqnamesurisprefixs current_namessnamessevs escape_cdatasksdoctypesitemsvslastevs entity_maps escape_attrib((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pysgenerate-s               #   L      # cCsyl|o=y|i|}WqGtj ot|d|SqGXn|idd}|idd}Wn#ttfj ot |nX|SdS(sEscape character data.sentitiess&s&sVscCs |iS(N(ssslower(ss((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pysXscs|ddjo |didd\}}nt|f\}}|o |tjoi|dt}n|}o|}n|||fSdS(Nis{is}sdefault( stagssplitsuris localnamesNones xhtml_urisnamessqnamesFalses transpose(stagsqnamesuris localname(s transposesnames(s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys grok_name^s s s ssremoveissiN(:sselfsdoctypesencodings entity_maps transposes inject_types _get_formatsformatsNonesTruesdefault_entity_mapsFalses isinstances basestringsdoctypesscallablesHTMLSerializers escape_cdatas escape_attribsNamespaceStacks namespacessnamess grok_namescurrentsstacksitersstreamsfragmentsserialize_doctypesinject_meta_content_types apply_filterssevsitemsTEXTs is_escapesescapesSTARTstagsCommentstextsencodesProcessingInstructionsFragmentspushsqnameslowersappendsattribsitemssattrssksvsqslqsis_boolean_attributesENDspopscan_be_empty_element(sselfsstreamsencodingsfragmentsformatsqnamestags escape_attribsescapesevs escape_cdatasstackscurrentsattrsslqs grok_names transposes inject_typesksdoctypesqsitemsvs entity_mapsnames((s transposesnamess5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pysgenerate4s                          +&   cCsyw|o=y|i|}WqGtj ot|d|SqGXn|o(|idd}|idd}nWn#tt fj ot |nX|SdS(sEscape character data.sentitiess&s&sq>Wq+W|o |t jodSn|o|SntSdS(sFigure out prefix given a URI.sxmlsN( surisxml_urisNones is_defaultsprefixsselfsstacksnamessitemsspsusdefaultsTrue(sselfsurisdefaults is_defaultspsprefixsusnames((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pysresolve_prefixs,      cCsO|djotSnx/|iD]$}|i|}|o|SqqWtSdS(sFigure out URI given a prefix.sxmlN(sprefixsxml_urisselfsstacksnamessgetsurisNone(sselfsprefixsurisnames((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys resolve_uri s   cCs't|to |i}n|ddjo|Sn|didd\}}|i||}|t jo|i i |}|t j o||i|iss(s isinstancesdoctypes basestringslen(sdoctype((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pysserialize_doctypeFs  (6s__doc__s __revision__s__date__s __author__s __copyright__s __license__shtmlentitydefsssets NameErrorssetssSets kid.elementsElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitysraise_serialization_errors kid.namespaces namespaces kid.parsersSTARTsENDsTEXTsCOMMENTsPIs _coalesces kid.formatsFormatsoutput_formatss__all__sxmlsurisxml_urisxhtmls xhtml_urisdefault_entity_mapscodepoint2namesitemssksvsunichrsdoctypessobjects Serializers XMLSerializers HTMLBasedsHTMLSerializersXHTMLSerializersPlainSerializersNamespaceStacksserialize_doctype('s xhtml_urissetsXHTMLSerializers encode_entitysTEXTsraise_serialization_errorsPlainSerializers XMLSerializers _coalescesCOMMENTs __revision__s__all__sFormatsFragments namespacesHTMLSerializersPIsENDsdoctypess __license__sNamespaceStacksserialize_doctypesxml_urishtmlentitydefss __author__sSTARTs namespacessdefault_entity_mapsElements SerializersComments __copyright__sProcessingInstructionsoutput_formatssksQNames__date__s HTMLBasedsv((s5build/bdist.darwin-8.0.1-x86/egg/kid/serialization.pys?s< 7 +   N# TPK0C8gVVkid/__init__.pyc; \PFc@sdZdZdZdklZeiZeiZei Z ei Z ei ZdkZdkZeidjp tddklZlZdklZd klZlZd klZd klZlZl Z l!Z!l"Z"d k#l$Z$l%Z%l&Z&l'Z'd k(l)Z)dk*l+Z+l,Z,l-Z-l.Z.l/Z/dk0l1Z1l2Z2dk3i4Z4ddddddddddddddddd d!d"d#d$d%d&gZ5ei6a7e8e8d'Z9e8d(Z:ei;i<d)oe9ei;i<d*nei;i<d+o$e9ei;i<d*ei;d+ne8d,Z=d-e>e8he8e8d.Z?hd/e-d0e><d1e-d0e>d2d1<d3e/d0e@d2d3<d4e/d0e@d2d4<d5e/d0e@d2d5<d6e.d2d6<d7e.d2d7<d8e.d2d8<d9e.d2d9<d:e.d2d:<d;e.d2d6d<e><d=e.d2d7d<e><d>e.d2d8d<e><d?e.d2d9d<e><d@e.d2d:d<e><dAe,s s KID_IMPORTsKID_IMPORT_EXTsKID_IMPORT_PATHcCsbtt|}|id}x!|dD]}t||}q-W|o ||_n|SdS(sImport 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. s.iN( s enable_imports __import__snamesmodssplits componentsscompsgetattrsencoding(snamesencodings componentsscompsmod((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysimport_templateLs   sc Cst|to3t|ot|}d} qOt}|} n |}d} dki } | djot i | } | o)t id| dit ifn| } | i|| }tii|otii|Sqndki}| djo|i|| ||}nF|i| dtd|d|} | id|d t!i"id }| i#||| d |d |d |} | SdS(sBypass 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. entity_map Entity map to be used when parsing the template. exec_module If you want full control over how the template module is executed, you can provide this callable that will be called with the template module and the code to be executed as parameters, after the code has been compiled and the module has been created. sNs %s (in %s)s, sforcesencodings entity_maps dump_codes dump_sources KID_OUTPUT_PYsstoresnss exec_module('s isinstancesfiles basestrings xml_sniffsQuickTextReadersfosfilenamesNones kid.importersimporterspathsfinds abs_filenames template_utilsTemplateNotFoundsjoinspathssget_template_namesnamessyssmodulesshas_keysgets kid.compilerscompilerscompilesencodings entity_mapscodesKidFilesFalsestemplatescachesossenvirons_create_modulesnss exec_modulesmod(sfilesnamescachesencodingsnss entity_maps exec_modulescodesfosmodsfilenamesimporterstemplates abs_filenamescompiler((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys load_templateis8      )   sxmlsdeclswmlsdoctypes xhtml-strictsxhtmlsxhtml-framesets html-strictshtmls html-framesets html-quirksshtml-frameset-quirkss HTML-stricts transposesHTMLs HTML-framesets HTML-quirkssHTML-frameset-quirkssplaincKs|ot|d|}n{|tj ot|d|d|}nR|tj o5tt|d|pt t |d|}nt i dy||i _Wn"tj ot idnX|i |SdS(sGet 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=True)`` 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. sencodingsnames*Must specify one of name, file, or source.s"Template could not be initialized.N(snamesimport_templatesencodingsmodsfilesNones load_templatessourcesQuickTextReadershexsids template_utils TemplateErrorsTemplatesmodules ExceptionsTemplateImportErrorskw(sfilessourcesnamesencodingskwsmod((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysTemplates   )cBstZdZedZdZeeeedZeeeedZ eeeedZ dZ dZ dZ d Zd Zd Zd Zegd ZdZdZdZdZedZRS(sBase 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. sxmlcOsax5|D]-}tt|otid|qqW|ii|t g|_ g|_ dS(s Initialize a template with instance attributes specified by keyword arguments. Keyword arguments are available to the template using self.var notation. s'Keyword argument %r is a reserved name.N( skwskshasattrs BaseTemplates template_utilsTemplateAttrsErrorsselfs__dict__supdatestransform_filters_filterss_layout_classes(sselfsargsskwsk((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys__init__s cCsV|i|}y|i|||||SWn#t j ot d|i nXdS(s_ 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 True 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. smoduleN( sselfs_get_serializersoutputs serializerswritesfilesencodingsfragmentsformats Exceptionsraise_template_errors __module__(sselfsfilesencodingsfragmentsoutputsformats serializer((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pyswrites cCsS|i|}y|i||||SWn#tj ot d|i nXdS(sw 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 True 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)] smoduleN( sselfs_get_serializersoutputs serializers serializesencodingsfragmentsformats Exceptionsraise_template_errors __module__(sselfsencodingsfragmentsoutputsformats serializer((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys serializes cCsS|i|}y|i||||SWn#tj ot d|i nXdS(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 True 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. smoduleN( sselfs_get_serializersoutputs serializersgeneratesencodingsfragmentsformats Exceptionsraise_template_errors __module__(sselfsencodingsfragmentsoutputsformats serializer((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysgenerate/s cCst|iSdS(N(sitersselfs transform(sself((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys__iter__IscCs|iSdS(N(sselfs serialize(sself((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys__str__LscCst|idddSdS(Nsencodingsutf-16(sunicodesselfs serialize(sself((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys __unicode__OscCsdS(N((sself((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys initializeRscCs3|itt|i|i}|SdS(s4Returns an iterator over the items in this template.N(sselfs initializes ElementStreams _coalescescontents_get_assume_encodingsstream(sselfsstream((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pyspullUs  cCsgSdS(s^Generate events for this template. Compiled templates implement this method. N((sself((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys_pull]scCsdkl}|i}t||i}|ixS|D]K}|i i do ||jo%|i d||i d|Sq<q<W|i SdS(N(sgetmroslayouti(sinspectsgetmrosselfs_layout_classessvisitedslists __class__smrosreversescs__dict__shas_keysinserts_pull(sselfscsmrosvisitedsgetmro((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pyscontentds    cCs|tjo|i}nst|to3t|ot|dt}qt |}n0t |dot |}nt i |}x$||iD]}|||}qW|SdS(s. Execute the template and apply any match transformations. If stream is specified, it must be one of the following: Element A kid.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. sfragmentstagN(sstreamsNonesselfspulls isinstances basestrings xml_sniffsXMLsFalsesdocumentshasattrs ElementStreamsensuresfilterss_filterssf(sselfsstreamsfilterssf((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys transformos  cCsy |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((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys_get_match_templatess   cCs<|tjo |iSn!t|to t|Sn|SdS(N(s serializersNonesselfs isinstances basestringsoutput_methods(sselfs serializer((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys_get_serializers    cCs#t|do |iSntSdS(Nsassume_encoding(shasattrsselfsassume_encoding(sself((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys_get_assume_encodings cCst||SdS(N(shasattrsselfsname(sselfsname((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysdefinedscCst|||SdS(N(sgetattrsselfsnamesdefault(sselfsnamesdefault((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysvalue_ofs(s__name__s __module__s__doc__soutput_methodss serializers__init__sNonesFalseswrites serializesgenerates__iter__s__str__s __unicode__s initializespulls_pullscontents transforms_get_match_templatess_get_serializers_get_assume_encodingsdefinedsvalue_of(((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys BaseTemplates&          !    s TemplatePathcBsMtZdZedZdZddZdZdZedZ RS(s%Finding templates on a list of paths.cCs{t|to|iti}n|tjo g}n|itig|_x|D]}|i|q`WdS(sInitialize with path list.N( s isinstancespathss basestringssplitsosspathsepsNonesappendsgetcwdsselfspath(sselfspathsspath((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys__init__s   cCs,tiitiitii|SdS(sNormalize path.N(sosspathsabspathsnormpaths expanduser(sselfspath((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys _cleanse_pathsicCs:|i|}||ijo|ii||ndS(s)Insert path to list if not already there.N(sselfs _cleanse_pathspathspathssinsertspos(sselfspathspos((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysinsertscCs7|i|}||ijo|ii|ndS(s)Append path to list if not already there.N(sselfs _cleanse_pathspathspathssappend(sselfspath((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysappendscCsQ|i|}gi}|iD]!}||jo||q q ~|_dS(sRemove path from list.N(sselfs _cleanse_pathspathsappends_[1]spathssp(sselfspaths_[1]sp((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysremovescCstii|}|otii|g}ng}x|i|D]p}tii||}tii |o|Sn|i t  o)|t 7}tii |o|SqqFqFWdS(s(Find file relative to path list and rel.N( sosspathsnormpathsrelsdirnamesselfspathsspsjoinsexistssendswithsKID_EXT(sselfspathsrelsp((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pysfinds ( s__name__s __module__s__doc__sNones__init__s _cleanse_pathsinsertsappendsremovesfind(((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys TemplatePaths     (Gs__doc__s __revision__s__date__skidsreleasesversions __version__sauthors __author__semails __email__s copyrights __copyright__slicenses __license__ssyssoss hexversionsAssertionErrorskid.utils xml_sniffsQuickTextReaders kid.namespaces Namespaceskid.codewriters KID_XMLNSsraise_template_errors kid.compilersKID_EXTs kid.elementsElements SubElementsCommentsProcessingInstructionsFragments kid.parsers ElementStreamsXMLsdocuments _coalesces kid.filterstransform_filterskid.serializations SerializersPlainSerializers XMLSerializersHTMLSerializersXHTMLSerializers kid.formatsFormatsoutput_formatsskid.template_utils template_utils__all__sgetdefaultencodingsassume_encodingsNones enable_importsdisable_importsenvironsgetsimport_templatesTrues load_templatesFalsesoutput_methodssTemplatesobjects BaseTemplates TemplatePathspath(,sraise_template_errorsXHTMLSerializers load_templates Namespaces __email__s ElementStreamsTemplatesPlainSerializerstransform_filters XMLSerializersQuickTextReaders _coalesces __revision__s__all__sFormatsFragmentsHTMLSerializersKID_EXTs template_utils xml_sniffsdisable_importsXMLsoutput_methodss __license__s enable_imports __author__ssysspathsElementsdocuments Serializers BaseTemplatesComments __copyright__s __version__sProcessingInstructions KID_XMLNSsoutput_formatss__date__s SubElementsimport_templatesreleasesoss TemplatePath((s0build/bdist.darwin-8.0.1-x86/egg/kid/__init__.pys? sJ        % % K   <W%4PKZ86@(Okid/serialization.py# -*- coding: utf-8 -*- """Infoset serialization formats (XML, XHTML, HTML, etc)""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import htmlentitydefs try: set except NameError: # fallback for Python 2.3 from sets import Set as set from kid.element import Element, Comment, ProcessingInstruction, \ Fragment, QName, namespaces, encode_entity, raise_serialization_error import kid.namespace as namespace from kid.parser import START, END, TEXT, COMMENT, PI, _coalesce from kid.format import Format, output_formats __all__ = ['doctypes', 'Serializer', 'XMLSerializer', 'HTMLSerializer'] # bring in well known namespaces xml_uri = namespace.xml.uri xhtml_uri = namespace.xhtml.uri # This is the default entity map: default_entity_map = {} for k, v in htmlentitydefs.codepoint2name.items(): default_entity_map[unichr(k)] = "&%s;" % v # Some common doctypes. # You can pass doctype strings from here or doctype tuples to Serializers. doctypes = { 'wml': ('wml', "-//WAPFORUM//DTD WML 1.1//EN", "http://www.wapforum.org/DTD/wml_1.1.xml"), 'xhtml-strict': ('html', "-//W3C//DTD XHTML 1.0 Strict//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"), 'xhtml': ('html', "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"), 'xhtml-frameset': ('html', "-//W3C//DTD XHTML 1.0 Frameset//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"), 'html-strict': ('HTML', "-//W3C//DTD HTML 4.01//EN", "http://www.w3.org/TR/html4/strict.dtd"), 'html': ('HTML', "-//W3C//DTD HTML 4.01 Transitional//EN", "http://www.w3.org/TR/html4/loose.dtd"), 'html-frameset': ('HTML', "-//W3C//DTD HTML 4.01 Frameset//EN", "http://www.w3.org/TR/html4/frameset.dtd"), 'html-quirks': ('HTML', '-//W3C//DTD HTML 4.01 Transitional//EN'), 'html-frameset-quirks': ('HTML', "-//W3C//DTD HTML 4.01 Frameset//EN") } class Serializer(object): namespaces = namespace.namespaces src_encoding = encoding = 'utf-8' format = output_formats['default'] formatted = False inline = False def __init__(self, encoding=None, src_encoding=None, formatted=None, inline=None, format=None): """Initialize Serializer. You can change the following parameters: encoding: the output encoding src_encoding: the source encoding formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) """ if encoding is not None: self.encoding = encoding if src_encoding is not None: self.src_encoding = src_encoding if formatted is not None: self.formatted = formatted if inline is not None: self.inline = inline if format is not None: self.format = format self.format = self._get_format(format) def _get_format(self, format): if format is None: return self.format elif isinstance(format, basestring): return output_formats[format] else: return format def is_formatted(self, tagname): return self.formatted def is_inline(self, tagname): return self.inline def serialize(self, stream, encoding=None, fragment=False, format=None): try: text = ''.join(self.generate(stream, encoding, fragment, format)) except TypeError: # workaround for bug 905389 in Python < 2.5 text = ''.join(tuple( self.generate(stream, encoding, fragment, format))) if not fragment: text = Format.strip(text) return text def write(self, stream, file, encoding=None, fragment=False, format=None): needs_closed = False if not hasattr(file, 'write'): needs_closed = True file = open(file, 'wb') try: write = file.write for text in self.generate(stream, encoding, fragment, format): write(text) finally: # only close a file if it was opened locally if needs_closed: file.close() def generate(self, stream, encoding=None, fragment=False, format=None): pass def apply_filters(self, stream, format=None): stream = _coalesce(stream, self.src_encoding) if format: stream = self.format_stream(stream, format) return stream def format_stream(self, stream, format): """Apply format to stream. Note that this method is unaware of the serialization of the tags and does only take into account the text inside the stream. So the results may sometimes differ from what you expect when formatting the complete serialized output. """ filter_text = format.filter indent, wrap = format.indent, format.wrap if indent is not None: indent_lines = format.indent_lines lstrip_blanks = format.lstrip_blanks rstrip_blanks = format.rstrip_blanks lstrip_lines = format.lstrip_lines min_level, max_level = format.min_level, format.max_level indent_level = [] new_line = False if wrap is not None: wrap_lines = format.wrap_lines indent_width, new_offset = format.indent_width, format.new_offset offset = 0 formatted = 0 text = last_char = '' for ev, item in stream: if ev == TEXT: text += item else: if ev in (START, END): tag = item.tag if not formatted: text = filter_text(text, last_char) if indent is None: if wrap is not None: text = wrap_lines(text, wrap, offset) else: level = len(indent_level) if max_level and level > max_level: level = max_level if min_level: level -= min_level if level < 0: level = 0 if wrap is not None: text = wrap_lines(text, wrap, offset, indent_width(level*indent)) if '\n' in text and indent_level: indent_level[-1] = True if new_line: if lstrip_blanks(text)[:1] != '\n': text = '\n' + lstrip_blanks(text) offset = 0 new_line = False if tag == Comment or not self.is_inline(tag): if ev == START: if indent_level: if rstrip_blanks(text)[-1:] != '\n': text = rstrip_blanks(text) + '\n' text = indent_lines(text, level*indent) indent_level[-1] = True elif text: text = lstrip_lines(text) if tag != Comment \ and not self.is_formatted(tag): indent_level.append(False) else: if indent_level: if indent_level.pop(): if rstrip_blanks(text)[-1:] == '\n': text = rstrip_blanks(text)[:-1] text = indent_lines(text, level*indent) text = rstrip_blanks(text) + '\n' level = len(indent_level) if max_level and level > max_level: level = max_level if min_level: level -= min_level if level < 0: level = 0 text += level*indent elif text: text = lstrip_lines(text) new_line = True elif text: text = indent_lines(text, level*indent) if tag == Comment or self.is_formatted(tag): if ev == START: formatted += 1 elif formatted: formatted -= 1 new_line = True yield TEXT, text if wrap is not None: offset = new_offset(text, offset) last_char = text[-1:] text = '' yield ev, item if text: if not formatted: text = filter_text(text, last_char) if wrap is not None: text = wrap_lines(text, wrap, offset) if indent is None: if wrap is not None: text = wrap_lines(text, wrap, offset) else: level = len(indent_level) if max_level and level > max_level: level = max_level if min_level: level -= min_level if level < 0: level = 0 if wrap is not None: text = wrap_lines(text, wrap, offset, indent_width(level*indent)) if rstrip_blanks(text)[-1:] == '\n': text = text[:-1] text = indent_lines(text, level*indent) yield TEXT, text class XMLSerializer(Serializer): decl = True doctype = None entity_map = None def __init__(self, encoding=None, decl=None, doctype=None, entity_map=None, namespaces=None, formatted=None, inline=None, format=None): """Initialize XMLSerializer. You can change the following parameters: encoding: the output encoding decl: add xml declaration at the beginning (True/False) doctype: add doctype (None, string, tuple) entity_map: use named entities for output (True/False or mapping) namespaces: mapping of namespaces formatted: whether all tags should be considered formatted inline: whether all tags should be considered inline format: format to be applied (string or instance of Format) """ Serializer.__init__(self, encoding=encoding, format=format, formatted=formatted, inline=inline) if decl is not None: self.decl = decl if doctype is not None: self.doctype = doctype if entity_map is not None: self.entity_map = entity_map if namespaces is not None: self.namespaces = namespaces def can_be_empty_element(self, item_name): return True def generate(self, stream, encoding=None, fragment=False, format=None): """Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. """ decl = self.decl doctype = self.doctype encoding = encoding or self.encoding or 'utf-8' entity_map = self.entity_map format = self._get_format(format) if format: if format.decl is not None: decl = format.decl if format.doctype is not None: doctype = format.doctype if format.entity_map is not None: entity_map = format.entity_map if entity_map == True: # if True, use default HTML entity map entity_map = default_entity_map elif entity_map == False: entity_map = None if isinstance(doctype, basestring): # allow doctype strings doctype = doctypes[self.doctype] escape_cdata = XMLSerializer.escape_cdata escape_attrib = XMLSerializer.escape_attrib lastev = None stream = iter(stream) names = NamespaceStack(self.namespaces) if not fragment: if decl: yield '\n' % encoding if doctype is not None: yield serialize_doctype(doctype) + '\n' text = None for ev, item in self.apply_filters(stream, format): 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 (Format.strip(text) or self.is_formatted(item.tag))) \ and self.can_be_empty_element(item.tag): yield ' />' lastev = END text = None names.pop() continue yield ">" if text: yield escape_cdata(text, encoding, entity_map) 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: current_names = names.current names.push(namespaces(item, remove=True)) qname = names.qname(item.tag, default=True) yield "<" + qname.encode(encoding) for k, v in item.attrib.items(): k = names.qname(k, default=False).encode(encoding) v = escape_attrib(v, encoding) yield ' %s="%s"' % (k, v) for prefix, uri in names.current.items(): if prefix not in current_names \ or current_names[prefix] != uri: v = escape_attrib(uri, encoding) if prefix: k = 'xmlns:' + prefix.encode(encoding) else: k = 'xmlns' yield ' %s="%s"' % (k, v) elif ev == END and item.tag not in ( Comment, ProcessingInstruction): qname = names.qname(item.tag, default=True) yield "" % qname.encode(encoding) names.pop() lastev = ev if fragment and text: yield escape_cdata(text, encoding, entity_map) return def escape_cdata(text, encoding=None, entity_map=None): """Escape character data.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) text = text.replace("&", "&") text = text.replace("<", "<") except (TypeError, AttributeError): raise_serialization_error(text) return text escape_cdata = staticmethod(escape_cdata) def escape_attrib(text, encoding=None, entity_map=None): """Escape attribute value.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) text = text.replace("&", "&") text = text.replace("<", "<") text = text.replace("\"", """) except (TypeError, AttributeError): raise_serialization_error(text) return text escape_attrib = staticmethod(escape_attrib) class HTMLBased(object): """Mixin class for HTML based serializers.""" inject_type = None empty_elements = set([ 'area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param']) formatted_elements = set([ 'code', 'kbd', 'math', 'pre', 'script', 'textarea']) inline_elements = set(['a', 'abbr', 'acronym', 'b', 'basefont', 'bdo', 'big', 'br', 'cite', 'code', 'dfn', 'em', 'font', 'i', 'img', 'input', 'kbd', 'label', 'q', 's', 'samp', 'select', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'textarea', 'tt', 'u', 'var']) def can_be_empty_element(self, tag): return self.tagname(tag) in self.empty_elements def is_formatted(self, tag): return self.tagname(tag) in self.formatted_elements def is_inline(self, tag): return self.tagname(tag) in self.inline_elements def is_escape(self, tag): return self.tagname(tag) not in self.noescape_elements def inject_meta_content_type(self, stream, encoding): """Injects a meta tag for the content-type.""" return self.inject_meta_tags(stream, [{'http-equiv': 'content-type', 'content': 'text/html; charset=%s' % encoding}]) def inject_meta_tags(self, stream, taglist): """Injects meta tags at the start of the head section. If meta tags already exist at that position, they are kept. Expects a list of meta-tag attributes with content keys. The attribute names and values must be given in lower case. """ done = False meta_tag = None for ev, item in stream: if not done: if ev in (START, END): tag = self.tagname(item.tag) if meta_tag: if item.tag == meta_tag: if ev == START: for attributes in taglist: for attrib, value in item.items(): attrib = attrib.lower() if attrib == 'content': continue if attrib not in attributes: break value = value.lower() if attributes[attrib] != value: break else: # that meta tag exists already attributes['content'] = None break else: for attributes in taglist: if attributes['content'] is None: continue meta_item = Element(meta_tag, **attributes) yield START, meta_item yield END, meta_item yield TEXT, '\n' done = True elif tag == 'head' and ev == START: meta_tag = item.tag[:-4] + 'meta' yield ev, item class HTMLSerializer(HTMLBased, Serializer): doctype = doctypes['html'] transpose = False inject_type = True entity_map = None 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=False, inject_type=None, entity_map=None, format=None): """Initialize HTMLSerializer. You can change the following parameters: encoding: the output encoding doctype: add doctype (None, string, tuple) transpose: alter tag names (None, True/False, callable) inject_type: inject content type (True/False) entity_map: use named entities for output (True/False or mapping) format: format to be applied (string or instance of Format) """ Serializer.__init__(self, encoding=encoding, format=format) if doctype is not None: self.doctype = doctype self.transpose = transpose if inject_type is not None: self.inject_type = inject_type if entity_map is not None: self.entity_map = entity_map def tagname(tag): """Remove namespace from tag and make it lowercase.""" if isinstance(tag, basestring): if tag.startswith('{'): tag = tag.split('}', 1)[-1] tag = tag.lower() return tag tagname = staticmethod(tagname) def is_escape(self, tag): return self.tagname(tag) not in self.noescape_elements def is_boolean_attribute(self, attribute): return attribute in self.boolean_attributes def generate(self, stream, encoding=None, fragment=False, format=None): """Serializes an event stream to bytes of the specified encoding. This function yields an encoded string over and over until the stream is exhausted. """ doctype = self.doctype encoding = encoding or self.encoding or 'utf-8' entity_map = self.entity_map transpose = self.transpose inject_type = self.inject_type format = self._get_format(format) if format: if format.doctype is not None: doctype = format.doctype if format.entity_map is not None: entity_map = format.entity_map if format.transpose is not None: transpose = format.transpose if format.inject_type is not None: inject_type = format.inject_type if entity_map == True: # if True, use default HTML entity map entity_map = default_entity_map elif entity_map == False: entity_map = None if isinstance(doctype, basestring): # allow doctype strings doctype = doctypes[self.doctype] if transpose is not None: if not callable(transpose): if transpose: transpose = lambda s: s.upper() else: transpose = lambda s: s.lower() escape_cdata = HTMLSerializer.escape_cdata escape_attrib = HTMLSerializer.escape_attrib 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_uri: qname = names.qname(tag, default=False) else: qname = localname if transpose: qname = transpose(qname) return uri, localname, qname current = None stack = [current] stream = iter(stream) if not fragment and doctype is not None: yield serialize_doctype(doctype) + '\n' if inject_type and encoding: stream = self.inject_meta_content_type(stream, encoding) for ev, item in self.apply_filters(stream, format): if ev == TEXT and item: escape = self.is_escape(current) yield escape_cdata(item, encoding, entity_map, escape) elif ev == START: if item.tag == Comment: yield "" % item.text.encode(encoding) continue elif item.tag == ProcessingInstruction: yield "" % item.text.encode(encoding) continue elif item.tag == Fragment: continue else: names.push(namespaces(item, remove=True)) tag = item.tag qname = grok_name(tag)[2] # 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: q = grok_name(k)[2] lq = q.lower() if lq == 'xml:lang': continue if self.is_boolean_attribute(lq): # 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, entity_map)) yield ">" elif ev == END and item.tag not in ( Comment, ProcessingInstruction, Fragment): current = stack.pop() if not self.can_be_empty_element(current): tag = item.tag qname = grok_name(tag)[2] yield "" % qname.encode(encoding) current = stack[-1] names.pop() def escape_cdata(text, encoding=None, entity_map=None, escape=True): """Escape character data.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) if escape: text = text.replace("&", "&") text = text.replace("<", "<") except (TypeError, AttributeError): raise_serialization_error(text) return text escape_cdata = staticmethod(escape_cdata) def escape_attrib(text, encoding=None, entity_map=None): """Escape attribute value.""" try: if encoding: try: text = text.encode(encoding) except UnicodeError: return encode_entity(text, entities=entity_map) text = text.replace("&", "&") text = text.replace("\"", """) except (TypeError, AttributeError): raise_serialization_error(text) return text escape_attrib = staticmethod(escape_attrib) class XHTMLSerializer(HTMLBased, XMLSerializer): doctype = doctypes['xhtml'] inject_type = True def __init__(self, encoding='utf-8', decl=None, doctype=None, inject_type=None, entity_map=None, namespaces=None, format=None): """Initialize XHTMLSerializer.""" XMLSerializer.__init__(self, encoding=encoding, decl=decl, doctype=doctype, entity_map=entity_map, namespaces=namespaces, format=format) if inject_type is not None: self.inject_type = inject_type def tagname(tag): """Remove namespace from tag.""" if isinstance(tag, basestring) and tag.startswith('{%s}' % xhtml_uri): tag = tag.split('}', 1)[-1] return tag tagname = staticmethod(tagname) def generate(self, stream, encoding=None, fragment=False, format=None): encoding = encoding or self.encoding or 'utf-8' inject_type = self.inject_type format = self._get_format(format) if format: if format.inject_type is not None: inject_type = format.inject_type if inject_type and encoding: stream = self.inject_meta_content_type(stream, encoding) return XMLSerializer.generate(self, stream, encoding=encoding, fragment=fragment, format=format) class PlainSerializer(Serializer): def generate(self, stream, encoding=None, fragment=False, format=None): """Generate only the text content.""" encoding = encoding or self.encoding or 'utf-8' for ev, item in self.apply_filters(stream, format): 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): names = self.stack.pop(0) if self.stack: self.current = self.stack[0] return names def resolve_prefix(self, uri, default=True): """Figure out prefix given a URI.""" if uri == xml_uri: return 'xml' # first check if the default is correct is_default = None prefix = None for names in self.stack: for p, u in names.items(): if default and is_default is None and not p: # this is the current default namespace is_default = (u == uri) if (default and is_default) or prefix: break if u == uri and p: prefix = p if is_default is not None: break if default and is_default == True: return '' elif prefix: return prefix else: return None def resolve_uri(self, prefix): """Figure out URI given a prefix.""" if prefix == 'xml': return xml_uri for names in self.stack: uri = names.get(prefix) if uri: return uri return None def qname(self, cname, default=False): 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 serialize_doctype(doctype): if isinstance(doctype, basestring): return doctype elif len(doctype) == 1: return '' % doctype elif len(doctype) == 2: return '' % doctype else: return '' % doctype PK0C8.{{kid/codewriter.pyc; \PFc@sNdZdZdZdZdZdZdkZdkZdkl Z dk l Z l Z d k lZlZd klZlZlZlZlZlZlZd klZlZlZd d ddgZdZdZeeZedZ edZ!edZ"edZ#edZ$edZ%edZ&edZ'edZ(edZ)edZ*edZ+edZ,dZ-dZ.d Z/e0e0e0d!Z1e0e0d"Z2e0e0e0d#Z3d$Z4e0e0e0d%Z5d&e6fd'YZ7d(e8fd)YZ9ei:d*ei;Z<d+Z=d,e6fd-YZ>d.e6fd/YZ?d0Z@d1d2ZAdS(3s/KidWriter Write Python source code from XML. s $Rev: 496 $s5$Date: 2007-07-15 18:14:35 -0400 (Sun, 15 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT N(ssplitext(s extract_tbsformat_exception_only(s __version__s Namespace(sdocumentsSTARTsENDsTEXTsXML_DECLsDOCTYPEsLOCATION(s namespacessCommentsProcessingInstructions KID_XMLNSs KID_PREFIXskidnssraise_template_errorshttp://purl.org/kid/ns#spysforsifsdefsslotscontentsreplacesmatchsstripsattrssextendsslayoutsomitsrepeatspythonskidcCs8t|d|d|d|}t|||iSdS(Nsencodingsfilenames entity_map(sdocumentssourcesencodingsfilenames entity_mapsdocs KidWritersparse(ssourcesencodingsfilenames entity_mapsdoc((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysparse3s cCs8t|d}zt||||SWd|iXdS(sParse the file specified. filename -- the name of a file. fp -- an optional file like object to read from. If not specified, filename is opened. srbN(sopensfilenamessourcesparsesencodings entity_mapsclose(sfilenamesencodings entity_mapssource((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pys parse_file8s c Cs|oyht|d}zGt|d|d|d|dt}t ||||}|i SWd|i XWqt j oqXndS(Nsrbsencodingsfilenames entity_mapsdebug(slinenosopensfilenamessourcesdocumentsencodings entity_mapsTruesdocs KidWriterswritersparsescloses Exception(sfilenamesencodings entity_mapslinenoswriterssourcesdoc((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pyserror_locationFs csHi}d|fdY}|i|_|i|_|SdS(s,Get exception with additional error message.sTemplateExceptionErrorcs#tZdZdZRS(NcsIxBtD]4}|id ot||t|q q WdS(Ns_(sdirserrorsargs startswithssetattrsselfsgetattr(sselfsarg(serror(s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pys__init__Xs cstdSdS(Ns (sstrserrors add_message(sself(s add_messageserror(s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pys__str__\s(s__name__s __module__s__init__s__str__((serrors add_message(s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysTemplateExceptionErrorWs N(serrors __class__sErrorsTemplateExceptionErrors__name__s __module__(serrors add_messagesErrorsTemplateExceptionError((serrors add_messages2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysTemplateExceptionErrorTs    cCs7|o |o| o_|tijoKti|}t|do |i}nt|do |i}qqqun| p |djon| o d}nt|dd}ti d \}} |t jo|| ifg} n!tti d} | ix| D]}||djp |d oqnt||d |d}| oqn|\\}} \}} ||joqng}| o ||jo|d8}d } n||jo|id || | jo|id | q| o=| | jo|id | | fqj|id| q| djo|id| qna|id|| o|id | n|id|| djo|id | n|odi|}y~|d8}|d8}ggf\}}xtt|D]\} }| |joq n|i"}|oP| |jo| o>|| i"o)|| i#}|od|}qqn| |jo | djoe|| i#o@| djo d} n|| i"}|o|d7}q q$|| i"}nt$|djo|d i"d}n|oIt$|djo|i| |i|q| |d<||dsutf-8is.pyiislinenois on line %ds , column %ds between columns %d and %ds after column %ds before column %dsbetween line %ds and line %dss... iKs ...iOiserror line not founds...s:s (cannot acquire source text: %s)s"Error location in template file %rs-Error in code generated from template file %rs N(.smodulesfilenamesencodingssyssmodulessmodshasattrskid_filessplitextspy_filesexc_infosexc_types exc_values SyntaxErrorslinenostbs extract_tbsreversestserror_locationslocations start_lines start_colsend_linesend_colsssappendsjoins error_lines error_texts enumeratesopenslinestextsrstripslstripslens LookupErrorsinserts Exceptionsesstrsformat_exception_onlys isinstancesTemplateExceptionErrors __class__(smodulesfilenamesencodings start_linesexc_types error_lineslocationstextspy_filestbs exc_valuesend_cols start_colslinesmodsesssend_linests error_text((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysraise_template_errorbs                           ) s KidWritercBstZeeedZedddZdZdZdZdZd Z d Z d Z d Z d Z dZdZdZdZdZRS(NcCs||_|pd|_||_d|_||_t|_g|_|i |_ |i |_ |i dd|_ |i |_ g|_g|_dS(Nsutf-8isleveli(sstreamsselfsencodingsfilenamesdepthslinenosNoneslocations locationsscodegens module_codes class_codes expand_codesend_module_codes module_defss inst_defs(sselfsstreamsencodingsfilenameslineno((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pys__init__s       is cCs2|iot||iSnt|||SdS(N(sselfslinenosLocationGeneratorscodesgetlocs CodeGeneratorslevelstab(sselfscodeslevelstab((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pyscodegens cCs |iSdS(N(sselfslocation(sself((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysgetlocsc Cs |i|i|i|ig}||ii7}x|iD]}||i7}qDW||i i7}||i i7}x|i D]}||i7}qW||i i7}|i oD|i d}d|jot|jn otSn||}| otSn|\}}d|jot|ijn otSn|i|}||odpd7}d|jot|ijno|i|}n,|d}|o|d7}n|df}| o||f\}}n||fSndi|SdS(Niiis (sselfsbegins proc_streams module_codesendspartsscodes module_defsscs class_codes expand_codes inst_defssend_module_codeslinenoslensNonespossis_starts locationss start_locsend_locsend_linesjoin( sselfs start_locscsposspartssend_lineslinenosend_locsis_start((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysparsesH      %  ( '  cCs|i}|id|iddtd|iddddd |id d d d ddddd|i}|id|idd|i |id|iddd|i }|iddS(Ns# -*- coding: %s -*-s# Kid template moduleskid_version = %rs kid_file = %rs 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()sdef generate(encoding=encoding, fragment=False, output=None, format=None, **kw): return Template(**kw).generate(encoding=encoding, fragment=fragment, output=output, format=format)sdef serialize(encoding=encoding, fragment=False, output=None, format=None, **kw): return Template(**kw).serialize(encoding=encoding, fragment=fragment, output=output, format=format)sdef write(file, encoding=encoding, fragment=False, output=None, format=None, **kw): return Template(**kw).write(file, encoding=encoding, fragment=fragment, output=output, format=format)sdef initialize(template): passsBaseTemplate = kid.BaseTemplatesdef 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, doctypes( sselfs module_codescodeslinesencodings __version__sfilenames expand_codes start_blocks end_blocksend_module_code(sselfscode((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysbegins<          cCs|iidS(N(sselfs expand_codes end_block(sself((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pysendIsc Cs x|iD]\}}|tjo|itjo|ii}|i doq n||i jo|i i } n |i } |i dp|i dp |ido=t|i}t|tod|}qt|}nt|i}| d|dn|itjod|iijo|iidd \} } n|id f\} } | tttfjo| o|i| qq|io|p|i } | i d | | fd~ nt}||i jo|i t!}|tj o|i"t!=t#|}ng} |i t%}|tj o}|i"t%=t#|}xV|id D]E} | i'd t(| d |i d| d| i|fqnW|i)n| i'd|i*}|i+ddi,| |i d|i }n|i-||i"||tj ox|}|i/dd }|i+d|i ddddddd|dddd |i)|i0i'||}n|i1ot2|i1d |diggi}|dD]}||iq"~}t}x|dD]}|djoq|i}|ddjoPt |t |}|tjp ||jo|}|djoPqqqqSqSW|tj p |djoEgi}|dD]"}||| i||q~|d)n|do|dddj oyt |dddWq6t j oy'di|d}t |ddWq2tj 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((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pys_adjust_python_blocks@B    E!7 (Bs__doc__s __revision__s__date__s __author__s __copyright__s __license__ssyssresos.pathssplitexts tracebacks extract_tbsformat_exception_onlyskids __version__s Namespaces kid.parsersdocumentsSTARTsENDsTEXTsXML_DECLsDOCTYPEsLOCATIONs kid.elements namespacessCommentsProcessingInstructions__all__s 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_fileserror_locationsTemplateExceptionErrorsraise_template_errorsobjects KidWriterslists SubExpressionscompilesDOTALLs _sub_exprs interpolates CodeGeneratorsLocationGenerators _ascii_encodes_adjust_python_block(7s QNAME_STRIPsraise_template_errors SubExpressionssplitexts NamespacesDOCTYPEs KID_PREFIXsparses QNAME_DEFs QNAME_REPEATs QNAME_LAYOUTsXML_DECLskidnssTemplateExceptionErrors QNAME_OMITs QNAME_SLOTs __revision__s__all__s KidWriters QNAME_REPLACEsformat_exception_onlysQNAME_ATTRIBUTESsres extract_tbsLOCATIONsTEXTs parse_files QNAME_FORs __version__sKID_PIsENDs _sub_exprs __license__sLocationGeneratorserror_locations QNAME_EXTENDSs interpolates __author__ssyssSTARTs _ascii_encodes namespacessQNAME_IFs QNAME_CONTENTsComments __copyright__sdocuments KID_XMLNSsProcessingInstructions CodeGenerators QNAME_MATCHs__date__s KID_ALT_PIs KID_OLD_PIs_adjust_python_block((s2build/bdist.darwin-8.0.1-x86/egg/kid/codewriter.pys?s\ 1               w   $,! PK1C8eBBkid/options.pyc; [PFc@sYdZdkZdZdZdZdZeiZdgZdZ de fdYZ dS( sConfiguration API.Ns $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s"David Stanek sCopyright 2006, David StaneksOptionsskid:cBs_tZhdZdZedZdZdZdZdZ dZ d Z RS( NcKsgh|_x*|iD]\}}|i||qWx*|iD]\}}|i||qCWdS(N(sselfs_optionssoptionssitemssnamesvaluessetsextra(sselfsoptionssextrasvaluesname((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pys__init__s   cCs|ii|i|SdS(scReturns True if a option exists or False if it doesn't. name: the option to check N(sselfs_optionsshas_keys_Options__prefixsname(sselfsname((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pysissetscCs |ii|i||SdS(sGet the value of an option. name: the option to retrieve default: returned for non-existing properties, defaults to None N(sselfs_optionssgets_Options__prefixsnamesdefault(sselfsnamesdefault((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pysget!scCs||i|i|<|SdS(sSet the value of an option. name: the option to set value: the value to be set for the option Returns the value passed in. N(svaluesselfs_optionss_Options__prefixsname(sselfsnamesvalue((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pysset)scCs+|i|o|i|i|=ndS(sRemove an option.N(sselfsissetsnames_optionss_Options__prefix(sselfsname((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pysremove3scCs3|i| otd|n|i|SdS(Ns no option %s(sselfsissetsnamesKeyErrorsget(sselfsname((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pys __getitem__8scCs|i||dS(N(sselfssetsnamesvalue(sselfsnamesvalue((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pys __setitem__=scCs3|i| otd|n|i|dS(Ns no option %s(sselfsissetsnamesKeyErrorsremove(sselfsname((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pys __delitem__@scCs'|it ot|}n|SdS(s,Add the prefix if it does not already exist.N(snames startswiths_prefix(sselfsname((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pys__prefixEs( s__name__s __module__s__init__sissetsNonesgetssetsremoves __getitem__s __setitem__s __delitem__s_Options__prefix(((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pysOptionss       ( s__doc__sreleases __revision__s__date__s __author__s __copyright__slicenses __license__s__all__s_prefixsobjectsOptions( s __copyright__s __revision__s__all__s __license__s_prefixs __author__s__date__sreleasesOptions((s/build/bdist.darwin-8.0.1-x86/egg/kid/options.pys?s   PK4C8; kid/filter.pyc; ]PFc@sdZdZdZdZdZdZdklZlZl Z l Z l Z dk l Z dklZd gZd Zd Zd Zd S(sKid tranformationss $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!Ryan Tomayko (rtomayko@gmail.com)s!Copyright 2004-2005, Ryan Tomaykos8MIT (s ElementStreamsSTARTsXML_DECLsdocuments _coalesce(s Namespace(sgenerate_contentstransform_filtercsDi}d}ti|}tt|||SdS(Ncstt|SdS(N(stransform_filtersgenerate_contentsitemstemplate(sitem(stemplate(s.build/bdist.darwin-8.0.1-x86/egg/kid/filter.pys apply_funcs(stemplates_get_match_templatess templatess apply_funcs ElementStreamsensuresstreams apply_matches(sstreamstemplates templatess apply_func((stemplates.build/bdist.darwin-8.0.1-x86/egg/kid/filter.pystransform_filters  c cs=x6|D].\}}|tjo t} xtdt|D]}||\} }| |o|i }t |||||i}t|djo%xh|D]\}}||fVqWnGxCtt|||| ||d|D]\}}||fVqWt} Pq<q<W| oqq+n||fVqWdS(Niii(sstreamsevsitemsSTARTsFalsesmatchedsrangeslens templatessismatchscallsexpands _coalescestemplates apply_funcs_get_assume_encodings newstreams apply_matchess ElementStreamsTrue( sstreamstemplates templatess apply_funcsisitems newstreamscallsevsmatchsmatched((s.build/bdist.darwin-8.0.1-x86/egg/kid/filter.pys apply_matchess0        c cstd}|i} |i}x|D]\}}|tjo |i| jo|i }|i d}yt ||i}WnF|i|}x]t|idD]\}}||fVqWqXx-|D]!\}}|tjo|VqqWq%q%WdS(Nshttp://www.w3.org/2001/XIncludeshrefi(s NamespacesxisincludesfallbacksstreamsevsitemsSTARTstagsexpandsgetshrefsdocumentstemplates_get_assume_encodingsdocsfinds fallback_elms ElementStreamsstripsXML_DECL( sstreamstemplates fallback_elmsxisevsdocsitemshrefsfallbacksinclude((s.build/bdist.darwin-8.0.1-x86/egg/kid/filter.pysxinclude_filter2s&        N(s__doc__s __revision__s__date__s __author__s __copyright__s __license__s kid.parsers ElementStreamsSTARTsXML_DECLsdocuments _coalesces kid.namespaces Namespaceskid.template_utilsgenerate_contents__all__stransform_filters apply_matchessxinclude_filter(s __copyright__s __revision__s__all__s __license__sgenerate_contentsxinclude_filters Namespaces __author__s__date__sSTARTs apply_matchess ElementStreamsXML_DECLstransform_filtersdocuments _coalesce((s.build/bdist.darwin-8.0.1-x86/egg/kid/filter.pys?s%     PK1C81UUkid/format.pyc; [PFc @sdZdZdZdZdZdZdkZddgZdefd YZ hd e d e <d e <d e de <de de dd<de de dd<de de dd<de d e de <de d e de <de d e de <de de de <de de ddde <de de ddde <de de ddde <de de de <de de ddde <de de ddde <de de ddde <d e d e de de <d!e de de de <d"e de ddde <d#e de ddde de <d$e de ddde de NsFormatsoutput_formatscBstZdZdZdZddf\ZZdZdZdZ dZ dZ d Z e id Ze id e iZe id e iZe id Ze idZe idZe idZe idZe idZe idZe idZe idZe ide iZe ide iZe ide iZe ide iZ e idZ!e idZ"e ide iZ#e idZ$dZ%dZ&e'e'd Z(d!Z)d"Z*e+e*Z*d#Z,e+e,Z,d$Z-e+e-Z-d%Z.e+e.Z.d&Z/e+e/Z/d'Z0e+e0Z0d(Z1e2e1Z1d)Z3e2e3Z3d*Z4e2e4Z4d+Z5e2e5Z5d,Z6e2e6Z6d-Z7e2e7Z7d.Z8e2e8Z8d/Z9e2e9Z9d0Z:d1Z;d2Z<d3Z=e'e'd4Z>e'e'd5Z?e'd6Z@e'd7d7d8ZAed9ZBe+eBZBd7d:ZCe+eCZCRS(;s#Formatting details for Serializers.iPs iiu’u‘’u“”u–—u…s [ \t\n\r]+s^[ \t]+s[ \t]+$s [ \t]{2,}s\n[ \t\n\r]*\ns[ \t]*\n[ \t\n\r]*s\n[ \t]*s's"s`s(?|tt |jo$|ddfjot pt }nWnt j onX|t j o|||s NamespacesxmlsxhtmlsatomsrdfsrsssnonscBsVtZedZdZdZeZeZdZdZ dZ dZ RS(NcCs+||_||_|o|t|N(sexistssjoinssplitext(sglob(stemplate_packages output_dirs template_dir(s ElementTreecCsxDtttdD]-}yti|Wqtj oqXqWxDtttdD]-}yti|Wq]tj oq]Xq]WxqtttdD]Z}tt |ddo |t j o+yti|Wqtj oqXqqWdS(Ns*.outs*.pycs*.pyis.kid( sglobsjoinpaths output_dirsfsossunlinksOSErrors template_dirsexistsssplitexts keep_files(sf((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pyscleanups&  )cCs tdS(N(scleanup(smodule((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pys setup_module+scCs#tiid o tndS(Ns KID_NOCLEANUP(sossenvironsgetscleanup(smodule((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pysteardown_module.scCs`t|dptt|dptt|dptt|dptdS(Nspullsgenerateswrites serialize(shasattrstsAssertionError(st((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pysassert_template_interface2scCsytid=Wntj onXtiydki}Wntj o t }nX|t jpt ti dki}ti|i }ttd}|dddd}|i}x|D]}qW|i|t|dS(Ns test.contexts context.outsfooi sbarsbla bla(ssyssmodulessKeyErrorskidsdisable_imports test.contextscontextscs ImportErrorsNonesAssertionErrors enable_importsTemplatesCsjoinpaths output_dirsoutstspullsitseswritescheck_xml_file(scsesitstsCsout((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_import_and_expand8s,        cCs^tiitd pttitd}t|tiitdptdS(Nstest_def( ssyssmodulesshas_keystemplate_packagesAssertionErrorskidsimport_templatestsassert_template_interface(st((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_import_template_funcOs cCstittddddt}t|tittddtddt}||j pt tittddtddt}||jpt dS(Ns test_if.kidsnamesscachestest_if( skids load_templatesjoinpaths template_dirsFalsestsassert_template_interfacestemplate_packagesTruest2sAssertionErrorst3(st2st3st((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_load_template_funcUs     c Csrtittddddt}d}ti|dtdhd|<}|i}d|jpt dS( Ns templates.kidsnamesscaches snsstsThis is a test( skids load_templatesjoinpaths template_dirsFalsestssst2s serializesxmlsAssertionError(sxmlst2ssst((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_load_template_func_with_nsbs $ cCsd}ti|}|idjptt|d ptd}ti|d|}|idjpt|idjptdS(Ns; Hello, World!sMousesDonaldcBs||iUd|_dS(NsDuck(scodesmods__dict__sDonald(smodscode((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pys exec_modulets s exec_modulesDuck( ssskids load_templatestsMickeysAssertionErrorshasattrs exec_modulesDonald(s exec_modulessst((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pys#test_load_template_with_exec_modulens cCs>tidtd}t|t|tiptdS(Nsnamestest_if(skidsTemplatestemplate_packagestsassert_template_interfaces isinstances BaseTemplatesAssertionError(st((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_template_func{s cCsCd}|tidtd|tittddS(NcCsHxA|iddD]-}|tj ot|djptqWdS(Nsencodingsasciii(sosgeneratesssNoneslensAssertionError(soss((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pysrun_testssnamestest_ifs test_if.kid(srun_testskidsTemplatestemplate_packages load_templatesjoinpaths template_dir(srun_test((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_generate_funcs cCsedfdY}tidtdid|tittd}|id|dS(NsFOcBstZdZRS(NcCsdS(N((sselfstext((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pyswrites(s__name__s __module__swrite(((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pysFOssnamestest_ifsfiles test_if.kid( sFOskidsTemplatestemplate_packageswrites load_templatesjoinpaths template_dirsm(smsFO((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_write_funcs#cCsCd}|tidtd|tittddS(NcCsv|idd}|tj ot|djpt|idd}|tj ot|djptdS(Nsencodingsutf-8isascii(sos serializesoutsNoneslensAssertionError(sosout((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pysrun_tests'snamestest_ifs test_if.kid(srun_testskidsTemplatestemplate_packages load_templatesjoinpaths template_dir(srun_test((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_serialize_funcs cCsOd}tid|}|ii}||jptd||fdS(Ns= sfiles%r != %r(stextskidsTemplatestemplates serializesstripsactualsAssertionError(stextsactualstemplate((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_short_formscCsd}tiddd|}|idt}|djptd}tiddd|}|idt}d}||jptd ||fdS( Nu&some plain "text" with & entities.ssources

${XML(text)}

stextsfragments-

some plain "text" with & entities.

ssomething

something else

s&

something

something else

s%r != %r( stextskidsTemplatests serializesTruesrsltsAssertionErrorsactualsexpected(sactualstextstsexpectedsrslt((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_XML_func_fragmentscCs[d}tiddd|}|idt}d}||jptd||fdS(Nssomething

something else

ssources

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

stextsfragments2

something

something else

s%r != %r( stextskidsTemplatests serializesTruesactualsexpectedsAssertionError(sactualstextstsexpected((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_XML_ns_fragments cCs3d}tiddd|}t|iGHdS(Nu asdf ― qwerssources

${XML(s)}

ss(ssskidsTemplatestsreprs serialize(ssst((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_XML_func_unicodescCstidd}tid|_d}|idt|jpt ti |iGH|idt|jpt dS(Nssources $xmls somenestedelementss'somenestedelementssfragment( skidsTemplatests ElementTrees fromstringsxmlsexpecteds serializesTruesAssertionErrorsdump(sexpectedst((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_dont_modify_treess  cCs<tidd}|idt}|djptdS(Nssourcessfragment(skidsTemplatests serializesTruesrsltsAssertionError(srsltst((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pys test_commentsss*c Cstttd|}x|D]}|dd!d}y<tid|dt }d|_ |i |t |Wq tj ohd|GHy&tii|d t d t d dWn d GHn!Xtit|dd dGHq Xq WdS(Ns test_%s.kidiis.outsfilescachesutf-8s Template: %sssourcesforcesencodings1Corresponding source module could not be created.s.pys0The correspoding source module has been created.(sglobsjoinpaths template_dirstests test_filessfsoutskidsTemplatesTruestemplatesassume_encodingswritescheck_xml_files Exceptionscompilers compile_files keep_filessappendssplitext(stestsfstemplates test_filessout((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_kid_filess&    cCstii}ti|i}|idjpt x|i dD]}|i d}|i d}|iddjo,ti|i}|i|d|_nyt||dtWnt j o n X|tiid 7_qHWdS( Nstestdocstestsattemptsexpectstypestextss diff_thisi(skidstestsdots ElementTreesparsesfilenamesgetrootsdocstagsAssertionErrorsfindallstsfindsattemptsexpectsgetsXMLstextsappendsdiff_elmsFalsesadditional_tests(sfilenamesattemptsdocsexpectstsdot((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pyscheck_xml_files"   cCsRxZ||gD]L}|io |iipt|_|io |iipt|_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((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pysdiff_elms" #'  !    cCs\tidd}tidd}t|djptt|djptdS(sDTest for collisions in templates created with a string (ticket #70).ssourcesss- s- N(skidsTemplatest1st2sstrsAssertionError(st2st1((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_string_templatess cCsdkl}ytiddt}Wn!|j o}t|}nXd}td|jpt d|jpt dS(s3Check for reserved keyword arguments (ticket #181).(sTemplateAttrsErrors
scontentsreserved name was not detecteds reserved nameN( skid.template_utilsTemplateAttrsErrorskidsTemplatesNonestsesstrsreprsAssertionError(sesTemplateAttrsErrorst((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pystest_reserved_namess (1s__doc__s __revision__s__date__s __author__s __copyright__s __license__sosssyssos.pathsexistssjoinsjoinpathssplitextsglobskidskid.teststemplate_packages output_dirs template_dirs xml.etrees ElementTrees ImportErrors elementtrees keep_filesscleanups setup_modulesteardown_modulesassert_template_interfacestest_import_and_expandstest_import_template_funcstest_load_template_funcstest_load_template_func_with_nss#test_load_template_with_exec_modulestest_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_xml_filesTruesdiff_elmstest_string_templatesstest_reserved_names()stest_short_forms keep_filessexistsstemplate_packagessplitextstest_load_template_funcstest_serialize_funcstest_load_template_func_with_nss ElementTreestest_XML_func_unicodes __revision__stest_dont_modify_treesstest_reserved_namesscleanupstest_XML_func_fragmentsjoinpathstest_template_funcstest_kid_filess test_commentssglobs output_dirstest_write_funcs __license__steardown_modules setup_modules __author__ssysstest_XML_ns_fragmentstest_string_templatess#test_load_template_with_exec_moduleskids __copyright__s template_dirstest_import_and_expandstest_import_template_funcs__date__stest_generate_funcsdiff_elmscheck_xml_filesossassert_template_interface((s5build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid.pys?sP                    PK2C8""kid/test/test_match.pyc; ZPFc@sdZdZdZdZdklZdklZdk l Z dk Z dZ d Z d Zd Zd Zd ZdS(s%Unit Tests for the template matching.s $Rev: 455 $s"David Stanek sCopyright 2005, David Stanek(sjoin(smkdtemp(srmtreeNcCs#tddatiitdS(Nsprefixskid_test_match_(smkdtempstmpdirskidspathsinsert(smodule((s7build/bdist.darwin-8.0.1-x86/egg/kid/test/test_match.pys setup_module scCstiitttdS(N(skidspathsremovestmpdirsrmtree(smodule((s7build/bdist.darwin-8.0.1-x86/egg/kid/test/test_match.pysteardown_modulescCstttddidtttddidtiddi}d|jptd|jptdS( Nsmatch0_base.kidsws Your title goes here

smatch0_page.kids Welcome to TurboGears

My Main page with bold text

sfiles$Welcome to TurboGearssBOLD( sopensjoinpathstmpdirswriteskidsTemplates serializeshtmlsAssertionError(shtml((s7build/bdist.darwin-8.0.1-x86/egg/kid/test/test_match.pys test_match0s cCstttddidtttddidtiddi}d|jptd|jptd |jptd |jptd |jptdS( Nsmatch1_base.kidsws 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.
( sopensjoinpathstmpdirswriteskidsTemplates serializeshtmlsAssertionError(shtml((s7build/bdist.darwin-8.0.1-x86/egg/kid/test/test_match.pys test_match1Bs cCstttddidtttddidddf}xtdD]}d |}ttt|did |ti d |}||_ |i }d |jptd |jptd|jptt|}|it|}qWWdS(sFTest for a know bad case in the apply_matches function (ticket # 142).smatch2_master.kidsws%
smatch2_userform.kids
smastersuserformismatch2_%s_%s.kids sfilesTHIS IS THE TAGs MASTER MATCHsseasources:userformN(sopensjoinpathstmpdirswritesextendssrangesisfileskidsTemplatestsactions serializeshtmlsAssertionErrorslistsreversestuple(sishtmlsextendssfilest((s7build/bdist.darwin-8.0.1-x86/egg/kid/test/test_match.pys test_match_2ks"   #     cCsUd}tid|}|idd}d}|GH|GH|i|ptdS(s=Check for an issue with additional blank lines (ticket #131).s one

hello world!

two ssourcesoutputshtmlsH one two N( stemplateskidsTemplatests serializesrsltsexpectsendswithsAssertionError(sexpectsrsltststemplate((s7build/bdist.darwin-8.0.1-x86/egg/kid/test/test_match.pys test_match_3s (s__doc__s __revision__s __author__s __copyright__sos.pathsjoinsjoinpathstempfilesmkdtempsshutilsrmtreeskids setup_modulesteardown_modules test_match0s test_match1s test_match_2s test_match_3( s test_match1s test_match0s __copyright__s __revision__smkdtempsteardown_modules setup_modules __author__s test_match_3s test_match_2srmtreeskidsjoinpath((s7build/bdist.darwin-8.0.1-x86/egg/kid/test/test_match.pys?s       , ) ,PKY86E'kid/test/test_serialization_escaping.py# -*- coding: utf-8 -*- """Tests exercising text escaping.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = "MIT " from kid.serialization import XMLSerializer, XHTMLSerializer, HTMLSerializer XML = XMLSerializer XHTML = XHTMLSerializer HTML = HTMLSerializer TEST_CHARS = ('<', '>', '"', "'", '&',) TEST_STRINGS = ('str', 'k\204se') TEST_COMBO = ('str<"&">str', "k\204se<'&'>k\204se") def escape_functions(): """Generator producing escape functions.""" for serializer in (HTMLSerializer, XMLSerializer, XHTMLSerializer): for escape in (serializer.escape_cdata, serializer.escape_attrib): yield serializer, escape def do_escape(func, test_chars, result_chars, encoding=None): for x, char in enumerate(test_chars): assert func(char, encoding) == result_chars[x] def test_escape(): expected = { XML.escape_cdata: ('<', '>', '"', "'", '&',), XML.escape_attrib: ('<', '>', '"', "'", '&',), XHTML.escape_cdata: ('<', '>', '"', "'", '&',), XHTML.escape_attrib: ('<', '>', '"', "'", '&',), HTML.escape_cdata: ('<', '>', '"', "'", '&',), HTML.escape_attrib: ('<', '>', '"', "'", '&',), } for serializer, escape in escape_functions(): do_escape(escape, TEST_CHARS, expected[escape]) def test_escape_encoding(): """Test the encoding part of the escaping functions.""" ascii_expected = ('str', 'k\204se') utf8_expected = ('str', 'k„se') for serializer, escape in escape_functions(): do_escape(escape, TEST_STRINGS, ascii_expected) do_escape(escape, TEST_STRINGS, utf8_expected, 'utf-8') def test_escape_encoding_combo(): ascii_expected = { XML.escape_cdata: ('str<"&">str', "k\204se<'&'>k\204se"), XML.escape_attrib: ('str<"&">str', "k\204se<'&'>k\204se"), XHTML.escape_cdata: ('str<"&">str', "k\204se<'&'>k\204se"), XHTML.escape_attrib: ('str<"&">str', "k\204se<'&'>k\204se"), HTML.escape_cdata: ('str<"&">str', "k\204se<'&'>k\204se"), HTML.escape_attrib: ('str<"&">str', "k\204se<'&'>k\204se"), } utf8_expected = { XML.escape_cdata: ('str<"&"str', "1k„se<'&'>k„se"), XML.escape_attrib: ('str<"&">str', "k„se<'&'>k„se"), XHTML.escape_cdata: ('str<"&">str', "k„se<'&'>k„se"), XHTML.escape_attrib: ('str<"&">str', "k„se<'&'>k„se"), HTML.escape_cdata: ('str<"&">str', "k„se<'&'>k„se"), HTML.escape_attrib: ('str<"&">str', "k„se<'&'>k„se"), } for serializer, escape in escape_functions(): do_escape(escape, TEST_COMBO, ascii_expected[escape]) do_escape(escape, TEST_COMBO, utf8_expected[escape], 'utf-8') def test_escaping_int(): for serializer, escape in escape_functions(): try: assert escape(1) except TypeError, e: assert str(e) == 'cannot serialize 1 (type int)' def test_escaping_nbsp(): for serializer, escape in escape_functions(): assert escape('\xa0', 'ascii') == ' ' assert escape('\xa0', 'ascii', {'\xa0': 'bingo'}) == 'bingo' PKY86}Akid/test/test_compiler.py# -*- coding: utf-8 -*- """Kid package tests.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys from os.path import join as joinpath, exists import kid import kid.compiler import kid.test.test_kid check_xml_file = kid.test.test_kid.check_xml_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') kid.disable_import() 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(joinpath(template_dir, 'test_content.pyc')) import test.test_content assert exists(joinpath(template_dir, 'test_content.pyc')) assert sys.modules.has_key('test.test_content') def test_import_and_expand(): from kid.test import output_dir 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_xml_file(out) PKY86ٓ((kid/test/__init__.py# -*- coding: utf-8 -*- """Kid test package.""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import sys import os import glob from os.path import abspath, basename, dirname, join as joinpath from kid.test.util import dot __all__ = ['dot', 'run_suite', 'template_package', 'output_dir', 'template_dir'] _mydir = abspath(joinpath(dirname(__file__), '..', '..')) template_dir = joinpath(_mydir, 'test') output_dir = template_dir template_package = 'test.' test_modules = [basename(f)[:-3] for f in glob.glob(joinpath(_mydir, 'kid', 'test', 'test*.py'))] additional_tests = 0 basic_tests = 0 def run_suite(args): stop_first = '-x' in args from kid.test.util import run_suite tests = ['kid.test.%s' % m for m in test_modules] run_suite(tests, stop_first) if __name__ == '__main__': run_suite(sys.argv[1:]) PK3C87\\!kid/test/test_extended_layout.pyc; [PFc@sgdZdZdZdZdklZdklZdk l Z dk Z dZ d Z d ZdS( s Unit Tests for Extended Layouts.s $Rev: 455 $s$Christoph Zwerschke s#Copyright 2006, Christoph Zwerschke(sjoin(smkdtemp(srmtreeNcCs#tddatiitdS(Nsprefixskid_test_extended_layout_(smkdtempstmpdirskidspathsinsert(smodule((sAbuild/bdist.darwin-8.0.1-x86/egg/kid/test/test_extended_layout.pys setup_module scCstiitttdS(N(skidspathsremovestmpdirsrmtree(smodule((sAbuild/bdist.darwin-8.0.1-x86/egg/kid/test/test_extended_layout.pysteardown_modulescCstttddidtidd}|idd}d|jpt d|jpt d |jpt d |jpt d |jpt d |jpt tttd didtidd }|idd}d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt tttddidtidd}|idd}d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt d|jpt dS(s2Test layout template extended by another template.s master.kidsws

Master Title

sfilesoutputsxhtmls+ssheads master.jssbodysTitles section.kidsF Section Title

Section Title

Section content
ssSection TitlessB(s HTMLTemplatestsexpecteds serializesrsltsAssertionError(sexpectedsrsltst((s?build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pystest_html_noescape_elementss  cCs:tdt}d}|i}||jptdS(Ns9s*(s HTMLTemplatesxhtml_namespacestsexpecteds serializesrsltsAssertionError(sexpectedsrsltst((s?build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pystest_html_boolean_attributess cCstdddt}td|_t|_d}ti|}||_dk l }|dt}|i d|}|id d }d }||jpttdd dt}t|_t|_d }ti|}||_|i }|idd}||jpt|idd}ti|}||_|i }|id d }|iddidd}||jptdS(Nsencodingsutf-8s transposes html-stricts(sFormatsno_empty_linessformats sssasciisContent

Hello, World!

s/>s>s content-types garbage-typessJ���<meta content="text/html; charset=ascii" http-equiv="content-type"><title>(���s���HTMLSerializers���Trues ���serializers���doctypess���doctypes ���inject_types���sources���kids���Templates���ts ���kid.formats���Formats���formats ���serializes���rslts���replaces���expecteds���AssertionErrors���Falses���None(���s���Formats���formats���sources���ts���expecteds���rslts ���serializer(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_doctype_and_injection���s:����           c����������C���s[��d�t��}��t�i�|���}�t�t�i��d�j�p�t��xt�i�D]}�|�i �d�|��}�d�|�i ���j�o~|�i �d��p�t��|�i ���i �d��p�t��|�i �d��o,�d�|�j�p�t��d �|�j�p�t��n)�d �|�j�p�t��d �|�j�p�t��d �|�j�p�t��d �|�j�oR�d�|�i ���j�p�t��d�|�i ���j�p�t��d�|�i ���j�p�t��n�d �|�i ���j�p�t��d�|�j�o2�d�|�i ���j�p�t��d�|�j�p�t��n/�d�|�i ���j�p�t��d�|�j�p�t��d�|�j�o,�d�|�j�p�t��d�|�j�p�t��n�d�|�j�p�t��d�|�j�p�t��|�i �d��ob�d �|�j�o�d�|�j�p�t��q.d�|�j�o�d�|�j�p�t��q.d�|�j�p�t��n_�d �|�j�o�d�|�j�p�t��n:�d�|�j�o�d�|�j�p�t��n�d�|�j�p�t��|��}�|�i�d�d��}�|�i �d �� o,�|�i�d!�d"��}�|�i�d#�t��d$��}�n�|�i ���|�j�o.�|�i���}�|�i�d%�d&��i�d'�d(��}�n�d)�|�}�|�i�|��p�t��q@�|�i�d*��o2�|�i �d+��p�t��|�i�|���p�t��q@�|�d,�j�p�t��|�d-�j�p�t��q@�Wd��S(.���Ns.���<html xmlns="%s"><h1 />Hello<br />World</html>i���s���outputs���htmls ���<!DOCTYPE s���<!doctype html public "s���xhtmls���DOCTYPE html PUBLICs��� "-//W3C//DTD XHTML 1.0s���DOCTYPE HTML PUBLICs��� "-//W3C//DTD HTML 4.01s���//EN"s���stricts ���transitionals���framesets���looses ��� Framesets ��� Transitionals���quirkss���http://s���dtds���"http://www.w3.org/TR/s���.dtd"s���/xhtml1/DTD/xhtml1-strict.dtd"s ���/xhtml1/DTD/xhtml1-frameset.dtd"s$���/xhtml1/DTD/xhtml1-transitional.dtd"s���/html4/strict.dtd"s���/html4/frameset.dtd"s���/html4/loose.dtd"s���<h1 />s ���<h1></h1>s���xs���<br />s���<br>s ��� xmlns="%s"s����s���HELLOs���Hellos���WORLDs���Worlds��� s���mls'���<?xml version="1.0" encoding="utf-8"?> s���plains ���HelloWorld(���s���xhtml_namespaces���xmls���kids���Templates���ts���lens���output_methodss���AssertionErrors���outputs ���serializes���ss���lowers ���startswiths���rs���replaces���uppers���endswith(���s���xmls���ss���rs���ts���output(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_output_methods���sp����  �        " c����������C���s^���t��d�t��}�t�d�|�_�t�i�d��}��|�|��_�d�}�|��i ���}�|�|�j�p�t ��d��S(���Ns ���transposes ���html-stricts ���<html xml:lang='en' lang='en' />sr���<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML LANG="en"></HTML>( ���s���HTMLSerializers���Trues ���serializers���doctypess���doctypes���kids���Templates���ts���expecteds ���serializes���rslts���AssertionError(���s���ts���expecteds���rslts ���serializer(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_strip_lang��s����   c����������C���si���t����}�t�|�_�t�|�_�t�i�|�_�t �i �d��}��|�|��_�d�}�|��i ���}�|�|�j�p�t��d��S(���Ns���<HTML><HEAD /></HTML>s���<html><head></head></html>(���s���HTMLSerializers ���serializers���Nones���doctypes���Falses ���inject_types���strings���lowers ���transposes���kids���Templates���ts���expecteds ���serializes���rslts���AssertionError(���s���ts���expecteds���rslts ���serializer(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_transpose_lower��s����      c����������C���sf���t����}�t�|�_�t�|�_�t�|�_�t�i�d��}��|�|��_�d�}�|��i ���}�|�|�j�p�t ��d��S(���Ns���<HTML><HEAD /></HTML>s���<HTML><HEAD></HEAD></HTML>(���s���HTMLSerializers ���serializers���Nones���doctypes���Falses ���inject_types ���transposes���kids���Templates���ts���expecteds ���serializes���rslts���AssertionError(���s���ts���expecteds���rslts ���serializer(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_transpose_off��s����      c����������C���s��xJ�d�D]B�}�t�i�d�|��}�|�i�d�d��}�|�i�d��p�t��q�Wt�i�d��i�d�d��}�|�i�d ��p�t��d �k�l �}�x�d �D]�}�y)�t�i�d�|��}�|�i�d�d��}�WnO�|�j �oC�}��t �|���}��d �|��j�o �d �|��j�o�d�|�}�qd�}�n�X|�i�d�|��p�t��q�Wt�i�d��i�d�d�d�d��}�|�i�d��p�t��t�i�d��}�|�i�d�d�d�d��}�|�i�d��p�t��d�S(���s1���Only real XML whitespace should be stripped away.s��� s ���<p>%s</p>s���encodings���latin-1s���<p />s ���<p> </p>s���outputs���xhtmls���<p> </p>(���s ���ExpatErrors��� s���not well-formeds ���invalid tokens ���XML Errors ���<p> </p>s���<p></p>s ���<p> </p>N( ���s���chars���kids���Templates���ts ���serializes���rslts���endswiths���AssertionErrors���xml.parsers.expats ���ExpatErrors���es���str(���s���es���chars���ts���rslts ���ExpatError(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_whitespace%��s2������ �  !c����������C���s`���t��i�d��i�d�d��}��|��i�d�d��i�d�d��}��|��i�d�d�d �d ��p�t��d �S( ���s7���Keep nonbreakable space inside paragraph (ticket #140).s�� <?python def nbsp1(): return XML("nbsp") def nbsp2(): return XML(" ") def nbsp3(): return XML(" ") def nbsp4(): return u'\u00a0' ?> <div xmlns:py="http://purl.org/kid/ns#"> <h1>ticket #140</h1> <span py:content="nbsp1()"/> <span py:content="nbsp2()"/> <span py:content="nbsp3()"/> <span py:content="nbsp4()"/> </div>s���encodings���latin-1s��� s����s��� s)���<div><h1>ticket#140</h1><span>nbsp</span>i���s���<span></span>s���</div>N(���s���kids���Templates ���serializes���rslts���replaces���endswiths���AssertionError(���s���rslt(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_whitespace2B��s�����c����������C���s���d�}��t�i�|���i�d�d��|��j�p�t��t�t�d��d�}��t�i�|���i�d�d��|��j�p�t��t�t�d��d�}��t�i�|���i�d�d��|��j�p�t��d �S( ���s<���Comments should not add an additional newline (ticket #107).sT���<?xml version="1.0" encoding="utf-8"?> <html> <!-- a comment --> <element /> </html>s���outputs���xmls���htmls7��� <HTML> <!-- a comment --> <ELEMENT> </ELEMENT> </HTML>s���HTMLs���xhtmls7��� <html> <!-- a comment --> <element> </element> </html>N(���s���expecteds���kids���Templates ���serializes���AssertionErrors���serialize_doctypes���doctypes(���s���expected(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_comment_whitespaceZ��s�����))c����������C���s{���t��i�d��}�t�t�d��d�}��|�i�d�d��|��j�p�t��t�t�d��d�}��|�i�d�d��|��j�p�t��d�S( ���s��Handling of empty lines in templates. Empty lines between elements should be removed. We assume that balanced_blocks is enabled for both HTML and XHTML templates. Inline elements in template should remain so. Other elements should be indented. s��� <html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg"/></a> </body> </html>s���htmls��� <HTML> <SCRIPT>some lines and more lines</SCRIPT><BODY> <A HREF="/"><IMG SRC="pic.jpg"></A> </BODY> </HTML>s���outputs���HTMLs���xhtmls��� <html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg" /></a> </body> </html>N(���s���kids���Templates���ts���serialize_doctypes���doctypess���expecteds ���serializes���AssertionError(���s���expecteds���t(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_empty_linesf��s ���� �   c����������C���s6���d�}��t�|���i���|��i�d�d��j�p�t��d�S(���s:���Check that no extra indentation is inserted (ticket #131).sE���<div> <a href="/"><img src="pic.jpg"/></a> </div>s���/>s���>N(���s���htmls ���HTMLTemplates ���serializes���replaces���AssertionError(���s���html(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_extra_indentation��s�����c����������C���s���d�}�d�}�t�i�|�d�d�}�t�i�|�d�|�i���}��|��i�d�d�d�t��}�d �}�|�|�j�p�t ��d �}�t�i�|�d�d�}�t�i�|�d�|�i���}��|��i�d�d�d�t��}�d �}�|�|�j�p�t ��d �}�|�|�j�p�t ��d �S(���s5���Check for extra indentation to textarea (ticket #83).sP��� <textarea xmlns:py="http://purl.org/kid/ns#" py:content="value" /> sQ��� <div xmlns:py="http://purl.org/kid/ns#"> ${widget} </div> s���values����s���widgets���outputs���xhtmls���fragments.���<div> <textarea></textarea> </div>sE��� <div xmlns:py="http://purl.org/kid/ns#">${widget}</div> s ���<div><textarea></textarea></div>sD��� <div xmlns:py="http://purl.org/kid/ns#"> ${widget}</div> N( ���s ���widgetsrcs���templates���kids���Templates���ts ���transforms���tmpls ���serializes���Trues���rslts���expecteds���AssertionError(���s���tmpls ���widgetsrcs���ts���templates���expecteds���rslt(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_textarea_indentation��s �����c����������C���sr���d�}�d�}�t�i�|�d�d�}�t�i�|�d�|�i���}��|��i�d�d�d�t��}�d �}�|�|�j�p�t ��d �S( ���s8���Check problem with handling of br in XHTML (ticket #83).s���<div><br/></div>s���<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> ${widget}<br/> </div>s���values����s���widgets���outputs���xhtmls���fragmentsY���<div xmlns="http://www.w3.org/1999/xhtml"> <div><br /></div><br /> </div>N( ���s ���widgetsrcs���templates���kids���Templates���ts ���transforms���tmpls ���serializes���Trues���rslts���expecteds���AssertionError(���s���tmpls ���widgetsrcs���ts���templates���expecteds���rslt(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_br_namespace_issues��s�����c����������C���s��d�}��t�i�|���}�x�t�t�t�f�D]�}�|���}�|�i �d�|�d�d��}�|�i �|��i �d�d���p�t ��|�d�t��}�|�i �d�|�d�d��}�|�i �|���p�t ��|�d�h��d�d �<�}�|�i �d�|�d�d��}�|�i �|��i �d�d ���p�t ��q%�Wd �S( ���s(���Check that   is rendered correctly.s���<p>Dr. Snuggles</p>s���outputs���encodings���asciis��� s��� s ���entity_mapu��� s��� Mooney N(���s���xmls���kids���Templates���ts ���XMLSerializers���HTMLSerializers���XHTMLSerializers���ss���outputs ���serializes���rs���endswiths���replaces���AssertionErrors���True(���s���xmls���ss���rs���ts���output(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys ���test_nbsp��s������ #c����������C���s`���d�}�d�}�t�i�|�d�t�i�|��i���}�|�i�d�d�d�t��}��|��d�j�p�t ��d�S( ���s5���Check that namespaces are not repeated (ticket #144).s4��� <div xmlns="http://www.w3.org/1999/xhtml"/>sw��� <div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#" py:content="div1"/>s���div1s���outputs���xhtmls���fragments;���<div xmlns="http://www.w3.org/1999/xhtml"><div></div></div>N( ���s���div1s���div2s���kids���Templates ���transforms���ts ���serializes���Trues���ss���AssertionError(���s���ss���ts���div2s���div1(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���test_no_repeated_namespaces��s �����$(2���s���__doc__s ���__revision__s���__date__s ���__author__s ���__copyright__s ���__license__s���kids ���kid.namespaces���xhtmls���kid.serializations���serialize_doctypes���doctypess���strs���xhtml_namespaces���test_serialize_doctypes���test_html_output_methods���test_HTML_output_methods���test_xhtml_output_methods���test_html_strict_output_methods���test_html_quirks_output_methods���test_xml_output_methods���HTMLSerializers ���XMLSerializers���XHTMLSerializers ���serializers���Nones���doctypes���Falses ���inject_types ���HTMLTemplates���test_html_transposes���test_html_empty_elementss���test_xhtml_empty_elementss���test_html_noescape_elementss���test_html_boolean_attributess���test_doctype_and_injections���test_output_methodss���test_strip_langs���strings���test_transpose_lowers���test_transpose_offs���test_whitespaces���test_whitespace2s���test_comment_whitespaces���test_empty_liness���test_extra_indentations���test_textarea_indentations���test_br_namespace_issuess ���test_nbsps���test_no_repeated_namespaces(*���s���test_br_namespace_issuess ���test_nbsps���XHTMLSerializers���test_html_output_methods���test_empty_liness���test_xhtml_empty_elementss���test_output_methodss���test_transpose_offs���test_HTML_output_methods ���XMLSerializers ���HTMLTemplates���test_html_transposes���test_comment_whitespaces ���__revision__s���test_no_repeated_namespacess ���__license__s���test_whitespace2s���HTMLSerializers���test_doctype_and_injections���test_html_noescape_elementss���test_serialize_doctypes���test_transpose_lowers���xhtml_namespaces���xhtmls���test_xml_output_methods���doctypess���test_xhtml_output_methods���test_textarea_indentations���serialize_doctypes���test_extra_indentations ���__author__s���test_whitespaces���strings���kids���test_html_quirks_output_methods���test_strip_langs ���__copyright__s���test_html_boolean_attributess���test_html_strict_output_methods���__date__s���test_html_empty_elementss ���serializer(����(����s?���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_serialization.pys���?���sR���                 ) A    )    PK�����Y862�2��2�����kid/test/test_error.py"""Unit Tests for error reporting.""" __revision__ = "$Rev: 496 $" __author__ = "Christoph Zwerschke <cito@online.de>" __copyright__ = "Copyright 2006, Christoph Zwerschke" import sys from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid from kid.test.util import raises # Error tracking is only fully supported in Python 2.4 # because we need the CurrentLineNumber attribute of Expat python24 = sys.version_info[:2] >= (2, 4) def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_error_') kid.path.insert(tmpdir) def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) class KidFileWriter: test_number = 0 def __init__(self): KidFileWriter.test_number += 1 self.file_number = 0 def name(self): return 'test_error_%d_%d' % (self.test_number, self.file_number) def filename(self, full=False): filename = '%s.kid' % self.name() if full: filename = joinpath(tmpdir, filename) return filename def write(self, xml): self.file_number += 1 open(self.filename(True), 'w').write(xml) def test_xml_error(): """Check that erroneous XML is reported.""" from xml.parsers.expat import ExpatError page = """\ <html> <h1>title</h1> <a><b>oops</b></a> <p>That's all, folks.</p> </html>""" kid.Template(page) page = page.replace('</b></a>', '</a></b>') e = str(raises(ExpatError, kid.Template, source=page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 3, column 24' in e assert page.splitlines()[2] in e # erroneous line assert "\n%25s\n" % "^" in e # offset pointer assert 'html' not in e assert 'title' not in e assert 'folks' not in e page = """\ <html xmlns:py="http://purl.org/kid/ns#"> <h1 py:replace="XML(xml)">title</h1> </html>""" t = kid.Template(source=page, xml="<h1>ok</h1>") from xml.parsers.expat import ExpatError content = """\ <h1>start</h1> this &is wrong <p>end</p>""" t = kid.Template(source=page, xml=content) e = str(raises(ExpatError, t.serialize)) assert 'Error parsing XML' in e assert 'not well-formed (invalid token): line 2, column 16' in e assert content.splitlines()[1] in e assert "\n%17s\n" % "^" in e assert 'html' not in e assert 'start' not in e assert 'end' not in e def test_xml_long_line(): """Check intelligent truncating of long XML error lines.""" from xml.parsers.expat import ExpatError page = '<a>x</b>' + 9999*'x' e = str(raises(ExpatError, kid.Template, page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 1, column 6' in e assert ('\n<a>x</b>' + 68*'x') in e assert "\n%7s\n" % "^" in e page = '<a>' + 9999*'x' + '</b>' e = str(raises(ExpatError, kid.Template, page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 1, column 10004' in e assert ('\n' + 72*'x' + '</b>') in e assert "\n%75s\n" % "^" in e page = '<a>' + 9999*'x' + '</b>' + 9999*'x' e = str(raises(ExpatError, kid.Template, page)) assert 'Error parsing XML' in e assert 'mismatched tag: line 1, column 10004' in e assert ('\n' + 36*'x' + '</b>' + 36*'x') in e assert "\n%39s\n" % "^" in e def test_xml_filename_error(): """Check that erroneous XML filename is reported.""" f = KidFileWriter() f.write("<xml>This is XML</xml>") t = kid.Template(file=f.filename()) f.write("This is not XML") from xml.parsers.expat import ExpatError e = str(raises(ExpatError, kid.Template, file=f.filename())) assert 'Error parsing XML' in e assert f.filename() in e assert 'This is not XML' in e assert 'syntax error: line 1, column 0' in e assert '\n^\n' in e def test_layout_error(): """Check that erroneous py:layout expressions are reported.""" page = '<html xmlns:py="http://purl.org/kid/ns#" py:layout="no_layout" />' # because py:layout is dynamic, the template can be created # but the error should show up when we try to serialize the template t = kid.Template(source=page) from kid.template_util import TemplateLayoutError e = str(raises(TemplateLayoutError, t.serialize)) assert 'not defined' in e assert 'while processing layout=' in e assert 'no_layout' in e def test_extends_error(): """Check that erroneous py:extends expressions are reported.""" page = '<html xmlns:py="http://purl.org/kid/ns#" py:extends="no_extends" />' # because py:extends is not dynamic, the template cannot be created from kid.template_util import TemplateExtendsError e = str(raises(TemplateExtendsError, kid.Template, source=page)) assert 'not defined' in e assert 'while processing extends=' in e assert 'no_extends' in e def test_attr_error(): """Check that erroneous py:attrs expressions are reported.""" page = """\ <html xmlns:py="http://purl.org/kid/ns#"> <p py:attrs="%s" /> </html>""" t = kid.Template(source=page % "abc=123, def=789") s = t.serialize() assert 'abc="123"' in s and 'def="789"' in s from kid.template_util import TemplateAttrsError t = kid.Template(source=page % "abc=123, 456=789") e = str(raises(TemplateAttrsError, t.serialize)) assert 'invalid' in e assert 'while processing attrs=' in e assert 'abc=123, 456=789' in e t = kid.Template(source=page % "{'mickey':'mouse'}") s = t.serialize() assert 'mickey="mouse"' in s t = kid.Template(source=page % "mickey mouse") e = str(raises(TemplateAttrsError, t.serialize)) assert 'while processing attrs=' in e assert 'mickey mouse' in e t = kid.Template(source=page % "{mickey:mouse}") e = str(raises(TemplateAttrsError, t.serialize)) assert 'not defined' in e assert 'mickey' in e and 'mouse' in e def test_tracking_1(): """Check error tracking when compiling a Kid template.""" from kid.compiler import compile_file f = KidFileWriter() xml = """<xml> <title>compilation fails the expression ${1/0} can be compiled the expression ${1//0} can be compiled the expression ${1///0} cannot be compiled the expression ${1+1} can be compiled """ for call in (compile_file, kid.load_template, kid.Template): f.write(xml) e = str(raises(SyntaxError, call, file=f.filename(call == compile_file))) assert 'invalid syntax (%s.py, line ' % f.name() in e assert ' 1///0' in e and ' ^\n' in e assert '1/0' not in e and '1//0' not in e and '1+1' not in e assert 'can be compiled' not in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'on line 5 between columns 8 and 54:' in e assert 'the expression ${1///0} cannot be compiled' in e assert 'xml>' not in e and 'title>' not in e assert 'p1>' not in e and 'p2>' not in e and 'p4>' not in e assert 'compilation fails' not in e xml = """ compilation fails """ for call in (compile_file, kid.load_template, kid.Template): f.write(xml) e = str(raises(SyntaxError, call, file=f.filename(call == compile_file))) assert 'invalid syntax (%s.py, line ' % f.name() in e assert 'oops = 1///0' in e and ' ^\n' in e assert 'ok =' not in e assert '1/0' not in e and '1//0' not in e and '1+1' not in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 10, column 8 and line 13, column 8:' in e assert ' oops = 1///0' in e assert 'xml>' not in e and 'title>' not in e assert 'compilation fails' not in e def test_tracking_2(): """Check error tracking when importing a Kid template.""" from kid.compiler import compile_file f = KidFileWriter() xml = """ import fails """ f.write(xml) try: e = compile_file(file=f.filename(True)) except Exception: e = None assert e == True, 'This file cannot be compiled properly.' for call in (kid.load_template, kid.Template): f.write(xml) e = str(raises(ZeroDivisionError, call, file=f.filename())) assert 'integer division or modulo by zero' in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 4, column 8 and line 5, column 8:' in e assert '' in e assert 'xml>' not in e and 'title>' not in e assert 'import fails' not in e def test_tracking_3(): """Check error tracking when executing a Kid template.""" f = KidFileWriter() xml = """ execution fails the expression ${1/2} can be evaluated the expression ${1/0} cannot be evaluated """ f.write(xml) t = kid.Template(file=f.filename()) def execute_template_method(t, n): if n == 1: import StringIO output = StringIO.StringIO() t.write(file=output) ret = output.getvalue() output.close() elif n == 2: ret = list(t.generate()) else: ret = t.serialize() return ret for n in range(3): e = str(raises(ZeroDivisionError, execute_template_method, t, n)) assert 'integer division or modulo by zero' in e if python24 and n < 2: assert 'Error location in template file ' in e assert f.filename() in e assert 'on line 4 between columns 8 and 53:' in e assert 'the expression ${1/0} cannot be evaluated' in e assert 'xml>' not in e and 'title>' not in e assert 'execution fails' not in e xml = """ execution fails """ f.write(xml) t = kid.Template(file=f.filename()) e = str(raises(ZeroDivisionError, t.serialize)) assert 'integer division or modulo by zero' in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 4, column 8 and line 5, column 8:' in e assert '' not in e and 'title>' not in e assert 'execution fails' not in e xml = """ execution fails

test1

test2

""" f.write(xml) t = kid.Template(file=f.filename()) e = str(raises(ZeroDivisionError, t.serialize)) assert 'integer division or modulo by zero' in e if python24: assert 'Error location in template file ' in e assert f.filename() in e assert 'between line 4, column 22 and line 5, column 8:' in e assert ' py:content="1/0"' in e assert '"1/2"' not in e assert 'xml>' not in e and 'title>' not in e assert 'p1>' not in e and 'h1>' not in e assert 'h2>' not in e assert 'execution fails' not in e def test_tracking_4(): """Check error tracking when compiling a Kid template.""" from kid.compiler import compile_file f = KidFileWriter() xml = """ execution fails test
""" f.write(xml) t = kid.Template(file=f.filename()) e = raises(UnicodeDecodeError, t.serialize) assert e.__class__.__name__ == UnicodeDecodeError.__name__ assert e.__class__.__module__ == UnicodeDecodeError.__module__ assert hasattr(e, 'reason') \ and e.reason == "ordinal not in range(128)" e = str(e) assert "can't decode byte 0xe4 in position 1" in e assert "ordinal not in range(128)" in e assert '\nError in code generated from template file ' in e assert f.filename() in e assert 'execution fails' not in e PK3C8S];#;#kid/test/test_element.pyc; ZPFc@sdZdZdZdZdZdZdkZdklZl Z l Z l Z l Z l Z lZlZdZd Zd Zd Zd Zd ZdZdZdZdZdZdS(skid.element testss $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s"David Stanek sCopyright 2006, David Staneks8MIT N(sElements SubElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitycCs!td}|idjpt|iGH|ihjpt|itjpt|itjpttdtdddd}|idjpt|ihdd<dd$(sElementselementsresmatchsNonesAssertionError(smatchselement((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_element.pystest_element_repr,s cCstd}|itd|itd|itd|itdt|djpt|didjpt|didjpttd |d<|did jpt|d=t|djpt|d \}}|idjpt|idjpttd td f|d *|did jpt|d id jpt|d 4t|d jpt|diGH|didjpt|idtd|idtd|didjpt|d idjptt|djpt|d}|i |t|d jpt|i }t|d jpt|didjpt|d idjpt|i |idjptt|djptdS(Nsparentschild0schild1schild2schild3iiischild4isfirstonesfirsttwoisinsert1sinsert0i(sElementsparentsappendslensAssertionErrorstagschild0schild1sinsertschildsremoves getchildrenschildrensclear(schild0schild1sparentschildschildren((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_element.pystest_element_children2sJ      cCstdtdddddd}|idtjpt|idd d jpt|iddjpt|idd djpt|idd|iddjpt|i}t|d jptx+dddgD]}||jptqW|i }t|d jptx=ddfddfddfgD]}||jptqgWdS( Nstestsaisbiscisdsi( sElementsdictselementsgetsNonesAssertionErrorssetskeysslensksitemssi(skeyssitemssksiselement((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_element.pystest_element_attributescs"$    "cCstd}t|d}|didjpt|dihjpt|ditjpt|di tjptt|dt dddd}|didjpt|dihdd<ddtddjptd}td|jptdS(s%TODO: do a more complete set of testssmy texts1 is > 0 && 2 < 3s1 is > 0 && 2 < 3N(s encode_entitysAssertionErrorsexpected(sexpected((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_element.pystest_encode_entitys(s__doc__s __revision__s__date__s __author__s __copyright__s __license__sres kid.elementsElements SubElementsCommentsProcessingInstructionsFragmentsQNames namespacess encode_entitystest_element_initstest_element_reprstest_element_childrenstest_element_attributesstest_subelements test_commentstest_processing_instructions test_fragments test_qnamestest_namespacesstest_encode_entity(s encode_entitystest_element_attributess test_commentstest_element_reprs __revision__stest_element_childrensFragmentstest_encode_entitysres __license__stest_processing_instructionstest_subelements __author__s test_fragments namespacesstest_namespacessElementsComments __copyright__stest_element_initsProcessingInstructions test_qnamesQNames__date__s SubElement((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_element.pys?s$ 7   1       PK2C8|0kid/test/test_layout.pyc; [PFc@sIdZdZdZdZdkZdZdZdZdZdS( s Unit Tests for layout templates.s $Rev: 421 $s#Daniel Miller sCopyright 2006, David StanekNcCsdkl}ytidiWnE|j o}t|}n&tj o d}nd}nXd|jptd|jptd|jptdS(N(sTemplateLayoutErrors[ s wrong errorssilents 'no_layout's not definedswhile processing layout=( skid.template_utilsTemplateLayoutErrorskidsTemplates serializesesstrs ExceptionsAssertionError(sesTemplateLayoutError((s8build/bdist.darwin-8.0.1-x86/egg/kid/test/test_layout.pystest_layout_error s   cCsZtid}tiddt|}|i}|iddjp tddS(Nsg ${body_content()} s body content sdynamic_layouts body contentis&body_content function was not executed( skidsTemplateslayoutstypeschilds serializesoutputsfindsAssertionError(soutputschildslayout((s8build/bdist.darwin-8.0.1-x86/egg/kid/test/test_layout.pystest_dynamic_layouts cCs`tid}tiddt|dd}|i}|iddjp tddS( Ns
s( test_var=${test_var} slayoutstest_vars test valuestest_var=test valueismatch template was not executed( skidsTemplateslayoutstypeschilds serializesoutputsfindsAssertionError(soutputschildslayout((s8build/bdist.darwin-8.0.1-x86/egg/kid/test/test_layout.pystest_match_locals(s! cCs`tid}tiddt|dd}|i}|iddjp tddS( Ns ${child_content()} s  test_var=${test_var} slayoutstest_vars test valuestest_var=test valueis'child_content function was not executed( skidsTemplateslayoutstypeschilds serializesoutputsfindsAssertionError(soutputschildslayout((s8build/bdist.darwin-8.0.1-x86/egg/kid/test/test_layout.pystest_def_localsMs! ( s__doc__s __revision__s __author__s __copyright__skidstest_layout_errorstest_dynamic_layoutstest_match_localsstest_def_locals(s __copyright__s __revision__stest_dynamic_layoutstest_match_localss __author__stest_def_localsskidstest_layout_error((s8build/bdist.darwin-8.0.1-x86/egg/kid/test/test_layout.pys?s    %PKY86rkid/test/test_match.py"""Unit Tests for the template matching.""" __revision__ = "$Rev: 455 $" __author__ = "David Stanek " __copyright__ = "Copyright 2005, David Stanek" from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_match_') kid.path.insert(tmpdir) def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_match0(): open(joinpath(tmpdir, "match0_base.kid"), 'w').write("""\ Your title goes here

""") open(joinpath(tmpdir, "match0_page.kid"), 'w').write("""\ Welcome to TurboGears

My Main page with bold text

""") html = kid.Template(file="match0_page.kid").serialize() assert 'Welcome to TurboGears' in html assert 'BOLD' in html def test_match1(): open(joinpath(tmpdir, "match1_base.kid"), 'w').write("""\ Some title here
Real content would go here.
""") open(joinpath(tmpdir, "match1_page.kid"), 'w').write("""\

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

""") html = kid.Template(file="match1_page.kid").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 test_match_2(): """Test for a know bad case in the apply_matches function (ticket # 142).""" open(joinpath(tmpdir, "match2_master.kid"), 'w').write("""\
""") open(joinpath(tmpdir, "match2_userform.kid"), 'w').write("""\
""") extends = ('master', 'userform') for i in range(2): file = "match2_%s_%s.kid" % extends open(joinpath(tmpdir, file), 'w').write("""\ """ % extends) t = kid.Template(file=file) t.action = file html = t.serialize() assert 'THIS IS THE TAG' 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 extends = list(extends) extends.reverse() extends = tuple(extends) def test_match_3(): """Check for an issue with additional blank lines (ticket #131).""" template = """\ one

hello world!

two """ t = kid.Template(source=template) rslt = t.serialize(output="html") expect = """ one two """ print rslt print expect assert rslt.endswith(expect) PK3C8U6g##kid/test/test_extends.pyc; [PFc@sdZdZdZdZdklZdklZdk l Z dk Z dZ d Z d Zd Zd Zd ZdS(sUnit Tests for Template Reuse.s $Rev: 455 $s$Christoph Zwerschke s#Copyright 2006, Christoph Zwerschke(sjoin(smkdtemp(srmtreeNcCsBtddatiittttddiddS(Nsprefixskid_test_extends_s layout.kidsws

my header

my footer

(smkdtempstmpdirskidspathsinsertsopensjoinpathswrite(smodule((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_extends.pys setup_module scCstiitttdS(N(skidspathsremovestmpdirsrmtree(smodule((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_extends.pysteardown_modulescCsd}xxddddfD]d}||}tid|i}d|jptd|jptd |jptqW|d }d kl }ytid|i}Wn9|j o}t |}n t j o d }nXd }d|jptd|jptd|jptd|}xhd dfD]Z}tid|i}d|jptd|jptd |jptqIWdS(s,Test the basic template reuse functionality.s

my content

s 'layout.kid's layout.kids'layout'slayoutssources my headers my contents my footers layout_module(sTemplateExtendsErrors wrong errorssilents'layout_module's not definedswhile processing extends=sd slayout_module.TemplateN( spagesextendsssourceskidsTemplates serializesrsltsAssertionErrorskid.template_utilsTemplateExtendsErrorsesstrs Exception(sTemplateExtendsErrorsessourcesextendssrsltspage((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_extends.pys test_extendss8      cCstttddidtttddidtidd}|idd}d }d }xM|i D]?}|i }|i||}|d jptd |q{Wd S( s1Test for the bug that was reported in ticket #66.s layout2.kidsws layout
header

... content will be inserted here ...

footer
s page2.kids> page

my content

sfilesoutputsxhtmls page
header

my content

footer
isMissing or misplaced: N(sopensjoinpathstmpdirswriteskidsTemplatests serializesrsltsexpectedsis splitlinesslinesstripsfindsAssertionError(sistsexpectedsrsltsline((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_extends.pystest_comments_in_extendsDs   cCstttddidtttddidtttddidtttddid tid d}|id d }d }d}xM|i D]?}|i }|i||}|djptd|qWdS(s2Test for the bug that was reported in ticket #194.s page3.kidswsP Welcome to the test
Welcome
s page3e.kids Extend Page page s layout3.kids Layout Title

s layout3e.kids Extend Layout layout sfilesoutputsxhtmls Layout Title

layout

Welcome page
isMissing or misplaced: N(sopensjoinpathstmpdirswriteskidsTemplatests serializesrsltsexpectedsis splitlinesslinesstripsfindsAssertionError(sistsexpectedsrsltsline((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_extends.pystest_layout_and_extendsvs     cCstttddiditttddiditidd}|idd}|GHd }gi }|i D]'}|io||iqq~}gi }|i D]'}|io||iqq~}||jptd S( s&This is how Pudge implements layouts. This will cause a generator to be sent to template_util.generate_content. For each of the (ev, item) pairs yielded from the generator will be fed through generate content. Before the fix the tuples were treated as text for the output. spudge_layout.kidsws
Interesting text here
stestlayout.kids
sfilesoutputsxmls
Interesting text here
N(sopensjoinpathstmpdirswritesstripskidsTemplatests serializesrsltsexpectedsappends_[1]s splitlinessxsAssertionError(sts_[1]sxsexpectedsrslt((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_extends.pystest_pudge_layouts% %  DD(s__doc__s __revision__s __author__s __copyright__sos.pathsjoinsjoinpathstempfilesmkdtempsshutilsrmtreeskids setup_modulesteardown_modules test_extendsstest_comments_in_extendsstest_layout_and_extendsstest_pudge_layout( s __copyright__s __revision__smkdtempsteardown_modules setup_modulestest_layout_and_extendsstest_pudge_layouts __author__s test_extendssrmtreestest_comments_in_extendsskidsjoinpath((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_extends.pys?s      & 2 7PKY86I/9l#l#kid/test/test_kid.py"""kid package tests.""" __revision__ = "$Rev: 455 $" __date__ = "$Date: 2006-12-21 01:42:34 -0500 (Thu, 21 Dec 2006) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " import os import sys from os.path import exists, join as joinpath, splitext from glob import glob import kid, kid.test from kid.test import template_package, output_dir, template_dir try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree keep_files = [] def cleanup(): for f in glob(joinpath(output_dir, '*.out')): try: os.unlink(f) except OSError: pass for f in glob(joinpath(template_dir, '*.pyc')): try: os.unlink(f) except OSError: pass for f in glob(joinpath(template_dir, '*.py')): if exists(splitext(f)[0] + '.kid') and not f in keep_files: try: os.unlink(f) except OSError: pass 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(): try: del sys.modules['test.context'] except KeyError: pass kid.disable_import() try: import test.context as c except ImportError: c = None assert c is None kid.enable_import() import test.context as c kid.disable_import() 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_xml_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=False) assert_template_interface(t) t2 = kid.load_template(joinpath(template_dir, 'test_if.kid'), name=template_package + 'test_if', cache=True) assert not t is t2 t3 = kid.load_template(joinpath(template_dir, 'test_if.kid'), name=template_package + 'test_if', cache=True) assert t3 is t2 def test_load_template_func_with_ns(): t = kid.load_template(joinpath(template_dir, 'templates.kid'), name='', cache=False) s = """ """ t2 = kid.load_template(s, cache=False, ns={'t': t}) xml = t2.serialize() assert "This is a test" in xml def test_load_template_with_exec_module(): s = """ Hello, World!""" t= kid.load_template(s) assert t.Mickey == 'Mouse' assert not hasattr(t, 'Donald') def exec_module(mod, code): exec code in mod.__dict__ mod.Donald = 'Duck' t = kid.load_template(s, exec_module=exec_module) assert t.Mickey == 'Mouse' assert t.Donald == 'Duck' 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=True) 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=True) 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=True) 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=True) == expected print ElementTree.dump(t.xml) assert t.serialize(fragment=True) == expected def test_comments(): t = kid.Template(source="") rslt = t.serialize(fragment=True) assert rslt == "" def test_kid_files(test='*'): test_files = glob(joinpath(template_dir, 'test_%s.kid' % test)) for f in test_files: out = f[0:-4] + '.out' try: template = kid.Template(file=f, cache=True) template.assume_encoding = "utf-8" template.write(out) check_xml_file(out) except Exception: print '\nTemplate: %s' % f try: kid.compiler.compile_file(f, source=True, force=True, encoding="utf-8") except: print "Corresponding source module could not be created." else: keep_files.append(splitext(f)[0] + '.py') print "The correspoding source module has been created." raise def check_xml_file(filename): dot = kid.test.dot doc = ElementTree.parse(filename).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=False) except AssertionError: raise else: dot() kid.test.additional_tests += 1 def diff_elm(elm1, elm2, diff_this=True): 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 collisions in templates created with a string (ticket #70).""" t1 = kid.Template(source="") t2 = kid.Template(source="") assert str(t1) == '\n' assert str(t2) == '\n' def test_reserved_names(): """Check for reserved keyword arguments (ticket #181).""" from kid.template_util import TemplateAttrsError try: t = kid.Template('
', content=None) except TemplateAttrsError, e: e = str(e) else: e = 'reserved name was not detected' assert repr('content') in e assert 'reserved name' in e PKY86R2! ! kid/test/test_extended_layout.py"""Unit Tests for Extended Layouts.""" __revision__ = "$Rev: 455 $" __author__ = "Christoph Zwerschke " __copyright__ = "Copyright 2006, Christoph Zwerschke" from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_extended_layout_') kid.path.insert(tmpdir) def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_extended_layout(): """Test layout template extended by another template.""" open(joinpath(tmpdir, 'master.kid'), 'w').write("""\

Master Title

""") t = kid.Template(file="master.kid") rslt = t.serialize(output='xhtml') assert '' in rslt assert '' in rslt assert 'head' not in rslt assert 'master.js' not in rslt assert 'body' not in rslt assert 'Title' not in rslt open(joinpath(tmpdir, 'section.kid'), 'w').write("""\ Section Title

Section Title

Section content
""") t = kid.Template(file="section.kid") rslt = t.serialize(output='xhtml') assert '' in rslt assert '' in rslt assert 'Section Title' in rslt assert '") expected = '' rslt = t.serialize() assert rslt == expected def test_html_boolean_attributes(): t = HTMLTemplate('' '' % xhtml_namespace) expected = '' rslt = t.serialize() assert rslt == expected def test_doctype_and_injection(): serializer = HTMLSerializer(encoding='utf-8', transpose=True) serializer.doctype = doctypes['html-strict'] serializer.inject_type = True source = "" t = kid.Template(source) t.serializer = serializer from kid.format import Format format=Format(no_empty_lines=True) rslt = t.serialize(format=format) rslt = rslt.replace('\n', '') expected = ('' '' '' '') assert rslt == expected serializer = HTMLSerializer(encoding='ascii', transpose=False) serializer.doctype = None serializer.inject_type = True source = ('' '' '' '' 'Content' '

Hello, World!

') t = kid.Template(source) t.serializer = serializer rslt = t.serialize() expected = source.replace('/>', '>') assert rslt == expected source = source.replace('content-type', 'garbage-type') t = kid.Template(source) t.serializer = serializer rslt = t.serialize() rslt = rslt.replace('\n', '') expected = source.replace('/>', '>').replace('', '<meta content="text/html; charset=ascii"' ' http-equiv="content-type"><title>') assert rslt == expected def test_output_methods(): xml = '<html xmlns="%s"><h1 />Hello<br />World</html>' % xhtml_namespace t = kid.Template(xml) assert len(kid.output_methods) >= 15 for output in kid.output_methods: s = t.serialize(output=output) if 'html' in output.lower(): # html or xhtml assert s.startswith('<!DOCTYPE ') assert s.lower().startswith('<!doctype html public "') if output.startswith('xhtml'): assert 'DOCTYPE html PUBLIC' in s assert ' "-//W3C//DTD XHTML 1.0' in s else: assert 'DOCTYPE HTML PUBLIC' in s assert ' "-//W3C//DTD HTML 4.01' in s assert '//EN"' in s if 'strict' in output: assert 'transitional' not in s.lower() assert 'frameset' not in s.lower() assert 'loose' not in s.lower() else: assert 'strict' not in s.lower() if 'frameset' in output: assert 'transitional' not in s.lower() assert ' Frameset' in s else: assert 'frameset' not in s.lower() assert ' Transitional' in s if 'quirks' in output: assert 'http://' not in s assert 'dtd' not in s else: assert '"http://www.w3.org/TR/' in s assert '.dtd"' in s if output.startswith('xhtml'): if 'strict' in output: assert '/xhtml1/DTD/xhtml1-strict.dtd"' in s elif 'frameset' in output: assert '/xhtml1/DTD/xhtml1-frameset.dtd"' in s else: assert '/xhtml1/DTD/xhtml1-transitional.dtd"' in s else: if 'strict' in output: assert '/html4/strict.dtd"' in s elif 'frameset' in output: assert '/html4/frameset.dtd"' in s else: assert '/html4/loose.dtd"' in s r = xml r = r.replace('<h1 />', '<h1></h1>') if not output.startswith('x'): r = r.replace('<br />', '<br>') r = r.replace(' xmlns="%s"' % xhtml_namespace, '') if output.lower() != output: r = r.upper() r = r.replace('HELLO', 'Hello').replace('WORLD', 'World') r = '\n' + r assert s.endswith(r) elif output.endswith('ml'): # xml or wml assert s.startswith('<?xml version="1.0" encoding="utf-8"?>\n') assert s.endswith(xml) else: assert output == 'plain' assert s == 'HelloWorld' def test_strip_lang(): serializer = HTMLSerializer(transpose=True) serializer.doctype = doctypes['html-strict'] t = kid.Template("<html xml:lang='en' lang='en' />") t.serializer = serializer expected = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"' \ ' "http://www.w3.org/TR/html4/strict.dtd">\n' \ '<HTML LANG="en"></HTML>' rslt = t.serialize() assert rslt == expected import string def test_transpose_lower(): serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = False serializer.transpose = string.lower t = kid.Template("<HTML><HEAD /></HTML>") t.serializer = serializer expected = '<html><head></head></html>' rslt = t.serialize() assert rslt == expected def test_transpose_off(): serializer = HTMLSerializer() serializer.doctype = None serializer.inject_type = False serializer.transpose = None t = kid.Template("<HTML><HEAD /></HTML>") t.serializer = serializer expected = '<HTML><HEAD></HEAD></HTML>' rslt = t.serialize() assert rslt == expected def test_whitespace(): """Only real XML whitespace should be stripped away.""" # These chars are whitespace in XML and Python: for char in '\x09\x0a\x0d\x20': # HT, LF, CR, SP t = kid.Template('<p>%s</p>' % char) rslt = t.serialize(encoding='latin-1') assert rslt.endswith('<p />') rslt = kid.Template('<p> </p>').serialize(output='xhtml') assert rslt.endswith('<p> </p>') # These chars are considered whitespace in Python, but not in XML: from xml.parsers.expat import ExpatError for char in '\x0b\x0c\xa0': # VT, FF, NBSP try: t = kid.Template('<p>%s</p>' % char) rslt = t.serialize(encoding='latin-1') except ExpatError, e: e = str(e) if 'not well-formed' in e and 'invalid token' in e: rslt = '<p>%s</p>' % char else: rslt = 'XML Error' assert rslt.endswith('<p>%s</p>' % char) rslt = kid.Template('<p> </p>').serialize( output='xhtml', encoding='latin-1') assert rslt.endswith('<p>\xa0</p>') t = kid.Template('<p> </p>') rslt = t.serialize(output='xhtml', encoding='latin-1') assert rslt.endswith('<p>\xa0</p>') def test_whitespace2(): """Keep nonbreakable space inside paragraph (ticket #140).""" rslt = kid.Template("""\ <?python def nbsp1(): return XML("nbsp") def nbsp2(): return XML(" ") def nbsp3(): return XML(" ") def nbsp4(): return u'\u00a0' ?> <div xmlns:py="http://purl.org/kid/ns#"> <h1>ticket #140</h1> <span py:content="nbsp1()"/> <span py:content="nbsp2()"/> <span py:content="nbsp3()"/> <span py:content="nbsp4()"/> </div>""").serialize(encoding='latin-1') rslt = rslt.replace(' ', '').replace('\n', '') assert rslt.endswith('<div><h1>ticket#140</h1><span>nbsp</span>' + 3*'<span>\xa0</span>' + '</div>') def test_comment_whitespace(): """Comments should not add an additional newline (ticket #107).""" expected = '<?xml version="1.0" encoding="utf-8"?>\n<html>\n' \ '<!-- a comment -->\n<element />\n</html>' assert kid.Template(expected).serialize(output='xml') == expected expected = serialize_doctype(doctypes['html']) + '\n<HTML>\n' \ '<!-- a comment -->\n<ELEMENT>\n</ELEMENT>\n</HTML>' assert kid.Template(expected).serialize(output='HTML') == expected expected = serialize_doctype(doctypes['xhtml']) + '\n<html>\n' \ '<!-- a comment -->\n<element>\n</element>\n</html>' assert kid.Template(expected).serialize(output='xhtml') == expected def test_empty_lines(): """Handling of empty lines in templates. Empty lines between elements should be removed. We assume that balanced_blocks is enabled for both HTML and XHTML templates. Inline elements in template should remain so. Other elements should be indented. """ t = kid.Template(""" <html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg"/></a> </body> </html>""") expected = serialize_doctype( doctypes['html']) + """\n<HTML> <SCRIPT>some lines and more lines</SCRIPT><BODY> <A HREF="/"><IMG SRC="pic.jpg"></A> </BODY> </HTML>""" assert t.serialize(output='HTML') == expected expected = serialize_doctype( doctypes['xhtml']) + """\n<html> <script>some lines and more lines</script><body> <a href="/"><img src="pic.jpg" /></a> </body> </html>""" assert t.serialize(output='xhtml') == expected def test_extra_indentation(): """Check that no extra indentation is inserted (ticket #131).""" html = """<div> <a href="/"><img src="pic.jpg"/></a> </div>""" assert HTMLTemplate(html).serialize() == html.replace('/>', '>') def test_textarea_indentation(): """Check for extra indentation to textarea (ticket #83).""" widgetsrc = """ <textarea xmlns:py="http://purl.org/kid/ns#" py:content="value" /> """ template = """ <div xmlns:py="http://purl.org/kid/ns#"> ${widget} </div> """ t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div> <textarea></textarea> </div>""" assert rslt == expected template = """ <div xmlns:py="http://purl.org/kid/ns#">${widget}</div> """ t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div><textarea></textarea></div>""" assert rslt == expected template = """ <div xmlns:py="http://purl.org/kid/ns#"> ${widget}</div> """ assert rslt == expected def test_br_namespace_issues(): """Check problem with handling of br in XHTML (ticket #83).""" widgetsrc = '<div><br/></div>' template = """<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> ${widget}<br/> </div>""" t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div xmlns="http://www.w3.org/1999/xhtml"> <div><br /></div><br /> </div>""" assert rslt == expected def test_nbsp(): """Check that   is rendered correctly.""" xml = '<p>Dr. Snuggles</p>' t = kid.Template(xml) for s in (XMLSerializer, HTMLSerializer, XHTMLSerializer): output = s() r = t.serialize(output=output, encoding='ascii') assert r.endswith(xml.replace(' ', ' ')) output = s(entity_map=True) r = t.serialize(output=output, encoding='ascii') assert r.endswith(xml) output = s(entity_map = {u'\xa0': ' Mooney '}) r = t.serialize(output=output, encoding='ascii') assert r.endswith(xml.replace(' ', ' Mooney ')) def test_no_repeated_namespaces(): """Check that namespaces are not repeated (ticket #144).""" div1 = """ <div xmlns="http://www.w3.org/1999/xhtml"/>""" div2 = """ <div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#" py:content="div1"/>""" t = kid.Template(div2, div1=kid.Template(div1).transform()) s = t.serialize(output='xhtml', fragment=True) assert s == '<div xmlns="http://www.w3.org/1999/xhtml"><div></div></div>' PK�����Y86.A% ��% �����kid/test/test_suffixes.py"""Unit Tests for the import extensions and path functionality.""" __revision__ = "$Rev: 455 $" __author__ = "David Stanek <dstanek@dstanek.com>" __copyright__ = "Copyright 2005, David Stanek" import sys from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree, copyfile import kid from kid.test.util import raises def setup_module(module): global tmpdir, tfile tmpdir = mkdtemp(prefix='kid_test_suffixes_') kid.path.insert(tmpdir) tfile = joinpath(tmpdir, 'test_suffixes0.kid') open(tfile, 'w').write("""\ <html xmlns:py="http://purl.org/kid/ns#"> <body> <p>my content</p> </body> </html>""") def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_enable_import_empty(): """By default *.kid files are imported.""" sys.path.insert(0, tmpdir) try: kid.disable_import() raises(ImportError, "import test_suffixes0") kid.enable_import() import test_suffixes0 raises(ImportError, "import test_suffixes1") kid.disable_import() finally: sys.path.remove(tmpdir) def test_enable_import_with_ext(): """Using exts any file extension can be importable.""" ext = ".html,.kid.html" sys.path.insert(0, tmpdir) try: raises(ImportError, "import test_suffixes1") raises(ImportError, "import test_suffixes2") raises(ImportError, "import test_suffixes3") kid.enable_import(ext=ext) dest = joinpath(tmpdir, "test_suffixes1.kid") copyfile(tfile, dest) import test_suffixes1 # *.kid files are always importable dest = joinpath(tmpdir, "test_suffixes2.html") copyfile(tfile, dest) import test_suffixes2 dest = joinpath(tmpdir, "test_suffixes3.kid.html") copyfile(tfile, dest) import test_suffixes3 dest = joinpath(tmpdir, "test_suffixes4.xhtml") copyfile(tfile, dest) raises(ImportError, "import test_suffixes4") kid.disable_import() finally: sys.path.remove(tmpdir) def test_enable_import_with_path(): """Using path any template directory can be importable.""" assert tmpdir not in sys.path raises(ImportError, "import test_suffixes4") kid.enable_import(path=tmpdir) dest = joinpath(tmpdir, "test_suffixes4.kid") copyfile(tfile, dest) import test_suffixes4 kid.disable_import(path=tmpdir) dest = joinpath(tmpdir, "test_suffixes5.kid") copyfile(tfile, dest) raises(ImportError, "import test_suffixes5") PK�����1C8 �� �����kid/test/test_namespace.pyc; ZPFc�����������@���sT���d��Z��d�Z�d�Z�d�Z�d�Z�d�Z�d�k�l�Z�d�k�l �Z �d���Z �d ���Z �d �S( ���s���kid.namespace tests.s ���$Rev: 492 $s5���$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!���Ryan Tomayko (rtomayko@gmail.com)s!���Copyright 2004-2005, Ryan Tomaykos8���MIT <http://www.opensource.org/licenses/mit-license.php>(���s ���Namespace(���s���NamespaceStackc����������C���s���t��d�d�d�d��}��|��i�d�j�p�t��|��d�d�j�p�t��|��i�d��d�j�p�t��t��d�t��}��|��i�d�j�p�t��|��d�d�j�p�t��|��i�d��d�j�p�t��d��S(���Ns���uris���urn:tests���prefixs���tests���{urn:test}names���names ���test:name(���s ���Namespaces���nss���names���AssertionErrors���qnames���None(���s���ns(����(����s;���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_namespace.pys���test_namespace_module���s����c������� ���C���s��t����}�h��d�d�<h��d�d�<d�d�<h��d�d�<h��d�d �<h��d�d �<h��d �d�<g�}�x�|�D]�}�|�i�|��qg�W|�i�}��|��d ��d�j�p�t��|��d��d �j�p�t��|�i�}�|�d�d �t �t �j�p�t��|�d�d �t �t �j�p�t��|�d �d �t �d�j�p�t��|�d �d �t �t �j�p�t��|�d�d �t �d�j�p�t��|�d�d �t �d�j�p�t��xU�t �t�|��d �d�d��D]7�}�|�i���}�|�G|�|�GH|�|�|�j�p�t��qWd��S(���Ns����s���urn:default/namespaces���test0s���urn:test_namespace_0s���test1s���urn:test_namespace_1s���test3s���urn:test_namespace_3s���urn:new/default/namespaces���urn:inner/test0s ���inner_test3s���defaulti���i(���s���NamespaceStacks���stacks ���namespacess���nss���pushs ���resolve_uris���rus���AssertionErrors���resolve_prefixs���rps���Trues���Nones���Falses���ranges���lens���xs���pop(���s���rus���rps ���namespacess���xs���nss���stack(����(����s;���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_namespace.pys���test_namespace_stack���s(���� W�        �  N( ���s���__doc__s ���__revision__s���__date__s ���__author__s ���__copyright__s ���__license__s ���kid.namespaces ���Namespaces���kid.serializations���NamespaceStacks���test_namespace_modules���test_namespace_stack( ���s ���__copyright__s ���__revision__s���NamespaceStacks ���__license__s ���Namespaces���test_namespace_stacks ���__author__s���__date__s���test_namespace_module(����(����s;���build/bdist.darwin-8.0.1-x86/egg/kid/test/test_namespace.pys���?���s���   PK�����2C8Yv<��<�����kid/test/__init__.pyc; [PFc�����������@���s=��d��Z��d�Z�d�Z�d�Z�d�Z�d�Z�d�k�Z�d�k�Z�d�k�Z�d�k �l �Z �l �Z �l �Z �l �Z�d�k�l�Z�d �d �d �d �d �g�Z�e �e�e �e��d�d���Z�e�e�d��Z�e�Z�d�Z�g��i�Z�e�i�e�e�d�d�d���D]�Z�e�e �e��d� �q�[�Z�d�Z�d�Z�d���Z�e�d�j�o�e�e�i�d��n�d�S(���s���Kid test package.s ���$Rev: 492 $s5���$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s!���Ryan Tomayko (rtomayko@gmail.com)s!���Copyright 2004-2005, Ryan Tomaykos8���MIT <http://www.opensource.org/licenses/mit-license.php>N(���s���abspaths���basenames���dirnames���join(���s���dots���dots ���run_suites���template_packages ���output_dirs ���template_dirs���..s���tests���test.s���kids���test*.pyii����c���������C���sU���d�|��j�}�d�k�l�}�g��i�}�t�D]�}�|�d�|��q'�~�}�|�|�|��d��S(���Ns���-x(���s ���run_suites ���kid.test.%s( ���s���argss ���stop_firsts ���kid.test.utils ���run_suites���appends���_[1]s ���test_moduless���ms���tests(���s���argss ���stop_firsts���testss���ms���_[1]s ���run_suite(����(����s5���build/bdist.darwin-8.0.1-x86/egg/kid/test/__init__.pys ���run_suite ���s����  +s���__main__i���( ���s���__doc__s ���__revision__s���__date__s ���__author__s ���__copyright__s ���__license__s���syss���oss���globs���os.paths���abspaths���basenames���dirnames���joins���joinpaths ���kid.test.utils���dots���__all__s���__file__s���_mydirs ���template_dirs ���output_dirs���template_packages���appends���_[1]s���fs ���test_moduless���additional_testss ���basic_testss ���run_suites���__name__s���argv(���s���template_packages���basenames���additional_testss���dirnames���_[1]s ���__revision__s���__all__s���_mydirs ���output_dirs���abspaths���joinpaths ���__license__s ���basic_testss���globs ���__author__s���syss ���__copyright__s ���template_dirs���fs���__date__s ���test_moduless ���run_suites���oss���dot(����(����s5���build/bdist.darwin-8.0.1-x86/egg/kid/test/__init__.pys���?���s*���    I  PK�����Y86T�������kid/test/test_extends.py"""Unit Tests for Template Reuse.""" __revision__ = "$Rev: 455 $" __author__ = "Christoph Zwerschke <cito@online.de>" __copyright__ = "Copyright 2006, Christoph Zwerschke" from os.path import join as joinpath from tempfile import mkdtemp from shutil import rmtree import kid def setup_module(module): global tmpdir tmpdir = mkdtemp(prefix='kid_test_extends_') kid.path.insert(tmpdir) open(joinpath(tmpdir, 'layout.kid'), 'w').write("""\ <html xmlns:py="http://purl.org/kid/ns#"> <body py:match="item.tag == 'body'"> <p>my header</p> <div py:replace="item[:]" /> <p>my footer</p> </body> </html>""") def teardown_module(module): kid.path.remove(tmpdir) rmtree(tmpdir) def test_extends(): """Test the basic template reuse functionality.""" page = """\ <html py:extends="%s" xmlns:py="http://purl.org/kid/ns#"> <body> <p>my content</p> </body> </html>""" for extends in ("'layout.kid'", "layout.kid", "'layout'", "layout"): source = page % extends rslt = kid.Template(source=source).serialize() assert 'my header' in rslt assert 'my content' in rslt assert 'my footer' in rslt source = page % "layout_module" from kid.template_util import TemplateExtendsError try: rslt = kid.Template(source=source).serialize() except TemplateExtendsError, e: e = str(e) except Exception: e = 'wrong error' else: e = 'silent' assert "'layout_module'" in e assert 'not defined' in e assert 'while processing extends=' in e source = """<?python layout_module = kid.load_template( kid.path.find('layout.kid')) ?> """ + source for extends in ("layout_module", "layout_module.Template"): rslt = kid.Template(source=source).serialize() assert 'my header' in rslt assert 'my content' in rslt assert 'my footer' in rslt def test_comments_in_extends(): """Test for the bug that was reported in ticket #66.""" open(joinpath(tmpdir, 'layout2.kid'), 'w').write("""\ <!-- layout --> <html xmlns:py="http://purl.org/kid/ns#"> <head><title>layout
header

... content will be inserted here ...

footer
""") open(joinpath(tmpdir, 'page2.kid'), 'w').write("""\ page

my content

""") t = kid.Template(file="page2.kid") rslt = t.serialize(output='xhtml') expected = """\ page
header

my content

footer
""" i = 0 for line in expected.splitlines(): line = line.strip() i = rslt.find(line, i) assert i >= 0, 'Missing or misplaced: ' + line def test_layout_and_extends(): """Test for the bug that was reported in ticket #194.""" open(joinpath(tmpdir, 'page3.kid'), 'w').write("""\ Welcome to the test
Welcome
""") open(joinpath(tmpdir, 'page3e.kid'), 'w').write("""\ Extend Page page """) open(joinpath(tmpdir, 'layout3.kid'), 'w').write("""\ Layout Title

""") open(joinpath(tmpdir, 'layout3e.kid'), 'w').write("""\ Extend Layout layout """) t = kid.Template(file="page3.kid") rslt = t.serialize(output='xhtml') expected = """\ Layout Title

layout

Welcome page
""" i = 0 for line in expected.splitlines(): line = line.strip() i = rslt.find(line, i) assert i >= 0, 'Missing or misplaced: ' + line def test_pudge_layout(): """This is how Pudge implements layouts. This will cause a generator to be sent to template_util.generate_content. For each of the (ev, item) pairs yielded from the generator will be fed through generate content. Before the fix the tuples were treated as text for the output. """ open(joinpath(tmpdir, 'pudge_layout.kid'), 'w').write("""
Interesting text here
""".strip()) open(joinpath(tmpdir, 'testlayout.kid'), 'w').write("""\
""".strip()) t = kid.Template(file="pudge_layout.kid") rslt = t.serialize(output='xml') print rslt expected = """\
Interesting text here
""" rslt = [x.strip() for x in rslt.splitlines() if x.strip()] expected = [x.strip() for x in expected.splitlines() if x.strip()] assert expected == rslt PK2C8O1 1 kid/test/test_options.pyc; ZPFc@sbdZdZdZdZdZdZdkZdkl Z dZ d Z d Z d Z dS( sKid properties tests.s $Rev: 492 $s5$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $s"David Stanek sCopyright 2006, David Staneks8MIT N(sraisescCs)tdddd}tii|}|iddjpt|iddjpttii|dd}|iddjpt|iddjpt|iddjpttiidddd}|iddjpt|iddjptdS(Nsencodingsutf-8soutputshtmlsstuffi(sdictsoptsskidsoptionssOptionssgetsAssertionError(soptionssopts((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_options.pys test_initscCstii}|idd|idd|iddjpt|iddjpt|idddjptt}|id||jpt|id|id|idt jptdS(Nsencodingsutf-8soutputshtmls not therei( skidsoptionssOptionsssetsgetsAssertionErrorsobjectsosremovesNone(soptionsso((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_options.pystest_setters_getters0s     cstiidds(s__doc__s __revision__s__date__s __author__s __copyright__s __license__s kid.optionsskids kid.test.utilsraisess test_initstest_setters_getters0stest_setters_getters1s test_isset( s __copyright__s __revision__s __license__s test_issetstest_setters_getters1stest_setters_getters0s __author__s__date__sraisess test_initskid((s9build/bdist.darwin-8.0.1-x86/egg/kid/test/test_options.pys?s     PKY86cTkid/test/test_parser.py# -*- coding: utf-8 -*- """kid.parser tests""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "Ryan Tomayko (rtomayko@gmail.com)" __copyright__ = "Copyright 2004-2005, Ryan Tomayko" __license__ = "MIT " from kid import Element, load_template, Template from kid.parser import ElementStream, XML def test_xml_type(): doc = XML("hello world", fragment=False) assert type(doc) is ElementStream doc = XML("hello world", fragment=True) assert type(doc) is ElementStream def test_expand(): doc = XML("world", fragment=False) assert type(doc) is ElementStream doc = doc.expand() assert type(doc) == type(Element('doc')) assert doc.tag == 'doc' assert doc[0].tag == 'hello' assert doc[0].text == 'world' def test_strip(): xml = """ The Title

Header 1

Header 1.1

Header 1.2

Header 1.2.1

Header 1.2.2

Hello, World!

Header 1.2.3

Header 1.3

""" xml_stream = XML(xml, fragment=False) assert type(xml_stream) is ElementStream xml_stream_stripped = xml_stream.strip(levels=6) assert type(xml_stream_stripped) is ElementStream from kid import XMLSerializer serializer = XMLSerializer(decl=False) xml_stripped = serializer.serialize(xml_stream_stripped, fragment=True) assert xml_stripped == 'Hello, World!' def test_xml_with_entity_map(): xml = ' ' assert list(XML(xml))[0][1] == u'\xa0' xml = '&codswallop;' try: e = list(XML(xml)) except Exception, e: e = str(e) assert 'undefined entity &codswallop;' in e xml = ' , &codswallop;!' entity_map = {'nbsp': u'Hello', 'codswallop': u'World'} assert list(XML(xml, entity_map=entity_map))[0][1] == u'Hello, World!' def test_load_template_with_entity_map(): xml = ' ' s = load_template(xml).serialize(encoding='ascii') assert s.endswith(' ') xml = '&codswallop;' try: e = load_template(xml).serialize(encoding='ascii') except Exception, e: e = str(e) assert 'undefined entity &codswallop;' in e xml = ' , &codswallop;!' entity_map = {'nbsp': u'Hello', 'codswallop': u'World'} s = load_template(xml, entity_map=entity_map).serialize(encoding='ascii') assert s.endswith('Hello, World!') def test_encoding(): s = ('\n' '' '\xb5\xb9\xe8\xbb\xbe\xfd\xe1\xed') r = load_template(s).serialize(encoding='utf-8') s = s.decode('iso-8859-2').replace('iso-8859-2', 'utf-8') r = r.decode('utf-8') assert r == s def test_expand_fragments(): """Testcase for expanding XML fragments (ticket #145).""" template = """
""" t = Template("""\

Hello World #$i

""") s = t.serialize(fragment=True) expected = """

Hello World #0

Hello World #1

Hello World #2

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True) assert s2 == s t = Template("""\

Hello World #$i

""") s = t.serialize(fragment=True) expected = """

Hello World #0

Hello World #1

Hello World #2

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True) assert s2 == s t = Template("""\

Hello World

""") s = t.serialize(fragment=True) expected = """

Hello World

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True) assert s2 == s t = Template("""\

Hello World

""") s = t.serialize(fragment=True).strip() expected = """

Hello World

""" assert s == expected stream = ElementStream(t.transform()).expand() t2 = Template(source=template, stream=stream) s2 = t2.serialize(fragment=True).strip() assert s2 == s PKY86Lggkid/test/test_element.py# -*- coding: utf-8 -*- """kid.element tests""" __revision__ = "$Rev: 492 $" __date__ = "$Date: 2007-07-06 21:38:45 -0400 (Fri, 06 Jul 2007) $" __author__ = "David Stanek " __copyright__ = "Copyright 2006, David Stanek" __license__ = "MIT " import re from kid.element import Element, SubElement, \ Comment, ProcessingInstruction, Fragment, QName, \ namespaces, encode_entity def test_element_init(): element = Element("test0") assert element.tag == "test0" print element.attrib assert element.attrib == {} assert element.text is None assert element.tail is None element = Element("test1", dict(a=0, b=1)) assert element.tag == "test1" assert element.attrib == {"a": 0, "b": 1} assert element.text is None assert element.tail is None element = Element("test2", a=0, b=1) assert element.tag == "test2" assert element.attrib == {"a": 0, "b": 1} assert element.text is None assert element.tail is None element = Element("test3", dict(a=0, b=1), c=2) assert element.tag == "test3" assert element.attrib == {"a": 0, "b": 1, "c": 2} assert element.text is None assert element.tail is None def test_element_repr(): element = Element("test0") print `element` match = re.match(r"^$", `element`) assert match is not None def test_element_children(): parent = Element("parent") parent.append(Element("child0")) parent.append(Element("child1")) parent.append(Element("child2")) parent.append(Element("child3")) assert len(parent) == 4 assert parent[0].tag == "child0" assert parent[3].tag == "child3" parent[3] = Element("child4") assert parent[3].tag == "child4" del parent[3] assert len(parent) == 3 child0, child1 = parent[:2] assert child0.tag == "child0" assert child1.tag == "child1" parent[:2] = Element("firstone"), Element("firsttwo") assert parent[0].tag == "firstone" assert parent[1].tag == "firsttwo" del parent[:2] assert len(parent) == 1 print parent[0].tag assert parent[0].tag == "child2" parent.insert(0, Element("insert1")) parent.insert(0, Element("insert0")) assert parent[0].tag == "insert0" assert parent[1].tag == "insert1" assert len(parent) == 3 child = parent[-1] parent.remove(child) assert len(parent) == 2 children = parent.getchildren() assert len(children) == 2 assert children[0].tag == "insert0" assert children[1].tag == "insert1" parent.clear() assert parent.tag == "parent" assert len(parent) == 0 def test_element_attributes(): element = Element("test", dict(a=0, b=1), c=2) assert element.get("d") is None assert element.get("d", "") == "" assert element.get("c") == 2 assert element.get("c", "") == 2 element.set("c", "c") assert element.get("c") == "c" keys = element.keys() assert len(keys) == 3 for k in ["a", "b", "c"]: assert k in keys items = element.items() assert len(items) == 3 for i in [("a", 0), ("b", 1), ("c", "c")]: assert i in items def test_subelement(): parent = Element("parent") child0 = SubElement(parent, "child0") assert parent[0].tag == "child0" assert parent[0].attrib == {} assert parent[0].text is None assert parent[0].tail is None child1 = SubElement(parent, "child1", dict(a=0, b=1)) assert parent[1].tag == "child1" assert parent[1].attrib == {"a": 0, "b": 1} assert parent[1].text is None assert parent[1].tail is None child2 = SubElement(parent, "child2", a=0, b=1) assert parent[2].tag == "child2" assert parent[2].attrib == {"a": 0, "b": 1} assert parent[2].text is None assert parent[2].tail is None child3 = SubElement(parent, "child3", dict(a=0, b=1), c=2) assert parent[3].tag == "child3" assert parent[3].attrib == {"a": 0, "b": 1, "c": 2} assert parent[3].text is None assert parent[3].tail is None assert parent.getchildren() == [child0, child1, child2, child3] def test_comment(): comment = Comment() assert comment.tag == Comment assert comment.text is None comment = Comment("some text here") assert comment.text == "some text here" def test_processing_instruction(): pi = ProcessingInstruction("test") assert pi.tag == ProcessingInstruction assert pi.text == "test" pi = ProcessingInstruction("test", "some text here") assert pi.text == "test some text here" def test_fragment(): fragment = Fragment() assert fragment.tag == Fragment assert fragment.text == "" fragment = Fragment("text here") assert fragment.text == "text here" def test_qname(): qname = QName("text") assert qname.text == "text" assert str(qname) == "text" qname = QName("urn:kid", "text") assert qname.text == "{urn:kid}text" assert str(qname) == "{urn:kid}text" def test_namespaces(): element = Element("test", { "xmlns": "default ns", "xmlns:junk-ns0": "junk-ns value 0", "xmlns:junk-ns1": "junk-ns value 1", "py:pyattr": "py value", "attr": "a new attr", }) ns = namespaces(element) expected = { "": "default ns", "junk-ns0": "junk-ns value 0", "junk-ns1": "junk-ns value 1", } assert ns == expected assert element.get("xmlns") == "default ns" assert element.get("xmlns:junk-ns0") == "junk-ns value 0" assert element.get("xmlns:junk-ns1") == "junk-ns value 1" assert element.get("py:pyattr") == "py value" assert element.get("attr") == "a new attr" ns = namespaces(element, remove=True) assert element.get("xmlns") is None assert element.get("xmlns:junk-ns0") is None assert element.get("xmlns:junk-ns1") is None assert element.get("py:pyattr") == "py value" assert element.get("attr") == "a new attr" def test_encode_entity(): """TODO: do a more complete set of tests""" assert encode_entity("my text") == "my text" expected = "1 is > 0 && 2 < 3" assert encode_entity("1 is > 0 && 2 < 3") == expected PKY86B;;(kid/test/test_attribute_interpolation.py"""Unit Tests for expression substition in attributes.""" __revision__ = "$Rev: 428 $" __author__ = "Christoph Zwerschke " __copyright__ = "Copyright 2006, Christoph Zwerschke" import kid def test_simple_interpolation(): """Simple variable substitution.""" s = kid.Template('
', a='hello', b=123, c=0.5).serialize() assert s.endswith('
') def test_expression_interpolation(): """Expression substitution.""" s = kid.Template('
', a=1, b=2, c=3).serialize() assert s.endswith('
') def test_remove_null_attributes(): """Expressions evaluating to None should remove the attribute.""" source = '
' s = kid.Template(source, a=0, b=False, c=None).serialize() assert s.endswith('
') source = '
' s = kid.Template(source, a=0, b=False, c=None).serialize() assert s.endswith('
') def test_interpolated_xml(): """Harmless XML expressions should be allowed here (ticket #27).""" sources = ('', """""") from kid.template_util import TemplateAttrsError for source in sources: xml = kid.XML("") try: kid.Template(source, xml=xml).serialize() except TemplateAttrsError, e: e = str(e) else: e = 'tag accepted in attribute' assert e == 'Illegal value for attribute "content"' text = "Résultat de la requête" xml = kid.XML(text) s = kid.Template(source, xml=xml).serialize(encoding='ascii') assert s.endswith('' % text) PK3C8B kid/test/test_kid_lang.pyc; [PFc@s^dZdZdZdkZdZdZdZdZdZd Z d Z dS( s $Rev: 421 $s"David Stanek sCopyright 2005, David StanekNcCsJd}tid|i}d|jptd|jptdS(s9A py:strip without an expression will strip that element.s stuff ssourceswrapperspresentN(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid_lang.pystest_strip_no_expr s cCsd}tid|ttf}d|ijpttid|ttf}d|ijpttid|ttf}d|ijpttid|ttf}|iiddjptdS(s1Test for the bug that was reported in ticket #97.s content content ssourcesiN( ssource_templateskidsTemplatesTruests serializesAssertionErrorsFalsescount(stssource_template((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid_lang.pys&test_strip_with_boolean_expression__ors cCsJd}tid|i}d|jptd|jptdS(Ns ssources you will never see this ssourceswrappersx(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid_lang.pys test_replace6scCsJd}tid|i}d|jptd|jptdS(s=py:strip as ignored if py:replace exists in the same element.s content ssourceswrappersxN(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid_lang.pystest_replace_with_stripBs cCs?d}tid|i}|iddjptdS(Ns  ssourcesi(ssourceskidsTemplates serializesdatascountsAssertionError(ssourcesdata((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid_lang.pys test_attrOscCsOd}tid|i}|GHd|jptd|jptdS(Ns ssourcesa="1"sb="2"(ssourceskidsTemplates serializesdatasAssertionError(ssourcesdata((s:build/bdist.darwin-8.0.1-x86/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((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_kid_lang.pys?s   PK3C8腺XZZkid/test/test_suffixes.pyc; [PFc@sdZdZdZdZdkZdklZdkl Z dk l Z l Z dk Z dklZd Zd Zd Zd Zd ZdS(s<Unit Tests for the import extensions and path functionality.s $Rev: 455 $s"David Stanek sCopyright 2005, David StanekN(sjoin(smkdtemp(srmtreescopyfile(sraisescCsHtddatiitttdattdiddS(Nsprefixskid_test_suffixes_stest_suffixes0.kidsws~

my content

( smkdtempstmpdirskidspathsinsertsjoinpathstfilesopenswrite(smodule((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_suffixes.pys setup_modules cCstiitttdS(N(skidspathsremovestmpdirsrmtree(smodule((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_suffixes.pysteardown_modulescCsptiidtzEtittdtidk }ttdtiWdtii tXdS(s$By default *.kid files are imported.isimport test_suffixes0Nsimport test_suffixes1( ssysspathsinsertstmpdirskidsdisable_importsraisess ImportErrors enable_importstest_suffixes0sremove(stest_suffixes0((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_suffixes.pystest_enable_import_empty s     cCsd}tiidtzttdttdttdtid|t td}t t |dk }t td }t t |dk}t td }t t |dk}t td }t t |ttd tiWdtiitXdS( s0Using exts any file extension can be importable.s.html,.kid.htmlisimport test_suffixes1simport test_suffixes2simport test_suffixes3sextstest_suffixes1.kidNstest_suffixes2.htmlstest_suffixes3.kid.htmlstest_suffixes4.xhtmlsimport test_suffixes4(sextssysspathsinsertstmpdirsraisess ImportErrorskids enable_importsjoinpathsdestscopyfilestfilestest_suffixes1stest_suffixes2stest_suffixes3sdisable_importsremove(stest_suffixes1stest_suffixes3sdestsextstest_suffixes2((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_suffixes.pystest_enable_import_with_ext-s.           cCsttijptttdtidtttd}t t |dk }ti dtttd}t t |ttddS(s4Using path any template directory can be importable.simport test_suffixes4spathstest_suffixes4.kidNstest_suffixes5.kidsimport test_suffixes5(stmpdirssysspathsAssertionErrorsraisess ImportErrorskids enable_importsjoinpathsdestscopyfilestfilestest_suffixes4sdisable_import(stest_suffixes4sdest((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_suffixes.pystest_enable_import_with_pathFs    (s__doc__s __revision__s __author__s __copyright__ssyssos.pathsjoinsjoinpathstempfilesmkdtempsshutilsrmtreescopyfileskids kid.test.utilsraisess setup_modulesteardown_modulestest_enable_import_emptystest_enable_import_with_extstest_enable_import_with_path(scopyfiles __copyright__s __revision__smkdtempstest_enable_import_with_extsteardown_modules setup_modules __author__ssysstest_enable_import_with_pathsraisessjoinpathstest_enable_import_emptyskidsrmtree((s:build/bdist.darwin-8.0.1-x86/egg/kid/test/test_suffixes.pys?s       PK+C8lMJEGG-INFO/SOURCES.txtPK+C8w>>EGG-INFO/entry_points.txtPK+C82UEGG-INFO/dependency_links.txtPK*C8؋HEGG-INFO/PKG-INFOPK*C8 !kEGG-INFO/top_level.txtPK4C82EGG-INFO/not-zip-safePK0C8~G$`"`"kid/importer.pycPKZ86C8kid/namespace.pyPKZ86ϐuuL?kid/codewriter.pyPK1C8+MMNMN kid/parser.pycPKZ86v9AAkid/__init__.pyPK0C8JdL&L&nEkid/compiler.pycPK1C8F\ kkid/run.pycPKZ86E }kid/util.pyPKZ86.p"" kid/server.pyPK1C8yy77Mkid/release.pycPKZ86_1RRkid/importer.pyPKZ86 \zz0kid/compiler.pyPK1C8@((kid/element.pycPKY86zkid/options.pyPKZ86k"-((!kid/template_util.pyPK1C8AJkid/compile.pycPKZ869 < < Ykid/parser.pyPKY86 ~_ _  kid/compile.pyPK1C8-33kid/template_util.pycPKY86KQQkid/element.pyPKY86]dUdU %kid/format.pyPK0C8qW @kid/util.pycPKZ86Xu Tkid/run.pyPK0C83''fkid/server.pycPK4C82<< ݎkid/pull.pycPK96ce"11Ckid/release.pyPK1C8?;))kid/serialization.pycPK0C8gVVkid/__init__.pycPKZ86@(Onkid/serialization.pyPK0C8.{{kid/codewriter.pycPK1C8eBBlkid/options.pycPK4C8; {kid/filter.pycPK1C81UUkid/format.pycPKZ86+G!! ikid/pull.pyPK0C8eU U kid/namespace.pycPKZ86 7kid/filter.pyPKY86|00/kid/test/test_namespace.pyPK2C8QwG/@@kid/test/test_kid.pycPK2C8""?kid/test/test_match.pycPKY86E'bkid/test/test_serialization_escaping.pyPKY86}Aqkid/test/test_compiler.pyPKY86ٓ((xkid/test/__init__.pyPK3C87\\!.}kid/test/test_extended_layout.pycPKY86i\ggɌkid/test/test_layout.pyPK1C8_(ekid/test/test_serialization_escaping.pycPK4C8 W )Ukid/test/test_attribute_interpolation.pycPKY86f||kid/test/util.pyPK3C8\\Okid/test/test_parser.pycPKY86; kid/test/test_codewriter.pyPK2C8b|qBBkid/test/test_error.pycPKY869"=kid/test/test_options.pyPK2C8v/ S S Ekid/test/test_codewriter.pycPK3C8\l~Rkid/test/test_templatepath.pycPKY86)*hkid/test/test_comment.pyPK2C8m PP|kid/test/test_unicode.pycPKY86^ Kgjjjkid/test/test_unicode.pyPK1C8An` kid/test/test_compiler.pycPK3C8 @``[kid/test/test_serialization.pycPKY86222kid/test/test_error.pyPK3C8S];#;#g$kid/test/test_element.pycPK2C8|0Gkid/test/test_layout.pycPKY86r[kid/test/test_match.pyPK3C8U6g##*xkid/test/test_extends.pycPKY86I/9l#l#kid/test/test_kid.pyPKY86R2! ! kid/test/test_extended_layout.pyPK2C8 __kid/test/test_comment.pycPKY86gl l kid/test/test_templatepath.pyPKY86B+ 4kid/test/test_kid_lang.pyPKY86 vvV kid/test/test_format.pyPK3C8fJ@x kid/test/test_scope.pycPK3C84N kid/test/test_format.pycPK2C8rHhh kid/test/util.pycPKY86b7 kid/test/test_scope.pyPKY86.эiFiF; kid/test/test_serialization.pyPKY86.A% % \ kid/test/test_suffixes.pyPK1C8  kid/test/test_namespace.pycPK2C8Yv<<ږ kid/test/__init__.pycPKY86TI kid/test/test_extends.pyPK2C8O1 1 6 kid/test/test_options.pycPKY86cT kid/test/test_parser.pyPKY86Lgg kid/test/test_element.pyPKY86B;;(w kid/test/test_attribute_interpolation.pyPK3C8B  kid/test/test_kid_lang.pycPK3C8腺XZZ kid/test/test_suffixes.pycPKZZs"