diff options
author | Luca Falavigna <dktrkranz@debian.org> | 2014-04-26 15:11:58 +0200 |
---|---|---|
committer | Luca Falavigna <dktrkranz@debian.org> | 2014-04-26 15:11:58 +0200 |
commit | 140d836e9cd54fb67b969fd82ef7ed19ba574d40 (patch) | |
tree | 0df3e32ee39603d43f9b90fd2f2e1f7cce4249d4 /bin | |
parent | cb3425abe0bc2d05caf401ca24b82a25a81f009d (diff) |
Imported Upstream version 2.3.1upstream/2.3.1
Diffstat (limited to 'bin')
-rw-r--r-- | bin/SConsDoc.py | 892 | ||||
-rw-r--r-- | bin/SConsExamples.py (renamed from bin/scons-doc.py) | 922 | ||||
-rw-r--r-- | bin/docs-create-example-outputs.py | 19 | ||||
-rw-r--r-- | bin/docs-update-generated.py | 51 | ||||
-rw-r--r-- | bin/docs-validate.py | 27 | ||||
-rw-r--r-- | bin/import-test.py | 4 | ||||
-rw-r--r-- | bin/linecount.py | 4 | ||||
-rw-r--r-- | bin/restore.sh | 26 | ||||
-rw-r--r-- | bin/scons-proc.py | 478 | ||||
-rw-r--r-- | bin/scons_dev_master.py | 15 | ||||
-rw-r--r-- | bin/update-release-info.py | 21 |
11 files changed, 1407 insertions, 1052 deletions
diff --git a/bin/SConsDoc.py b/bin/SConsDoc.py index 4927dc0..d0575b0 100644 --- a/bin/SConsDoc.py +++ b/bin/SConsDoc.py @@ -1,5 +1,27 @@ #!/usr/bin/env python # +# Copyright (c) 2010 The SCons Foundation +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# # Module for handling SCons documentation processing. # @@ -16,13 +38,12 @@ Builder example: <builder name="BUILDER"> <summary> - This is the summary description of an SCons Builder. + <para>This is the summary description of an SCons Builder. It will get placed in the man page, and in the appropriate User's Guide appendix. The name of any builder may be interpolated anywhere in the document by specifying the - &b-BUILDER; - element. It need not be on a line by itself. + &b-BUILDER; element. It need not be on a line by itself.</para> Unlike normal XML, blank lines are significant in these descriptions and serve to separate paragraphs. @@ -42,18 +63,12 @@ Function example: (arg1, arg2, key=value) </arguments> <summary> - This is the summary description of an SCons function. + <para>This is the summary description of an SCons function. It will get placed in the man page, and in the appropriate User's Guide appendix. The name of any builder may be interpolated anywhere in the document by specifying the - &f-FUNCTION; - element. It need not be on a line by itself. - - Unlike normal XML, blank lines are significant in these - descriptions and serve to separate paragraphs. - They'll get replaced in DocBook output with appropriate tags - to indicate a new paragraph. + &f-FUNCTION; element. It need not be on a line by itself.</para> <example> print "this is example code, it will be offset and indented" @@ -65,18 +80,12 @@ Construction variable example: <cvar name="VARIABLE"> <summary> - This is the summary description of a construction variable. + <para>This is the summary description of a construction variable. It will get placed in the man page, and in the appropriate User's Guide appendix. The name of any construction variable may be interpolated anywhere in the document by specifying the - &t-VARIABLE; - element. It need not be on a line by itself. - - Unlike normal XML, blank lines are significant in these - descriptions and serve to separate paragraphs. - They'll get replaced in DocBook output with appropriate tags - to indicate a new paragraph. + &t-VARIABLE; element. It need not be on a line by itself.</para> <example> print "this is example code, it will be offset and indented" @@ -88,18 +97,12 @@ Tool example: <tool name="TOOL"> <summary> - This is the summary description of an SCons Tool. + <para>This is the summary description of an SCons Tool. It will get placed in the man page, and in the appropriate User's Guide appendix. The name of any tool may be interpolated anywhere in the document by specifying the - &t-TOOL; - element. It need not be on a line by itself. - - Unlike normal XML, blank lines are significant in these - descriptions and serve to separate paragraphs. - They'll get replaced in DocBook output with appropriate tags - to indicate a new paragraph. + &t-TOOL; element. It need not be on a line by itself.</para> <example> print "this is example code, it will be offset and indented" @@ -112,7 +115,543 @@ import imp import os.path import re import sys -import xml.sax.handler +import copy + +# Do we have libxml2/libxslt/lxml? +has_libxml2 = True +try: + import libxml2 + import libxslt +except: + has_libxml2 = False + try: + import lxml + except: + print("Failed to import either libxml2/libxslt or lxml") + sys.exit(1) + +has_etree = False +if not has_libxml2: + try: + from lxml import etree + has_etree = True + except ImportError: + pass +if not has_etree: + try: + # Python 2.5 + import xml.etree.cElementTree as etree + except ImportError: + try: + # Python 2.5 + import xml.etree.ElementTree as etree + except ImportError: + try: + # normal cElementTree install + import cElementTree as etree + except ImportError: + try: + # normal ElementTree install + import elementtree.ElementTree as etree + except ImportError: + print("Failed to import ElementTree from any known place") + sys.exit(1) + +re_entity = re.compile("\&([^;]+);") +re_entity_header = re.compile("<!DOCTYPE\s+sconsdoc\s+[^\]]+\]>") + +# Namespace for the SCons Docbook XSD +dbxsd="http://www.scons.org/dbxsd/v1.0" +# Namespace map identifier for the SCons Docbook XSD +dbxid="dbx" +# Namespace for schema instances +xsi = "http://www.w3.org/2001/XMLSchema-instance" + +# Header comment with copyright +copyright_comment = """ +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation + +This file is processed by the bin/SConsDoc.py module. +See its __doc__ string for a discussion of the format. +""" + +def isSConsXml(fpath): + """ Check whether the given file is a SCons XML file, i.e. it + contains the default target namespace definition. + """ + try: + f = open(fpath,'r') + content = f.read() + f.close() + if content.find('xmlns="%s"' % dbxsd) >= 0: + return True + except: + pass + + return False + +def remove_entities(content): + # Cut out entity inclusions + content = re_entity_header.sub("", content, re.M) + # Cut out entities themselves + content = re_entity.sub(lambda match: match.group(1), content) + + return content + +default_xsd = os.path.join('doc','xsd','scons.xsd') + +ARG = "dbscons" + +class Libxml2ValidityHandler: + + def __init__(self): + self.errors = [] + self.warnings = [] + + def error(self, msg, data): + if data != ARG: + raise Exception, "Error handler did not receive correct argument" + self.errors.append(msg) + + def warning(self, msg, data): + if data != ARG: + raise Exception, "Warning handler did not receive correct argument" + self.warnings.append(msg) + + +class DoctypeEntity: + def __init__(self, name_, uri_): + self.name = name_ + self.uri = uri_ + + def getEntityString(self): + txt = """ <!ENTITY %(perc)s %(name)s SYSTEM "%(uri)s"> + %(perc)s%(name)s; +""" % {'perc' : perc, 'name' : self.name, 'uri' : self.uri} + + return txt + +class DoctypeDeclaration: + def __init__(self, name_=None): + self.name = name_ + self.entries = [] + if self.name is None: + # Add default entries + self.name = "sconsdoc" + self.addEntity("scons", "../scons.mod") + self.addEntity("builders-mod", "builders.mod") + self.addEntity("functions-mod", "functions.mod") + self.addEntity("tools-mod", "tools.mod") + self.addEntity("variables-mod", "variables.mod") + + def addEntity(self, name, uri): + self.entries.append(DoctypeEntity(name, uri)) + + def createDoctype(self): + content = '<!DOCTYPE %s [\n' % self.name + for e in self.entries: + content += e.getEntityString() + content += ']>\n' + + return content + +if not has_libxml2: + class TreeFactory: + def __init__(self): + pass + + def newNode(self, tag): + return etree.Element(tag) + + def newEtreeNode(self, tag, init_ns=False): + if init_ns: + NSMAP = {None: dbxsd, + 'xsi' : xsi} + return etree.Element(tag, nsmap=NSMAP) + + return etree.Element(tag) + + def copyNode(self, node): + return copy.deepcopy(node) + + def appendNode(self, parent, child): + parent.append(child) + + def hasAttribute(self, node, att): + return att in node.attrib + + def getAttribute(self, node, att): + return node.attrib[att] + + def setAttribute(self, node, att, value): + node.attrib[att] = value + + def getText(self, root): + return root.text + + def setText(self, root, txt): + root.text = txt + + def writeGenTree(self, root, fp): + dt = DoctypeDeclaration() + fp.write(etree.tostring(root, xml_declaration=True, + encoding="UTF-8", pretty_print=True, + doctype=dt.createDoctype())) + + def writeTree(self, root, fpath): + fp = open(fpath, 'w') + fp.write(etree.tostring(root, xml_declaration=True, + encoding="UTF-8", pretty_print=True)) + fp.close() + + def prettyPrintFile(self, fpath): + fin = open(fpath,'r') + tree = etree.parse(fin) + pretty_content = etree.tostring(tree, pretty_print=True) + fin.close() + + fout = open(fpath,'w') + fout.write(pretty_content) + fout.close() + + def decorateWithHeader(self, root): + root.attrib["{"+xsi+"}schemaLocation"] = "%s/scons.xsd scons.xsd" % dbxsd + return root + + def newXmlTree(self, root): + """ Return a XML file tree with the correct namespaces set, + the element root as top entry and the given header comment. + """ + NSMAP = {None: dbxsd, + 'xsi' : xsi} + t = etree.Element(root, nsmap=NSMAP) + return self.decorateWithHeader(t) + + def validateXml(self, fpath, xmlschema_context): + # Use lxml + xmlschema = etree.XMLSchema(xmlschema_context) + try: + doc = etree.parse(fpath) + except Exception, e: + print "ERROR: %s fails to parse:"%fpath + print e + return False + doc.xinclude() + try: + xmlschema.assertValid(doc) + except Exception, e: + print "ERROR: %s fails to validate:" % fpath + print e + return False + return True + + def findAll(self, root, tag, ns=None, xp_ctxt=None, nsmap=None): + expression = ".//{%s}%s" % (nsmap[ns], tag) + if not ns or not nsmap: + expression = ".//%s" % tag + return root.findall(expression) + + def findAllChildrenOf(self, root, tag, ns=None, xp_ctxt=None, nsmap=None): + expression = "./{%s}%s/*" % (nsmap[ns], tag) + if not ns or not nsmap: + expression = "./%s/*" % tag + return root.findall(expression) + + def convertElementTree(self, root): + """ Convert the given tree of etree.Element + entries to a list of tree nodes for the + current XML toolkit. + """ + return [root] + +else: + class TreeFactory: + def __init__(self): + pass + + def newNode(self, tag): + return libxml2.newNode(tag) + + def newEtreeNode(self, tag, init_ns=False): + return etree.Element(tag) + + def copyNode(self, node): + return node.copyNode(1) + + def appendNode(self, parent, child): + if hasattr(parent, 'addChild'): + parent.addChild(child) + else: + parent.append(child) + + def hasAttribute(self, node, att): + if hasattr(node, 'hasProp'): + return node.hasProp(att) + return att in node.attrib + + def getAttribute(self, node, att): + if hasattr(node, 'prop'): + return node.prop(att) + return node.attrib[att] + + def setAttribute(self, node, att, value): + if hasattr(node, 'setProp'): + node.setProp(att, value) + else: + node.attrib[att] = value + + def getText(self, root): + if hasattr(root, 'getContent'): + return root.getContent() + return root.text + + def setText(self, root, txt): + if hasattr(root, 'setContent'): + root.setContent(txt) + else: + root.text = txt + + def writeGenTree(self, root, fp): + doc = libxml2.newDoc('1.0') + dtd = doc.newDtd("sconsdoc", None, None) + doc.addChild(dtd) + doc.setRootElement(root) + content = doc.serialize("UTF-8", 1) + dt = DoctypeDeclaration() + # This is clearly a hack, but unfortunately libxml2 + # doesn't support writing PERs (Parsed Entity References). + # So, we simply replace the empty doctype with the + # text we need... + content = content.replace("<!DOCTYPE sconsdoc>", dt.createDoctype()) + fp.write(content) + doc.freeDoc() + + def writeTree(self, root, fpath): + fp = open(fpath, 'w') + doc = libxml2.newDoc('1.0') + doc.setRootElement(root) + fp.write(doc.serialize("UTF-8", 1)) + doc.freeDoc() + fp.close() + + def prettyPrintFile(self, fpath): + # Read file and resolve entities + doc = libxml2.readFile(fpath, None, libxml2d.XML_PARSE_NOENT) + fp = open(fpath, 'w') + # Prettyprint + fp.write(doc.serialize("UTF-8", 1)) + fp.close() + # Cleanup + doc.freeDoc() + + def decorateWithHeader(self, root): + # Register the namespaces + ns = root.newNs(dbxsd, None) + xi = root.newNs(xsi, 'xsi') + root.setNs(ns) #put this node in the target namespace + + root.setNsProp(xi, 'schemaLocation', "%s/scons.xsd scons.xsd" % dbxsd) + + return root + + def newXmlTree(self, root): + """ Return a XML file tree with the correct namespaces set, + the element root as top entry and the given header comment. + """ + t = libxml2.newNode(root) + return self.decorateWithHeader(t) + + def validateXml(self, fpath, xmlschema_context): + # Create validation context + validation_context = xmlschema_context.schemaNewValidCtxt() + # Set error/warning handlers + eh = Libxml2ValidityHandler() + validation_context.setValidityErrorHandler(eh.error, eh.warning, ARG) + # Read file and resolve entities + doc = libxml2.readFile(fpath, None, libxml2.XML_PARSE_NOENT) + doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT) + err = validation_context.schemaValidateDoc(doc) + # Cleanup + doc.freeDoc() + del validation_context + + if err or eh.errors: + for e in eh.errors: + print e.rstrip("\n") + print "%s fails to validate" % fpath + return False + + return True + + def findAll(self, root, tag, ns=None, xpath_context=None, nsmap=None): + if hasattr(root, 'xpathEval') and xpath_context: + # Use the xpath context + xpath_context.setContextNode(root) + expression = ".//%s" % tag + if ns: + expression = ".//%s:%s" % (ns, tag) + return xpath_context.xpathEval(expression) + else: + expression = ".//{%s}%s" % (nsmap[ns], tag) + if not ns or not nsmap: + expression = ".//%s" % tag + return root.findall(expression) + + def findAllChildrenOf(self, root, tag, ns=None, xpath_context=None, nsmap=None): + if hasattr(root, 'xpathEval') and xpath_context: + # Use the xpath context + xpath_context.setContextNode(root) + expression = "./%s/node()" % tag + if ns: + expression = "./%s:%s/node()" % (ns, tag) + + return xpath_context.xpathEval(expression) + else: + expression = "./{%s}%s/node()" % (nsmap[ns], tag) + if not ns or not nsmap: + expression = "./%s/node()" % tag + return root.findall(expression) + + def expandChildElements(self, child): + """ Helper function for convertElementTree, + converts a single child recursively. + """ + nchild = self.newNode(child.tag) + # Copy attributes + for key, val in child.attrib: + self.setAttribute(nchild, key, val) + elements = [] + # Add text + if child.text: + t = libxml2.newText(child.text) + self.appendNode(nchild, t) + # Add children + for c in child: + for n in self.expandChildElements(c): + self.appendNode(nchild, n) + elements.append(nchild) + # Add tail + if child.tail: + tail = libxml2.newText(child.tail) + elements.append(tail) + + return elements + + def convertElementTree(self, root): + """ Convert the given tree of etree.Element + entries to a list of tree nodes for the + current XML toolkit. + """ + nroot = self.newNode(root.tag) + # Copy attributes + for key, val in root.attrib: + self.setAttribute(nroot, key, val) + elements = [] + # Add text + if root.text: + t = libxml2.newText(root.text) + self.appendNode(nroot, t) + # Add children + for c in root: + for n in self.expandChildElements(c): + self.appendNode(nroot, n) + elements.append(nroot) + # Add tail + if root.tail: + tail = libxml2.newText(root.tail) + elements.append(tail) + + return elements + +tf = TreeFactory() + + +class SConsDocTree: + def __init__(self): + self.nsmap = {'dbx' : dbxsd} + self.doc = None + self.root = None + self.xpath_context = None + + def parseContent(self, content, include_entities=True): + """ Parses the given content as XML file. This method + is used when we generate the basic lists of entities + for the builders, tools and functions. + So we usually don't bother about namespaces and resolving + entities here...this is handled in parseXmlFile below + (step 2 of the overall process). + """ + if not include_entities: + content = remove_entities(content) + # Create domtree from given content string + self.root = etree.fromstring(content) + + def parseXmlFile(self, fpath): + nsmap = {'dbx' : dbxsd} + if not has_libxml2: + # Create domtree from file + domtree = etree.parse(fpath) + self.root = domtree.getroot() + else: + # Read file and resolve entities + self.doc = libxml2.readFile(fpath, None, libxml2.XML_PARSE_NOENT) + self.root = self.doc.getRootElement() + # Create xpath context + self.xpath_context = self.doc.xpathNewContext() + # Register namespaces + for key, val in self.nsmap.iteritems(): + self.xpath_context.xpathRegisterNs(key, val) + + def __del__(self): + if self.doc is not None: + self.doc.freeDoc() + if self.xpath_context is not None: + self.xpath_context.xpathFreeContext() + +perc="%" + +def validate_all_xml(dpaths, xsdfile=default_xsd): + xmlschema_context = None + if not has_libxml2: + # Use lxml + xmlschema_context = etree.parse(xsdfile) + else: + # Use libxml2 and prepare the schema validation context + ctxt = libxml2.schemaNewParserCtxt(xsdfile) + xmlschema_context = ctxt.schemaParse() + del ctxt + + fpaths = [] + for dp in dpaths: + if dp.endswith('.xml') and isSConsXml(dp): + path='.' + fpaths.append(dp) + else: + for path, dirs, files in os.walk(dp): + for f in files: + if f.endswith('.xml'): + fp = os.path.join(path, f) + if isSConsXml(fp): + fpaths.append(fp) + + fails = [] + for idx, fp in enumerate(fpaths): + fpath = os.path.join(path, fp) + print "%.2f%s (%d/%d) %s" % (float(idx+1)*100.0/float(len(fpaths)), + perc, idx+1, len(fpaths),fp) + + if not tf.validateXml(fp, xmlschema_context): + fails.append(fp) + continue + + if has_libxml2: + # Cleanup + del xmlschema_context + + if fails: + return False + + return True class Item(object): def __init__(self, name): @@ -120,9 +659,10 @@ class Item(object): self.sort_name = name.lower() if self.sort_name[0] == '_': self.sort_name = self.sort_name[1:] - self.summary = [] - self.sets = None - self.uses = None + self.sets = [] + self.uses = [] + self.summary = None + self.arguments = None def cmp_name(self, name): if name[0] == '_': name = name[1:] @@ -136,7 +676,6 @@ class Builder(Item): class Function(Item): def __init__(self, name): super(Function, self).__init__(name) - self.arguments = [] class Tool(Item): def __init__(self, name): @@ -146,18 +685,6 @@ class Tool(Item): class ConstructionVariable(Item): pass -class Chunk(object): - def __init__(self, tag, body=None): - self.tag = tag - if not body: - body = [] - self.body = body - def __str__(self): - body = ''.join(self.body) - return "<%s>%s</%s>\n" % (self.tag, body, self.tag) - def append(self, data): - self.body.append(data) - class Arguments(object): def __init__(self, signature, body=None): if not body: @@ -175,206 +702,99 @@ class Arguments(object): def append(self, data): self.body.append(data) -class Summary(object): +class SConsDocHandler(object): def __init__(self): - self.body = [] - self.collect = [] - def append(self, data): - self.collect.append(data) - def end_para(self): - text = ''.join(self.collect) - paras = text.split('\n\n') - if paras == ['\n']: - return - if paras[0] == '': - self.body.append('\n') - paras = paras[1:] - paras[0] = '\n' + paras[0] - if paras[-1] == '': - paras = paras[:-1] - paras[-1] = paras[-1] + '\n' - last = '\n' - else: - last = None - sep = None - for p in paras: - c = Chunk("para", p) - if sep: - self.body.append(sep) - self.body.append(c) - sep = '\n' - if last: - self.body.append(last) - def begin_chunk(self, chunk): - self.end_para() - self.collect = chunk - def end_chunk(self): - self.body.append(self.collect) - self.collect = [] - -class SConsDocHandler(xml.sax.handler.ContentHandler, - xml.sax.handler.ErrorHandler): - def __init__(self): - self._start_dispatch = {} - self._end_dispatch = {} - keys = list(self.__class__.__dict__.keys()) - start_tag_method_names = [k for k in keys if k[:6] == 'start_'] - end_tag_method_names = [k for k in keys if k[:4] == 'end_'] - for method_name in start_tag_method_names: - tag = method_name[6:] - self._start_dispatch[tag] = getattr(self, method_name) - for method_name in end_tag_method_names: - tag = method_name[4:] - self._end_dispatch[tag] = getattr(self, method_name) - self.stack = [] - self.collect = [] - self.current_object = [] self.builders = {} self.functions = {} self.tools = {} self.cvars = {} - def startElement(self, name, attrs): + def parseItems(self, domelem, xpath_context, nsmap): + items = [] + + for i in tf.findAll(domelem, "item", dbxid, xpath_context, nsmap): + txt = tf.getText(i) + if txt is not None: + txt = txt.strip() + if len(txt): + items.append(txt.strip()) + + return items + + def parseUsesSets(self, domelem, xpath_context, nsmap): + uses = [] + sets = [] + + for u in tf.findAll(domelem, "uses", dbxid, xpath_context, nsmap): + uses.extend(self.parseItems(u, xpath_context, nsmap)) + for s in tf.findAll(domelem, "sets", dbxid, xpath_context, nsmap): + sets.extend(self.parseItems(s, xpath_context, nsmap)) + + return sorted(uses), sorted(sets) + + def parseInstance(self, domelem, map, Class, + xpath_context, nsmap, include_entities=True): + name = 'unknown' + if tf.hasAttribute(domelem, 'name'): + name = tf.getAttribute(domelem, 'name') try: - start_element_method = self._start_dispatch[name] + instance = map[name] except KeyError: - self.characters('<%s>' % name) - else: - start_element_method(attrs) - - def endElement(self, name): - try: - end_element_method = self._end_dispatch[name] - except KeyError: - self.characters('</%s>' % name) - else: - end_element_method() - - # - # - def characters(self, chars): - self.collect.append(chars) - - def begin_collecting(self, chunk): - self.collect = chunk - def end_collecting(self): - self.collect = [] - - def begin_chunk(self): - pass - def end_chunk(self): - pass - - # - # - # - - def begin_xxx(self, obj): - self.stack.append(self.current_object) - self.current_object = obj - def end_xxx(self): - self.current_object = self.stack.pop() - - # - # - # - def start_scons_doc(self, attrs): - pass - def end_scons_doc(self): - pass - - def start_builder(self, attrs): - name = attrs.get('name') - try: - builder = self.builders[name] - except KeyError: - builder = Builder(name) - self.builders[name] = builder - self.begin_xxx(builder) - def end_builder(self): - self.end_xxx() - - def start_scons_function(self, attrs): - name = attrs.get('name') - try: - function = self.functions[name] - except KeyError: - function = Function(name) - self.functions[name] = function - self.begin_xxx(function) - def end_scons_function(self): - self.end_xxx() - - def start_tool(self, attrs): - name = attrs.get('name') - try: - tool = self.tools[name] - except KeyError: - tool = Tool(name) - self.tools[name] = tool - self.begin_xxx(tool) - def end_tool(self): - self.end_xxx() - - def start_cvar(self, attrs): - name = attrs.get('name') - try: - cvar = self.cvars[name] - except KeyError: - cvar = ConstructionVariable(name) - self.cvars[name] = cvar - self.begin_xxx(cvar) - def end_cvar(self): - self.end_xxx() - - def start_arguments(self, attrs): - arguments = Arguments(attrs.get('signature', "both")) - self.current_object.arguments.append(arguments) - self.begin_xxx(arguments) - self.begin_collecting(arguments) - def end_arguments(self): - self.end_xxx() - - def start_summary(self, attrs): - summary = Summary() - self.current_object.summary = summary - self.begin_xxx(summary) - self.begin_collecting(summary) - def end_summary(self): - self.current_object.end_para() - self.end_xxx() - - def start_example(self, attrs): - example = Chunk("programlisting") - self.current_object.begin_chunk(example) - def end_example(self): - self.current_object.end_chunk() - - def start_uses(self, attrs): - self.begin_collecting([]) - def end_uses(self): - self.current_object.uses = sorted(''.join(self.collect).split()) - self.end_collecting() - - def start_sets(self, attrs): - self.begin_collecting([]) - def end_sets(self): - self.current_object.sets = sorted(''.join(self.collect).split()) - self.end_collecting() - - # Stuff for the ErrorHandler portion. - def error(self, exception): - linenum = exception._linenum - self.preamble_lines - sys.stderr.write('%s:%d:%d: %s (error)\n' % (self.filename, linenum, exception._colnum, ''.join(exception.args))) - - def fatalError(self, exception): - linenum = exception._linenum - self.preamble_lines - sys.stderr.write('%s:%d:%d: %s (fatalError)\n' % (self.filename, linenum, exception._colnum, ''.join(exception.args))) - - def set_file_info(self, filename, preamble_lines): - self.filename = filename - self.preamble_lines = preamble_lines - + instance = Class(name) + map[name] = instance + uses, sets = self.parseUsesSets(domelem, xpath_context, nsmap) + instance.uses.extend(uses) + instance.sets.extend(sets) + if include_entities: + # Parse summary and function arguments + for s in tf.findAllChildrenOf(domelem, "summary", dbxid, xpath_context, nsmap): + if instance.summary is None: + instance.summary = [] + instance.summary.append(tf.copyNode(s)) + for a in tf.findAll(domelem, "arguments", dbxid, xpath_context, nsmap): + if instance.arguments is None: + instance.arguments = [] + instance.arguments.append(tf.copyNode(a)) + + def parseDomtree(self, root, xpath_context=None, nsmap=None, include_entities=True): + # Process Builders + for b in tf.findAll(root, "builder", dbxid, xpath_context, nsmap): + self.parseInstance(b, self.builders, Builder, + xpath_context, nsmap, include_entities) + # Process Functions + for f in tf.findAll(root, "scons_function", dbxid, xpath_context, nsmap): + self.parseInstance(f, self.functions, Function, + xpath_context, nsmap, include_entities) + # Process Tools + for t in tf.findAll(root, "tool", dbxid, xpath_context, nsmap): + self.parseInstance(t, self.tools, Tool, + xpath_context, nsmap, include_entities) + # Process CVars + for c in tf.findAll(root, "cvar", dbxid, xpath_context, nsmap): + self.parseInstance(c, self.cvars, ConstructionVariable, + xpath_context, nsmap, include_entities) + + def parseContent(self, content, include_entities=True): + """ Parses the given content as XML file. This method + is used when we generate the basic lists of entities + for the builders, tools and functions. + So we usually don't bother about namespaces and resolving + entities here...this is handled in parseXmlFile below + (step 2 of the overall process). + """ + # Create doctree + t = SConsDocTree() + t.parseContent(content, include_entities) + # Parse it + self.parseDomtree(t.root, t.xpath_context, t.nsmap, include_entities) + + def parseXmlFile(self, fpath): + # Create doctree + t = SConsDocTree() + t.parseXmlFile(fpath) + # Parse it + self.parseDomtree(t.root, t.xpath_context, t.nsmap) + # lifted from Ka-Ping Yee's way cool pydoc module. def importfile(path): """Import a Python source file or compiled file given its path.""" diff --git a/bin/scons-doc.py b/bin/SConsExamples.py index cf5d5b2..9823a05 100644 --- a/bin/scons-doc.py +++ b/bin/SConsExamples.py @@ -1,7 +1,7 @@ -#!/usr/bin/env python -# +# !/usr/bin/env python +# # Copyright (c) 2010 The SCons Foundation -# +# # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including @@ -9,10 +9,10 @@ # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: -# +# # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. -# +# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -21,38 +21,18 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -# -# scons-doc.py - an SGML preprocessor for capturing SCons output -# and inserting it into examples in our DocBook -# documentation -# -# Synopsis: -# -# scons-doc [OPTIONS] [.in files] -# -# When no input files are given, the folder doc/user/* is searched for .in files. -# -# Available options: -# -# -d, --diff create examples for the .in file and output a unified -# diff against the related .xml file -# -r, --run create examples for the .in file, but do not change -# any files -# -s, --simple_diff use a simpler output for the diff mode (no unified -# diff!) -# -u, --update create examples for the .in file and update the -# related .xml file -# -# This script looks for some SGML tags that describe SCons example +# +# +# This script looks for some XML tags that describe SCons example # configurations and commands to execute in those configurations, and # uses TestCmd.py to execute the commands and insert the output from -# those commands into the SGML that we output. This way, we can run a +# those commands into the XML that we output. This way, we can run a # script and update all of our example documentation output without # a lot of laborious by-hand checking. -# +# # An "SCons example" looks like this, and essentially describes a set of # input files (program source files as well as SConscript files): -# +# # <scons_example name="ex1"> # <file name="SConstruct" printme="1"> # env = Environment() @@ -62,7 +42,7 @@ # int main() { printf("foo.c\n"); } # </file> # </scons_example> -# +# # The <file> contents within the <scons_example> tag will get written # into a temporary directory whenever example output needs to be # generated. By default, the <file> contents are not inserted into text @@ -70,49 +50,364 @@ # in which case they will get inserted within a <programlisting> tag. # This makes it easy to define the example at the appropriate # point in the text where you intend to show the SConstruct file. -# +# # Note that you should usually give the <scons_example> a "name" # attribute so that you can refer to the example configuration later to # run SCons and generate output. -# +# # If you just want to show a file's contents without worry about running # SCons, there's a shorter <sconstruct> tag: -# +# # <sconstruct> # env = Environment() # env.Program('foo') # </sconstruct> -# +# # This is essentially equivalent to <scons_example><file printme="1">, # but it's more straightforward. -# +# # SCons output is generated from the following sort of tag: -# +# # <scons_output example="ex1" os="posix"> -# <scons_output_command>scons -Q foo</scons_output_command> -# <scons_output_command>scons -Q foo</scons_output_command> +# <scons_output_command suffix="1">scons -Q foo</scons_output_command> +# <scons_output_command suffix="2">scons -Q foo</scons_output_command> # </scons_output> -# +# # You tell it which example to use with the "example" attribute, and then # give it a list of <scons_output_command> tags to execute. You can also # supply an "os" tag, which specifies the type of operating system this # example is intended to show; if you omit this, default value is "posix". -# -# The generated SGML will show the command line (with the appropriate +# +# The generated XML will show the command line (with the appropriate # command-line prompt for the operating system), execute the command in # a temporary directory with the example files, capture the standard # output from SCons, and insert it into the text as appropriate. # Error output gets passed through to your error output so you # can see if there are any problems executing the command. -# +# -import optparse import os import re -import sgmllib import sys import time -import glob + +import SConsDoc +from SConsDoc import tf as stf + +# +# The available types for ExampleFile entries +# +FT_FILE = 0 # a physical file (=<file>) +FT_FILEREF = 1 # a reference (=<scons_example_file>) + +class ExampleFile: + def __init__(self, type_=FT_FILE): + self.type = type_ + self.name = '' + self.content = '' + self.chmod = '' + + def isFileRef(self): + return self.type == FT_FILEREF + +class ExampleFolder: + def __init__(self): + self.name = '' + self.chmod = '' + +class ExampleCommand: + def __init__(self): + self.edit = None + self.environment = '' + self.output = '' + self.cmd = '' + +class ExampleOutput: + def __init__(self): + self.name = '' + self.tools = '' + self.os = 'posix' + self.preserve = None + self.suffix = '' + self.commands = [] + +class ExampleInfo: + def __init__(self): + self.name = '' + self.files = [] + self.folders = [] + self.outputs = [] + + def getFileContents(self, fname): + for f in self.files: + if fname == f.name and not f.isFileRef(): + return f.content + + return '' + +def readExampleInfos(fpath, examples): + """ Add the example infos for the file fpath to the + global dictionary examples. + """ + + # Create doctree + t = SConsDoc.SConsDocTree() + t.parseXmlFile(fpath) + + # Parse scons_examples + for e in stf.findAll(t.root, "scons_example", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + n = '' + if stf.hasAttribute(e, 'name'): + n = stf.getAttribute(e, 'name') + if n and n not in examples: + i = ExampleInfo() + i.name = n + examples[n] = i + + # Parse file and directory entries + for f in stf.findAll(e, "file", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + fi = ExampleFile() + if stf.hasAttribute(f, 'name'): + fi.name = stf.getAttribute(f, 'name') + if stf.hasAttribute(f, 'chmod'): + fi.chmod = stf.getAttribute(f, 'chmod') + fi.content = stf.getText(f) + examples[n].files.append(fi) + for d in stf.findAll(e, "directory", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + di = ExampleFolder() + if stf.hasAttribute(d, 'name'): + di.name = stf.getAttribute(d, 'name') + if stf.hasAttribute(d, 'chmod'): + di.chmod = stf.getAttribute(d, 'chmod') + examples[n].folders.append(di) + + + # Parse scons_example_files + for f in stf.findAll(t.root, "scons_example_file", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + if stf.hasAttribute(f, 'example'): + e = stf.getAttribute(f, 'example') + else: + continue + fi = ExampleFile(FT_FILEREF) + if stf.hasAttribute(f, 'name'): + fi.name = stf.getAttribute(f, 'name') + if stf.hasAttribute(f, 'chmod'): + fi.chmod = stf.getAttribute(f, 'chmod') + fi.content = stf.getText(f) + examples[e].files.append(fi) + + + # Parse scons_output + for o in stf.findAll(t.root, "scons_output", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + if stf.hasAttribute(o, 'example'): + n = stf.getAttribute(o, 'example') + else: + continue + + eout = ExampleOutput() + if stf.hasAttribute(o, 'name'): + eout.name = stf.getAttribute(o, 'name') + if stf.hasAttribute(o, 'tools'): + eout.tools = stf.getAttribute(o, 'tools') + if stf.hasAttribute(o, 'os'): + eout.os = stf.getAttribute(o, 'os') + if stf.hasAttribute(o, 'suffix'): + eout.suffix = stf.getAttribute(o, 'suffix') + + for c in stf.findAll(o, "scons_output_command", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + oc = ExampleCommand() + if stf.hasAttribute(c, 'edit'): + oc.edit = stf.getAttribute(c, 'edit') + if stf.hasAttribute(c, 'environment'): + oc.environment = stf.getAttribute(c, 'environment') + if stf.hasAttribute(c, 'output'): + oc.output = stf.getAttribute(c, 'output') + if stf.hasAttribute(c, 'cmd'): + oc.cmd = stf.getAttribute(c, 'cmd') + else: + oc.cmd = stf.getText(c) + + eout.commands.append(oc) + + examples[n].outputs.append(eout) + +def readAllExampleInfos(dpath): + """ Scan for XML files in the given directory and + collect together all relevant infos (files/folders, + output commands) in a map, which gets returned. + """ + examples = {} + for path, dirs, files in os.walk(dpath): + for f in files: + if f.endswith('.xml'): + fpath = os.path.join(path, f) + if SConsDoc.isSConsXml(fpath): + readExampleInfos(fpath, examples) + + return examples + +generated_examples = os.path.join('doc', 'generated', 'examples') + +def ensureExampleOutputsExist(dpath): + """ Scan for XML files in the given directory and + ensure that for every example output we have a + corresponding output file in the 'generated/examples' + folder. + """ + # Ensure that the output folder exists + if not os.path.isdir(generated_examples): + os.mkdir(generated_examples) + + examples = readAllExampleInfos(dpath) + for key, value in examples.iteritems(): + # Process all scons_output tags + for o in value.outputs: + cpath = os.path.join(generated_examples, + key + '_' + o.suffix + '.xml') + if not os.path.isfile(cpath): + # Start new XML file + s = stf.newXmlTree("screen") + stf.setText(s, "NO OUTPUT YET! Run the script to generate/update all examples.") + # Write file + stf.writeTree(s, cpath) + + # Process all scons_example_file tags + for r in value.files: + if r.isFileRef(): + # Get file's content + content = value.getFileContents(r.name) + fpath = os.path.join(generated_examples, + key + '_' + r.name.replace("/", "_")) + # Write file + f = open(fpath, 'w') + f.write("%s\n" % content) + f.close() + +perc = "%" + +def createAllExampleOutputs(dpath): + """ Scan for XML files in the given directory and + creates all output files for every example in + the 'generated/examples' folder. + """ + # Ensure that the output folder exists + if not os.path.isdir(generated_examples): + os.mkdir(generated_examples) + + examples = readAllExampleInfos(dpath) + total = len(examples) + idx = 0 + for key, value in examples.iteritems(): + # Process all scons_output tags + print "%.2f%s (%d/%d) %s" % (float(idx + 1) * 100.0 / float(total), + perc, idx + 1, total, key) + + create_scons_output(value) + # Process all scons_example_file tags + for r in value.files: + if r.isFileRef(): + # Get file's content + content = value.getFileContents(r.name) + fpath = os.path.join(generated_examples, + key + '_' + r.name.replace("/", "_")) + # Write file + f = open(fpath, 'w') + f.write("%s\n" % content) + f.close() + idx += 1 + +def collectSConsExampleNames(fpath): + """ Return a set() of example names, used in the given file fpath. + """ + names = set() + suffixes = {} + failed_suffixes = False + + # Create doctree + t = SConsDoc.SConsDocTree() + t.parseXmlFile(fpath) + + # Parse it + for e in stf.findAll(t.root, "scons_example", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + n = '' + if stf.hasAttribute(e, 'name'): + n = stf.getAttribute(e, 'name') + if n: + names.add(n) + if n not in suffixes: + suffixes[n] = [] + else: + print "Error: Example in file '%s' is missing a name!" % fpath + failed_suffixes = True + + for o in stf.findAll(t.root, "scons_output", SConsDoc.dbxid, + t.xpath_context, t.nsmap): + n = '' + if stf.hasAttribute(o, 'example'): + n = stf.getAttribute(o, 'example') + else: + print "Error: scons_output in file '%s' is missing an example name!" % fpath + failed_suffixes = True + + if n not in suffixes: + print "Error: scons_output in file '%s' is referencing non-existent example '%s'!" % (fpath, n) + failed_suffixes = True + continue + + s = '' + if stf.hasAttribute(o, 'suffix'): + s = stf.getAttribute(o, 'suffix') + else: + print "Error: scons_output in file '%s' (example '%s') is missing a suffix!" % (fpath, n) + failed_suffixes = True + + if s not in suffixes[n]: + suffixes[n].append(s) + else: + print "Error: scons_output in file '%s' (example '%s') is using a duplicate suffix '%s'!" % (fpath, n, s) + failed_suffixes = True + + return names, failed_suffixes + +def exampleNamesAreUnique(dpath): + """ Scan for XML files in the given directory and + check whether the scons_example names are unique. + """ + unique = True + allnames = set() + for path, dirs, files in os.walk(dpath): + for f in files: + if f.endswith('.xml'): + fpath = os.path.join(path, f) + if SConsDoc.isSConsXml(fpath): + names, failed_suffixes = collectSConsExampleNames(fpath) + if failed_suffixes: + unique = False + i = allnames.intersection(names) + if i: + print "Not unique in %s are: %s" % (fpath, ', '.join(i)) + unique = False + + allnames |= names + + return unique + +# ############################################################### +# +# In the second half of this module (starting here) +# we define the variables and functions that are required +# to actually run the examples, collect their output and +# write it into the files in doc/generated/examples... +# which then get included by our UserGuide. +# +# ############################################################### sys.path.append(os.path.join(os.getcwd(), 'QMTest')) sys.path.append(os.path.join(os.getcwd(), 'build', 'QMTest')) @@ -129,64 +424,13 @@ os.environ['SCONS_LIB_DIR'] = scons_lib_dir import TestCmd -# The regular expression that identifies entity references in the -# standard sgmllib omits the underscore from the legal characters. -# Override it with our own regular expression that adds underscore. -sgmllib.entityref = re.compile('&([a-zA-Z][-_.a-zA-Z0-9]*)[^-_a-zA-Z0-9]') - -# Classes for collecting different types of data we're interested in. -class DataCollector(object): - """Generic class for collecting data between a start tag and end - tag. We subclass for various types of tags we care about.""" - def __init__(self): - self.data = "" - def afunc(self, data): - self.data = self.data + data - -class Example(DataCollector): - """An SCons example. This is essentially a list of files that - will get written to a temporary directory to collect output - from one or more SCons runs.""" - def __init__(self): - DataCollector.__init__(self) - self.files = [] - self.dirs = [] - -class File(DataCollector): - """A file, that will get written out to a temporary directory - for one or more SCons runs.""" - def __init__(self, name): - DataCollector.__init__(self) - self.name = name - -class Directory(DataCollector): - """A directory, that will get created in a temporary directory - for one or more SCons runs.""" - def __init__(self, name): - DataCollector.__init__(self) - self.name = name - -class Output(DataCollector): - """Where the command output goes. This is essentially - a list of commands that will get executed.""" - def __init__(self): - DataCollector.__init__(self) - self.commandlist = [] - -class Command(DataCollector): - """A tag for where the command output goes. This is essentially - a list of commands that will get executed.""" - def __init__(self): - DataCollector.__init__(self) - self.output = None - Prompt = { 'posix' : '% ', 'win32' : 'C:\\>' } # The magick SCons hackery that makes this work. -# +# # So that our examples can still use the default SConstruct file, we # actually feed the following into SCons via stdin and then have it # SConscript() the SConstruct file. This stdin wrapper creates a set @@ -194,7 +438,7 @@ Prompt = { # Surrogates print output like the real tools and behave like them # without actually having to be on the right platform or have the right # tool installed. -# +# # The upshot: The wrapper transparently changes the world out from # under the top-level SConstruct file in an example just so we can get # the command output. @@ -432,16 +676,16 @@ def command_scons(args, c, test, dict): except KeyError: delete_keys.append(key) os.environ[key] = val - test.run(interpreter = sys.executable, - program = scons_py, + test.run(interpreter=sys.executable, + program=scons_py, # We use ToolSurrogates to capture win32 output by "building" # examples using a fake win32 tool chain. Suppress the # warnings that come from the new revamped VS support so # we can build doc on (Linux) systems that don't have # Visual C installed. - arguments = '--warn=no-visual-c-missing -f - ' + ' '.join(args), - chdir = test.workpath('WORK'), - stdin = Stdin % dict) + arguments='--warn=no-visual-c-missing -f - ' + ' '.join(args), + chdir=test.workpath('WORK'), + stdin=Stdin % dict) os.environ.update(save_vals) for key in delete_keys: del(os.environ[key]) @@ -453,8 +697,8 @@ def command_scons(args, c, test, dict): if lines: while lines[-1] == '': lines = lines[:-1] - #err = test.stderr() - #if err: + # err = test.stderr() + # if err: # sys.stderr.write(err) return lines @@ -475,10 +719,10 @@ def command_touch(args, c, test, dict): return [] def command_edit(args, c, test, dict): - try: - add_string = c.edit[:] - except AttributeError: + if c.edit is None: add_string = 'void edit(void) { ; }\n' + else: + add_string = c.edit[:] if add_string[-1] != '\n': add_string = add_string + '\n' for file in args: @@ -517,218 +761,44 @@ def ExecuteCommand(args, c, t, dict): func = lambda args, c, t, dict: [] return func(args[1:], c, t, dict) -class MySGML(sgmllib.SGMLParser): - """A subclass of the standard Python sgmllib SGML parser. - - This extends the standard sgmllib parser to recognize, and do cool - stuff with, the added tags that describe our SCons examples, - commands, and other stuff. - """ - def __init__(self, outfp): - sgmllib.SGMLParser.__init__(self) - self.examples = {} - self.afunclist = [] - self.outfp = outfp - - # The first set of methods here essentially implement pass-through - # handling of most of the stuff in an SGML file. We're really - # only concerned with the tags specific to SCons example processing, - # the methods for which get defined below. - - def handle_data(self, data): - try: - f = self.afunclist[-1] - except IndexError: - self.outfp.write(data) - else: - f(data) - - def handle_comment(self, data): - self.outfp.write('<!--' + data + '-->') - - def handle_decl(self, data): - self.outfp.write('<!' + data + '>') - - def unknown_starttag(self, tag, attrs): - try: - f = self.example.afunc - except AttributeError: - f = self.outfp.write - if not attrs: - f('<' + tag + '>') - else: - f('<' + tag) - for name, value in attrs: - f(' ' + name + '=' + '"' + value + '"') - f('>') - - def unknown_endtag(self, tag): - self.outfp.write('</' + tag + '>') - - def unknown_entityref(self, ref): - self.outfp.write('&' + ref + ';') - def unknown_charref(self, ref): - self.outfp.write('&#' + ref + ';') - - # Here is where the heavy lifting begins. The following methods - # handle the begin-end tags of our SCons examples. - - def for_display(self, contents): - contents = contents.replace('__ROOT__', '') - contents = contents.replace('<', '<') - contents = contents.replace('>', '>') - return contents - - def start_scons_example(self, attrs): - t = [t for t in attrs if t[0] == 'name'] - if t: - name = t[0][1] - try: - e = self.examples[name] - except KeyError: - e = self.examples[name] = Example() - else: - e = Example() - for name, value in attrs: - setattr(e, name, value) - self.e = e - self.afunclist.append(e.afunc) - - def end_scons_example(self): - e = self.e - files = [f for f in e.files if f.printme] - if files: - self.outfp.write('<programlisting>') - for f in files: - if f.printme: - i = len(f.data) - 1 - while f.data[i] == ' ': - i = i - 1 - output = self.for_display(f.data[:i+1]) - self.outfp.write(output) - if e.data and e.data[0] == '\n': - e.data = e.data[1:] - self.outfp.write(e.data + '</programlisting>') - delattr(self, 'e') - self.afunclist = self.afunclist[:-1] - - def start_file(self, attrs): - try: - e = self.e - except AttributeError: - self.error("<file> tag outside of <scons_example>") - t = [t for t in attrs if t[0] == 'name'] - if not t: - self.error("no <file> name attribute found") - try: - e.prefix - except AttributeError: - e.prefix = e.data - e.data = "" - f = File(t[0][1]) - f.printme = None - for name, value in attrs: - setattr(f, name, value) - e.files.append(f) - self.afunclist.append(f.afunc) - - def end_file(self): - self.e.data = "" - self.afunclist = self.afunclist[:-1] - - def start_directory(self, attrs): - try: - e = self.e - except AttributeError: - self.error("<directory> tag outside of <scons_example>") - t = [t for t in attrs if t[0] == 'name'] - if not t: - self.error("no <directory> name attribute found") - try: - e.prefix - except AttributeError: - e.prefix = e.data - e.data = "" - d = Directory(t[0][1]) - for name, value in attrs: - setattr(d, name, value) - e.dirs.append(d) - self.afunclist.append(d.afunc) - - def end_directory(self): - self.e.data = "" - self.afunclist = self.afunclist[:-1] - - def start_scons_example_file(self, attrs): - t = [t for t in attrs if t[0] == 'example'] - if not t: - self.error("no <scons_example_file> example attribute found") - exname = t[0][1] - try: - e = self.examples[exname] - except KeyError: - self.error("unknown example name '%s'" % exname) - fattrs = [t for t in attrs if t[0] == 'name'] - if not fattrs: - self.error("no <scons_example_file> name attribute found") - fname = fattrs[0][1] - f = [f for f in e.files if f.name == fname] - if not f: - self.error("example '%s' does not have a file named '%s'" % (exname, fname)) - self.f = f[0] - - def end_scons_example_file(self): - f = self.f - self.outfp.write('<programlisting>') - self.outfp.write(f.data + '</programlisting>') - delattr(self, 'f') - - def start_scons_output(self, attrs): - t = [t for t in attrs if t[0] == 'example'] - if not t: - self.error("no <scons_output> example attribute found") - exname = t[0][1] - try: - e = self.examples[exname] - except KeyError: - self.error("unknown example name '%s'" % exname) - # Default values for an example. - o = Output() - o.preserve = None - o.os = 'posix' - o.tools = '' - o.e = e - # Locally-set. - for name, value in attrs: - setattr(o, name, value) - self.o = o - self.afunclist.append(o.afunc) - - def end_scons_output(self): - # The real raison d'etre for this script, this is where we - # actually execute SCons to fetch the output. - o = self.o - e = o.e +def create_scons_output(e): + # The real raison d'etre for this script, this is where we + # actually execute SCons to fetch the output. + + # Loop over all outputs for the example + for o in e.outputs: + # Create new test directory t = TestCmd.TestCmd(workdir='', combine=1) if o.preserve: t.preserve() t.subdir('ROOT', 'WORK') t.rootpath = t.workpath('ROOT').replace('\\', '\\\\') - - for d in e.dirs: + + for d in e.folders: dir = t.workpath('WORK', d.name) if not os.path.exists(dir): os.makedirs(dir) - + for f in e.files: + if f.isFileRef(): + continue + # + # Left-align file's contents, starting on the first + # non-empty line + # + data = f.content.split('\n') i = 0 - while f.data[i] == '\n': + # Skip empty lines + while data[i] == '': i = i + 1 - lines = f.data[i:].split('\n') + lines = data[i:] i = 0 + # Scan first line for the number of spaces + # that this block is indented while lines[0][i] == ' ': i = i + 1 + # Left-align block lines = [l[i:] for l in lines] path = f.name.replace('__ROOT__', t.rootpath) if not os.path.isabs(path): @@ -741,197 +811,85 @@ class MySGML(sgmllib.SGMLParser): path = t.workpath('WORK', path) t.write(path, content) if hasattr(f, 'chmod'): - os.chmod(path, int(f.chmod, 0)) - - i = len(o.prefix) - while o.prefix[i-1] != '\n': - i = i - 1 - - self.outfp.write('<screen>' + o.prefix[:i]) - p = o.prefix[i:] - + if len(f.chmod): + os.chmod(path, int(f.chmod, 0)) + # Regular expressions for making the doc output consistent, # regardless of reported addresses or Python version. - + # Massage addresses in object repr strings to a constant. address_re = re.compile(r' at 0x[0-9a-fA-F]*\>') - + # Massage file names in stack traces (sometimes reported as absolute # paths) to a consistent relative path. engine_re = re.compile(r' File ".*/src/engine/SCons/') - + # Python 2.5 changed the stack trace when the module is read # from standard input from read "... line 7, in ?" to # "... line 7, in <module>". file_re = re.compile(r'^( *File ".*", line \d+, in) \?$', re.M) - + # Python 2.6 made UserList a new-style class, which changes the # AttributeError message generated by our NodeList subclass. nodelist_re = re.compile(r'(AttributeError:) NodeList instance (has no attribute \S+)') - - for c in o.commandlist: - self.outfp.write(p + Prompt[o.os]) - d = c.data.replace('__ROOT__', '') - self.outfp.write('<userinput>' + d + '</userinput>\n') - - e = c.data.replace('__ROOT__', t.workpath('ROOT')) - args = e.split() - lines = ExecuteCommand(args, c, t, {'osname':o.os, 'tools':o.tools}) - content = None - if c.output: - content = c.output - elif lines: - content = ( '\n' + p).join(lines) - if content: - content = address_re.sub(r' at 0x700000>', content) - content = engine_re.sub(r' File "bootstrap/src/engine/SCons/', content) - content = file_re.sub(r'\1 <module>', content) - content = nodelist_re.sub(r"\1 'NodeList' object \2", content) - content = self.for_display(content) - self.outfp.write(p + content + '\n') - - if o.data[0] == '\n': - o.data = o.data[1:] - self.outfp.write(o.data + '</screen>') - delattr(self, 'o') - self.afunclist = self.afunclist[:-1] - - def start_scons_output_command(self, attrs): - try: - o = self.o - except AttributeError: - self.error("<scons_output_command> tag outside of <scons_output>") - try: - o.prefix - except AttributeError: - o.prefix = o.data - o.data = "" - c = Command() - for name, value in attrs: - setattr(c, name, value) - o.commandlist.append(c) - self.afunclist.append(c.afunc) - - def end_scons_output_command(self): - self.o.data = "" - self.afunclist = self.afunclist[:-1] - - def start_sconstruct(self, attrs): - f = File('') - self.f = f - self.afunclist.append(f.afunc) - - def end_sconstruct(self): - f = self.f - self.outfp.write('<programlisting>') - output = self.for_display(f.data) - self.outfp.write(output + '</programlisting>') - delattr(self, 'f') - self.afunclist = self.afunclist[:-1] - -def process(filename, fout=sys.stdout): - if filename == '-': - f = sys.stdin - else: - try: - f = open(filename, 'r') - except EnvironmentError, e: - sys.stderr.write('%s: %s\n' % (filename, e)) - return 1 - - data = f.read() - if f is not sys.stdin: - f.close() - - if data.startswith('<?xml '): - first_line, data = data.split('\n', 1) - fout.write(first_line + '\n') - - x = MySGML(fout) - for c in data: - x.feed(c) - x.close() - - return 0 - -def main(argv=None): - if argv is None: - argv = sys.argv - - parser = optparse.OptionParser() - parser.add_option('-d', '--diff', - action='store_true', dest='diff', default=False, - help='create examples for the .in file and output a unified diff against the related .xml file') - parser.add_option('-r', '--run', - action='store_true', dest='run', default=False, - help='create examples for the .in file, but do not change any files') - parser.add_option('-s', '--simple_diff', - action='store_true', dest='simple', default=False, - help='use a simpler output for the diff mode (no unified diff!)') - parser.add_option('-u', '--update', - action='store_true', dest='update', default=False, - help='create examples for the .in file and update the related .xml file') - - opts, args = parser.parse_args(argv[1:]) - - if opts.diff: - import StringIO - import difflib - - if not args: - args = glob.glob('doc/user/*.in') - for arg in sorted(args): - diff = None - s = StringIO.StringIO() - process(arg,s) - filename = arg[:-2]+'xml' - try: - fxml = open(filename, 'r') - xmlcontent = fxml.read() - fxml.close() - if opts.simple: - diff = list(difflib.context_diff(xmlcontent.splitlines(), - s.getvalue().splitlines(), - fromfile=arg, tofile=filename)) + + # Root element for our subtree + sroot = stf.newEtreeNode("screen", True) + curchild = None + content = "" + for c in o.commands: + content += Prompt[o.os] + if curchild is not None: + if not c.output: + # Append content as tail + curchild.tail = content + content = "\n" + # Add new child for userinput tag + curchild = stf.newEtreeNode("userinput") + d = c.cmd.replace('__ROOT__', '') + curchild.text = d + sroot.append(curchild) else: - diff = list(difflib.unified_diff(xmlcontent.splitlines(), - s.getvalue().splitlines(), - fromfile=arg, tofile=filename, - lineterm='')) - except EnvironmentError, e: - sys.stderr.write('%s: %s\n' % (filename, e)) - - s.close() - if diff: - print "%s:" % arg - print '\n'.join(diff) - elif opts.run: - if not args: - args = glob.glob('doc/user/*.in') - for arg in sorted(args): - print "%s:" % arg - process(arg) - elif opts.update: - if not args: - args = glob.glob('doc/user/*.in') - for arg in sorted(args): - print "%s:" % arg - filename = arg[:-2]+'xml' - try: - fxml = open(filename, 'w') - process(arg, fxml) - fxml.close() - except EnvironmentError, e: - sys.stderr.write('%s: %s\n' % (filename, e)) - else: - if not args: - args = ['-'] - - for arg in args: - process(arg) + content += c.output + '\n' + else: + if not c.output: + # Add first text to root + sroot.text = content + content = "\n" + # Add new child for userinput tag + curchild = stf.newEtreeNode("userinput") + d = c.cmd.replace('__ROOT__', '') + curchild.text = d + sroot.append(curchild) + else: + content += c.output + '\n' + # Execute command and capture its output + cmd_work = c.cmd.replace('__ROOT__', t.workpath('ROOT')) + args = cmd_work.split() + lines = ExecuteCommand(args, c, t, {'osname':o.os, 'tools':o.tools}) + if not c.output and lines: + ncontent = '\n'.join(lines) + ncontent = address_re.sub(r' at 0x700000>', ncontent) + ncontent = engine_re.sub(r' File "bootstrap/src/engine/SCons/', ncontent) + ncontent = file_re.sub(r'\1 <module>', ncontent) + ncontent = nodelist_re.sub(r"\1 'NodeList' object \2", ncontent) + ncontent = ncontent.replace('__ROOT__', '') + content += ncontent + '\n' + # Add last piece of content + if len(content): + if curchild is not None: + curchild.tail = content + else: + sroot.text = content + + # Construct filename + fpath = os.path.join(generated_examples, + e.name + '_' + o.suffix + '.xml') + # Expand Element tree + s = stf.decorateWithHeader(stf.convertElementTree(sroot)[0]) + # Write it to file + stf.writeTree(s, fpath) -if __name__ == "__main__": - sys.exit(main()) # Local Variables: # tab-width:4 diff --git a/bin/docs-create-example-outputs.py b/bin/docs-create-example-outputs.py new file mode 100644 index 0000000..30dc0ee --- /dev/null +++ b/bin/docs-create-example-outputs.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +# +# Searches through the whole doc/user tree and creates +# all output files for the single examples. +# + +import os +import sys +import SConsExamples + +if __name__ == "__main__": + print "Checking whether all example names are unique..." + if SConsExamples.exampleNamesAreUnique(os.path.join('doc','user')): + print "OK" + else: + print "Not all example names and suffixes are unique! Please correct the errors listed above and try again." + sys.exit(0) + + SConsExamples.createAllExampleOutputs(os.path.join('doc','user')) diff --git a/bin/docs-update-generated.py b/bin/docs-update-generated.py new file mode 100644 index 0000000..66b22c0 --- /dev/null +++ b/bin/docs-update-generated.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +# +# Searches through the whole source tree and updates +# the generated *.gen/*.mod files in the docs folder, keeping all +# documentation for the tools, builders and functions... +# as well as the entity declarations for them. +# Uses scons-proc.py under the hood... +# + +import os +import SConsDoc + +# Directory where all generated files are stored +gen_folder = os.path.join('doc','generated') + +def argpair(key): + """ Return the argument pair *.gen,*.mod for the given key. """ + arg = '%s,%s' % (os.path.join(gen_folder,'%s.gen' % key), + os.path.join(gen_folder,'%s.mod' % key)) + + return arg + +def generate_all(): + """ Scan for XML files in the src directory and call scons-proc.py + to generate the *.gen/*.mod files from it. + """ + flist = [] + for path, dirs, files in os.walk('src'): + for f in files: + if f.endswith('.xml'): + fpath = os.path.join(path, f) + if SConsDoc.isSConsXml(fpath): + flist.append(fpath) + + if flist: + # Does the destination folder exist + if not os.path.isdir(gen_folder): + try: + os.makedirs(gen_folder) + except: + print "Couldn't create destination folder %s! Exiting..." % gen_folder + return + # Call scons-proc.py + os.system('python %s -b %s -f %s -t %s -v %s %s' % + (os.path.join('bin','scons-proc.py'), + argpair('builders'), argpair('functions'), + argpair('tools'), argpair('variables'), ' '.join(flist))) + + +if __name__ == "__main__": + generate_all() diff --git a/bin/docs-validate.py b/bin/docs-validate.py new file mode 100644 index 0000000..c445c3f --- /dev/null +++ b/bin/docs-validate.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python +# +# Searches through the whole source tree and validates all +# documentation files against our own XSD in docs/xsd. +# + +import sys,os +import SConsDoc + +if __name__ == "__main__": + if len(sys.argv)>1: + if SConsDoc.validate_all_xml((sys.argv[1],)): + print "OK" + else: + print "Validation failed! Please correct the errors above and try again." + else: + if SConsDoc.validate_all_xml(['src', + os.path.join('doc','design'), + os.path.join('doc','developer'), + os.path.join('doc','man'), + os.path.join('doc','python10'), + os.path.join('doc','reference'), + os.path.join('doc','user') + ]): + print "OK" + else: + print "Validation failed! Please correct the errors above and try again." diff --git a/bin/import-test.py b/bin/import-test.py index a565deb..ccec096 100644 --- a/bin/import-test.py +++ b/bin/import-test.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation +# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation # # tree2test.py - turn a directory tree into TestSCons code # @@ -25,7 +25,7 @@ # """ triple-quotes will need to have their contents edited by hand. # -__revision__ = "bin/import-test.py 2013/03/03 09:48:35 garyo" +__revision__ = "bin/import-test.py 2014/03/02 14:18:15 garyo" import os.path import sys diff --git a/bin/linecount.py b/bin/linecount.py index 8d1fd7c..9088529 100644 --- a/bin/linecount.py +++ b/bin/linecount.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation +# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation # # Count statistics about SCons test and source files. This must be run # against a fully-populated tree (for example, one that's been freshly @@ -23,7 +23,7 @@ # interesting one for most purposes. from __future__ import division -__revision__ = "bin/linecount.py 2013/03/03 09:48:35 garyo" +__revision__ = "bin/linecount.py 2014/03/02 14:18:15 garyo" import os.path diff --git a/bin/restore.sh b/bin/restore.sh index b2b10b1..df296a4 100644 --- a/bin/restore.sh +++ b/bin/restore.sh @@ -1,6 +1,6 @@ #!/usr/bin/env sh # -# Simple hack script to restore __revision__, __COPYRIGHT_, 2.3.0 +# Simple hack script to restore __revision__, __COPYRIGHT_, 2.3.1 # and other similar variables to what gets checked in to source. This # comes in handy when people send in diffs based on the released source. # @@ -22,9 +22,9 @@ header() { for i in `find $DIRS -name '*.py'`; do header $i ed $i <<EOF -g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation/p +g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation/p w -/^__revision__ = /s/= .*/= "bin/restore.sh 2013/03/03 09:48:35 garyo"/p +/^__revision__ = /s/= .*/= "bin/restore.sh 2014/03/02 14:18:15 garyo"/p w q EOF @@ -33,9 +33,9 @@ done for i in `find $DIRS -name 'scons.bat'`; do header $i ed $i <<EOF -g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation/p +g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation/p w -/^@REM src\/script\/scons.bat/s/@REM .* knight/@REM bin/restore.sh 2013/03/03 09:48:35 garyo/p +/^@REM src\/script\/scons.bat/s/@REM .* knight/@REM bin/restore.sh 2014/03/02 14:18:15 garyo/p w q EOF @@ -44,13 +44,13 @@ done for i in `find $DIRS -name '__init__.py' -o -name 'scons.py' -o -name 'sconsign.py'`; do header $i ed $i <<EOF -/^__version__ = /s/= .*/= "2.3.0"/p +/^__version__ = /s/= .*/= "2.3.1"/p w /^__build__ = /s/= .*/= ""/p w -/^__buildsys__ = /s/= .*/= "reepicheep"/p +/^__buildsys__ = /s/= .*/= "lubuntu"/p w -/^__date__ = /s/= .*/= "2013/03/03 09:48:35"/p +/^__date__ = /s/= .*/= "2014/03/02 14:18:15"/p w /^__developer__ = /s/= .*/= "garyo"/p w @@ -61,7 +61,7 @@ done for i in `find $DIRS -name 'setup.py'`; do header $i ed $i <<EOF -/^ *version = /s/= .*/= "2.3.0",/p +/^ *version = /s/= .*/= "2.3.1",/p w q EOF @@ -70,11 +70,11 @@ done for i in `find $DIRS -name '*.txt'`; do header $i ed $i <<EOF -g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation/p +g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation/p w -/# [^ ]* 0.96.[CD][0-9]* [0-9\/]* [0-9:]* knight$/s/.*/# bin/restore.sh 2013/03/03 09:48:35 garyo/p +/# [^ ]* 0.96.[CD][0-9]* [0-9\/]* [0-9:]* knight$/s/.*/# bin/restore.sh 2014/03/02 14:18:15 garyo/p w -/Version [0-9][0-9]*\.[0-9][0-9]*/s//Version 2.3.0/p +/Version [0-9][0-9]*\.[0-9][0-9]*/s//Version 2.3.1/p w q EOF @@ -83,7 +83,7 @@ done for i in `find $DIRS -name '*.xml'`; do header $i ed $i <<EOF -g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation/p +g/Copyright (c) 2001.*SCons Foundation/s//Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation/p w q EOF diff --git a/bin/scons-proc.py b/bin/scons-proc.py index 1f537c7..9567db8 100644 --- a/bin/scons-proc.py +++ b/bin/scons-proc.py @@ -5,17 +5,15 @@ # This script creates formatted lists of the Builders, functions, Tools # or construction variables documented in the specified XML files. # -# Dependening on the options, the lists are output in either +# Depending on the options, the lists are output in either # DocBook-formatted generated XML files containing the summary text -# and/or .mod files contining the ENTITY definitions for each item, -# or in man-page-formatted output. +# and/or .mod files containing the ENTITY definitions for each item. # import getopt import os import re import string import sys -import xml.sax try: from io import StringIO # usable as of 2.6; takes unicode only except ImportError: @@ -23,32 +21,31 @@ except ImportError: exec('from cStringIO import StringIO') import SConsDoc +from SConsDoc import tf as stf base_sys_path = [os.getcwd() + '/build/test-tar-gz/lib/scons'] + sys.path helpstr = """\ -Usage: scons-proc.py [--man|--xml] - [-b file(s)] [-f file(s)] [-t file(s)] [-v file(s)] +Usage: scons-proc.py [-b file(s)] [-f file(s)] [-t file(s)] [-v file(s)] [infile ...] Options: -b file(s) dump builder information to the specified file(s) -f file(s) dump function information to the specified file(s) -t file(s) dump tool information to the specified file(s) -v file(s) dump variable information to the specified file(s) - --man print info in man page format, each -[btv] argument - is a single file name - --xml (default) print info in SML format, each -[btv] argument - is a pair of comma-separated .gen,.mod file names + + Regard that each -[btv] argument is a pair of + comma-separated .gen,.mod file names. + """ opts, args = getopt.getopt(sys.argv[1:], "b:f:ht:v:", ['builders=', 'help', - 'man', 'xml', 'tools=', 'variables=']) + 'tools=', 'variables=']) buildersfiles = None functionsfiles = None -output_type = '--xml' toolsfiles = None variablesfiles = None @@ -60,55 +57,29 @@ for o, a in opts: elif o in ['-h', '--help']: sys.stdout.write(helpstr) sys.exit(0) - elif o in ['--man', '--xml']: - output_type = o elif o in ['-t', '--tools']: toolsfiles = a elif o in ['-v', '--variables']: variablesfiles = a -h = SConsDoc.SConsDocHandler() -saxparser = xml.sax.make_parser() -saxparser.setContentHandler(h) -saxparser.setErrorHandler(h) - -xml_preamble = """\ -<?xml version="1.0"?> -<scons_doc> -""" - -xml_postamble = """\ -</scons_doc> -""" - -for f in args: - _, ext = os.path.splitext(f) - if ext == '.py': - dir, _ = os.path.split(f) - if dir: - sys.path = [dir] + base_sys_path - module = SConsDoc.importfile(f) - h.set_file_info(f, len(xml_preamble.split('\n'))) - try: - content = module.__scons_doc__ - except AttributeError: - content = None +def parse_docs(args, include_entities=True): + h = SConsDoc.SConsDocHandler() + for f in args: + if include_entities: + try: + h.parseXmlFile(f) + except: + sys.stderr.write("error in %s\n" % f) + raise else: - del module.__scons_doc__ - else: - h.set_file_info(f, len(xml_preamble.split('\n'))) - content = open(f).read() - if content: - content = content.replace('&', '&') - # Strip newlines after comments so they don't turn into - # spurious paragraph separators. - content = content.replace('-->\n', '-->') - input = xml_preamble + content + xml_postamble - try: - saxparser.parse(StringIO(unicode(input))) - except: - sys.stderr.write("error in %s\n" % f) - raise + content = open(f).read() + if content: + try: + h.parseContent(content, include_entities) + except: + sys.stderr.write("error in %s\n" % f) + raise + return h Warning = """\ <!-- @@ -137,176 +108,113 @@ class SCons_XML(object): self.values = entries for k, v in kw.items(): setattr(self, k, v) + def fopen(self, name): if name == '-': return sys.stdout return open(name, 'w') - -class SCons_XML_to_XML(SCons_XML): + def write(self, files): gen, mod = files.split(',') - g.write_gen(gen) - g.write_mod(mod) + self.write_gen(gen) + self.write_mod(mod) + def write_gen(self, filename): if not filename: return - f = self.fopen(filename) + # Try to split off .gen filename + if filename.count(','): + fl = filename.split(',') + filename = fl[0] + + # Start new XML file + root = stf.newXmlTree("variablelist") + for v in self.values: - f.write('\n<varlistentry id="%s%s">\n' % - (v.prefix, v.idfunc())) - f.write('%s\n' % v.xml_term()) - f.write('<listitem>\n') - for chunk in v.summary.body: - f.write(str(chunk)) - if v.sets: + + ve = stf.newNode("varlistentry") + stf.setAttribute(ve, 'id', '%s%s' % (v.prefix, v.idfunc())) + for t in v.xml_terms(): + stf.appendNode(ve, t) + vl = stf.newNode("listitem") + added = False + if v.summary is not None: + for s in v.summary: + added = True + stf.appendNode(vl, stf.copyNode(s)) + + if len(v.sets): + added = True + vp = stf.newNode("para") s = ['&cv-link-%s;' % x for x in v.sets] - f.write('<para>\n') - f.write('Sets: ' + ', '.join(s) + '.\n') - f.write('</para>\n') - if v.uses: + stf.setText(vp, 'Sets: ' + ', '.join(s) + '.') + stf.appendNode(vl, vp) + if len(v.uses): + added = True + vp = stf.newNode("para") u = ['&cv-link-%s;' % x for x in v.uses] - f.write('<para>\n') - f.write('Uses: ' + ', '.join(u) + '.\n') - f.write('</para>\n') - f.write('</listitem>\n') - f.write('</varlistentry>\n') + stf.setText(vp, 'Uses: ' + ', '.join(u) + '.') + stf.appendNode(vl, vp) + + # Still nothing added to this list item? + if not added: + # Append an empty para + vp = stf.newNode("para") + stf.appendNode(vl, vp) + + stf.appendNode(ve, vl) + stf.appendNode(root, ve) + + # Write file + f = self.fopen(filename) + stf.writeGenTree(root, f) + def write_mod(self, filename): - description = self.values[0].description + try: + description = self.values[0].description + except: + description = "" if not filename: return + # Try to split off .mod filename + if filename.count(','): + fl = filename.split(',') + filename = fl[1] f = self.fopen(filename) f.write(Warning) f.write('\n') f.write(Regular_Entities_Header % description) f.write('\n') for v in self.values: - f.write('<!ENTITY %s%s "<%s>%s</%s>">\n' % + f.write('<!ENTITY %s%s "<%s xmlns=\'%s\'>%s</%s>">\n' % (v.prefix, v.idfunc(), - v.tag, v.entityfunc(), v.tag)) + v.tag, SConsDoc.dbxsd, v.entityfunc(), v.tag)) if self.env_signatures: f.write('\n') for v in self.values: - f.write('<!ENTITY %senv-%s "<%s>env.%s</%s>">\n' % + f.write('<!ENTITY %senv-%s "<%s xmlns=\'%s\'>env.%s</%s>">\n' % (v.prefix, v.idfunc(), - v.tag, v.entityfunc(), v.tag)) + v.tag, SConsDoc.dbxsd, v.entityfunc(), v.tag)) f.write('\n') f.write(Warning) f.write('\n') f.write(Link_Entities_Header % description) f.write('\n') for v in self.values: - f.write('<!ENTITY %slink-%s \'<link linkend="%s%s"><%s>%s</%s></link>\'>\n' % + f.write('<!ENTITY %slink-%s "<link linkend=\'%s%s\' xmlns=\'%s\'><%s>%s</%s></link>">\n' % (v.prefix, v.idfunc(), - v.prefix, v.idfunc(), + v.prefix, v.idfunc(), SConsDoc.dbxsd, v.tag, v.entityfunc(), v.tag)) if self.env_signatures: f.write('\n') for v in self.values: - f.write('<!ENTITY %slink-env-%s \'<link linkend="%s%s"><%s>env.%s</%s></link>\'>\n' % + f.write('<!ENTITY %slink-env-%s "<link linkend=\'%s%s\' xmlns=\'%s\'><%s>env.%s</%s></link>">\n' % (v.prefix, v.idfunc(), - v.prefix, v.idfunc(), + v.prefix, v.idfunc(), SConsDoc.dbxsd, v.tag, v.entityfunc(), v.tag)) f.write('\n') f.write(Warning) -class SCons_XML_to_man(SCons_XML): - def write(self, filename): - """ - Converts the contents of the specified filename from DocBook XML - to man page macros. - - This does not do an intelligent job. In particular, it doesn't - actually use the structured nature of XML to handle arbitrary - input. Instead, we're using text replacement and regular - expression substitutions to convert observed patterns into the - macros we want. To the extent that we're relatively consistent - with our input .xml, this works, but could easily break if handed - input that doesn't match these specific expectations. - """ - if not filename: - return - f = self.fopen(filename) - chunks = [] - for v in self.values: - chunks.extend(v.man_separator()) - chunks.extend(v.initial_man_chunks()) - chunks.extend(list(map(str, v.summary.body))) - - body = ''.join(chunks) - - # Simple transformation of examples into our defined macros for those. - body = body.replace('<programlisting>', '.ES') - body = body.replace('</programlisting>', '.EE') - - # Replace groupings of <para> tags and surrounding newlines - # with single blank lines. - body = body.replace('\n</para>\n<para>\n', '\n\n') - body = body.replace('<para>\n', '') - body = body.replace('<para>', '\n') - body = body.replace('</para>\n', '') - - # Convert <variablelist> and its child tags. - body = body.replace('<variablelist>\n', '.RS 10\n') - # Handling <varlistentry> needs to be rationalized and made - # consistent. Right now, the <term> values map to arbitrary, - # ad-hoc idioms in the current man page. - body = re.compile(r'<varlistentry>\n<term><literal>([^<]*)</literal></term>\n<listitem>\n').sub(r'.TP 6\n.B \1\n', body) - body = re.compile(r'<varlistentry>\n<term><parameter>([^<]*)</parameter></term>\n<listitem>\n').sub(r'.IP \1\n', body) - body = re.compile(r'<varlistentry>\n<term>([^<]*)</term>\n<listitem>\n').sub(r'.HP 6\n.B \1\n', body) - body = body.replace('</listitem>\n', '') - body = body.replace('</varlistentry>\n', '') - body = body.replace('</variablelist>\n', '.RE\n') - - # Get rid of unnecessary .IP macros, and unnecessary blank lines - # in front of .IP macros. - body = re.sub(r'\.EE\n\n+(?!\.IP)', '.EE\n.IP\n', body) - body = body.replace('\n.EE\n.IP\n.ES\n', '\n.EE\n\n.ES\n') - body = body.replace('\n.IP\n\'\\"', '\n\n\'\\"') - - # Convert various named entities and tagged names to nroff - # in-line font conversions (\fB, \fI, \fP). - body = re.sub('&(scons|SConstruct|SConscript|Dir|jar|Make|lambda);', - r'\\fB\1\\fP', body) - body = re.sub('&(TARGET|TARGETS|SOURCE|SOURCES);', r'\\fB$\1\\fP', body) - body = re.sub('&(target|source);', r'\\fI\1\\fP', body) - body = re.sub('&b(-link)?-([^;]*);', r'\\fB\2\\fP()', body) - body = re.sub('&cv(-link)?-([^;]*);', r'\\fB$\2\\fP', body) - body = re.sub('&f(-link)?-env-([^;]*);', r'\\fBenv.\2\\fP()', body) - body = re.sub('&f(-link)?-([^;]*);', r'\\fB\2\\fP()', body) - body = re.sub(r'<(application|command|envar|filename|function|literal|option)>([^<]*)</\1>', - r'\\fB\2\\fP', body) - body = re.sub(r'<(classname|emphasis|varname)>([^<]*)</\1>', - r'\\fI\2\\fP', body) - - # Convert groupings of font conversions (\fB, \fI, \fP) to - # man page .B, .BR, .I, .IR, .R, .RB and .RI macros. - body = re.compile(r'^\\f([BI])([^\\]* [^\\]*)\\fP\s*$', re.M).sub(r'.\1 "\2"', body) - body = re.compile(r'^\\f([BI])(.*)\\fP\s*$', re.M).sub(r'.\1 \2', body) - body = re.compile(r'^\\f([BI])(.*)\\fP(\S+)$', re.M).sub(r'.\1R \2 \3', body) - body = re.compile(r'^(\.B)( .*)\\fP(.*)\\fB(.*)$', re.M).sub(r'\1R\2 \3 \4', body) - body = re.compile(r'^(\.B)R?( .*)\\fP(.*)\\fI(.*)$', re.M).sub(r'\1I\2\3 \4', body) - body = re.compile(r'^(\.I)( .*)\\fP\\fB(.*)\\fP\\fI(.*)$', re.M).sub(r'\1R\2 \3 \4', body) - body = re.compile(r'^(\S+)\\f([BI])(.*)\\fP$', re.M).sub(r'.R\2 \1 \3', body) - body = re.compile(r'^(\S+)\\f([BI])(.*)\\fP([^\s\\]+)$', re.M).sub(r'.R\2 \1 \3 \4', body) - body = re.compile(r'^(\.R[BI].*[\S])\s+$;', re.M).sub(r'\1', body) - - # Convert < and > entities to literal < and > characters. - body = body.replace('<', '<') - body = body.replace('>', '>') - - # Backslashes. Oh joy. - body = re.sub(r'\\(?=[^f])', r'\\\\', body) - body = re.compile("^'\\\\\\\\", re.M).sub("'\\\\", body) - body = re.compile(r'^\.([BI]R?) ([^"]\S*\\\\\S+[^"])$', re.M).sub(r'.\1 "\2"', body) - - # Put backslashes in front of various hyphens that need - # to be long em-dashes. - body = re.compile(r'^\.([BI]R?) --', re.M).sub(r'.\1 \-\-', body) - body = re.compile(r'^\.([BI]R?) -', re.M).sub(r'.\1 \-', body) - body = re.compile(r'\\f([BI])-', re.M).sub(r'\\f\1\-', body) - - f.write(body) - class Proxy(object): def __init__(self, subject): """Wrap an object as a Proxy object""" @@ -329,156 +237,132 @@ class Proxy(object): class SConsThing(Proxy): def idfunc(self): return self.name - def xml_term(self): - return '<term>%s</term>' % self.name + + def xml_terms(self): + e = stf.newNode("term") + stf.setText(e, self.name) + return [e] class Builder(SConsThing): description = 'builder' prefix = 'b-' tag = 'function' - def xml_term(self): - return ('<term><synopsis><%s>%s()</%s></synopsis>\n<synopsis><%s>env.%s()</%s></synopsis></term>' % - (self.tag, self.name, self.tag, self.tag, self.name, self.tag)) + + def xml_terms(self): + ta = stf.newNode("term") + b = stf.newNode(self.tag) + stf.setText(b, self.name+'()') + stf.appendNode(ta, b) + tb = stf.newNode("term") + b = stf.newNode(self.tag) + stf.setText(b, 'env.'+self.name+'()') + stf.appendNode(tb, b) + return [ta, tb] + def entityfunc(self): return self.name - def man_separator(self): - return ['\n', "'\\" + '"'*69 + '\n'] - def initial_man_chunks(self): - return [ '.IP %s()\n.IP env.%s()\n' % (self.name, self.name) ] class Function(SConsThing): description = 'function' prefix = 'f-' tag = 'function' - def args_to_xml(self, arg): - s = ''.join(arg.body).strip() - result = [] - for m in re.findall('([a-zA-Z/_]+=?|[^a-zA-Z/_]+)', s): - if m[0] in string.letters: - if m[-1] == '=': - result.append('<literal>%s</literal>=' % m[:-1]) - else: - result.append('<varname>%s</varname>' % m) - else: - result.append(m) - return ''.join(result) - def xml_term(self): - try: + + def xml_terms(self): + if self.arguments is None: + a = stf.newNode("arguments") + stf.setText(a, '()') + arguments = [a] + else: arguments = self.arguments - except AttributeError: - arguments = ['()'] - result = ['<term>'] + tlist = [] for arg in arguments: - try: - signature = arg.signature - except AttributeError: - signature = "both" - s = self.args_to_xml(arg) + signature = 'both' + if stf.hasAttribute(arg, 'signature'): + signature = stf.getAttribute(arg, 'signature') + s = stf.getText(arg).strip() if signature in ('both', 'global'): - result.append('<synopsis>%s%s</synopsis>\n' % (self.name, s)) #<br> + t = stf.newNode("term") + syn = stf.newNode("literal") + stf.setText(syn, '%s%s' % (self.name, s)) + stf.appendNode(t, syn) + tlist.append(t) if signature in ('both', 'env'): - result.append('<synopsis><varname>env</varname>.%s%s</synopsis>' % (self.name, s)) - result.append('</term>') - return ''.join(result) + t = stf.newNode("term") + syn = stf.newNode("literal") + stf.setText(syn, 'env.%s%s' % (self.name, s)) + stf.appendNode(t, syn) + tlist.append(t) + + if not tlist: + tlist.append(stf.newNode("term")) + return tlist + def entityfunc(self): return self.name - def man_separator(self): - return ['\n', "'\\" + '"'*69 + '\n'] - def args_to_man(self, arg): - """Converts the contents of an <arguments> tag, which - specifies a function's calling signature, into a series - of tokens that alternate between literal tokens - (to be displayed in roman or bold face) and variable - names (to be displayed in italics). - - This is complicated by the presence of Python "keyword=var" - arguments, where "keyword=" should be displayed literally, - and "var" should be displayed in italics. We do this by - detecting the keyword= var portion and appending it to the - previous string, if any. - """ - s = ''.join(arg.body).strip() - result = [] - for m in re.findall('([a-zA-Z/_]+=?|[^a-zA-Z/_]+)', s): - if m[-1] == '=' and result: - if result[-1][-1] == '"': - result[-1] = result[-1][:-1] + m + '"' - else: - result[-1] += m - else: - if ' ' in m: - m = '"%s"' % m - result.append(m) - return ' '.join(result) - def initial_man_chunks(self): - try: - arguments = self.arguments - except AttributeError: - arguments = ['()'] - result = [] - for arg in arguments: - try: - signature = arg.signature - except AttributeError: - signature = "both" - s = self.args_to_man(arg) - if signature in ('both', 'global'): - result.append('.TP\n.RI %s%s\n' % (self.name, s)) - if signature in ('both', 'env'): - result.append('.TP\n.IR env .%s%s\n' % (self.name, s)) - return result class Tool(SConsThing): description = 'tool' prefix = 't-' tag = 'literal' + def idfunc(self): return self.name.replace('+', 'X') + def entityfunc(self): return self.name - def man_separator(self): - return ['\n'] - def initial_man_chunks(self): - return ['.IP %s\n' % self.name] class Variable(SConsThing): description = 'construction variable' prefix = 'cv-' tag = 'envar' + def entityfunc(self): return '$' + self.name - def man_separator(self): - return ['\n'] - def initial_man_chunks(self): - return ['.IP %s\n' % self.name] -if output_type == '--man': - processor_class = SCons_XML_to_man -elif output_type == '--xml': - processor_class = SCons_XML_to_XML +def write_output_files(h, buildersfiles, functionsfiles, + toolsfiles, variablesfiles, write_func): + if buildersfiles: + g = processor_class([ Builder(b) for b in sorted(h.builders.values()) ], + env_signatures=True) + write_func(g, buildersfiles) + + if functionsfiles: + g = processor_class([ Function(b) for b in sorted(h.functions.values()) ], + env_signatures=True) + write_func(g, functionsfiles) + + if toolsfiles: + g = processor_class([ Tool(t) for t in sorted(h.tools.values()) ], + env_signatures=False) + write_func(g, toolsfiles) + + if variablesfiles: + g = processor_class([ Variable(v) for v in sorted(h.cvars.values()) ], + env_signatures=False) + write_func(g, variablesfiles) + +processor_class = SCons_XML + +# Step 1: Creating entity files for builders, functions,... +print "Generating entity files..." +h = parse_docs(args, False) +write_output_files(h, buildersfiles, functionsfiles, toolsfiles, + variablesfiles, SCons_XML.write_mod) + +# Step 2: Validating all input files +print "Validating files against SCons XSD..." +if SConsDoc.validate_all_xml(['src']): + print "OK" else: - sys.stderr.write("Unknown output type '%s'\n" % output_type) - sys.exit(1) - -if buildersfiles: - g = processor_class([ Builder(b) for b in sorted(h.builders.values()) ], - env_signatures=True) - g.write(buildersfiles) - -if functionsfiles: - g = processor_class([ Function(b) for b in sorted(h.functions.values()) ], - env_signatures=True) - g.write(functionsfiles) - -if toolsfiles: - g = processor_class([ Tool(t) for t in sorted(h.tools.values()) ], - env_signatures=False) - g.write(toolsfiles) - -if variablesfiles: - g = processor_class([ Variable(v) for v in sorted(h.cvars.values()) ], - env_signatures=False) - g.write(variablesfiles) + print "Validation failed! Please correct the errors above and try again." + +# Step 3: Creating actual documentation snippets, using the +# fully resolved and updated entities from the *.mod files. +print "Updating documentation for builders, tools and functions..." +h = parse_docs(args, True) +write_output_files(h, buildersfiles, functionsfiles, toolsfiles, + variablesfiles, SCons_XML.write) +print "Done" # Local Variables: # tab-width:4 diff --git a/bin/scons_dev_master.py b/bin/scons_dev_master.py index 9372df4..3c41ac0 100644 --- a/bin/scons_dev_master.py +++ b/bin/scons_dev_master.py @@ -25,19 +25,14 @@ PYTHON_PACKAGES = [ ] BUILDING_PACKAGES = [ - 'docbook', - 'docbook-dsssl', - 'docbook-utils', - 'docbook-xml', - 'groff-base', - 'jade', - 'jadetex', - 'man2html', + 'python-libxml2', + 'python-libxslt1', + 'fop', + 'python-dev', 'python-epydoc', 'rpm', - 'sp', 'tar', - + # additional packages that Bill Deegan's web page suggests #'docbook-to-man', #'docbook-xsl', diff --git a/bin/update-release-info.py b/bin/update-release-info.py index 1b3015a..b8c50bd 100644 --- a/bin/update-release-info.py +++ b/bin/update-release-info.py @@ -36,7 +36,7 @@ In 'post' mode, files are prepared for the next release cycle: src/Announce.txt. """ # -# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation +# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the @@ -57,7 +57,7 @@ In 'post' mode, files are prepared for the next release cycle: # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -__revision__ = "bin/update-release-info.py 2013/03/03 09:48:35 garyo" +__revision__ = "bin/update-release-info.py 2014/03/02 14:18:15 garyo" import os import sys @@ -333,17 +333,18 @@ t.replace_assign('deprecated_python_version', str(deprecated_version)) # Update doc/user/main.{in,xml} docyears = ', '.join(map(str, iter(range(2004, release_date[0] + 1)))) -t = UpdateFile(os.path.join('doc', 'user', 'main.in')) -if DEBUG: t.file = '/tmp/main.in' -## TODO debug these -#t.sub('<pubdate>[^<]*</pubdate>', '<pubdate>' + docyears + '</pubdate>') -#t.sub('<year>[^<]*</year>', '<year>' + docyears + '</year>') +if os.path.exists(os.path.join('doc', 'user', 'main.in')): + # this is no longer used as of Dec 2013 + t = UpdateFile(os.path.join('doc', 'user', 'main.in')) + if DEBUG: t.file = '/tmp/main.in' + ## TODO debug these + #t.sub('<pubdate>[^<]*</pubdate>', '<pubdate>' + docyears + '</pubdate>') + #t.sub('<year>[^<]*</year>', '<year>' + docyears + '</year>') t = UpdateFile(os.path.join('doc', 'user', 'main.xml')) if DEBUG: t.file = '/tmp/main.xml' -## TODO debug these -#t.sub('<pubdate>[^<]*</pubdate>', '<pubdate>' + docyears + '</pubdate>') -#t.sub('<year>[^<]*</year>', '<year>' + docyears + '</year>') +t.sub('<pubdate>[^<]*</pubdate>', '<pubdate>' + docyears + '</pubdate>') +t.sub('<year>[^<]*</year>', '<year>' + docyears + '</year>') # Write out the last update |