Skip to content

Commit

Permalink
starting to make some code convetion thingy and cleanup to be more re…
Browse files Browse the repository at this point in the history
…adable
loechel committed Aug 10, 2017

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 5b860d1 commit a7e1d7d
Showing 16 changed files with 1,215 additions and 511 deletions.
4 changes: 4 additions & 0 deletions lib/diazo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
# -*- coding: utf-8 -*-

import logging


logging.basicConfig()
85 changes: 61 additions & 24 deletions lib/diazo/compiler.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""\
Usage: %prog [options] [-r] RULES [-t] THEME
@@ -9,28 +10,38 @@
theme="//div[@id='page-content']"/>
</rules>\
"""
import logging
import pkg_resources

from diazo.rules import process_rules
from diazo.utils import _createOptionParser
from diazo.utils import CustomResolver
from diazo.utils import pkg_xsl
from diazo.utils import quote_param
from diazo.utils import split_params
from lxml import etree
from six import string_types
from diazo.rules import process_rules
from diazo.utils import pkg_xsl, _createOptionParser, CustomResolver
from diazo.utils import quote_param, split_params

import logging
import pkg_resources


logger = logging.getLogger('diazo')
usage = __doc__


def set_parser(stylesheet, parser, compiler_parser=None):
dummy_doc = etree.parse(open(
pkg_resources.resource_filename('diazo', 'dummy.html')), parser=parser)
dummy_doc = etree.parse(
open(
pkg_resources.resource_filename('diazo', 'dummy.html'),
),
parser=parser,
)
name = 'file:///__diazo__'
resolver = CustomResolver({name: stylesheet})
if compiler_parser is None:
compiler_parser = etree.XMLParser()
compiler_parser.resolvers.add(resolver)
identity = pkg_xsl('identity.xsl', compiler_parser)
output_doc = identity(dummy_doc, docurl="'%s'" % name)
output_doc = identity(dummy_doc, docurl="'{name}'".format(name=name))
compiler_parser.resolvers.remove(resolver)
return output_doc

@@ -42,10 +53,13 @@ def build_xsl_params_document(xsl_params):
xsl_params['path'] = ''
known_params = etree.XML(
'<xsl:stylesheet version="1.0" '
'xmlns:xsl="http://www.w3.org/1999/XSL/Transform" />')
'xmlns:xsl="http://www.w3.org/1999/XSL/Transform" />',
)
for param_name, param_value in xsl_params.items():
param_element = etree.SubElement(
known_params, "{http://www.w3.org/1999/XSL/Transform}param")
known_params,
'{http://www.w3.org/1999/XSL/Transform}param',
)
param_element.attrib['name'] = param_name
if isinstance(param_value, string_types):
param_element.text = param_value
@@ -56,11 +70,25 @@ def build_xsl_params_document(xsl_params):
return known_params


def compile_theme(rules, theme=None, extra=None, css=True, xinclude=True,
absolute_prefix=None, update=True, trace=False,
includemode=None, parser=None, compiler_parser=None,
rules_parser=None, access_control=None, read_network=False,
indent=None, xsl_params=None, runtrace=False):
def compile_theme(
rules,
theme=None,
extra=None,
css=True,
xinclude=True,
absolute_prefix=None,
update=True,
trace=False,
includemode=None,
parser=None,
compiler_parser=None,
rules_parser=None,
access_control=None,
read_network=False,
indent=None,
xsl_params=None,
runtrace=False,
):
"""Invoke the diazo compiler.
* ``rules`` is the rules file
@@ -120,7 +148,8 @@ def compile_theme(rules, theme=None, extra=None, css=True, xinclude=True,
# Create a pseudo resolver for this
known_params_url = 'file:///__diazo_known_params__'
emit_stylesheet_resolver = CustomResolver({
known_params_url: etree.tostring(known_params)})
known_params_url: etree.tostring(known_params),
})
emit_stylesheet_parser = etree.XMLParser()
emit_stylesheet_parser.resolvers.add(emit_stylesheet_resolver)

@@ -133,10 +162,15 @@ def compile_theme(rules, theme=None, extra=None, css=True, xinclude=True,

# Run the final stage compiler
emit_stylesheet = pkg_xsl(
'emit-stylesheet.xsl', parser=emit_stylesheet_parser)
'emit-stylesheet.xsl',
parser=emit_stylesheet_parser,
)
compiled_doc = emit_stylesheet(rules_doc, **params)
compiled_doc = set_parser(etree.tostring(compiled_doc), parser,
compiler_parser)
compiled_doc = set_parser(
etree.tostring(compiled_doc),
parser,
compiler_parser,
)

return compiled_doc

@@ -153,9 +187,9 @@ def main():
elif len(args) == 1:
options.rules, = args
else:
parser.error("Wrong number of arguments.")
parser.error('Wrong number of arguments.')
elif args:
parser.error("Wrong number of arguments.")
parser.error('Wrong number of arguments.')

if options.trace:
logger.setLevel(logging.DEBUG)
@@ -172,13 +206,16 @@ def main():
absolute_prefix=options.absolute_prefix,
includemode=options.includemode,
read_network=options.read_network,
xsl_params=xsl_params
xsl_params=xsl_params,
)
root = output_xslt.getroot()
if not root.tail:
root.tail = '\n'
output_xslt.write(options.output, encoding='utf-8',
pretty_print=options.pretty_print)
output_xslt.write(
options.output,
encoding='utf-8',
pretty_print=options.pretty_print,
)


if __name__ == '__main__':
78 changes: 54 additions & 24 deletions lib/diazo/cssrules.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""\
Usage: %prog RULES
@@ -9,13 +10,16 @@
<copy css:content="#content-wrapper" css:theme="#page-content"/>
</rules>\
"""

from __future__ import absolute_import
from optparse import OptionParser
from lxml import etree
from cssselect import GenericTranslator
from . import utils
import sys
from diazo import utils
from lxml import etree
from optparse import OptionParser

import logging
import sys


logger = logging.getLogger('diazo')
usage = __doc__
@@ -34,28 +38,44 @@ def xpath_descendant_combinator(self, left, right):
def convert_css_selectors(rules):
"""Convert css rules to xpath rules element tree in place
"""
# XXX: There is a
# :root pseudo-class - http://www.w3.org/TR/css3-selectors/#root-pseudo
# XXX: There is a :root pseudo-class
# http://www.w3.org/TR/css3-selectors/#root-pseudo
# We may wish to add support to lxml.cssselect for it some day.
for element in rules.xpath("//@*[namespace-uri()='%s']/.." %
utils.namespaces['css']):
for element in rules.xpath(
"//@*[namespace-uri()='{nsp}']/..".format(nsp=utils.namespaces['css']),
):
tag_namespace = utils.namespace(element.tag)
css_prefix = element.attrib.get(utils.fullname(utils.namespaces['css'],
'prefix'), None)
css_prefix = element.attrib.get(
utils.fullname(
utils.namespaces['css'],
'prefix',
),
None,
)
for name, value in element.attrib.items():
if not name.startswith('{%s}' % utils.namespaces['css']):
if not name.startswith(
'{%s}' % utils.namespaces['css'],
):
continue
localname = utils.localname(name)
if localname == 'prefix':
continue
if not value:
element.attrib[localname] = ""
element.attrib[localname] = ''
continue
if (tag_namespace == utils.namespaces['diazo'] and
localname in ('content', 'content-children', 'if-content',
'if-not-content') or
(tag_namespace == utils.namespaces['xsl'] and
localname in ('match',))):
if (
tag_namespace == utils.namespaces['diazo'] and
localname in
(
'content',
'content-children',
'if-content',
'if-not-content',
) or (
tag_namespace == utils.namespaces['xsl'] and
localname in ('match',)
)
):
prefix = css_prefix or '//'
tr = _location_path_translator
else:
@@ -70,16 +90,26 @@ def main():
"""Called from console script
"""
parser = OptionParser(usage=usage)
parser.add_option("-o", "--output", metavar="output.html",
help="Output filename (instead of stdout)",
dest="output", default=sys.stdout)
parser.add_option("-p", "--pretty-print", action="store_true",
help="Pretty print output",
dest="pretty_print", default=False)
parser.add_option(
'-o',
'--output',
metavar='output.html',
help='Output filename (instead of stdout)',
dest='output',
default=sys.stdout,
)
parser.add_option(
'-p',
'--pretty-print',
action='store_true',
help='Pretty print output',
dest='pretty_print',
default=False,
)
(options, args) = parser.parse_args()

if len(args) != 1:
parser.error("Invalid number of arguments")
parser.error('Invalid number of arguments')
rules = etree.parse(args[0])
convert_css_selectors(rules)
rules.write(options.output, pretty_print=options.pretty_print)
5 changes: 4 additions & 1 deletion lib/diazo/defaults.xsl
Original file line number Diff line number Diff line change
@@ -10,7 +10,10 @@
xmlns:xhtml="http://www.w3.org/1999/xhtml"
exclude-result-prefixes="exsl str css dv dyn xhtml">

<xsl:variable name="normalized_path"><xsl:value-of select="$path"/><xsl:if test="substring($path, string-length($path)) != '/'">/</xsl:if></xsl:variable>
<xsl:variable name="normalized_path">
<xsl:value-of select="$path"/>
<xsl:if test="substring($path, string-length($path)) != '/'">/</xsl:if>
</xsl:variable>

<xsl:output method="xml" indent="no" omit-xml-declaration="yes"
media-type="text/html" encoding="UTF-8"
Loading

0 comments on commit a7e1d7d

Please sign in to comment.