2 # Author: David Goodger <goodger@python.org>
3 # Copyright: This module has been placed in the public domain.
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`.
28 __docformat__
= 'reStructuredText'
34 import ConfigParser
as CP
37 from optparse
import SUPPRESS_HELP
41 from docutils
.utils
.error_reporting
import locale_encoding
, ErrorOutput
, ErrorString
44 def store_multiple(option
, opt
, value
, parser
, *args
, **kwargs
):
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`.
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
):
58 Read a configuration file during option processing. (Option callback.)
61 new_settings
= parser
.get_config_file_settings(value
)
62 except ValueError, error
:
64 parser
.values
.update(new_settings
, parser
)
66 def validate_encoding(setting
, value
, option_parser
,
67 config_parser
=None, config_section
=None):
71 raise (LookupError('setting "%s": unknown encoding: "%s"'
73 None, sys
.exc_info()[2])
76 def validate_encoding_error_handler(setting
, value
, option_parser
,
77 config_parser
=None, config_section
=None):
79 codecs
.lookup_error(value
)
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])
89 def validate_encoding_and_error_handler(
90 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
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.
96 encoding
, handler
= value
.split(':')
97 validate_encoding_error_handler(
98 setting
+ '_error_handler', handler
, option_parser
,
99 config_parser
, config_section
)
101 config_parser
.set(config_section
, setting
+ '_error_handler',
104 setattr(option_parser
.values
, setting
+ '_error_handler', handler
)
107 validate_encoding(setting
, encoding
, option_parser
,
108 config_parser
, config_section
)
111 def validate_boolean(setting
, value
, option_parser
,
112 config_parser
=None, config_section
=None):
113 if isinstance(value
, unicode):
115 return option_parser
.booleans
[value
.strip().lower()]
117 raise (LookupError('unknown boolean value: "%s"' % value
),
118 None, sys
.exc_info()[2])
121 def validate_nonnegative_int(setting
, value
, option_parser
,
122 config_parser
=None, config_section
=None):
125 raise ValueError('negative value; must be positive or zero')
128 def validate_threshold(setting
, value
, option_parser
,
129 config_parser
=None, config_section
=None):
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(':')
145 value
.extend(last
.split(':'))
148 def validate_url_trailing_slash(
149 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
152 elif value
.endswith('/'):
157 def validate_dependency_file(setting
, value
, option_parser
,
158 config_parser
=None, config_section
=None):
160 return docutils
.utils
.DependencyList(value
)
162 return docutils
.utils
.DependencyList(None)
164 def validate_strip_class(setting
, value
, option_parser
,
165 config_parser
=None, config_section
=None):
167 if isinstance(value
, unicode):
169 class_values
= filter(None, [v
.strip() for v
in value
.pop().split(',')])
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
)
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
.getcwdu() # type(base_path) == unicode
188 # to allow combining non-ASCII cwd with unicode values in `pathdict`
191 value
= pathdict
[key
]
192 if isinstance(value
, list):
193 value
= [make_one_path_absolute(base_path
, path
)
196 value
= make_one_path_absolute(base_path
, value
)
197 pathdict
[key
] = value
199 def make_one_path_absolute(base_path
, path
):
200 return os
.path
.abspath(os
.path
.join(base_path
, path
))
202 def filter_settings_spec(settings_spec
, *exclude
, **replace
):
203 """Return a copy of `settings_spec` excluding/replacing some settings.
205 `settings_spec` is a tuple of configuration settings with a structure
206 described for docutils.SettingsSpec.settings_spec.
208 Optional positional arguments are names of to-be-excluded settings.
209 Keyword arguments are option specification replacements.
210 (See the html4strict writer for an example.)
212 settings
= list(settings_spec
)
213 # every third item is a sequence of option tuples
214 for i
in range(2, len(settings
), 3):
216 for opt_spec
in settings
[i
]:
217 # opt_spec is ("<help>", [<option strings>], {<keyword args>})
218 opt_name
= [opt_string
[2:].replace('-', '_')
219 for opt_string
in opt_spec
[1]
220 if opt_string
.startswith('--')
222 if opt_name
in exclude
:
224 if opt_name
in replace
.keys():
225 newopts
.append(replace
[opt_name
])
227 newopts
.append(opt_spec
)
228 settings
[i
] = tuple(newopts
)
229 return tuple(settings
)
232 class Values(optparse
.Values
):
235 Updates list attributes by extension rather than by replacement.
236 Works in conjunction with the `OptionParser.lists` instance attribute.
239 def __init__(self
, *args
, **kwargs
):
240 optparse
.Values
.__init
__(self
, *args
, **kwargs
)
241 if (not hasattr(self
, 'record_dependencies')
242 or self
.record_dependencies
is None):
243 # Set up dependency list, in case it is needed.
244 self
.record_dependencies
= docutils
.utils
.DependencyList()
246 def update(self
, other_dict
, option_parser
):
247 if isinstance(other_dict
, Values
):
248 other_dict
= other_dict
.__dict
__
249 other_dict
= other_dict
.copy()
250 for setting
in option_parser
.lists
.keys():
251 if (hasattr(self
, setting
) and setting
in other_dict
):
252 value
= getattr(self
, setting
)
254 value
+= other_dict
[setting
]
255 del other_dict
[setting
]
256 self
._update
_loose
(other_dict
)
259 """Return a shallow copy of `self`."""
260 return self
.__class
__(defaults
=self
.__dict
__)
263 class Option(optparse
.Option
):
265 ATTRS
= optparse
.Option
.ATTRS
+ ['validator', 'overrides']
267 def process(self
, opt
, value
, values
, parser
):
269 Call the validator function on applicable settings and
270 evaluate the 'overrides' option.
271 Extends `optparse.Option.process`.
273 result
= optparse
.Option
.process(self
, opt
, value
, values
, parser
)
277 value
= getattr(values
, setting
)
279 new_value
= self
.validator(setting
, value
, parser
)
280 except Exception, error
:
281 raise (optparse
.OptionValueError(
282 'Error in option "%s":\n %s'
283 % (opt
, ErrorString(error
))),
284 None, sys
.exc_info()[2])
285 setattr(values
, setting
, new_value
)
287 setattr(values
, self
.overrides
, None)
291 class OptionParser(optparse
.OptionParser
, docutils
.SettingsSpec
):
294 Parser for command-line and library use. The `settings_spec`
295 specification here and in other Docutils components are merged to build
296 the set of command-line options and runtime settings for this process.
298 Common settings (defined below) and component-specific settings must not
299 conflict. Short options are reserved for common settings, and components
300 are restrict to using long options.
303 standard_config_files
= [
304 '/etc/docutils.conf', # system-wide
305 './docutils.conf', # project-specific
306 '~/.docutils'] # user-specific
307 """Docutils configuration files, using ConfigParser syntax. Filenames
308 will be tilde-expanded later. Later files override earlier ones."""
310 threshold_choices
= 'info 1 warning 2 error 3 severe 4 none 5'.split()
311 """Possible inputs for for --report and --halt threshold values."""
313 thresholds
= {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
314 """Lookup table for --report and --halt threshold values."""
316 booleans
={'1': 1, 'on': 1, 'yes': 1, 'true': 1,
317 '0': 0, 'off': 0, 'no': 0, 'false': 0, '': 0}
318 """Lookup table for boolean configuration file settings."""
320 default_error_encoding
= getattr(sys
.stderr
, 'encoding',
321 None) or locale_encoding
or 'ascii'
323 default_error_encoding_error_handler
= 'backslashreplace'
326 'General Docutils Options',
328 (('Specify the document title as metadata.',
330 ('Include a "Generated by Docutils" credit and link.',
331 ['--generator', '-g'], {'action': 'store_true',
332 'validator': validate_boolean
}),
333 ('Do not include a generator credit.',
334 ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
335 ('Include the date at the end of the document (UTC).',
336 ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
337 'dest': 'datestamp'}),
338 ('Include the time & date (UTC).',
339 ['--time', '-t'], {'action': 'store_const',
340 'const': '%Y-%m-%d %H:%M UTC',
341 'dest': 'datestamp'}),
342 ('Do not include a datestamp of any kind.',
343 ['--no-datestamp'], {'action': 'store_const', 'const': None,
344 'dest': 'datestamp'}),
345 ('Include a "View document source" link.',
346 ['--source-link', '-s'], {'action': 'store_true',
347 'validator': validate_boolean
}),
348 ('Use <URL> for a source link; implies --source-link.',
349 ['--source-url'], {'metavar': '<URL>'}),
350 ('Do not include a "View document source" link.',
351 ['--no-source-link'],
352 {'action': 'callback', 'callback': store_multiple
,
353 'callback_args': ('source_link', 'source_url')}),
354 ('Link from section headers to TOC entries. (default)',
355 ['--toc-entry-backlinks'],
356 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
357 'default': 'entry'}),
358 ('Link from section headers to the top of the TOC.',
359 ['--toc-top-backlinks'],
360 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
361 ('Disable backlinks to the table of contents.',
362 ['--no-toc-backlinks'],
363 {'dest': 'toc_backlinks', 'action': 'store_false'}),
364 ('Link from footnotes/citations to references. (default)',
365 ['--footnote-backlinks'],
366 {'action': 'store_true', 'default': 1,
367 'validator': validate_boolean
}),
368 ('Disable backlinks from footnotes and citations.',
369 ['--no-footnote-backlinks'],
370 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
371 ('Enable section numbering by Docutils. (default)',
372 ['--section-numbering'],
373 {'action': 'store_true', 'dest': 'sectnum_xform',
374 'default': 1, 'validator': validate_boolean
}),
375 ('Disable section numbering by Docutils.',
376 ['--no-section-numbering'],
377 {'action': 'store_false', 'dest': 'sectnum_xform'}),
378 ('Remove comment elements from the document tree.',
379 ['--strip-comments'],
380 {'action': 'store_true', 'validator': validate_boolean
}),
381 ('Leave comment elements in the document tree. (default)',
382 ['--leave-comments'],
383 {'action': 'store_false', 'dest': 'strip_comments'}),
384 ('Remove all elements with classes="<class>" from the document tree. '
385 'Warning: potentially dangerous; use with caution. '
386 '(Multiple-use option.)',
387 ['--strip-elements-with-class'],
388 {'action': 'append', 'dest': 'strip_elements_with_classes',
389 'metavar': '<class>', 'validator': validate_strip_class
}),
390 ('Remove all classes="<class>" attributes from elements in the '
391 'document tree. Warning: potentially dangerous; use with caution. '
392 '(Multiple-use option.)',
394 {'action': 'append', 'dest': 'strip_classes',
395 'metavar': '<class>', 'validator': validate_strip_class
}),
396 ('Report system messages at or higher than <level>: "info" or "1", '
397 '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
398 ['--report', '-r'], {'choices': threshold_choices
, 'default': 2,
399 'dest': 'report_level', 'metavar': '<level>',
400 'validator': validate_threshold
}),
401 ('Report all system messages. (Same as "--report=1".)',
402 ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
403 'dest': 'report_level'}),
404 ('Report no system messages. (Same as "--report=5".)',
405 ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
406 'dest': 'report_level'}),
407 ('Halt execution at system messages at or above <level>. '
408 'Levels as in --report. Default: 4 (severe).',
409 ['--halt'], {'choices': threshold_choices
, 'dest': 'halt_level',
410 'default': 4, 'metavar': '<level>',
411 'validator': validate_threshold
}),
412 ('Halt at the slightest problem. Same as "--halt=info".',
413 ['--strict'], {'action': 'store_const', 'const': 1,
414 'dest': 'halt_level'}),
415 ('Enable a non-zero exit status for non-halting system messages at '
416 'or above <level>. Default: 5 (disabled).',
417 ['--exit-status'], {'choices': threshold_choices
,
418 'dest': 'exit_status_level',
419 'default': 5, 'metavar': '<level>',
420 'validator': validate_threshold
}),
421 ('Enable debug-level system messages and diagnostics.',
422 ['--debug'], {'action': 'store_true', 'validator': validate_boolean
}),
423 ('Disable debug output. (default)',
424 ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
425 ('Send the output of system messages to <file>.',
426 ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
427 ('Enable Python tracebacks when Docutils is halted.',
428 ['--traceback'], {'action': 'store_true', 'default': None,
429 'validator': validate_boolean
}),
430 ('Disable Python tracebacks. (default)',
431 ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
432 ('Specify the encoding and optionally the '
433 'error handler of input text. Default: <locale-dependent>:strict.',
434 ['--input-encoding', '-i'],
435 {'metavar': '<name[:handler]>',
436 'validator': validate_encoding_and_error_handler
}),
437 ('Specify the error handler for undecodable characters. '
438 'Choices: "strict" (default), "ignore", and "replace".',
439 ['--input-encoding-error-handler'],
440 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
441 ('Specify the text encoding and optionally the error handler for '
442 'output. Default: UTF-8:strict.',
443 ['--output-encoding', '-o'],
444 {'metavar': '<name[:handler]>', 'default': 'utf-8',
445 'validator': validate_encoding_and_error_handler
}),
446 ('Specify error handler for unencodable output characters; '
447 '"strict" (default), "ignore", "replace", '
448 '"xmlcharrefreplace", "backslashreplace".',
449 ['--output-encoding-error-handler'],
450 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
451 ('Specify text encoding and error handler for error output. '
453 % (default_error_encoding
, default_error_encoding_error_handler
),
454 ['--error-encoding', '-e'],
455 {'metavar': '<name[:handler]>', 'default': default_error_encoding
,
456 'validator': validate_encoding_and_error_handler
}),
457 ('Specify the error handler for unencodable characters in '
458 'error output. Default: %s.'
459 % default_error_encoding_error_handler
,
460 ['--error-encoding-error-handler'],
461 {'default': default_error_encoding_error_handler
,
462 'validator': validate_encoding_error_handler
}),
463 ('Specify the language (as BCP 47 language tag). Default: en.',
464 ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
465 'metavar': '<name>'}),
466 ('Write output file dependencies to <file>.',
467 ['--record-dependencies'],
468 {'metavar': '<file>', 'validator': validate_dependency_file
,
469 'default': None}), # default set in Values class
470 ('Read configuration settings from <file>, if it exists.',
471 ['--config'], {'metavar': '<file>', 'type': 'string',
472 'action': 'callback', 'callback': read_config_file
}),
473 ("Show this program's version number and exit.",
474 ['--version', '-V'], {'action': 'version'}),
475 ('Show this help message and exit.',
476 ['--help', '-h'], {'action': 'help'}),
477 # Typically not useful for non-programmatical use:
478 (SUPPRESS_HELP
, ['--id-prefix'], {'default': ''}),
479 (SUPPRESS_HELP
, ['--auto-id-prefix'], {'default': 'id'}),
480 # Hidden options, for development use only:
481 (SUPPRESS_HELP
, ['--dump-settings'], {'action': 'store_true'}),
482 (SUPPRESS_HELP
, ['--dump-internals'], {'action': 'store_true'}),
483 (SUPPRESS_HELP
, ['--dump-transforms'], {'action': 'store_true'}),
484 (SUPPRESS_HELP
, ['--dump-pseudo-xml'], {'action': 'store_true'}),
485 (SUPPRESS_HELP
, ['--expose-internal-attribute'],
486 {'action': 'append', 'dest': 'expose_internals',
487 'validator': validate_colon_separated_string_list
}),
488 (SUPPRESS_HELP
, ['--strict-visitor'], {'action': 'store_true'}),
490 """Runtime settings and command-line options common to all Docutils front
491 ends. Setting specs specific to individual Docutils components are also
492 used (see `populate_from_components()`)."""
494 settings_defaults
= {'_disable_config': None,
496 '_destination': None,
497 '_config_files': None}
498 """Defaults for settings that don't have command-line option equivalents."""
500 relative_path_settings
= ('warning_stream',)
502 config_section
= 'general'
504 version_template
= ('%%prog (Docutils %s [%s], Python %s, on %s)'
505 % (docutils
.__version
__, docutils
.__version
_details
__,
506 sys
.version
.split()[0], sys
.platform
))
507 """Default version message."""
509 def __init__(self
, components
=(), defaults
=None, read_config_files
=None,
512 `components` is a list of Docutils components each containing a
513 ``.settings_spec`` attribute. `defaults` is a mapping of setting
518 """Set of list-type settings."""
520 self
.config_files
= []
521 """List of paths of applied configuration files."""
523 optparse
.OptionParser
.__init
__(
524 self
, option_class
=Option
, add_help_option
=None,
525 formatter
=optparse
.TitledHelpFormatter(width
=78),
528 self
.version
= self
.version_template
529 # Make an instance copy (it will be modified):
530 self
.relative_path_settings
= list(self
.relative_path_settings
)
531 self
.components
= (self
,) + tuple(components
)
532 self
.populate_from_components(self
.components
)
533 self
.set_defaults_from_dict(defaults
or {})
534 if read_config_files
and not self
.defaults
['_disable_config']:
536 config_settings
= self
.get_standard_config_settings()
537 except ValueError, error
:
539 self
.set_defaults_from_dict(config_settings
.__dict
__)
541 def populate_from_components(self
, components
):
543 For each component, first populate from the `SettingsSpec.settings_spec`
544 structure, then from the `SettingsSpec.settings_defaults` dictionary.
545 After all components have been processed, check for and populate from
546 each component's `SettingsSpec.settings_default_overrides` dictionary.
548 for component
in components
:
549 if component
is None:
551 settings_spec
= component
.settings_spec
552 self
.relative_path_settings
.extend(
553 component
.relative_path_settings
)
554 for i
in range(0, len(settings_spec
), 3):
555 title
, description
, option_spec
= settings_spec
[i
:i
+3]
557 group
= optparse
.OptionGroup(self
, title
, description
)
558 self
.add_option_group(group
)
560 group
= self
# single options
561 for (help_text
, option_strings
, kwargs
) in option_spec
:
562 option
= group
.add_option(help=help_text
, *option_strings
,
564 if kwargs
.get('action') == 'append':
565 self
.lists
[option
.dest
] = 1
566 if component
.settings_defaults
:
567 self
.defaults
.update(component
.settings_defaults
)
568 for component
in components
:
569 if component
and component
.settings_default_overrides
:
570 self
.defaults
.update(component
.settings_default_overrides
)
572 def get_standard_config_files(self
):
573 """Return list of config files, from environment or standard."""
575 config_files
= os
.environ
['DOCUTILSCONFIG'].split(os
.pathsep
)
577 config_files
= self
.standard_config_files
579 # If 'HOME' is not set, expandvars() requires the 'pwd' module which is
580 # not available under certain environments, for example, within
581 # mod_python. The publisher ends up in here, and we need to publish
582 # from within mod_python. Therefore we need to avoid expanding when we
583 # are in those environments.
584 expand
= os
.path
.expanduser
585 if 'HOME' not in os
.environ
:
590 return [expand(f
) for f
in config_files
if f
.strip()]
592 def get_standard_config_settings(self
):
594 for filename
in self
.get_standard_config_files():
595 settings
.update(self
.get_config_file_settings(filename
), self
)
598 def get_config_file_settings(self
, config_file
):
599 """Returns a dictionary containing appropriate config file settings."""
600 parser
= ConfigParser()
601 parser
.read(config_file
, self
)
602 self
.config_files
.extend(parser
._files
)
603 base_path
= os
.path
.dirname(config_file
)
606 for component
in self
.components
:
609 for section
in (tuple(component
.config_section_dependencies
or ())
610 + (component
.config_section
,)):
611 if section
in applied
:
614 settings
.update(parser
.get_section(section
), self
)
616 settings
.__dict
__, self
.relative_path_settings
, base_path
)
617 return settings
.__dict
__
619 def check_values(self
, values
, args
):
620 """Store positional arguments as runtime settings."""
621 values
._source
, values
._destination
= self
.check_args(args
)
622 make_paths_absolute(values
.__dict
__, self
.relative_path_settings
)
623 values
._config
_files
= self
.config_files
626 def check_args(self
, args
):
627 source
= destination
= None
630 if source
== '-': # means stdin
633 destination
= args
.pop(0)
634 if destination
== '-': # means stdout
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
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
662 for group
in self
.option_groups
+ [self
]:
663 for option
in group
.option_list
:
664 if option
.dest
== dest
:
666 raise KeyError('No option with dest == %r.' % dest
)
669 class ConfigParser(CP
.RawConfigParser
):
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."""
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
)
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
:
704 # Config files must be UTF-8-encoded:
705 fp
= codecs
.open(filename
, 'r', 'utf-8')
709 if sys
.version_info
< (3,2):
710 CP
.RawConfigParser
.readfp(self
, fp
, filename
)
712 CP
.RawConfigParser
.read_file(self
, fp
, filename
)
713 except UnicodeDecodeError:
714 self
._stderr
.write(self
.not_utf8_error
% (filename
, filename
))
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
,
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
)
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
746 for section
in self
.sections():
747 for setting
in self
.options(section
):
749 option
= option_parser
.get_option_by_dest(setting
)
753 value
= self
.get(section
, setting
)
755 new_value
= option
.validator(
756 setting
, value
, option_parser
,
757 config_parser
=self
, config_section
=section
)
758 except Exception, error
:
760 'Error in config file "%s", section "[%s]":\n'
763 % (filename
, section
, ErrorString(error
),
764 setting
, value
)), None, sys
.exc_info()[2])
765 self
.set(section
, setting
, new_value
)
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
781 if self
.has_section(section
):
782 for option
in self
.options(section
):
783 section_dict
[option
] = self
.get(section
, option
)
787 class ConfigDeprecationWarning(DeprecationWarning):
788 """Warning for deprecated configuration file features."""