Issue 1984: Documentation for ParseDepends
[scons.git] / doc / SConscript
1 #
2 # SConscript file for building SCons documentation.
3 #
4
5 #
6 # __COPYRIGHT__
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining
9 # a copy of this software and associated documentation files (the
10 # "Software"), to deal in the Software without restriction, including
11 # without limitation the rights to use, copy, modify, merge, publish,
12 # distribute, sublicense, and/or sell copies of the Software, and to
13 # permit persons to whom the Software is furnished to do so, subject to
14 # the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be included
17 # in all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
20 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
21 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
23 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 #
27
28 import os.path
29 import re
30 import string
31
32 Import('build_dir', 'env', 'whereis')
33
34 env = env.Clone()
35
36 build = os.path.join(build_dir, 'doc')
37
38 #
39 #
40 #
41 dist_doc_tar_gz = '$DISTDIR/scons-doc-${VERSION}.tar.gz'
42
43 #
44 # We'll only try to build text files (for some documents)
45 # if lynx is available to do the dump.
46 #
47 fig2dev = whereis('fig2dev')
48 epydoc = whereis('epydoc')
49 groff = whereis('groff')
50 lynx = whereis('lynx')
51 man2html = whereis('man2html')
52 jade = whereis('openjade') or whereis('jade')
53 jadetex = whereis('jadetex')
54 pdfjadetex = whereis('pdfjadetex')
55 jw = whereis('jw')
56 tidy = whereis('tidy')
57
58 tar_deps = []
59 tar_list = []
60
61 entity_re = re.compile(r'<!entity\s+(?:%\s+)?(?:\S+)\s+SYSTEM\s+"([^"]*)">', re.I)
62 format_re = re.compile(r'<(?:graphic|imagedata)\s+fileref="([^"]*)"(?:\s+format="([^"]*)")?')
63
64 #
65 # Find internal dependencies in .xml files:
66 #
67 #   <!entity bground SYSTEM "bground.xml">
68 #   <graphic fileref="file.jpg">
69 #   <imagedata fileref="file.jpg">
70 #
71 # This only finds one per line, and assumes that anything
72 # defined as a SYSTEM entity is, in fact, a file included
73 # somewhere in the document.
74 #
75 def scanxml(node, env, target):
76     includes = []
77
78     contents = node.get_contents()
79
80     includes.extend(entity_re.findall(contents))
81
82     matches = format_re.findall(contents)
83     for m in matches:
84         file, format = m
85         if format and file[-len(format):] != format:
86             file = file + '.' + format
87         if not os.path.isabs(file):
88             a = []
89             f = file
90             while f:
91                 f, tail = os.path.split(f)
92                 if tail == 'doc':
93                     break
94                 a = [tail] + a
95             file = apply(os.path.join, a, {})
96         includes.append(file)
97
98     return includes
99
100 s = Scanner(name = 'xml', function = scanxml, skeys = ['.xml', '.mod'])
101
102 orig_env = env
103 env = orig_env.Clone(SCANNERS = [s],
104                      SCONS_PROC_PY = File('#bin/scons-proc.py').rfile(),
105                      SCONSOUTPUT_PY = File('#bin/sconsoutput.py').rfile())
106
107 # Fetch the list of files in the build engine that contain
108 # SCons documentation XML for processing.
109 def chop(s): return s[:-1]
110
111 # If we ever read doc from __scons_doc__ strings in *.py files again,
112 # here's how it's done:
113 #manifest_in = File('#src/engine/MANIFEST.in').rstr()
114 #manifest_xml_in = File('#src/engine/MANIFEST-xml.in').rstr()
115 #scons_doc_files = map(chop, open(manifest_in).readlines() +\
116 #                            open(manifest_xml_in).readlines())
117 #scons_doc_files = map(lambda x: '#src/engine/'+x, scons_doc_files)
118 #manifest_in = File('#src/engine/MANIFEST.in').rstr()
119
120 manifest_xml_in = File('#src/engine/MANIFEST-xml.in').rstr()
121 scons_doc_files = map(chop, open(manifest_xml_in).readlines())
122 scons_doc_files = map(lambda x: File('#src/engine/'+x).rstr(), scons_doc_files)
123
124 if not jw:
125     print "jw not found, skipping building User Guide."
126 else:
127     #
128     # Always create a version.xml file containing the version information
129     # for this run.  Ignore it for dependency purposes so we don't
130     # rebuild all the docs every time just because the date changes.
131     #
132     date, ver, rev = env.Dictionary('DATE', 'VERSION', 'REVISION')
133     version_xml = File(os.path.join(build, "version.xml"))
134     #version_xml = File("version.xml")
135     verfile = str(version_xml)
136     try:
137         os.unlink(verfile)
138     except OSError:
139         pass    # okay if the file didn't exist
140     dir, f = os.path.split(verfile)
141     try:
142         os.makedirs(dir)
143     except OSError:
144         pass    # okay if the directory already exists
145     open(verfile, "w").write("""<!--
146 THIS IS AN AUTOMATICALLY-GENERATED FILE.  DO NOT EDIT.
147 -->
148 <!ENTITY builddate "%s">
149 <!ENTITY buildversion "%s">
150 <!ENTITY buildrevision "%s">
151 """ % (date, ver, rev))
152
153     builders_gen = os.path.join(build, 'user', 'builders.gen')
154     builders_mod = os.path.join(build, 'user', 'builders.mod')
155     tools_gen = os.path.join(build, 'user', 'tools.gen')
156     tools_mod = os.path.join(build, 'user', 'tools.mod')
157     variables_gen = os.path.join(build, 'user', 'variables.gen')
158     variables_mod = os.path.join(build, 'user', 'variables.mod')
159
160     # We put $( - $) around $SOURCES in the command line below because
161     # the path names will change when a given input file is found in
162     # a repository one run and locally the next, and we don't want
163     # to rebuild documentation just because it's found in one location
164     # vs. the other.  The *.gen and *.mod targets will still be dependent
165     # on the list of the files themselves.
166     doc_output_files = [builders_gen, builders_mod,
167                         tools_gen, tools_mod,
168                         variables_gen, variables_mod]
169     b = env.Command(doc_output_files,
170                     scons_doc_files,
171                     "$PYTHON $SCONS_PROC_PY --xml -b ${TARGETS[0]},${TARGETS[1]} -t ${TARGETS[2]},${TARGETS[3]} -v ${TARGETS[4]},${TARGETS[5]} $( $SOURCES $)")
172     env.Depends(b, "$SCONS_PROC_PY")
173
174     env.Local(b)
175
176     #
177     # Each document will live in its own subdirectory.  List them here
178     # as hash keys, with a hash of the info to control its build.
179     #
180     docs = {
181         'design' : {
182                 'htmlindex' : 'book1.html',
183                 'ps'        : 1,
184                 'pdf'       : 1,
185                 'text'      : 0,
186         },
187         # This doesn't build on all systems, and the document is old
188         # enough that there's reallyno need to build it every time any
189         # more, so just comment it out for now.
190         #'python10' : {
191         #        'htmlindex' : 't1.html',
192         #        'html'      : 1,
193         #        'ps'        : 1,
194         #        'pdf'       : 0,
195         #        'text'      : 0,
196         #        'graphics'  : [
197         #                        'arch.fig',
198         #                        'builder.fig',
199         #                        'job-task.fig',
200         #                        'node.fig',
201         #                        'scanner.fig',
202         #                        'sig.fig'
203         #                      ],
204         #},
205         'reference' : {
206                 'htmlindex' : 'book1.html',
207                 'html'      : 1,
208                 'ps'        : 1,
209                 'pdf'       : 1,
210                 'text'      : 0,
211         },
212         # For whenever (if ever?) we start putting developer guide
213         # information in a printable document instead of the wiki.
214         #'developer' : {
215         #        'htmlindex' : 'book1.html',
216         #        'html'      : 1,
217         #        'ps'        : 1,
218         #        'pdf'       : 1,
219         #        'text'      : 0,
220         #},
221         'user' : {
222                 'htmlindex' : 'book1.html',
223                 'html'      : 1,
224                 'ps'        : 1,
225                 'pdf'       : 1,
226                 'text'      : 1,
227                 'graphics'  : [
228                                 'SCons-win32-install-1.jpg',
229                                 'SCons-win32-install-2.jpg',
230                                 'SCons-win32-install-3.jpg',
231                                 'SCons-win32-install-4.jpg',
232                               ],
233                 'sconsoutput' : 1,
234         },
235     }
236
237     #
238     # We have to tell SCons to scan the top-level XML files which
239     # get included by the document XML files in the subdirectories.
240     #
241     manifest = File('MANIFEST').rstr()
242     src_files = map(lambda x: x[:-1], open(manifest).readlines())
243     for s in src_files:
244         base, ext = os.path.splitext(s)
245         if ext in ['.fig', '.jpg']:
246             orig_env.Install(build, s)
247         else:
248             orig_env.SCons_revision(os.path.join(build, s), s)
249         Local(os.path.join(build, s))
250
251     #
252     # For each document, build the document itself in HTML, Postscript,
253     # and PDF formats.
254     #
255     for doc in docs.keys():
256         manifest = File(os.path.join(doc, 'MANIFEST')).rstr()
257         src_files = map(lambda x: x[:-1],
258                         open(manifest).readlines())
259         build_doc = docs[doc].get('sconsoutput') and int(ARGUMENTS.get('BUILDDOC', 0))
260         for s in src_files:
261             doc_s = os.path.join(doc, s)
262             build_s = os.path.join(build, doc, s)
263             base, ext = os.path.splitext(doc_s)
264             if ext in ['.fig', '.jpg']:
265                 orig_env.InstallAs(build_s, doc_s)
266             else:
267                 if build_doc and ext == '.xml':
268                     env.Command(doc_s,
269                                 base + '.in',
270                                 "$PYTHON $SCONSOUTPUT_PY $SOURCE > $TARGET")
271                 orig_env.SCons_revision(build_s, doc_s)
272             Local(build_s)
273
274         main = os.path.join(build, doc, 'main.xml')
275         out = 'main.out'
276
277         # Hard-coding the scons-src path is a bit of a hack.  This can
278         # be reworked when a better solution presents itself.
279         scons_src_main = os.path.join(build_dir, 'scons-src', 'doc', main)
280         env.Ignore(scons_src_main, version_xml)
281
282         htmldir = os.path.join(build, 'HTML', 'scons-%s' % doc)
283         htmlindex = os.path.join(htmldir, docs[doc]['htmlindex'])
284         html = os.path.join(build, 'HTML', 'scons-%s.html' % doc)
285         ps = os.path.join(build, 'PS', 'scons-%s.ps' % doc)
286         pdf = os.path.join(build, 'PDF', 'scons-%s.pdf' % doc)
287         text = os.path.join(build, 'TEXT', 'scons-%s.txt' % doc)
288
289         if docs[doc].get('html') and jade:
290             def copy_index_html(target, source, env):
291                 # Older versions of DocBook|jw|jade|whatever would
292                 # create a book1.html file, while newer versions create
293                 # an index.html file (logically enough).  The scons.org
294                 # web site links expect book1.html, so we're going to
295                 # leave the target as is, and run this post-processing
296                 # action function to check that the target really did
297                 # get created, and if it didn't, copy it from index.html.
298                 t = str(target[0])
299                 if not os.path.exists(t):
300                     i = os.path.join(os.path.split(t)[0], 'index.html')
301                     open(t, 'w').write(open(i, 'r').read())
302                 return None
303
304             cmds = [
305                 Delete("${TARGET.dir}/*.html"),
306                 "jw -b html -o ${TARGET.dir} $SOURCES",
307             ]
308             if tidy:
309                 cmds.append("tidy -m -q $TARGET || true")
310             cmds.append(Action(copy_index_html))
311             env.Command(htmlindex, File(main), cmds)
312             Local(htmlindex)
313
314             cmds = [
315                 Delete("${TARGET.dir}/main.html"),
316                 "jw -u -b html -o ${TARGET.dir} $SOURCES",
317                 Move("$TARGET", "${TARGET.dir}/main.html"),
318             ]
319             if tidy:
320                 cmds.append("tidy -m -q $TARGET || true")
321             env.Command(html, File(main), cmds)
322             Local(html)
323
324             env.Ignore([html, htmlindex], version_xml)
325
326             tar_deps.extend([html, htmlindex])
327             tar_list.extend([html, htmldir])
328
329             for g in docs[doc].get('graphics', []):
330                 base, ext = os.path.splitext(g)
331                 if ext == '.fig':
332                     jpg = base + '.jpg'
333                     htmldir_jpg = os.path.join(htmldir, jpg)
334                     if fig2dev:
335                         fig = os.path.join(build, doc, g)
336                         env.Command(htmldir_jpg, fig,
337                                     "%s -L jpeg -q 100 $SOURCES $TARGET" % fig2dev)
338                     else:
339                         env.InstallAs(htmldir_jpg, jpg)
340                     env.Depends(html, htmldir_jpg)
341                     Local(htmldir_jpg)
342                 else:
343                     src = os.path.join(build, doc, g)
344                     Local(env.Install(htmldir, src))
345
346         if docs[doc].get('ps') and jadetex:
347             env.Command(ps, main, [
348                 Delete("${TARGET.dir}/%s" % out),
349                 "jw -b ps -o ${TARGET.dir} $SOURCES",
350                 "mv ${TARGET.dir}/main.ps $TARGET",
351                 Delete("${TARGET.dir}/%s" % out),
352             ])
353             Local(ps)
354
355             env.Ignore(ps, version_xml)
356
357             tar_deps.append(ps)
358             tar_list.append(ps)
359
360             for g in docs[doc].get('graphics', []):
361                 base, ext = os.path.splitext(g)
362                 if ext == '.fig':
363                     eps = base + '.eps'
364                     build_eps = os.path.join(build, 'PS', eps)
365                     if fig2dev:
366                         fig = os.path.join(build, doc, g)
367                         env.Command(build_eps, fig, "%s -L eps $SOURCES $TARGET" % fig2dev)
368                     else:
369                         env.InstallAs(build_eps, eps)
370                     env.Depends(ps, build_eps)
371                     Local(build_eps)
372                 else:
373                     src = os.path.join(build, doc, g)
374                     Local(env.Install(htmldir, src))
375
376         if docs[doc].get('pdf') and pdfjadetex:
377             env.Command(pdf, main, [
378                 Delete("${TARGET.dir}/%s" % out),
379                 "jw -b pdf -o ${TARGET.dir} $SOURCES",
380                 "mv ${TARGET.dir}/main.pdf $TARGET",
381                 Delete("${TARGET.dir}/out"),
382             ])
383             Local(pdf)
384
385             env.Ignore(pdf, version_xml)
386
387             tar_deps.append(pdf)
388             tar_list.append(pdf)
389
390         if docs[doc].get('text') and jade and lynx:
391             env.Command(text, html, "lynx -dump ${SOURCE.abspath} > $TARGET")
392             Local(text)
393
394             env.Ignore(text, version_xml)
395
396             tar_deps.append(text)
397             tar_list.append(text)
398
399 #
400 # Man page(s), in good ol' troff format.
401 #
402 man_page_list = ['scons.1', 'sconsign.1', 'scons-time.1']
403
404 for m in man_page_list:
405     x = orig_env.SCons_revision(os.path.join(build, 'man', m),
406                             os.path.join('man', m))
407
408 man_i_files = ['builders.man', 'tools.man', 'variables.man']
409
410 man_intermediate_files = map(lambda x: os.path.join(build, 'man', x),
411                              man_i_files)
412
413 cmd = "$PYTHON $SCONS_PROC_PY --man -b ${TARGETS[0]} -t ${TARGETS[1]} -v ${TARGETS[2]} $( $SOURCES $)"
414 man_intermediate_files = env.Command(man_intermediate_files,
415                                      scons_doc_files,
416                                      cmd)
417 env.Depends(man_intermediate_files, "$SCONS_PROC_PY")
418 Local(man_intermediate_files)
419
420 for man_1 in man_page_list:
421     man, _1 = os.path.splitext(man_1)
422
423     man_1 = os.path.join(build, 'man', man_1)
424
425     if groff:
426         ps = os.path.join(build, 'PS', '%s-man.ps' % man)
427         text = os.path.join(build, 'TEXT', '%s-man.txt' % man)
428
429         b = env.Command(ps, man_1, "( cd ${SOURCES.dir} && groff -man -Tps ${SOURCES.file} ) > $TARGET")
430         Local(ps)
431         env.Depends(b, man_intermediate_files)
432
433         b = env.Command(text, man_1, "( cd ${SOURCES.dir} && groff -man -Tascii ${SOURCES.file} ) > $TARGET")
434         Local(text)
435         env.Depends(b, man_intermediate_files)
436
437         tar_deps.extend([ps, text])
438         tar_list.extend([ps, text])
439
440     if man2html:
441         html = os.path.join(build, 'HTML' , '%s-man.html' % man)
442
443         def strip_to_first_html_tag(target, source, env):
444             t = str(target[0])
445             contents = open(t).read()
446             contents = contents[string.find(contents, '<HTML>'):]
447             open(t, 'w').write(contents)
448             return 0
449
450         cmds = [
451             "( cd %s/man && cp %s .. )" % (build, string.join(man_i_files)),
452             "( cd ${SOURCE.dir} && man2html ${SOURCE.file} ) > $TARGET",
453             Action(strip_to_first_html_tag),
454         ]
455         if tidy:
456             cmds.append("tidy -m -q $TARGET || true")
457         b = env.Command(html, man_1, cmds)
458         Local(html)
459         env.Depends(b, man_intermediate_files)
460
461         tar_deps.append(html)
462         tar_list.append(html)
463
464 if not epydoc:
465     print "epydoc not found, skipping building API documentation."
466 else:
467     # XXX Should be in common with reading the same thing in
468     # the SConstruct file.
469     e = os.path.join('#src', 'engine')
470     manifest_in = File(os.path.join(e, 'MANIFEST.in')).rstr()
471     sources = map(lambda x: x[:-1], open(manifest_in).readlines())
472     sources = filter(lambda x: string.find(x, 'Optik') == -1, sources)
473     sources = filter(lambda x: string.find(x, 'Platform') == -1, sources)
474     sources = filter(lambda x: string.find(x, 'Tool') == -1, sources)
475     # XXX
476     sources = filter(lambda x: string.find(x, 'Options') == -1, sources)
477
478     e = os.path.join(build, '..', 'scons', 'engine')
479     sources = map(lambda x, e=e: os.path.join(e, x), sources)
480
481     epydoc_commands = [
482         Delete('$OUTDIR'),
483         '$EPYDOC $EPYDOCFLAGS --debug --output $OUTDIR --docformat=restructuredText --name SCons --url http://www.scons.org/ $SOURCES',
484         Touch('$TARGET'),
485     ]
486
487     htmldir = os.path.join(build, 'HTML', 'scons-api')
488     env.Command('${OUTDIR}/index.html', sources, epydoc_commands,
489                 EPYDOC=epydoc, EPYDOCFLAGS='--html', OUTDIR=htmldir)
490     tar_deps.append(htmldir)
491     tar_list.append(htmldir)
492
493     # PDF and PostScript and TeX are built from the
494     # same invocation.
495     api_dir = os.path.join(build, 'scons-api')
496     api_pdf = os.path.join(api_dir, 'api.pdf')
497     api_ps = os.path.join(api_dir, 'api.ps')
498     api_tex = os.path.join(api_dir, 'api.tex')
499     api_targets = [api_pdf, api_ps, api_tex]
500     env.Command(api_targets, sources, epydoc_commands,
501                 EPYDOC=epydoc, EPYDOCFLAGS='--pdf', OUTDIR=api_dir)
502     Local(api_targets)
503
504     pdf_install = os.path.join(build, 'PDF', 'scons-api.pdf')
505     env.InstallAs(pdf_install, api_pdf)
506     tar_deps.append(pdf_install)
507     tar_list.append(pdf_install)
508     Local(pdf_install)
509
510     ps_install = os.path.join(build, 'PS', 'scons-api.ps')
511     env.InstallAs(ps_install, api_ps)
512     tar_deps.append(ps_install)
513     tar_list.append(ps_install)
514     Local(ps_install)
515
516 #
517 # Now actually create the tar file of the documentation,
518 # for easy distribution to the web site.
519 #
520 if tar_deps:
521     tar_list = string.join(map(lambda x, b=build+'/': string.replace(x, b, ''),
522                            tar_list))
523     t = env.Command(dist_doc_tar_gz, tar_deps,
524                 "tar cf${TAR_HFLAG} - -C %s %s | gzip > $TARGET" % (build, tar_list))
525     AddPostAction(dist_doc_tar_gz, Chmod(dist_doc_tar_gz, 0644))
526     Local(t)
527     Alias('doc', t)
528 else:
529     Alias('doc', os.path.join(build_dir, 'doc'))