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