Fix XML in documentation, and in the bin/scons-doc.py script that generates
[scons.git] / bin / scons-doc.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2010 The SCons Foundation
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining
6 # a copy of this software and associated documentation files (the
7 # "Software"), to deal in the Software without restriction, including
8 # without limitation the rights to use, copy, modify, merge, publish,
9 # distribute, sublicense, and/or sell copies of the Software, and to
10 # permit persons to whom the Software is furnished to do so, subject to
11 # the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included
14 # in all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
17 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
18 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
24 #
25 # scons-doc.py -    an SGML preprocessor for capturing SCons output
26 #                   and inserting it into examples in our DocBook
27 #                   documentation
28 #
29 # This script looks for some SGML tags that describe SCons example
30 # configurations and commands to execute in those configurations, and
31 # uses TestCmd.py to execute the commands and insert the output from
32 # those commands into the SGML that we output.  This way, we can run a
33 # script and update all of our example documentation output without
34 # a lot of laborious by-hand checking.
35 #
36 # An "SCons example" looks like this, and essentially describes a set of
37 # input files (program source files as well as SConscript files):
38 #
39 #       <scons_example name="ex1">
40 #         <file name="SConstruct" printme="1">
41 #           env = Environment()
42 #           env.Program('foo')
43 #         </file>
44 #         <file name="foo.c">
45 #           int main() { printf("foo.c\n"); }
46 #         </file>
47 #       </scons_example>
48 #
49 # The <file> contents within the <scons_example> tag will get written
50 # into a temporary directory whenever example output needs to be
51 # generated.  By default, the <file> contents are not inserted into text
52 # directly, unless you set the "printme" attribute on one or more files,
53 # in which case they will get inserted within a <programlisting> tag.
54 # This makes it easy to define the example at the appropriate
55 # point in the text where you intend to show the SConstruct file.
56 #
57 # Note that you should usually give the <scons_example> a "name"
58 # attribute so that you can refer to the example configuration later to
59 # run SCons and generate output.
60 #
61 # If you just want to show a file's contents without worry about running
62 # SCons, there's a shorter <sconstruct> tag:
63 #
64 #       <sconstruct>
65 #         env = Environment()
66 #         env.Program('foo')
67 #       </sconstruct>
68 #
69 # This is essentially equivalent to <scons_example><file printme="1">,
70 # but it's more straightforward.
71 #
72 # SCons output is generated from the following sort of tag:
73 #
74 #       <scons_output example="ex1" os="posix">
75 #         <scons_output_command>scons -Q foo</scons_output_command>
76 #         <scons_output_command>scons -Q foo</scons_output_command>
77 #       </scons_output>
78 #
79 # You tell it which example to use with the "example" attribute, and then
80 # give it a list of <scons_output_command> tags to execute.  You can also
81 # supply an "os" tag, which specifies the type of operating system this
82 # example is intended to show; if you omit this, default value is "posix".
83 #
84 # The generated SGML will show the command line (with the appropriate
85 # command-line prompt for the operating system), execute the command in
86 # a temporary directory with the example files, capture the standard
87 # output from SCons, and insert it into the text as appropriate.
88 # Error output gets passed through to your error output so you
89 # can see if there are any problems executing the command.
90 #
91 from __future__ import generators  ### KEEP FOR COMPATIBILITY FIXERS
92
93 import optparse
94 import os
95 import re
96 import sgmllib
97 import sys
98 import time
99
100 sys.path.append(os.path.join(os.getcwd(), 'QMTest'))
101 sys.path.append(os.path.join(os.getcwd(), 'build', 'QMTest'))
102
103 scons_py = os.path.join('bootstrap', 'src', 'script', 'scons.py')
104 if not os.path.exists(scons_py):
105     scons_py = os.path.join('src', 'script', 'scons.py')
106
107 scons_lib_dir = os.path.join(os.getcwd(), 'bootstrap', 'src', 'engine')
108 if not os.path.exists(scons_lib_dir):
109     scons_lib_dir = os.path.join(os.getcwd(), 'src', 'engine')
110
111 os.environ['SCONS_LIB_DIR'] = scons_lib_dir
112
113 import TestCmd
114
115 # The regular expression that identifies entity references in the
116 # standard sgmllib omits the underscore from the legal characters.
117 # Override it with our own regular expression that adds underscore.
118 sgmllib.entityref = re.compile('&([a-zA-Z][-_.a-zA-Z0-9]*)[^-_a-zA-Z0-9]')
119
120 # Classes for collecting different types of data we're interested in.
121 class DataCollector:
122     """Generic class for collecting data between a start tag and end
123     tag.  We subclass for various types of tags we care about."""
124     def __init__(self):
125         self.data = ""
126     def afunc(self, data):
127         self.data = self.data + data
128
129 class Example(DataCollector):
130     """An SCons example.  This is essentially a list of files that
131     will get written to a temporary directory to collect output
132     from one or more SCons runs."""
133     def __init__(self):
134         DataCollector.__init__(self)
135         self.files = []
136         self.dirs = []
137
138 class File(DataCollector):
139     """A file, that will get written out to a temporary directory
140     for one or more SCons runs."""
141     def __init__(self, name):
142         DataCollector.__init__(self)
143         self.name = name
144
145 class Directory(DataCollector):
146     """A directory, that will get created in a temporary directory
147     for one or more SCons runs."""
148     def __init__(self, name):
149         DataCollector.__init__(self)
150         self.name = name
151
152 class Output(DataCollector):
153     """Where the command output goes.  This is essentially
154     a list of commands that will get executed."""
155     def __init__(self):
156         DataCollector.__init__(self)
157         self.commandlist = []
158
159 class Command(DataCollector):
160     """A tag for where the command output goes.  This is essentially
161     a list of commands that will get executed."""
162     def __init__(self):
163         DataCollector.__init__(self)
164         self.output = None
165
166 Prompt = {
167     'posix' : '% ',
168     'win32' : 'C:\\>'
169 }
170
171 # The magick SCons hackery that makes this work.
172 #
173 # So that our examples can still use the default SConstruct file, we
174 # actually feed the following into SCons via stdin and then have it
175 # SConscript() the SConstruct file.  This stdin wrapper creates a set
176 # of ToolSurrogates for the tools for the appropriate platform.  These
177 # Surrogates print output like the real tools and behave like them
178 # without actually having to be on the right platform or have the right
179 # tool installed.
180 #
181 # The upshot:  The wrapper transparently changes the world out from
182 # under the top-level SConstruct file in an example just so we can get
183 # the command output.
184
185 Stdin = """\
186 import os
187 import re
188 import SCons.Action
189 import SCons.Defaults
190 import SCons.Node.FS
191
192 platform = '%(osname)s'
193
194 Sep = {
195     'posix' : '/',
196     'win32' : '\\\\',
197 }[platform]
198
199
200 #  Slip our own __str__() method into the EntryProxy class used to expand
201 #  $TARGET{S} and $SOURCE{S} to translate the path-name separators from
202 #  what's appropriate for the system we're running on to what's appropriate
203 #  for the example system.
204 orig = SCons.Node.FS.EntryProxy
205 class MyEntryProxy(orig):
206     def __str__(self):
207         return str(self._Proxy__subject).replace(os.sep, Sep)
208 SCons.Node.FS.EntryProxy = MyEntryProxy
209
210 # Slip our own RDirs() method into the Node.FS.File class so that the
211 # expansions of $_{CPPINC,F77INC,LIBDIR}FLAGS will have the path-name
212 # separators translated from what's appropriate for the system we're
213 # running on to what's appropriate for the example system.
214 orig_RDirs = SCons.Node.FS.File.RDirs
215 def my_RDirs(self, pathlist, orig_RDirs=orig_RDirs):
216     return [str(x).replace(os.sep, Sep) for x in orig_RDirs(self, pathlist)]
217 SCons.Node.FS.File.RDirs = my_RDirs
218
219 class Curry:
220     def __init__(self, fun, *args, **kwargs):
221         self.fun = fun
222         self.pending = args[:]
223         self.kwargs = kwargs.copy()
224
225     def __call__(self, *args, **kwargs):
226         if kwargs and self.kwargs:
227             kw = self.kwargs.copy()
228             kw.update(kwargs)
229         else:
230             kw = kwargs or self.kwargs
231
232         return self.fun(*self.pending + args, **kw)
233
234 def Str(target, source, env, cmd=""):
235     result = []
236     for cmd in env.subst_list(cmd, target=target, source=source):
237         result.append(' '.join(map(str, cmd)))
238     return '\\n'.join(result)
239
240 class ToolSurrogate:
241     def __init__(self, tool, variable, func, varlist):
242         self.tool = tool
243         if not isinstance(variable, list):
244             variable = [variable]
245         self.variable = variable
246         self.func = func
247         self.varlist = varlist
248     def __call__(self, env):
249         t = Tool(self.tool)
250         t.generate(env)
251         for v in self.variable:
252             orig = env[v]
253             try:
254                 strfunction = orig.strfunction
255             except AttributeError:
256                 strfunction = Curry(Str, cmd=orig)
257             # Don't call Action() through its global function name, because
258             # that leads to infinite recursion in trying to initialize the
259             # Default Environment.
260             env[v] = SCons.Action.Action(self.func,
261                                          strfunction=strfunction,
262                                          varlist=self.varlist)
263     def __repr__(self):
264         # This is for the benefit of printing the 'TOOLS'
265         # variable through env.Dump().
266         return repr(self.tool)
267
268 def Null(target, source, env):
269     pass
270
271 def Cat(target, source, env):
272     target = str(target[0])
273     f = open(target, "wb")
274     for src in map(str, source):
275         f.write(open(src, "rb").read())
276     f.close()
277
278 def CCCom(target, source, env):
279     target = str(target[0])
280     fp = open(target, "wb")
281     def process(source_file, fp=fp):
282         for line in open(source_file, "rb").readlines():
283             m = re.match(r'#include\s[<"]([^<"]+)[>"]', line)
284             if m:
285                 include = m.group(1)
286                 for d in [str(env.Dir('$CPPPATH')), '.']:
287                     f = os.path.join(d, include)
288                     if os.path.exists(f):
289                         process(f)
290                         break
291             elif line[:11] != "STRIP CCCOM":
292                 fp.write(line)
293     for src in map(str, source):
294         process(src)
295         fp.write('debug = ' + ARGUMENTS.get('debug', '0') + '\\n')
296     fp.close()
297
298 public_class_re = re.compile('^public class (\S+)', re.MULTILINE)
299
300 def JavaCCom(target, source, env):
301     # This is a fake Java compiler that just looks for
302     #   public class FooBar
303     # lines in the source file(s) and spits those out
304     # to .class files named after the class.
305     tlist = list(map(str, target))
306     not_copied = {}
307     for t in tlist:
308        not_copied[t] = 1
309     for src in map(str, source):
310         contents = open(src, "rb").read()
311         classes = public_class_re.findall(contents)
312         for c in classes:
313             for t in [x for x in tlist if x.find(c) != -1]:
314                 open(t, "wb").write(contents)
315                 del not_copied[t]
316     for t in not_copied.keys():
317         open(t, "wb").write("\\n")
318
319 def JavaHCom(target, source, env):
320     tlist = map(str, target)
321     slist = map(str, source)
322     for t, s in zip(tlist, slist):
323         open(t, "wb").write(open(s, "rb").read())
324
325 def find_class_files(arg, dirname, names):
326     class_files = filter(lambda n: n[-6:] == '.class', names)
327     paths = map(lambda n: os.path.join(dirname, n), class_files)
328     arg.extend(paths)
329
330 def JarCom(target, source, env):
331     target = str(target[0])
332     class_files = []
333     for src in map(str, source):
334         os.path.walk(src, find_class_files, class_files)
335     f = open(target, "wb")
336     for cf in class_files:
337         f.write(open(cf, "rb").read())
338     f.close()
339
340 # XXX Adding COLOR, COLORS and PACKAGE to the 'cc' varlist(s) by hand
341 # here is bogus.  It's for the benefit of doc/user/command-line.in, which
342 # uses examples that want  to rebuild based on changes to these variables.
343 # It would be better to figure out a way to do it based on the content of
344 # the generated command-line, or else find a way to let the example markup
345 # language in doc/user/command-line.in tell this script what variables to
346 # add, but that's more difficult than I want to figure out how to do right
347 # now, so let's just use the simple brute force approach for the moment.
348
349 ToolList = {
350     'posix' :   [('cc', ['CCCOM', 'SHCCCOM'], CCCom, ['CCFLAGS', 'CPPDEFINES', 'COLOR', 'COLORS', 'PACKAGE']),
351                  ('link', ['LINKCOM', 'SHLINKCOM'], Cat, []),
352                  ('ar', ['ARCOM', 'RANLIBCOM'], Cat, []),
353                  ('tar', 'TARCOM', Null, []),
354                  ('zip', 'ZIPCOM', Null, []),
355                  ('BitKeeper', 'BITKEEPERCOM', Cat, []),
356                  ('CVS', 'CVSCOM', Cat, []),
357                  ('RCS', 'RCS_COCOM', Cat, []),
358                  ('SCCS', 'SCCSCOM', Cat, []),
359                  ('javac', 'JAVACCOM', JavaCCom, []),
360                  ('javah', 'JAVAHCOM', JavaHCom, []),
361                  ('jar', 'JARCOM', JarCom, []),
362                  ('rmic', 'RMICCOM', Cat, []),
363                 ],
364     'win32' :   [('msvc', ['CCCOM', 'SHCCCOM', 'RCCOM'], CCCom, ['CCFLAGS', 'CPPDEFINES', 'COLOR', 'COLORS', 'PACKAGE']),
365                  ('mslink', ['LINKCOM', 'SHLINKCOM'], Cat, []),
366                  ('mslib', 'ARCOM', Cat, []),
367                  ('tar', 'TARCOM', Null, []),
368                  ('zip', 'ZIPCOM', Null, []),
369                  ('BitKeeper', 'BITKEEPERCOM', Cat, []),
370                  ('CVS', 'CVSCOM', Cat, []),
371                  ('RCS', 'RCS_COCOM', Cat, []),
372                  ('SCCS', 'SCCSCOM', Cat, []),
373                  ('javac', 'JAVACCOM', JavaCCom, []),
374                  ('javah', 'JAVAHCOM', JavaHCom, []),
375                  ('jar', 'JARCOM', JarCom, []),
376                  ('rmic', 'RMICCOM', Cat, []),
377                 ],
378 }
379
380 toollist = ToolList[platform]
381 filter_tools = '%(tools)s'.split()
382 if filter_tools:
383     toollist = [x for x in toollist if x[0] in filter_tools]
384
385 toollist = [ToolSurrogate(*t) for t in toollist]
386
387 toollist.append('install')
388
389 def surrogate_spawn(sh, escape, cmd, args, env):
390     pass
391
392 def surrogate_pspawn(sh, escape, cmd, args, env, stdout, stderr):
393     pass
394
395 SCons.Defaults.ConstructionEnvironment.update({
396     'PLATFORM' : platform,
397     'TOOLS'    : toollist,
398     'SPAWN'    : surrogate_spawn,
399     'PSPAWN'   : surrogate_pspawn,
400 })
401
402 SConscript('SConstruct')
403 """
404
405 # "Commands" that we will execute in our examples.
406 def command_scons(args, c, test, dict):
407     save_vals = {}
408     delete_keys = []
409     try:
410         ce = c.environment
411     except AttributeError:
412         pass
413     else:
414         for arg in c.environment.split():
415             key, val = arg.split('=')
416             try:
417                 save_vals[key] = os.environ[key]
418             except KeyError:
419                 delete_keys.append(key)
420             os.environ[key] = val
421     test.run(interpreter = sys.executable,
422              program = scons_py,
423              # We use ToolSurrogates to capture win32 output by "building"
424              # examples using a fake win32 tool chain.  Suppress the
425              # warnings that come from the new revamped VS support so
426              # we can build doc on (Linux) systems that don't have
427              # Visual C installed.
428              arguments = '--warn=no-visual-c-missing -f - ' + ' '.join(args),
429              chdir = test.workpath('WORK'),
430              stdin = Stdin % dict)
431     os.environ.update(save_vals)
432     for key in delete_keys:
433         del(os.environ[key])
434     out = test.stdout()
435     out = out.replace(test.workpath('ROOT'), '')
436     out = out.replace(test.workpath('WORK/SConstruct'),
437                               '/home/my/project/SConstruct')
438     lines = out.split('\n')
439     if lines:
440         while lines[-1] == '':
441             lines = lines[:-1]
442     #err = test.stderr()
443     #if err:
444     #    sys.stderr.write(err)
445     return lines
446
447 def command_touch(args, c, test, dict):
448     if args[0] == '-t':
449         t = int(time.mktime(time.strptime(args[1], '%Y%m%d%H%M')))
450         times = (t, t)
451         args = args[2:]
452     else:
453         time.sleep(1)
454         times = None
455     for file in args:
456         if not os.path.isabs(file):
457             file = os.path.join(test.workpath('WORK'), file)
458         if not os.path.exists(file):
459             open(file, 'wb')
460         os.utime(file, times)
461     return []
462
463 def command_edit(args, c, test, dict):
464     try:
465         add_string = c.edit[:]
466     except AttributeError:
467         add_string = 'void edit(void) { ; }\n'
468     if add_string[-1] != '\n':
469         add_string = add_string + '\n'
470     for file in args:
471         if not os.path.isabs(file):
472             file = os.path.join(test.workpath('WORK'), file)
473         contents = open(file, 'rb').read()
474         open(file, 'wb').write(contents + add_string)
475     return []
476
477 def command_ls(args, c, test, dict):
478     def ls(a):
479         return ['  '.join(sorted([x for x in os.listdir(a) if x[0] != '.']))]
480     if args:
481         l = []
482         for a in args:
483             l.extend(ls(test.workpath('WORK', a)))
484         return l
485     else:
486         return ls(test.workpath('WORK'))
487
488 def command_sleep(args, c, test, dict):
489     time.sleep(int(args[0]))
490
491 CommandDict = {
492     'scons' : command_scons,
493     'touch' : command_touch,
494     'edit'  : command_edit,
495     'ls'    : command_ls,
496     'sleep' : command_sleep,
497 }
498
499 def ExecuteCommand(args, c, t, dict):
500     try:
501         func = CommandDict[args[0]]
502     except KeyError:
503         func = lambda args, c, t, dict: []
504     return func(args[1:], c, t, dict)
505
506 class MySGML(sgmllib.SGMLParser):
507     """A subclass of the standard Python 2.2 sgmllib SGML parser.
508
509     This extends the standard sgmllib parser to recognize, and do cool
510     stuff with, the added tags that describe our SCons examples,
511     commands, and other stuff.
512
513     Note that this doesn't work with the 1.5.2 sgmllib module, because
514     that didn't have the ability to work with ENTITY declarations.
515     """
516     def __init__(self, outfp):
517         sgmllib.SGMLParser.__init__(self)
518         self.examples = {}
519         self.afunclist = []
520         self.outfp = outfp
521
522     # The first set of methods here essentially implement pass-through
523     # handling of most of the stuff in an SGML file.  We're really
524     # only concerned with the tags specific to SCons example processing,
525     # the methods for which get defined below.
526
527     def handle_data(self, data):
528         try:
529             f = self.afunclist[-1]
530         except IndexError:
531             self.outfp.write(data)
532         else:
533             f(data)
534
535     def handle_comment(self, data):
536         self.outfp.write('<!--' + data + '-->')
537
538     def handle_decl(self, data):
539         self.outfp.write('<!' + data + '>')
540
541     def unknown_starttag(self, tag, attrs):
542         try:
543             f = self.example.afunc
544         except AttributeError:
545             f = self.outfp.write
546         if not attrs:
547             f('<' + tag + '>')
548         else:
549             f('<' + tag)
550             for name, value in attrs:
551                 f(' ' + name + '=' + '"' + value + '"')
552             f('>')
553
554     def unknown_endtag(self, tag):
555         self.outfp.write('</' + tag + '>')
556
557     def unknown_entityref(self, ref):
558         self.outfp.write('&' + ref + ';')
559
560     def unknown_charref(self, ref):
561         self.outfp.write('&#' + ref + ';')
562
563     # Here is where the heavy lifting begins.  The following methods
564     # handle the begin-end tags of our SCons examples.
565
566     def for_display(self, contents):
567         contents = contents.replace('__ROOT__', '')
568         contents = contents.replace('<', '&lt;')
569         contents = contents.replace('>', '&gt;')
570         return contents
571
572     def start_scons_example(self, attrs):
573         t = [t for t in attrs if t[0] == 'name']
574         if t:
575             name = t[0][1]
576             try:
577                e = self.examples[name]
578             except KeyError:
579                e = self.examples[name] = Example()
580         else:
581             e = Example()
582         for name, value in attrs:
583             setattr(e, name, value)
584         self.e = e
585         self.afunclist.append(e.afunc)
586
587     def end_scons_example(self):
588         e = self.e
589         files = [f for f in e.files if f.printme]
590         if files:
591             self.outfp.write('<programlisting>')
592             for f in files:
593                 if f.printme:
594                     i = len(f.data) - 1
595                     while f.data[i] == ' ':
596                         i = i - 1
597                     output = self.for_display(f.data[:i+1])
598                     self.outfp.write(output)
599             if e.data and e.data[0] == '\n':
600                 e.data = e.data[1:]
601             self.outfp.write(e.data + '</programlisting>')
602         delattr(self, 'e')
603         self.afunclist = self.afunclist[:-1]
604
605     def start_file(self, attrs):
606         try:
607             e = self.e
608         except AttributeError:
609             self.error("<file> tag outside of <scons_example>")
610         t = [t for t in attrs if t[0] == 'name']
611         if not t:
612             self.error("no <file> name attribute found")
613         try:
614             e.prefix
615         except AttributeError:
616             e.prefix = e.data
617             e.data = ""
618         f = File(t[0][1])
619         f.printme = None
620         for name, value in attrs:
621             setattr(f, name, value)
622         e.files.append(f)
623         self.afunclist.append(f.afunc)
624
625     def end_file(self):
626         self.e.data = ""
627         self.afunclist = self.afunclist[:-1]
628
629     def start_directory(self, attrs):
630         try:
631             e = self.e
632         except AttributeError:
633             self.error("<directory> tag outside of <scons_example>")
634         t = [t for t in attrs if t[0] == 'name']
635         if not t:
636             self.error("no <directory> name attribute found")
637         try:
638             e.prefix
639         except AttributeError:
640             e.prefix = e.data
641             e.data = ""
642         d = Directory(t[0][1])
643         for name, value in attrs:
644             setattr(d, name, value)
645         e.dirs.append(d)
646         self.afunclist.append(d.afunc)
647
648     def end_directory(self):
649         self.e.data = ""
650         self.afunclist = self.afunclist[:-1]
651
652     def start_scons_example_file(self, attrs):
653         t = [t for t in attrs if t[0] == 'example']
654         if not t:
655             self.error("no <scons_example_file> example attribute found")
656         exname = t[0][1]
657         try:
658             e = self.examples[exname]
659         except KeyError:
660             self.error("unknown example name '%s'" % exname)
661         fattrs = [t for t in attrs if t[0] == 'name']
662         if not fattrs:
663             self.error("no <scons_example_file> name attribute found")
664         fname = fattrs[0][1]
665         f = [f for f in e.files if f.name == fname]
666         if not f:
667             self.error("example '%s' does not have a file named '%s'" % (exname, fname))
668         self.f = f[0]
669
670     def end_scons_example_file(self):
671         f = self.f
672         self.outfp.write('<programlisting>')
673         self.outfp.write(f.data + '</programlisting>')
674         delattr(self, 'f')
675
676     def start_scons_output(self, attrs):
677         t = [t for t in attrs if t[0] == 'example']
678         if not t:
679             self.error("no <scons_output> example attribute found")
680         exname = t[0][1]
681         try:
682             e = self.examples[exname]
683         except KeyError:
684             self.error("unknown example name '%s'" % exname)
685         # Default values for an example.
686         o = Output()
687         o.preserve = None
688         o.os = 'posix'
689         o.tools = ''
690         o.e = e
691         # Locally-set.
692         for name, value in attrs:
693             setattr(o, name, value)
694         self.o = o
695         self.afunclist.append(o.afunc)
696
697     def end_scons_output(self):
698         # The real raison d'etre for this script, this is where we
699         # actually execute SCons to fetch the output.
700         o = self.o
701         e = o.e
702         t = TestCmd.TestCmd(workdir='', combine=1)
703         if o.preserve:
704             t.preserve()
705         t.subdir('ROOT', 'WORK')
706         t.rootpath = t.workpath('ROOT').replace('\\', '\\\\')
707
708         for d in e.dirs:
709             dir = t.workpath('WORK', d.name)
710             if not os.path.exists(dir):
711                 os.makedirs(dir)
712
713         for f in e.files:
714             i = 0
715             while f.data[i] == '\n':
716                 i = i + 1
717             lines = f.data[i:].split('\n')
718             i = 0
719             while lines[0][i] == ' ':
720                 i = i + 1
721             lines = [l[i:] for l in lines]
722             path = f.name.replace('__ROOT__', t.rootpath)
723             if not os.path.isabs(path):
724                 path = t.workpath('WORK', path)
725             dir, name = os.path.split(path)
726             if dir and not os.path.exists(dir):
727                 os.makedirs(dir)
728             content = '\n'.join(lines)
729             content = content.replace('__ROOT__', t.rootpath)
730             path = t.workpath('WORK', path)
731             t.write(path, content)
732             if hasattr(f, 'chmod'):
733                 os.chmod(path, int(f.chmod, 0))
734
735         i = len(o.prefix)
736         while o.prefix[i-1] != '\n':
737             i = i - 1
738
739         self.outfp.write('<screen>' + o.prefix[:i])
740         p = o.prefix[i:]
741
742         # Regular expressions for making the doc output consistent,
743         # regardless of reported addresses or Python version.
744
745         # Massage addresses in object repr strings to a constant.
746         address_re = re.compile(r' at 0x[0-9a-fA-F]*\>')
747
748         # Massage file names in stack traces (sometimes reported as absolute
749         # paths) to a consistent relative path.
750         engine_re = re.compile(r' File ".*/src/engine/SCons/')
751
752         # Python 2.5 changed the stack trace when the module is read
753         # from standard input from read "... line 7, in ?" to
754         # "... line 7, in <module>".
755         file_re = re.compile(r'^( *File ".*", line \d+, in) \?$', re.M)
756
757         # Python 2.6 made UserList a new-style class, which changes the
758         # AttributeError message generated by our NodeList subclass.
759         nodelist_re = re.compile(r'(AttributeError:) NodeList instance (has no attribute \S+)')
760
761         for c in o.commandlist:
762             self.outfp.write(p + Prompt[o.os])
763             d = c.data.replace('__ROOT__', '')
764             self.outfp.write('<userinput>' + d + '</userinput>\n')
765
766             e = c.data.replace('__ROOT__', t.workpath('ROOT'))
767             args = e.split()
768             lines = ExecuteCommand(args, c, t, {'osname':o.os, 'tools':o.tools})
769             content = None
770             if c.output:
771                 content = c.output
772             elif lines:
773                 content = ( '\n' + p).join(lines)
774             if content:
775                 content = address_re.sub(r' at 0x700000&gt;', content)
776                 content = engine_re.sub(r' File "bootstrap/src/engine/SCons/', content)
777                 content = file_re.sub(r'\1 <module>', content)
778                 content = nodelist_re.sub(r"\1 'NodeList' object \2", content)
779                 content = self.for_display(content)
780                 self.outfp.write(p + content + '\n')
781
782         if o.data[0] == '\n':
783             o.data = o.data[1:]
784         self.outfp.write(o.data + '</screen>')
785         delattr(self, 'o')
786         self.afunclist = self.afunclist[:-1]
787
788     def start_scons_output_command(self, attrs):
789         try:
790             o = self.o
791         except AttributeError:
792             self.error("<scons_output_command> tag outside of <scons_output>")
793         try:
794             o.prefix
795         except AttributeError:
796             o.prefix = o.data
797             o.data = ""
798         c = Command()
799         for name, value in attrs:
800             setattr(c, name, value)
801         o.commandlist.append(c)
802         self.afunclist.append(c.afunc)
803
804     def end_scons_output_command(self):
805         self.o.data = ""
806         self.afunclist = self.afunclist[:-1]
807
808     def start_sconstruct(self, attrs):
809         f = File('')
810         self.f = f
811         self.afunclist.append(f.afunc)
812
813     def end_sconstruct(self):
814         f = self.f
815         self.outfp.write('<programlisting>')
816         output = self.for_display(f.data)
817         self.outfp.write(output + '</programlisting>')
818         delattr(self, 'f')
819         self.afunclist = self.afunclist[:-1]
820
821 def process(filename):
822     if filename == '-':
823         f = sys.stdin
824     else:
825         try:
826             f = open(filename, 'r')
827         except EnvironmentError, e:
828             sys.stderr.write('%s: %s\n' % (filename, msg))
829             return 1
830
831     data = f.read()
832     if f is not sys.stdin:
833         f.close()
834
835     if data.startswith('<?xml '):
836         first_line, data = data.split('\n', 1)
837         sys.stdout.write(first_line + '\n')
838
839     x = MySGML(sys.stdout)
840     for c in data:
841         x.feed(c)
842     x.close()
843
844     return 0
845
846 def main(argv=None):
847     if argv is None:
848         argv = sys.argv
849
850     parser = optparse.OptionParser()
851     opts, args = parser.parse_args(argv[1:])
852
853     if not args:
854         args = ['-']
855
856     for arg in args:
857         process(arg)
858
859 if __name__ == "__main__":
860     sys.exit(main())
861
862 # Local Variables:
863 # tab-width:4
864 # indent-tabs-mode:nil
865 # End:
866 # vim: set expandtab tabstop=4 shiftwidth=4: