Updated rst.el with rst-mode.el 0.2.9
[docutils.git] / docutils / frontend.py
blob93506bce5c9f6f5d5ff948ac11dfbe30bc384a41
1 # Author: David Goodger
2 # Contact: goodger@users.sourceforge.net
3 # Revision: $Revision$
4 # Date: $Date$
5 # Copyright: This module has been placed in the public domain.
7 """
8 Command-line and common processing for Docutils front-end tools.
10 Exports the following classes:
12 * `OptionParser`: Standard Docutils command-line processing.
13 * `Option`: Customized version of `optparse.Option`; validation support.
14 * `Values`: Runtime settings; objects are simple structs
15 (``object.attribute``). Supports cumulative list settings (attributes).
16 * `ConfigParser`: Standard Docutils config file processing.
18 Also exports the following functions:
20 * Option callbacks: `store_multiple`, `read_config_file`.
21 * Setting validators: `validate_encoding`,
22 `validate_encoding_error_handler`,
23 `validate_encoding_and_error_handler`, `validate_boolean`,
24 `validate_threshold`, `validate_colon_separated_string_list`,
25 `validate_dependency_file`.
26 * `make_paths_absolute`.
27 """
29 __docformat__ = 'reStructuredText'
31 import os
32 import os.path
33 import sys
34 import types
35 import warnings
36 import ConfigParser as CP
37 import codecs
38 import docutils
39 try:
40 import optparse
41 from optparse import SUPPRESS_HELP
42 except ImportError:
43 import optik as optparse
44 from optik import SUPPRESS_HELP
47 def store_multiple(option, opt, value, parser, *args, **kwargs):
48 """
49 Store multiple values in `parser.values`. (Option callback.)
51 Store `None` for each attribute named in `args`, and store the value for
52 each key (attribute name) in `kwargs`.
53 """
54 for attribute in args:
55 setattr(parser.values, attribute, None)
56 for key, value in kwargs.items():
57 setattr(parser.values, key, value)
59 def read_config_file(option, opt, value, parser):
60 """
61 Read a configuration file during option processing. (Option callback.)
62 """
63 try:
64 new_settings = parser.get_config_file_settings(value)
65 except ValueError, error:
66 parser.error(error)
67 parser.values.update(new_settings, parser)
69 def validate_encoding(setting, value, option_parser,
70 config_parser=None, config_section=None):
71 try:
72 codecs.lookup(value)
73 except LookupError:
74 raise (LookupError('setting "%s": unknown encoding: "%s"'
75 % (setting, value)),
76 None, sys.exc_info()[2])
77 return value
79 def validate_encoding_error_handler(setting, value, option_parser,
80 config_parser=None, config_section=None):
81 try:
82 codecs.lookup_error(value)
83 except AttributeError: # prior to Python 2.3
84 if value not in ('strict', 'ignore', 'replace', 'xmlcharrefreplace'):
85 raise (LookupError(
86 'unknown encoding error handler: "%s" (choices: '
87 '"strict", "ignore", "replace", or "xmlcharrefreplace")' % value),
88 None, sys.exc_info()[2])
89 except LookupError:
90 raise (LookupError(
91 'unknown encoding error handler: "%s" (choices: '
92 '"strict", "ignore", "replace", "backslashreplace", '
93 '"xmlcharrefreplace", and possibly others; see documentation for '
94 'the Python ``codecs`` module)' % value),
95 None, sys.exc_info()[2])
96 return value
98 def validate_encoding_and_error_handler(
99 setting, value, option_parser, config_parser=None, config_section=None):
101 Side-effect: if an error handler is included in the value, it is inserted
102 into the appropriate place as if it was a separate setting/option.
104 if ':' in value:
105 encoding, handler = value.split(':')
106 validate_encoding_error_handler(
107 setting + '_error_handler', handler, option_parser,
108 config_parser, config_section)
109 if config_parser:
110 config_parser.set(config_section, setting + '_error_handler',
111 handler)
112 else:
113 setattr(option_parser.values, setting + '_error_handler', handler)
114 else:
115 encoding = value
116 validate_encoding(setting, encoding, option_parser,
117 config_parser, config_section)
118 return encoding
120 def validate_boolean(setting, value, option_parser,
121 config_parser=None, config_section=None):
122 if isinstance(value, types.StringType):
123 try:
124 return option_parser.booleans[value.strip().lower()]
125 except KeyError:
126 raise (LookupError('unknown boolean value: "%s"' % value),
127 None, sys.exc_info()[2])
128 return value
130 def validate_nonnegative_int(setting, value, option_parser,
131 config_parser=None, config_section=None):
132 value = int(value)
133 if value < 0:
134 raise ValueError('negative value; must be positive or zero')
135 return value
137 def validate_threshold(setting, value, option_parser,
138 config_parser=None, config_section=None):
139 try:
140 return int(value)
141 except ValueError:
142 try:
143 return option_parser.thresholds[value.lower()]
144 except (KeyError, AttributeError):
145 raise (LookupError('unknown threshold: %r.' % value),
146 None, sys.exc_info[2])
148 def validate_colon_separated_string_list(
149 setting, value, option_parser, config_parser=None, config_section=None):
150 if isinstance(value, types.StringType):
151 value = value.split(':')
152 else:
153 last = value.pop()
154 value.extend(last.split(':'))
155 return value
157 def validate_url_trailing_slash(
158 setting, value, option_parser, config_parser=None, config_section=None):
159 if not value:
160 return './'
161 elif value.endswith('/'):
162 return value
163 else:
164 return value + '/'
166 def validate_dependency_file(
167 setting, value, option_parser, config_parser=None, config_section=None):
168 try:
169 return docutils.utils.DependencyList(value)
170 except IOError:
171 return docutils.utils.DependencyList(None)
173 def make_paths_absolute(pathdict, keys, base_path=None):
175 Interpret filesystem path settings relative to the `base_path` given.
177 Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
178 `OptionParser.relative_path_settings`.
180 if base_path is None:
181 base_path = os.getcwd()
182 for key in keys:
183 if pathdict.has_key(key):
184 value = pathdict[key]
185 if isinstance(value, types.ListType):
186 value = [make_one_path_absolute(base_path, path)
187 for path in value]
188 elif value:
189 value = make_one_path_absolute(base_path, value)
190 pathdict[key] = value
192 def make_one_path_absolute(base_path, path):
193 return os.path.abspath(os.path.join(base_path, path))
196 class Values(optparse.Values):
199 Updates list attributes by extension rather than by replacement.
200 Works in conjunction with the `OptionParser.lists` instance attribute.
203 def __init__(self, *args, **kwargs):
204 optparse.Values.__init__(self, *args, **kwargs)
205 if (not hasattr(self, 'record_dependencies')
206 or self.record_dependencies is None):
207 # Set up dependency list, in case it is needed.
208 self.record_dependencies = docutils.utils.DependencyList()
210 def update(self, other_dict, option_parser):
211 if isinstance(other_dict, Values):
212 other_dict = other_dict.__dict__
213 other_dict = other_dict.copy()
214 for setting in option_parser.lists.keys():
215 if (hasattr(self, setting) and other_dict.has_key(setting)):
216 value = getattr(self, setting)
217 if value:
218 value += other_dict[setting]
219 del other_dict[setting]
220 self._update_loose(other_dict)
222 def copy(self):
223 """Return a shallow copy of `self`."""
224 return self.__class__(defaults=self.__dict__)
227 class Option(optparse.Option):
229 ATTRS = optparse.Option.ATTRS + ['validator', 'overrides']
231 def process(self, opt, value, values, parser):
233 Call the validator function on applicable settings and
234 evaluate the 'overrides' option.
235 Extends `optparse.Option.process`.
237 result = optparse.Option.process(self, opt, value, values, parser)
238 setting = self.dest
239 if setting:
240 if self.validator:
241 value = getattr(values, setting)
242 try:
243 new_value = self.validator(setting, value, parser)
244 except Exception, error:
245 raise (optparse.OptionValueError(
246 'Error in option "%s":\n %s: %s'
247 % (opt, error.__class__.__name__, error)),
248 None, sys.exc_info()[2])
249 setattr(values, setting, new_value)
250 if self.overrides:
251 setattr(values, self.overrides, None)
252 return result
255 class OptionParser(optparse.OptionParser, docutils.SettingsSpec):
258 Parser for command-line and library use. The `settings_spec`
259 specification here and in other Docutils components are merged to build
260 the set of command-line options and runtime settings for this process.
262 Common settings (defined below) and component-specific settings must not
263 conflict. Short options are reserved for common settings, and components
264 are restrict to using long options.
267 standard_config_files = [
268 '/etc/docutils.conf', # system-wide
269 './docutils.conf', # project-specific
270 '~/.docutils'] # user-specific
271 """Docutils configuration files, using ConfigParser syntax. Filenames
272 will be tilde-expanded later. Later files override earlier ones."""
274 threshold_choices = 'info 1 warning 2 error 3 severe 4 none 5'.split()
275 """Possible inputs for for --report and --halt threshold values."""
277 thresholds = {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
278 """Lookup table for --report and --halt threshold values."""
280 booleans={'1': 1, 'on': 1, 'yes': 1, 'true': 1,
281 '0': 0, 'off': 0, 'no': 0, 'false': 0, '': 0}
282 """Lookup table for boolean configuration file settings."""
284 if hasattr(codecs, 'backslashreplace_errors'):
285 default_error_encoding_error_handler = 'backslashreplace'
286 else:
287 default_error_encoding_error_handler = 'replace'
289 settings_spec = (
290 'General Docutils Options',
291 None,
292 (('Specify the document title as metadata (not part of the document '
293 'body). Overrides a document-provided title. There is no default.',
294 ['--title'], {}),
295 ('Include a "Generated by Docutils" credit and link at the end '
296 'of the document.',
297 ['--generator', '-g'], {'action': 'store_true',
298 'validator': validate_boolean}),
299 ('Do not include a generator credit.',
300 ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
301 ('Include the date at the end of the document (UTC).',
302 ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
303 'dest': 'datestamp'}),
304 ('Include the time & date at the end of the document (UTC).',
305 ['--time', '-t'], {'action': 'store_const',
306 'const': '%Y-%m-%d %H:%M UTC',
307 'dest': 'datestamp'}),
308 ('Do not include a datestamp of any kind.',
309 ['--no-datestamp'], {'action': 'store_const', 'const': None,
310 'dest': 'datestamp'}),
311 ('Include a "View document source" link (relative to destination).',
312 ['--source-link', '-s'], {'action': 'store_true',
313 'validator': validate_boolean}),
314 ('Use the supplied <URL> verbatim for a "View document source" '
315 'link; implies --source-link.',
316 ['--source-url'], {'metavar': '<URL>'}),
317 ('Do not include a "View document source" link.',
318 ['--no-source-link'],
319 {'action': 'callback', 'callback': store_multiple,
320 'callback_args': ('source_link', 'source_url')}),
321 ('Enable backlinks from section headers to table of contents '
322 'entries. This is the default.',
323 ['--toc-entry-backlinks'],
324 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
325 'default': 'entry'}),
326 ('Enable backlinks from section headers to the top of the table of '
327 'contents.',
328 ['--toc-top-backlinks'],
329 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
330 ('Disable backlinks to the table of contents.',
331 ['--no-toc-backlinks'],
332 {'dest': 'toc_backlinks', 'action': 'store_false'}),
333 ('Enable backlinks from footnotes and citations to their '
334 'references. This is the default.',
335 ['--footnote-backlinks'],
336 {'action': 'store_true', 'default': 1,
337 'validator': validate_boolean}),
338 ('Disable backlinks from footnotes and citations.',
339 ['--no-footnote-backlinks'],
340 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
341 ('Disable Docutils section numbering',
342 ['--no-section-numbering'],
343 {'action': 'store_false', 'dest': 'sectnum_xform',
344 'default': 1, 'validator': validate_boolean}),
345 ('Set verbosity threshold; report system messages at or higher than '
346 '<level> (by name or number: "info" or "1", warning/2, error/3, '
347 'severe/4; also, "none" or "5"). Default is 2 (warning).',
348 ['--report', '-r'], {'choices': threshold_choices, 'default': 2,
349 'dest': 'report_level', 'metavar': '<level>',
350 'validator': validate_threshold}),
351 ('Report all system messages, info-level and higher. (Same as '
352 '"--report=info".)',
353 ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
354 'dest': 'report_level'}),
355 ('Do not report any system messages. (Same as "--report=none".)',
356 ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
357 'dest': 'report_level'}),
358 ('Set the threshold (<level>) at or above which system messages are '
359 'converted to exceptions, halting execution immediately by '
360 'exiting (or propagating the exception if --traceback set). '
361 'Levels as in --report. Default is 4 (severe).',
362 ['--halt'], {'choices': threshold_choices, 'dest': 'halt_level',
363 'default': 4, 'metavar': '<level>',
364 'validator': validate_threshold}),
365 ('Same as "--halt=info": halt processing at the slightest problem.',
366 ['--strict'], {'action': 'store_const', 'const': 'info',
367 'dest': 'halt_level'}),
368 ('Enable a non-zero exit status for normal exit if non-halting '
369 'system messages (at or above <level>) were generated. Levels as '
370 'in --report. Default is 5 (disabled). Exit status is the maximum '
371 'system message level plus 10 (11 for INFO, etc.).',
372 ['--exit-status'], {'choices': threshold_choices,
373 'dest': 'exit_status_level',
374 'default': 5, 'metavar': '<level>',
375 'validator': validate_threshold}),
376 ('Report debug-level system messages and generate diagnostic output.',
377 ['--debug'], {'action': 'store_true', 'validator': validate_boolean}),
378 ('Do not report debug-level system messages or generate diagnostic '
379 'output.',
380 ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
381 ('Send the output of system messages (warnings) to <file>.',
382 ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
383 ('Enable Python tracebacks when halt-level system messages and '
384 'other exceptions occur. Useful for debugging, and essential for '
385 'issue reports.',
386 ['--traceback'], {'action': 'store_true', 'default': None,
387 'validator': validate_boolean}),
388 ('Disable Python tracebacks when errors occur; report just the error '
389 'instead. This is the default.',
390 ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
391 ('Specify the encoding of input text. Default is locale-dependent. '
392 'Optionally also specify the error handler for undecodable '
393 'characters, after a colon (":"); default is "strict". (See '
394 '"--intput-encoding-error-handler".)',
395 ['--input-encoding', '-i'],
396 {'metavar': '<name[:handler]>',
397 'validator': validate_encoding_and_error_handler}),
398 ('Specify the error handler for undecodable characters in '
399 'the input. Acceptable values include "strict", "ignore", and '
400 '"replace". Default is "strict". '
401 'Usually specified as part of --input-encoding.',
402 ['--input-encoding-error-handler'],
403 {'default': 'strict', 'validator': validate_encoding_error_handler}),
404 ('Specify the text encoding for output. Default is UTF-8. '
405 'Optionally also specify the error handler for unencodable '
406 'characters, after a colon (":"); default is "strict". (See '
407 '"--output-encoding-error-handler".)',
408 ['--output-encoding', '-o'],
409 {'metavar': '<name[:handler]>', 'default': 'utf-8',
410 'validator': validate_encoding_and_error_handler}),
411 ('Specify the error handler for unencodable characters in '
412 'the output. Acceptable values include "strict", "ignore", '
413 '"replace", "xmlcharrefreplace", and '
414 '"backslashreplace" (in Python 2.3+). Default is "strict". '
415 'Usually specified as part of --output-encoding.',
416 ['--output-encoding-error-handler'],
417 {'default': 'strict', 'validator': validate_encoding_error_handler}),
418 ('Specify the text encoding for error output. Default is ASCII. '
419 'Optionally also specify the error handler for unencodable '
420 'characters, after a colon (":"); default is "%s". (See '
421 '"--output-encoding-error-handler".)'
422 % default_error_encoding_error_handler,
423 ['--error-encoding', '-e'],
424 {'metavar': '<name[:handler]>', 'default': 'ascii',
425 'validator': validate_encoding_and_error_handler}),
426 ('Specify the error handler for unencodable characters in '
427 'error output. See --output-encoding-error-handler for acceptable '
428 'values. Default is "%s". Usually specified as part of '
429 '--error-encoding.' % default_error_encoding_error_handler,
430 ['--error-encoding-error-handler'],
431 {'default': default_error_encoding_error_handler,
432 'validator': validate_encoding_error_handler}),
433 ('Specify the language of input text (ISO 639 2-letter identifier).'
434 ' Default is "en" (English).',
435 ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
436 'metavar': '<name>'}),
437 ('Write dependencies (caused e.g. by file inclusions) to '
438 '<file>. Useful in conjunction with programs like "make".',
439 ['--record-dependencies'],
440 {'metavar': '<file>', 'validator': validate_dependency_file,
441 'default': None}), # default set in Values class
442 ('Read configuration settings from <file>, if it exists.',
443 ['--config'], {'metavar': '<file>', 'type': 'string',
444 'action': 'callback', 'callback': read_config_file}),
445 ("Show this program's version number and exit.",
446 ['--version', '-V'], {'action': 'version'}),
447 ('Show this help message and exit.',
448 ['--help', '-h'], {'action': 'help'}),
449 # Typically not useful for non-programmatical use.
450 (SUPPRESS_HELP, ['--id-prefix'], {'default': ''}),
451 (SUPPRESS_HELP, ['--auto-id-prefix'], {'default': 'id'}),
452 # Hidden options, for development use only:
453 (SUPPRESS_HELP, ['--dump-settings'], {'action': 'store_true'}),
454 (SUPPRESS_HELP, ['--dump-internals'], {'action': 'store_true'}),
455 (SUPPRESS_HELP, ['--dump-transforms'], {'action': 'store_true'}),
456 (SUPPRESS_HELP, ['--dump-pseudo-xml'], {'action': 'store_true'}),
457 (SUPPRESS_HELP, ['--expose-internal-attribute'],
458 {'action': 'append', 'dest': 'expose_internals',
459 'validator': validate_colon_separated_string_list}),
460 (SUPPRESS_HELP, ['--strict-visitor'], {'action': 'store_true'}),
462 """Runtime settings and command-line options common to all Docutils front
463 ends. Setting specs specific to individual Docutils components are also
464 used (see `populate_from_components()`)."""
466 settings_defaults = {'_disable_config': None,
467 '_source': None,
468 '_destination': None,}
469 """Defaults for settings that don't have command-line option equivalents."""
471 relative_path_settings = ('warning_stream',)
473 config_section = 'general'
475 version_template = ('%%prog (Docutils %s [%s])'
476 % (docutils.__version__, docutils.__version_details__))
477 """Default version message."""
479 def __init__(self, components=(), defaults=None, read_config_files=None,
480 *args, **kwargs):
482 `components` is a list of Docutils components each containing a
483 ``.settings_spec`` attribute. `defaults` is a mapping of setting
484 default overrides.
487 self.lists = {}
488 """Set of list-type settings."""
490 optparse.OptionParser.__init__(
491 self, option_class=Option, add_help_option=None,
492 formatter=optparse.TitledHelpFormatter(width=78),
493 *args, **kwargs)
494 if not self.version:
495 self.version = self.version_template
496 # Make an instance copy (it will be modified):
497 self.relative_path_settings = list(self.relative_path_settings)
498 self.components = (self,) + tuple(components)
499 self.populate_from_components(self.components)
500 self.set_defaults(**(defaults or {}))
501 if read_config_files and not self.defaults['_disable_config']:
502 try:
503 config_settings = self.get_standard_config_settings()
504 except ValueError, error:
505 self.error(error)
506 self.set_defaults(**config_settings.__dict__)
508 def populate_from_components(self, components):
510 For each component, first populate from the `SettingsSpec.settings_spec`
511 structure, then from the `SettingsSpec.settings_defaults` dictionary.
512 After all components have been processed, check for and populate from
513 each component's `SettingsSpec.settings_default_overrides` dictionary.
515 for component in components:
516 if component is None:
517 continue
518 settings_spec = component.settings_spec
519 self.relative_path_settings.extend(
520 component.relative_path_settings)
521 for i in range(0, len(settings_spec), 3):
522 title, description, option_spec = settings_spec[i:i+3]
523 if title:
524 group = optparse.OptionGroup(self, title, description)
525 self.add_option_group(group)
526 else:
527 group = self # single options
528 for (help_text, option_strings, kwargs) in option_spec:
529 option = group.add_option(help=help_text, *option_strings,
530 **kwargs)
531 if kwargs.get('action') == 'append':
532 self.lists[option.dest] = 1
533 if component.settings_defaults:
534 self.defaults.update(component.settings_defaults)
535 for component in components:
536 if component and component.settings_default_overrides:
537 self.defaults.update(component.settings_default_overrides)
539 def get_standard_config_files(self):
540 """Return list of config files, from environment or standard."""
541 try:
542 config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep)
543 except KeyError:
544 config_files = self.standard_config_files
545 return [os.path.expanduser(f) for f in config_files if f.strip()]
547 def get_standard_config_settings(self):
548 settings = Values()
549 for filename in self.get_standard_config_files():
550 settings.update(self.get_config_file_settings(filename), self)
551 return settings
553 def get_config_file_settings(self, config_file):
554 """Returns a dictionary containing appropriate config file settings."""
555 parser = ConfigParser()
556 parser.read(config_file, self)
557 base_path = os.path.dirname(config_file)
558 applied = {}
559 settings = Values()
560 for component in self.components:
561 if not component:
562 continue
563 for section in (tuple(component.config_section_dependencies or ())
564 + (component.config_section,)):
565 if applied.has_key(section):
566 continue
567 applied[section] = 1
568 settings.update(parser.get_section(section), self)
569 make_paths_absolute(
570 settings.__dict__, self.relative_path_settings, base_path)
571 return settings.__dict__
573 def check_values(self, values, args):
574 """Store positional arguments as runtime settings."""
575 values._source, values._destination = self.check_args(args)
576 make_paths_absolute(values.__dict__, self.relative_path_settings,
577 os.getcwd())
578 return values
580 def check_args(self, args):
581 source = destination = None
582 if args:
583 source = args.pop(0)
584 if source == '-': # means stdin
585 source = None
586 if args:
587 destination = args.pop(0)
588 if destination == '-': # means stdout
589 destination = None
590 if args:
591 self.error('Maximum 2 arguments allowed.')
592 if source and source == destination:
593 self.error('Do not specify the same file for both source and '
594 'destination. It will clobber the source file.')
595 return source, destination
597 def get_default_values(self):
598 """Needed to get custom `Values` instances."""
599 return Values(self.defaults)
601 def get_option_by_dest(self, dest):
603 Get an option by its dest.
605 If you're supplying a dest which is shared by several options,
606 it is undefined which option of those is returned.
608 A KeyError is raised if there is no option with the supplied
609 dest.
611 for group in self.option_groups + [self]:
612 for option in group.option_list:
613 if option.dest == dest:
614 return option
615 raise KeyError('No option with dest == %r.' % dest)
618 class ConfigParser(CP.ConfigParser):
620 old_settings = {
621 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
622 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
623 'pep_template': ('pep_html writer', 'template')}
624 """{old setting: (new section, new setting)} mapping, used by
625 `handle_old_config`, to convert settings from the old [options] section."""
627 old_warning = """
628 The "[option]" section is deprecated. Support for old-format configuration
629 files may be removed in a future Docutils release. Please revise your
630 configuration files. See <http://docutils.sf.net/docs/user/config.html>,
631 section "Old-Format Configuration Files".
634 def read(self, filenames, option_parser):
635 if type(filenames) in (types.StringType, types.UnicodeType):
636 filenames = [filenames]
637 for filename in filenames:
638 CP.ConfigParser.read(self, filename)
639 if self.has_section('options'):
640 self.handle_old_config(filename)
641 self.validate_settings(filename, option_parser)
643 def handle_old_config(self, filename):
644 warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning,
645 filename, 0)
646 options = self.get_section('options')
647 if not self.has_section('general'):
648 self.add_section('general')
649 for key, value in options.items():
650 if self.old_settings.has_key(key):
651 section, setting = self.old_settings[key]
652 if not self.has_section(section):
653 self.add_section(section)
654 else:
655 section = 'general'
656 setting = key
657 if not self.has_option(section, setting):
658 self.set(section, setting, value)
659 self.remove_section('options')
661 def validate_settings(self, filename, option_parser):
663 Call the validator function and implement overrides on all applicable
664 settings.
666 for section in self.sections():
667 for setting in self.options(section):
668 try:
669 option = option_parser.get_option_by_dest(setting)
670 except KeyError:
671 continue
672 if option.validator:
673 value = self.get(section, setting, raw=1)
674 try:
675 new_value = option.validator(
676 setting, value, option_parser,
677 config_parser=self, config_section=section)
678 except Exception, error:
679 raise (ValueError(
680 'Error in config file "%s", section "[%s]":\n'
681 ' %s: %s\n %s = %s'
682 % (filename, section, error.__class__.__name__,
683 error, setting, value)), None, sys.exc_info()[2])
684 self.set(section, setting, new_value)
685 if option.overrides:
686 self.set(section, option.overrides, None)
688 def optionxform(self, optionstr):
690 Transform '-' to '_' so the cmdline form of option names can be used.
692 return optionstr.lower().replace('-', '_')
694 def get_section(self, section):
696 Return a given section as a dictionary (empty if the section
697 doesn't exist).
699 section_dict = {}
700 if self.has_section(section):
701 for option in self.options(section):
702 section_dict[option] = self.get(section, option, raw=1)
703 return section_dict
706 class ConfigDeprecationWarning(DeprecationWarning):
707 """Warning for deprecated configuration file features."""