| 1 |
# $Id: frontend.py 10294 2026-01-25 14:12:56Z milde $ |
| 2 |
# Author: David Goodger <[email protected]> |
| 3 |
# Copyright: This module has been placed in the public domain. |
| 4 |
|
| 5 |
""" |
| 6 |
Command-line and common processing for Docutils front-end tools. |
| 7 |
|
| 8 |
This module is provisional. |
| 9 |
Major changes will happen with the transition from the |
| 10 |
"optparse" module to "arparse" in Docutils 2.0 or later. |
| 11 |
|
| 12 |
Applications should use the high-level API provided by `docutils.core`. |
| 13 |
See https://docutils.sourceforge.io/docs/api/runtime-settings.html. |
| 14 |
|
| 15 |
Exports the following classes: |
| 16 |
|
| 17 |
* `OptionParser`: Standard Docutils command-line processing. |
| 18 |
Deprecated. Will be replaced by an ArgumentParser. |
| 19 |
* `Option`: Customized version of `optparse.Option`; validation support. |
| 20 |
Deprecated. Will be removed. |
| 21 |
* `Values`: Runtime settings; objects are simple structs |
| 22 |
(``object.attribute``). Supports cumulative list settings (attributes). |
| 23 |
Deprecated. Will be removed. |
| 24 |
* `ConfigParser`: Standard Docutils config file processing. |
| 25 |
Provisional. Details will change. |
| 26 |
|
| 27 |
Also exports the following functions: |
| 28 |
|
| 29 |
Interface function: |
| 30 |
`get_default_settings()`. New in 0.19. |
| 31 |
|
| 32 |
Option callbacks: |
| 33 |
`store_multiple()`, `read_config_file()`. Deprecated. To be removed. |
| 34 |
|
| 35 |
Setting validators: |
| 36 |
`validate_encoding()`, `validate_encoding_error_handler()`, |
| 37 |
`validate_encoding_and_error_handler()`, |
| 38 |
`validate_boolean()`, `validate_ternary()`, |
| 39 |
`validate_nonnegative_int()`, `validate_threshold()`, |
| 40 |
`validate_colon_separated_string_list()`, |
| 41 |
`validate_comma_separated_list()`, |
| 42 |
`validate_url_trailing_slash()`, |
| 43 |
`validate_dependency_file()`, |
| 44 |
`validate_strip_class()` |
| 45 |
`validate_smartquotes_locales()`. |
| 46 |
|
| 47 |
Provisional. |
| 48 |
|
| 49 |
Misc: |
| 50 |
`make_paths_absolute()`, `filter_settings_spec()`. Provisional. |
| 51 |
""" |
| 52 |
|
| 53 |
from __future__ import annotations |
| 54 |
|
| 55 |
__docformat__ = 'reStructuredText' |
| 56 |
|
| 57 |
|
| 58 |
import codecs |
| 59 |
import configparser |
| 60 |
import optparse |
| 61 |
import os |
| 62 |
import os.path |
| 63 |
import sys |
| 64 |
import warnings |
| 65 |
from optparse import SUPPRESS_HELP |
| 66 |
from pathlib import Path |
| 67 |
|
| 68 |
import docutils |
| 69 |
from docutils import io, utils |
| 70 |
|
| 71 |
TYPE_CHECKING = False |
| 72 |
if TYPE_CHECKING: |
| 73 |
from collections.abc import Iterable, Mapping, Sequence |
| 74 |
from typing import Any, ClassVar, Literal, Protocol |
| 75 |
|
| 76 |
from docutils import SettingsSpec, _OptionTuple, _SettingsSpecTuple |
| 77 |
from docutils.io import StrPath |
| 78 |
|
| 79 |
class _OptionValidator(Protocol): |
| 80 |
def __call__( |
| 81 |
self, |
| 82 |
setting: str, |
| 83 |
value: str | None, |
| 84 |
option_parser: OptionParser, |
| 85 |
/, |
| 86 |
config_parser: ConfigParser | None = None, |
| 87 |
config_section: str | None = None, |
| 88 |
) -> Any: |
| 89 |
... |
| 90 |
|
| 91 |
|
| 92 |
def store_multiple(option: optparse.Option, |
| 93 |
opt: str, |
| 94 |
value: Any, |
| 95 |
parser: OptionParser, |
| 96 |
*args: str, |
| 97 |
**kwargs: Any, |
| 98 |
) -> None: |
| 99 |
""" |
| 100 |
Store multiple values in `parser.values`. (Option callback.) |
| 101 |
|
| 102 |
Store `None` for each attribute named in `args`, and store the value for |
| 103 |
each key (attribute name) in `kwargs`. |
| 104 |
|
| 105 |
Deprecated. Will be removed with the switch to from optparse to argparse. |
| 106 |
""" |
| 107 |
for attribute in args: |
| 108 |
setattr(parser.values, attribute, None) |
| 109 |
for key, value in kwargs.items(): |
| 110 |
setattr(parser.values, key, value) |
| 111 |
|
| 112 |
|
| 113 |
def read_config_file(option: optparse.Option, |
| 114 |
opt: str, |
| 115 |
value: Any, |
| 116 |
parser: OptionParser, |
| 117 |
) -> None: |
| 118 |
""" |
| 119 |
Read a configuration file during option processing. (Option callback.) |
| 120 |
|
| 121 |
Deprecated. Will be removed with the switch to from optparse to argparse. |
| 122 |
""" |
| 123 |
try: |
| 124 |
new_settings = parser.get_config_file_settings(value) |
| 125 |
except ValueError as err: |
| 126 |
parser.error(err) |
| 127 |
parser.values.update(new_settings, parser) |
| 128 |
|
| 129 |
|
| 130 |
def validate_encoding(setting: str, |
| 131 |
value: str | None = None, |
| 132 |
option_parser: OptionParser | None = None, |
| 133 |
config_parser: ConfigParser | None = None, |
| 134 |
config_section: str | None = None, |
| 135 |
) -> str | None: |
| 136 |
# All arguments except `value` are ignored |
| 137 |
# (kept for compatibility with "optparse" module). |
| 138 |
# If there is only one positional argument, it is interpreted as `value`. |
| 139 |
if value is None: |
| 140 |
value = setting |
| 141 |
if value == '': |
| 142 |
warnings.warn('Input encoding detection will be removed and the ' |
| 143 |
'special encoding values None and "" become invalid ' |
| 144 |
'in Docutils 1.0.', FutureWarning, stacklevel=2) |
| 145 |
return None |
| 146 |
try: |
| 147 |
codecs.lookup(value) |
| 148 |
except LookupError: |
| 149 |
prefix = f'setting "{setting}":' if setting else '' |
| 150 |
raise LookupError(f'{prefix} unknown encoding: "{value}"') |
| 151 |
return value |
| 152 |
|
| 153 |
|
| 154 |
def validate_encoding_error_handler( |
| 155 |
setting: str, |
| 156 |
value: str | None = None, |
| 157 |
option_parser: OptionParser | None = None, |
| 158 |
config_parser: ConfigParser | None = None, |
| 159 |
config_section: str | None = None, |
| 160 |
) -> str: |
| 161 |
# All arguments except `value` are ignored |
| 162 |
# (kept for compatibility with "optparse" module). |
| 163 |
# If there is only one positional argument, it is interpreted as `value`. |
| 164 |
if value is None: |
| 165 |
value = setting |
| 166 |
try: |
| 167 |
codecs.lookup_error(value) |
| 168 |
except LookupError: |
| 169 |
raise LookupError( |
| 170 |
'unknown encoding error handler: "%s" (choices: ' |
| 171 |
'"strict", "ignore", "replace", "backslashreplace", ' |
| 172 |
'"xmlcharrefreplace", and possibly others; see documentation for ' |
| 173 |
'the Python ``codecs`` module)' % value) |
| 174 |
return value |
| 175 |
|
| 176 |
|
| 177 |
def validate_encoding_and_error_handler( |
| 178 |
setting: str, |
| 179 |
value: str | None = None, |
| 180 |
option_parser: OptionParser | None = None, |
| 181 |
config_parser: ConfigParser | None = None, |
| 182 |
config_section: str | None = None, |
| 183 |
) -> str: |
| 184 |
"""Check/normalize encoding settings |
| 185 |
|
| 186 |
Side-effect: if an error handler is included in the value, it is inserted |
| 187 |
into the appropriate place as if it were a separate setting/option. |
| 188 |
|
| 189 |
All arguments except `value` are ignored |
| 190 |
(kept for compatibility with "optparse" module). |
| 191 |
If there is only one positional argument, it is interpreted as `value`. |
| 192 |
""" |
| 193 |
if ':' in value: |
| 194 |
encoding, handler = value.split(':') |
| 195 |
validate_encoding_error_handler(handler) |
| 196 |
if config_parser: |
| 197 |
config_parser.set(config_section, setting + '_error_handler', |
| 198 |
handler) |
| 199 |
else: |
| 200 |
setattr(option_parser.values, setting + '_error_handler', handler) |
| 201 |
else: |
| 202 |
encoding = value |
| 203 |
return validate_encoding(encoding) |
| 204 |
|
| 205 |
|
| 206 |
def validate_boolean(setting: str | bool, |
| 207 |
value: str | None = None, |
| 208 |
option_parser: OptionParser | None = None, |
| 209 |
config_parser: ConfigParser | None = None, |
| 210 |
config_section: str | None = None, |
| 211 |
) -> bool: |
| 212 |
"""Check/normalize boolean settings: |
| 213 |
|
| 214 |
:True: '1', 'on', 'yes', 'true' |
| 215 |
:False: '0', 'off', 'no','false', '' |
| 216 |
|
| 217 |
All arguments except `value` are ignored |
| 218 |
(kept for compatibility with "optparse" module). |
| 219 |
If there is only one positional argument, it is interpreted as `value`. |
| 220 |
""" |
| 221 |
if value is None: |
| 222 |
value = setting |
| 223 |
if isinstance(value, bool): |
| 224 |
return value |
| 225 |
try: |
| 226 |
return OptionParser.booleans[value.strip().lower()] |
| 227 |
except KeyError: |
| 228 |
raise LookupError('unknown boolean value: "%s"' % value) |
| 229 |
|
| 230 |
|
| 231 |
def validate_ternary(setting: str | bool, |
| 232 |
value: str | None = None, |
| 233 |
option_parser: OptionParser | None = None, |
| 234 |
config_parser: ConfigParser | None = None, |
| 235 |
config_section: str | None = None, |
| 236 |
) -> str | bool | None: |
| 237 |
"""Check/normalize three-value settings: |
| 238 |
|
| 239 |
:True: '1', 'on', 'yes', 'true' |
| 240 |
:False: '0', 'off', 'no','false', '' |
| 241 |
:any other value: returned as-is. |
| 242 |
|
| 243 |
All arguments except `value` are ignored |
| 244 |
(kept for compatibility with "optparse" module). |
| 245 |
If there is only one positional argument, it is interpreted as `value`. |
| 246 |
""" |
| 247 |
if value is None: |
| 248 |
value = setting |
| 249 |
if isinstance(value, bool) or value is None: |
| 250 |
return value |
| 251 |
try: |
| 252 |
return OptionParser.booleans[value.strip().lower()] |
| 253 |
except KeyError: |
| 254 |
return value |
| 255 |
|
| 256 |
|
| 257 |
def validate_nonnegative_int(setting: str | int, |
| 258 |
value: str | None = None, |
| 259 |
option_parser: OptionParser | None = None, |
| 260 |
config_parser: ConfigParser | None = None, |
| 261 |
config_section: str | None = None, |
| 262 |
) -> int: |
| 263 |
# All arguments except `value` are ignored |
| 264 |
# (kept for compatibility with "optparse" module). |
| 265 |
# If there is only one positional argument, it is interpreted as `value`. |
| 266 |
if value is None: |
| 267 |
value = setting |
| 268 |
value = int(value) |
| 269 |
if value < 0: |
| 270 |
raise ValueError('negative value; must be positive or zero') |
| 271 |
return value |
| 272 |
|
| 273 |
|
| 274 |
def validate_threshold(setting: str | int, |
| 275 |
value: str | None = None, |
| 276 |
option_parser: OptionParser | None = None, |
| 277 |
config_parser: ConfigParser | None = None, |
| 278 |
config_section: str | None = None, |
| 279 |
) -> int: |
| 280 |
# All arguments except `value` are ignored |
| 281 |
# (kept for compatibility with "optparse" module). |
| 282 |
# If there is only one positional argument, it is interpreted as `value`. |
| 283 |
if value is None: |
| 284 |
value = setting |
| 285 |
try: |
| 286 |
return int(value) |
| 287 |
except ValueError: |
| 288 |
try: |
| 289 |
return OptionParser.thresholds[value.lower()] |
| 290 |
except (KeyError, AttributeError): |
| 291 |
raise LookupError('unknown threshold: %r.' % value) |
| 292 |
|
| 293 |
|
| 294 |
def validate_colon_separated_string_list( |
| 295 |
setting: str | list[str], |
| 296 |
value: str | None = None, |
| 297 |
option_parser: OptionParser | None = None, |
| 298 |
config_parser: ConfigParser | None = None, |
| 299 |
config_section: str | None = None, |
| 300 |
) -> list[str]: |
| 301 |
# All arguments except `value` are ignored |
| 302 |
# (kept for compatibility with "optparse" module). |
| 303 |
# If there is only one positional argument, it is interpreted as `value`. |
| 304 |
if value is None: |
| 305 |
value = setting |
| 306 |
if not isinstance(value, list): |
| 307 |
value = value.split(':') |
| 308 |
else: |
| 309 |
last = value.pop() |
| 310 |
value.extend(last.split(':')) |
| 311 |
return value |
| 312 |
|
| 313 |
|
| 314 |
def validate_comma_separated_list( |
| 315 |
setting: str | list[str], |
| 316 |
value: str | None = None, |
| 317 |
option_parser: OptionParser | None = None, |
| 318 |
config_parser: ConfigParser | None = None, |
| 319 |
config_section: str | None = None, |
| 320 |
) -> list[str]: |
| 321 |
"""Check/normalize list arguments (split at "," and strip whitespace). |
| 322 |
|
| 323 |
All arguments except `value` are ignored |
| 324 |
(kept for compatibility with "optparse" module). |
| 325 |
If there is only one positional argument, it is interpreted as `value`. |
| 326 |
""" |
| 327 |
if value is None: |
| 328 |
value = setting |
| 329 |
# `value` may be ``bytes``, ``str``, or a ``list`` (when given as |
| 330 |
# command line option and "action" is "append"). |
| 331 |
if not isinstance(value, list): |
| 332 |
value = [value] |
| 333 |
# this function is called for every option added to `value` |
| 334 |
# -> split the last item and append the result: |
| 335 |
last = value.pop() |
| 336 |
items = [i.strip(' \t\n') for i in last.split(',') if i.strip(' \t\n')] |
| 337 |
value.extend(items) |
| 338 |
return value |
| 339 |
|
| 340 |
|
| 341 |
def validate_math_output(setting: str, |
| 342 |
value: str | None = None, |
| 343 |
option_parser: OptionParser | None = None, |
| 344 |
config_parser: ConfigParser | None = None, |
| 345 |
config_section: str | None = None, |
| 346 |
) -> tuple[()] | tuple[str, str]: |
| 347 |
"""Check "math-output" setting, return list with "format" and "options". |
| 348 |
|
| 349 |
See also https://docutils.sourceforge.io/docs/user/config.html#math-output |
| 350 |
|
| 351 |
Argument list for compatibility with "optparse" module. |
| 352 |
All arguments except `value` are ignored. |
| 353 |
If there is only one positional argument, it is interpreted as `value`. |
| 354 |
""" |
| 355 |
if value is None: |
| 356 |
value = setting |
| 357 |
|
| 358 |
formats = ('html', 'latex', 'mathml', 'mathjax') |
| 359 |
tex2mathml_converters = ('', 'latexml', 'ttm', 'blahtexml', 'pandoc') |
| 360 |
|
| 361 |
if not value: |
| 362 |
return () |
| 363 |
values = value.split(maxsplit=1) |
| 364 |
format = values[0].lower() |
| 365 |
try: |
| 366 |
options = values[1] |
| 367 |
except IndexError: |
| 368 |
options = '' |
| 369 |
if format not in formats: |
| 370 |
raise LookupError(f'Unknown math output format: "{value}",\n' |
| 371 |
f' choose from {formats}.') |
| 372 |
if format == 'mathml': |
| 373 |
converter = options.lower() |
| 374 |
if converter not in tex2mathml_converters: |
| 375 |
raise LookupError(f'MathML converter "{options}" not supported,\n' |
| 376 |
f' choose from {tex2mathml_converters}.') |
| 377 |
options = converter |
| 378 |
return format, options |
| 379 |
|
| 380 |
|
| 381 |
def validate_url_trailing_slash(setting: str | None, |
| 382 |
value: str | None = None, |
| 383 |
option_parser: OptionParser | None = None, |
| 384 |
config_parser: ConfigParser | None = None, |
| 385 |
config_section: str | None = None, |
| 386 |
) -> str: |
| 387 |
# All arguments except `value` are ignored |
| 388 |
# (kept for compatibility with "optparse" module). |
| 389 |
# If there is only one positional argument, it is interpreted as `value`. |
| 390 |
if value is None: |
| 391 |
value = setting |
| 392 |
if not value: |
| 393 |
return './' |
| 394 |
elif value.endswith('/'): |
| 395 |
return value |
| 396 |
else: |
| 397 |
return value + '/' |
| 398 |
|
| 399 |
|
| 400 |
def validate_dependency_file(setting: str | None, |
| 401 |
value: str | None = None, |
| 402 |
option_parser: OptionParser | None = None, |
| 403 |
config_parser: ConfigParser | None = None, |
| 404 |
config_section: str | None = None, |
| 405 |
) -> utils.DependencyList: |
| 406 |
# All arguments except `value` are ignored |
| 407 |
# (kept for compatibility with "optparse" module). |
| 408 |
# If there is only one positional argument, it is interpreted as `value`. |
| 409 |
if value is None: |
| 410 |
value = setting |
| 411 |
try: |
| 412 |
return utils.DependencyList(value) |
| 413 |
except OSError: |
| 414 |
# TODO: warn/info? |
| 415 |
return utils.DependencyList(None) |
| 416 |
|
| 417 |
|
| 418 |
def validate_strip_class(setting: str, |
| 419 |
value: str | None = None, |
| 420 |
option_parser: OptionParser | None = None, |
| 421 |
config_parser: ConfigParser | None = None, |
| 422 |
config_section: str | None = None, |
| 423 |
) -> list[str]: |
| 424 |
# All arguments except `value` are ignored |
| 425 |
# (kept for compatibility with "optparse" module). |
| 426 |
# If there is only one positional argument, it is interpreted as `value`. |
| 427 |
if value is None: |
| 428 |
value = setting |
| 429 |
# value is a comma separated string list: |
| 430 |
value = validate_comma_separated_list(value) |
| 431 |
# validate list elements: |
| 432 |
for cls in value: |
| 433 |
normalized = docutils.nodes.make_id(cls) |
| 434 |
if cls != normalized: |
| 435 |
raise ValueError('Invalid class value %r (perhaps %r?)' |
| 436 |
% (cls, normalized)) |
| 437 |
return value |
| 438 |
|
| 439 |
|
| 440 |
def validate_smartquotes_locales( |
| 441 |
setting: str | list[str | tuple[str, str]], |
| 442 |
value: str | None = None, |
| 443 |
option_parser: OptionParser | None = None, |
| 444 |
config_parser: ConfigParser | None = None, |
| 445 |
config_section: str | None = None, |
| 446 |
) -> list[tuple[str, Sequence[str]]]: |
| 447 |
"""Check/normalize a comma separated list of smart quote definitions. |
| 448 |
|
| 449 |
Return a list of (language-tag, quotes) string tuples. |
| 450 |
|
| 451 |
All arguments except `value` are ignored |
| 452 |
(kept for compatibility with "optparse" module). |
| 453 |
If there is only one positional argument, it is interpreted as `value`. |
| 454 |
""" |
| 455 |
if value is None: |
| 456 |
value = setting |
| 457 |
# value is a comma separated string list: |
| 458 |
value = validate_comma_separated_list(value) |
| 459 |
# validate list elements |
| 460 |
lc_quotes = [] |
| 461 |
for item in value: |
| 462 |
try: |
| 463 |
lang, quotes = item.split(':', 1) |
| 464 |
except AttributeError: |
| 465 |
# this function is called for every option added to `value` |
| 466 |
# -> ignore if already a tuple: |
| 467 |
lc_quotes.append(item) |
| 468 |
continue |
| 469 |
except ValueError: |
| 470 |
raise ValueError('Invalid value "%s".' |
| 471 |
' Format is "<language>:<quotes>".' |
| 472 |
% item.encode('ascii', 'backslashreplace')) |
| 473 |
# parse colon separated string list: |
| 474 |
quotes = quotes.strip() |
| 475 |
multichar_quotes = quotes.split(':') |
| 476 |
if len(multichar_quotes) == 4: |
| 477 |
quotes = multichar_quotes |
| 478 |
elif len(quotes) != 4: |
| 479 |
raise ValueError('Invalid value "%s". Please specify 4 quotes\n' |
| 480 |
' (primary open/close; secondary open/close).' |
| 481 |
% item.encode('ascii', 'backslashreplace')) |
| 482 |
lc_quotes.append((lang, quotes)) |
| 483 |
return lc_quotes |
| 484 |
|
| 485 |
|
| 486 |
def make_paths_absolute(pathdict: dict[str, list[StrPath] | StrPath], |
| 487 |
keys: tuple[str], |
| 488 |
base_path: StrPath | None = None, |
| 489 |
) -> None: |
| 490 |
""" |
| 491 |
Interpret filesystem path settings relative to the `base_path` given. |
| 492 |
|
| 493 |
Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from |
| 494 |
`OptionParser.relative_path_settings`. |
| 495 |
""" |
| 496 |
if base_path is None: |
| 497 |
base_path = Path.cwd() |
| 498 |
else: |
| 499 |
base_path = Path(base_path) |
| 500 |
if sys.platform == 'win32' and sys.version_info[:2] <= (3, 9): |
| 501 |
base_path = base_path.absolute() |
| 502 |
for key in keys: |
| 503 |
if key in pathdict: |
| 504 |
value = pathdict[key] |
| 505 |
if isinstance(value, (list, tuple)): |
| 506 |
value = [str((base_path/path).resolve()) for path in value] |
| 507 |
elif value: |
| 508 |
value = str((base_path/value).resolve()) |
| 509 |
pathdict[key] = value |
| 510 |
|
| 511 |
|
| 512 |
def make_one_path_absolute(base_path: StrPath, path: StrPath) -> str: |
| 513 |
# deprecated, will be removed |
| 514 |
warnings.warn('frontend.make_one_path_absolute() will be removed ' |
| 515 |
'in Docutils 2.0 or later.', |
| 516 |
DeprecationWarning, stacklevel=2) |
| 517 |
return os.path.abspath(os.path.join(base_path, path)) |
| 518 |
|
| 519 |
|
| 520 |
def filter_settings_spec(settings_spec: _SettingsSpecTuple, |
| 521 |
*exclude: str, |
| 522 |
**replace: _OptionTuple, |
| 523 |
) -> _SettingsSpecTuple: |
| 524 |
"""Return a copy of `settings_spec` excluding/replacing some settings. |
| 525 |
|
| 526 |
`settings_spec` is a tuple of configuration settings |
| 527 |
(cf. `docutils.SettingsSpec.settings_spec`). |
| 528 |
|
| 529 |
Optional positional arguments are names of to-be-excluded settings. |
| 530 |
Keyword arguments are option specification replacements. |
| 531 |
(See the html4strict writer for an example.) |
| 532 |
""" |
| 533 |
settings = list(settings_spec) |
| 534 |
# every third item is a sequence of option tuples |
| 535 |
for i in range(2, len(settings), 3): |
| 536 |
newopts: list[_OptionTuple] = [] |
| 537 |
for opt_spec in settings[i]: |
| 538 |
# opt_spec is ("<help>", [<option strings>], {<keyword args>}) |
| 539 |
opt_name = [opt_string[2:].replace('-', '_') |
| 540 |
for opt_string in opt_spec[1] |
| 541 |
if opt_string.startswith('--')][0] |
| 542 |
if opt_name in exclude: |
| 543 |
continue |
| 544 |
if opt_name in replace.keys(): |
| 545 |
newopts.append(replace[opt_name]) |
| 546 |
else: |
| 547 |
newopts.append(opt_spec) |
| 548 |
settings[i] = tuple(newopts) |
| 549 |
return tuple(settings) |
| 550 |
|
| 551 |
|
| 552 |
class Values(optparse.Values): |
| 553 |
"""Storage for option values. |
| 554 |
|
| 555 |
Updates list attributes by extension rather than by replacement. |
| 556 |
Works in conjunction with the `OptionParser.lists` instance attribute. |
| 557 |
|
| 558 |
Deprecated. Will be removed when switching to the "argparse" module. |
| 559 |
""" |
| 560 |
|
| 561 |
def __init__(self, defaults: dict[str, Any] | None = None) -> None: |
| 562 |
warnings.warn('frontend.Values class will be removed ' |
| 563 |
'in Docutils 2.0 or later.', |
| 564 |
DeprecationWarning, stacklevel=2) |
| 565 |
super().__init__(defaults=defaults) |
| 566 |
if getattr(self, 'record_dependencies', None) is None: |
| 567 |
# Set up dummy dependency list. |
| 568 |
self.record_dependencies = utils.DependencyList() |
| 569 |
|
| 570 |
def update(self, |
| 571 |
other_dict: Values | Mapping[str, Any], |
| 572 |
option_parser: OptionParser, |
| 573 |
) -> None: |
| 574 |
if isinstance(other_dict, Values): |
| 575 |
other_dict = other_dict.__dict__ |
| 576 |
other_dict = dict(other_dict) # also works with ConfigParser sections |
| 577 |
for setting in option_parser.lists.keys(): |
| 578 |
if hasattr(self, setting) and setting in other_dict: |
| 579 |
value = getattr(self, setting) |
| 580 |
if value: |
| 581 |
value += other_dict[setting] |
| 582 |
del other_dict[setting] |
| 583 |
self._update_loose(other_dict) |
| 584 |
|
| 585 |
def copy(self) -> Values: |
| 586 |
"""Return a shallow copy of `self`.""" |
| 587 |
with warnings.catch_warnings(): |
| 588 |
warnings.filterwarnings('ignore', category=DeprecationWarning) |
| 589 |
return self.__class__(defaults=self.__dict__) |
| 590 |
|
| 591 |
def setdefault(self, name: str, default: Any) -> Any: |
| 592 |
"""Return ``self.name`` or ``default``. |
| 593 |
|
| 594 |
If ``self.name`` is unset, set ``self.name = default``. |
| 595 |
""" |
| 596 |
if getattr(self, name, None) is None: |
| 597 |
setattr(self, name, default) |
| 598 |
return getattr(self, name) |
| 599 |
|
| 600 |
|
| 601 |
class Option(optparse.Option): |
| 602 |
"""Add validation and override support to `optparse.Option`. |
| 603 |
|
| 604 |
Deprecated. Will be removed. |
| 605 |
""" |
| 606 |
|
| 607 |
ATTRS = optparse.Option.ATTRS + ['validator', 'overrides'] |
| 608 |
|
| 609 |
validator: _OptionValidator |
| 610 |
overrides: str | None |
| 611 |
|
| 612 |
def __init__(self, *args: str | None, **kwargs: Any) -> None: |
| 613 |
warnings.warn('The frontend.Option class will be removed ' |
| 614 |
'in Docutils 2.0 or later.', |
| 615 |
DeprecationWarning, stacklevel=2) |
| 616 |
super().__init__(*args, **kwargs) |
| 617 |
|
| 618 |
def process(self, |
| 619 |
opt: str, |
| 620 |
value: Any, |
| 621 |
values: Values, |
| 622 |
parser: OptionParser, |
| 623 |
) -> int: |
| 624 |
""" |
| 625 |
Call the validator function on applicable settings and |
| 626 |
evaluate the 'overrides' option. |
| 627 |
Extends `optparse.Option.process`. |
| 628 |
""" |
| 629 |
result = super().process(opt, value, values, parser) |
| 630 |
setting = self.dest |
| 631 |
if setting: |
| 632 |
if self.validator: |
| 633 |
value = getattr(values, setting) |
| 634 |
try: |
| 635 |
new_value = self.validator(setting, value, parser) |
| 636 |
except Exception as err: |
| 637 |
raise optparse.OptionValueError( |
| 638 |
'Error in option "%s":\n %s' |
| 639 |
% (opt, io.error_string(err))) |
| 640 |
setattr(values, setting, new_value) |
| 641 |
if self.overrides: |
| 642 |
setattr(values, self.overrides, None) |
| 643 |
return result |
| 644 |
|
| 645 |
|
| 646 |
class OptionParser(optparse.OptionParser, docutils.SettingsSpec): |
| 647 |
""" |
| 648 |
Settings parser for command-line and library use. |
| 649 |
|
| 650 |
The `settings_spec` specification here and in other Docutils components |
| 651 |
are merged to build the set of command-line options and runtime settings |
| 652 |
for this process. |
| 653 |
|
| 654 |
Common settings (defined below) and component-specific settings must not |
| 655 |
conflict. Short options are reserved for common settings, and components |
| 656 |
are restricted to using long options. |
| 657 |
|
| 658 |
Deprecated. |
| 659 |
Will be replaced by a subclass of `argparse.ArgumentParser`. |
| 660 |
""" |
| 661 |
|
| 662 |
standard_config_files: ClassVar[list[str]] = [ |
| 663 |
'/etc/docutils.conf', # system-wide |
| 664 |
'./docutils.conf', # project-specific |
| 665 |
'~/.docutils'] # user-specific |
| 666 |
"""Docutils configuration files, using ConfigParser syntax. |
| 667 |
|
| 668 |
Filenames will be tilde-expanded later. Later files override earlier ones. |
| 669 |
""" |
| 670 |
|
| 671 |
threshold_choices: ClassVar[tuple[str]] = ( |
| 672 |
'info', '1', 'warning', '2', 'error', '3', 'severe', '4', 'none', '5') |
| 673 |
"""Possible inputs for for --report and --halt threshold values.""" |
| 674 |
|
| 675 |
thresholds: ClassVar[dict[str, int]] = { |
| 676 |
'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5} |
| 677 |
"""Lookup table for --report and --halt threshold values.""" |
| 678 |
|
| 679 |
booleans: ClassVar[dict[str, bool]] = { |
| 680 |
'1': True, 'on': True, 'yes': True, 'true': True, |
| 681 |
'0': False, 'off': False, 'no': False, 'false': False, '': False} |
| 682 |
"""Lookup table for boolean configuration file settings.""" |
| 683 |
|
| 684 |
default_error_encoding: ClassVar[str] = ( |
| 685 |
getattr(sys.stderr, 'encoding', None) |
| 686 |
or io._locale_encoding |
| 687 |
or 'ascii') |
| 688 |
|
| 689 |
default_error_encoding_error_handler: ClassVar[str] = 'backslashreplace' |
| 690 |
|
| 691 |
settings_spec = ( |
| 692 |
'General Docutils Options', |
| 693 |
None, |
| 694 |
(('Output destination name. Obsoletes the <destination> ' |
| 695 |
'positional argument. Default: None (stdout).', |
| 696 |
['--output-path', '--output'], {'metavar': '<destination>'}), |
| 697 |
('Specify the document title as metadata.', |
| 698 |
['--title'], {'metavar': '<title>'}), |
| 699 |
('Include a "Generated by Docutils" credit and link.', |
| 700 |
['--generator', '-g'], {'action': 'store_true', |
| 701 |
'validator': validate_boolean}), |
| 702 |
('Do not include a generator credit.', |
| 703 |
['--no-generator'], {'action': 'store_false', 'dest': 'generator'}), |
| 704 |
('Include the date at the end of the document (UTC).', |
| 705 |
['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d', |
| 706 |
'dest': 'datestamp'}), |
| 707 |
('Include the time & date (UTC).', |
| 708 |
['--time', '-t'], {'action': 'store_const', |
| 709 |
'const': '%Y-%m-%d %H:%M UTC', |
| 710 |
'dest': 'datestamp'}), |
| 711 |
('Do not include a datestamp of any kind.', |
| 712 |
['--no-datestamp'], {'action': 'store_const', 'const': None, |
| 713 |
'dest': 'datestamp'}), |
| 714 |
('Base directory for absolute paths when reading ' |
| 715 |
'from the local filesystem. Default "".', |
| 716 |
['--root-prefix'], |
| 717 |
{'default': '', 'metavar': '<path>'}), |
| 718 |
('Include a "View document source" link.', |
| 719 |
['--source-link', '-s'], {'action': 'store_true', |
| 720 |
'validator': validate_boolean}), |
| 721 |
('Use <URL> for a source link; implies --source-link.', |
| 722 |
['--source-url'], {'metavar': '<URL>'}), |
| 723 |
('Do not include a "View document source" link.', |
| 724 |
['--no-source-link'], |
| 725 |
{'action': 'callback', 'callback': store_multiple, |
| 726 |
'callback_args': ('source_link', 'source_url')}), |
| 727 |
('Link from section headers to TOC entries. (default)', |
| 728 |
['--toc-entry-backlinks'], |
| 729 |
{'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry', |
| 730 |
'default': 'entry'}), |
| 731 |
('Link from section headers to the top of the TOC.', |
| 732 |
['--toc-top-backlinks'], |
| 733 |
{'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}), |
| 734 |
('Disable backlinks to the table of contents.', |
| 735 |
['--no-toc-backlinks'], |
| 736 |
{'dest': 'toc_backlinks', 'action': 'store_false'}), |
| 737 |
('Link from footnotes/citations to references. (default)', |
| 738 |
['--footnote-backlinks'], |
| 739 |
{'action': 'store_true', 'default': True, |
| 740 |
'validator': validate_boolean}), |
| 741 |
('Disable backlinks from footnotes and citations.', |
| 742 |
['--no-footnote-backlinks'], |
| 743 |
{'dest': 'footnote_backlinks', 'action': 'store_false'}), |
| 744 |
('Enable section numbering by Docutils. (default)', |
| 745 |
['--section-numbering'], |
| 746 |
{'action': 'store_true', 'dest': 'sectnum_xform', |
| 747 |
'default': True, 'validator': validate_boolean}), |
| 748 |
('Disable section numbering by Docutils.', |
| 749 |
['--no-section-numbering'], |
| 750 |
{'action': 'store_false', 'dest': 'sectnum_xform'}), |
| 751 |
('Remove comment elements from the document tree.', |
| 752 |
['--strip-comments'], |
| 753 |
{'action': 'store_true', 'validator': validate_boolean}), |
| 754 |
('Leave comment elements in the document tree. (default)', |
| 755 |
['--leave-comments'], |
| 756 |
{'action': 'store_false', 'dest': 'strip_comments'}), |
| 757 |
('Remove all elements with classes="<class>" from the document tree. ' |
| 758 |
'Warning: potentially dangerous; use with caution. ' |
| 759 |
'(Multiple-use option.)', |
| 760 |
['--strip-elements-with-class'], |
| 761 |
{'action': 'append', 'dest': 'strip_elements_with_classes', |
| 762 |
'metavar': '<class>', 'validator': validate_strip_class}), |
| 763 |
('Remove all classes="<class>" attributes from elements in the ' |
| 764 |
'document tree. Warning: potentially dangerous; use with caution. ' |
| 765 |
'(Multiple-use option.)', |
| 766 |
['--strip-class'], |
| 767 |
{'action': 'append', 'dest': 'strip_classes', |
| 768 |
'metavar': '<class>', 'validator': validate_strip_class}), |
| 769 |
('Report system messages at or higher than <level>: "info" or "1", ' |
| 770 |
'"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"', |
| 771 |
['--report', '-r'], {'choices': threshold_choices, 'default': 2, |
| 772 |
'dest': 'report_level', 'metavar': '<level>', |
| 773 |
'validator': validate_threshold}), |
| 774 |
('Report all system messages. (Same as "--report=1".)', |
| 775 |
['--verbose', '-v'], {'action': 'store_const', 'const': 1, |
| 776 |
'dest': 'report_level'}), |
| 777 |
('Report no system messages. (Same as "--report=5".)', |
| 778 |
['--quiet', '-q'], {'action': 'store_const', 'const': 5, |
| 779 |
'dest': 'report_level'}), |
| 780 |
('Halt execution at system messages at or above <level>. ' |
| 781 |
'Levels as in --report. Default: 4 (severe).', |
| 782 |
['--halt'], {'choices': threshold_choices, 'dest': 'halt_level', |
| 783 |
'default': 4, 'metavar': '<level>', |
| 784 |
'validator': validate_threshold}), |
| 785 |
('Halt at the slightest problem. Same as "--halt=info".', |
| 786 |
['--strict'], {'action': 'store_const', 'const': 1, |
| 787 |
'dest': 'halt_level'}), |
| 788 |
('Enable a non-zero exit status for non-halting system messages at ' |
| 789 |
'or above <level>. Default: 5 (disabled).', |
| 790 |
['--exit-status'], {'choices': threshold_choices, |
| 791 |
'dest': 'exit_status_level', |
| 792 |
'default': 5, 'metavar': '<level>', |
| 793 |
'validator': validate_threshold}), |
| 794 |
('Enable debug-level system messages and diagnostics.', |
| 795 |
['--debug'], {'action': 'store_true', |
| 796 |
'validator': validate_boolean}), |
| 797 |
('Disable debug output. (default)', |
| 798 |
['--no-debug'], {'action': 'store_false', 'dest': 'debug'}), |
| 799 |
('Send the output of system messages to <file>.', |
| 800 |
['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}), |
| 801 |
('Enable Python tracebacks when Docutils is halted.', |
| 802 |
['--traceback'], {'action': 'store_true', 'default': None, |
| 803 |
'validator': validate_boolean}), |
| 804 |
('Disable Python tracebacks. (default)', |
| 805 |
['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}), |
| 806 |
('Specify the encoding and optionally the ' |
| 807 |
'error handler of input text. Default: utf-8.', |
| 808 |
['--input-encoding'], |
| 809 |
{'metavar': '<name[:handler]>', 'default': 'utf-8', |
| 810 |
'validator': validate_encoding_and_error_handler}), |
| 811 |
(SUPPRESS_HELP, ['--input-encoding-error-handler'], |
| 812 |
{'default': 'strict', 'validator': validate_encoding_error_handler}), |
| 813 |
('Specify the text encoding and optionally the error handler for ' |
| 814 |
'output. Default: utf-8.', |
| 815 |
['--output-encoding'], |
| 816 |
{'metavar': '<name[:handler]>', 'default': 'utf-8', |
| 817 |
'validator': validate_encoding_and_error_handler}), |
| 818 |
(SUPPRESS_HELP, ['--output-encoding-error-handler'], |
| 819 |
{'default': 'strict', 'validator': validate_encoding_error_handler}), |
| 820 |
('Specify text encoding and optionally the error handler' |
| 821 |
f' for error output. Default: {default_error_encoding}.', |
| 822 |
['--error-encoding', '-e'], |
| 823 |
{'metavar': '<name[:handler]>', 'default': default_error_encoding, |
| 824 |
'validator': validate_encoding_and_error_handler}), |
| 825 |
(SUPPRESS_HELP, ['--error-encoding-error-handler'], |
| 826 |
{'default': default_error_encoding_error_handler, |
| 827 |
'validator': validate_encoding_error_handler}), |
| 828 |
('Specify the language (as BCP 47 language tag). Default: en.', |
| 829 |
['--language', '-l'], {'dest': 'language_code', 'default': 'en', |
| 830 |
'metavar': '<tag>'}), |
| 831 |
('Write output file dependencies to <file>.', |
| 832 |
['--record-dependencies'], |
| 833 |
{'metavar': '<file>', 'validator': validate_dependency_file, |
| 834 |
'default': None}), # default set in Values class |
| 835 |
('Read configuration settings from <file>, if it exists.', |
| 836 |
['--config'], {'metavar': '<file>', 'type': 'string', |
| 837 |
'action': 'callback', 'callback': read_config_file}), |
| 838 |
("Show this program's version number and exit.", |
| 839 |
['--version', '-V'], {'action': 'version'}), |
| 840 |
('Show this help message and exit.', |
| 841 |
['--help', '-h'], {'action': 'help'}), |
| 842 |
# Typically not useful for non-programmatical use: |
| 843 |
(SUPPRESS_HELP, ['--id-prefix'], {'default': ''}), |
| 844 |
(SUPPRESS_HELP, ['--auto-id-prefix'], {'default': '%'}), |
| 845 |
# Hidden options, for development use only: |
| 846 |
(SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}), |
| 847 |
(SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}), |
| 848 |
(SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}), |
| 849 |
(SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}), |
| 850 |
(SUPPRESS_HELP, ['--expose-internal-attribute'], |
| 851 |
{'action': 'append', 'dest': 'expose_internals', |
| 852 |
'validator': validate_colon_separated_string_list}), |
| 853 |
(SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}), |
| 854 |
)) |
| 855 |
"""Runtime settings and command-line options common to all Docutils front |
| 856 |
ends. Setting specs specific to individual Docutils components are also |
| 857 |
used (see `populate_from_components()`).""" |
| 858 |
|
| 859 |
settings_defaults = {'_disable_config': None, |
| 860 |
'_source': None, |
| 861 |
'_destination': None, |
| 862 |
'_config_files': None} |
| 863 |
"""Defaults for settings without command-line option equivalents. |
| 864 |
|
| 865 |
See https://docutils.sourceforge.io/docs/user/config.html#internal-settings |
| 866 |
""" |
| 867 |
|
| 868 |
relative_path_settings: tuple[str, ...] = () # will be modified |
| 869 |
|
| 870 |
config_section = 'general' |
| 871 |
|
| 872 |
version_template: ClassVar[str] = '%%prog (Docutils %s%s, Python %s, on %s)' % ( # NoQA: E501 |
| 873 |
docutils.__version__, |
| 874 |
(details := docutils.__version_details__) and f' [{details}]' or '', |
| 875 |
sys.version.split()[0], |
| 876 |
sys.platform) |
| 877 |
"""Default version message.""" |
| 878 |
|
| 879 |
def __init__(self, |
| 880 |
components: Iterable[SettingsSpec] = (), |
| 881 |
defaults: Mapping[str, Any] | None = None, |
| 882 |
read_config_files: bool | None = False, |
| 883 |
*args, |
| 884 |
**kwargs, |
| 885 |
) -> None: |
| 886 |
"""Set up OptionParser instance. |
| 887 |
|
| 888 |
`components` is a list of Docutils components each containing a |
| 889 |
``.settings_spec`` attribute. |
| 890 |
`defaults` is a mapping of setting default overrides. |
| 891 |
""" |
| 892 |
|
| 893 |
self.lists: dict[str, Literal[True]] = {} |
| 894 |
"""Set of list-type settings.""" |
| 895 |
|
| 896 |
self.config_files: list[str] = [] |
| 897 |
"""List of paths of applied configuration files.""" |
| 898 |
|
| 899 |
self.relative_path_settings = ('warning_stream',) # will be modified |
| 900 |
|
| 901 |
warnings.warn( |
| 902 |
'The frontend.OptionParser class will be replaced by a subclass ' |
| 903 |
'of argparse.ArgumentParser in Docutils 2.0 or later.\n ' |
| 904 |
'To get default settings, use frontend.get_default_settings().', |
| 905 |
DeprecationWarning, stacklevel=2) |
| 906 |
super().__init__(option_class=Option, add_help_option=False, |
| 907 |
formatter=optparse.TitledHelpFormatter(width=78), |
| 908 |
*args, **kwargs) |
| 909 |
if not self.version: |
| 910 |
self.version = self.version_template |
| 911 |
self.components: tuple[SettingsSpec, ...] = (self, *components) |
| 912 |
self.populate_from_components(self.components) |
| 913 |
self.defaults.update(defaults or {}) |
| 914 |
if read_config_files and not self.defaults['_disable_config']: |
| 915 |
try: |
| 916 |
config_settings = self.get_standard_config_settings() |
| 917 |
except ValueError as err: |
| 918 |
self.error(str(err)) |
| 919 |
self.defaults.update(config_settings.__dict__) |
| 920 |
|
| 921 |
def populate_from_components(self, components: Iterable[SettingsSpec], |
| 922 |
) -> None: |
| 923 |
"""Collect settings specification from components. |
| 924 |
|
| 925 |
For each component, populate from the `SettingsSpec.settings_spec` |
| 926 |
structure, then from the `SettingsSpec.settings_defaults` dictionary. |
| 927 |
After all components have been processed, check for and populate from |
| 928 |
each component's `SettingsSpec.settings_default_overrides` dictionary. |
| 929 |
""" |
| 930 |
for component in components: |
| 931 |
if component is None: |
| 932 |
continue |
| 933 |
settings_spec = component.settings_spec |
| 934 |
self.relative_path_settings += component.relative_path_settings |
| 935 |
for i in range(0, len(settings_spec), 3): |
| 936 |
title, description, option_spec = settings_spec[i:i+3] |
| 937 |
if title: |
| 938 |
group = optparse.OptionGroup(self, title, description) |
| 939 |
self.add_option_group(group) |
| 940 |
else: |
| 941 |
group = self # single options |
| 942 |
for (help_text, option_strings, kwargs) in option_spec: |
| 943 |
option = group.add_option(help=help_text, *option_strings, |
| 944 |
**kwargs) |
| 945 |
if kwargs.get('action') == 'append': |
| 946 |
self.lists[option.dest] = True |
| 947 |
if component.settings_defaults: |
| 948 |
self.defaults.update(component.settings_defaults) |
| 949 |
for component in components: |
| 950 |
if component and component.settings_default_overrides: |
| 951 |
self.defaults.update(component.settings_default_overrides) |
| 952 |
|
| 953 |
@classmethod |
| 954 |
def get_standard_config_files(cls) -> Sequence[StrPath]: |
| 955 |
"""Return list of config files, from environment or standard.""" |
| 956 |
if 'DOCUTILSCONFIG' in os.environ: |
| 957 |
config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep) |
| 958 |
else: |
| 959 |
config_files = cls.standard_config_files |
| 960 |
return [os.path.expanduser(f) for f in config_files if f.strip()] |
| 961 |
|
| 962 |
def get_standard_config_settings(self) -> Values: |
| 963 |
with warnings.catch_warnings(): |
| 964 |
warnings.filterwarnings('ignore', category=DeprecationWarning) |
| 965 |
settings = Values() |
| 966 |
for filename in self.get_standard_config_files(): |
| 967 |
settings.update(self.get_config_file_settings(filename), self) |
| 968 |
return settings |
| 969 |
|
| 970 |
def get_config_file_settings(self, config_file: str) -> dict[str, Any]: |
| 971 |
"""Returns a dictionary containing appropriate config file settings.""" |
| 972 |
config_parser = ConfigParser() |
| 973 |
# parse config file, add filename if found and successfully read. |
| 974 |
applied = set() |
| 975 |
with warnings.catch_warnings(): |
| 976 |
warnings.filterwarnings('ignore', category=DeprecationWarning) |
| 977 |
self.config_files += config_parser.read(config_file, self) |
| 978 |
settings = Values() |
| 979 |
for component in self.components: |
| 980 |
if not component: |
| 981 |
continue |
| 982 |
for section in (tuple(component.config_section_dependencies or ()) |
| 983 |
+ (component.config_section,)): |
| 984 |
if section in applied: |
| 985 |
continue |
| 986 |
applied.add(section) |
| 987 |
if config_parser.has_section(section): |
| 988 |
settings.update(config_parser[section], self) |
| 989 |
make_paths_absolute(settings.__dict__, |
| 990 |
self.relative_path_settings, |
| 991 |
os.path.dirname(config_file)) |
| 992 |
return settings.__dict__ |
| 993 |
|
| 994 |
def check_values(self, values: Values, args: list[str]) -> Values: |
| 995 |
"""Store positional arguments as runtime settings.""" |
| 996 |
values._source, values._destination = self.check_args(args) |
| 997 |
make_paths_absolute(values.__dict__, self.relative_path_settings) |
| 998 |
values._config_files = self.config_files |
| 999 |
return values |
| 1000 |
|
| 1001 |
def check_args(self, args: list[str]) -> tuple[str|None, str|None]: |
| 1002 |
# provisional: argument handling will change, see RELEASE_NOTES |
| 1003 |
source = destination = None |
| 1004 |
if args: |
| 1005 |
source = args.pop(0) |
| 1006 |
if source == '-': # means stdin |
| 1007 |
source = None |
| 1008 |
if args: |
| 1009 |
destination = args.pop(0) |
| 1010 |
if destination == '-': # means stdout |
| 1011 |
destination = None |
| 1012 |
if args: |
| 1013 |
self.error('Maximum 2 arguments allowed.') |
| 1014 |
if source and source == destination: |
| 1015 |
self.error('Do not specify the same file for both source and ' |
| 1016 |
'destination. It will clobber the source file.') |
| 1017 |
return source, destination |
| 1018 |
|
| 1019 |
def get_default_values(self) -> Values: |
| 1020 |
"""Needed to get custom `Values` instances.""" |
| 1021 |
with warnings.catch_warnings(): |
| 1022 |
warnings.filterwarnings('ignore', category=DeprecationWarning) |
| 1023 |
defaults = Values(self.defaults) |
| 1024 |
defaults._config_files = self.config_files |
| 1025 |
return defaults |
| 1026 |
|
| 1027 |
def get_option_by_dest(self, dest: str) -> Option: |
| 1028 |
""" |
| 1029 |
Get an option by its dest. |
| 1030 |
|
| 1031 |
If you're supplying a dest which is shared by several options, |
| 1032 |
it is undefined which option of those is returned. |
| 1033 |
|
| 1034 |
A KeyError is raised if there is no option with the supplied |
| 1035 |
dest. |
| 1036 |
""" |
| 1037 |
for group in self.option_groups + [self]: |
| 1038 |
for option in group.option_list: |
| 1039 |
if option.dest == dest: |
| 1040 |
return option |
| 1041 |
raise KeyError('No option with dest == %r.' % dest) |
| 1042 |
|
| 1043 |
|
| 1044 |
class ConfigParser(configparser.RawConfigParser): |
| 1045 |
"""Parser for Docutils configuration files. |
| 1046 |
|
| 1047 |
See https://docutils.sourceforge.io/docs/user/config.html. |
| 1048 |
|
| 1049 |
Option key normalization includes conversion of '-' to '_'. |
| 1050 |
|
| 1051 |
Config file encoding is "utf-8". Encoding errors are reported |
| 1052 |
and the affected file(s) skipped. |
| 1053 |
|
| 1054 |
This class is provisional and will change in future versions. |
| 1055 |
""" |
| 1056 |
|
| 1057 |
old_settings: ClassVar[dict[str, tuple[str, str]]] = { |
| 1058 |
'pep_stylesheet': ('pep_html writer', 'stylesheet'), |
| 1059 |
'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'), |
| 1060 |
'pep_template': ('pep_html writer', 'template')} |
| 1061 |
"""{old setting: (new section, new setting)} mapping, used by |
| 1062 |
`handle_old_config`, to convert settings from the old [options] section. |
| 1063 |
""" |
| 1064 |
|
| 1065 |
old_warning: ClassVar[str] = ( |
| 1066 |
'The "[option]" section is deprecated.\n' |
| 1067 |
'Support for old-format configuration files will be removed in ' |
| 1068 |
'Docutils 2.0. Please revise your configuration files. ' |
| 1069 |
'See <https://docutils.sourceforge.io/docs/user/config.html>, ' |
| 1070 |
'section "Old-Format Configuration Files".') |
| 1071 |
|
| 1072 |
not_utf8_error: ClassVar[str] = """\ |
| 1073 |
Unable to read configuration file "%s": content not encoded as UTF-8. |
| 1074 |
Skipping "%s" configuration file. |
| 1075 |
""" |
| 1076 |
|
| 1077 |
def read(self, |
| 1078 |
filenames: str | Sequence[str], |
| 1079 |
option_parser: OptionParser | None = None, |
| 1080 |
) -> list[str]: |
| 1081 |
# Currently, if a `docutils.frontend.OptionParser` instance is |
| 1082 |
# supplied, setting values are validated. |
| 1083 |
if option_parser is not None: |
| 1084 |
warnings.warn('frontend.ConfigParser.read(): parameter ' |
| 1085 |
'"option_parser" will be removed ' |
| 1086 |
'in Docutils 2.0 or later.', |
| 1087 |
DeprecationWarning, stacklevel=2) |
| 1088 |
read_ok = [] |
| 1089 |
if isinstance(filenames, str): |
| 1090 |
filenames = [filenames] |
| 1091 |
for filename in filenames: |
| 1092 |
# Config files are UTF-8-encoded: |
| 1093 |
try: |
| 1094 |
read_ok += super().read(filename, encoding='utf-8') |
| 1095 |
except UnicodeDecodeError: |
| 1096 |
sys.stderr.write(self.not_utf8_error % (filename, filename)) |
| 1097 |
continue |
| 1098 |
if 'options' in self: |
| 1099 |
self.handle_old_config(filename) |
| 1100 |
if option_parser is not None: |
| 1101 |
self.validate_settings(filename, option_parser) |
| 1102 |
return read_ok |
| 1103 |
|
| 1104 |
def handle_old_config(self, filename: str) -> None: |
| 1105 |
warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning, |
| 1106 |
filename, 0) |
| 1107 |
try: |
| 1108 |
options = dict(self['options']) |
| 1109 |
except KeyError: |
| 1110 |
options = {} |
| 1111 |
if not self.has_section('general'): |
| 1112 |
self.add_section('general') |
| 1113 |
for key, value in options.items(): |
| 1114 |
if key in self.old_settings: |
| 1115 |
section, setting = self.old_settings[key] |
| 1116 |
if not self.has_section(section): |
| 1117 |
self.add_section(section) |
| 1118 |
else: |
| 1119 |
section = 'general' |
| 1120 |
setting = key |
| 1121 |
if not self.has_option(section, setting): |
| 1122 |
self.set(section, setting, value) |
| 1123 |
self.remove_section('options') |
| 1124 |
|
| 1125 |
def validate_settings(self, filename: str, option_parser: OptionParser, |
| 1126 |
) -> None: |
| 1127 |
""" |
| 1128 |
Call the validator function and implement overrides on all applicable |
| 1129 |
settings. |
| 1130 |
""" |
| 1131 |
for section in self.sections(): |
| 1132 |
for setting in self.options(section): |
| 1133 |
try: |
| 1134 |
option = option_parser.get_option_by_dest(setting) |
| 1135 |
except KeyError: |
| 1136 |
continue |
| 1137 |
if option.validator: |
| 1138 |
value = self.get(section, setting) |
| 1139 |
try: |
| 1140 |
new_value = option.validator( |
| 1141 |
setting, value, option_parser, |
| 1142 |
config_parser=self, config_section=section) |
| 1143 |
except Exception as err: |
| 1144 |
raise ValueError(f'Error in config file "{filename}", ' |
| 1145 |
f'section "[{section}]":\n' |
| 1146 |
f' {io.error_string(err)}\n' |
| 1147 |
f' {setting} = {value}') |
| 1148 |
self.set(section, setting, new_value) |
| 1149 |
if option.overrides: |
| 1150 |
self.set(section, option.overrides, None) |
| 1151 |
|
| 1152 |
def optionxform(self, optionstr: str) -> str: |
| 1153 |
""" |
| 1154 |
Lowercase and transform '-' to '_'. |
| 1155 |
|
| 1156 |
So the cmdline form of option names can be used in config files. |
| 1157 |
""" |
| 1158 |
return optionstr.lower().replace('-', '_') |
| 1159 |
|
| 1160 |
|
| 1161 |
class ConfigDeprecationWarning(FutureWarning): |
| 1162 |
"""Warning for deprecated configuration file features.""" |
| 1163 |
|
| 1164 |
|
| 1165 |
def get_default_settings(*components: type[SettingsSpec]) -> Values: |
| 1166 |
"""Return default runtime settings for `components`. |
| 1167 |
|
| 1168 |
Return a `frontend.Values` instance with defaults for generic Docutils |
| 1169 |
settings and settings from the `components` (`SettingsSpec` instances). |
| 1170 |
|
| 1171 |
This corresponds to steps 1 and 2 in the `runtime settings priority`__. |
| 1172 |
|
| 1173 |
__ https://docutils.sourceforge.io/docs/api/runtime-settings.html |
| 1174 |
#settings-priority |
| 1175 |
""" |
| 1176 |
with warnings.catch_warnings(): |
| 1177 |
warnings.filterwarnings('ignore', category=DeprecationWarning) |
| 1178 |
return OptionParser(components).get_default_values() |