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

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

443 statements  

1# $Id$ 

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. 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 ('Specify the error handler for undecodable characters. ' 

812 'Choices: "strict" (default), "ignore", and "replace".', 

813 ['--input-encoding-error-handler'], 

814 {'default': 'strict', 'validator': validate_encoding_error_handler}), 

815 ('Specify the text encoding and optionally the error handler for ' 

816 'output. Default: utf-8.', 

817 ['--output-encoding'], 

818 {'metavar': '<name[:handler]>', 'default': 'utf-8', 

819 'validator': validate_encoding_and_error_handler}), 

820 ('Specify error handler for unencodable output characters; ' 

821 '"strict" (default), "ignore", "replace", ' 

822 '"xmlcharrefreplace", "backslashreplace".', 

823 ['--output-encoding-error-handler'], 

824 {'default': 'strict', 'validator': validate_encoding_error_handler}), 

825 ('Specify text encoding and optionally error handler ' 

826 'for error output. Default: %s.' % default_error_encoding, 

827 ['--error-encoding', '-e'], 

828 {'metavar': '<name[:handler]>', 'default': default_error_encoding, 

829 'validator': validate_encoding_and_error_handler}), 

830 ('Specify the error handler for unencodable characters in ' 

831 'error output. Default: %s.' 

832 % default_error_encoding_error_handler, 

833 ['--error-encoding-error-handler'], 

834 {'default': default_error_encoding_error_handler, 

835 'validator': validate_encoding_error_handler}), 

836 ('Specify the language (as BCP 47 language tag). Default: en.', 

837 ['--language', '-l'], {'dest': 'language_code', 'default': 'en', 

838 'metavar': '<name>'}), 

839 ('Write output file dependencies to <file>.', 

840 ['--record-dependencies'], 

841 {'metavar': '<file>', 'validator': validate_dependency_file, 

842 'default': None}), # default set in Values class 

843 ('Read configuration settings from <file>, if it exists.', 

844 ['--config'], {'metavar': '<file>', 'type': 'string', 

845 'action': 'callback', 'callback': read_config_file}), 

846 ("Show this program's version number and exit.", 

847 ['--version', '-V'], {'action': 'version'}), 

848 ('Show this help message and exit.', 

849 ['--help', '-h'], {'action': 'help'}), 

850 # Typically not useful for non-programmatical use: 

851 (SUPPRESS_HELP, ['--id-prefix'], {'default': ''}), 

852 (SUPPRESS_HELP, ['--auto-id-prefix'], {'default': '%'}), 

853 # Hidden options, for development use only: 

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

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

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

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

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

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

860 'validator': validate_colon_separated_string_list}), 

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

862 )) 

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

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

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

866 

867 settings_defaults = {'_disable_config': None, 

868 '_source': None, 

869 '_destination': None, 

870 '_config_files': None} 

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

872 

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

874 """ 

875 

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

877 

878 config_section = 'general' 

879 

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

881 docutils.__version__, 

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

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

884 sys.platform) 

885 """Default version message.""" 

886 

887 def __init__(self, 

888 components: Iterable[SettingsSpec] = (), 

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

890 read_config_files: bool | None = False, 

891 *args, 

892 **kwargs, 

893 ) -> None: 

894 """Set up OptionParser instance. 

895 

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

897 ``.settings_spec`` attribute. 

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

899 """ 

900 

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

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

903 

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

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

906 

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

908 

909 warnings.warn( 

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

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

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

913 DeprecationWarning, stacklevel=2) 

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

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

916 *args, **kwargs) 

917 if not self.version: 

918 self.version = self.version_template 

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

920 self.populate_from_components(self.components) 

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

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

923 try: 

924 config_settings = self.get_standard_config_settings() 

925 except ValueError as err: 

926 self.error(str(err)) 

927 self.defaults.update(config_settings.__dict__) 

928 

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

930 ) -> None: 

931 """Collect settings specification from components. 

932 

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

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

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

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

937 """ 

938 for component in components: 

939 if component is None: 

940 continue 

941 settings_spec = component.settings_spec 

942 self.relative_path_settings += component.relative_path_settings 

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

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

945 if title: 

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

947 self.add_option_group(group) 

948 else: 

949 group = self # single options 

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

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

952 **kwargs) 

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

954 self.lists[option.dest] = True 

955 if component.settings_defaults: 

956 self.defaults.update(component.settings_defaults) 

957 for component in components: 

958 if component and component.settings_default_overrides: 

959 self.defaults.update(component.settings_default_overrides) 

960 

961 @classmethod 

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

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

964 if 'DOCUTILSCONFIG' in os.environ: 

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

966 else: 

967 config_files = cls.standard_config_files 

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

969 

970 def get_standard_config_settings(self) -> Values: 

971 with warnings.catch_warnings(): 

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

973 settings = Values() 

974 for filename in self.get_standard_config_files(): 

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

976 return settings 

977 

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

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

980 config_parser = ConfigParser() 

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

982 applied = set() 

983 with warnings.catch_warnings(): 

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

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

986 settings = Values() 

987 for component in self.components: 

988 if not component: 

989 continue 

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

991 + (component.config_section,)): 

992 if section in applied: 

993 continue 

994 applied.add(section) 

995 if config_parser.has_section(section): 

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

997 make_paths_absolute(settings.__dict__, 

998 self.relative_path_settings, 

999 os.path.dirname(config_file)) 

1000 return settings.__dict__ 

1001 

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

1003 """Store positional arguments as runtime settings.""" 

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

1005 make_paths_absolute(values.__dict__, self.relative_path_settings) 

1006 values._config_files = self.config_files 

1007 return values 

1008 

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

1010 # provisional: argument handling will change, see RELEASE_NOTES 

1011 source = destination = None 

1012 if args: 

1013 source = args.pop(0) 

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

1015 source = None 

1016 if args: 

1017 destination = args.pop(0) 

1018 if destination == '-': # means stdout 

1019 destination = None 

1020 if args: 

1021 self.error('Maximum 2 arguments allowed.') 

1022 if source and source == destination: 

1023 self.error('Do not specify the same file for both source and ' 

1024 'destination. It will clobber the source file.') 

1025 return source, destination 

1026 

1027 def get_default_values(self) -> Values: 

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

1029 with warnings.catch_warnings(): 

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

1031 defaults = Values(self.defaults) 

1032 defaults._config_files = self.config_files 

1033 return defaults 

1034 

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

1036 """ 

1037 Get an option by its dest. 

1038 

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

1040 it is undefined which option of those is returned. 

1041 

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

1043 dest. 

1044 """ 

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

1046 for option in group.option_list: 

1047 if option.dest == dest: 

1048 return option 

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

1050 

1051 

1052class ConfigParser(configparser.RawConfigParser): 

1053 """Parser for Docutils configuration files. 

1054 

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

1056 

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

1058 

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

1060 and the affected file(s) skipped. 

1061 

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

1063 """ 

1064 

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

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

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

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

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

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

1071 """ 

1072 

1073 old_warning: ClassVar[str] = ( 

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

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

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

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

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

1079 

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

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

1082Skipping "%s" configuration file. 

1083""" 

1084 

1085 def read(self, 

1086 filenames: str | Sequence[str], 

1087 option_parser: OptionParser | None = None, 

1088 ) -> list[str]: 

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

1090 # supplied, setting values are validated. 

1091 if option_parser is not None: 

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

1093 '"option_parser" will be removed ' 

1094 'in Docutils 2.0 or later.', 

1095 DeprecationWarning, stacklevel=2) 

1096 read_ok = [] 

1097 if isinstance(filenames, str): 

1098 filenames = [filenames] 

1099 for filename in filenames: 

1100 # Config files are UTF-8-encoded: 

1101 try: 

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

1103 except UnicodeDecodeError: 

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

1105 continue 

1106 if 'options' in self: 

1107 self.handle_old_config(filename) 

1108 if option_parser is not None: 

1109 self.validate_settings(filename, option_parser) 

1110 return read_ok 

1111 

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

1113 warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning, 

1114 filename, 0) 

1115 try: 

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

1117 except KeyError: 

1118 options = {} 

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

1120 self.add_section('general') 

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

1122 if key in self.old_settings: 

1123 section, setting = self.old_settings[key] 

1124 if not self.has_section(section): 

1125 self.add_section(section) 

1126 else: 

1127 section = 'general' 

1128 setting = key 

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

1130 self.set(section, setting, value) 

1131 self.remove_section('options') 

1132 

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

1134 ) -> None: 

1135 """ 

1136 Call the validator function and implement overrides on all applicable 

1137 settings. 

1138 """ 

1139 for section in self.sections(): 

1140 for setting in self.options(section): 

1141 try: 

1142 option = option_parser.get_option_by_dest(setting) 

1143 except KeyError: 

1144 continue 

1145 if option.validator: 

1146 value = self.get(section, setting) 

1147 try: 

1148 new_value = option.validator( 

1149 setting, value, option_parser, 

1150 config_parser=self, config_section=section) 

1151 except Exception as err: 

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

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

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

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

1156 self.set(section, setting, new_value) 

1157 if option.overrides: 

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

1159 

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

1161 """ 

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

1163 

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

1165 """ 

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

1167 

1168 

1169class ConfigDeprecationWarning(FutureWarning): 

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

1171 

1172 

1173def get_default_settings(*components: SettingsSpec) -> Values: 

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

1175 

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

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

1178 

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

1180 

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

1182 #settings-priority 

1183 """ 

1184 with warnings.catch_warnings(): 

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

1186 return OptionParser(components).get_default_values()