File: buildhtml.py

package info (click to toggle)
python-docutils 0.22%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 11,448 kB
  • sloc: python: 53,302; lisp: 14,475; xml: 1,807; javascript: 1,032; makefile: 102; sh: 96
file content (354 lines) | stat: -rwxr-xr-x 13,854 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python3

# $Id: buildhtml.py 10045 2025-03-09 01:02:23Z aa-turner $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.

"""
Generate .html from all reStructuredText files in a directory.

Source files are understood to be standalone reStructuredText documents.
Files with names starting ``pep-`` are interpreted as reStructuredText PEPs.
"""

from __future__ import annotations

__docformat__ = 'reStructuredText'

from pathlib import Path

try:
    import locale
    locale.setlocale(locale.LC_ALL, '')
except Exception:
    pass

import os
import os.path
import sys
import warnings
from fnmatch import fnmatch
from types import SimpleNamespace

import docutils
import docutils.io
from docutils import core, frontend, ApplicationError
from docutils.parsers import rst
from docutils.utils import relative_path
from docutils.readers import standalone, pep
from docutils.writers import html4css1, html5_polyglot, pep_html

TYPE_CHECKING = False
if TYPE_CHECKING:
    from typing import Literal

    from docutils.frontend import Values

usage = '%prog [options] [<directory> ...]'
description = ('Generate .html from all reStructuredText files '
               'in each <directory> (default is the current directory).')


class SettingsSpec(docutils.SettingsSpec):

    """
    Runtime settings & command-line options for the "buildhtml" front end.
    """

    prune_default = ['/*/.hg', '/*/.bzr', '/*/.git', '/*/.svn',
                     '/*/.venv', '/*/__pycache__']
    sources_default = ['*.rst', '*.txt']

    # Can't be included in OptionParser below because we don't want to
    # override the base class.
    settings_spec = (
        'Build-HTML Options',
        None,
        (('Process all files matching any of the given '
          'glob-style patterns (separated by colons). '
          'This option overwrites the default or config-file values. '
          f'Default: "{":".join(sources_default)}".',
          ['--sources'],
          {'metavar': '<patterns>',
           'default': sources_default,
           'validator': frontend.validate_colon_separated_string_list}),
         ('Recursively ignore files matching any of the given '
          'glob-style patterns (separated by colons). '
          'This option may be used more than once to add more patterns.',
          ['--ignore'],
          {'metavar': '<patterns>', 'action': 'append',
           'default': [],
           'validator': frontend.validate_colon_separated_string_list}),
         ('Do not scan subdirectories for files to process.',
          ['--local'], {'dest': 'recurse', 'action': 'store_false'}),
         ('Recursively scan subdirectories for files to process.  This is '
          'the default.',
          ['--recurse'],
          {'action': 'store_true', 'default': 1,
           'validator': frontend.validate_boolean}),
         ('Do not process files in <directory> (glob-style patterns, '
          'separated by colons).  This option may be used '
          'more than once to add more patterns.  Default: "%s".'
          % ':'.join(prune_default),
          ['--prune'],
          {'metavar': '<directory>', 'action': 'append',
           'validator': frontend.validate_colon_separated_string_list,
           'default': prune_default}),
         ('Docutils writer, one of "html", "html4", "html5". '
          'Default: "html" (use Docutils\' default HTML writer).',
          ['--writer'],
          {'metavar': '<writer>',
           'choices': ['html', 'html4', 'html5'],
           # 'default': 'html' (set below)
           }),
         (frontend.SUPPRESS_HELP,  # Obsoleted by "--writer"
          ['--html-writer'],
          {'metavar': '<writer>',
           'choices': ['html', 'html4', 'html5']}),
         ('Work silently (no progress messages).  Independent of "--quiet".',
          ['--silent'],
          {'action': 'store_true', 'validator': frontend.validate_boolean}),
         ('Do not process files, show files that would be processed.',
          ['--dry-run'],
          {'action': 'store_true', 'validator': frontend.validate_boolean}),))

    relative_path_settings = ('prune',)
    config_section = 'buildhtml application'
    config_section_dependencies = ('applications',)


class OptionParser(frontend.OptionParser):

    """
    Command-line option processing for the ``buildhtml.py`` front end.
    """

    def check_values(self, values: Values, args: list[str]) -> Values:
        super().check_values(values, args)
        values._source = None
        return values

    def check_args(self, args: list[str]) -> tuple[None, None]:
        self.values._directories = args or [os.getcwd()]
        # backwards compatibility:
        return None, None


class Struct(SimpleNamespace):
    components: tuple[docutils.SettingsSpec, ...]
    reader: str
    writer: str
    option_parser: OptionParser
    setting_defaults: Values
    config_settings: Values


class Builder:
    publishers: dict[str, Struct] = {
        '': Struct(
            components=(
                pep.Reader, rst.Parser, pep_html.Writer, SettingsSpec,
            ),
        ),
        'html4': Struct(
            components=(
                rst.Parser, standalone.Reader, html4css1.Writer, SettingsSpec,
            ),
            reader='standalone',
            writer='html4',
        ),
        'html5': Struct(
            components=(
                rst.Parser, standalone.Reader, html5_polyglot.Writer,
                SettingsSpec,
            ),
            reader='standalone',
            writer='html5',
        ),
        'PEPs': Struct(
            components=(
                rst.Parser, pep.Reader, pep_html.Writer, SettingsSpec,
            ),
            reader='pep',
            writer='pep_html',
        ),
    }
    """Publisher-specific settings.  Key '' is for the front-end script
    itself.  ``self.publishers[''].components`` must contain a superset of
    all components used by individual publishers."""

    def __init__(self) -> None:
        self.publishers = self.publishers.copy()
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            self.settings_spec = frontend.Values()
            self.initial_settings = frontend.Values()
        self.directories = []

        self.setup_publishers()
        # default html writer (may change to html5 some time):
        self.publishers['html'] = self.publishers['html4']

    def setup_publishers(self) -> None:
        """
        Manage configurations for individual publishers.

        Each publisher (combination of parser, reader, and writer) may have
        its own configuration defaults, which must be kept separate from those
        of the other publishers.  Setting defaults are combined with the
        config file settings and command-line options by
        `self.get_settings()`.
        """
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            for publisher in self.publishers.values():
                option_parser = OptionParser(
                    components=publisher.components, read_config_files=True,
                    usage=usage, description=description)
                publisher.option_parser = option_parser
                publisher.setting_defaults = option_parser.get_default_values()
                frontend.make_paths_absolute(
                    publisher.setting_defaults.__dict__,
                    list(option_parser.relative_path_settings))
                publisher.config_settings = (
                    option_parser.get_standard_config_settings())
            self.settings_spec = self.publishers[''].option_parser.parse_args(
                values=frontend.Values())  # no defaults; just the cmdline opts
            self.initial_settings = self.get_settings('')

        if self.initial_settings.html_writer is not None:
            warnings.warn('The configuration setting "html_writer" '
                          'will be removed in Docutils 2.0. '
                          'Use setting "writer" instead.',
                          FutureWarning, stacklevel=5)
        if self.initial_settings.writer is None:
            self.initial_settings.writer = (self.initial_settings.html_writer
                                            or 'html')

    def get_settings(
        self,
        publisher_name: Literal['', 'html', 'html5', 'html4', 'PEPs'],
        directory: str | os.PathLike[str] | None = None,
    ) -> Values:
        """
        Return a settings object, from multiple sources.

        Copy the setting defaults, overlay the startup config file settings,
        then the local config file settings, then the command-line options.

        If `directory` is not None, it is searched for a file "docutils.conf"
        which is parsed after standard configuration files.
        Path settings in this configuration file are resolved relative
        to `directory`, not the current working directory.
        """
        publisher = self.publishers[publisher_name]
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            settings = frontend.Values(publisher.setting_defaults.__dict__)
        settings.update(publisher.config_settings, publisher.option_parser)
        if directory:
            local_config = publisher.option_parser.get_config_file_settings(
                os.path.join(directory, 'docutils.conf'))
            frontend.make_paths_absolute(
                local_config,
                list(publisher.option_parser.relative_path_settings),
                directory)
            settings.update(local_config, publisher.option_parser)
        settings.update(self.settings_spec.__dict__, publisher.option_parser)
        # remove duplicate entries from "appending" settings:
        settings.ignore = list(set(settings.ignore))
        settings.prune = list(set(settings.prune))
        return settings

    def run(
        self,
        directory: str | os.PathLike[str] | None = None,
        recurse: bool = True,
    ) -> None:
        recurse = recurse and self.initial_settings.recurse
        if directory:
            self.directories = [directory]
        elif self.settings_spec._directories:
            self.directories = self.settings_spec._directories
        else:
            self.directories = [os.getcwd()]
        for directory in self.directories:
            dir_abs = Path(directory).resolve()
            for dirpath, dirnames, filenames in os.walk(dir_abs):
                # `os.walk()` by default recurses down the tree,
                # we modify `dirnames` in-place to control the behaviour.
                if recurse:
                    dirnames.sort()
                else:
                    del dirnames[:]
                self.visit(Path(dirpath), dirnames, filenames)

    def visit(
        self,
        dirpath: Path,
        dirnames: list[str],
        filenames: list[str],
    ) -> None:
        settings = self.get_settings('', dirpath)
        errout = docutils.io.ErrorOutput(encoding=settings.error_encoding)
        if match_patterns(dirpath, settings.prune):
            errout.write('/// ...Skipping directory (pruned): %s\n'
                         % relative_path(None, dirpath))
            sys.stderr.flush()
            dirnames.clear()  # modify in-place to control `os.walk()` run
            return
        if not self.initial_settings.silent:
            errout.write('/// Processing directory: %s\n'
                         % relative_path(None, dirpath))
            sys.stderr.flush()
        for name in sorted(filenames):
            if match_patterns(name, settings.ignore):
                continue
            if match_patterns(name, settings.sources):
                self.process_rst_source_file(dirpath, name)

    def process_rst_source_file(self, directory: Path, name: str) -> None:
        if name.startswith('pep-'):
            publisher = 'PEPs'
        else:
            publisher = self.initial_settings.writer
        settings = self.get_settings(publisher, directory)
        errout = docutils.io.ErrorOutput(encoding=settings.error_encoding)
        pub_struct = self.publishers[publisher]
        settings._source = str(directory / name)
        settings._destination = os.path.splitext(settings._source)[0] + '.html'
        if not self.initial_settings.silent:
            errout.write('    ::: Processing: %s\n' % name)
            sys.stderr.flush()
        if not settings.dry_run:
            try:
                core.publish_file(source_path=settings._source,
                                  destination_path=settings._destination,
                                  reader=pub_struct.reader,
                                  parser='restructuredtext',
                                  writer=pub_struct.writer,
                                  settings=settings)
            except ApplicationError as err:
                errout.write(f'        {type(err).__name__}: {err}\n')


def match_patterns(name: str | os.PathLike[str], patterns: str) -> bool:
    """Return True, if `name` matches any item of the sequence `patterns`.

    Matching is done with `fnmatch.fnmatch`. It resembles shell-style
    globbing, but without special treatment of path separators and '.'
    (in contrast to the `glob module` and `pathlib.PurePath.match()`).
    For example, "``/*.py``" matches "/a/b/c.py".

    PROVISIONAL.
    TODO: use `pathlib.PurePath.match()` once this supports "**".
    """
    name = os.fspath(name)
    for pattern in patterns:
        if fnmatch(name, pattern):
            return True
    return False


if __name__ == "__main__":
    Builder().run()