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

5
Last change on this file since bb13624 was 859096b, checked in by Chris Johns <chrisj@…>, on 08/21/18 at 04:54:41

waf: Fix type in single html build.

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