source: rtems-docs/common/waf.py @ 4407039

5
Last change on this file since 4407039 was 4407039, checked in by Chris Johns <chrisj@…>, on 02/19/19 at 22:16:19

waf: Fix building the images in the src path.

  • Property mode set to 100644
File size: 19.7 KB
Line 
1#
2# RTEMS Documentation Project
3#
4# Waf build support.
5#
6
7
8from __future__ import print_function
9
10import os
11import re
12import sys
13
14from waflib.Build import BuildContext
15
16import latex
17import conf
18
19sphinx_min_version = (1, 3)
20
21def version_cmdline(ctx):
22    return '-Drelease="%s" -Dversion="%s"' % (ctx.env.RELEASE, ctx.env.VERSION)
23
24def sphinx_cmdline(ctx, build_type, conf_dir, doctrees,
25                   source_dir, output_dir, configs = []):
26    cfgs = ''
27    for c in configs:
28        cfgs += ' -D %s=%s' % (c, configs[c])
29    rule = "${BIN_SPHINX_BUILD} %s -b %s -c %s %s -d %s %s %s %s ${SRC}" % \
30           (sphinx_verbose(ctx), build_type, conf_dir, version_cmdline(ctx),
31            doctrees, cfgs, source_dir, output_dir)
32    return rule
33
34def cmd_spell(ctx):
35    from waflib import Options
36    from sys import argv
37    from subprocess import call
38
39    Options.commands = None # stop warnings about knowing commands.
40
41    if not ctx.env.BIN_ASPELL:
42        ctx.fatal("'aspell' is required please install and re-run configure.")
43
44    if len(argv) < 3:
45        ctx.fatal("Please supply at least one file name")
46
47    files = argv[2:]
48
49    path = ctx.path.parent.abspath()
50
51    # XXX: add error checking eg check if file exists.
52    for file in files:
53        cmd = ctx.env.BIN_ASPELL + \
54              ["-c",
55               "--personal=%s/common/spell/dict/rtems" % path,
56               "--extra-dicts=%s/common/spell/en_GB-ise-w_accents.multi" % path,
57               file]
58        print("running:", cmd)
59        call(cmd)
60
61def cmd_linkcheck(ctx):
62    conf_dir = ctx.path.get_src()
63    source_dir = ctx.path.get_src()
64    buildtype = 'linkcheck'
65    build_dir, output_node, output_dir, doctrees = build_dir_setup(ctx, buildtype)
66    rule = sphinx_cmdline(ctx, buildtype, conf_dir, doctrees, source_dir, output_dir)
67    ctx(
68        rule   = rule,
69        cwd    = ctx.path.abspath(),
70        source = ctx.path.ant_glob('**/*.rst'),
71        target = "linkcheck/output.txt"
72    )
73
74class spell(BuildContext):
75    __doc__ = "Check spelling.  Supply a list of files or a glob (*.rst)"
76    cmd = 'spell'
77    fun = 'cmd_spell'
78
79class linkcheck(BuildContext):
80    __doc__ = "Check all external URL references."
81    cmd = 'linkcheck'
82    fun = 'cmd_linkcheck'
83
84def check_sphinx_version(ctx, minver):
85    try:
86        import sphinx
87        # sphinx.version_info was introduced in sphinx ver 1.2
88        version = sphinx.version_info
89        # version looks like (1, 7, 0, 'final', 0))
90        ver = version[0:2]
91    except:
92        try:
93            # sphinx-build returns its version info in stderr
94            (out, err) = ctx.cmd_and_log(ctx.env.BIN_SPHINX_BUILD +
95                              ['--version'], output=Context.BOTH)
96            # err looks like 'sphinx-build 1.7.0\n'
97            version = err.split(" ")[-1:][0].strip()
98            ver = tuple(map(int, re.split('[\D]', version)))
99        except:
100            try:
101                # sphinx-build returns its version info in stdout
102                version = ctx.cmd_and_log(ctx.env.BIN_SPHINX_BUILD +
103                              ['--version']).split(" ")[-1:][0].strip()
104                try:
105                    ver = tuple(map(int, re.split('[\D]', version)))
106                except:
107                    ctx.fatal("Sphinx version cannot be checked or Sphinx is not installed")
108            except:
109                ctx.fatal("Sphinx version cannot be checked or Sphinx is not installed")
110    if ver < minver:
111        ctx.fatal("Sphinx version is too old: %s" % ".".join(map(str, ver)))
112    return ver
113
114def sphinx_verbose(ctx):
115    return ' '.join(ctx.env.SPHINX_VERBOSE)
116
117def is_top_build(ctx):
118    from_top = False
119    if ctx.env['BUILD_FROM_TOP'] and ctx.env['BUILD_FROM_TOP'] == 'yes':
120        from_top = True
121    return from_top
122
123def build_dir_setup(ctx, buildtype):
124    where = buildtype
125    if is_top_build(ctx):
126        where = os.path.join(ctx.path.name, where)
127    bnode = ctx.bldnode.find_node(where)
128    if bnode is None:
129        ctx.bldnode.make_node(where).mkdir()
130    build_dir = ctx.path.get_bld().relpath()
131    output_node = ctx.path.get_bld().make_node(buildtype)
132    output_dir = output_node.abspath()
133    doctrees = os.path.join(os.path.dirname(output_dir), 'doctrees', buildtype)
134    return build_dir, output_node, output_dir, doctrees
135
136def pdf_resources(ctx, buildtype):
137    packages_base = ctx.path.parent.find_dir('common/latex')
138    if packages_base is None:
139        ctx.fatal('Latex package directory not found')
140    base = packages_base.path_from(ctx.path)
141    fnode = ctx.path.get_bld().make_node(buildtype)
142    fnode.mkdir()
143    local_packages = latex.local_packages()
144    targets = []
145    if local_packages is not None:
146        srcs = [os.path.join(base, p) for p in local_packages]
147        targets += [fnode.make_node(p) for p in local_packages]
148        ctx(features = "subst",
149            is_copy  = True,
150            source   = srcs,
151            target   = targets)
152    targets += [fnode.make_node('rtemsextrafonts.sty')]
153    ctx(features = "subst",
154        is_copy  = True,
155        source   = os.path.join(base, ctx.env.RTEMSEXTRAFONTS),
156        target   = fnode.make_node('rtemsextrafonts.sty'))
157    return targets
158
159def html_resources(ctx, buildtype):
160    extra_source = []
161    for dir_name in ["_static", "_templates"]:
162        files = ctx.path.parent.find_node("common").ant_glob("%s/*" % dir_name)
163        fnode = ctx.path.get_bld().make_node(os.path.join(buildtype, dir_name))
164        targets = [fnode.make_node(x.name) for x in files]
165        extra_source += targets
166        fnode.mkdir() # dirs
167        ctx(features = "subst",
168            is_copy  = True,
169            source   = files,
170            target   = targets)
171        ctx.add_group()
172    return extra_source
173
174def check_sphinx_extension(ctx, extension):
175    def run_sphinx(bld):
176        rst_node = bld.srcnode.make_node('testbuild/contents.rst')
177        rst_node.parent.mkdir()
178        rst_node.write('.. COMMENT test sphinx\n')
179        bld(rule = bld.kw['rule'], source = rst_node)
180
181    ctx.start_msg("Checking for '%s'" % (extension))
182    try:
183        ctx.run_build(fragment = 'xx',
184                      rule = "${BIN_SPHINX_BUILD} -b html -D extensions=%s -C . out" % (extension),
185                      build_fun = run_sphinx,
186                      env = ctx.env)
187    except ctx.errors.ConfigurationError:
188        ctx.end_msg('not found (see README.txt)', 'RED')
189        ctx.fatal('The configuration failed')
190    ctx.end_msg('found')
191
192def cmd_configure(ctx):
193    check_sphinx = not ctx.env.BIN_SPHINX_BUILD
194    if check_sphinx:
195        ctx.find_program("sphinx-build", var="BIN_SPHINX_BUILD", mandatory = True)
196        ctx.find_program("aspell", var = "BIN_ASPELL", mandatory = False)
197
198        ctx.start_msg("Checking if Sphinx is at least %s.%s" % sphinx_min_version)
199        ver = check_sphinx_version(ctx, sphinx_min_version)
200        ctx.end_msg("yes (%s)" % ".".join(map(str, ver)))
201
202        ctx.start_msg("Checking Sphinx Verbose ")
203        if 'SPHINX_VERBOSE' not in ctx.env:
204            ctx.env.append_value('SPHINX_VERBOSE', ctx.options.sphinx_verbose)
205            level = sphinx_verbose(ctx)
206            if level == '-Q':
207                level = 'quiet'
208            ctx.end_msg(level)
209        #
210        # Check extensions.
211        #
212        check_sphinx_extension(ctx, 'sphinx.ext.autodoc')
213        check_sphinx_extension(ctx, 'sphinx.ext.coverage')
214        check_sphinx_extension(ctx, 'sphinx.ext.doctest')
215        check_sphinx_extension(ctx, 'sphinx.ext.graphviz')
216        check_sphinx_extension(ctx, 'sphinx.ext.intersphinx')
217        check_sphinx_extension(ctx, 'sphinx.ext.mathjax')
218        check_sphinx_extension(ctx, 'sphinxcontrib.bibtex')
219
220    #
221    # Optional builds.
222    #
223    ctx.env.BUILD_PDF = 'no'
224    if ctx.options.pdf:
225        if conf.latex_engine == 'xelatex':
226            if not ctx.env.LATEX_CMD:
227                ctx.load('tex')
228                if not ctx.env.XELATEX or not ctx.env.MAKEINDEX:
229                    ctx.fatal('The programs xelatex and makeindex are required for PDF output')
230                ctx.env.LATEX_CMD = 'xelatex'
231                latex.configure_tests(ctx)
232                # Minted needs 'shell-escape'
233                if 'XELATEXFLAGS' not in ctx.env or \
234                   '-shell-escape' not in ctx.env['XELATEXFLAGS']:
235                    ctx.env.append_value('XELATEXFLAGS', '-shell-escape')
236                ctx.env.append_value('MAKEINDEXFLAGS', ['-s', 'python.ist'])
237        elif conf.latex_engine == 'pdflatex':
238            if not ctx.env.LATEX_CMD:
239                ctx.load('tex')
240                if not ctx.env.PDFLATEX or not ctx.env.MAKEINDEX:
241                    ctx.fatal('The programs pdflatex and makeindex are required for PDF output')
242                if 'PDFLATEXFLAGS' not in ctx.env or \
243                   '-shell-escape' not in ctx.env['PDFLATEXFLAGS']:
244                    ctx.env.append_value('PDFLATEXFLAGS', '-shell-escape')
245                ctx.env.append_value('MAKEINDEXFLAGS', ['-s', 'python.ist'])
246                ctx.env.LATEX_CMD = 'pdflatex'
247                latex.configure_tests(ctx)
248        else:
249            ctx.fatal('Unsupported latex engine: %s' % (conf.latex_engine))
250        ctx.env.BUILD_PDF = 'yes'
251
252    ctx.envBUILD_SINGLEHTML = 'no'
253    if ctx.options.singlehtml:
254        check_inliner = not ctx.env.BIN_INLINER
255        if check_inliner:
256            ctx.env.BUILD_SINGLEHTML = 'yes'
257            ctx.find_program("inliner", var = "BIN_INLINER", mandatory = False)
258            if not ctx.env.BIN_INLINER:
259                ctx.fatal("Node.js inliner is required install with 'npm install -g inliner' " +
260                          "(https://github.com/remy/inliner)")
261
262    ctx.envBUILD_PLANTUML = 'no'
263    if ctx.options.plantuml:
264        check_plantuml = not ctx.env.BIN_PUML
265        if check_plantuml:
266            ctx.env.BUILD_PLANTUML = 'yes'
267            ctx.find_program("puml", var = "BIN_PUML", mandatory = False)
268            if not ctx.env.BIN_PUML:
269                ctx.fatal("Node.js puml is required install with 'npm install -g node-plantuml' " +
270                          "(https://www.npmjs.com/package/node-plantuml)")
271
272    ctx.envBUILD_DITAA = 'no'
273    if ctx.options.ditaa:
274        #
275        # We use DITAA via PlantUML
276        #
277        if not ctx.env.BIN_PUML:
278            ctx.find_program("puml", var = "BIN_PUML", mandatory = False)
279            if not ctx.env.BIN_PUML:
280                ctx.fatal("DITAA uses PlantUML; " +
281                          "Node.js puml is required install with 'npm install -g node-plantuml' " +
282                          "(https://www.npmjs.com/package/node-plantuml)")
283        check_ditaa = not ctx.env.BIN_DITAA
284        if check_ditaa:
285            ctx.env.BUILD_DITAA = 'yes'
286            ctx.find_program("ditaa", var = "BIN_DITAA", mandatory = False)
287            if not ctx.env.BIN_DITAA:
288                ctx.fatal("DITAA not found, plase install")
289
290def doc_pdf(ctx, source_dir, conf_dir, extra_source):
291    buildtype = 'latex'
292    build_dir, output_node, output_dir, doctrees = build_dir_setup(ctx, buildtype)
293    resources = pdf_resources(ctx, buildtype)
294    rule = sphinx_cmdline(ctx, buildtype, conf_dir, doctrees, source_dir, output_dir)
295    ctx(
296        rule         = rule,
297        cwd          = ctx.path,
298        source       = ctx.path.ant_glob('**/*.rst') + extra_source,
299        depends_on   = extra_source,
300        target       = ctx.path.find_or_declare("%s/%s.tex" % (buildtype,
301                                                               ctx.path.name))
302    )
303    ctx(
304        features     = 'tex',
305        cwd          = output_dir,
306        type         = ctx.env.LATEX_CMD,
307        source       = "%s/%s.tex" % (buildtype, ctx.path.name),
308        prompt       = 0
309    )
310    ctx.install_files('${PREFIX}',
311                      '%s/%s.pdf' % (buildtype, ctx.path.name),
312                      cwd = output_node,
313                      quiet = True)
314
315def doc_singlehtml(ctx, source_dir, conf_dir, extra_source):
316    #
317    # Use a run command to handle stdout and stderr output from inliner. Using
318    # a standard rule in the build context locks up.
319    #
320    def run(task):
321        src = task.inputs[0].abspath()
322        tgt = task.outputs[0].abspath()
323        cmd = '%s %s' % (task.env.BIN_INLINER[0], src)
324        so = open(tgt, 'w')
325        se = open(tgt + '.err', 'w')
326        r = task.exec_command(cmd, stdout = so, stderr = se)
327        so.close()
328        se.close()
329        #
330        # The inliner does not handle internal href's correctly and places the
331        # input's file name in the href. Strip these.
332        #
333        with open(tgt, 'r') as i:
334            before = i.read()
335            after = before.replace('index.html', '')
336        i.close()
337        with open(tgt, 'w') as o:
338            o.write(after)
339        o.close()
340        return r
341
342    buildtype = 'singlehtml'
343    build_dir, output_node, output_dir, doctrees = build_dir_setup(ctx, buildtype)
344    resources = html_resources(ctx, buildtype)
345    rule = sphinx_cmdline(ctx, buildtype, conf_dir, doctrees, source_dir, output_dir)
346    ctx(
347        rule         = rule,
348        cwd          = ctx.path,
349        source       = ctx.path.ant_glob('**/*.rst') + extra_source,
350        depends_on   = resources,
351        target       = ctx.path.find_or_declare("%s/index.html" % (buildtype)),
352        install_path = None
353    )
354    ctx(
355        rule         = run,
356        inliner      = ctx.env.BIN_INLINER,
357        source       = "%s/index.html" % buildtype,
358        target       = "%s/%s.html" % (buildtype, ctx.path.name),
359        install_path = '${PREFIX}'
360    )
361
362def doc_html(ctx, source_dir, conf_dir, extra_source):
363    buildtype = 'html'
364    build_dir, output_node, output_dir, doctrees = build_dir_setup(ctx, buildtype)
365    resources = html_resources(ctx, buildtype)
366    templates = os.path.join(str(ctx.path.get_bld()), buildtype, '_templates')
367    configs = { 'templates_path': templates }
368    rule = sphinx_cmdline(ctx, buildtype, conf_dir, doctrees, source_dir, output_dir, configs)
369    ctx(
370        rule         = rule,
371        cwd          = ctx.path,
372        source       = ctx.path.ant_glob('**/*.rst') + extra_source,
373        depends_on   = resources,
374        target       = ctx.path.find_or_declare('%s/index.html' % buildtype),
375        install_path = None
376    )
377    ctx.install_files('${PREFIX}/%s' % (ctx.path.name),
378                      output_node.ant_glob('**/*', quiet = True),
379                      cwd = output_node,
380                      relative_trick = True,
381                      quiet = True)
382
383def images_plantuml(ctx, source_dir, conf_dir, ext):
384    #
385    # Use a run command to handle stdout and stderr output from puml.
386    #
387    def run(task):
388        src = task.inputs[0].abspath()
389        tgt = task.outputs[0].abspath()
390        cmd = '%s generate %s -o %s' % (task.env.BIN_PUML[0], src, tgt)
391        so = open(tgt + '.out', 'w')
392        r = task.exec_command(cmd, stdout = so, stderr = so)
393        so.close()
394        return r
395
396    for src in ctx.path.ant_glob('**/*' + ext):
397        tgt = src.change_ext('.png')
398        ctx(
399            rule         = run,
400            inliner      = ctx.env.BIN_PUML,
401            source       = src,
402            target       = tgt,
403            install_path = None
404        )
405
406def cmd_build(ctx, extra_source = []):
407    conf_dir = ctx.path.get_src()
408    source_dir = ctx.path.get_src()
409
410    if ctx.env.BUILD_PDF == 'yes':
411        doc_pdf(ctx, source_dir, conf_dir, extra_source)
412
413    if ctx.env.BUILD_SINGLEHTML == 'yes':
414        doc_singlehtml(ctx, source_dir, conf_dir, extra_source)
415
416    doc_html(ctx, source_dir, conf_dir, extra_source)
417
418def cmd_build_images(ctx):
419    conf_dir = ctx.path.get_src()
420    source_dir = ctx.path.get_src()
421    if ctx.env.BUILD_PLANTUML == 'yes':
422        images_plantuml(ctx, source_dir, conf_dir, '.puml')
423    if ctx.env.BUILD_DITAA == 'yes':
424        images_plantuml(ctx, source_dir, conf_dir, '.ditaa')
425
426def cmd_options(ctx):
427    ctx.add_option('--disable-extra-fonts',
428                   action = 'store_true',
429                   default = False,
430                   help = "Disable building with extra fonts for better quality (lower quality).")
431    ctx.add_option('--sphinx-verbose',
432                   action = 'store',
433                   default = "-Q",
434                   help = "Sphinx verbose.")
435    ctx.add_option('--pdf',
436                   action = 'store_true',
437                   default = False,
438                   help = "Build PDF.")
439    ctx.add_option('--singlehtml',
440                   action = 'store_true',
441                   default = False,
442                   help = "Build Single HTML file, requires Node Inliner")
443    ctx.add_option('--plantuml',
444                   action = 'store_true',
445                   default = False,
446                   help = "Build PlantUML images from source, need puml from npm")
447    ctx.add_option('--ditaa',
448                   action = 'store_true',
449                   default = False,
450                   help = "Build DITAA images using PlantUML from source, need ditaa and puml")
451
452def cmd_options_path(ctx):
453    cmd_options(ctx)
454    ctx.add_option('--rtems-path-py',
455                   type = 'string',
456                   help = "Full path to py/ in RTEMS source repository.")
457
458def cmd_configure_path(ctx):
459    if not ctx.options.rtems_path_py:
460        ctx.fatal("--rtems-path-py is required")
461
462    ctx.env.RTEMS_PATH = ctx.options.rtems_path_py
463
464    cmd_configure(ctx)
465
466def xml_catalogue(ctx, building):
467    #
468    # The following is a hack to find the top_dir because the task does
469    # provided a reference to top_dir like a build context.
470    #
471    top_dir = ctx.get_cwd().find_node('..')
472    #
473    # Read the conf.py files in each directory to gather the doc details.
474    #
475    catalogue = {}
476    sp = sys.path[:]
477    for doc in building:
478        #
479        # Import using the imp API so the module is reloaded for us.
480        #
481        import imp
482        sys.path = [top_dir.find_node(doc).abspath()]
483        mf = imp.find_module('conf')
484        sys.path = sp[:]
485        try:
486            bconf = imp.load_module('bconf', mf[0], mf[1], mf[2])
487        finally:
488            mf[0].close()
489        catalogue[doc] = {
490            'title': bconf.project,
491            'version': str(ctx.env.VERSION),
492            'release': str(ctx.env.VERSION),
493            'pdf': bconf.latex_documents[0][1].replace('.tex', '.pdf'),
494            'html': '%s/index.html' % (doc),
495            'singlehtml': '%s.html' % (doc)
496        }
497        bconf = None
498
499    import xml.dom.minidom as xml
500    cat = xml.Document()
501
502    root = cat.createElement('rtems-docs')
503    root.setAttribute('date', ctx.env.DATE)
504    cat.appendChild(root)
505
506    heading = cat.createElement('catalogue')
507    text = cat.createTextNode(str(ctx.env.VERSION))
508    heading.appendChild(text)
509    root.appendChild(heading)
510
511    builds = ['html']
512    if ctx.env.BUILD_PDF == 'yes':
513        builds += ['pdf']
514    if ctx.env.BUILD_SINGLEHTML == 'yes':
515        builds += ['singlehtml']
516
517    for d in building:
518        doc = cat.createElement('doc')
519        name = cat.createElement('name')
520        text = cat.createTextNode(d)
521        name.appendChild(text)
522        title = cat.createElement('title')
523        text = cat.createTextNode(catalogue[d]['title'])
524        title.appendChild(text)
525        release = cat.createElement('release')
526        text = cat.createTextNode(catalogue[d]['release'])
527        release.appendChild(text)
528        version = cat.createElement('version')
529        text = cat.createTextNode(catalogue[d]['version'])
530        version.appendChild(text)
531        doc.appendChild(name)
532        doc.appendChild(title)
533        doc.appendChild(release)
534        doc.appendChild(version)
535        for b in builds:
536            output = cat.createElement(b)
537            text = cat.createTextNode(catalogue[d][b])
538            output.appendChild(text)
539            doc.appendChild(output)
540        root.appendChild(doc)
541
542    catnode = ctx.get_cwd().make_node('catalogue.xml')
543    catnode.write(cat.toprettyxml(indent = ' ' * 2, newl = os.linesep))
544
545    cat.unlink()
Note: See TracBrowser for help on using the repository browser.