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