From 140d836e9cd54fb67b969fd82ef7ed19ba574d40 Mon Sep 17 00:00:00 2001 From: Luca Falavigna Date: Sat, 26 Apr 2014 15:11:58 +0200 Subject: Imported Upstream version 2.3.1 --- bin/SConsDoc.py | 892 +++++++++++++++++++++++++---------- bin/SConsExamples.py | 898 +++++++++++++++++++++++++++++++++++ bin/docs-create-example-outputs.py | 19 + bin/docs-update-generated.py | 51 ++ bin/docs-validate.py | 27 ++ bin/import-test.py | 4 +- bin/linecount.py | 4 +- bin/restore.sh | 26 +- bin/scons-doc.py | 940 ------------------------------------- bin/scons-proc.py | 478 +++++++------------ bin/scons_dev_master.py | 15 +- bin/update-release-info.py | 21 +- 12 files changed, 1865 insertions(+), 1510 deletions(-) create mode 100644 bin/SConsExamples.py create mode 100644 bin/docs-create-example-outputs.py create mode 100644 bin/docs-update-generated.py create mode 100644 bin/docs-validate.py delete mode 100644 bin/scons-doc.py (limited to 'bin') 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: - This is the summary description of an SCons Builder. + 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. 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) - This is the summary description of an SCons function. + 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. print "this is example code, it will be offset and indented" @@ -65,18 +80,12 @@ Construction variable example: - This is the summary description of a construction variable. + 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. print "this is example code, it will be offset and indented" @@ -88,18 +97,12 @@ Tool example: - This is the summary description of an SCons Tool. + 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. 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("") + +# 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 = """ + %(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 = '\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("", 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\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('' % 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/SConsExamples.py b/bin/SConsExamples.py new file mode 100644 index 0000000..9823a05 --- /dev/null +++ b/bin/SConsExamples.py @@ -0,0 +1,898 @@ +# !/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. + +# +# +# 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 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): +# +# +# +# env = Environment() +# env.Program('foo') +# +# +# int main() { printf("foo.c\n"); } +# +# +# +# The contents within the tag will get written +# into a temporary directory whenever example output needs to be +# generated. By default, the contents are not inserted into text +# directly, unless you set the "printme" attribute on one or more files, +# in which case they will get inserted within a 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 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 tag: +# +# +# env = Environment() +# env.Program('foo') +# +# +# This is essentially equivalent to , +# but it's more straightforward. +# +# SCons output is generated from the following sort of tag: +# +# +# scons -Q foo +# scons -Q foo +# +# +# You tell it which example to use with the "example" attribute, and then +# give it a list of 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 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 os +import re +import sys +import time + +import SConsDoc +from SConsDoc import tf as stf + +# +# The available types for ExampleFile entries +# +FT_FILE = 0 # a physical file (=) +FT_FILEREF = 1 # a reference (=) + +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')) + +scons_py = os.path.join('bootstrap', 'src', 'script', 'scons.py') +if not os.path.exists(scons_py): + scons_py = os.path.join('src', 'script', 'scons.py') + +scons_lib_dir = os.path.join(os.getcwd(), 'bootstrap', 'src', 'engine') +if not os.path.exists(scons_lib_dir): + scons_lib_dir = os.path.join(os.getcwd(), 'src', 'engine') + +os.environ['SCONS_LIB_DIR'] = scons_lib_dir + +import TestCmd + +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 +# of ToolSurrogates for the tools for the appropriate platform. These +# 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. + +Stdin = """\ +import os +import re +import SCons.Action +import SCons.Defaults +import SCons.Node.FS + +platform = '%(osname)s' + +Sep = { + 'posix' : '/', + 'win32' : '\\\\', +}[platform] + + +# Slip our own __str__() method into the EntryProxy class used to expand +# $TARGET{S} and $SOURCE{S} to translate the path-name separators from +# what's appropriate for the system we're running on to what's appropriate +# for the example system. +orig = SCons.Node.FS.EntryProxy +class MyEntryProxy(orig): + def __str__(self): + return str(self._subject).replace(os.sep, Sep) +SCons.Node.FS.EntryProxy = MyEntryProxy + +# Slip our own RDirs() method into the Node.FS.File class so that the +# expansions of $_{CPPINC,F77INC,LIBDIR}FLAGS will have the path-name +# separators translated from what's appropriate for the system we're +# running on to what's appropriate for the example system. +orig_RDirs = SCons.Node.FS.File.RDirs +def my_RDirs(self, pathlist, orig_RDirs=orig_RDirs): + return [str(x).replace(os.sep, Sep) for x in orig_RDirs(self, pathlist)] +SCons.Node.FS.File.RDirs = my_RDirs + +class Curry(object): + def __init__(self, fun, *args, **kwargs): + self.fun = fun + self.pending = args[:] + self.kwargs = kwargs.copy() + + def __call__(self, *args, **kwargs): + if kwargs and self.kwargs: + kw = self.kwargs.copy() + kw.update(kwargs) + else: + kw = kwargs or self.kwargs + + return self.fun(*self.pending + args, **kw) + +def Str(target, source, env, cmd=""): + result = [] + for cmd in env.subst_list(cmd, target=target, source=source): + result.append(' '.join(map(str, cmd))) + return '\\n'.join(result) + +class ToolSurrogate(object): + def __init__(self, tool, variable, func, varlist): + self.tool = tool + if not isinstance(variable, list): + variable = [variable] + self.variable = variable + self.func = func + self.varlist = varlist + def __call__(self, env): + t = Tool(self.tool) + t.generate(env) + for v in self.variable: + orig = env[v] + try: + strfunction = orig.strfunction + except AttributeError: + strfunction = Curry(Str, cmd=orig) + # Don't call Action() through its global function name, because + # that leads to infinite recursion in trying to initialize the + # Default Environment. + env[v] = SCons.Action.Action(self.func, + strfunction=strfunction, + varlist=self.varlist) + def __repr__(self): + # This is for the benefit of printing the 'TOOLS' + # variable through env.Dump(). + return repr(self.tool) + +def Null(target, source, env): + pass + +def Cat(target, source, env): + target = str(target[0]) + f = open(target, "wb") + for src in map(str, source): + f.write(open(src, "rb").read()) + f.close() + +def CCCom(target, source, env): + target = str(target[0]) + fp = open(target, "wb") + def process(source_file, fp=fp): + for line in open(source_file, "rb").readlines(): + m = re.match(r'#include\s[<"]([^<"]+)[>"]', line) + if m: + include = m.group(1) + for d in [str(env.Dir('$CPPPATH')), '.']: + f = os.path.join(d, include) + if os.path.exists(f): + process(f) + break + elif line[:11] != "STRIP CCCOM": + fp.write(line) + for src in map(str, source): + process(src) + fp.write('debug = ' + ARGUMENTS.get('debug', '0') + '\\n') + fp.close() + +public_class_re = re.compile('^public class (\S+)', re.MULTILINE) + +def JavaCCom(target, source, env): + # This is a fake Java compiler that just looks for + # public class FooBar + # lines in the source file(s) and spits those out + # to .class files named after the class. + tlist = list(map(str, target)) + not_copied = {} + for t in tlist: + not_copied[t] = 1 + for src in map(str, source): + contents = open(src, "rb").read() + classes = public_class_re.findall(contents) + for c in classes: + for t in [x for x in tlist if x.find(c) != -1]: + open(t, "wb").write(contents) + del not_copied[t] + for t in not_copied.keys(): + open(t, "wb").write("\\n") + +def JavaHCom(target, source, env): + tlist = map(str, target) + slist = map(str, source) + for t, s in zip(tlist, slist): + open(t, "wb").write(open(s, "rb").read()) + +def JarCom(target, source, env): + target = str(target[0]) + class_files = [] + for src in map(str, source): + for dirpath, dirnames, filenames in os.walk(src): + class_files.extend([ os.path.join(dirpath, f) + for f in filenames if f.endswith('.class') ]) + f = open(target, "wb") + for cf in class_files: + f.write(open(cf, "rb").read()) + f.close() + +# XXX Adding COLOR, COLORS and PACKAGE to the 'cc' varlist(s) by hand +# here is bogus. It's for the benefit of doc/user/command-line.in, which +# uses examples that want to rebuild based on changes to these variables. +# It would be better to figure out a way to do it based on the content of +# the generated command-line, or else find a way to let the example markup +# language in doc/user/command-line.in tell this script what variables to +# add, but that's more difficult than I want to figure out how to do right +# now, so let's just use the simple brute force approach for the moment. + +ToolList = { + 'posix' : [('cc', ['CCCOM', 'SHCCCOM'], CCCom, ['CCFLAGS', 'CPPDEFINES', 'COLOR', 'COLORS', 'PACKAGE']), + ('link', ['LINKCOM', 'SHLINKCOM'], Cat, []), + ('ar', ['ARCOM', 'RANLIBCOM'], Cat, []), + ('tar', 'TARCOM', Null, []), + ('zip', 'ZIPCOM', Null, []), + ('BitKeeper', 'BITKEEPERCOM', Cat, []), + ('CVS', 'CVSCOM', Cat, []), + ('RCS', 'RCS_COCOM', Cat, []), + ('SCCS', 'SCCSCOM', Cat, []), + ('javac', 'JAVACCOM', JavaCCom, []), + ('javah', 'JAVAHCOM', JavaHCom, []), + ('jar', 'JARCOM', JarCom, []), + ('rmic', 'RMICCOM', Cat, []), + ], + 'win32' : [('msvc', ['CCCOM', 'SHCCCOM', 'RCCOM'], CCCom, ['CCFLAGS', 'CPPDEFINES', 'COLOR', 'COLORS', 'PACKAGE']), + ('mslink', ['LINKCOM', 'SHLINKCOM'], Cat, []), + ('mslib', 'ARCOM', Cat, []), + ('tar', 'TARCOM', Null, []), + ('zip', 'ZIPCOM', Null, []), + ('BitKeeper', 'BITKEEPERCOM', Cat, []), + ('CVS', 'CVSCOM', Cat, []), + ('RCS', 'RCS_COCOM', Cat, []), + ('SCCS', 'SCCSCOM', Cat, []), + ('javac', 'JAVACCOM', JavaCCom, []), + ('javah', 'JAVAHCOM', JavaHCom, []), + ('jar', 'JARCOM', JarCom, []), + ('rmic', 'RMICCOM', Cat, []), + ], +} + +toollist = ToolList[platform] +filter_tools = '%(tools)s'.split() +if filter_tools: + toollist = [x for x in toollist if x[0] in filter_tools] + +toollist = [ToolSurrogate(*t) for t in toollist] + +toollist.append('install') + +def surrogate_spawn(sh, escape, cmd, args, env): + pass + +def surrogate_pspawn(sh, escape, cmd, args, env, stdout, stderr): + pass + +SCons.Defaults.ConstructionEnvironment.update({ + 'PLATFORM' : platform, + 'TOOLS' : toollist, + 'SPAWN' : surrogate_spawn, + 'PSPAWN' : surrogate_pspawn, +}) + +SConscript('SConstruct') +""" + +# "Commands" that we will execute in our examples. +def command_scons(args, c, test, dict): + save_vals = {} + delete_keys = [] + try: + ce = c.environment + except AttributeError: + pass + else: + for arg in c.environment.split(): + key, val = arg.split('=') + try: + save_vals[key] = os.environ[key] + except KeyError: + delete_keys.append(key) + os.environ[key] = val + 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) + os.environ.update(save_vals) + for key in delete_keys: + del(os.environ[key]) + out = test.stdout() + out = out.replace(test.workpath('ROOT'), '') + out = out.replace(test.workpath('WORK/SConstruct'), + '/home/my/project/SConstruct') + lines = out.split('\n') + if lines: + while lines[-1] == '': + lines = lines[:-1] + # err = test.stderr() + # if err: + # sys.stderr.write(err) + return lines + +def command_touch(args, c, test, dict): + if args[0] == '-t': + t = int(time.mktime(time.strptime(args[1], '%Y%m%d%H%M'))) + times = (t, t) + args = args[2:] + else: + time.sleep(1) + times = None + for file in args: + if not os.path.isabs(file): + file = os.path.join(test.workpath('WORK'), file) + if not os.path.exists(file): + open(file, 'wb') + os.utime(file, times) + return [] + +def command_edit(args, c, test, dict): + 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: + if not os.path.isabs(file): + file = os.path.join(test.workpath('WORK'), file) + contents = open(file, 'rb').read() + open(file, 'wb').write(contents + add_string) + return [] + +def command_ls(args, c, test, dict): + def ls(a): + return [' '.join(sorted([x for x in os.listdir(a) if x[0] != '.']))] + if args: + l = [] + for a in args: + l.extend(ls(test.workpath('WORK', a))) + return l + else: + return ls(test.workpath('WORK')) + +def command_sleep(args, c, test, dict): + time.sleep(int(args[0])) + +CommandDict = { + 'scons' : command_scons, + 'touch' : command_touch, + 'edit' : command_edit, + 'ls' : command_ls, + 'sleep' : command_sleep, +} + +def ExecuteCommand(args, c, t, dict): + try: + func = CommandDict[args[0]] + except KeyError: + func = lambda args, c, t, dict: [] + return func(args[1:], c, t, dict) + + +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.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 + # Skip empty lines + while data[i] == '': + i = i + 1 + 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): + path = t.workpath('WORK', path) + dir, name = os.path.split(path) + if dir and not os.path.exists(dir): + os.makedirs(dir) + content = '\n'.join(lines) + content = content.replace('__ROOT__', t.rootpath) + path = t.workpath('WORK', path) + t.write(path, content) + if hasattr(f, 'chmod'): + 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 ". + 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+)') + + # 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: + 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 ', 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) + + +# Local Variables: +# tab-width:4 +# indent-tabs-mode:nil +# End: +# vim: set expandtab tabstop=4 shiftwidth=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 < -# -# env = Environment() -# env.Program('foo') -# -# -# int main() { printf("foo.c\n"); } -# -# -# -# The contents within the tag will get written -# into a temporary directory whenever example output needs to be -# generated. By default, the contents are not inserted into text -# directly, unless you set the "printme" attribute on one or more files, -# in which case they will get inserted within a 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 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 tag: -# -# -# env = Environment() -# env.Program('foo') -# -# -# This is essentially equivalent to , -# but it's more straightforward. -# -# SCons output is generated from the following sort of tag: -# -# -# scons -Q foo -# scons -Q foo -# -# -# You tell it which example to use with the "example" attribute, and then -# give it a list of 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 -# 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 - -sys.path.append(os.path.join(os.getcwd(), 'QMTest')) -sys.path.append(os.path.join(os.getcwd(), 'build', 'QMTest')) - -scons_py = os.path.join('bootstrap', 'src', 'script', 'scons.py') -if not os.path.exists(scons_py): - scons_py = os.path.join('src', 'script', 'scons.py') - -scons_lib_dir = os.path.join(os.getcwd(), 'bootstrap', 'src', 'engine') -if not os.path.exists(scons_lib_dir): - scons_lib_dir = os.path.join(os.getcwd(), 'src', 'engine') - -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 -# of ToolSurrogates for the tools for the appropriate platform. These -# 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. - -Stdin = """\ -import os -import re -import SCons.Action -import SCons.Defaults -import SCons.Node.FS - -platform = '%(osname)s' - -Sep = { - 'posix' : '/', - 'win32' : '\\\\', -}[platform] - - -# Slip our own __str__() method into the EntryProxy class used to expand -# $TARGET{S} and $SOURCE{S} to translate the path-name separators from -# what's appropriate for the system we're running on to what's appropriate -# for the example system. -orig = SCons.Node.FS.EntryProxy -class MyEntryProxy(orig): - def __str__(self): - return str(self._subject).replace(os.sep, Sep) -SCons.Node.FS.EntryProxy = MyEntryProxy - -# Slip our own RDirs() method into the Node.FS.File class so that the -# expansions of $_{CPPINC,F77INC,LIBDIR}FLAGS will have the path-name -# separators translated from what's appropriate for the system we're -# running on to what's appropriate for the example system. -orig_RDirs = SCons.Node.FS.File.RDirs -def my_RDirs(self, pathlist, orig_RDirs=orig_RDirs): - return [str(x).replace(os.sep, Sep) for x in orig_RDirs(self, pathlist)] -SCons.Node.FS.File.RDirs = my_RDirs - -class Curry(object): - def __init__(self, fun, *args, **kwargs): - self.fun = fun - self.pending = args[:] - self.kwargs = kwargs.copy() - - def __call__(self, *args, **kwargs): - if kwargs and self.kwargs: - kw = self.kwargs.copy() - kw.update(kwargs) - else: - kw = kwargs or self.kwargs - - return self.fun(*self.pending + args, **kw) - -def Str(target, source, env, cmd=""): - result = [] - for cmd in env.subst_list(cmd, target=target, source=source): - result.append(' '.join(map(str, cmd))) - return '\\n'.join(result) - -class ToolSurrogate(object): - def __init__(self, tool, variable, func, varlist): - self.tool = tool - if not isinstance(variable, list): - variable = [variable] - self.variable = variable - self.func = func - self.varlist = varlist - def __call__(self, env): - t = Tool(self.tool) - t.generate(env) - for v in self.variable: - orig = env[v] - try: - strfunction = orig.strfunction - except AttributeError: - strfunction = Curry(Str, cmd=orig) - # Don't call Action() through its global function name, because - # that leads to infinite recursion in trying to initialize the - # Default Environment. - env[v] = SCons.Action.Action(self.func, - strfunction=strfunction, - varlist=self.varlist) - def __repr__(self): - # This is for the benefit of printing the 'TOOLS' - # variable through env.Dump(). - return repr(self.tool) - -def Null(target, source, env): - pass - -def Cat(target, source, env): - target = str(target[0]) - f = open(target, "wb") - for src in map(str, source): - f.write(open(src, "rb").read()) - f.close() - -def CCCom(target, source, env): - target = str(target[0]) - fp = open(target, "wb") - def process(source_file, fp=fp): - for line in open(source_file, "rb").readlines(): - m = re.match(r'#include\s[<"]([^<"]+)[>"]', line) - if m: - include = m.group(1) - for d in [str(env.Dir('$CPPPATH')), '.']: - f = os.path.join(d, include) - if os.path.exists(f): - process(f) - break - elif line[:11] != "STRIP CCCOM": - fp.write(line) - for src in map(str, source): - process(src) - fp.write('debug = ' + ARGUMENTS.get('debug', '0') + '\\n') - fp.close() - -public_class_re = re.compile('^public class (\S+)', re.MULTILINE) - -def JavaCCom(target, source, env): - # This is a fake Java compiler that just looks for - # public class FooBar - # lines in the source file(s) and spits those out - # to .class files named after the class. - tlist = list(map(str, target)) - not_copied = {} - for t in tlist: - not_copied[t] = 1 - for src in map(str, source): - contents = open(src, "rb").read() - classes = public_class_re.findall(contents) - for c in classes: - for t in [x for x in tlist if x.find(c) != -1]: - open(t, "wb").write(contents) - del not_copied[t] - for t in not_copied.keys(): - open(t, "wb").write("\\n") - -def JavaHCom(target, source, env): - tlist = map(str, target) - slist = map(str, source) - for t, s in zip(tlist, slist): - open(t, "wb").write(open(s, "rb").read()) - -def JarCom(target, source, env): - target = str(target[0]) - class_files = [] - for src in map(str, source): - for dirpath, dirnames, filenames in os.walk(src): - class_files.extend([ os.path.join(dirpath, f) - for f in filenames if f.endswith('.class') ]) - f = open(target, "wb") - for cf in class_files: - f.write(open(cf, "rb").read()) - f.close() - -# XXX Adding COLOR, COLORS and PACKAGE to the 'cc' varlist(s) by hand -# here is bogus. It's for the benefit of doc/user/command-line.in, which -# uses examples that want to rebuild based on changes to these variables. -# It would be better to figure out a way to do it based on the content of -# the generated command-line, or else find a way to let the example markup -# language in doc/user/command-line.in tell this script what variables to -# add, but that's more difficult than I want to figure out how to do right -# now, so let's just use the simple brute force approach for the moment. - -ToolList = { - 'posix' : [('cc', ['CCCOM', 'SHCCCOM'], CCCom, ['CCFLAGS', 'CPPDEFINES', 'COLOR', 'COLORS', 'PACKAGE']), - ('link', ['LINKCOM', 'SHLINKCOM'], Cat, []), - ('ar', ['ARCOM', 'RANLIBCOM'], Cat, []), - ('tar', 'TARCOM', Null, []), - ('zip', 'ZIPCOM', Null, []), - ('BitKeeper', 'BITKEEPERCOM', Cat, []), - ('CVS', 'CVSCOM', Cat, []), - ('RCS', 'RCS_COCOM', Cat, []), - ('SCCS', 'SCCSCOM', Cat, []), - ('javac', 'JAVACCOM', JavaCCom, []), - ('javah', 'JAVAHCOM', JavaHCom, []), - ('jar', 'JARCOM', JarCom, []), - ('rmic', 'RMICCOM', Cat, []), - ], - 'win32' : [('msvc', ['CCCOM', 'SHCCCOM', 'RCCOM'], CCCom, ['CCFLAGS', 'CPPDEFINES', 'COLOR', 'COLORS', 'PACKAGE']), - ('mslink', ['LINKCOM', 'SHLINKCOM'], Cat, []), - ('mslib', 'ARCOM', Cat, []), - ('tar', 'TARCOM', Null, []), - ('zip', 'ZIPCOM', Null, []), - ('BitKeeper', 'BITKEEPERCOM', Cat, []), - ('CVS', 'CVSCOM', Cat, []), - ('RCS', 'RCS_COCOM', Cat, []), - ('SCCS', 'SCCSCOM', Cat, []), - ('javac', 'JAVACCOM', JavaCCom, []), - ('javah', 'JAVAHCOM', JavaHCom, []), - ('jar', 'JARCOM', JarCom, []), - ('rmic', 'RMICCOM', Cat, []), - ], -} - -toollist = ToolList[platform] -filter_tools = '%(tools)s'.split() -if filter_tools: - toollist = [x for x in toollist if x[0] in filter_tools] - -toollist = [ToolSurrogate(*t) for t in toollist] - -toollist.append('install') - -def surrogate_spawn(sh, escape, cmd, args, env): - pass - -def surrogate_pspawn(sh, escape, cmd, args, env, stdout, stderr): - pass - -SCons.Defaults.ConstructionEnvironment.update({ - 'PLATFORM' : platform, - 'TOOLS' : toollist, - 'SPAWN' : surrogate_spawn, - 'PSPAWN' : surrogate_pspawn, -}) - -SConscript('SConstruct') -""" - -# "Commands" that we will execute in our examples. -def command_scons(args, c, test, dict): - save_vals = {} - delete_keys = [] - try: - ce = c.environment - except AttributeError: - pass - else: - for arg in c.environment.split(): - key, val = arg.split('=') - try: - save_vals[key] = os.environ[key] - except KeyError: - delete_keys.append(key) - os.environ[key] = val - 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) - os.environ.update(save_vals) - for key in delete_keys: - del(os.environ[key]) - out = test.stdout() - out = out.replace(test.workpath('ROOT'), '') - out = out.replace(test.workpath('WORK/SConstruct'), - '/home/my/project/SConstruct') - lines = out.split('\n') - if lines: - while lines[-1] == '': - lines = lines[:-1] - #err = test.stderr() - #if err: - # sys.stderr.write(err) - return lines - -def command_touch(args, c, test, dict): - if args[0] == '-t': - t = int(time.mktime(time.strptime(args[1], '%Y%m%d%H%M'))) - times = (t, t) - args = args[2:] - else: - time.sleep(1) - times = None - for file in args: - if not os.path.isabs(file): - file = os.path.join(test.workpath('WORK'), file) - if not os.path.exists(file): - open(file, 'wb') - os.utime(file, times) - return [] - -def command_edit(args, c, test, dict): - try: - add_string = c.edit[:] - except AttributeError: - add_string = 'void edit(void) { ; }\n' - if add_string[-1] != '\n': - add_string = add_string + '\n' - for file in args: - if not os.path.isabs(file): - file = os.path.join(test.workpath('WORK'), file) - contents = open(file, 'rb').read() - open(file, 'wb').write(contents + add_string) - return [] - -def command_ls(args, c, test, dict): - def ls(a): - return [' '.join(sorted([x for x in os.listdir(a) if x[0] != '.']))] - if args: - l = [] - for a in args: - l.extend(ls(test.workpath('WORK', a))) - return l - else: - return ls(test.workpath('WORK')) - -def command_sleep(args, c, test, dict): - time.sleep(int(args[0])) - -CommandDict = { - 'scons' : command_scons, - 'touch' : command_touch, - 'edit' : command_edit, - 'ls' : command_ls, - 'sleep' : command_sleep, -} - -def ExecuteCommand(args, c, t, dict): - try: - func = CommandDict[args[0]] - except KeyError: - 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('') - - def handle_decl(self, data): - self.outfp.write('') - - 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('') - - 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('') - 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 + '') - delattr(self, 'e') - self.afunclist = self.afunclist[:-1] - - def start_file(self, attrs): - try: - e = self.e - except AttributeError: - self.error(" tag outside of ") - t = [t for t in attrs if t[0] == 'name'] - if not t: - self.error("no 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(" tag outside of ") - t = [t for t in attrs if t[0] == 'name'] - if not t: - self.error("no 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 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 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('') - self.outfp.write(f.data + '') - 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 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 - 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: - dir = t.workpath('WORK', d.name) - if not os.path.exists(dir): - os.makedirs(dir) - - for f in e.files: - i = 0 - while f.data[i] == '\n': - i = i + 1 - lines = f.data[i:].split('\n') - i = 0 - while lines[0][i] == ' ': - i = i + 1 - lines = [l[i:] for l in lines] - path = f.name.replace('__ROOT__', t.rootpath) - if not os.path.isabs(path): - path = t.workpath('WORK', path) - dir, name = os.path.split(path) - if dir and not os.path.exists(dir): - os.makedirs(dir) - content = '\n'.join(lines) - content = content.replace('__ROOT__', t.rootpath) - 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('' + o.prefix[:i]) - p = o.prefix[i:] - - # 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 ". - 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('' + d + '\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 ', 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 + '') - delattr(self, 'o') - self.afunclist = self.afunclist[:-1] - - def start_scons_output_command(self, attrs): - try: - o = self.o - except AttributeError: - self.error(" tag outside of ") - 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('') - output = self.for_display(f.data) - self.outfp.write(output + '') - 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_postamble = """\ - -""" - -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 = """\