You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

854 lines
36 KiB

4 years ago
  1. # $Id: frontend.py 8126 2017-06-23 09:34:28Z milde $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. Command-line and common processing for Docutils front-end tools.
  6. Exports the following classes:
  7. * `OptionParser`: Standard Docutils command-line processing.
  8. * `Option`: Customized version of `optparse.Option`; validation support.
  9. * `Values`: Runtime settings; objects are simple structs
  10. (``object.attribute``). Supports cumulative list settings (attributes).
  11. * `ConfigParser`: Standard Docutils config file processing.
  12. Also exports the following functions:
  13. * Option callbacks: `store_multiple`, `read_config_file`.
  14. * Setting validators: `validate_encoding`,
  15. `validate_encoding_error_handler`,
  16. `validate_encoding_and_error_handler`,
  17. `validate_boolean`, `validate_ternary`, `validate_threshold`,
  18. `validate_colon_separated_string_list`,
  19. `validate_comma_separated_string_list`,
  20. `validate_dependency_file`.
  21. * `make_paths_absolute`.
  22. * SettingSpec manipulation: `filter_settings_spec`.
  23. """
  24. __docformat__ = 'reStructuredText'
  25. import os
  26. import os.path
  27. import sys
  28. import warnings
  29. import configparser as CP
  30. import codecs
  31. import optparse
  32. from optparse import SUPPRESS_HELP
  33. import docutils
  34. import docutils.utils
  35. import docutils.nodes
  36. from docutils.utils.error_reporting import (locale_encoding, SafeString,
  37. ErrorOutput, ErrorString)
  38. def store_multiple(option, opt, value, parser, *args, **kwargs):
  39. """
  40. Store multiple values in `parser.values`. (Option callback.)
  41. Store `None` for each attribute named in `args`, and store the value for
  42. each key (attribute name) in `kwargs`.
  43. """
  44. for attribute in args:
  45. setattr(parser.values, attribute, None)
  46. for key, value in list(kwargs.items()):
  47. setattr(parser.values, key, value)
  48. def read_config_file(option, opt, value, parser):
  49. """
  50. Read a configuration file during option processing. (Option callback.)
  51. """
  52. try:
  53. new_settings = parser.get_config_file_settings(value)
  54. except ValueError as error:
  55. parser.error(error)
  56. parser.values.update(new_settings, parser)
  57. def validate_encoding(setting, value, option_parser,
  58. config_parser=None, config_section=None):
  59. try:
  60. codecs.lookup(value)
  61. except LookupError:
  62. raise LookupError('setting "%s": unknown encoding: "%s"'
  63. % (setting, value))
  64. return value
  65. def validate_encoding_error_handler(setting, value, option_parser,
  66. config_parser=None, config_section=None):
  67. try:
  68. codecs.lookup_error(value)
  69. except LookupError:
  70. raise LookupError(
  71. 'unknown encoding error handler: "%s" (choices: '
  72. '"strict", "ignore", "replace", "backslashreplace", '
  73. '"xmlcharrefreplace", and possibly others; see documentation for '
  74. 'the Python ``codecs`` module)' % value)
  75. return value
  76. def validate_encoding_and_error_handler(
  77. setting, value, option_parser, config_parser=None, config_section=None):
  78. """
  79. Side-effect: if an error handler is included in the value, it is inserted
  80. into the appropriate place as if it was a separate setting/option.
  81. """
  82. if ':' in value:
  83. encoding, handler = value.split(':')
  84. validate_encoding_error_handler(
  85. setting + '_error_handler', handler, option_parser,
  86. config_parser, config_section)
  87. if config_parser:
  88. config_parser.set(config_section, setting + '_error_handler',
  89. handler)
  90. else:
  91. setattr(option_parser.values, setting + '_error_handler', handler)
  92. else:
  93. encoding = value
  94. validate_encoding(setting, encoding, option_parser,
  95. config_parser, config_section)
  96. return encoding
  97. def validate_boolean(setting, value, option_parser,
  98. config_parser=None, config_section=None):
  99. """Check/normalize boolean settings:
  100. True: '1', 'on', 'yes', 'true'
  101. False: '0', 'off', 'no','false', ''
  102. """
  103. if isinstance(value, bool):
  104. return value
  105. try:
  106. return option_parser.booleans[value.strip().lower()]
  107. except KeyError:
  108. raise LookupError('unknown boolean value: "%s"' % value)
  109. def validate_ternary(setting, value, option_parser,
  110. config_parser=None, config_section=None):
  111. """Check/normalize three-value settings:
  112. True: '1', 'on', 'yes', 'true'
  113. False: '0', 'off', 'no','false', ''
  114. any other value: returned as-is.
  115. """
  116. if isinstance(value, bool) or value is None:
  117. return value
  118. try:
  119. return option_parser.booleans[value.strip().lower()]
  120. except KeyError:
  121. return value
  122. def validate_nonnegative_int(setting, value, option_parser,
  123. config_parser=None, config_section=None):
  124. value = int(value)
  125. if value < 0:
  126. raise ValueError('negative value; must be positive or zero')
  127. return value
  128. def validate_threshold(setting, value, option_parser,
  129. config_parser=None, config_section=None):
  130. try:
  131. return int(value)
  132. except ValueError:
  133. try:
  134. return option_parser.thresholds[value.lower()]
  135. except (KeyError, AttributeError):
  136. raise LookupError('unknown threshold: %r.' % value)
  137. def validate_colon_separated_string_list(
  138. setting, value, option_parser, config_parser=None, config_section=None):
  139. if not isinstance(value, list):
  140. value = value.split(':')
  141. else:
  142. last = value.pop()
  143. value.extend(last.split(':'))
  144. return value
  145. def validate_comma_separated_list(setting, value, option_parser,
  146. config_parser=None, config_section=None):
  147. """Check/normalize list arguments (split at "," and strip whitespace).
  148. """
  149. # `value` is already a ``list`` when given as command line option
  150. # and "action" is "append" and ``unicode`` or ``str`` else.
  151. if not isinstance(value, list):
  152. value = [value]
  153. # this function is called for every option added to `value`
  154. # -> split the last item and append the result:
  155. last = value.pop()
  156. items = [i.strip(' \t\n') for i in last.split(',') if i.strip(' \t\n')]
  157. value.extend(items)
  158. return value
  159. def validate_url_trailing_slash(
  160. setting, value, option_parser, config_parser=None, config_section=None):
  161. if not value:
  162. return './'
  163. elif value.endswith('/'):
  164. return value
  165. else:
  166. return value + '/'
  167. def validate_dependency_file(setting, value, option_parser,
  168. config_parser=None, config_section=None):
  169. try:
  170. return docutils.utils.DependencyList(value)
  171. except IOError:
  172. return docutils.utils.DependencyList(None)
  173. def validate_strip_class(setting, value, option_parser,
  174. config_parser=None, config_section=None):
  175. # value is a comma separated string list:
  176. value = validate_comma_separated_list(setting, value, option_parser,
  177. config_parser, config_section)
  178. # validate list elements:
  179. for cls in value:
  180. normalized = docutils.nodes.make_id(cls)
  181. if cls != normalized:
  182. raise ValueError('Invalid class value %r (perhaps %r?)'
  183. % (cls, normalized))
  184. return value
  185. def validate_smartquotes_locales(setting, value, option_parser,
  186. config_parser=None, config_section=None):
  187. """Check/normalize a comma separated list of smart quote definitions.
  188. Return a list of (language-tag, quotes) string tuples."""
  189. # value is a comma separated string list:
  190. value = validate_comma_separated_list(setting, value, option_parser,
  191. config_parser, config_section)
  192. # validate list elements
  193. lc_quotes = []
  194. for item in value:
  195. try:
  196. lang, quotes = item.split(':', 1)
  197. except AttributeError:
  198. # this function is called for every option added to `value`
  199. # -> ignore if already a tuple:
  200. lc_quotes.append(item)
  201. continue
  202. except ValueError:
  203. raise ValueError('Invalid value "%s".'
  204. ' Format is "<language>:<quotes>".'
  205. % item.encode('ascii', 'backslashreplace'))
  206. # parse colon separated string list:
  207. quotes = quotes.strip()
  208. multichar_quotes = quotes.split(':')
  209. if len(multichar_quotes) == 4:
  210. quotes = multichar_quotes
  211. elif len(quotes) != 4:
  212. raise ValueError('Invalid value "%s". Please specify 4 quotes\n'
  213. ' (primary open/close; secondary open/close).'
  214. % item.encode('ascii', 'backslashreplace'))
  215. lc_quotes.append((lang,quotes))
  216. return lc_quotes
  217. def make_paths_absolute(pathdict, keys, base_path=None):
  218. """
  219. Interpret filesystem path settings relative to the `base_path` given.
  220. Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
  221. `OptionParser.relative_path_settings`.
  222. """
  223. if base_path is None:
  224. base_path = os.getcwd() # type(base_path) == unicode
  225. # to allow combining non-ASCII cwd with unicode values in `pathdict`
  226. for key in keys:
  227. if key in pathdict:
  228. value = pathdict[key]
  229. if isinstance(value, list):
  230. value = [make_one_path_absolute(base_path, path)
  231. for path in value]
  232. elif value:
  233. value = make_one_path_absolute(base_path, value)
  234. pathdict[key] = value
  235. def make_one_path_absolute(base_path, path):
  236. return os.path.abspath(os.path.join(base_path, path))
  237. def filter_settings_spec(settings_spec, *exclude, **replace):
  238. """Return a copy of `settings_spec` excluding/replacing some settings.
  239. `settings_spec` is a tuple of configuration settings with a structure
  240. described for docutils.SettingsSpec.settings_spec.
  241. Optional positional arguments are names of to-be-excluded settings.
  242. Keyword arguments are option specification replacements.
  243. (See the html4strict writer for an example.)
  244. """
  245. settings = list(settings_spec)
  246. # every third item is a sequence of option tuples
  247. for i in range(2, len(settings), 3):
  248. newopts = []
  249. for opt_spec in settings[i]:
  250. # opt_spec is ("<help>", [<option strings>], {<keyword args>})
  251. opt_name = [opt_string[2:].replace('-', '_')
  252. for opt_string in opt_spec[1]
  253. if opt_string.startswith('--')
  254. ][0]
  255. if opt_name in exclude:
  256. continue
  257. if opt_name in list(replace.keys()):
  258. newopts.append(replace[opt_name])
  259. else:
  260. newopts.append(opt_spec)
  261. settings[i] = tuple(newopts)
  262. return tuple(settings)
  263. class Values(optparse.Values):
  264. """
  265. Updates list attributes by extension rather than by replacement.
  266. Works in conjunction with the `OptionParser.lists` instance attribute.
  267. """
  268. def __init__(self, *args, **kwargs):
  269. optparse.Values.__init__(self, *args, **kwargs)
  270. if (not hasattr(self, 'record_dependencies')
  271. or self.record_dependencies is None):
  272. # Set up dependency list, in case it is needed.
  273. self.record_dependencies = docutils.utils.DependencyList()
  274. def update(self, other_dict, option_parser):
  275. if isinstance(other_dict, Values):
  276. other_dict = other_dict.__dict__
  277. other_dict = other_dict.copy()
  278. for setting in list(option_parser.lists.keys()):
  279. if (hasattr(self, setting) and setting in other_dict):
  280. value = getattr(self, setting)
  281. if value:
  282. value += other_dict[setting]
  283. del other_dict[setting]
  284. self._update_loose(other_dict)
  285. def copy(self):
  286. """Return a shallow copy of `self`."""
  287. return self.__class__(defaults=self.__dict__)
  288. class Option(optparse.Option):
  289. ATTRS = optparse.Option.ATTRS + ['validator', 'overrides']
  290. def process(self, opt, value, values, parser):
  291. """
  292. Call the validator function on applicable settings and
  293. evaluate the 'overrides' option.
  294. Extends `optparse.Option.process`.
  295. """
  296. result = optparse.Option.process(self, opt, value, values, parser)
  297. setting = self.dest
  298. if setting:
  299. if self.validator:
  300. value = getattr(values, setting)
  301. try:
  302. new_value = self.validator(setting, value, parser)
  303. except Exception as error:
  304. raise optparse.OptionValueError(
  305. 'Error in option "%s":\n %s'
  306. % (opt, ErrorString(error)))
  307. setattr(values, setting, new_value)
  308. if self.overrides:
  309. setattr(values, self.overrides, None)
  310. return result
  311. class OptionParser(optparse.OptionParser, docutils.SettingsSpec):
  312. """
  313. Parser for command-line and library use. The `settings_spec`
  314. specification here and in other Docutils components are merged to build
  315. the set of command-line options and runtime settings for this process.
  316. Common settings (defined below) and component-specific settings must not
  317. conflict. Short options are reserved for common settings, and components
  318. are restrict to using long options.
  319. """
  320. standard_config_files = [
  321. '/etc/docutils.conf', # system-wide
  322. './docutils.conf', # project-specific
  323. '~/.docutils'] # user-specific
  324. """Docutils configuration files, using ConfigParser syntax. Filenames
  325. will be tilde-expanded later. Later files override earlier ones."""
  326. threshold_choices = 'info 1 warning 2 error 3 severe 4 none 5'.split()
  327. """Possible inputs for for --report and --halt threshold values."""
  328. thresholds = {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
  329. """Lookup table for --report and --halt threshold values."""
  330. booleans={'1': True, 'on': True, 'yes': True, 'true': True,
  331. '0': False, 'off': False, 'no': False, 'false': False, '': False}
  332. """Lookup table for boolean configuration file settings."""
  333. default_error_encoding = getattr(sys.stderr, 'encoding',
  334. None) or locale_encoding or 'ascii'
  335. default_error_encoding_error_handler = 'backslashreplace'
  336. settings_spec = (
  337. 'General Docutils Options',
  338. None,
  339. (('Specify the document title as metadata.',
  340. ['--title'], {}),
  341. ('Include a "Generated by Docutils" credit and link.',
  342. ['--generator', '-g'], {'action': 'store_true',
  343. 'validator': validate_boolean}),
  344. ('Do not include a generator credit.',
  345. ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
  346. ('Include the date at the end of the document (UTC).',
  347. ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
  348. 'dest': 'datestamp'}),
  349. ('Include the time & date (UTC).',
  350. ['--time', '-t'], {'action': 'store_const',
  351. 'const': '%Y-%m-%d %H:%M UTC',
  352. 'dest': 'datestamp'}),
  353. ('Do not include a datestamp of any kind.',
  354. ['--no-datestamp'], {'action': 'store_const', 'const': None,
  355. 'dest': 'datestamp'}),
  356. ('Include a "View document source" link.',
  357. ['--source-link', '-s'], {'action': 'store_true',
  358. 'validator': validate_boolean}),
  359. ('Use <URL> for a source link; implies --source-link.',
  360. ['--source-url'], {'metavar': '<URL>'}),
  361. ('Do not include a "View document source" link.',
  362. ['--no-source-link'],
  363. {'action': 'callback', 'callback': store_multiple,
  364. 'callback_args': ('source_link', 'source_url')}),
  365. ('Link from section headers to TOC entries. (default)',
  366. ['--toc-entry-backlinks'],
  367. {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
  368. 'default': 'entry'}),
  369. ('Link from section headers to the top of the TOC.',
  370. ['--toc-top-backlinks'],
  371. {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
  372. ('Disable backlinks to the table of contents.',
  373. ['--no-toc-backlinks'],
  374. {'dest': 'toc_backlinks', 'action': 'store_false'}),
  375. ('Link from footnotes/citations to references. (default)',
  376. ['--footnote-backlinks'],
  377. {'action': 'store_true', 'default': 1,
  378. 'validator': validate_boolean}),
  379. ('Disable backlinks from footnotes and citations.',
  380. ['--no-footnote-backlinks'],
  381. {'dest': 'footnote_backlinks', 'action': 'store_false'}),
  382. ('Enable section numbering by Docutils. (default)',
  383. ['--section-numbering'],
  384. {'action': 'store_true', 'dest': 'sectnum_xform',
  385. 'default': 1, 'validator': validate_boolean}),
  386. ('Disable section numbering by Docutils.',
  387. ['--no-section-numbering'],
  388. {'action': 'store_false', 'dest': 'sectnum_xform'}),
  389. ('Remove comment elements from the document tree.',
  390. ['--strip-comments'],
  391. {'action': 'store_true', 'validator': validate_boolean}),
  392. ('Leave comment elements in the document tree. (default)',
  393. ['--leave-comments'],
  394. {'action': 'store_false', 'dest': 'strip_comments'}),
  395. ('Remove all elements with classes="<class>" from the document tree. '
  396. 'Warning: potentially dangerous; use with caution. '
  397. '(Multiple-use option.)',
  398. ['--strip-elements-with-class'],
  399. {'action': 'append', 'dest': 'strip_elements_with_classes',
  400. 'metavar': '<class>', 'validator': validate_strip_class}),
  401. ('Remove all classes="<class>" attributes from elements in the '
  402. 'document tree. Warning: potentially dangerous; use with caution. '
  403. '(Multiple-use option.)',
  404. ['--strip-class'],
  405. {'action': 'append', 'dest': 'strip_classes',
  406. 'metavar': '<class>', 'validator': validate_strip_class}),
  407. ('Report system messages at or higher than <level>: "info" or "1", '
  408. '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
  409. ['--report', '-r'], {'choices': threshold_choices, 'default': 2,
  410. 'dest': 'report_level', 'metavar': '<level>',
  411. 'validator': validate_threshold}),
  412. ('Report all system messages. (Same as "--report=1".)',
  413. ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
  414. 'dest': 'report_level'}),
  415. ('Report no system messages. (Same as "--report=5".)',
  416. ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
  417. 'dest': 'report_level'}),
  418. ('Halt execution at system messages at or above <level>. '
  419. 'Levels as in --report. Default: 4 (severe).',
  420. ['--halt'], {'choices': threshold_choices, 'dest': 'halt_level',
  421. 'default': 4, 'metavar': '<level>',
  422. 'validator': validate_threshold}),
  423. ('Halt at the slightest problem. Same as "--halt=info".',
  424. ['--strict'], {'action': 'store_const', 'const': 1,
  425. 'dest': 'halt_level'}),
  426. ('Enable a non-zero exit status for non-halting system messages at '
  427. 'or above <level>. Default: 5 (disabled).',
  428. ['--exit-status'], {'choices': threshold_choices,
  429. 'dest': 'exit_status_level',
  430. 'default': 5, 'metavar': '<level>',
  431. 'validator': validate_threshold}),
  432. ('Enable debug-level system messages and diagnostics.',
  433. ['--debug'], {'action': 'store_true', 'validator': validate_boolean}),
  434. ('Disable debug output. (default)',
  435. ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
  436. ('Send the output of system messages to <file>.',
  437. ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
  438. ('Enable Python tracebacks when Docutils is halted.',
  439. ['--traceback'], {'action': 'store_true', 'default': None,
  440. 'validator': validate_boolean}),
  441. ('Disable Python tracebacks. (default)',
  442. ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
  443. ('Specify the encoding and optionally the '
  444. 'error handler of input text. Default: <locale-dependent>:strict.',
  445. ['--input-encoding', '-i'],
  446. {'metavar': '<name[:handler]>',
  447. 'validator': validate_encoding_and_error_handler}),
  448. ('Specify the error handler for undecodable characters. '
  449. 'Choices: "strict" (default), "ignore", and "replace".',
  450. ['--input-encoding-error-handler'],
  451. {'default': 'strict', 'validator': validate_encoding_error_handler}),
  452. ('Specify the text encoding and optionally the error handler for '
  453. 'output. Default: UTF-8:strict.',
  454. ['--output-encoding', '-o'],
  455. {'metavar': '<name[:handler]>', 'default': 'utf-8',
  456. 'validator': validate_encoding_and_error_handler}),
  457. ('Specify error handler for unencodable output characters; '
  458. '"strict" (default), "ignore", "replace", '
  459. '"xmlcharrefreplace", "backslashreplace".',
  460. ['--output-encoding-error-handler'],
  461. {'default': 'strict', 'validator': validate_encoding_error_handler}),
  462. ('Specify text encoding and error handler for error output. '
  463. 'Default: %s:%s.'
  464. % (default_error_encoding, default_error_encoding_error_handler),
  465. ['--error-encoding', '-e'],
  466. {'metavar': '<name[:handler]>', 'default': default_error_encoding,
  467. 'validator': validate_encoding_and_error_handler}),
  468. ('Specify the error handler for unencodable characters in '
  469. 'error output. Default: %s.'
  470. % default_error_encoding_error_handler,
  471. ['--error-encoding-error-handler'],
  472. {'default': default_error_encoding_error_handler,
  473. 'validator': validate_encoding_error_handler}),
  474. ('Specify the language (as BCP 47 language tag). Default: en.',
  475. ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
  476. 'metavar': '<name>'}),
  477. ('Write output file dependencies to <file>.',
  478. ['--record-dependencies'],
  479. {'metavar': '<file>', 'validator': validate_dependency_file,
  480. 'default': None}), # default set in Values class
  481. ('Read configuration settings from <file>, if it exists.',
  482. ['--config'], {'metavar': '<file>', 'type': 'string',
  483. 'action': 'callback', 'callback': read_config_file}),
  484. ("Show this program's version number and exit.",
  485. ['--version', '-V'], {'action': 'version'}),
  486. ('Show this help message and exit.',
  487. ['--help', '-h'], {'action': 'help'}),
  488. # Typically not useful for non-programmatical use:
  489. (SUPPRESS_HELP, ['--id-prefix'], {'default': ''}),
  490. (SUPPRESS_HELP, ['--auto-id-prefix'], {'default': 'id'}),
  491. # Hidden options, for development use only:
  492. (SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}),
  493. (SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}),
  494. (SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}),
  495. (SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}),
  496. (SUPPRESS_HELP, ['--expose-internal-attribute'],
  497. {'action': 'append', 'dest': 'expose_internals',
  498. 'validator': validate_colon_separated_string_list}),
  499. (SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}),
  500. ))
  501. """Runtime settings and command-line options common to all Docutils front
  502. ends. Setting specs specific to individual Docutils components are also
  503. used (see `populate_from_components()`)."""
  504. settings_defaults = {'_disable_config': None,
  505. '_source': None,
  506. '_destination': None,
  507. '_config_files': None}
  508. """Defaults for settings that don't have command-line option equivalents."""
  509. relative_path_settings = ('warning_stream',)
  510. config_section = 'general'
  511. version_template = ('%%prog (Docutils %s%s, Python %s, on %s)'
  512. % (docutils.__version__,
  513. docutils.__version_details__ and
  514. ' [%s]'%docutils.__version_details__ or '',
  515. sys.version.split()[0], sys.platform))
  516. """Default version message."""
  517. def __init__(self, components=(), defaults=None, read_config_files=None,
  518. *args, **kwargs):
  519. """
  520. `components` is a list of Docutils components each containing a
  521. ``.settings_spec`` attribute. `defaults` is a mapping of setting
  522. default overrides.
  523. """
  524. self.lists = {}
  525. """Set of list-type settings."""
  526. self.config_files = []
  527. """List of paths of applied configuration files."""
  528. optparse.OptionParser.__init__(
  529. self, option_class=Option, add_help_option=None,
  530. formatter=optparse.TitledHelpFormatter(width=78),
  531. *args, **kwargs)
  532. if not self.version:
  533. self.version = self.version_template
  534. # Make an instance copy (it will be modified):
  535. self.relative_path_settings = list(self.relative_path_settings)
  536. self.components = (self,) + tuple(components)
  537. self.populate_from_components(self.components)
  538. self.set_defaults_from_dict(defaults or {})
  539. if read_config_files and not self.defaults['_disable_config']:
  540. try:
  541. config_settings = self.get_standard_config_settings()
  542. except ValueError as error:
  543. self.error(SafeString(error))
  544. self.set_defaults_from_dict(config_settings.__dict__)
  545. def populate_from_components(self, components):
  546. """
  547. For each component, first populate from the `SettingsSpec.settings_spec`
  548. structure, then from the `SettingsSpec.settings_defaults` dictionary.
  549. After all components have been processed, check for and populate from
  550. each component's `SettingsSpec.settings_default_overrides` dictionary.
  551. """
  552. for component in components:
  553. if component is None:
  554. continue
  555. settings_spec = component.settings_spec
  556. self.relative_path_settings.extend(
  557. component.relative_path_settings)
  558. for i in range(0, len(settings_spec), 3):
  559. title, description, option_spec = settings_spec[i:i+3]
  560. if title:
  561. group = optparse.OptionGroup(self, title, description)
  562. self.add_option_group(group)
  563. else:
  564. group = self # single options
  565. for (help_text, option_strings, kwargs) in option_spec:
  566. option = group.add_option(help=help_text, *option_strings,
  567. **kwargs)
  568. if kwargs.get('action') == 'append':
  569. self.lists[option.dest] = 1
  570. if component.settings_defaults:
  571. self.defaults.update(component.settings_defaults)
  572. for component in components:
  573. if component and component.settings_default_overrides:
  574. self.defaults.update(component.settings_default_overrides)
  575. def get_standard_config_files(self):
  576. """Return list of config files, from environment or standard."""
  577. try:
  578. config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep)
  579. except KeyError:
  580. config_files = self.standard_config_files
  581. # If 'HOME' is not set, expandvars() requires the 'pwd' module which is
  582. # not available under certain environments, for example, within
  583. # mod_python. The publisher ends up in here, and we need to publish
  584. # from within mod_python. Therefore we need to avoid expanding when we
  585. # are in those environments.
  586. expand = os.path.expanduser
  587. if 'HOME' not in os.environ:
  588. try:
  589. import pwd
  590. except ImportError:
  591. expand = lambda x: x
  592. return [expand(f) for f in config_files if f.strip()]
  593. def get_standard_config_settings(self):
  594. settings = Values()
  595. for filename in self.get_standard_config_files():
  596. settings.update(self.get_config_file_settings(filename), self)
  597. return settings
  598. def get_config_file_settings(self, config_file):
  599. """Returns a dictionary containing appropriate config file settings."""
  600. parser = ConfigParser()
  601. parser.read(config_file, self)
  602. self.config_files.extend(parser._files)
  603. base_path = os.path.dirname(config_file)
  604. applied = {}
  605. settings = Values()
  606. for component in self.components:
  607. if not component:
  608. continue
  609. for section in (tuple(component.config_section_dependencies or ())
  610. + (component.config_section,)):
  611. if section in applied:
  612. continue
  613. applied[section] = 1
  614. settings.update(parser.get_section(section), self)
  615. make_paths_absolute(
  616. settings.__dict__, self.relative_path_settings, base_path)
  617. return settings.__dict__
  618. def check_values(self, values, args):
  619. """Store positional arguments as runtime settings."""
  620. values._source, values._destination = self.check_args(args)
  621. make_paths_absolute(values.__dict__, self.relative_path_settings)
  622. values._config_files = self.config_files
  623. return values
  624. def check_args(self, args):
  625. source = destination = None
  626. if args:
  627. source = args.pop(0)
  628. if source == '-': # means stdin
  629. source = None
  630. if args:
  631. destination = args.pop(0)
  632. if destination == '-': # means stdout
  633. destination = None
  634. if args:
  635. self.error('Maximum 2 arguments allowed.')
  636. if source and source == destination:
  637. self.error('Do not specify the same file for both source and '
  638. 'destination. It will clobber the source file.')
  639. return source, destination
  640. def set_defaults_from_dict(self, defaults):
  641. self.defaults.update(defaults)
  642. def get_default_values(self):
  643. """Needed to get custom `Values` instances."""
  644. defaults = Values(self.defaults)
  645. defaults._config_files = self.config_files
  646. return defaults
  647. def get_option_by_dest(self, dest):
  648. """
  649. Get an option by its dest.
  650. If you're supplying a dest which is shared by several options,
  651. it is undefined which option of those is returned.
  652. A KeyError is raised if there is no option with the supplied
  653. dest.
  654. """
  655. for group in self.option_groups + [self]:
  656. for option in group.option_list:
  657. if option.dest == dest:
  658. return option
  659. raise KeyError('No option with dest == %r.' % dest)
  660. class ConfigParser(CP.RawConfigParser):
  661. old_settings = {
  662. 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
  663. 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
  664. 'pep_template': ('pep_html writer', 'template')}
  665. """{old setting: (new section, new setting)} mapping, used by
  666. `handle_old_config`, to convert settings from the old [options] section."""
  667. old_warning = """
  668. The "[option]" section is deprecated. Support for old-format configuration
  669. files may be removed in a future Docutils release. Please revise your
  670. configuration files. See <http://docutils.sf.net/docs/user/config.html>,
  671. section "Old-Format Configuration Files".
  672. """
  673. not_utf8_error = """\
  674. Unable to read configuration file "%s": content not encoded as UTF-8.
  675. Skipping "%s" configuration file.
  676. """
  677. def __init__(self, *args, **kwargs):
  678. CP.RawConfigParser.__init__(self, *args, **kwargs)
  679. self._files = []
  680. """List of paths of configuration files read."""
  681. self._stderr = ErrorOutput()
  682. """Wrapper around sys.stderr catching en-/decoding errors"""
  683. def read(self, filenames, option_parser):
  684. if type(filenames) in (str, str):
  685. filenames = [filenames]
  686. for filename in filenames:
  687. try:
  688. # Config files must be UTF-8-encoded:
  689. fp = codecs.open(filename, 'r', 'utf-8')
  690. except IOError:
  691. continue
  692. try:
  693. if sys.version_info < (3,2):
  694. CP.RawConfigParser.readfp(self, fp, filename)
  695. else:
  696. CP.RawConfigParser.read_file(self, fp, filename)
  697. except UnicodeDecodeError:
  698. self._stderr.write(self.not_utf8_error % (filename, filename))
  699. fp.close()
  700. continue
  701. fp.close()
  702. self._files.append(filename)
  703. if self.has_section('options'):
  704. self.handle_old_config(filename)
  705. self.validate_settings(filename, option_parser)
  706. def handle_old_config(self, filename):
  707. warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning,
  708. filename, 0)
  709. options = self.get_section('options')
  710. if not self.has_section('general'):
  711. self.add_section('general')
  712. for key, value in list(options.items()):
  713. if key in self.old_settings:
  714. section, setting = self.old_settings[key]
  715. if not self.has_section(section):
  716. self.add_section(section)
  717. else:
  718. section = 'general'
  719. setting = key
  720. if not self.has_option(section, setting):
  721. self.set(section, setting, value)
  722. self.remove_section('options')
  723. def validate_settings(self, filename, option_parser):
  724. """
  725. Call the validator function and implement overrides on all applicable
  726. settings.
  727. """
  728. for section in self.sections():
  729. for setting in self.options(section):
  730. try:
  731. option = option_parser.get_option_by_dest(setting)
  732. except KeyError:
  733. continue
  734. if option.validator:
  735. value = self.get(section, setting)
  736. try:
  737. new_value = option.validator(
  738. setting, value, option_parser,
  739. config_parser=self, config_section=section)
  740. except Exception as error:
  741. raise ValueError(
  742. 'Error in config file "%s", section "[%s]":\n'
  743. ' %s\n'
  744. ' %s = %s'
  745. % (filename, section, ErrorString(error),
  746. setting, value))
  747. self.set(section, setting, new_value)
  748. if option.overrides:
  749. self.set(section, option.overrides, None)
  750. def optionxform(self, optionstr):
  751. """
  752. Transform '-' to '_' so the cmdline form of option names can be used.
  753. """
  754. return optionstr.lower().replace('-', '_')
  755. def get_section(self, section):
  756. """
  757. Return a given section as a dictionary (empty if the section
  758. doesn't exist).
  759. """
  760. section_dict = {}
  761. if self.has_section(section):
  762. for option in self.options(section):
  763. section_dict[option] = self.get(section, option)
  764. return section_dict
  765. class ConfigDeprecationWarning(DeprecationWarning):
  766. """Warning for deprecated configuration file features."""