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