edouard@1940: #!/usr/bin/env python edouard@1940: # -*- coding: utf-8 -*- edouard@1940: # This file is part of Beremiz. edouard@1940: # See COPYING file for copyrights details. edouard@1940: edouard@1940: from __future__ import absolute_import edouard@1940: import os edouard@1940: from lxml import etree edouard@1940: import util.paths as paths edouard@1940: from plcopen.structures import StdBlckLibs edouard@1940: edouard@1940: ScriptDirectory = paths.AbsDir(__file__) edouard@1940: edouard@1944: edouard@1940: class XSLTModelQuery(object): edouard@1940: """ a class to handle XSLT queries on project and libs """ edouard@1940: def __init__(self, controller, xsltpath, ext = []): edouard@1940: # arbitrary set debug to false, updated later edouard@1940: self.debug = False edouard@1940: edouard@1940: # merge xslt extensions for library access to query specific ones edouard@1940: xsltext = [ edouard@1940: ("GetProject", lambda *_ignored: edouard@1940: controller.GetProject(self.debug)), edouard@1940: ("GetStdLibs", lambda *_ignored: edouard@1940: [lib for lib in StdBlckLibs.values()]), edouard@1940: ("GetExtensions", lambda *_ignored: edouard@1940: [ctn["types"] for ctn in controller.ConfNodeTypes]) edouard@1940: ] + ext edouard@1940: edouard@1940: # parse and compile. "beremiz" arbitrary namespace for extensions edouard@1940: self.xslt = etree.XSLT( edouard@1940: etree.parse( edouard@1940: os.path.join(ScriptDirectory, xsltpath), edouard@1940: etree.XMLParser()), edouard@1940: extensions={ ("beremiz", name):call for name, call in xsltext}) edouard@1940: edouard@1940: def _process_xslt(self, root, debug, **kwargs): edouard@1940: self.debug = debug edouard@1943: res = self.xslt(root,**{k:etree.XSLT.strparam(v) for k,v in kwargs.iteritems()}) edouard@1943: # print(self.xslt.error_log) edouard@1943: return res edouard@1944: edouard@1944: edouard@1944: # ------------------------------------------------------------------------------- edouard@1944: # Helpers functions for translating list of arguments edouard@1944: # from xslt to valid arguments edouard@1944: # ------------------------------------------------------------------------------- edouard@1944: edouard@1944: edouard@1944: def _StringValue(x): edouard@1944: return x edouard@1944: edouard@1944: edouard@1944: def _BoolValue(x): edouard@1944: return x in ["true", "0"] edouard@1944: edouard@1944: edouard@1944: def _translate_args(translations, args): edouard@1944: return [translate(arg[0]) if len(arg) > 0 else None edouard@1944: for translate, arg in edouard@1944: zip(translations, args)] edouard@1944: