Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/docutils/frontend.py: 31%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

437 statements  

1# $Id: frontend.py 10348 2026-06-11 07:46:01Z milde $ 

2# Author: David Goodger <goodger@python.org> 

3# Copyright: This module has been placed in the public domain. 

4 

5""" 

6Command-line and common processing for Docutils front-end tools. 

7 

8This module is provisional. 

9Major changes will happen with the transition from the 

10"optparse" module to "arparse" in Docutils 2.0 or later. 

11 

12Applications should use the high-level API provided by `docutils.core`. 

13See https://docutils.sourceforge.io/docs/api/runtime-settings.html. 

14 

15Exports 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 

27Also exports the following functions: 

28 

29Interface function: 

30 `get_default_settings()`. New in 0.19. 

31 

32Option callbacks: 

33 `store_multiple()`, `read_config_file()`. Deprecated. To be removed. 

34 

35Setting 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 

49Misc: 

50 `make_paths_absolute()`, `filter_settings_spec()`. Provisional. 

51""" 

52 

53from __future__ import annotations 

54 

55__docformat__ = 'reStructuredText' 

56 

57 

58import codecs 

59import configparser 

60import optparse 

61import os 

62import os.path 

63import sys 

64import warnings 

65from optparse import SUPPRESS_HELP 

66from pathlib import Path 

67 

68import docutils 

69from docutils import io, utils 

70 

71TYPE_CHECKING = False 

72if 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 

92def 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 

113def 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 

130def 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 

154def 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 

177def 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 

206def 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 

231def 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 

257def 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 

274def 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 

294def 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 

314def 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 

341def 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 

381def 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 

400def 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 

418def 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 

440def 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 

486def 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 

512def 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 

520def 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 

552class 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 

601class 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 

646class 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. Default: None (stdout).', 

695 ['--output', '-o'], {'metavar': '<destination>', 

696 'dest': 'output_path'}), 

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 (SUPPRESS_HELP, ['--output-path'], {}), 

846 # Hidden options, for development use only: 

847 (SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}), 

848 (SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}), 

849 (SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}), 

850 (SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}), 

851 (SUPPRESS_HELP, ['--expose-internal-attribute'], 

852 {'action': 'append', 'dest': 'expose_internals', 

853 'validator': validate_colon_separated_string_list}), 

854 (SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}), 

855 )) 

856 """Runtime settings and command-line options common to all Docutils front 

857 ends. Setting specs specific to individual Docutils components are also 

858 used (see `populate_from_components()`).""" 

859 

860 settings_defaults = {'_disable_config': None, 

861 '_source': None, 

862 '_destination': None, 

863 '_config_files': None} 

864 """Defaults for settings without command-line option equivalents. 

865 

866 See https://docutils.sourceforge.io/docs/user/config.html#internal-settings 

867 """ 

868 

869 relative_path_settings: tuple[str, ...] = () # will be modified 

870 

871 config_section = 'general' 

872 

873 version_template: ClassVar[str] = '%%prog (Docutils %s%s, Python %s, on %s)' % ( # NoQA: E501 

874 docutils.__version__, 

875 (details := docutils.__version_details__) and f' [{details}]' or '', 

876 sys.version.split()[0], 

877 sys.platform) 

878 """Default version message.""" 

879 

880 def __init__(self, 

881 components: Iterable[SettingsSpec] = (), 

882 defaults: Mapping[str, Any] | None = None, 

883 read_config_files: bool | None = False, 

884 *args, 

885 **kwargs, 

886 ) -> None: 

887 """Set up OptionParser instance. 

888 

889 `components` is a list of Docutils components each containing a 

890 ``.settings_spec`` attribute. 

891 `defaults` is a mapping of setting default overrides. 

892 """ 

893 

894 self.lists: dict[str, Literal[True]] = {} 

895 """Set of list-type settings.""" 

896 

897 self.config_files: list[str] = [] 

898 """List of paths of applied configuration files.""" 

899 

900 self.relative_path_settings = ('warning_stream',) # will be modified 

901 

902 warnings.warn( 

903 'The frontend.OptionParser class will be replaced by a subclass ' 

904 'of argparse.ArgumentParser in Docutils 2.0 or later.\n ' 

905 'To get default settings, use frontend.get_default_settings().', 

906 DeprecationWarning, stacklevel=2) 

907 super().__init__(option_class=Option, add_help_option=False, 

908 formatter=optparse.TitledHelpFormatter(width=78), 

909 *args, **kwargs) 

910 if not self.version: 

911 self.version = self.version_template 

912 self.components: tuple[SettingsSpec, ...] = (self, *components) 

913 self.populate_from_components(self.components) 

914 self.defaults.update(defaults or {}) 

915 if read_config_files and not self.defaults['_disable_config']: 

916 try: 

917 config_settings = self.get_standard_config_settings() 

918 except ValueError as err: 

919 self.error(str(err)) 

920 self.defaults.update(config_settings.__dict__) 

921 

922 def populate_from_components(self, components: Iterable[SettingsSpec], 

923 ) -> None: 

924 """Collect settings specification from components. 

925 

926 For each component, populate from the `SettingsSpec.settings_spec` 

927 structure, then from the `SettingsSpec.settings_defaults` dictionary. 

928 After all components have been processed, check for and populate from 

929 each component's `SettingsSpec.settings_default_overrides` dictionary. 

930 """ 

931 for component in components: 

932 if component is None: 

933 continue 

934 settings_spec = component.settings_spec 

935 self.relative_path_settings += component.relative_path_settings 

936 for i in range(0, len(settings_spec), 3): 

937 title, description, option_spec = settings_spec[i:i+3] 

938 if title: 

939 group = optparse.OptionGroup(self, title, description) 

940 self.add_option_group(group) 

941 else: 

942 group = self # single options 

943 for (help_text, option_strings, kwargs) in option_spec: 

944 option = group.add_option(help=help_text, *option_strings, 

945 **kwargs) 

946 if kwargs.get('action') == 'append': 

947 self.lists[option.dest] = True 

948 if component.settings_defaults: 

949 self.defaults.update(component.settings_defaults) 

950 for component in components: 

951 if component and component.settings_default_overrides: 

952 self.defaults.update(component.settings_default_overrides) 

953 

954 @classmethod 

955 def get_standard_config_files(cls) -> Sequence[StrPath]: 

956 """Return list of config files, from environment or standard.""" 

957 if 'DOCUTILSCONFIG' in os.environ: 

958 config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep) 

959 else: 

960 config_files = cls.standard_config_files 

961 return [os.path.expanduser(f) for f in config_files if f.strip()] 

962 

963 def get_standard_config_settings(self) -> Values: 

964 with warnings.catch_warnings(): 

965 warnings.filterwarnings('ignore', category=DeprecationWarning) 

966 settings = Values() 

967 for filename in self.get_standard_config_files(): 

968 settings.update(self.get_config_file_settings(filename), self) 

969 return settings 

970 

971 def get_config_file_settings(self, config_file: str) -> dict[str, Any]: 

972 """Returns a dictionary containing appropriate config file settings.""" 

973 config_parser = ConfigParser() 

974 # parse config file, add filename if found and successfully read. 

975 applied = set() 

976 with warnings.catch_warnings(): 

977 warnings.filterwarnings('ignore', category=DeprecationWarning) 

978 self.config_files += config_parser.read(config_file, self) 

979 settings = Values() 

980 for component in self.components: 

981 if not component: 

982 continue 

983 for section in (tuple(component.config_section_dependencies or ()) 

984 + (component.config_section,)): 

985 if section in applied: 

986 continue 

987 applied.add(section) 

988 if config_parser.has_section(section): 

989 settings.update(config_parser[section], self) 

990 make_paths_absolute(settings.__dict__, 

991 self.relative_path_settings, 

992 os.path.dirname(config_file)) 

993 return settings.__dict__ 

994 

995 def check_values(self, values: Values, args: list[str]) -> Values: 

996 """Store positional arguments as runtime settings. 

997 

998 Provisional. Handling of positional arguments will change 

999 in Docutils 2.0 (see RELEASE-NOTES). 

1000 """ 

1001 values._source, values._destination = self.check_args(args) 

1002 make_paths_absolute(values.__dict__, self.relative_path_settings) 

1003 values._config_files = self.config_files 

1004 return values 

1005 

1006 def check_args(self, args: list[str]) -> tuple[str|None]: 

1007 # internal, provisional: 

1008 # will be removed in Docutils 2.0 when multiple sources are allowed. 

1009 source = None 

1010 if args: 

1011 source = args.pop(0) 

1012 if source == '-': # means stdin 

1013 source = None 

1014 if args: 

1015 self.error('Only 1 argument allowed.') 

1016 return source, None 

1017 

1018 def get_default_values(self) -> Values: 

1019 """Needed to get custom `Values` instances.""" 

1020 with warnings.catch_warnings(): 

1021 warnings.filterwarnings('ignore', category=DeprecationWarning) 

1022 defaults = Values(self.defaults) 

1023 defaults._config_files = self.config_files 

1024 return defaults 

1025 

1026 def get_option_by_dest(self, dest: str) -> Option: 

1027 """ 

1028 Get an option by its dest. 

1029 

1030 If you're supplying a dest which is shared by several options, 

1031 it is undefined which option of those is returned. 

1032 

1033 A KeyError is raised if there is no option with the supplied 

1034 dest. 

1035 """ 

1036 for group in self.option_groups + [self]: 

1037 for option in group.option_list: 

1038 if option.dest == dest: 

1039 return option 

1040 raise KeyError('No option with dest == %r.' % dest) 

1041 

1042 

1043class ConfigParser(configparser.RawConfigParser): 

1044 """Parser for Docutils configuration files. 

1045 

1046 See https://docutils.sourceforge.io/docs/user/config.html. 

1047 

1048 Option key normalization includes conversion of '-' to '_'. 

1049 

1050 Config file encoding is "utf-8". Encoding errors are reported 

1051 and the affected file(s) skipped. 

1052 

1053 This class is provisional and will change in future versions. 

1054 """ 

1055 

1056 old_settings: ClassVar[dict[str, tuple[str, str]]] = { 

1057 'pep_stylesheet': ('pep_html writer', 'stylesheet'), 

1058 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'), 

1059 'pep_template': ('pep_html writer', 'template')} 

1060 """{old setting: (new section, new setting)} mapping, used by 

1061 `handle_old_config`, to convert settings from the old [options] section. 

1062 """ 

1063 

1064 old_warning: ClassVar[str] = ( 

1065 'The "[option]" section is deprecated.\n' 

1066 'Support for old-format configuration files will be removed in ' 

1067 'Docutils 2.0. Please revise your configuration files. ' 

1068 'See <https://docutils.sourceforge.io/docs/user/config.html>, ' 

1069 'section "Old-Format Configuration Files".') 

1070 

1071 not_utf8_error: ClassVar[str] = """\ 

1072Unable to read configuration file "%s": content not encoded as UTF-8. 

1073Skipping "%s" configuration file. 

1074""" 

1075 

1076 def read(self, 

1077 filenames: str | Sequence[str], 

1078 option_parser: OptionParser | None = None, 

1079 ) -> list[str]: 

1080 # Currently, if a `docutils.frontend.OptionParser` instance is 

1081 # supplied, setting values are validated. 

1082 if option_parser is not None: 

1083 warnings.warn('frontend.ConfigParser.read(): parameter ' 

1084 '"option_parser" will be removed ' 

1085 'in Docutils 2.0 or later.', 

1086 DeprecationWarning, stacklevel=2) 

1087 read_ok = [] 

1088 if isinstance(filenames, str): 

1089 filenames = [filenames] 

1090 for filename in filenames: 

1091 # Config files are UTF-8-encoded: 

1092 try: 

1093 read_ok += super().read(filename, encoding='utf-8') 

1094 except UnicodeDecodeError: 

1095 sys.stderr.write(self.not_utf8_error % (filename, filename)) 

1096 continue 

1097 if 'options' in self: 

1098 self.handle_old_config(filename) 

1099 if option_parser is not None: 

1100 self.validate_settings(filename, option_parser) 

1101 return read_ok 

1102 

1103 def handle_old_config(self, filename: str) -> None: 

1104 warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning, 

1105 filename, 0) 

1106 try: 

1107 options = dict(self['options']) 

1108 except KeyError: 

1109 options = {} 

1110 if not self.has_section('general'): 

1111 self.add_section('general') 

1112 for key, value in options.items(): 

1113 if key in self.old_settings: 

1114 section, setting = self.old_settings[key] 

1115 if not self.has_section(section): 

1116 self.add_section(section) 

1117 else: 

1118 section = 'general' 

1119 setting = key 

1120 if not self.has_option(section, setting): 

1121 self.set(section, setting, value) 

1122 self.remove_section('options') 

1123 

1124 def validate_settings(self, filename: str, option_parser: OptionParser, 

1125 ) -> None: 

1126 """ 

1127 Call the validator function and implement overrides on all applicable 

1128 settings. 

1129 """ 

1130 for section in self.sections(): 

1131 for setting in self.options(section): 

1132 try: 

1133 option = option_parser.get_option_by_dest(setting) 

1134 except KeyError: 

1135 continue 

1136 if option.validator: 

1137 value = self.get(section, setting) 

1138 try: 

1139 new_value = option.validator( 

1140 setting, value, option_parser, 

1141 config_parser=self, config_section=section) 

1142 except Exception as err: 

1143 raise ValueError(f'Error in config file "{filename}", ' 

1144 f'section "[{section}]":\n' 

1145 f' {io.error_string(err)}\n' 

1146 f' {setting} = {value}') 

1147 self.set(section, setting, new_value) 

1148 if option.overrides: 

1149 self.set(section, option.overrides, None) 

1150 

1151 def optionxform(self, optionstr: str) -> str: 

1152 """ 

1153 Lowercase and transform '-' to '_'. 

1154 

1155 So the cmdline form of option names can be used in config files. 

1156 """ 

1157 return optionstr.lower().replace('-', '_') 

1158 

1159 

1160class ConfigDeprecationWarning(FutureWarning): 

1161 """Warning for deprecated configuration file features.""" 

1162 

1163 

1164def get_default_settings(*components: type[SettingsSpec]) -> Values: 

1165 """Return default runtime settings for `components`. 

1166 

1167 Return a `frontend.Values` instance with defaults for generic Docutils 

1168 settings and settings from the `components` (`SettingsSpec` instances). 

1169 

1170 This corresponds to steps 1 and 2 in the `runtime settings priority`__. 

1171 

1172 __ https://docutils.sourceforge.io/docs/api/runtime-settings.html 

1173 #settings-priority 

1174 """ 

1175 with warnings.catch_warnings(): 

1176 warnings.filterwarnings('ignore', category=DeprecationWarning) 

1177 return OptionParser(components).get_default_values()