Ejemplo n.º 1
0
 def __init__(self, namespace=None):
     """Create the factory, optionally bound to the given namespace.
     
     :param namespace: the namespace URI for any created elements, or `None`
                       for no namespace
     """
     if namespace and not isinstance(namespace, Namespace):
         namespace = Namespace(namespace)
     self.namespace = namespace
Ejemplo n.º 2
0
 def test_pickle(self):
     ns = Namespace('http://www.example.org/namespace')
     buf = BytesIO()
     pickle.dump(ns, buf, 2)
     buf.seek(0)
     unpickled = pickle.load(buf)
     self.assertEquals("Namespace('http://www.example.org/namespace')",
                       repr(unpickled))
     self.assertEquals('http://www.example.org/namespace', unpickled.uri)
Ejemplo n.º 3
0
def _rewrite_stream(stream, directives, ctxt, vars, bind):
    stream = list(stream)
    mutable_attrs = {}

    for control_attribute in directives:
        control_attribute.inject(mutable_attrs, ctxt, vars)

    kind, (tagname, attrs), pos = stream[0]
    if len(stream) == 2:
        contents = None
    else:
        contents = _simplify_stream(stream[1:-1], ctxt, vars)

    existing_attributes = {}
    for qname, value in attrs:
        if qname.namespace is None:
            if not isinstance(value, unicode):
                value = _simplify_stream(value, ctxt, vars)
                attrs |= ((qname, value), )
            existing_attributes[qname.localname] = qname
            mutable_attrs[qname.localname] = value

    try:
        render_context = ctxt['flatland_render_context']
    except KeyError:
        ctxt['flatland_render_context'] = render_context = Context()

    new_contents = transform(tagname.localname, mutable_attrs, contents,
                             render_context, bind)

    if new_contents is None:
        new_contents = ()
    elif isinstance(new_contents, unicode):
        new_contents = [(TEXT, new_contents, (None, -1, -1))]

    pairs = sorted(mutable_attrs.iteritems(), key=_attribute_sort_key)
    for attribute_name, value in pairs:
        if attribute_name in existing_attributes:
            qname = existing_attributes.pop(attribute_name)
        else:
            qname = QName(attribute_name)
        attrs |= ((qname, value), )
    for qname in existing_attributes.values():
        attrs -= qname

    stream[0] = (kind, (tagname, attrs), pos)
    if new_contents and tagname.localname == u'select' and bind is not None:
        if tagname.namespace:
            sub_tag = Namespace(tagname.namespace).option
        else:  # pragma: nocover
            sub_tag = QName('option')
        new_contents = _bind_unbound_tags(new_contents, sub_tag, bind)
    if new_contents:
        stream[1:-1] = new_contents
    return iter(stream)
Ejemplo n.º 4
0
class ChildRemover(TagListener):
    """Sample TagListener implementation that discards all children from
    matching nodes."""
    NAMESPACE = Namespace(u'http://code.discorporate.us/child-remover')

    def inspect(self, event, context):
        if event[0] is not START:
            return False

        kind, (tag, attributes), pos = event

        if tag in self.NAMESPACE:
            return (self.start, self.end)
        else:
            for attr, value in attributes:
                if attr in self.NAMESPACE:
                    return (default_start, self.end)

        return False

    def end(self, start, event, stream, context, history):
        """I remove all children."""
        # fixme: guessed missing symbol, cover w/ tests
        return start, self.end, None
Ejemplo n.º 5
0
    def _extract_includes(self, stream):
        streams = [[]]  # stacked lists of events of the "compiled" template
        prefixes = {}
        fallbacks = []
        includes = []
        xinclude_ns = Namespace(self.XINCLUDE_NAMESPACE)

        for kind, data, pos in stream:
            stream = streams[-1]

            if kind is START:
                # Record any directive attributes in start tags
                tag, attrs = data
                if tag in xinclude_ns:
                    if tag.localname == 'include':
                        include_href = attrs.get('href')
                        if not include_href:
                            raise TemplateSyntaxError(
                                'Include misses required '
                                'attribute "href"', self.filepath, *pos[1:])
                        includes.append((include_href, attrs.get('parse')))
                        streams.append([])
                    elif tag.localname == 'fallback':
                        streams.append([])
                        fallbacks.append(streams[-1])
                else:
                    stream.append((kind, (tag, attrs), pos))

            elif kind is END:
                if fallbacks and data == xinclude_ns['fallback']:
                    assert streams.pop() is fallbacks[-1]
                elif data == xinclude_ns['include']:
                    fallback = None
                    if len(fallbacks) == len(includes):
                        fallback = fallbacks.pop()
                    streams.pop()  # discard anything between the include tags
                    # and the fallback element
                    stream = streams[-1]
                    href, parse = includes.pop()
                    try:
                        cls = {
                            'xml': MarkupTemplate,
                            'text': NewTextTemplate
                        }.get(parse) or self.__class__
                    except KeyError:
                        raise TemplateSyntaxError(
                            'Invalid value for "parse" '
                            'attribute of include', self.filepath, *pos[1:])
                    stream.append((INCLUDE, (href, cls, fallback), pos))
                else:
                    stream.append((kind, data, pos))

            elif kind is START_NS and data[1] == xinclude_ns:
                # Strip out the XInclude namespace
                prefixes[data[0]] = data[1]

            elif kind is END_NS and data in prefixes:
                prefixes.pop(data)

            else:
                stream.append((kind, data, pos))

        assert len(streams) == 1
        return streams[0]
Ejemplo n.º 6
0
 def test_repr_eval_non_ascii(self):
     ns = Namespace('http://www.example.org/nämespäcé')
     self.assertEqual(eval(repr(ns)), ns)
Ejemplo n.º 7
0
 def test_repr_eval(self):
     ns = Namespace('http://www.example.org/namespace')
     self.assertEqual(eval(repr(ns)), ns)
Ejemplo n.º 8
0
 def test_repr(self):
     self.assertEqual("Namespace('http://www.example.org/namespace')",
                      repr(Namespace('http://www.example.org/namespace')))
Ejemplo n.º 9
0
import os
import re
from types import FunctionType

from genshi.core import Attrs, Namespace, QName, START, END, TEXT, \
                        XML_NAMESPACE, _ensure, StreamEventKind
from genshi.template.eval import _ast
from genshi.template.base import DirectiveFactory, EXPR, SUB, _apply_directives
from genshi.template.directives import Directive, StripDirective
from genshi.template.markup import MarkupTemplate, EXEC
from genshi.compat import IS_PYTHON2

__all__ = ['Translator', 'extract']
__docformat__ = 'restructuredtext en'

I18N_NAMESPACE = Namespace('http://genshi.edgewall.org/i18n')

MSGBUF = StreamEventKind('MSGBUF')
SUB_START = StreamEventKind('SUB_START')
SUB_END = StreamEventKind('SUB_END')

GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext', 'dgettext', 'dngettext',
                     'ugettext', 'ungettext')


class I18NDirective(Directive):
    """Simple interface for i18n directives to support messages extraction."""
    def __call__(self, stream, directives, ctxt, **vars):
        return _apply_directives(stream, directives, ctxt, vars)

Ejemplo n.º 10
0
from genshi.template.base import (
    DirectiveFactory,
    EXPR,
    SUB,
    TemplateSyntaxError,
    _eval_expr,
)
from genshi.template.eval import Expression
from genshi.template.directives import Directive
from genshi.template.interpolation import interpolate

from flatland.out.generic import transform, Context

__all__ = ('setup', )

NS = Namespace(u'http://ns.discorporate.us/flatland/genshi')

_static_attribute_order = [u'type', u'name', u'value']

_to_context = {}
for key in (u'auto-name', u'auto-value', u'auto-domid', u'auto-for',
            u'auto-tabindex', u'auto-filter', u'domid-format'):
    _to_context[key] = key.replace(u'-', u'_')

_bind_qname = NS.bind


def setup(template):
    """Register the flatland directives with a template.

    :param template: a `Template` instance