source: rtems-docs/common/waf.py @ 1393ba0

5
Last change on this file since 1393ba0 was 1393ba0, checked in by Chris Johns <chrisj@…>, on 03/01/19 at 02:06:11

waf: Fix argument bug getting extra source.

  • Property mode set to 100644
File size: 20.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_options(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_options(ctx):
115    return ' '.join(ctx.env.SPHINX_OPTIONS)
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    resources = []
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        resources += 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 resources
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 Options ")
203        if 'SPHINX_OPTIONS' not in ctx.env:
204            ctx.env.append_value('SPHINX_OPTIONS', ctx.options.sphinx_options)
205            opts = sphinx_options(ctx)
206            if len(opts) == 0:
207                opts = 'none'
208            ctx.end_msg(opts)
209
210        ctx.start_msg("Checking Sphinx Nit-Pick mode ")
211        if ctx.options.sphinx_nit_pick:
212            opt = '-n'
213            msg = 'yes'
214        else:
215            opt = '-Q'
216            msg = 'no'
217        ctx.env.append_value('SPHINX_OPTIONS', opt)
218        ctx.end_msg(msg)
219
220        #
221        # Check extensions.
222        #
223        check_sphinx_extension(ctx, 'sphinx.ext.autodoc')
224        check_sphinx_extension(ctx, 'sphinx.ext.coverage')
225        check_sphinx_extension(ctx, 'sphinx.ext.doctest')
226        check_sphinx_extension(ctx, 'sphinx.ext.graphviz')
227        check_sphinx_extension(ctx, 'sphinx.ext.intersphinx')
228        check_sphinx_extension(ctx, 'sphinx.ext.mathjax')
229        check_sphinx_extension(ctx, 'sphinxcontrib.bibtex')
230
231    #
232    # Optional builds.
233    #
234    ctx.env.BUILD_PDF = 'no'
235    if ctx.options.pdf:
236        if conf.latex_engine == 'xelatex':
237            if not ctx.env.LATEX_CMD:
238                ctx.load('tex')
239                if not ctx.env.XELATEX or not ctx.env.MAKEINDEX:
240                    ctx.fatal('The programs xelatex and makeindex are required for PDF output')
241                ctx.env.LATEX_CMD = 'xelatex'
242                latex.configure_tests(ctx)
243                # Minted needs 'shell-escape'
244                if 'XELATEXFLAGS' not in ctx.env or \
245                   '-shell-escape' not in ctx.env['XELATEXFLAGS']:
246                    ctx.env.append_value('XELATEXFLAGS', '-shell-escape')
247                ctx.env.append_value('MAKEINDEXFLAGS', ['-s', 'python.ist'])
248        elif conf.latex_engine == 'pdflatex':
249            if not ctx.env.LATEX_CMD:
250                ctx.load('tex')
251                if not ctx.env.PDFLATEX or not ctx.env.MAKEINDEX:
252                    ctx.fatal('The programs pdflatex and makeindex are required for PDF output')
253                if 'PDFLATEXFLAGS' not in ctx.env or \
254                   '-shell-escape' not in ctx.env['PDFLATEXFLAGS']:
255                    ctx.env.append_value('PDFLATEXFLAGS', '-shell-escape')
256                ctx.env.append_value('MAKEINDEXFLAGS', ['-s', 'python.ist'])
257                ctx.env.LATEX_CMD = 'pdflatex'
258                latex.configure_tests(ctx)
259        else:
260            ctx.fatal('Unsupported latex engine: %s' % (conf.latex_engine))
261        ctx.env.BUILD_PDF = 'yes'
262
263    ctx.envBUILD_SINGLEHTML = 'no'
264    if ctx.options.singlehtml:
265        check_inliner = not ctx.env.BIN_INLINER
266        if check_inliner:
267            ctx.env.BUILD_SINGLEHTML = 'yes'
268            ctx.find_program("inliner", var = "BIN_INLINER", mandatory = False)
269            if not ctx.env.BIN_INLINER:
270                ctx.fatal("Node.js inliner is required install with 'npm install -g inliner' " +
271                          "(https://github.com/remy/inliner)")
272
273    ctx.envBUILD_PLANTUML = 'no'
274    if ctx.options.plantuml:
275        check_plantuml = not ctx.env.BIN_PUML
276        if check_plantuml:
277            ctx.env.BUILD_PLANTUML = 'yes'
278            ctx.find_program("puml", var = "BIN_PUML", mandatory = False)
279            if not ctx.env.BIN_PUML:
280                ctx.fatal("Node.js puml is required install with 'npm install -g node-plantuml' " +
281                          "(https://www.npmjs.com/package/node-plantuml)")
282
283    ctx.envBUILD_DITAA = 'no'
284    if ctx.options.ditaa:
285        #
286        # We use DITAA via PlantUML
287        #
288        if not ctx.env.BIN_PUML:
289            ctx.find_program("puml", var = "BIN_PUML", mandatory = False)
290            if not ctx.env.BIN_PUML:
291                ctx.fatal("DITAA uses PlantUML; " +
292                          "Node.js puml is required install with 'npm install -g node-plantuml' " +
293                          "(https://www.npmjs.com/package/node-plantuml)")
294        check_ditaa = not ctx.env.BIN_DITAA
295        if check_ditaa:
296            ctx.env.BUILD_DITAA = 'yes'
297            ctx.find_program("ditaa", var = "BIN_DITAA", mandatory = False)
298            if not ctx.env.BIN_DITAA:
299                ctx.fatal("DITAA not found, plase install")
300
301def sources_exclude(ctx, sources):
302    exclude = sources.get('exclude', [])
303    if len(exclude) == 0:
304        return exclude
305    return [ctx.path.find_node(e) for e in exclude]
306
307def sources_extra(ctx, sources):
308    extra = sources.get('extra', [])
309    if len(extra) == 0:
310        extra = [ctx.path.find_node(e) for e in extra]
311    return [e for e in extra if e not in sources_exclude(ctx, sources)]
312
313def sources_source(ctx, sources):
314    extra = sources_extra(ctx, sources)
315    exclude = sources_exclude(ctx, sources)
316    source = ctx.path.ant_glob('**/*.rst')
317    return [s for s in source if s not in exclude] + extra
318
319def doc_pdf(ctx, source_dir, conf_dir, sources):
320    buildtype = 'latex'
321    build_dir, output_node, output_dir, doctrees = build_dir_setup(ctx, buildtype)
322    resources = pdf_resources(ctx, buildtype)
323    rule = sphinx_cmdline(ctx, buildtype, conf_dir, doctrees, source_dir, output_dir)
324    ctx(
325        rule         = rule,
326        cwd          = ctx.path,
327        source       = sources_source(ctx, sources),
328        depends_on   = sources_extra(ctx, sources),
329        target       = ctx.path.find_or_declare("%s/%s.tex" % (buildtype,
330                                                               ctx.path.name))
331    )
332    ctx(
333        features     = 'tex',
334        cwd          = output_dir,
335        type         = ctx.env.LATEX_CMD,
336        source       = "%s/%s.tex" % (buildtype, ctx.path.name),
337        prompt       = 0
338    )
339    ctx.install_files('${PREFIX}',
340                      '%s/%s.pdf' % (buildtype, ctx.path.name),
341                      cwd = output_node,
342                      quiet = True)
343
344def doc_singlehtml(ctx, source_dir, conf_dir, sources):
345    #
346    # Use a run command to handle stdout and stderr output from inliner. Using
347    # a standard rule in the build context locks up.
348    #
349    def run(task):
350        src = task.inputs[0].abspath()
351        tgt = task.outputs[0].abspath()
352        cmd = '%s %s' % (task.env.BIN_INLINER[0], src)
353        so = open(tgt, 'w')
354        se = open(tgt + '.err', 'w')
355        r = task.exec_command(cmd, stdout = so, stderr = se)
356        so.close()
357        se.close()
358        #
359        # The inliner does not handle internal href's correctly and places the
360        # input's file name in the href. Strip these.
361        #
362        with open(tgt, 'r') as i:
363            before = i.read()
364            after = before.replace('index.html', '')
365        i.close()
366        with open(tgt, 'w') as o:
367            o.write(after)
368        o.close()
369        return r
370
371    buildtype = 'singlehtml'
372    build_dir, output_node, output_dir, doctrees = build_dir_setup(ctx, buildtype)
373    resources = html_resources(ctx, buildtype)
374    rule = sphinx_cmdline(ctx, buildtype, conf_dir, doctrees, source_dir, output_dir)
375    ctx(
376        rule         = rule,
377        cwd          = ctx.path,
378        source       = sources_source(ctx, sources),
379        depends_on   = resources,
380        target       = ctx.path.find_or_declare("%s/index.html" % (buildtype)),
381        install_path = None
382    )
383    ctx(
384        rule         = run,
385        inliner      = ctx.env.BIN_INLINER,
386        source       = "%s/index.html" % buildtype,
387        target       = "%s/%s.html" % (buildtype, ctx.path.name),
388        install_path = '${PREFIX}'
389    )
390
391def doc_html(ctx, source_dir, conf_dir, sources):
392    buildtype = 'html'
393    build_dir, output_node, output_dir, doctrees = build_dir_setup(ctx, buildtype)
394    resources = html_resources(ctx, buildtype)
395    templates = os.path.join(str(ctx.path.get_bld()), buildtype, '_templates')
396    configs = { 'templates_path': templates }
397    rule = sphinx_cmdline(ctx, buildtype, conf_dir, doctrees, source_dir, output_dir, configs)
398    ctx(
399        rule         = rule,
400        cwd          = ctx.path,
401        source       = sources_source(ctx, sources),
402        depends_on   = resources,
403        target       = ctx.path.find_or_declare('%s/index.html' % buildtype),
404        install_path = None
405    )
406    ctx.install_files('${PREFIX}/%s' % (ctx.path.name),
407                      output_node.ant_glob('**/*', quiet = True),
408                      cwd = output_node,
409                      relative_trick = True,
410                      quiet = True)
411
412def images_plantuml(ctx, source_dir, conf_dir, ext):
413    #
414    # Use a run command to handle stdout and stderr output from puml.
415    #
416    def run(task):
417        src = task.inputs[0].abspath()
418        tgt = task.outputs[0].abspath()
419        cmd = '%s generate %s -o %s' % (task.env.BIN_PUML[0], src, tgt)
420        so = open(tgt + '.out', 'w')
421        r = task.exec_command(cmd, stdout = so, stderr = so)
422        so.close()
423        return r
424
425    for src in ctx.path.ant_glob('**/*' + ext):
426        tgt = src.change_ext('.png')
427        ctx(
428            rule         = run,
429            inliner      = ctx.env.BIN_PUML,
430            source       = src,
431            target       = tgt,
432            install_path = None
433        )
434
435def cmd_build(ctx, sources = {}):
436    conf_dir = ctx.path.get_src()
437    source_dir = ctx.path.get_src()
438
439    if ctx.env.BUILD_PDF == 'yes':
440        doc_pdf(ctx, source_dir, conf_dir, sources)
441
442    if ctx.env.BUILD_SINGLEHTML == 'yes':
443        doc_singlehtml(ctx, source_dir, conf_dir, sources)
444
445    doc_html(ctx, source_dir, conf_dir, sources)
446
447def cmd_build_images(ctx):
448    conf_dir = ctx.path.get_src()
449    source_dir = ctx.path.get_src()
450    if ctx.env.BUILD_PLANTUML == 'yes':
451        images_plantuml(ctx, source_dir, conf_dir, '.puml')
452    if ctx.env.BUILD_DITAA == 'yes':
453        images_plantuml(ctx, source_dir, conf_dir, '.ditaa')
454
455def cmd_options(ctx):
456    ctx.add_option('--disable-extra-fonts',
457                   action = 'store_true',
458                   default = False,
459                   help = "Disable building with extra fonts for better quality (lower quality).")
460    ctx.add_option('--sphinx-options',
461                   action = 'store',
462                   default = "",
463                   help = "Additional Sphinx options.")
464    ctx.add_option('--sphinx-nit-pick',
465                   action = 'store_true',
466                   default = False,
467                   help = "Enable Sphinx nit-picky mode else be quiet")
468    ctx.add_option('--pdf',
469                   action = 'store_true',
470                   default = False,
471                   help = "Build PDF.")
472    ctx.add_option('--singlehtml',
473                   action = 'store_true',
474                   default = False,
475                   help = "Build Single HTML file, requires Node Inliner")
476    ctx.add_option('--plantuml',
477                   action = 'store_true',
478                   default = False,
479                   help = "Build PlantUML images from source, need puml from npm")
480    ctx.add_option('--ditaa',
481                   action = 'store_true',
482                   default = False,
483                   help = "Build DITAA images using PlantUML from source, need ditaa and puml")
484
485def cmd_options_path(ctx):
486    cmd_options(ctx)
487    ctx.add_option('--rtems-path-py',
488                   type = 'string',
489                   help = "Full path to py/ in RTEMS source repository.")
490
491def cmd_configure_path(ctx):
492    if not ctx.options.rtems_path_py:
493        ctx.fatal("--rtems-path-py is required")
494
495    ctx.env.RTEMS_PATH = ctx.options.rtems_path_py
496
497    cmd_configure(ctx)
498
499def xml_catalogue(ctx, building):
500    #
501    # The following is a hack to find the top_dir because the task does
502    # provided a reference to top_dir like a build context.
503    #
504    top_dir = ctx.get_cwd().find_node('..')
505    #
506    # Read the conf.py files in each directory to gather the doc details.
507    #
508    catalogue = {}
509    sp = sys.path[:]
510    for doc in building:
511        #
512        # Import using the imp API so the module is reloaded for us.
513        #
514        import imp
515        sys.path = [top_dir.find_node(doc).abspath()]
516        mf = imp.find_module('conf')
517        sys.path = sp[:]
518        try:
519            bconf = imp.load_module('bconf', mf[0], mf[1], mf[2])
520        finally:
521            mf[0].close()
522        catalogue[doc] = {
523            'title': bconf.project,
524            'version': str(ctx.env.VERSION),
525            'release': str(ctx.env.VERSION),
526            'pdf': bconf.latex_documents[0][1].replace('.tex', '.pdf'),
527            'html': '%s/index.html' % (doc),
528            'singlehtml': '%s.html' % (doc)
529        }
530        bconf = None
531
532    import xml.dom.minidom as xml
533    cat = xml.Document()
534
535    root = cat.createElement('rtems-docs')
536    root.setAttribute('date', ctx.env.DATE)
537    cat.appendChild(root)
538
539    heading = cat.createElement('catalogue')
540    text = cat.createTextNode(str(ctx.env.VERSION))
541    heading.appendChild(text)
542    root.appendChild(heading)
543
544    builds = ['html']
545    if ctx.env.BUILD_PDF == 'yes':
546        builds += ['pdf']
547    if ctx.env.BUILD_SINGLEHTML == 'yes':
548        builds += ['singlehtml']
549
550    for d in building:
551        doc = cat.createElement('doc')
552        name = cat.createElement('name')
553        text = cat.createTextNode(d)
554        name.appendChild(text)
555        title = cat.createElement('title')
556        text = cat.createTextNode(catalogue[d]['title'])
557        title.appendChild(text)
558        release = cat.createElement('release')
559        text = cat.createTextNode(catalogue[d]['release'])
560        release.appendChild(text)
561        version = cat.createElement('version')
562        text = cat.createTextNode(catalogue[d]['version'])
563        version.appendChild(text)
564        doc.appendChild(name)
565        doc.appendChild(title)
566        doc.appendChild(release)
567        doc.appendChild(version)
568        for b in builds:
569            output = cat.createElement(b)
570            text = cat.createTextNode(catalogue[d][b])
571            output.appendChild(text)
572            doc.appendChild(output)
573        root.appendChild(doc)
574
575    catnode = ctx.get_cwd().make_node('catalogue.xml')
576    catnode.write(cat.toprettyxml(indent = ' ' * 2, newl = os.linesep))
577
578    cat.unlink()
Note: See TracBrowser for help on using the repository browser.