Fix deprecation warning with Python 3.2
[docutils.git] / docutils / frontend.py
blobb4cde7514e997a0ac76a55ff6d03f6cfd769a7fb
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
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 if config_parser: # validate all values
167 class_values = value
168 else: # just validate the latest value
169 class_values = [value[-1]]
170 for class_value in class_values:
171 normalized = docutils.nodes.make_id(class_value)
172 if class_value != normalized:
173 raise ValueError('invalid class value %r (perhaps %r?)'
174 % (class_value, normalized))
175 return value
177 def make_paths_absolute(pathdict, keys, base_path=None):
179 Interpret filesystem path settings relative to the `base_path` given.
181 Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
182 `OptionParser.relative_path_settings`.
184 if base_path is None:
185 base_path = os.getcwd()
186 for key in keys:
187 if key in pathdict:
188 value = pathdict[key]
189 if isinstance(value, list):
190 value = [make_one_path_absolute(base_path, path)
191 for path in value]
192 elif value:
193 value = make_one_path_absolute(base_path, value)
194 pathdict[key] = value
196 def make_one_path_absolute(base_path, path):
197 return os.path.abspath(os.path.join(base_path, path))
199 def filter_settings_spec(settings_spec, *exclude, **replace):
200 """Return a copy of `settings_spec` excluding/replacing some settings.
202 `settings_spec` is a tuple of configuration settings with a structure
203 described for docutils.SettingsSpec.settings_spec.
205 Optional positional arguments are names of to-be-excluded settings.
206 Keyword arguments are option specification replacements.
207 (See the html4strict writer for an example.)
209 settings = list(settings_spec)
210 # every third item is a sequence of option tuples
211 for i in range(2, len(settings), 3):
212 newopts = []
213 for opt_spec in settings[i]:
214 # opt_spec is ("<help>", [<option strings>], {<keyword args>})
215 opt_name = [opt_string[2:].replace('-', '_')
216 for opt_string in opt_spec[1]
217 if opt_string.startswith('--')
218 ][0]
219 if opt_name in exclude:
220 continue
221 if opt_name in replace.keys():
222 newopts.append(replace[opt_name])
223 else:
224 newopts.append(opt_spec)
225 settings[i] = tuple(newopts)
226 return tuple(settings)
229 class Values(optparse.Values):
232 Updates list attributes by extension rather than by replacement.
233 Works in conjunction with the `OptionParser.lists` instance attribute.
236 def __init__(self, *args, **kwargs):
237 optparse.Values.__init__(self, *args, **kwargs)
238 if (not hasattr(self, 'record_dependencies')
239 or self.record_dependencies is None):
240 # Set up dependency list, in case it is needed.
241 self.record_dependencies = docutils.utils.DependencyList()
243 def update(self, other_dict, option_parser):
244 if isinstance(other_dict, Values):
245 other_dict = other_dict.__dict__
246 other_dict = other_dict.copy()
247 for setting in option_parser.lists.keys():
248 if (hasattr(self, setting) and setting in other_dict):
249 value = getattr(self, setting)
250 if value:
251 value += other_dict[setting]
252 del other_dict[setting]
253 self._update_loose(other_dict)
255 def copy(self):
256 """Return a shallow copy of `self`."""
257 return self.__class__(defaults=self.__dict__)
260 class Option(optparse.Option):
262 ATTRS = optparse.Option.ATTRS + ['validator', 'overrides']
264 def process(self, opt, value, values, parser):
266 Call the validator function on applicable settings and
267 evaluate the 'overrides' option.
268 Extends `optparse.Option.process`.
270 result = optparse.Option.process(self, opt, value, values, parser)
271 setting = self.dest
272 if setting:
273 if self.validator:
274 value = getattr(values, setting)
275 try:
276 new_value = self.validator(setting, value, parser)
277 except Exception, error:
278 raise (optparse.OptionValueError(
279 'Error in option "%s":\n %s'
280 % (opt, ErrorString(error))),
281 None, sys.exc_info()[2])
282 setattr(values, setting, new_value)
283 if self.overrides:
284 setattr(values, self.overrides, None)
285 return result
288 class OptionParser(optparse.OptionParser, docutils.SettingsSpec):
291 Parser for command-line and library use. The `settings_spec`
292 specification here and in other Docutils components are merged to build
293 the set of command-line options and runtime settings for this process.
295 Common settings (defined below) and component-specific settings must not
296 conflict. Short options are reserved for common settings, and components
297 are restrict to using long options.
300 standard_config_files = [
301 '/etc/docutils.conf', # system-wide
302 './docutils.conf', # project-specific
303 '~/.docutils'] # user-specific
304 """Docutils configuration files, using ConfigParser syntax. Filenames
305 will be tilde-expanded later. Later files override earlier ones."""
307 threshold_choices = 'info 1 warning 2 error 3 severe 4 none 5'.split()
308 """Possible inputs for for --report and --halt threshold values."""
310 thresholds = {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
311 """Lookup table for --report and --halt threshold values."""
313 booleans={'1': 1, 'on': 1, 'yes': 1, 'true': 1,
314 '0': 0, 'off': 0, 'no': 0, 'false': 0, '': 0}
315 """Lookup table for boolean configuration file settings."""
317 default_error_encoding = getattr(sys.stderr, 'encoding',
318 None) or locale_encoding or 'ascii'
320 default_error_encoding_error_handler = 'backslashreplace'
322 settings_spec = (
323 'General Docutils Options',
324 None,
325 (('Specify the document title as metadata.',
326 ['--title'], {}),
327 ('Include a "Generated by Docutils" credit and link.',
328 ['--generator', '-g'], {'action': 'store_true',
329 'validator': validate_boolean}),
330 ('Do not include a generator credit.',
331 ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
332 ('Include the date at the end of the document (UTC).',
333 ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
334 'dest': 'datestamp'}),
335 ('Include the time & date (UTC).',
336 ['--time', '-t'], {'action': 'store_const',
337 'const': '%Y-%m-%d %H:%M UTC',
338 'dest': 'datestamp'}),
339 ('Do not include a datestamp of any kind.',
340 ['--no-datestamp'], {'action': 'store_const', 'const': None,
341 'dest': 'datestamp'}),
342 ('Include a "View document source" link.',
343 ['--source-link', '-s'], {'action': 'store_true',
344 'validator': validate_boolean}),
345 ('Use <URL> for a source link; implies --source-link.',
346 ['--source-url'], {'metavar': '<URL>'}),
347 ('Do not include a "View document source" link.',
348 ['--no-source-link'],
349 {'action': 'callback', 'callback': store_multiple,
350 'callback_args': ('source_link', 'source_url')}),
351 ('Link from section headers to TOC entries. (default)',
352 ['--toc-entry-backlinks'],
353 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
354 'default': 'entry'}),
355 ('Link from section headers to the top of the TOC.',
356 ['--toc-top-backlinks'],
357 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
358 ('Disable backlinks to the table of contents.',
359 ['--no-toc-backlinks'],
360 {'dest': 'toc_backlinks', 'action': 'store_false'}),
361 ('Link from footnotes/citations to references. (default)',
362 ['--footnote-backlinks'],
363 {'action': 'store_true', 'default': 1,
364 'validator': validate_boolean}),
365 ('Disable backlinks from footnotes and citations.',
366 ['--no-footnote-backlinks'],
367 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
368 ('Enable section numbering by Docutils. (default)',
369 ['--section-numbering'],
370 {'action': 'store_true', 'dest': 'sectnum_xform',
371 'default': 1, 'validator': validate_boolean}),
372 ('Disable section numbering by Docutils.',
373 ['--no-section-numbering'],
374 {'action': 'store_false', 'dest': 'sectnum_xform'}),
375 ('Remove comment elements from the document tree.',
376 ['--strip-comments'],
377 {'action': 'store_true', 'validator': validate_boolean}),
378 ('Leave comment elements in the document tree. (default)',
379 ['--leave-comments'],
380 {'action': 'store_false', 'dest': 'strip_comments'}),
381 ('Remove all elements with classes="<class>" from the document tree. '
382 'Warning: potentially dangerous; use with caution. '
383 '(Multiple-use option.)',
384 ['--strip-elements-with-class'],
385 {'action': 'append', 'dest': 'strip_elements_with_classes',
386 'metavar': '<class>', 'validator': validate_strip_class}),
387 ('Remove all classes="<class>" attributes from elements in the '
388 'document tree. Warning: potentially dangerous; use with caution. '
389 '(Multiple-use option.)',
390 ['--strip-class'],
391 {'action': 'append', 'dest': 'strip_classes',
392 'metavar': '<class>', 'validator': validate_strip_class}),
393 ('Report system messages at or higher than <level>: "info" or "1", '
394 '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
395 ['--report', '-r'], {'choices': threshold_choices, 'default': 2,
396 'dest': 'report_level', 'metavar': '<level>',
397 'validator': validate_threshold}),
398 ('Report all system messages. (Same as "--report=1".)',
399 ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
400 'dest': 'report_level'}),
401 ('Report no system messages. (Same as "--report=5".)',
402 ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
403 'dest': 'report_level'}),
404 ('Halt execution at system messages at or above <level>. '
405 'Levels as in --report. Default: 4 (severe).',
406 ['--halt'], {'choices': threshold_choices, 'dest': 'halt_level',
407 'default': 4, 'metavar': '<level>',
408 'validator': validate_threshold}),
409 ('Halt at the slightest problem. Same as "--halt=info".',
410 ['--strict'], {'action': 'store_const', 'const': 1,
411 'dest': 'halt_level'}),
412 ('Enable a non-zero exit status for non-halting system messages at '
413 'or above <level>. Default: 5 (disabled).',
414 ['--exit-status'], {'choices': threshold_choices,
415 'dest': 'exit_status_level',
416 'default': 5, 'metavar': '<level>',
417 'validator': validate_threshold}),
418 ('Enable debug-level system messages and diagnostics.',
419 ['--debug'], {'action': 'store_true', 'validator': validate_boolean}),
420 ('Disable debug output. (default)',
421 ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
422 ('Send the output of system messages to <file>.',
423 ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
424 ('Enable Python tracebacks when Docutils is halted.',
425 ['--traceback'], {'action': 'store_true', 'default': None,
426 'validator': validate_boolean}),
427 ('Disable Python tracebacks. (default)',
428 ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
429 ('Specify the encoding and optionally the '
430 'error handler of input text. Default: <locale-dependent>:strict.',
431 ['--input-encoding', '-i'],
432 {'metavar': '<name[:handler]>',
433 'validator': validate_encoding_and_error_handler}),
434 ('Specify the error handler for undecodable characters. '
435 'Choices: "strict" (default), "ignore", and "replace".',
436 ['--input-encoding-error-handler'],
437 {'default': 'strict', 'validator': validate_encoding_error_handler}),
438 ('Specify the text encoding and optionally the error handler for '
439 'output. Default: UTF-8:strict.',
440 ['--output-encoding', '-o'],
441 {'metavar': '<name[:handler]>', 'default': 'utf-8',
442 'validator': validate_encoding_and_error_handler}),
443 ('Specify error handler for unencodable output characters; '
444 '"strict" (default), "ignore", "replace", '
445 '"xmlcharrefreplace", "backslashreplace".',
446 ['--output-encoding-error-handler'],
447 {'default': 'strict', 'validator': validate_encoding_error_handler}),
448 ('Specify text encoding and error handler for error output. '
449 'Default: %s:%s.'
450 % (default_error_encoding, default_error_encoding_error_handler),
451 ['--error-encoding', '-e'],
452 {'metavar': '<name[:handler]>', 'default': default_error_encoding,
453 'validator': validate_encoding_and_error_handler}),
454 ('Specify the error handler for unencodable characters in '
455 'error output. Default: %s.'
456 % default_error_encoding_error_handler,
457 ['--error-encoding-error-handler'],
458 {'default': default_error_encoding_error_handler,
459 'validator': validate_encoding_error_handler}),
460 ('Specify the language (as BCP 47 language tag). Default: en.',
461 ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
462 'metavar': '<name>'}),
463 ('Write output file dependencies to <file>.',
464 ['--record-dependencies'],
465 {'metavar': '<file>', 'validator': validate_dependency_file,
466 'default': None}), # default set in Values class
467 ('Read configuration settings from <file>, if it exists.',
468 ['--config'], {'metavar': '<file>', 'type': 'string',
469 'action': 'callback', 'callback': read_config_file}),
470 ("Show this program's version number and exit.",
471 ['--version', '-V'], {'action': 'version'}),
472 ('Show this help message and exit.',
473 ['--help', '-h'], {'action': 'help'}),
474 # Typically not useful for non-programmatical use:
475 (SUPPRESS_HELP, ['--id-prefix'], {'default': ''}),
476 (SUPPRESS_HELP, ['--auto-id-prefix'], {'default': 'id'}),
477 # Hidden options, for development use only:
478 (SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}),
479 (SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}),
480 (SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}),
481 (SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}),
482 (SUPPRESS_HELP, ['--expose-internal-attribute'],
483 {'action': 'append', 'dest': 'expose_internals',
484 'validator': validate_colon_separated_string_list}),
485 (SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}),
487 """Runtime settings and command-line options common to all Docutils front
488 ends. Setting specs specific to individual Docutils components are also
489 used (see `populate_from_components()`)."""
491 settings_defaults = {'_disable_config': None,
492 '_source': None,
493 '_destination': None,
494 '_config_files': None}
495 """Defaults for settings that don't have command-line option equivalents."""
497 relative_path_settings = ('warning_stream',)
499 config_section = 'general'
501 version_template = ('%%prog (Docutils %s [%s], Python %s, on %s)'
502 % (docutils.__version__, docutils.__version_details__,
503 sys.version.split()[0], sys.platform))
504 """Default version message."""
506 def __init__(self, components=(), defaults=None, read_config_files=None,
507 *args, **kwargs):
509 `components` is a list of Docutils components each containing a
510 ``.settings_spec`` attribute. `defaults` is a mapping of setting
511 default overrides.
514 self.lists = {}
515 """Set of list-type settings."""
517 self.config_files = []
518 """List of paths of applied configuration files."""
520 optparse.OptionParser.__init__(
521 self, option_class=Option, add_help_option=None,
522 formatter=optparse.TitledHelpFormatter(width=78),
523 *args, **kwargs)
524 if not self.version:
525 self.version = self.version_template
526 # Make an instance copy (it will be modified):
527 self.relative_path_settings = list(self.relative_path_settings)
528 self.components = (self,) + tuple(components)
529 self.populate_from_components(self.components)
530 self.set_defaults_from_dict(defaults or {})
531 if read_config_files and not self.defaults['_disable_config']:
532 try:
533 config_settings = self.get_standard_config_settings()
534 except ValueError, error:
535 self.error(error)
536 self.set_defaults_from_dict(config_settings.__dict__)
538 def populate_from_components(self, components):
540 For each component, first populate from the `SettingsSpec.settings_spec`
541 structure, then from the `SettingsSpec.settings_defaults` dictionary.
542 After all components have been processed, check for and populate from
543 each component's `SettingsSpec.settings_default_overrides` dictionary.
545 for component in components:
546 if component is None:
547 continue
548 settings_spec = component.settings_spec
549 self.relative_path_settings.extend(
550 component.relative_path_settings)
551 for i in range(0, len(settings_spec), 3):
552 title, description, option_spec = settings_spec[i:i+3]
553 if title:
554 group = optparse.OptionGroup(self, title, description)
555 self.add_option_group(group)
556 else:
557 group = self # single options
558 for (help_text, option_strings, kwargs) in option_spec:
559 option = group.add_option(help=help_text, *option_strings,
560 **kwargs)
561 if kwargs.get('action') == 'append':
562 self.lists[option.dest] = 1
563 if component.settings_defaults:
564 self.defaults.update(component.settings_defaults)
565 for component in components:
566 if component and component.settings_default_overrides:
567 self.defaults.update(component.settings_default_overrides)
569 def get_standard_config_files(self):
570 """Return list of config files, from environment or standard."""
571 try:
572 config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep)
573 except KeyError:
574 config_files = self.standard_config_files
576 # If 'HOME' is not set, expandvars() requires the 'pwd' module which is
577 # not available under certain environments, for example, within
578 # mod_python. The publisher ends up in here, and we need to publish
579 # from within mod_python. Therefore we need to avoid expanding when we
580 # are in those environments.
581 expand = os.path.expanduser
582 if 'HOME' not in os.environ:
583 try:
584 import pwd
585 except ImportError:
586 expand = lambda x: x
587 return [expand(f) for f in config_files if f.strip()]
589 def get_standard_config_settings(self):
590 settings = Values()
591 for filename in self.get_standard_config_files():
592 settings.update(self.get_config_file_settings(filename), self)
593 return settings
595 def get_config_file_settings(self, config_file):
596 """Returns a dictionary containing appropriate config file settings."""
597 parser = ConfigParser()
598 parser.read(config_file, self)
599 self.config_files.extend(parser._files)
600 base_path = os.path.dirname(config_file)
601 applied = {}
602 settings = Values()
603 for component in self.components:
604 if not component:
605 continue
606 for section in (tuple(component.config_section_dependencies or ())
607 + (component.config_section,)):
608 if section in applied:
609 continue
610 applied[section] = 1
611 settings.update(parser.get_section(section), self)
612 make_paths_absolute(
613 settings.__dict__, self.relative_path_settings, base_path)
614 return settings.__dict__
616 def check_values(self, values, args):
617 """Store positional arguments as runtime settings."""
618 values._source, values._destination = self.check_args(args)
619 make_paths_absolute(values.__dict__, self.relative_path_settings,
620 os.getcwd())
621 values._config_files = self.config_files
622 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
641 def set_defaults_from_dict(self, defaults):
642 self.defaults.update(defaults)
644 def get_default_values(self):
645 """Needed to get custom `Values` instances."""
646 defaults = Values(self.defaults)
647 defaults._config_files = self.config_files
648 return defaults
650 def get_option_by_dest(self, dest):
652 Get an option by its dest.
654 If you're supplying a dest which is shared by several options,
655 it is undefined which option of those is returned.
657 A KeyError is raised if there is no option with the supplied
658 dest.
660 for group in self.option_groups + [self]:
661 for option in group.option_list:
662 if option.dest == dest:
663 return option
664 raise KeyError('No option with dest == %r.' % dest)
667 class ConfigParser(CP.RawConfigParser):
669 old_settings = {
670 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
671 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
672 'pep_template': ('pep_html writer', 'template')}
673 """{old setting: (new section, new setting)} mapping, used by
674 `handle_old_config`, to convert settings from the old [options] section."""
676 old_warning = """
677 The "[option]" section is deprecated. Support for old-format configuration
678 files may be removed in a future Docutils release. Please revise your
679 configuration files. See <http://docutils.sf.net/docs/user/config.html>,
680 section "Old-Format Configuration Files".
683 not_utf8_error = """\
684 Unable to read configuration file "%s": content not encoded as UTF-8.
685 Skipping "%s" configuration file.
688 def __init__(self, *args, **kwargs):
689 CP.RawConfigParser.__init__(self, *args, **kwargs)
691 self._files = []
692 """List of paths of configuration files read."""
694 self._stderr = ErrorOutput()
695 """Wrapper around sys.stderr catching en-/decoding errors"""
697 def read(self, filenames, option_parser):
698 if type(filenames) in (str, unicode):
699 filenames = [filenames]
700 for filename in filenames:
701 try:
702 # Config files must be UTF-8-encoded:
703 fp = codecs.open(filename, 'r', 'utf-8')
704 except IOError:
705 continue
706 try:
707 if sys.version_info < (3,2):
708 CP.RawConfigParser.readfp(self, fp, filename)
709 else:
710 CP.RawConfigParser.read_file(self, fp, filename)
711 except UnicodeDecodeError:
712 self._stderr.write(self.not_utf8_error % (filename, filename))
713 fp.close()
714 continue
715 fp.close()
716 self._files.append(filename)
717 if self.has_section('options'):
718 self.handle_old_config(filename)
719 self.validate_settings(filename, option_parser)
721 def handle_old_config(self, filename):
722 warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning,
723 filename, 0)
724 options = self.get_section('options')
725 if not self.has_section('general'):
726 self.add_section('general')
727 for key, value in options.items():
728 if key in self.old_settings:
729 section, setting = self.old_settings[key]
730 if not self.has_section(section):
731 self.add_section(section)
732 else:
733 section = 'general'
734 setting = key
735 if not self.has_option(section, setting):
736 self.set(section, setting, value)
737 self.remove_section('options')
739 def validate_settings(self, filename, option_parser):
741 Call the validator function and implement overrides on all applicable
742 settings.
744 for section in self.sections():
745 for setting in self.options(section):
746 try:
747 option = option_parser.get_option_by_dest(setting)
748 except KeyError:
749 continue
750 if option.validator:
751 value = self.get(section, setting)
752 try:
753 new_value = option.validator(
754 setting, value, option_parser,
755 config_parser=self, config_section=section)
756 except Exception, error:
757 raise (ValueError(
758 'Error in config file "%s", section "[%s]":\n'
759 ' %s\n'
760 ' %s = %s'
761 % (filename, section, ErrorString(error),
762 setting, value)), None, sys.exc_info()[2])
763 self.set(section, setting, new_value)
764 if option.overrides:
765 self.set(section, option.overrides, None)
767 def optionxform(self, optionstr):
769 Transform '-' to '_' so the cmdline form of option names can be used.
771 return optionstr.lower().replace('-', '_')
773 def get_section(self, section):
775 Return a given section as a dictionary (empty if the section
776 doesn't exist).
778 section_dict = {}
779 if self.has_section(section):
780 for option in self.options(section):
781 section_dict[option] = self.get(section, option)
782 return section_dict
785 class ConfigDeprecationWarning(DeprecationWarning):
786 """Warning for deprecated configuration file features."""