meld3-0.6.10/0000755000076500000240000000000012055263644013537 5ustar mnaberezstaff00000000000000meld3-0.6.10/CHANGES.txt0000644000076500000240000003473612055263341015357 0ustar mnaberezstaff000000000000000.6.10 (2012-11-27) Fixed a bug where an exception could be raised when escaping certain attribute or cdata values. This was caused by meld3 trying to use _encode_entity from xml.etree without importing it first. Thanks to Jorge Puente Sarrin for contributing the patch. 0.6.9 (2012-09-12) ------------------ Fixed a test failure that only occurred on some builds of Python 2.7 where parsing an unknown entity could raise an expat.error instead of SyntaxError. 0.6.8 (2012-01-12) ------------------ Added the C extension source (cmeld3.c) to the release package by including it in MANIFEST.in. Thanks to Soren Hansen for noticing it was missing from prior releases. Running setup.py will now halt on error if a compatible version of Python is not detected. 0.6.7 (2010-08-04) ------------------ Make compatible with Python 2.7 (patch kindly contributed by Jonathan Riboux). 0.6.6 (2009-09-30) ------------------ Change download location. This really should be a setuptools package so we can upload it to PyPI. No functionality changes. 0.6.5 (2008-07-21) ------------------ Apply patch for Python 2.5 compatibility from both Toshio and Anders. Create distro tarball via: rm MANIFEST USE_MELD3_EXTENSION_MODULES=1 python setup.py sdist .. in order to get the cmeld3.c file in the distribution. 0.6.4 (2008-01-17) ------------------ Make the default build use the Python-based meld "helper" instead of the C-based one. Since the primary consumer of meld3 (as far as I know) is "supervisor", and since the typical supervisor consumer is likely not to have a C compiler and Python development libraries on his system, it makes more sense for the default build not to compile the C extensions. However, if the environment variable "USE_MELD3_EXTENSION_MODULES" is set when "setup.py install" is invoked, the C extensions will be built. meld3 is much slower without the C extensions, so using "USE_MELD3_EXTENSION_MODULES" is usually a good idea for performance-sensitive systems. As a result of this change, the "NO_MELD3_EXTENSION_MODULES" environment variable introduced in 0.6.1 now has no effect. 0.6.3 (2007-08-25) ------------------ Fixed two more memory leaks (one in bfclonehandler, the other in findmeldhandler) in the c helper module. 0.6.2 (2007-08-23) ------------------ Fixed a number of memory leaks in the C implementation of the helper module. Any use of "findmeld", "clone", "getiterator", or "content" previously leaked references. 0.6.1 (2007-08-21) ------------------ Allow people to install meld3 without building extension modules. If the environment variable "NO_MELD3_EXTENSION_MODULES" is set, the meld3 setup.py file will not build any extension modules. meld3 will still work, only more slowly than if the extension modules existed. 0.6 (2006-09-18) ---------------- Fixed crashbug when repeating trees with "structure" nodes in them. Symptom: bus error. Thanks to Terrence Brannon for the report. 0.5 (2006-02-19) ---------------- Add 'fillmeldhtmlform' method to nodes. Fix obscure parsing bug that arose when attempting to change the URI used as a "meld id" (do not lowercase). Added three methods to element nodes: write_htmlstring write_xmlstring write_xhtmlstring These methods have the same respective argument lists as their "write_foo" cousins, except they don't accept a "file" argument. Instead of writing to a file, they return a string containing the renderering of the element. You can now use the meld3.py module to interactively try out different renderings. To do this, invoke meld3.py with a filename and a dotted-python-path name to a mutator function that accepts a single argument (the root element), e.g.: python meld3.py sample.html meld3.sample_mutator The rendering will be sent to stdout Remove unused parse method. Add __setslice__, __delslice__, remove methods that correctly update parent pointers. Don't call into superclass to do append, insert, __setitem__, etc. Internal speedups: - Avoid function call overhead in various places by inlining code. - _write_html/_write_xml now accept a callable "write" argument instead of a file argument (avoid file.write call overhead). - HTML serializer only calls _escape_cdata/_escape_attrib if necessary instead of calling it without regard to its need. - Use string.encode(encoding) instead of calling an _encode function. - Perform special-case rendering for English-centric encodings during write_html. - Ignore things that might be "QNames" during rendering. - "getiterator", "content", "clone", and "findmeld" now implemented in a C module. Experimental. Disable via changing "import cmeld3 as helper" in meld3.py to something like "import wontbehere". Fix text and attribute serialization to only quote ampersands that aren't already part of entities. Do the minimal possible thing to escape text and attribute values during rendering. For text, this is escaping ampersands that aren't parts of entities and the less-than (<) character. For attribute values, this is amps and less-than as well as the quote (") character. This was done partly because I think the spec allows it but it's also what Kid does, shrug. Change 'diffmeld()' to return a dictionary of dictionaries. The dictionary returned by diffmeld has the keys 'reduced' and 'unreduced'. the values of both 'reduced' and 'unreduced' is another dictionary. The leafmost dictionary has the keys 'added', 'removed', and 'moved. In the 'unreduced' dictionary, *all* meld tags that have been added, removed, or moved are present (this was the behavior of diffmeld previously). In the 'reduced' dictionary, the added, removed, and moved values are reduced to the smallest number of tags which share a common lineage. Add a meldprofile.py script. 0.4 (2006-01-01) ---------------- The clone() method of elements copied neither the text nor the tail of the element (this is what caused markup created by "repeats" to fall all on one line). Add diffing capability to meld nodes. The file 'melddiff.py' shows an example of using the diff API. Add a 'meldid()' method to elements. This returns None if the element has no meld id, otherwise it returns the id. Add a 'fillmeld(**kw)' method to elements. This does the same thing as '__mod__' but returns meld ids (the keys of **kw) that cannot be found anywhere in the tree. Make source distro into a distutils-installable package. 0.3 (2005-12-26) ---------------- Fix broken example.py file. Add ZPT-alike methods on elements: 'content', 'replace', and 'attributes'. 'content' replaces the node's content; 'replace' replaces the node itself with a text value, and 'attributes' sets the attributes of the node. Using the ElementTree API to do the same things usually causes the code to run faster, but these functions are more convenient and more easily grokked by ZPT people. Override __delitem__ on meld elements in order to relieve deleted items of their parent pointers. Strip all xhtml namespace identifiers out of XHTML output. Browsers just can't deal with this. Undocumented element API method 'remove' renamed to 'deparent' (it was shadowing an ElementTree API method). Documentation improvements and change examples to use ZPT-alike methods. Add support for HTML input files. Input files don't need to be strictly well-formed XML anymore. Remove the 'parse' top-level function in favor of explicit separate xml parsing and html parsing functions. Add 'parse_xml' and 'parse_html' top-level parsing functions. Add 'parse_xmlstring' and 'parse_htmlstring' module-scope functions which calls their respective 'parse_xxx' function with a StringIO containing the passed text. 0.2 (2005-12-24) ---------------- Use a method on elements to do writing rather than requiring a user call a "write" function. The equivalent is now a method of the element named "write_xml". element.write_xml(file) performs a write of XML into the file. element.write_xml(...) includes an XML declaration in its serialization (but no doctype, at least by default). Various non-XML serialization methods have been added. The default arguments of these serialization methods are what I'm guessing are the most common cases desired for various kinds of qoutput:: element.write_html(...). This serializes the node and its children to HTML. This feature was inspired by and based on code Ian Bicking. By default, the serialization will include a 'loose' HTML DTD doctype (this can be overridden with the doctype= argument). "Empty" shortcut elements such as "
" will be converted to a balanced pair of tags e.g. "
". But some HTML tags (defined as per the HTML 4 spec as area, base, basefont, br, col, frame, hr, img, input, isindex, link, meta, param) will not be followed with a balanced ending tag; only the beginning tag will be output. Additionally, "boolean" tag attributes will not be followed with any value. The "boolean" tags are selected, checked, compact, declare, defer, disabled, ismap, multiple, nohref, noresize, noshade, and nowrap. So the XML input "" will be turned into "". Additionally, 'script' and 'style' tags will not have their contents escaped (e.g. so "&" will not be turned into & when it's iside the textual content of a script or style tag.) element.write_xhtml(...). This serializes the node and its children to XHTML. By default, the serialization will include a 'loose' XHTML doctype (this can be overridden with the doctype= argument). No XML declaration is included in the serialization by default. If you want to serialize an XML declaration, pass 'declaration=True'. All serialization methods have a number of optional arguments:: fragment: If this is true, serialize an element as a "fragment". When an element is serialized as a fragment, it will not include either a declaration nor a doctype (the declaration= and doctype= arguments will be ignored). doctype: Output a custom doctype during the writing of XML and HTML (see write, write_xml, write_xhtml, and write_html). Use the constants in meld3.doctype (xhtml, xhtml_strict, html, and html_strict) to avoid passing a literal 3-tuple of (name, pubid, system) as the doctype parameter. If fragment=True is specified for serialization, this argument has no effect. encoding: Specify a character encoding to be used during writing (see write, write_xml write_html, and write_xhtml). The encoding must be a valid Python codec name (e.g. 'utf-8'). If this is provided for write_xml and write_xhtml, and the XML declaration is serialized, the declaration will include the encoding. If an encoding is passed to write_html, no explicit encoding is included in the declaration but the serialization will be done with utf-8. XML serializations (write_xml and write_xhtml) have the aforementioned arguments but expose two additional optional arguments:: declaration: If this is true, an xml declaration header is output during the writing of XML (see write, write_xml, and write_xhtml). If the encoding is specified, and the serialization is meant to include an XML declaration (via declaration=), the declaration will include the encoding. If 'fragment=True' is specified for serialization, this argument has no effect. It doesn't matter if your input document had a declaration header; this option must be used to control declaration output. pipeline: If this is true, allow meld identifiers to be preserved during the writing of XML and XHTML (see write, write_xml and write_xhtml). meld identifiers cannot be preserved on HTML serializations because HTML doesn't understand namespaces. HTML entities can now be parsed properly (magically) when a DOCTYPE is not supplied in the source of the XML passed to 'parse'. If your source document does not contain a DOCTYPE declaration, the DOCTYPE is set to 'loose' XHTML 'by magic'. If your source document does contain a DOCTYPE declaration, the existing DOCTYPE is used (and HTML entities thus may or may not work as a result, depending on the DOCTYPE). To prevent this behavior, pass a false value to the xhtml= parameter of the 'parse' function. This in no way effects output, which is independent of parsing. This does not imply that any *non*-HTML entity can be parsed in the input stream under any circumstance without having it defined it in your source document. Comments are now preserved in output. They are also present in the ElementTree node tree (as Comment elements), so beware. Processing instructions (e.g. ) are completely thrown away at parse time and do not exist anywhere in the element tree. Avoid use of deepcopy in the clone() method of elements (much speedier to explicitly recurse). The "meld helper" namespace (e.g. element.meld) is no longer present or supported. Instead of using element.meld['foo'] to find an element with the meld:id "foo", use element.findmeld('foo'). This returns None if the node cannot be found. Instead of using element.meld.get('foo', 'somedefault'), use element.findmeld('foo', 'somedefault'). Instead of using element.meld.repeat(...), use element.repeat(...). Elements now support a __mod__ which can accept a dictionarylike operand and which causes the text of elements with meld ids which match the keys in the dictionary to be set to the key's value in the dictionary. For example, if an element contains subelements with the meld ids "foo" and "bar", you can replace those nodes' text values with the following:: element % {'foo':'foo text', 'bar':'bar text'} __mod__ will not accept a non-dictionary-like object (such as a list or tuple). __mod__ will never raise an error unless you pass it a non-dictionary-like object; if it can't find a node corresponding to a key in the dictionary, it moves on to the next key. Only the text values of the nodes which are found during this process are replaced. Using duplicate meld identifiers on separate elements in the document now causes a ValueError to be raised at parse time. 0.1 (2005-12-18) ---------------- Initial release. meld3-0.6.10/COPYRIGHT.txt0000644000076500000240000000067611722530176015656 0ustar mnaberezstaff00000000000000Copyright (c) 2005-2012 Chris McDonough. All Rights Reserved. This software is subject to the provisions of the Zope Public License, Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. meld3-0.6.10/LICENSE.txt0000644000076500000240000000420311722530176015356 0ustar mnaberezstaff00000000000000Zope Public License (ZPL) Version 2.1 ------------------------------------- A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. meld3-0.6.10/meld3/0000755000076500000240000000000012055263644014543 5ustar mnaberezstaff00000000000000meld3-0.6.10/meld3/__init__.py0000644000076500000240000000023411722530176016650 0ustar mnaberezstaff00000000000000# make these easier to import from meld3 import parse_xml from meld3 import parse_html from meld3 import parse_xmlstring from meld3 import parse_htmlstring meld3-0.6.10/meld3/clearsilverprofile.py0000644000076500000240000000316512023761722021011 0ustar mnaberezstaff00000000000000import sys import profile as profiler import pstats import neo_cgi # XXX yuck, must import before neo_util even though not used. import neo_util import neo_cs template = """ This is the title
This is the head slot
""" hdf = neo_util.HDF() for i in range(0, 20): hdf.setValue('values.%d.0' % i, str(i)) hdf.setValue('values.%d.1' % i, str(i)) def test(cs): this_cs = cs(hdf) this_cs.parseStr(template) foo = this_cs.render() def profile(num): ## import cProfile ## profiler = cProfile profiler.run("[test(cs) for x in range(0,100)]", 'logfile.dat') stats = pstats.Stats('logfile.dat') stats.strip_dirs() stats.sort_stats('cumulative', 'calls') #stats.sort_stats('calls') stats.print_stats(num) if __name__ == '__main__': cs = neo_cs.CS test(cs) profile(30) import timeit t = timeit.Timer("test(cs)", "from __main__ import test, cs") repeat = 50 number = 50 result = t.repeat(repeat, number) best = min(result) print "%d loops " % repeat usec = best * 1e6 / number msec = usec / 1000 print "best of %d: %.*g msec per loop" % (repeat, 8, msec) meld3-0.6.10/meld3/cmeld3.c0000644000076500000240000002373611722530176016066 0ustar mnaberezstaff00000000000000#include /* fprintf(stderr, "%s:%s:%d\n", __FILE__,__FUNCTION__,__LINE__); fflush(stderr); */ static PyObject *PySTR__class__, *PySTR__dict__, *PySTR_children; static PyObject *PySTRattrib, *PySTRparent, *PySTR_MELD_ID; static PyObject *PySTRtag, *PySTRtext, *PySTRtail, *PySTRstructure; static PyObject *PySTRReplace; static PyObject *emptyattrs, *emptychildren = NULL; static PyObject* bfclone(PyObject *nodes, PyObject *parent) { int len, i; if (!(PyList_Check(nodes))) { return NULL; } len = PyList_Size(nodes); if (len < 0) { return NULL; } PyObject *L; if (!(L = PyList_New(0))) return NULL; for (i = 0; i < len; i++) { PyObject *node; if (!(node = PyList_GetItem(nodes, i))) { return NULL; } PyObject *klass; PyObject *children; PyObject *text; PyObject *tail; PyObject *tag; PyObject *attrib; PyObject *structure; PyObject *dict; PyObject *newdict; PyObject *newchildren; PyObject *attrib_copy; PyObject *element; int childsize; if (!(klass = PyObject_GetAttr(node, PySTR__class__))) return NULL; if (!(dict = PyObject_GetAttr(node, PySTR__dict__))) return NULL; if (!(children = PyDict_GetItem(dict, PySTR_children))) return NULL; if (!(tag = PyDict_GetItem(dict, PySTRtag))) return NULL; if (!(attrib = PyDict_GetItem(dict, PySTRattrib))) return NULL; if (!(text = PyDict_GetItem(dict, PySTRtext))) { text = Py_None; } if (!(tail = PyDict_GetItem(dict, PySTRtail))) { tail = Py_None; } if (!(structure = PyDict_GetItem(dict, PySTRstructure))) { structure = Py_None; } Py_DECREF(dict); if (!(newdict = PyDict_New())) return NULL; if (!(newchildren = PyList_New(0))) return NULL; attrib_copy = PyDict_Copy(attrib); PyDict_SetItem(newdict, PySTR_children, newchildren); Py_DECREF(newchildren); PyDict_SetItem(newdict, PySTRattrib, attrib_copy); Py_DECREF(attrib_copy); PyDict_SetItem(newdict, PySTRtext, text); PyDict_SetItem(newdict, PySTRtail, tail); PyDict_SetItem(newdict, PySTRtag, tag); PyDict_SetItem(newdict, PySTRstructure, structure); PyDict_SetItem(newdict, PySTRparent, parent); if (!(element = PyInstance_NewRaw(klass, newdict))) { return NULL; } Py_DECREF(newdict); Py_DECREF(klass); if (PyList_Append(L, element)) { return NULL; } Py_DECREF(element); if (!PyList_Check(children)) return NULL; if ((childsize = PyList_Size(children)) < 0) { return NULL; } else { if (childsize > 0) { bfclone(children, element); } } } if (PyObject_SetAttr(parent, PySTR_children, L)) return NULL; Py_DECREF(L); return parent; } static PyObject* bfclonehandler(PyObject *self, PyObject *args) { PyObject *node, *parent; if (!PyArg_ParseTuple(args, "OO:clone", &node, &parent)) { return NULL; } PyObject *klass; PyObject *children; PyObject *text; PyObject *tail; PyObject *tag; PyObject *attrib; PyObject *structure; PyObject *dict; PyObject *newdict; PyObject *newchildren; PyObject *attrib_copy; PyObject *element; if (!(klass = PyObject_GetAttr(node, PySTR__class__))) return NULL; if (!(dict = PyObject_GetAttr(node, PySTR__dict__))) return NULL; if (!(children = PyDict_GetItem(dict, PySTR_children))) return NULL; if (!(tag = PyDict_GetItem(dict, PySTRtag))) return NULL; if (!(attrib = PyDict_GetItem(dict, PySTRattrib))) return NULL; if (!(text = PyDict_GetItem(dict, PySTRtext))) { text = Py_None; } if (!(tail = PyDict_GetItem(dict, PySTRtail))) { tail = Py_None; } if (!(structure = PyDict_GetItem(dict, PySTRstructure))) { structure = Py_None; } Py_DECREF(dict); if (!(newdict = PyDict_New())) return NULL; if (!(newchildren = PyList_New(0))) return NULL; attrib_copy = PyDict_Copy(attrib); PyDict_SetItem(newdict, PySTR_children, newchildren); Py_DECREF(newchildren); PyDict_SetItem(newdict, PySTRattrib, attrib_copy); Py_DECREF(attrib_copy); PyDict_SetItem(newdict, PySTRtext, text); PyDict_SetItem(newdict, PySTRtail, tail); PyDict_SetItem(newdict, PySTRtag, tag); PyDict_SetItem(newdict, PySTRstructure, structure); PyDict_SetItem(newdict, PySTRparent, parent); if (!(element = PyInstance_NewRaw(klass, newdict))) return NULL; Py_DECREF(newdict); Py_DECREF(klass); PyObject *pchildren; if (parent != Py_None) { if (!(pchildren=PyObject_GetAttr(parent, PySTR_children))) return NULL; if (PyList_Append(pchildren, element)) return NULL; Py_DECREF(pchildren); } if (!(PyList_Check(children))) return NULL; if (PyList_Size(children) > 0) { if (bfclone(children, element) == NULL) { return NULL; } } return element; } PyDoc_STRVAR(bfclonehandler_doc, "bfclone(node, parent=None)\n \ \n\ Return a clone of the meld3 node named by node (breadth-first). If parent\n\ is not None, append the clone to the parent.\n"); static PyObject* getiterator(PyObject *node, PyObject *list) { if (PyList_Append(list, node) == -1) { return NULL; } PyObject *children; PyObject *child; if (!(children = PyObject_GetAttr(node, PySTR_children))) { return NULL; } int len, i; len = PyList_Size(children); if (len < 0) { return NULL; } for (i = 0; i < len; i++) { if (!(child = PyList_GetItem(children, i))) { return NULL; } getiterator(child, list); } Py_DECREF(children); return list; } static PyObject* getiteratorhandler(PyObject *self, PyObject *args) { PyObject *node; if (!PyArg_ParseTuple(args, "O:getiterator", &node)) { return NULL; } PyObject *list; PyObject *result; if (!(list = PyList_New(0))) { return NULL; } result = getiterator(node, list); if (result == NULL) { PyList_SetSlice(list, 0, PyList_GET_SIZE(list), (PyObject *)NULL); Py_DECREF(list); } return result; } PyDoc_STRVAR(getiteratorhandler_doc, "getiterator(node)\n\ \n\ Returns an iterator for the node."); static char* _MELD_ID = "{http://www.plope.com/software/meld3}id"; /*static PyObject *PySTR_MELD_ID = PyString_FromString(_MELD_ID);*/ static PyObject* findmeld(PyObject *node, PyObject *name) { PyObject *attrib, *meldid, *result; if (!(attrib = PyObject_GetAttr(node, PySTRattrib))) return NULL; meldid = PyDict_GetItem(attrib, PySTR_MELD_ID); Py_DECREF(attrib); if (meldid != NULL) { int compareresult = PyUnicode_Compare(meldid, name); if (compareresult == 0) { Py_INCREF(node); return node; } } int len, i; result = Py_None; PyObject *children = PyObject_GetAttr(node, PySTR_children); len = PyList_Size(children); for (i = 0; i < len; i++) { PyObject *child = PyList_GetItem(children, i); result = findmeld(child, name); if (result != Py_None) { break; } } Py_DECREF(children); return result; } static PyObject* findmeldhandler(PyObject *self, PyObject *args) { PyObject *node, *name, *result; if (!PyArg_ParseTuple(args, "OO:findmeld", &node, &name)) { return NULL; } if (!(result = findmeld(node, name))) return NULL; if (result == Py_None) { Py_INCREF(Py_None); } return result; } PyDoc_STRVAR(findmeldhandler_doc, "findmeld(node, meldid)\n\ \n\ Return a meld node or None.\n"); static PyObject* contenthandler(PyObject *self, PyObject *args) { PyObject *node, *text, *structure; if (!PyArg_ParseTuple(args, "OOO:content", &node, &text, &structure)) { return NULL; } PyObject *replacel = NULL; PyObject *replace = NULL; PyObject *replacenode = NULL; PyObject *newchildren = NULL; PyObject *newdict = NULL; PyObject *klass = NULL; if (!(klass = PyObject_GetAttr(node, PySTR__class__))) return NULL; if (!(replacel = PyObject_GetAttr(node, PySTRReplace))) return NULL; if (!(replace = PyList_GetItem(replacel, 0))) return NULL; Py_DECREF(replacel); PyObject_SetAttr(node, PySTRtext, Py_None); if (!(newdict = PyDict_New())) return NULL; if (PyDict_SetItem(newdict, PySTRparent, node) == -1) return NULL; if (PyDict_SetItem(newdict, PySTRattrib, emptyattrs) == -1) return NULL; if (PyDict_SetItem(newdict, PySTRtext, text) == -1) return NULL; if (PyDict_SetItem(newdict, PySTRstructure, structure) == -1) return NULL; if (PyDict_SetItem(newdict, PySTRtag, replace) == -1) return NULL; if (PyDict_SetItem(newdict, PySTR_children, emptychildren) == -1) { return NULL; } if (!(replacenode = PyInstance_NewRaw(klass, newdict))) return NULL; Py_DECREF(klass); Py_DECREF(newdict); if (!(newchildren = PyList_New(1))) return NULL; PyList_SET_ITEM(newchildren, 0, replacenode); // steals a reference to rn PyObject_SetAttr(node, PySTR_children, newchildren); Py_DECREF(newchildren); Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(contenthandler_doc, "content(node, text, structure)\n\ \n\ Add a content node to node."); static PyMethodDef methods[] = { {"bfclone", bfclonehandler, METH_VARARGS, bfclonehandler_doc}, {"getiterator", getiteratorhandler, METH_VARARGS, getiteratorhandler_doc}, {"findmeld", findmeldhandler, METH_VARARGS, findmeldhandler_doc}, {"content", contenthandler, METH_VARARGS, contenthandler_doc}, {NULL, NULL} }; PyMODINIT_FUNC initcmeld3(void) { #define DEFINE_STRING(s) \ if (!(PySTR##s = PyString_FromString(#s))) return DEFINE_STRING(__class__); DEFINE_STRING(__dict__); DEFINE_STRING(_children); DEFINE_STRING(parent); DEFINE_STRING(tag); DEFINE_STRING(attrib); DEFINE_STRING(text); DEFINE_STRING(tail); DEFINE_STRING(structure); DEFINE_STRING(Replace); #undef DEFINE_STRING PySTR_MELD_ID = PyString_FromString(_MELD_ID); if (!PySTR_MELD_ID) { return; } emptyattrs = PyDict_New(); /* emptyattrs = PyDictProxy_New(emptyattrs); can't copy a proxy, so... */ emptychildren = PyList_New(0); Py_InitModule3("cmeld3", methods, "C helpers for meld3"); } meld3-0.6.10/meld3/example.py0000644000076500000240000000301411722530176016543 0ustar mnaberezstaff00000000000000xml = """ This is the title
Name Description
Name Description
""" from meld3 import parse_xmlstring from meld3 import parse_htmlstring from StringIO import StringIO import sys root = parse_xmlstring(xml) root.findmeld('title').content('My document') root.findmeld('form1').attributes(action='./handler') data = ( {'name':'Boys', 'description':'Ugly'}, {'name':'Girls', 'description':'Pretty'}, ) iterator = root.findmeld('tr').repeat(data) for element, item in iterator: element.findmeld('td1').content(item['name']) element.findmeld('td2').content(item['description']) root.write_xhtml(sys.stdout) meld3-0.6.10/meld3/meld3.py0000644000076500000240000014475512055262013016126 0ustar mnaberezstaff00000000000000import htmlentitydefs import os import re import types import mimetools import string from StringIO import StringIO try: from elementtree.ElementTree import TreeBuilder from elementtree.ElementTree import XMLTreeBuilder from elementtree.ElementTree import Comment from elementtree.ElementTree import ProcessingInstruction from elementtree.ElementTree import QName from elementtree.ElementTree import _raise_serialization_error from elementtree.ElementTree import _namespace_map from elementtree.ElementTree import _encode_entity from elementtree.ElementTree import fixtag from elementtree.ElementTree import parse as et_parse from elementtree.ElementTree import ElementPath except ImportError: from xml.etree.ElementTree import TreeBuilder from xml.etree.ElementTree import XMLTreeBuilder from xml.etree.ElementTree import Comment from xml.etree.ElementTree import ProcessingInstruction from xml.etree.ElementTree import QName from xml.etree.ElementTree import _raise_serialization_error from xml.etree.ElementTree import _namespace_map from xml.etree.ElementTree import parse as et_parse from xml.etree.ElementTree import ElementPath try: from xml.etree.ElementTree import _encode_entity except ImportError: # python 2.7 def _encode_entity(text): pattern = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"')) _escape_map = { "&": "&", "<": "<", ">": ">", '"': """, } def _encode(s, encoding): try: return s.encode(encoding) except AttributeError: return s def escape_entities(m, map=_escape_map): out = [] append = out.append for char in m.group(): text = map.get(char) if text is None: text = "&#%d;" % ord(char) append(text) return string.join(out, "") try: return _encode(pattern.sub(escape_entities, text), "ascii") except TypeError: raise TypeError( "cannot serialize %r (type %s)" % (text, type(text).__name__) ) try: from xml.etree.ElementTree import fixtag except ImportError: # python 2.7 def fixtag(tag, namespaces): # given a decorated tag (of the form {uri}tag), return prefixed # tag and namespace declaration, if any if isinstance(tag, QName): tag = tag.text namespace_uri, tag = string.split(tag[1:], "}", 1) prefix = namespaces.get(namespace_uri) if prefix is None: prefix = _namespace_map.get(namespace_uri) if prefix is None: prefix = "ns%d" % len(namespaces) namespaces[namespace_uri] = prefix if prefix == "xml": xmlns = None else: xmlns = ("xmlns:%s" % prefix, namespace_uri) else: xmlns = None return "%s:%s" % (prefix, tag), xmlns # HTMLTreeBuilder does not exist in python 2.5 standard elementtree from HTMLParser import HTMLParser AUTOCLOSE = "p", "li", "tr", "th", "td", "head", "body" IGNOREEND = "img", "hr", "meta", "link", "br" is_not_ascii = re.compile(eval(r'u"[\u0080-\uffff]"')).search # replace element factory def Replace(text, structure=False): element = _MeldElementInterface(Replace, {}) element.text = text element.structure = structure return element class IO: def __init__(self): self.data = "" def write(self, data): self.data += data def getvalue(self): return self.data def clear(self): self.data = "" class PyHelper: def findmeld(self, node, name, default=None): iterator = self.getiterator(node) for element in iterator: val = element.attrib.get(_MELD_ID) if val == name: return element return default def clone(self, node, parent=None): # NOTE: this is not implemented by the C version (it used to be # but I don't want to maintain it) element = _MeldElementInterface(node.tag, node.attrib.copy()) element.text = node.text element.tail = node.tail element.structure = node.structure if parent is not None: # avoid calling self.append to reduce function call overhead parent._children.append(element) element.parent = parent for child in node._children: self.clone(child, element) return element def _bfclone(self, nodes, parent): L = [] for node in nodes: element = _MeldElementInterface(node.tag, node.attrib.copy()) element.parent = parent element.text = node.text element.tail = node.tail element.structure = node.structure if node._children: self._bfclone(node._children, element) L.append(element) parent._children = L def bfclone(self, node, parent=None): element = _MeldElementInterface(node.tag, node.attrib.copy()) element.text = node.text element.tail = node.tail element.structure = node.structure element.parent = parent if parent is not None: parent._children.append(element) if node._children: self._bfclone(node._children, element) return element def getiterator(self, node, tag=None): nodes = [] if tag == "*": tag = None if tag is None or node.tag == tag: nodes.append(node) for element in node._children: nodes.extend(self.getiterator(element, tag)) return nodes def content(self, node, text, structure=False): node.text = None replacenode = Replace(text, structure) replacenode.parent = node replacenode.text = text replacenode.structure = structure node._children = [replacenode] pyhelper = PyHelper() try: import cmeld3 as chelper except ImportError: chelper = None if chelper and not os.getenv('MELD3_PYIMPL'): helper = chelper else: helper = pyhelper _MELD_NS_URL = 'http://www.plope.com/software/meld3' _MELD_PREFIX = '{%s}' % _MELD_NS_URL _MELD_LOCAL = 'id' _MELD_ID = '%s%s' % (_MELD_PREFIX, _MELD_LOCAL) _MELD_SHORT_ID = 'meld:%s' % _MELD_LOCAL _XHTML_NS_URL = 'http://www.w3.org/1999/xhtml' _XHTML_PREFIX = '{%s}' % _XHTML_NS_URL _XHTML_PREFIX_LEN = len(_XHTML_PREFIX) _marker = [] class doctype: # lookup table for ease of use in external code 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') 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') class _MeldElementInterface: parent = None attrib = None text = None tail = None structure = None Replace = [Replace] # this is used by C code # overrides to reduce MRU lookups def __init__(self, tag, attrib): self.tag = tag self.attrib = attrib self._children = [] def __repr__(self): return "" % (self.tag, id(self)) def __len__(self): return len(self._children) def __getitem__(self, index): return self._children[index] def __getslice__(self, start, stop): return self._children[start:stop] def getchildren(self): return self._children def find(self, path): return ElementPath.find(self, path) def findtext(self, path, default=None): return ElementPath.findtext(self, path, default) def findall(self, path): return ElementPath.findall(self, path) def clear(self): self.attrib.clear() self._children = [] self.text = self.tail = None def get(self, key, default=None): return self.attrib.get(key, default) def set(self, key, value): self.attrib[key] = value def keys(self): return self.attrib.keys() def items(self): return self.attrib.items() def getiterator(self, *ignored_args, **ignored_kw): # we ignore any tag= passed in to us, because it's too painful # to support in our C version return helper.getiterator(self) # overrides to support parent pointers and factories def __setitem__(self, index, element): self._children[index] = element element.parent = self def __setslice__(self, start, stop, elements): for element in elements: element.parent = self self._children[start:stop] = list(elements) def append(self, element): self._children.append(element) element.parent = self def insert(self, index, element): self._children.insert(index, element) element.parent = self def __delitem__(self, index): ob = self._children[index] ob.parent = None del self._children[index] def __delslice__(self, start, stop): obs = self._children[start:stop] for ob in obs: ob.parent = None del self._children[start:stop] def remove(self, element): self._children.remove(element) element.parent = None def makeelement(self, tag, attrib): return self.__class__(tag, attrib) # meld-specific def __mod__(self, other): """ Fill in the text values of meld nodes in tree; only support dictionarylike operand (sequence operand doesn't seem to make sense here)""" return self.fillmelds(**other) def fillmelds(self, **kw): """ Fill in the text values of meld nodes in tree using the keyword arguments passed in; use the keyword keys as meld ids and the keyword values as text that should fill in the node text on which that meld id is found. Return a list of keys from **kw that were not able to be found anywhere in the tree. Never raises an exception. """ unfilled = [] for k in kw: node = self.findmeld(k) if node is None: unfilled.append(k) else: node.text = kw[k] return unfilled def fillmeldhtmlform(self, **kw): """ Perform magic to 'fill in' HTML form element values from a dictionary. Unlike 'fillmelds', the type of element being 'filled' is taken into consideration. Perform a 'findmeld' on each key in the dictionary and use the value that corresponds to the key to perform mutation of the tree, changing data in what is presumed to be one or more HTML form elements according to the following rules:: If the found element is an 'input group' (its meld id ends with the string ':inputgroup'), set the 'checked' attribute on the appropriate subelement which has a 'value' attribute which matches the dictionary value. Also remove the 'checked' attribute from every other 'input' subelement of the input group. If no input subelement's value matches the dictionary value, this key is treated as 'unfilled'. If the found element is an 'input type=text', 'input type=hidden', 'input type=submit', 'input type=password', 'input type=reset' or 'input type=file' element, replace its 'value' attribute with the value. If the found element is an 'input type=checkbox' or 'input type='radio' element, set its 'checked' attribute to true if the dict value is true, or remove its 'checked' attribute if the dict value is false. If the found element is a 'select' element and the value exists in the 'value=' attribute of one of its 'option' subelements, change that option's 'selected' attribute to true and mark all other option elements as unselected. If the select element does not contain an option with a value that matches the dictionary value, do nothing and return this key as unfilled. If the found element is a 'textarea' or any other kind of element, replace its text with the value. If the element corresponding to the key is not found, do nothing and treat the key as 'unfilled'. Return a list of 'unfilled' keys, representing meld ids present in the dictionary but not present in the element tree or meld ids which could not be filled due to the lack of any matching subelements for 'select' nodes or 'inputgroup' nodes. """ unfilled = [] for k in kw: node = self.findmeld(k) if node is None: unfilled.append(k) continue val = kw[k] if k.endswith(':inputgroup'): # an input group is a list of input type="checkbox" or # input type="radio" elements that can be treated as a group # because they attempt to specify the same value found = [] unfound = [] for child in node.findall('input'): input_type = child.attrib.get('type', '').lower() if input_type not in ('checkbox', 'radio'): continue input_val = child.attrib.get('value', '') if val == input_val: found.append(child) else: unfound.append(child) if not found: unfilled.append(k) else: for option in found: option.attrib['checked'] = 'checked' for option in unfound: try: del option.attrib['checked'] except KeyError: pass else: tag = node.tag.lower() if tag == 'input': input_type = node.attrib.get('type', 'text').lower() # fill in value attrib for most input types if input_type in ('hidden', 'submit', 'text', 'password', 'reset', 'file'): node.attrib['value'] = val # unless it's a checkbox or radio attribute, then we # fill in its checked attribute elif input_type in ('checkbox', 'radio'): if val: node.attrib['checked'] = 'checked' else: try: del node.attrib['checked'] except KeyError: pass else: unfilled.append(k) elif tag == 'select': # if the node is a select node, we want to select # the value matching val, otherwise it's unfilled found = [] unfound = [] for option in node.findall('option'): if option.attrib.get('value', '') == val: found.append(option) else: unfound.append(option) if not found: unfilled.append(k) else: for option in found: option.attrib['selected'] = 'selected' for option in unfound: try: del option.attrib['selected'] except KeyError: pass else: node.text = kw[k] return unfilled def findmeld(self, name, default=None): """ Find a node in the tree that has a 'meld id' corresponding to 'name'. Iterate over all subnodes recursively looking for a node which matches. If we can't find the node, return None.""" # this could be faster if we indexed all the meld nodes in the # tree; we just walk the whole hierarchy now. result = helper.findmeld(self, name) if result is None: return default return result def findmelds(self): """ Find all nodes that have a meld id attribute and return the found nodes in a list""" return self.findwithattrib(_MELD_ID) def findwithattrib(self, attrib, value=None): """ Find all nodes that have an attribute named 'attrib'. If 'value' is not None, omit nodes on which the attribute value does not compare equally to 'value'. Return the found nodes in a list.""" iterator = helper.getiterator(self) elements = [] for element in iterator: attribval = element.attrib.get(attrib) if attribval is not None: if value is None: elements.append(element) else: if value == attribval: elements.append(element) return elements # ZPT-alike methods def repeat(self, iterable, childname=None): """repeats an element with values from an iterable. If 'childname' is not None, repeat the element on which the repeat is called, otherwise find the child element with a 'meld:id' matching 'childname' and repeat that. The element is repeated within its parent element (nodes that are created as a result of a repeat share the same parent). This method returns an iterable; the value of each iteration is a two-sequence in the form (newelement, data). 'newelement' is a clone of the template element (including clones of its children) which has already been seated in its parent element in the template. 'data' is a value from the passed in iterable. Changing 'newelement' (typically based on values from 'data') mutates the element 'in place'.""" if childname: element = self.findmeld(childname) else: element = self parent = element.parent # creating a list is faster than yielding a generator (py 2.4) L = [] first = True for thing in iterable: if first is True: clone = element else: clone = helper.bfclone(element, parent) L.append((clone, thing)) first = False return L def replace(self, text, structure=False): """ Replace this element with a Replace node in our parent with the text 'text' and return the index of our position in our parent. If we have no parent, do nothing, and return None. Pass the 'structure' flag to the replace node so it can do the right thing at render time. """ parent = self.parent i = self.deparent() if i is not None: # reduce function call overhead by not calliing self.insert node = Replace(text, structure) parent._children.insert(i, node) node.parent = parent return i def content(self, text, structure=False): """ Delete this node's children and append a Replace node that contains text. Always return None. Pass the 'structure' flag to the replace node so it can do the right thing at render time.""" helper.content(self, text, structure) def attributes(self, **kw): """ Set attributes on this node. """ for k, v in kw.items(): # prevent this from getting to the parser if possible if not isinstance(k, types.StringTypes): raise ValueError, 'do not set non-stringtype as key: %s' % k if not isinstance(v, types.StringTypes): raise ValueError, 'do not set non-stringtype as val: %s' % v self.attrib[k] = kw[k] # output methods def write_xmlstring(self, encoding=None, doctype=None, fragment=False, declaration=True, pipeline=False): data = [] write = data.append if not fragment: if declaration: _write_declaration(write, encoding) if doctype: _write_doctype(write, doctype) _write_xml(write, self, encoding, {}, pipeline) return ''.join(data) def write_xml(self, file, encoding=None, doctype=None, fragment=False, declaration=True, pipeline=False): """ Write XML to 'file' (which can be a filename or filelike object) encoding - encoding string (if None, 'utf-8' encoding is assumed) Must be a recognizable Python encoding type. doctype - 3-tuple indicating name, pubid, system of doctype. The default is to prevent a doctype from being emitted. fragment - True if a 'fragment' should be emitted for this node (no declaration, no doctype). This causes both the 'declaration' and 'doctype' parameters to become ignored if provided. declaration - emit an xml declaration header (including an encoding if it's not None). The default is to emit the doctype. pipeline - preserve 'meld' namespace identifiers in output for use in pipelining """ if not hasattr(file, "write"): file = open(file, "wb") data = self.write_xmlstring(encoding, doctype, fragment, declaration, pipeline) file.write(data) def write_htmlstring(self, encoding=None, doctype=doctype.html, fragment=False): data = [] write = data.append if encoding is None: encoding = 'utf8' if encoding in ('utf8', 'utf-8', 'latin-1', 'latin1', 'ascii'): # optimize for common dumb-American case (only encode once at # the end) if not fragment: if doctype: _write_doctype(write, doctype) _write_html_no_encoding(write, self, {}) joined = ''.join(data) return joined else: if not fragment: if doctype: _write_doctype(write, doctype) _write_html(write, self, encoding, {}) joined = ''.join(data) return joined def write_html(self, file, encoding=None, doctype=doctype.html, fragment=False): """ Write HTML to 'file' (which can be a filename or filelike object) encoding - encoding string (if None, 'utf-8' encoding is assumed). Unlike XML output, this is not used in a declaration, but it is used to do actual character encoding during output. Must be a recognizable Python encoding type. doctype - 3-tuple indicating name, pubid, system of doctype. The default is the value of doctype.html (HTML 4.0 'loose') fragment - True if a "fragment" should be omitted (no doctype). This overrides any provided "doctype" parameter if provided. Namespace'd elements and attributes have their namespaces removed during output when writing HTML, so pipelining cannot be performed. HTML is not valid XML, so an XML declaration header is never emitted. """ if not hasattr(file, "write"): file = open(file, "wb") page = self.write_htmlstring(encoding, doctype, fragment) file.write(page) def write_xhtmlstring(self, encoding=None, doctype=doctype.xhtml, fragment=False, declaration=False, pipeline=False): data = [] write = data.append if not fragment: if declaration: _write_declaration(write, encoding) if doctype: _write_doctype(write, doctype) _write_xml(write, self, encoding, {}, pipeline, xhtml=True) return ''.join(data) def write_xhtml(self, file, encoding=None, doctype=doctype.xhtml, fragment=False, declaration=False, pipeline=False): """ Write XHTML to 'file' (which can be a filename or filelike object) encoding - encoding string (if None, 'utf-8' encoding is assumed) Must be a recognizable Python encoding type. doctype - 3-tuple indicating name, pubid, system of doctype. The default is the value of doctype.xhtml (XHTML 'loose'). fragment - True if a 'fragment' should be emitted for this node (no declaration, no doctype). This causes both the 'declaration' and 'doctype' parameters to be ignored. declaration - emit an xml declaration header (including an encoding string if 'encoding' is not None) pipeline - preserve 'meld' namespace identifiers in output for use in pipelining """ # use a list as a collector, and only call the write method of # the file once we've collected all output (reduce function call # overhead) data = [] write = data.append if not hasattr(file, "write"): file = open(file, "wb") page = self.write_xhtmlstring(encoding, doctype, fragment, declaration, pipeline) file.write(page) def clone(self, parent=None): """ Create a clone of an element. If parent is not None, append the element to the parent. Recurse as necessary to create a deep clone of the element. """ return helper.bfclone(self, parent) def deparent(self): """ Remove ourselves from our parent node (de-parent) and return the index of the parent which was deleted. """ i = self.parentindex() if i is not None: del self.parent[i] return i def parentindex(self): """ Return the parent node index in which we live """ parent = self.parent if parent is not None: return parent._children.index(self) def shortrepr(self, encoding=None): data = [] _write_html(data.append, self, encoding, {}, maxdepth=2) return ''.join(data) def diffmeld(self, other): """ Compute the meld element differences from this node (the source) to 'other' (the target). Return a dictionary of sequences in the form {'unreduced: {'added':[], 'removed':[], 'moved':[]}, 'reduced': {'added':[], 'removed':[], 'moved':[]},} """ srcelements = self.findmelds() tgtelements = other.findmelds() srcids = [ x.meldid() for x in srcelements ] tgtids = [ x.meldid() for x in tgtelements ] removed = [] for srcelement in srcelements: if srcelement.meldid() not in tgtids: removed.append(srcelement) added = [] for tgtelement in tgtelements: if tgtelement.meldid() not in srcids: added.append(tgtelement) moved = [] for srcelement in srcelements: srcid = srcelement.meldid() if srcid in tgtids: i = tgtids.index(srcid) tgtelement = tgtelements[i] if not sharedlineage(srcelement, tgtelement): moved.append(tgtelement) unreduced = {'added':added, 'removed':removed, 'moved':moved} moved_reduced = diffreduce(moved) added_reduced = diffreduce(added) removed_reduced = diffreduce(removed) reduced = {'moved':moved_reduced, 'added':added_reduced, 'removed':removed_reduced} return {'unreduced':unreduced, 'reduced':reduced} def meldid(self): return self.attrib.get(_MELD_ID) def lineage(self): L = [] parent = self while parent is not None: L.append(parent) parent = parent.parent return L def MeldTreeBuilder(): return TreeBuilder(element_factory=_MeldElementInterface) class MeldParser(XMLTreeBuilder): """ A parser based on Fredrik's PIParser at http://effbot.org/zone/element-pi.htm. It blithely ignores the case of a comment existing outside the root element and ignores processing instructions entirely. We need to validate that there are no repeated meld id's in the source as well """ def __init__(self, html=0, target=None): XMLTreeBuilder.__init__(self, html, target) # assumes ElementTree 1.2.X self._parser.CommentHandler = self.handle_comment self.meldids = {} def handle_comment(self, data): self._target.start(Comment, {}) self._target.data(data) self._target.end(Comment) def _start(self, tag, attrib_in): # this is used by self._parser (an Expat parser) as # StartElementHandler but only if _start_list is not # provided... so why does this method exist? for key in attrib_in: if '{' + key == _MELD_ID: meldid = attrib_in[key] if self.meldids.get(meldid): raise ValueError, ('Repeated meld id "%s" in source' % meldid) self.meldids[meldid] = 1 return XMLTreeBuilder._start(self, tag, attrib_in) def _start_list(self, tag, attrib_in): # This is used by self._parser (an Expat parser) # as StartElementHandler. attrib_in is a flat even-length # sequence of name, value pairs for all attributes. # See http://python.org/doc/lib/xmlparser-objects.html for i in range(0, len(attrib_in), 2): # For some reason, clark names are missing the leading '{' attrib = self._fixname(attrib_in[i]) if _MELD_ID == attrib: meldid = attrib_in[i+1] if self.meldids.get(meldid): raise ValueError, ('Repeated meld id "%s" in source' % meldid) self.meldids[meldid] = 1 return XMLTreeBuilder._start_list(self, tag, attrib_in) def close(self): val = XMLTreeBuilder.close(self) self.meldids = {} return val class HTMLMeldParser(HTMLParser): """ A mostly-cut-and-paste of ElementTree's HTMLTreeBuilder that does special meld3 things (like preserve comments and munge meld ids). Subclassing is not possible due to private attributes. :-(""" def __init__(self, builder=None, encoding=None): self.__stack = [] if builder is None: builder = MeldTreeBuilder() self.builder = builder self.encoding = encoding or "iso-8859-1" HTMLParser.__init__(self) self.meldids = {} def close(self): HTMLParser.close(self) self.meldids = {} return self.builder.close() def handle_starttag(self, tag, attrs): if tag == "meta": # look for encoding directives http_equiv = content = None for k, v in attrs: if k == "http-equiv": http_equiv = v.lower() elif k == "content": content = v if http_equiv == "content-type" and content: # use mimetools to parse the http header header = mimetools.Message( StringIO("%s: %s\n\n" % (http_equiv, content)) ) encoding = header.getparam("charset") if encoding: self.encoding = encoding if tag in AUTOCLOSE: if self.__stack and self.__stack[-1] == tag: self.handle_endtag(tag) self.__stack.append(tag) attrib = {} if attrs: for k, v in attrs: if k == _MELD_SHORT_ID: k = _MELD_ID if self.meldids.get(v): raise ValueError, ('Repeated meld id "%s" in source' % v) self.meldids[v] = 1 else: k = k.lower() attrib[k] = v self.builder.start(tag, attrib) if tag in IGNOREEND: self.__stack.pop() self.builder.end(tag) def handle_endtag(self, tag): if tag in IGNOREEND: return lasttag = self.__stack.pop() if tag != lasttag and lasttag in AUTOCLOSE: self.handle_endtag(lasttag) self.builder.end(tag) def handle_charref(self, char): if char[:1] == "x": char = int(char[1:], 16) else: char = int(char) if 0 <= char < 128: self.builder.data(chr(char)) else: self.builder.data(unichr(char)) def handle_entityref(self, name): entity = htmlentitydefs.entitydefs.get(name) if entity: if len(entity) == 1: entity = ord(entity) else: entity = int(entity[2:-1]) if 0 <= entity < 128: self.builder.data(chr(entity)) else: self.builder.data(unichr(entity)) else: self.unknown_entityref(name) def handle_data(self, data): if isinstance(data, type('')) and is_not_ascii(data): # convert to unicode, but only if necessary data = unicode(data, self.encoding, "ignore") self.builder.data(data) def unknown_entityref(self, name): pass # ignore by default; override if necessary def handle_comment(self, data): self.builder.start(Comment, {}) self.builder.data(data) self.builder.end(Comment) def do_parse(source, parser): root = et_parse(source, parser=parser).getroot() iterator = root.getiterator() for p in iterator: for c in p: c.parent = p return root def parse_xml(source): """ Parse source (a filelike object) into an element tree. If html is true, use a parser that can resolve somewhat ambiguous HTML into XHTML. Otherwise use a 'normal' parser only.""" builder = MeldTreeBuilder() parser = MeldParser(target=builder) return do_parse(source, parser) def parse_html(source, encoding=None): builder = MeldTreeBuilder() parser = HTMLMeldParser(builder, encoding) return do_parse(source, parser) def parse_xmlstring(text): source = StringIO(text) return parse_xml(source) def parse_htmlstring(text, encoding=None): source = StringIO(text) return parse_html(source, encoding) attrib_needs_escaping = re.compile(r'[&"<]').search cdata_needs_escaping = re.compile(r'[&<]').search def _both_case(mapping): # Add equivalent upper-case keys to mapping. lc_keys = mapping.keys() for k in lc_keys: mapping[k.upper()] = mapping[k] _HTMLTAGS_UNBALANCED = {'area':1, 'base':1, 'basefont':1, 'br':1, 'col':1, 'frame':1, 'hr':1, 'img':1, 'input':1, 'isindex':1, 'link':1, 'meta':1, 'param':1} _both_case(_HTMLTAGS_UNBALANCED) _HTMLTAGS_NOESCAPE = {'script':1, 'style':1} _both_case(_HTMLTAGS_NOESCAPE) _HTMLATTRS_BOOLEAN = {'selected':1, 'checked':1, 'compact':1, 'declare':1, 'defer':1, 'disabled':1, 'ismap':1, 'multiple':1, 'nohref':1, 'noresize':1, 'noshade':1, 'nowrap':1} _both_case(_HTMLATTRS_BOOLEAN) def _write_html(write, node, encoding, namespaces, depth=-1, maxdepth=None): " Write HTML to file """ if encoding is None: encoding = 'utf-8' tag = node.tag tail = node.tail text = node.text tail = node.tail to_write = "" if tag is Replace: if not node.structure: if cdata_needs_escaping(text): text = _escape_cdata(text) write(text.encode(encoding)) elif tag is Comment: if cdata_needs_escaping(text): text = _escape_cdata(text) write(''.encode(encoding)) elif tag is ProcessingInstruction: if cdata_needs_escaping(text): text = _escape_cdata(text) write(''.encode(encoding)) else: xmlns_items = [] # new namespaces in this scope try: if tag[:1] == "{": if tag[:_XHTML_PREFIX_LEN] == _XHTML_PREFIX: tag = tag[_XHTML_PREFIX_LEN:] else: tag, xmlns = fixtag(tag, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(tag) to_write += "<%s" % tag.encode(encoding) attrib = node.attrib if attrib is not None: if len(attrib) > 1: attrib_keys = attrib.keys() attrib_keys.sort() else: attrib_keys = attrib for k in attrib_keys: try: if k[:1] == "{": continue except TypeError: _raise_serialization_error(k) if k in _HTMLATTRS_BOOLEAN: to_write += ' ' + k.encode(encoding) else: v = attrib[k] to_write += " %s=\"%s\"" % (k, v) for k, v in xmlns_items: to_write += " %s=\"%s\"" % (k, v) to_write += ">" if text is not None and text: if tag in _HTMLTAGS_NOESCAPE: to_write += text.encode(encoding) elif cdata_needs_escaping(text): to_write += _escape_cdata(text) else: to_write += text.encode(encoding) write(to_write) for child in node._children: if maxdepth is not None: depth = depth + 1 if depth < maxdepth: _write_html(write, child, encoding, namespaces, depth, maxdepth) elif depth == maxdepth and text: write(' [...]\n') else: _write_html(write, child, encoding, namespaces, depth, maxdepth) if text or node._children or tag not in _HTMLTAGS_UNBALANCED: write("") if tail: if cdata_needs_escaping(tail): write(_escape_cdata(tail)) else: write(tail.encode(encoding)) def _write_html_no_encoding(write, node, namespaces): """ Append HTML to string without any particular unicode encoding. We have a separate function for this due to the fact that encoding while recursing is very expensive if this will get serialized out to utf8 anyway (the encoding can happen afterwards). We append to a string because it's faster than calling any 'write' or 'append' function.""" tag = node.tag tail = node.tail text = node.text tail = node.tail to_write = "" if tag is Replace: if not node.structure: if cdata_needs_escaping(text): text = _escape_cdata_noencoding(text) write(text) elif tag is Comment: if cdata_needs_escaping(text): text = _escape_cdata_noencoding(text) write('') elif tag is ProcessingInstruction: if cdata_needs_escaping(text): text = _escape_cdata_noencoding(text) write('') else: xmlns_items = [] # new namespaces in this scope try: if tag[:1] == "{": if tag[:_XHTML_PREFIX_LEN] == _XHTML_PREFIX: tag = tag[_XHTML_PREFIX_LEN:] else: tag, xmlns = fixtag(tag, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(tag) to_write += "<" + tag attrib = node.attrib if attrib is not None: if len(attrib) > 1: attrib_keys = attrib.keys() attrib_keys.sort() else: attrib_keys = attrib for k in attrib_keys: try: if k[:1] == "{": continue except TypeError: _raise_serialization_error(k) if k in _HTMLATTRS_BOOLEAN: to_write += ' ' + k else: v = attrib[k] to_write += " %s=\"%s\"" % (k, v) for k, v in xmlns_items: to_write += " %s=\"%s\"" % (k, v) to_write += ">" if text is not None and text: if tag in _HTMLTAGS_NOESCAPE: to_write += text elif cdata_needs_escaping(text): to_write += _escape_cdata_noencoding(text) else: to_write += text write(to_write) for child in node._children: _write_html_no_encoding(write, child, namespaces) if text or node._children or tag not in _HTMLTAGS_UNBALANCED: write("") if tail: if cdata_needs_escaping(tail): write(_escape_cdata_noencoding(tail)) else: write(tail) def _write_xml(write, node, encoding, namespaces, pipeline, xhtml=False): """ Write XML to a file """ if encoding is None: encoding = 'utf-8' tag = node.tag if tag is Comment: write("" % _escape_cdata(node.text, encoding)) elif tag is ProcessingInstruction: write("" % _escape_cdata(node.text, encoding)) elif tag is Replace: if node.structure: # this may produce invalid xml write(node.text.encode(encoding)) else: write(_escape_cdata(node.text, encoding)) else: if xhtml: if tag[:_XHTML_PREFIX_LEN] == _XHTML_PREFIX: tag = tag[_XHTML_PREFIX_LEN:] if node.attrib: items = node.attrib.items() else: items = [] # must always be sortable. xmlns_items = [] # new namespaces in this scope try: if tag[:1] == "{": tag, xmlns = fixtag(tag, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(tag) write("<" + tag.encode(encoding)) if items or xmlns_items: items.sort() # lexical order for k, v in items: try: if k[:1] == "{": if not pipeline: if k == _MELD_ID: continue k, xmlns = fixtag(k, namespaces) if xmlns: xmlns_items.append(xmlns) if not pipeline: # special-case for HTML input if k == 'xmlns:meld': continue except TypeError: _raise_serialization_error(k) write(" %s=\"%s\"" % (k.encode(encoding), _escape_attrib(v, encoding))) for k, v in xmlns_items: write(" %s=\"%s\"" % (k.encode(encoding), _escape_attrib(v, encoding))) if node.text or node._children: write(">") if node.text: write(_escape_cdata(node.text, encoding)) for n in node._children: _write_xml(write, n, encoding, namespaces, pipeline, xhtml) write("") else: write(" />") for k, v in xmlns_items: del namespaces[v] if node.tail: write(_escape_cdata(node.tail, encoding)) # overrides to elementtree to increase speed and get entity quoting correct. nonentity_re = re.compile('&(?!([#\w]*;))') # negative lookahead assertion def _escape_cdata(text, encoding=None): # escape character data try: if encoding: try: text = text.encode(encoding) except UnicodeError: return _encode_entity(text) text = nonentity_re.sub('&', text) text = text.replace("<", "<") return text except (TypeError, AttributeError): _raise_serialization_error(text) def _escape_attrib(text, encoding=None): # escape attribute value try: if encoding: try: text = text.encode(encoding) except UnicodeError: return _encode_entity(text) # don't requote properly-quoted entities text = nonentity_re.sub('&', text) text = text.replace("<", "<") text = text.replace('"', """) return text except (TypeError, AttributeError): _raise_serialization_error(text) def _escape_cdata_noencoding(text): # escape character data text = nonentity_re.sub('&', text) text = text.replace("<", "<") return text def _escape_attrib_noencoding(text): # don't requote properly-quoted entities text = nonentity_re.sub('&', text) text = text.replace("<", "<") text = text.replace('"', """) return text # utility functions def _write_declaration(write, encoding): if not encoding: write('\n') else: write('\n' % encoding) def _write_doctype(write, doctype): try: name, pubid, system = doctype except (ValueError, TypeError): raise ValueError, ("doctype must be supplied as a 3-tuple in the form " "(name, pubid, system) e.g. '%s'" % doctype.xhtml) write('\n' % (name, pubid, system)) xml_decl_re = re.compile(r'<\?xml .*?\?>') begin_tag_re = re.compile(r'<[^/?!]?\w+') '' % doctype.html def insert_doctype(data, doctype=doctype.xhtml): # jam an html doctype declaration into 'data' if it # doesn't already contain a doctype declaration match = xml_decl_re.search(data) dt_string = '' % doctype if match is not None: start, end = match.span(0) before = data[:start] tag = data[start:end] after = data[end:] return before + tag + dt_string + after else: return dt_string + data def insert_meld_ns_decl(data): match = begin_tag_re.search(data) if match is not None: start, end = match.span(0) before = data[:start] tag = data[start:end] + ' xmlns:meld="%s"' % _MELD_NS_URL after = data[end:] data = before + tag + after return data def prefeed(data, doctype=doctype.xhtml): if data.find(' This is the title
This is the head slot
Name Description
""" values = [] for thing in range(0, 20): values.append((str(thing), str(thing))) def run(root): clone = root.clone() ob = clone.findmeld('tr') for tr, (name, desc) in ob.repeat(values): tr.findmeld('td1').content(name) tr.findmeld('td2').content(desc) foo = clone.write_htmlstring() def profile(num): ## import cProfile ## profiler = cProfile profiler.run("[run(root) for x in range(0,100)]", 'logfile.dat') stats = pstats.Stats('logfile.dat') stats.strip_dirs() stats.sort_stats('cumulative', 'calls') #stats.sort_stats('calls') stats.print_stats(num) if __name__ == '__main__': root = meld3.parse_xmlstring(template) run(root) profile(30) import timeit t = timeit.Timer("run(root)", "from __main__ import run, root") repeat = 50 number = 50 result = t.repeat(repeat, number) best = min(result) print "%d loops " % repeat usec = best * 1e6 / number msec = usec / 1000 print "best of %d: %.*g msec per loop" % (repeat, 8, msec) #run(root, trace=True) meld3-0.6.10/meld3/test_getiterator.py0000644000076500000240000000233012023761722020476 0ustar mnaberezstaff00000000000000import hotshot import hotshot.stats import meld3 # get rid of the noise of setting up an encoding # in profile output '.'.encode('utf-8') template = """ This is the title
This is the head slot
Name Description
""" class IO: def __init__(self): self.data = '' def write(self, data): self.data += data def run(root): clone = root.clone() print clone.getiterator() if __name__ == '__main__': profiler= hotshot.Profile("logfile.dat") root = meld3.parse_xmlstring(template) profiler.run("run(root)") profiler.close() stats = hotshot.stats.load("logfile.dat") stats.strip_dirs() #stats.sort_stats('cumulative', 'calls') stats.sort_stats('calls') stats.print_stats(200) meld3-0.6.10/meld3/test_meld3.py0000644000076500000240000017117212055260437017166 0ustar mnaberezstaff00000000000000import unittest from StringIO import StringIO import re import sys _SIMPLE_XML = r""" Name Description """ _SIMPLE_XHTML = r""" Hello! """ _EMPTYTAGS_HTML = """

""" _BOOLEANATTRS_XHTML= """ """ _ENTITIES_XHTML= r"""

 

""" _COMPLEX_XHTML = r""" This will be escaped in html output: &
Name Description
""" _NVU_HTML = """ test doc Oh yeah...

Yup More Stuff Oh Yeah
1 2 3 4

And an image...

dumb """ _FILLMELDFORM_HTML = """\ Emergency Contacts
Emergency Contacts
Title
First Name
Middle Name
Last Name
Suffix
Address 1
Address 2
City
State
ZIP
Home Phone
Cell/Mobile Phone
Email Address
Over 18? (Checkbox Boolean)
Mail OK? (Checkbox Ternary)
Favorite Color (Radio) Red Green Blue

Return to list

""" class MeldAPITests(unittest.TestCase): def _makeElement(self, string): from meld3 import parse_xmlstring return parse_xmlstring(string) def _makeElementFromHTML(self, string): from meld3 import parse_htmlstring return parse_htmlstring(string) def test_findmeld(self): root = self._makeElement(_SIMPLE_XML) item = root.findmeld('item') self.assertEqual(item.tag, 'item') name = root.findmeld('name') self.assertEqual(name.text, 'Name') def test_findmeld_default(self): root = self._makeElement(_SIMPLE_XML) item = root.findmeld('item') self.assertEqual(item.tag, 'item') unknown = root.findmeld('unknown', 'foo') self.assertEqual(unknown, 'foo') self.assertEqual(root.findmeld('unknown'), None) def test_repeat_nochild(self): root = self._makeElement(_SIMPLE_XML) item = root.findmeld('item') self.assertEqual(item.tag, 'item') data = [{'name':'Jeff Buckley', 'description':'ethereal'}, {'name':'Slipknot', 'description':'heavy'}] for element, d in item.repeat(data): element.findmeld('name').text = d['name'] element.findmeld('description').text = d['description'] self.assertEqual(item[0].text, 'Jeff Buckley') self.assertEqual(item[1].text, 'ethereal') def test_repeat_child(self): root = self._makeElement(_SIMPLE_XML) list = root.findmeld('list') self.assertEqual(list.tag, 'list') data = [{'name':'Jeff Buckley', 'description':'ethereal'}, {'name':'Slipknot', 'description':'heavy'}] for element, d in list.repeat(data, 'item'): element.findmeld('name').text = d['name'] element.findmeld('description').text = d['description'] self.assertEqual(list[0][0].text, 'Jeff Buckley') self.assertEqual(list[0][1].text, 'ethereal') self.assertEqual(list[1][0].text, 'Slipknot') self.assertEqual(list[1][1].text, 'heavy') def test_mod(self): root = self._makeElement(_SIMPLE_XML) root % {'description':'foo', 'name':'bar'} name = root.findmeld('name') self.assertEqual(name.text, 'bar') desc = root.findmeld('description') self.assertEqual(desc.text, 'foo') def test_fillmelds(self): root = self._makeElement(_SIMPLE_XML) unfilled = root.fillmelds(**{'description':'foo', 'jammyjam':'a'}) desc = root.findmeld('description') self.assertEqual(desc.text, 'foo') self.assertEqual(unfilled, ['jammyjam']) def test_fillmeldhtmlform(self): data = [ {'honorific':'Mr.', 'firstname':'Chris', 'middlename':'Phillips', 'lastname':'McDonough', 'address1':'802 Caroline St.', 'address2':'Apt. 2B', 'city':'Fredericksburg', 'state': 'VA', 'zip':'22401', 'homephone':'555-1212', 'cellphone':'555-1313', 'email':'chrism@plope.com', 'suffix':'Sr.', 'over18':True, 'mailok:inputgroup':'true', 'favorite_color:inputgroup':'Green'}, {'honorific':'Mr.', 'firstname':'Fred', 'middlename':'', 'lastname':'Rogers', 'address1':'1 Imaginary Lane', 'address2':'Apt. 3A', 'city':'Never Never Land', 'state': 'LA', 'zip':'00001', 'homephone':'555-1111', 'cellphone':'555-4444', 'email':'fred@neighborhood.com', 'suffix':'Jr.', 'over18':False, 'mailok:inputgroup':'false','favorite_color:inputgroup':'Yellow',}, {'firstname':'Fred', 'middlename':'', 'lastname':'Rogers', 'address1':'1 Imaginary Lane', 'address2':'Apt. 3A', 'city':'Never Never Land', 'state': 'LA', 'zip':'00001', 'homephone':'555-1111', 'cellphone':'555-4444', 'email':'fred@neighborhood.com', 'suffix':'IV', 'over18':False, 'mailok:inputgroup':'false', 'favorite_color:inputgroup':'Blue', 'notthere':1,}, ] root = self._makeElementFromHTML(_FILLMELDFORM_HTML) clone = root.clone() unfilled = clone.fillmeldhtmlform(**data[0]) self.assertEqual(unfilled, []) self.assertEqual(clone.findmeld('honorific').attrib['value'], 'Mr.') self.assertEqual(clone.findmeld('firstname').attrib['value'], 'Chris') middlename = clone.findmeld('middlename') self.assertEqual(middlename.attrib['value'], 'Phillips') suffix = clone.findmeld('suffix') self.assertEqual(suffix[1].attrib['selected'], 'selected') self.assertEqual(clone.findmeld('over18').attrib['checked'], 'checked') mailok = clone.findmeld('mailok:inputgroup') self.assertEqual(mailok[1].attrib['checked'], 'checked') favoritecolor = clone.findmeld('favorite_color:inputgroup') self.assertEqual(favoritecolor[1].attrib['checked'], 'checked') clone = root.clone() unfilled = clone.fillmeldhtmlform(**data[1]) self.assertEqual(unfilled, ['favorite_color:inputgroup']) self.assertEqual(clone.findmeld('over18').attrib.get('checked'), None) mailok = clone.findmeld('mailok:inputgroup') self.assertEqual(mailok[2].attrib['checked'], 'checked') self.assertEqual(mailok[1].attrib.get('checked'), None) clone = root.clone() unfilled = clone.fillmeldhtmlform(**data[2]) self.assertEqual(unfilled, ['notthere', 'suffix']) self.assertEqual(clone.findmeld('honorific').text, None) favoritecolor = clone.findmeld('favorite_color:inputgroup') self.assertEqual(favoritecolor[2].attrib['checked'], 'checked') self.assertEqual(favoritecolor[1].attrib.get('checked'), None) def test_replace_removes_all_elements(self): from meld3 import Replace root = self._makeElement(_SIMPLE_XML) L = root.findmeld('list') L.replace('this is a textual replacement') R = root[0] self.assertEqual(R.tag, Replace) self.assertEqual(len(root.getchildren()), 1) def test_replace_replaces_the_right_element(self): from meld3 import Replace root = self._makeElement(_SIMPLE_XML) D = root.findmeld('description') D.replace('this is a textual replacement') self.assertEqual(len(root.getchildren()), 1) L = root[0] self.assertEqual(L.tag, 'list') self.assertEqual(len(L.getchildren()), 1) I = L[0] self.assertEqual(I.tag, 'item') self.assertEqual(len(I.getchildren()), 2) N = I[0] self.assertEqual(N.tag, 'name') self.assertEqual(len(N.getchildren()), 0) D = I[1] self.assertEqual(D.tag, Replace) self.assertEqual(D.text, 'this is a textual replacement') self.assertEqual(len(D.getchildren()), 0) self.assertEqual(D.structure, False) def test_content(self): from meld3 import Replace root = self._makeElement(_SIMPLE_XML) D = root.findmeld('description') D.content('this is a textual replacement') self.assertEqual(len(root.getchildren()), 1) L = root[0] self.assertEqual(L.tag, 'list') self.assertEqual(len(L.getchildren()), 1) I = L[0] self.assertEqual(I.tag, 'item') self.assertEqual(len(I.getchildren()), 2) N = I[0] self.assertEqual(N.tag, 'name') self.assertEqual(len(N.getchildren()), 0) D = I[1] self.assertEqual(D.tag, 'description') self.assertEqual(D.text, None) self.assertEqual(len(D.getchildren()), 1) T = D[0] self.assertEqual(T.tag, Replace) self.assertEqual(T.text, 'this is a textual replacement') self.assertEqual(T.structure, False) def test_attributes(self): from meld3 import _MELD_ID root = self._makeElement(_COMPLEX_XHTML) D = root.findmeld('form1') D.attributes(foo='bar', baz='1', g='2', action='#') self.assertEqual(D.attrib, { 'foo':'bar', 'baz':'1', 'g':'2', 'method':'POST', 'action':'#', _MELD_ID: 'form1'}) def test_attributes_nonstringtype_raises(self): root = self._makeElement('') self.assertRaises(ValueError, root.attributes, foo=1) class MeldElementInterfaceTests(unittest.TestCase): def _getTargetClass(self): from meld3 import _MeldElementInterface return _MeldElementInterface def _makeOne(self, *arg, **kw): klass = self._getTargetClass() return klass(*arg, **kw) def test_repeat(self): root = self._makeOne('root', {}) from meld3 import _MELD_ID item = self._makeOne('item', {_MELD_ID:'item'}) record = self._makeOne('record', {_MELD_ID:'record'}) name = self._makeOne('name', {_MELD_ID:'name'}) description = self._makeOne('description', {_MELD_ID:'description'}) record.append(name) record.append(description) item.append(record) root.append(item) data = [{'name':'Jeff Buckley', 'description':'ethereal'}, {'name':'Slipknot', 'description':'heavy'}] for element, d in item.repeat(data): element.findmeld('name').text = d['name'] element.findmeld('description').text = d['description'] self.assertEqual(len(root), 2) item1 = root[0] self.assertEqual(len(item1), 1) record1 = item1[0] self.assertEqual(len(record1), 2) name1 = record1[0] desc1 = record1[1] self.assertEqual(name1.text, 'Jeff Buckley') self.assertEqual(desc1.text, 'ethereal') item2 = root[1] self.assertEqual(len(item2), 1) record2 = item2[0] self.assertEqual(len(record2), 2) name2 = record2[0] desc2 = record2[1] self.assertEqual(name2.text, 'Slipknot') self.assertEqual(desc2.text, 'heavy') def test_content_simple_nostructure(self): el = self._makeOne('div', {'id':'thediv'}) el.content('hello') self.assertEqual(len(el._children), 1) replacenode = el._children[0] self.assertEqual(replacenode.parent, el) self.assertEqual(replacenode.text, 'hello') self.assertEqual(replacenode.structure, False) from meld3 import Replace self.assertEqual(replacenode.tag, Replace) def test_content_simple_structure(self): el = self._makeOne('div', {'id':'thediv'}) el.content('hello', structure=True) self.assertEqual(len(el._children), 1) replacenode = el._children[0] self.assertEqual(replacenode.parent, el) self.assertEqual(replacenode.text, 'hello') self.assertEqual(replacenode.structure, True) from meld3 import Replace self.assertEqual(replacenode.tag, Replace) def test_findmeld_simple(self): from meld3 import _MELD_ID el = self._makeOne('div', {_MELD_ID:'thediv'}) self.assertEqual(el.findmeld('thediv'), el) def test_findmeld_simple_oneleveldown(self): from meld3 import _MELD_ID el = self._makeOne('div', {_MELD_ID:'thediv'}) span = self._makeOne('span', {_MELD_ID:'thespan'}) el.append(span) self.assertEqual(el.findmeld('thespan'), span) def test_findmeld_simple_twolevelsdown(self): from meld3 import _MELD_ID el = self._makeOne('div', {_MELD_ID:'thediv'}) span = self._makeOne('span', {_MELD_ID:'thespan'}) a = self._makeOne('a', {_MELD_ID:'thea'}) span.append(a) el.append(span) self.assertEqual(el.findmeld('thea'), a) def test_ctor(self): iface = self._makeOne('div', {'id':'thediv'}) self.assertEqual(iface.parent, None) self.assertEqual(iface.tag, 'div') self.assertEqual(iface.attrib, {'id':'thediv'}) def test_getiterator_simple(self): div = self._makeOne('div', {'id':'thediv'}) iterator = div.getiterator() self.assertEqual(len(iterator), 1) self.assertEqual(iterator[0], div) def test_getiterator(self): div = self._makeOne('div', {'id':'thediv'}) span = self._makeOne('span', {}) span2 = self._makeOne('span', {'id':'2'}) span3 = self._makeOne('span3', {'id':'3'}) span3.text = 'abc' span3.tail = ' ' div.append(span) span.append(span2) span2.append(span3) it = div.getiterator() self.assertEqual(len(it), 4) self.assertEqual(it[0], div) self.assertEqual(it[1], span) self.assertEqual(it[2], span2) self.assertEqual(it[3], span3) def test_getiterator_tag_ignored(self): div = self._makeOne('div', {'id':'thediv'}) span = self._makeOne('span', {}) span2 = self._makeOne('span', {'id':'2'}) span3 = self._makeOne('span3', {'id':'3'}) span3.text = 'abc' span3.tail = ' ' div.append(span) span.append(span2) span2.append(span3) it = div.getiterator(tag='div') self.assertEqual(len(it), 4) self.assertEqual(it[0], div) self.assertEqual(it[1], span) self.assertEqual(it[2], span2) self.assertEqual(it[3], span3) def test_append(self): div = self._makeOne('div', {'id':'thediv'}) span = self._makeOne('span', {}) div.append(span) self.assertEqual(div[0].tag, 'span') self.assertEqual(span.parent, div) def test__setitem__(self): div = self._makeOne('div', {'id':'thediv'}) span = self._makeOne('span', {}) span2 = self._makeOne('span', {'id':'2'}) div.append(span) div[0] = span2 self.assertEqual(div[0].tag, 'span') self.assertEqual(div[0].attrib, {'id':'2'}) self.assertEqual(div[0].parent, div) def test_insert(self): div = self._makeOne('div', {'id':'thediv'}) span = self._makeOne('span', {}) span2 = self._makeOne('span', {'id':'2'}) div.append(span) div.insert(0, span2) self.assertEqual(div[0].tag, 'span') self.assertEqual(div[0].attrib, {'id':'2'}) self.assertEqual(div[0].parent, div) self.assertEqual(div[1].tag, 'span') self.assertEqual(div[1].attrib, {}) self.assertEqual(div[1].parent, div) def test_clone_simple(self): div = self._makeOne('div', {'id':'thediv'}) div.text = 'abc' div.tail = ' ' span = self._makeOne('span', {}) div.append(span) div2 = div.clone() def test_clone(self): div = self._makeOne('div', {'id':'thediv'}) span = self._makeOne('span', {}) span2 = self._makeOne('span', {'id':'2'}) span3 = self._makeOne('span3', {'id':'3'}) span3.text = 'abc' span3.tail = ' ' div.append(span) span.append(span2) span2.append(span3) div2 = div.clone() self.assertEqual(div.tag, div2.tag) self.assertEqual(div.attrib, div2.attrib) self.assertEqual(div[0].tag, div2[0].tag) self.assertEqual(div[0].attrib, div2[0].attrib) self.assertEqual(div[0][0].tag, div2[0][0].tag) self.assertEqual(div[0][0].attrib, div2[0][0].attrib) self.assertEqual(div[0][0][0].tag, div2[0][0][0].tag) self.assertEqual(div[0][0][0].attrib, div2[0][0][0].attrib) self.assertEqual(div[0][0][0].text, div2[0][0][0].text) self.assertEqual(div[0][0][0].tail, div2[0][0][0].tail) self.failIfEqual(id(div), id(div2)) self.failIfEqual(id(div[0]), id(div2[0])) self.failIfEqual(id(div[0][0]), id(div2[0][0])) self.failIfEqual(id(div[0][0][0]), id(div2[0][0][0])) def test_deparent_noparent(self): div = self._makeOne('div', {}) self.assertEqual(div.parent, None) div.deparent() self.assertEqual(div.parent, None) def test_deparent_withparent(self): parent = self._makeOne('parent', {}) self.assertEqual(parent.parent, None) child = self._makeOne('child', {}) parent.append(child) self.assertEqual(parent.parent, None) self.assertEqual(child.parent, parent) self.assertEqual(parent[0], child) child.deparent() self.assertEqual(child.parent, None) self.assertRaises(IndexError, parent.__getitem__, 0) def test_setslice(self): parent = self._makeOne('parent', {}) child1 = self._makeOne('child1', {}) child2 = self._makeOne('child2', {}) child3 = self._makeOne('child3', {}) children = (child1, child2, child3) parent[0:2] = children self.assertEqual(child1.parent, parent) self.assertEqual(child2.parent, parent) self.assertEqual(child3.parent, parent) self.assertEqual(parent._children, list(children)) def test_delslice(self): parent = self._makeOne('parent', {}) child1 = self._makeOne('child1', {}) child2 = self._makeOne('child2', {}) child3 = self._makeOne('child3', {}) children = (child1, child2, child3) parent[0:2] = children del parent[0:2] self.assertEqual(child1.parent, None) self.assertEqual(child2.parent, None) self.assertEqual(child3.parent, parent) self.assertEqual(len(parent._children), 1) def test_remove(self): parent = self._makeOne('parent', {}) child1 = self._makeOne('child1', {}) parent.append(child1) parent.remove(child1) self.assertEqual(child1.parent, None) self.assertEqual(len(parent._children), 0) def test_lineage(self): from meld3 import _MELD_ID div1 = self._makeOne('div', {_MELD_ID:'div1'}) span1 = self._makeOne('span', {_MELD_ID:'span1'}) span2 = self._makeOne('span', {_MELD_ID:'span2'}) span3 = self._makeOne('span', {_MELD_ID:'span3'}) span4 = self._makeOne('span', {_MELD_ID:'span4'}) span5 = self._makeOne('span', {_MELD_ID:'span5'}) span6 = self._makeOne('span', {_MELD_ID:'span6'}) unknown = self._makeOne('span', {}) div2 = self._makeOne('div2', {_MELD_ID:'div2'}) div1.append(span1) span1.append(span2) span2.append(span3) span3.append(unknown) unknown.append(span4) span4.append(span5) span5.append(span6) div1.append(div2) def ids(L): return [ x.meldid() for x in L ] self.assertEqual(ids(div1.lineage()), ['div1']) self.assertEqual(ids(span1.lineage()), ['span1', 'div1']) self.assertEqual(ids(span2.lineage()), ['span2', 'span1', 'div1']) self.assertEqual(ids(span3.lineage()), ['span3', 'span2', 'span1', 'div1']) self.assertEqual(ids(unknown.lineage()), [None, 'span3', 'span2', 'span1', 'div1']) self.assertEqual(ids(span4.lineage()), ['span4', None, 'span3', 'span2', 'span1','div1']) self.assertEqual(ids(span5.lineage()), ['span5', 'span4', None, 'span3', 'span2', 'span1','div1']) self.assertEqual(ids(span6.lineage()), ['span6', 'span5', 'span4', None,'span3', 'span2', 'span1','div1']) self.assertEqual(ids(div2.lineage()), ['div2', 'div1']) def test_shortrepr(self): div = self._makeOne('div', {'id':'div1'}) span = self._makeOne('span', {}) span2 = self._makeOne('span', {'id':'2'}) span3 = self._makeOne('span3', {'id':'3'}) span4 = self._makeOne('span4', {'id':'4'}) span5 = self._makeOne('span5', {'id':'5'}) span6 = self._makeOne('span6', {'id':'6'}) div2 = self._makeOne('div2', {'id':'div2'}) div.append(span) span.append(span2) div.append(div2) r = div.shortrepr() self.assertEqual(r, '
') def test_shortrepr2(self): from meld3 import parse_xmlstring root = parse_xmlstring(_COMPLEX_XHTML) r = root.shortrepr() self.assertEqual(r, '\n \n \n [...]\n\n \n [...]\n') def test_diffmeld1(self): from meld3 import parse_xmlstring from meld3 import _MELD_ID root = parse_xmlstring(_COMPLEX_XHTML) clone = root.clone() div = self._makeOne('div', {_MELD_ID:'newdiv'}) clone.append(div) tr = clone.findmeld('tr') tr.deparent() title = clone.findmeld('title') title.deparent() clone.append(title) # unreduced diff = root.diffmeld(clone) changes = diff['unreduced'] addedtags = [ x.attrib[_MELD_ID] for x in changes['added'] ] removedtags = [x.attrib[_MELD_ID] for x in changes['removed'] ] movedtags = [ x.attrib[_MELD_ID] for x in changes['moved'] ] addedtags.sort() removedtags.sort() movedtags.sort() self.assertEqual(addedtags,['newdiv']) self.assertEqual(removedtags,['td1', 'td2', 'tr']) self.assertEqual(movedtags, ['title']) # reduced changes = diff['reduced'] addedtags = [ x.attrib[_MELD_ID] for x in changes['added'] ] removedtags = [x.attrib[_MELD_ID] for x in changes['removed'] ] movedtags = [ x.attrib[_MELD_ID] for x in changes['moved'] ] addedtags.sort() removedtags.sort() movedtags.sort() self.assertEqual(addedtags,['newdiv']) self.assertEqual(removedtags,['tr']) self.assertEqual(movedtags, ['title']) def test_diffmeld2(self): source = """ """ target = """ """ from meld3 import parse_htmlstring source_root = parse_htmlstring(source) target_root = parse_htmlstring(target) changes = source_root.diffmeld(target_root) # unreduced actual = [x.meldid() for x in changes['unreduced']['moved']] expected = ['b'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['added']] expected = [] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['removed']] expected = [] self.assertEqual(expected, actual) # reduced actual = [x.meldid() for x in changes['reduced']['moved']] expected = ['b'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['added']] expected = [] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['removed']] expected = [] self.assertEqual(expected, actual) def test_diffmeld3(self): source = """ """ target = """ """ from meld3 import parse_htmlstring source_root = parse_htmlstring(source) target_root = parse_htmlstring(target) changes = source_root.diffmeld(target_root) # unreduced actual = [x.meldid() for x in changes['unreduced']['moved']] expected = ['b', 'c'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['added']] expected = ['d', 'e'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['removed']] expected = ['z', 'y'] self.assertEqual(expected, actual) # reduced actual = [x.meldid() for x in changes['reduced']['moved']] expected = ['b'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['added']] expected = ['d'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['removed']] expected = ['z'] self.assertEqual(expected, actual) def test_diffmeld4(self): source = """ """ target = """

""" from meld3 import parse_htmlstring source_root = parse_htmlstring(source) target_root = parse_htmlstring(target) changes = source_root.diffmeld(target_root) # unreduced actual = [x.meldid() for x in changes['unreduced']['moved']] expected = ['a', 'b'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['added']] expected = ['m', 'n'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['removed']] expected = ['c', 'd', 'z', 'y'] self.assertEqual(expected, actual) # reduced actual = [x.meldid() for x in changes['reduced']['moved']] expected = ['a'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['added']] expected = ['m'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['removed']] expected = ['c', 'z'] self.assertEqual(expected, actual) def test_diffmeld5(self): source = """ """ target = """

""" from meld3 import parse_htmlstring source_root = parse_htmlstring(source) target_root = parse_htmlstring(target) changes = source_root.diffmeld(target_root) # unreduced actual = [x.meldid() for x in changes['unreduced']['moved']] expected = ['a', 'b', 'c', 'd'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['added']] expected = [] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['unreduced']['removed']] expected = [] self.assertEqual(expected, actual) # reduced actual = [x.meldid() for x in changes['reduced']['moved']] expected = ['a', 'c'] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['added']] expected = [] self.assertEqual(expected, actual) actual = [x.meldid() for x in changes['reduced']['removed']] expected = [] self.assertEqual(expected, actual) class ParserTests(unittest.TestCase): def _parse(self, *args): from meld3 import parse_xmlstring root = parse_xmlstring(*args) return root def _parse_html(self, *args): from meld3 import parse_htmlstring root = parse_htmlstring(*args) return root def test_parse_simple_xml(self): from meld3 import _MELD_ID root = self._parse(_SIMPLE_XML) self.assertEqual(root.tag, 'root') self.assertEqual(root.parent, None) l1st = root[0] self.assertEqual(l1st.tag, 'list') self.assertEqual(l1st.parent, root) self.assertEqual(l1st.attrib[_MELD_ID], 'list') item = l1st[0] self.assertEqual(item.tag, 'item') self.assertEqual(item.parent, l1st) self.assertEqual(item.attrib[_MELD_ID], 'item') name = item[0] description = item[1] self.assertEqual(name.tag, 'name') self.assertEqual(name.parent, item) self.assertEqual(name.attrib[_MELD_ID], 'name') self.assertEqual(description.tag, 'description') self.assertEqual(description.parent, item) self.assertEqual(description.attrib[_MELD_ID], 'description') def test_parse_simple_xhtml(self): xhtml_ns = '{http://www.w3.org/1999/xhtml}%s' from meld3 import _MELD_ID root = self._parse(_SIMPLE_XHTML) self.assertEqual(root.tag, xhtml_ns % 'html') self.assertEqual(root.attrib, {}) self.assertEqual(root.parent, None) body = root[0] self.assertEqual(body.tag, xhtml_ns % 'body') self.assertEqual(body.attrib[_MELD_ID], 'body') self.assertEqual(body.parent, root) def test_parse_complex_xhtml(self): xhtml_ns = '{http://www.w3.org/1999/xhtml}%s' from meld3 import _MELD_ID root = self._parse(_COMPLEX_XHTML) self.assertEqual(root.tag, xhtml_ns % 'html') self.assertEqual(root.attrib, {}) self.assertEqual(root.parent, None) head = root[0] self.assertEqual(head.tag, xhtml_ns % 'head') self.assertEqual(head.attrib, {}) self.assertEqual(head.parent, root) meta = head[0] self.assertEqual(meta.tag, xhtml_ns % 'meta') self.assertEqual(meta.attrib['content'], 'text/html; charset=ISO-8859-1') self.assertEqual(meta.parent, head) title = head[1] self.assertEqual(title.tag, xhtml_ns % 'title') self.assertEqual(title.attrib[_MELD_ID], 'title') self.assertEqual(title.parent, head) comment = root[1] body = root[2] self.assertEqual(body.tag, xhtml_ns % 'body') self.assertEqual(body.attrib, {}) self.assertEqual(body.parent, root) div1 = body[0] self.assertEqual(div1.tag, xhtml_ns % 'div') self.assertEqual(div1.attrib, {'{http://foo/bar}baz': 'slab'}) self.assertEqual(div1.parent, body) div2 = body[1] self.assertEqual(div2.tag, xhtml_ns % 'div') self.assertEqual(div2.attrib[_MELD_ID], 'content_well') self.assertEqual(div2.parent, body) form = div2[0] self.assertEqual(form.tag, xhtml_ns % 'form') self.assertEqual(form.attrib[_MELD_ID], 'form1') self.assertEqual(form.attrib['action'], '.') self.assertEqual(form.attrib['method'], 'POST') self.assertEqual(form.parent, div2) img = form[0] self.assertEqual(img.tag, xhtml_ns % 'img') self.assertEqual(img.parent, form) table = form[1] self.assertEqual(table.tag, xhtml_ns % 'table') self.assertEqual(table.attrib[_MELD_ID], 'table1') self.assertEqual(table.attrib['border'], '0') self.assertEqual(table.parent, form) tbody = table[0] self.assertEqual(tbody.tag, xhtml_ns % 'tbody') self.assertEqual(tbody.attrib[_MELD_ID], 'tbody') self.assertEqual(tbody.parent, table) tr = tbody[0] self.assertEqual(tr.tag, xhtml_ns % 'tr') self.assertEqual(tr.attrib[_MELD_ID], 'tr') self.assertEqual(tr.attrib['class'], 'foo') self.assertEqual(tr.parent, tbody) td1 = tr[0] self.assertEqual(td1.tag, xhtml_ns % 'td') self.assertEqual(td1.attrib[_MELD_ID], 'td1') self.assertEqual(td1.parent, tr) td2 = tr[1] self.assertEqual(td2.tag, xhtml_ns % 'td') self.assertEqual(td2.attrib[_MELD_ID], 'td2') self.assertEqual(td2.parent, tr) def test_nvu_html(self): from meld3 import _MELD_ID from meld3 import Comment root = self._parse_html(_NVU_HTML) self.assertEqual(root.tag, 'html') self.assertEqual(root.attrib, {}) self.assertEqual(root.parent, None) head = root[0] self.assertEqual(head.tag, 'head') self.assertEqual(head.attrib, {}) self.assertEqual(head.parent, root) meta = head[0] self.assertEqual(meta.tag, 'meta') self.assertEqual(meta.attrib['content'], 'text/html; charset=ISO-8859-1') title = head[1] self.assertEqual(title.tag, 'title') self.assertEqual(title.attrib[_MELD_ID], 'title') self.assertEqual(title.parent, head) body = root[1] self.assertEqual(body.tag, 'body') self.assertEqual(body.attrib, {}) self.assertEqual(body.parent, root) comment = body[0] self.assertEqual(comment.tag, Comment) br1 = body[1] br2 = body[2] table = body[3] self.assertEqual(table.tag, 'table') self.assertEqual(table.attrib, {'style': 'text-align: left; width: 100px;', 'border':'1', 'cellpadding':'2', 'cellspacing':'2'}) self.assertEqual(table.parent, body) br3 = body[4] href = body[5] self.assertEqual(href.tag, 'a') br4 = body[6] br5 = body[7] img = body[8] self.assertEqual(img.tag, 'img') def test_dupe_meldids_fails_parse_xml(self): meld_ns = "http://www.plope.com/software/meld3" repeated = ('' '' % meld_ns) self.assertRaises(ValueError, self._parse, repeated) def test_dupe_meldids_fails_parse_html(self): meld_ns = "http://www.plope.com/software/meld3" repeated = ('' '' % meld_ns) self.assertRaises(ValueError, self._parse_html, repeated) class UtilTests(unittest.TestCase): def test_insert_xhtml_doctype(self): from meld3 import insert_doctype orig = '' actual = insert_doctype(orig) expected = '' self.assertEqual(actual, expected) def test_insert_doctype_after_xmldecl(self): from meld3 import insert_doctype orig = '' actual = insert_doctype(orig) expected = '' self.assertEqual(actual, expected) def test_insert_meld_ns_decl(self): from meld3 import insert_meld_ns_decl orig = '' actual = insert_meld_ns_decl(orig) expected = '' self.assertEqual(actual, expected) def test_prefeed_preserves_existing_meld_ns(self): from meld3 import prefeed orig = '' actual = prefeed(orig) expected = '' self.assertEqual(actual, expected) def test_prefeed_preserves_existing_doctype(self): from meld3 import prefeed orig = '' actual = prefeed(orig) self.assertEqual(actual, orig) class WriterTests(unittest.TestCase): def _parse(self, xml): from meld3 import parse_xmlstring root = parse_xmlstring(xml) return root def _parse_html(self, xml): from meld3 import parse_htmlstring root = parse_htmlstring(xml) return root def _write(self, fn, **kw): out = StringIO() fn(out, **kw) out.seek(0) actual = out.read() return actual def _write_xml(self, node, **kw): return self._write(node.write_xml, **kw) def _write_html(self, node, **kw): return self._write(node.write_html, **kw) def _write_xhtml(self, node, **kw): return self._write(node.write_xhtml, **kw) def assertNormalizedXMLEqual(self, a, b): a = normalize_xml(a) b = normalize_xml(b) self.assertEqual(a, b) def assertNormalizedHTMLEqual(self, a, b): a = normalize_html(a) b = normalize_html(b) self.assertEqual(a, b) def test_write_simple_xml(self): root = self._parse(_SIMPLE_XML) actual = self._write_xml(root) expected = """ Name Description """ self.assertNormalizedXMLEqual(actual, expected) for el, data in root.findmeld('item').repeat(((1,2),)): el.findmeld('name').text = str(data[0]) el.findmeld('description').text = str(data[1]) actual = self._write_xml(root) expected = """ 1 2 """ self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml(self): root = self._parse(_SIMPLE_XHTML) actual = self._write_xhtml(root) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_as_html(self): root = self._parse(_SIMPLE_XHTML) actual = self._write_html(root) expected = """ Hello! """ self.assertNormalizedHTMLEqual(actual, expected) def test_write_complex_xhtml_as_html(self): root = self._parse(_COMPLEX_XHTML) actual = self._write_html(root) expected = """ This will be escaped in html output: &
Name Description
""" self.assertNormalizedHTMLEqual(actual, expected) def test_write_complex_xhtml_as_xhtml(self): # I'm not entirely sure if the cdata "script" quoting in this # test is entirely correct for XHTML. Ryan Tomayko suggests # that escaped entities are handled properly in script tags by # XML-aware browsers at # http://sourceforge.net/mailarchive/message.php?msg_id=10835582 # but I haven't tested it at all. ZPT does not seem to do # this; it outputs unescaped data. root = self._parse(_COMPLEX_XHTML) actual = self._write_xhtml(root) expected = """ This will be escaped in html output: &
Name Description
""" self.assertNormalizedXMLEqual(actual, expected) def test_write_emptytags_html(self): root = self._parse(_EMPTYTAGS_HTML) actual = self._write_html(root) expected = """

""" self.assertEqual(actual, expected) def test_write_booleanattrs_xhtml_as_html(self): root = self._parse(_BOOLEANATTRS_XHTML) actual = self._write_html(root) expected = """ """ self.assertNormalizedHTMLEqual(actual, expected) def test_write_simple_xhtml_pipeline(self): root = self._parse(_SIMPLE_XHTML) actual = self._write_xhtml(root, pipeline=True) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xml_pipeline(self): root = self._parse(_SIMPLE_XML) actual = self._write_xml(root, pipeline=True) expected = """ Name Description """ self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xml_override_encoding(self): root = self._parse(_SIMPLE_XML) from meld3 import doctype actual = self._write_xml(root, encoding="latin-1") expected = """ Name Description """ self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xml_as_fragment(self): root = self._parse(_SIMPLE_XML) from meld3 import doctype actual = self._write_xml(root, fragment=True) expected = """ Name Description """ self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xml_with_doctype(self): root = self._parse(_SIMPLE_XML) from meld3 import doctype actual = self._write_xml(root, doctype=doctype.xhtml) expected = """ Name Description """ self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xml_doctype_nodeclaration(self): root = self._parse(_SIMPLE_XML) from meld3 import doctype actual = self._write_xml(root, declaration=False, doctype=doctype.xhtml) expected = """ Name Description """ self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xml_fragment_kills_doctype_and_declaration(self): root = self._parse(_SIMPLE_XML) from meld3 import doctype actual = self._write_xml(root, declaration=True, doctype=doctype.xhtml, fragment=True) expected = """ Name Description """ self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_override_encoding(self): root = self._parse(_SIMPLE_XHTML) from meld3 import doctype actual = self._write_xhtml(root, encoding="latin-1", declaration=True) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_as_fragment(self): root = self._parse(_SIMPLE_XHTML) from meld3 import doctype actual = self._write_xhtml(root, fragment=True) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_with_doctype(self): root = self._parse(_SIMPLE_XHTML) from meld3 import doctype actual = self._write_xhtml(root, doctype=doctype.xhtml) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_doctype_nodeclaration(self): root = self._parse(_SIMPLE_XHTML) from meld3 import doctype actual = self._write_xhtml(root, declaration=False, doctype=doctype.xhtml) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_fragment_kills_doctype_and_declaration(self): root = self._parse(_SIMPLE_XHTML) from meld3 import doctype actual = self._write_xhtml(root, declaration=True, doctype=doctype.xhtml, fragment=True) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_as_html_fragment(self): root = self._parse(_SIMPLE_XHTML) from meld3 import doctype actual = self._write_html(root, fragment=True) expected = """Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_with_doctype_as_html(self): root = self._parse(_SIMPLE_XHTML) actual = self._write_html(root) expected = """ Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_simple_xhtml_as_html_new_doctype(self): root = self._parse(_SIMPLE_XHTML) from meld3 import doctype actual = self._write_html(root, doctype=doctype.html_strict) expected = """ Hello!""" self.assertNormalizedXMLEqual(actual, expected) def test_write_entities_xhtml_no_doctype(self): root = self._parse_html(_ENTITIES_XHTML) # this will be considered an XHTML document by default; we needn't # declare a doctype actual = self._write_xhtml(root) expected =r"""

 

""" def test_write_entities_xhtml_with_doctype(self): dt = '' root = self._parse_html(dt + _ENTITIES_XHTML) actual = self._write_xhtml(root) expected =r"""

 

""" def test_unknown_entity(self): # exception thrown may vary by python or expat version from xml.parsers import expat self.assertRaises((expat.error, SyntaxError), self._parse, '&fleeb;') def test_content_nostructure(self): root = self._parse(_SIMPLE_XML) D = root.findmeld('description') D.content('description &&', structure=False) actual = self._write_xml(root) expected = """ Name description &<foo>&<bar> """ self.assertNormalizedXMLEqual(actual, expected) def test_content_structure(self): root = self._parse(_SIMPLE_XML) D = root.findmeld('description') D.content('description & ', structure=True) actual = self._write_xml(root) expected = """ Name description & """ self.assertNormalizedXMLEqual(actual, expected) def test_replace_nostructure(self): root = self._parse(_SIMPLE_XML) D = root.findmeld('description') D.replace('description &&', structure=False) actual = self._write_xml(root) expected = """ Name description &<foo>&<bar> """ self.assertNormalizedXMLEqual(actual, expected) def test_replace_structure(self): root = self._parse(_SIMPLE_XML) D = root.findmeld('description') D.replace('description & ', structure=True) actual = self._write_xml(root) expected = """ Name description & """ self.assertNormalizedXMLEqual(actual, expected) def test_escape_cdata(self): a = '< > <& &' && &foo "" http://www.plope.com?foo=bar&bang=baz {' from meld3 import _escape_cdata self.assertEqual('< > <& &' && &foo "" http://www.plope.com?foo=bar&bang=baz {', _escape_cdata(a)) def test_escape_cdata_unicodeerror(self): a = eval(r'u"\u0080"') from meld3 import _escape_cdata self.assertEqual('€', _escape_cdata(a, 'ascii')) def test_escape_attrib(self): a = '< > <& &' && &foo "" http://www.plope.com?foo=bar&bang=baz {' from meld3 import _escape_attrib self.assertEqual('< > <& &' && &foo "" http://www.plope.com?foo=bar&bang=baz {', _escape_attrib(a)) def test_escape_attrib_unicodeerror(self): a = eval(r'u"\u0080"') from meld3 import _escape_attrib self.assertEqual('€', _escape_attrib(a, 'ascii')) def normalize_html(s): s = re.sub(r"[ \t]+", " ", s) s = re.sub(r"/>", ">", s) return s def normalize_xml(s): s = re.sub(r"\s+", " ", s) s = re.sub(r"(?s)\s+<", "<", s) s = re.sub(r"(?s)>\s+", ">", s) return s def test_suite(): suite = unittest.TestSuite() suite.addTest( unittest.makeSuite( MeldAPITests ) ) suite.addTest( unittest.makeSuite( MeldElementInterfaceTests ) ) suite.addTest( unittest.makeSuite( ParserTests ) ) suite.addTest( unittest.makeSuite( WriterTests) ) suite.addTest( unittest.makeSuite( UtilTests) ) return suite def main(): unittest.main(defaultTest='test_suite') if __name__ == '__main__': main() meld3-0.6.10/meld3/testclone.py0000644000076500000240000000246512023761722017117 0ustar mnaberezstaff00000000000000import meld3 import time import timeit parent = meld3._MeldElementInterface('parent', {}) clonable = meld3._MeldElementInterface('root', {}) child1 = clonable.makeelement('child1', {}) child2 = clonable.makeelement('child2', {}) clonable.append(child1) child1.append(child2) for x in range(0, 10): new = child2.makeelement('tag%s'%x, {'x'+str(x):1}) child2.append(new) for x in range(0, 10): new = child1.makeelement('tag%s'%x, {'x'+str(x):1}) child1.append(new) NUM = 1000 def dotimeit(timer, name): repeat = 100 number = 100 result = timer.repeat(repeat, number) best = min(result) usec = best * 1e6 / number msec = usec / 1000 print "%s best of %d: %.*g msec per loop" % (name, repeat, 8, msec) t = timeit.Timer("meld3.chelper.clone(clonable, parent)", "from __main__ import meld3, clonable, parent") dotimeit(t, "C DF") t = timeit.Timer("meld3.chelper.bfclone(clonable, parent)", "from __main__ import meld3, clonable, parent") dotimeit(t, "C BF") t = timeit.Timer("meld3.pyhelper.clone(clonable, parent)", "from __main__ import meld3, clonable, parent") dotimeit(t, "Py DF") t = timeit.Timer("meld3.pyhelper.bfclone(clonable, parent)", "from __main__ import meld3, clonable, parent") dotimeit(t, "Py BF") meld3-0.6.10/meld3/zptprofile.py0000644000076500000240000000366412023761722017317 0ustar mnaberezstaff00000000000000import sys import profile as profiler import pstats sys.path.insert(0, '/Users/chrism/projects/meld/z310/lib/python') from zope.pagetemplate.pagetemplate import PageTemplate class mypt(PageTemplate): def pt_getContext(self, args=(), options={}, **kw): rval = PageTemplate.pt_getContext(self, args=args) options.update(rval) return options template = """ This is the title
This is the head slot
Name Description
""" class IO: def __init__(self): self.data = [] def write(self, data): self.data.append(data) def getvalue(self): return ''.join(self.data) def clear(self): self.data = [] values = [] for thing in range(0, 20): values.append((str(thing), str(thing))) def test(pt): foo = pt(values=values) def profile(num): ## import cProfile ## profiler = cProfile profiler.run("[test(pt) for x in range(0,100)]", 'logfile_zpt.dat') stats = pstats.Stats('logfile_zpt.dat') stats.strip_dirs() stats.sort_stats('cumulative', 'calls') #stats.sort_stats('calls') stats.print_stats(num) if __name__ == '__main__': pt = mypt() pt.write(template) test(pt) profile(30) import timeit t = timeit.Timer("test(pt)", "from __main__ import test, pt") repeat = 50 number = 50 result = t.repeat(repeat, number) best = min(result) print "%d loops " % repeat usec = best * 1e6 / number msec = usec / 1000 print "best of %d: %.*g msec per loop" % (repeat, 8, msec) meld3-0.6.10/PKG-INFO0000644000076500000240000000104612055263644014635 0ustar mnaberezstaff00000000000000Metadata-Version: 1.0 Name: meld3 Version: 0.6.10 Summary: meld3 is an HTML/XML templating engine. Home-page: https://github.com/supervisor/meld3 Author: Mike Naberezny Author-email: mike@naberezny.com License: ZPL 2.1 Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: Operating System :: POSIX Classifier: Programming Language :: Python :: 2 :: Only Classifier: Topic :: Text Processing :: Markup :: HTML meld3-0.6.10/README.txt0000644000076500000240000005277411722530176015251 0ustar mnaberezstaff00000000000000meld3 Overview meld3 is an HTML/XML templating system for Python 2.3+ which keeps template markup and dynamic rendering logic separate from one another. See http://www.entrian.com/PyMeld for a treatise on the benefits of this pattern. meld3 can deal with HTML or XML/XHTML input and can output well-formed HTML or XML/XHTML. meld3 is a variation of Paul Winkler's Meld2, which is itself a variation of Richie Hindle's PyMeld. meld3 uses Frederik Lundh's ElementTree library. Requirements Python 2.3+ ElementTree 1.2+ (http://effbot.org/downloads/#elementtree) Installation Run 'python setup.py install'. Differences from PyMeld - Templates created for use under PyMeld will not work under meld3 due to differences in meld tag identification (meld3's id attributes are in a nondefault XML namespace, PyMeld's are not). Rationale: it should be possible to look at a template and have a good shot at figuring out which pieces of it might get replaced with dynamic content. XML ids are required for other things like CSS styles, so you can't assume if you see an XML id in a template that it was put in there to be a meld identifier. In the worst case scenario, if XML ids were used instead of namespaced id's, and an unused id was present in the source document, the designer would leave it in there even if he wasn't using it because he would think it was a meld id and the programmer would leave it in there even if he wasn't using it because he would think it was being used by the designer's stylesheets. Menawhile, nobody's actually using it and it's just cluttering up the template. Also, having a separate namespace helps the programmer not stomp on the designer by changing identifiers (or needing to grep stylesheets), and lets them avoid fighting over what to call elements. - The "id" attribute used to mark up is in the a separate namespace (aka. xmlns="http://www.plope.com/software/meld3"). So instead of marking up a tag like this: '
', meld3 requires that you qualify the "id" attribute with a "meld" namespace element, like this: '
'. As per the XML namespace specification, the "meld" name is completely optional, and must only represent the "http://www.plope.com/software/meld3" namespace identifier, so '
' is just as valid as as '
' - Output documents by default do not include any meld3 namespace id attributes. If you wish to preserve meld3 ids (for instance, in order to do pipelining of meld3 templates), you can preserve meld ids by passing a "pipeline" option to a "write" function (e.g. write_xml, wwrite_xhtml). - Output can be performed in "XML mode", "XHTML mode" and "HTML mode". HTML output follows recommendations for HTML 4.01, while XML and XHTML output outputs valid XML If you create an empty textarea element and output it in XML and XHTML mode the output will be rendered <'textarea/>'. In HTML mode, it will be rendered as ''. In HTML mode, various other tags like 'img' aren't "balanced" with an ending tag, and so forth. You can decide how you wish to render your templates by passing an 'html' flag to the meld 'writer'. - meld3 elements are instances of ElementTree elements and support the "ElementTree _ElementInterface API":http://effbot.org/zone/pythondoc-elementtree-ElementTree.htm#elementtree.ElementTree._ElementInterface-class) instead of the PyMeld node API. The ElementTree _ElementInterface API has been extended by meld3 to perform various functions specific to meld3. - meld3 elements do not support the __mod__ method with a sequence argument; they do support the __mod__ method with a dictionary argument, however. - meld3 elements support various ZPT-alike methods like "repeat", "content", "attributes", and "replace" that are meant to work like their ZPT counterparts. Examples A valid example meld3 template is as follows:: This is the title
Name Description
Name Description
Note that the script contains no logic, only "meld:id" identifiers. All "meld:id" identifiers in a single document must be unique for a meld template to be parseable. A script which parses the above template and does some transformations is below. Consider the variable "xml" below bound to a string representing the XHTML above:: from meld3 import parse_xmlstring from meld3 import parse_htmlstring from StringIO import StringIO import sys root = parse_xmlstring(xml) root.findmeld('title').content('My document') root.findmeld('form1').attributes(action='./handler') data = ( {'name':'Boys', 'description':'Ugly'}, {'name':'Girls', 'description':'Pretty'}, ) iterator = root.findmeld('tr').repeat(data) for element, item in iterator: element.findmeld('td1').content(item['name']) element.findmeld('td2').content(item['description']) You used the "parse_xmlstring" function to transform the XML into a tree of nodes above. This was possible because the input was well-formed XML. If it had not been, you would have needed to use the "parse_htmlstring" function instead. To output the result of the transformations to stdout as XML, we use the 'write' method of any element. Below, we use the root element (consider it bound to the value of "root" in the above script):: import sys root.write_xml(sys.stdout) ... My document Name Description Boys Ugly Girls Pretty We can also serialize our element tree as well-formed XHTML, which is largely like rendering to XML except it by default doesn't emit the XML declaration and it removes all "html" namespace declarations from the output. It also emits a XHTML 'loose' doctype declaration near the top of the document:: import sys root.write_xhtml(sys.stdout) ... My document
Name Description
Boys Ugly
Girls Pretty
We can also output text in HTML mode, This serializes the node and its children to HTML (this feature was inspired by and based on code Ian Bicking). By default, the serialization will include a 'loose' HTML DTD doctype (this can be overridden with the doctype= argument). "Empty" shortcut elements such as '
' will be converted to a balanced pair of tags e.g. '
'. But some HTML tags (defined as per the HTML 4 spec as area, base, basefont, br, col, frame, hr, img, input, isindex, link, meta, param) will not be followed with a balanced ending tag; only the beginning tag will be output. Additionally, "boolean" tag attributes will not be followed with any value. The "boolean" tags are selected, checked, compact, declare, defer, disabled, ismap, multiple, nohref, noresize, noshade, and nowrap. So the XML input '' will be turned into ''. Additionally, 'script' and 'style' tags will not have their contents escaped (e.g. so "&" will not be turned into '&' when it's iside the textual content of a script or style tag.):: import sys root.write_html(sys.stdout) ... My document
Name Description
Boys Ugly
Girls Pretty
Element API meld3 elements support all of the "ElementTree _ElementInterface API":http://effbot.org/zone/pythondoc-elementtree-ElementTree.htm#elementtree.ElementTree._ElementInterface-class . Other meld-specific methods of elements are as follows:: "clone(parent=None)": clones a node and all of its children via a recursive copy. If parent is passed in, append the clone to the parent node. "findmeld(name, default=None)": searches the this element and its children for elements that have a 'meld:id' attribute that matches "name"; if no element can be found, return the default. "meldid()": Returns the "meld id" of the element or None if the element has no meld id. "repeat(iterable, childname=None)": repeats an element with values from an iterable. If 'childname' is not None, repeat the element on which repeat was called, otherwise find the child element with a 'meld:id' matching 'childname' and repeat that. The element is repeated within its parent element. This method returns an iterable; the value of each iteration is a two-sequence in the form (newelement, data). 'newelement' is a clone of the template element (including clones of its children) which has already been seated in its parent element in the template. 'data' is a value from the passed in iterable. Changing 'newelement' (typically based on values from 'data') mutates the element "in place". "replace(text, structure=False)": (ala ZPT's 'replace' comnand) Replace this element in our parent with a 'Replace' node representing the text 'text'. Return the index of the index position in our parent that was replaced. If 'structure' is true, at rendering time, the outputted text will not be escaped in the serialization. If we have no parent, do nothing, and return None. This method leaves a special kind of node in the element tree (a 'Replace' node) to represent the replacement. NOTE: This command has the potential to cause a non-well-formed XML/HTML serialization at render time if "structure" is True. "content(text, structure=False)": (ala ZPT's 'content' command) Delete every child element in this element and append a Replace node that contains 'text'. Always return None. If 'structure' is true, at rendering time, the outputted text will not be escaped in the serialization. If we have no parent, do nothing, and return None. NOTE: This command has the potential to cause a non-well-formed XML/HTML serialization at render time if "structure" is True. "attributes(**kw)": (ala ZPT's 'attributes' command) For each key value pair in the kw list, add an attribute to this node where the attribute's name is 'key' and the attributes value is 'value'. Keys and values must be string or unicode types, else a ValueError is raised. Returns None. "__mod__(other)": Fill in the text values of meld nodes in this element and children recursively; only support dictionarylike "other" operand (sequence operand doesn't seem to make sense here). "fillmelds(**kw)":Fill in the text values of meld nodes in this element and children recursively. Return the names of keys in the **kw dictionary that could not be found anywhere in the tree. Never raise an exception. "write_xml(file, encoding=None, doctype=None, fragment=False, declaration=True, pipeline=False)": Write XML to 'file' (which can be a filename or filelike object) encoding -- encoding string (if None, 'utf-8' encoding is assumed) Must be a recognizable Python encoding type. doctype -- 3-tuple indicating name, pubid, system of doctype. The default is to prevent a doctype from being emitted. fragment -- True if a 'fragment' should be emitted for this node (no declaration, no doctype). This causes both the 'declaration' and 'doctype' parameters to become ignored if provided. declaration -- emit an xml declaration header (including an encoding if it's not None). The default is to emit the doctype. pipeline -- preserve 'meld' namespace identifiers in output for use in pipelining "write_xhtml(self, file, encoding=None, doctype=doctype.xhtml, fragment=False, declaration=False, pipeline=False)": Write XHTML to 'file' (which can be a filename or filelike object) encoding -- encoding string (if None, 'utf-8' encoding is assumed) Must be a recognizable Python encoding type. doctype -- 3-tuple indicating name, pubid, system of doctype. The default is the value of doctype.xhtml (XHTML 'loose'). fragment -- True if a 'fragment' should be emitted for this node (no declaration, no doctype). This causes both the 'declaration' and 'doctype' parameters to be ignored. declaration -- emit an xml declaration header (including an encoding string if 'encoding' is not None) pipeline -- preserve 'meld' namespace identifiers in output for use in pipelining Note that despite the fact that you can tell meld which doctype to serve, meld does no semantic or syntactical validation of attributes or elements when serving content in XHTML mode; you as a programmer are still responsible for ensuring that your rendering does not include font tags, for instance. Rationale for defaults: By default, 'write_xhtml' doesn't emit an XML declaration because versions of IE before 7 apparently go into "quirks" layout mode when they see an XML declaration, instead of sniffing the DOCTYPE like they do when the xml declaration is not present to determine the layout mode. (see http://hsivonen.iki.fi/doctype/ and http://blogs.msdn.com/ie/archive/2005/09/15/467901.aspx). 'write_xhtml' emits a 'loose' XHTML doctype by default instead of a 'strict' XHTML doctype because 'tidy' emits a 'loose' doctye by default when you convert an HTML document into XHTML via '-asxhtml', and I couldn't think of a good reason to contradict that precedent. A note about emitting the proper Content-Type header when serving pages rendered with write_xhtml: you can sometimes use the content-type 'application/xhtml+xml' (see "http://www.w3.org/TR/xhtml-media-types/#application-xhtml-xml"). The official specification calls for this. But not all browsers support this content type (notably, no version of IE supports it, nor apparently does Safari). So these pages *may* be served using the 'text/html' content type and most browsers will attempt to do doctype sniffing to figure out if the document is actually XHTML. It appears that you can use the Accepts header in the request to figure out if the user agent accepts 'application/xhtml+xml' if you're a stickler for correctness. In practice, this seems like the right thing to do. See "http://keystonewebsites.com/articles/mime_type.php" for more information on serving up the correct content type header. "write_html(self, file, encoding=None, doctype=doctype.html,fragment=False)": Write HTML to 'file' (which can be a filename or filelike object) encoding -- encoding string (if None, 'utf-8' encoding is assumed). Unlike XML output, this is not used in a declaration, but it is used to do actual character encoding during output. Must be a recognizable Python encoding type. doctype -- 3-tuple indicating name, pubid, system of doctype. The default is the value of doctype.html (HTML 4.0 'loose') fragment -- True if a "fragment" should be omitted (no doctype). This overrides any provided "doctype" parameter if provided. Namespace'd elements and attributes have their namespaces removed during output when writing HTML, so pipelining cannot be performed. HTML is not valid XML, so an XML declaration header is never emitted. In general: For all output methods, comments are preserved in output. They are also present in the ElementTree node tree (as Comment elements), so beware. Processing instructions (e.g. '') are completely thrown away at parse time and do not exist anywhere in the element tree or in the output (use the declaration= parameter to emit a declaration processing instruction). Parsing API XML source text is turned into element trees using the "parse_xmlstring" function (demonstrated in examples above). A function that accepts a filename or a filelike object instead of a string, but which performs the same function is named "parse_xml", e.g.:: from meld3 import parse_xml from meld3 import parse_xmlstring HTML source text is turned into element trees using the "parse_htmlstring" function. A function that accepts a filename or a filelike object instead of a string, but which performs the same function is named "parse_html", e.g.:: from meld3 import parse_html from meld3 import parse_htmlstring Using duplicate meld identifiers on separate elements in the source document causes a ValueError to be raised at parse time. When using parse_xml and parse_xmlstring, documents which contain entity references (e.g. ' ') must have the entities defined in the source document or must have a DOCTYPE declaration that allows those entities to be resolved by the expat parser. When using parse_xml and parse_xmlstring, input documents must include the meld3 namespace declaration (conventionally on the root element). For example, '...' parse_html and parse_htmlstring take an optional "encoding" argument which specifies the document source encoding. To Do The API is not yet finalized. This implementation depends on classes internal to ElementTree and hasn't been tested with cElementTree or lxml, and almost certainly won't work with either due to this. See TODO.txt for more to-do items. Reporting Bugs and Requesting Features Please visit http://www.plope.com/software/collector to report bugs and request features. Environment Variables MELD3_PYIMPL If set to a non-null value, disables the C extension module which is used to speed things up somewhat. Have fun! - Chris McDonough (chrism@plope.com) meld3-0.6.10/setup.py0000644000076500000240000000256012055263404015246 0ustar mnaberezstaff00000000000000from distutils.core import setup, Extension import os import sys if sys.version_info[:2] < (2, 3) or sys.version_info[0] > 2: msg = ("meld3 requires Python 2.3 or later but does not work on any " "version of Python 3. You are using version %s. Please " "install using a supported version." % sys.version) sys.stderr.write(msg) sys.exit(1) if os.environ.get('USE_MELD3_EXTENSION_MODULES'): ext_modules=[Extension("meld3/cmeld3", ["meld3/cmeld3.c"])] else: # by default, allow people to install meld3 without building the # extension modules (meld works fine without them, it's just slower). ext_modules = [] CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: POSIX', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Text Processing :: Markup :: HTML' ] setup( name = 'meld3', version = '0.6.10', description = 'meld3 is an HTML/XML templating engine.', classifiers = CLASSIFIERS, author = 'Chris McDonough', author_email = 'chrism@plope.com', maintainer = "Mike Naberezny", maintainer_email = "mike@naberezny.com", license='ZPL 2.1', packages=['meld3'], url='https://github.com/supervisor/meld3', ext_modules=ext_modules, ) meld3-0.6.10/TODO.txt0000644000076500000240000000207611722530176015047 0ustar mnaberezstaff00000000000000- Document fillmeldhtmlform method. - Preserve xmlns="http://www.w3.org/1999/xhtml" On tags when it's provided in the parsed XML input during xhtml output (or figure out why it makes the XML writer go berserk and output every tag with that qualified namespace, or just output it by default in XHTML mode only if that makes sense). - Revisit . Maybe output an http-equiv content type tag by default matching the serlialization mode. - Investigate why using the "plope.com" namespace identifier is bad. - HTML serializer only calls _escape_cdata/_escape_attrib if necessary instead of calling it without regard to its need. This needs to be done for the XML serializer too.