1#!/usr/bin/env python3
2# pylint: disable=C0112,C0114,C0115,C0116,C0301,R0903
3# -*- Python -*- See copyright, etc below
4######################################################################
5
6import argparse
7import os
8import re
9
10#######################################################################
11
12
13class VlSphinxFix:
14    debug = 0
15    SkipBasenames = {}
16
17    def process(self, path):
18        if os.path.isdir(path):
19            for basefile in os.listdir(path):
20                file = os.path.join(path, basefile)
21                if ((basefile != ".") and (basefile != "..")
22                        and basefile not in self.SkipBasenames
23                        and not os.path.islink(file)):
24                    self.process(file)
25        elif re.search(r'\.(html|tex)$', path):
26            self._edit(path)
27
28    def _edit(self, filename):
29        is_html = re.search(r'\.(html)$', filename)
30        with open(filename) as fhr:
31            origfile = fhr.read()
32            wholefile = origfile
33            # Option doesn't like spaces, so we use
34            # :option:`/*verilator&32;metacomment*/`
35            wholefile = re.sub(r'verilator-32-', r'verilator-', wholefile)
36            if is_html:
37                wholefile = re.sub(r'&32;', r' ', wholefile)
38                wholefile = re.sub(r'&96;', r'`', wholefile)
39            else:
40                wholefile = re.sub(r'&32;', r' ', wholefile)
41                wholefile = re.sub(r'&96;', r'`', wholefile)
42            if wholefile != origfile:
43                if self.debug:
44                    print("Edit %s" % filename)
45                tempname = filename + ".tmp"
46                with open(tempname, "w") as fhw:
47                    fhw.write(wholefile)
48                os.rename(tempname, filename)
49
50
51#######################################################################
52
53parser = argparse.ArgumentParser(
54    allow_abbrev=False,
55    formatter_class=argparse.RawDescriptionHelpFormatter,
56    description="""Post-process Sphinx HTML.""",
57    epilog=
58    """ Copyright 2021-2021 by Wilson Snyder.  This package is free software;
59you can redistribute it and/or modify it under the terms of either the GNU
60Lesser General Public License Version 3 or the Perl Artistic License
61Version 2.0.
62
63SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0""")
64
65parser.add_argument('--debug',
66                    action='store_const',
67                    const=9,
68                    help='enable debug')
69parser.add_argument('path', help='path to edit')
70Args = parser.parse_args()
71
72o = VlSphinxFix()
73o.debug = Args.debug
74o.process(Args.path)
75
76######################################################################
77# Local Variables:
78# compile-command: "./vl_sphinx_fix --debug _build"
79# End:
80