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`,
22 `validate_boolean`, `validate_ternary`, `validate_threshold`,
23 `validate_colon_separated_string_list`,
24 `validate_comma_separated_string_list`,
25 `validate_dependency_file`.
26 * `make_paths_absolute`.
27 * SettingSpec manipulation: `filter_settings_spec`.
30 __docformat__
= 'reStructuredText'
36 import ConfigParser
as CP
39 from optparse
import SUPPRESS_HELP
43 from docutils
.utils
.error_reporting
import locale_encoding
, ErrorOutput
, ErrorString
46 def store_multiple(option
, opt
, value
, parser
, *args
, **kwargs
):
48 Store multiple values in `parser.values`. (Option callback.)
50 Store `None` for each attribute named in `args`, and store the value for
51 each key (attribute name) in `kwargs`.
53 for attribute
in args
:
54 setattr(parser
.values
, attribute
, None)
55 for key
, value
in kwargs
.items():
56 setattr(parser
.values
, key
, value
)
58 def read_config_file(option
, opt
, value
, parser
):
60 Read a configuration file during option processing. (Option callback.)
63 new_settings
= parser
.get_config_file_settings(value
)
64 except ValueError, error
:
66 parser
.values
.update(new_settings
, parser
)
68 def validate_encoding(setting
, value
, option_parser
,
69 config_parser
=None, config_section
=None):
73 raise (LookupError('setting "%s": unknown encoding: "%s"'
75 None, sys
.exc_info()[2])
78 def validate_encoding_error_handler(setting
, value
, option_parser
,
79 config_parser
=None, config_section
=None):
81 codecs
.lookup_error(value
)
84 'unknown encoding error handler: "%s" (choices: '
85 '"strict", "ignore", "replace", "backslashreplace", '
86 '"xmlcharrefreplace", and possibly others; see documentation for '
87 'the Python ``codecs`` module)' % value
),
88 None, sys
.exc_info()[2])
91 def validate_encoding_and_error_handler(
92 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
94 Side-effect: if an error handler is included in the value, it is inserted
95 into the appropriate place as if it was a separate setting/option.
98 encoding
, handler
= value
.split(':')
99 validate_encoding_error_handler(
100 setting
+ '_error_handler', handler
, option_parser
,
101 config_parser
, config_section
)
103 config_parser
.set(config_section
, setting
+ '_error_handler',
106 setattr(option_parser
.values
, setting
+ '_error_handler', handler
)
109 validate_encoding(setting
, encoding
, option_parser
,
110 config_parser
, config_section
)
113 def validate_boolean(setting
, value
, option_parser
,
114 config_parser
=None, config_section
=None):
115 """Check/normalize boolean settings:
116 True: '1', 'on', 'yes', 'true'
117 False: '0', 'off', 'no','false', ''
119 if isinstance(value
, bool):
122 return option_parser
.booleans
[value
.strip().lower()]
124 raise (LookupError('unknown boolean value: "%s"' % value
),
125 None, sys
.exc_info()[2])
127 def validate_ternary(setting
, value
, option_parser
,
128 config_parser
=None, config_section
=None):
129 """Check/normalize three-value settings:
130 True: '1', 'on', 'yes', 'true'
131 False: '0', 'off', 'no','false', ''
132 any other value: returned as-is.
134 if isinstance(value
, bool) or value
is None:
137 return option_parser
.booleans
[value
.strip().lower()]
141 def validate_nonnegative_int(setting
, value
, option_parser
,
142 config_parser
=None, config_section
=None):
145 raise ValueError('negative value; must be positive or zero')
148 def validate_threshold(setting
, value
, option_parser
,
149 config_parser
=None, config_section
=None):
154 return option_parser
.thresholds
[value
.lower()]
155 except (KeyError, AttributeError):
156 raise (LookupError('unknown threshold: %r.' % value
),
157 None, sys
.exc_info
[2])
159 def validate_colon_separated_string_list(
160 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
161 if isinstance(value
, unicode):
162 value
= value
.split(':')
165 value
.extend(last
.split(':'))
168 def validate_comma_separated_list(setting
, value
, option_parser
,
169 config_parser
=None, config_section
=None):
170 """Check/normalize list arguments (split at "," and strip whitespace).
172 # `value` is already a list when given as command line option
173 # and "action" is "append"
174 if isinstance(value
, unicode):
176 # this function is called for every option added to `value`
177 # -> split the last item and append the result:
179 classes
= [cls
.strip(u
' \t\n') for cls
in last
.split(',')
180 if cls
.strip(u
' \t\n')]
181 value
.extend(classes
)
184 def validate_url_trailing_slash(
185 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
188 elif value
.endswith('/'):
193 def validate_dependency_file(setting
, value
, option_parser
,
194 config_parser
=None, config_section
=None):
196 return docutils
.utils
.DependencyList(value
)
198 return docutils
.utils
.DependencyList(None)
200 def validate_strip_class(setting
, value
, option_parser
,
201 config_parser
=None, config_section
=None):
202 # value is a comma separated string list:
203 value
= validate_comma_separated_list(setting
, value
, option_parser
,
204 config_parser
, config_section
)
205 # validate list elements:
207 normalized
= docutils
.nodes
.make_id(cls
)
208 if cls
!= normalized
:
209 raise ValueError('invalid class value %r (perhaps %r?)'
213 def make_paths_absolute(pathdict
, keys
, base_path
=None):
215 Interpret filesystem path settings relative to the `base_path` given.
217 Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
218 `OptionParser.relative_path_settings`.
220 if base_path
is None:
221 base_path
= os
.getcwdu() # type(base_path) == unicode
222 # to allow combining non-ASCII cwd with unicode values in `pathdict`
225 value
= pathdict
[key
]
226 if isinstance(value
, list):
227 value
= [make_one_path_absolute(base_path
, path
)
230 value
= make_one_path_absolute(base_path
, value
)
231 pathdict
[key
] = value
233 def make_one_path_absolute(base_path
, path
):
234 return os
.path
.abspath(os
.path
.join(base_path
, path
))
236 def filter_settings_spec(settings_spec
, *exclude
, **replace
):
237 """Return a copy of `settings_spec` excluding/replacing some settings.
239 `settings_spec` is a tuple of configuration settings with a structure
240 described for docutils.SettingsSpec.settings_spec.
242 Optional positional arguments are names of to-be-excluded settings.
243 Keyword arguments are option specification replacements.
244 (See the html4strict writer for an example.)
246 settings
= list(settings_spec
)
247 # every third item is a sequence of option tuples
248 for i
in range(2, len(settings
), 3):
250 for opt_spec
in settings
[i
]:
251 # opt_spec is ("<help>", [<option strings>], {<keyword args>})
252 opt_name
= [opt_string
[2:].replace('-', '_')
253 for opt_string
in opt_spec
[1]
254 if opt_string
.startswith('--')
256 if opt_name
in exclude
:
258 if opt_name
in replace
.keys():
259 newopts
.append(replace
[opt_name
])
261 newopts
.append(opt_spec
)
262 settings
[i
] = tuple(newopts
)
263 return tuple(settings
)
266 class Values(optparse
.Values
):
269 Updates list attributes by extension rather than by replacement.
270 Works in conjunction with the `OptionParser.lists` instance attribute.
273 def __init__(self
, *args
, **kwargs
):
274 optparse
.Values
.__init
__(self
, *args
, **kwargs
)
275 if (not hasattr(self
, 'record_dependencies')
276 or self
.record_dependencies
is None):
277 # Set up dependency list, in case it is needed.
278 self
.record_dependencies
= docutils
.utils
.DependencyList()
280 def update(self
, other_dict
, option_parser
):
281 if isinstance(other_dict
, Values
):
282 other_dict
= other_dict
.__dict
__
283 other_dict
= other_dict
.copy()
284 for setting
in option_parser
.lists
.keys():
285 if (hasattr(self
, setting
) and setting
in other_dict
):
286 value
= getattr(self
, setting
)
288 value
+= other_dict
[setting
]
289 del other_dict
[setting
]
290 self
._update
_loose
(other_dict
)
293 """Return a shallow copy of `self`."""
294 return self
.__class
__(defaults
=self
.__dict
__)
297 class Option(optparse
.Option
):
299 ATTRS
= optparse
.Option
.ATTRS
+ ['validator', 'overrides']
301 def process(self
, opt
, value
, values
, parser
):
303 Call the validator function on applicable settings and
304 evaluate the 'overrides' option.
305 Extends `optparse.Option.process`.
307 result
= optparse
.Option
.process(self
, opt
, value
, values
, parser
)
311 value
= getattr(values
, setting
)
313 new_value
= self
.validator(setting
, value
, parser
)
314 except Exception, error
:
315 raise (optparse
.OptionValueError(
316 'Error in option "%s":\n %s'
317 % (opt
, ErrorString(error
))),
318 None, sys
.exc_info()[2])
319 setattr(values
, setting
, new_value
)
321 setattr(values
, self
.overrides
, None)
325 class OptionParser(optparse
.OptionParser
, docutils
.SettingsSpec
):
328 Parser for command-line and library use. The `settings_spec`
329 specification here and in other Docutils components are merged to build
330 the set of command-line options and runtime settings for this process.
332 Common settings (defined below) and component-specific settings must not
333 conflict. Short options are reserved for common settings, and components
334 are restrict to using long options.
337 standard_config_files
= [
338 '/etc/docutils.conf', # system-wide
339 './docutils.conf', # project-specific
340 '~/.docutils'] # user-specific
341 """Docutils configuration files, using ConfigParser syntax. Filenames
342 will be tilde-expanded later. Later files override earlier ones."""
344 threshold_choices
= 'info 1 warning 2 error 3 severe 4 none 5'.split()
345 """Possible inputs for for --report and --halt threshold values."""
347 thresholds
= {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
348 """Lookup table for --report and --halt threshold values."""
350 booleans
={'1': True, 'on': True, 'yes': True, 'true': True,
351 '0': False, 'off': False, 'no': False, 'false': False, '': False}
352 """Lookup table for boolean configuration file settings."""
354 default_error_encoding
= getattr(sys
.stderr
, 'encoding',
355 None) or locale_encoding
or 'ascii'
357 default_error_encoding_error_handler
= 'backslashreplace'
360 'General Docutils Options',
362 (('Specify the document title as metadata.',
364 ('Include a "Generated by Docutils" credit and link.',
365 ['--generator', '-g'], {'action': 'store_true',
366 'validator': validate_boolean
}),
367 ('Do not include a generator credit.',
368 ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
369 ('Include the date at the end of the document (UTC).',
370 ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
371 'dest': 'datestamp'}),
372 ('Include the time & date (UTC).',
373 ['--time', '-t'], {'action': 'store_const',
374 'const': '%Y-%m-%d %H:%M UTC',
375 'dest': 'datestamp'}),
376 ('Do not include a datestamp of any kind.',
377 ['--no-datestamp'], {'action': 'store_const', 'const': None,
378 'dest': 'datestamp'}),
379 ('Include a "View document source" link.',
380 ['--source-link', '-s'], {'action': 'store_true',
381 'validator': validate_boolean
}),
382 ('Use <URL> for a source link; implies --source-link.',
383 ['--source-url'], {'metavar': '<URL>'}),
384 ('Do not include a "View document source" link.',
385 ['--no-source-link'],
386 {'action': 'callback', 'callback': store_multiple
,
387 'callback_args': ('source_link', 'source_url')}),
388 ('Link from section headers to TOC entries. (default)',
389 ['--toc-entry-backlinks'],
390 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
391 'default': 'entry'}),
392 ('Link from section headers to the top of the TOC.',
393 ['--toc-top-backlinks'],
394 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
395 ('Disable backlinks to the table of contents.',
396 ['--no-toc-backlinks'],
397 {'dest': 'toc_backlinks', 'action': 'store_false'}),
398 ('Link from footnotes/citations to references. (default)',
399 ['--footnote-backlinks'],
400 {'action': 'store_true', 'default': 1,
401 'validator': validate_boolean
}),
402 ('Disable backlinks from footnotes and citations.',
403 ['--no-footnote-backlinks'],
404 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
405 ('Enable section numbering by Docutils. (default)',
406 ['--section-numbering'],
407 {'action': 'store_true', 'dest': 'sectnum_xform',
408 'default': 1, 'validator': validate_boolean
}),
409 ('Disable section numbering by Docutils.',
410 ['--no-section-numbering'],
411 {'action': 'store_false', 'dest': 'sectnum_xform'}),
412 ('Remove comment elements from the document tree.',
413 ['--strip-comments'],
414 {'action': 'store_true', 'validator': validate_boolean
}),
415 ('Leave comment elements in the document tree. (default)',
416 ['--leave-comments'],
417 {'action': 'store_false', 'dest': 'strip_comments'}),
418 ('Remove all elements with classes="<class>" from the document tree. '
419 'Warning: potentially dangerous; use with caution. '
420 '(Multiple-use option.)',
421 ['--strip-elements-with-class'],
422 {'action': 'append', 'dest': 'strip_elements_with_classes',
423 'metavar': '<class>', 'validator': validate_strip_class
}),
424 ('Remove all classes="<class>" attributes from elements in the '
425 'document tree. Warning: potentially dangerous; use with caution. '
426 '(Multiple-use option.)',
428 {'action': 'append', 'dest': 'strip_classes',
429 'metavar': '<class>', 'validator': validate_strip_class
}),
430 ('Report system messages at or higher than <level>: "info" or "1", '
431 '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
432 ['--report', '-r'], {'choices': threshold_choices
, 'default': 2,
433 'dest': 'report_level', 'metavar': '<level>',
434 'validator': validate_threshold
}),
435 ('Report all system messages. (Same as "--report=1".)',
436 ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
437 'dest': 'report_level'}),
438 ('Report no system messages. (Same as "--report=5".)',
439 ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
440 'dest': 'report_level'}),
441 ('Halt execution at system messages at or above <level>. '
442 'Levels as in --report. Default: 4 (severe).',
443 ['--halt'], {'choices': threshold_choices
, 'dest': 'halt_level',
444 'default': 4, 'metavar': '<level>',
445 'validator': validate_threshold
}),
446 ('Halt at the slightest problem. Same as "--halt=info".',
447 ['--strict'], {'action': 'store_const', 'const': 1,
448 'dest': 'halt_level'}),
449 ('Enable a non-zero exit status for non-halting system messages at '
450 'or above <level>. Default: 5 (disabled).',
451 ['--exit-status'], {'choices': threshold_choices
,
452 'dest': 'exit_status_level',
453 'default': 5, 'metavar': '<level>',
454 'validator': validate_threshold
}),
455 ('Enable debug-level system messages and diagnostics.',
456 ['--debug'], {'action': 'store_true', 'validator': validate_boolean
}),
457 ('Disable debug output. (default)',
458 ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
459 ('Send the output of system messages to <file>.',
460 ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
461 ('Enable Python tracebacks when Docutils is halted.',
462 ['--traceback'], {'action': 'store_true', 'default': None,
463 'validator': validate_boolean
}),
464 ('Disable Python tracebacks. (default)',
465 ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
466 ('Specify the encoding and optionally the '
467 'error handler of input text. Default: <locale-dependent>:strict.',
468 ['--input-encoding', '-i'],
469 {'metavar': '<name[:handler]>',
470 'validator': validate_encoding_and_error_handler
}),
471 ('Specify the error handler for undecodable characters. '
472 'Choices: "strict" (default), "ignore", and "replace".',
473 ['--input-encoding-error-handler'],
474 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
475 ('Specify the text encoding and optionally the error handler for '
476 'output. Default: UTF-8:strict.',
477 ['--output-encoding', '-o'],
478 {'metavar': '<name[:handler]>', 'default': 'utf-8',
479 'validator': validate_encoding_and_error_handler
}),
480 ('Specify error handler for unencodable output characters; '
481 '"strict" (default), "ignore", "replace", '
482 '"xmlcharrefreplace", "backslashreplace".',
483 ['--output-encoding-error-handler'],
484 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
485 ('Specify text encoding and error handler for error output. '
487 % (default_error_encoding
, default_error_encoding_error_handler
),
488 ['--error-encoding', '-e'],
489 {'metavar': '<name[:handler]>', 'default': default_error_encoding
,
490 'validator': validate_encoding_and_error_handler
}),
491 ('Specify the error handler for unencodable characters in '
492 'error output. Default: %s.'
493 % default_error_encoding_error_handler
,
494 ['--error-encoding-error-handler'],
495 {'default': default_error_encoding_error_handler
,
496 'validator': validate_encoding_error_handler
}),
497 ('Specify the language (as BCP 47 language tag). Default: en.',
498 ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
499 'metavar': '<name>'}),
500 ('Write output file dependencies to <file>.',
501 ['--record-dependencies'],
502 {'metavar': '<file>', 'validator': validate_dependency_file
,
503 'default': None}), # default set in Values class
504 ('Read configuration settings from <file>, if it exists.',
505 ['--config'], {'metavar': '<file>', 'type': 'string',
506 'action': 'callback', 'callback': read_config_file
}),
507 ("Show this program's version number and exit.",
508 ['--version', '-V'], {'action': 'version'}),
509 ('Show this help message and exit.',
510 ['--help', '-h'], {'action': 'help'}),
511 # Typically not useful for non-programmatical use:
512 (SUPPRESS_HELP
, ['--id-prefix'], {'default': ''}),
513 (SUPPRESS_HELP
, ['--auto-id-prefix'], {'default': 'id'}),
514 # Hidden options, for development use only:
515 (SUPPRESS_HELP
, ['--dump-settings'], {'action': 'store_true'}),
516 (SUPPRESS_HELP
, ['--dump-internals'], {'action': 'store_true'}),
517 (SUPPRESS_HELP
, ['--dump-transforms'], {'action': 'store_true'}),
518 (SUPPRESS_HELP
, ['--dump-pseudo-xml'], {'action': 'store_true'}),
519 (SUPPRESS_HELP
, ['--expose-internal-attribute'],
520 {'action': 'append', 'dest': 'expose_internals',
521 'validator': validate_colon_separated_string_list
}),
522 (SUPPRESS_HELP
, ['--strict-visitor'], {'action': 'store_true'}),
524 """Runtime settings and command-line options common to all Docutils front
525 ends. Setting specs specific to individual Docutils components are also
526 used (see `populate_from_components()`)."""
528 settings_defaults
= {'_disable_config': None,
530 '_destination': None,
531 '_config_files': None}
532 """Defaults for settings that don't have command-line option equivalents."""
534 relative_path_settings
= ('warning_stream',)
536 config_section
= 'general'
538 version_template
= ('%%prog (Docutils %s [%s], Python %s, on %s)'
539 % (docutils
.__version
__, docutils
.__version
_details
__,
540 sys
.version
.split()[0], sys
.platform
))
541 """Default version message."""
543 def __init__(self
, components
=(), defaults
=None, read_config_files
=None,
546 `components` is a list of Docutils components each containing a
547 ``.settings_spec`` attribute. `defaults` is a mapping of setting
552 """Set of list-type settings."""
554 self
.config_files
= []
555 """List of paths of applied configuration files."""
557 optparse
.OptionParser
.__init
__(
558 self
, option_class
=Option
, add_help_option
=None,
559 formatter
=optparse
.TitledHelpFormatter(width
=78),
562 self
.version
= self
.version_template
563 # Make an instance copy (it will be modified):
564 self
.relative_path_settings
= list(self
.relative_path_settings
)
565 self
.components
= (self
,) + tuple(components
)
566 self
.populate_from_components(self
.components
)
567 self
.set_defaults_from_dict(defaults
or {})
568 if read_config_files
and not self
.defaults
['_disable_config']:
570 config_settings
= self
.get_standard_config_settings()
571 except ValueError, error
:
573 self
.set_defaults_from_dict(config_settings
.__dict
__)
575 def populate_from_components(self
, components
):
577 For each component, first populate from the `SettingsSpec.settings_spec`
578 structure, then from the `SettingsSpec.settings_defaults` dictionary.
579 After all components have been processed, check for and populate from
580 each component's `SettingsSpec.settings_default_overrides` dictionary.
582 for component
in components
:
583 if component
is None:
585 settings_spec
= component
.settings_spec
586 self
.relative_path_settings
.extend(
587 component
.relative_path_settings
)
588 for i
in range(0, len(settings_spec
), 3):
589 title
, description
, option_spec
= settings_spec
[i
:i
+3]
591 group
= optparse
.OptionGroup(self
, title
, description
)
592 self
.add_option_group(group
)
594 group
= self
# single options
595 for (help_text
, option_strings
, kwargs
) in option_spec
:
596 option
= group
.add_option(help=help_text
, *option_strings
,
598 if kwargs
.get('action') == 'append':
599 self
.lists
[option
.dest
] = 1
600 if component
.settings_defaults
:
601 self
.defaults
.update(component
.settings_defaults
)
602 for component
in components
:
603 if component
and component
.settings_default_overrides
:
604 self
.defaults
.update(component
.settings_default_overrides
)
606 def get_standard_config_files(self
):
607 """Return list of config files, from environment or standard."""
609 config_files
= os
.environ
['DOCUTILSCONFIG'].split(os
.pathsep
)
611 config_files
= self
.standard_config_files
613 # If 'HOME' is not set, expandvars() requires the 'pwd' module which is
614 # not available under certain environments, for example, within
615 # mod_python. The publisher ends up in here, and we need to publish
616 # from within mod_python. Therefore we need to avoid expanding when we
617 # are in those environments.
618 expand
= os
.path
.expanduser
619 if 'HOME' not in os
.environ
:
624 return [expand(f
) for f
in config_files
if f
.strip()]
626 def get_standard_config_settings(self
):
628 for filename
in self
.get_standard_config_files():
629 settings
.update(self
.get_config_file_settings(filename
), self
)
632 def get_config_file_settings(self
, config_file
):
633 """Returns a dictionary containing appropriate config file settings."""
634 parser
= ConfigParser()
635 parser
.read(config_file
, self
)
636 self
.config_files
.extend(parser
._files
)
637 base_path
= os
.path
.dirname(config_file
)
640 for component
in self
.components
:
643 for section
in (tuple(component
.config_section_dependencies
or ())
644 + (component
.config_section
,)):
645 if section
in applied
:
648 settings
.update(parser
.get_section(section
), self
)
650 settings
.__dict
__, self
.relative_path_settings
, base_path
)
651 return settings
.__dict
__
653 def check_values(self
, values
, args
):
654 """Store positional arguments as runtime settings."""
655 values
._source
, values
._destination
= self
.check_args(args
)
656 make_paths_absolute(values
.__dict
__, self
.relative_path_settings
)
657 values
._config
_files
= self
.config_files
660 def check_args(self
, args
):
661 source
= destination
= None
664 if source
== '-': # means stdin
667 destination
= args
.pop(0)
668 if destination
== '-': # means stdout
671 self
.error('Maximum 2 arguments allowed.')
672 if source
and source
== destination
:
673 self
.error('Do not specify the same file for both source and '
674 'destination. It will clobber the source file.')
675 return source
, destination
677 def set_defaults_from_dict(self
, defaults
):
678 self
.defaults
.update(defaults
)
680 def get_default_values(self
):
681 """Needed to get custom `Values` instances."""
682 defaults
= Values(self
.defaults
)
683 defaults
._config
_files
= self
.config_files
686 def get_option_by_dest(self
, dest
):
688 Get an option by its dest.
690 If you're supplying a dest which is shared by several options,
691 it is undefined which option of those is returned.
693 A KeyError is raised if there is no option with the supplied
696 for group
in self
.option_groups
+ [self
]:
697 for option
in group
.option_list
:
698 if option
.dest
== dest
:
700 raise KeyError('No option with dest == %r.' % dest
)
703 class ConfigParser(CP
.RawConfigParser
):
706 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
707 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
708 'pep_template': ('pep_html writer', 'template')}
709 """{old setting: (new section, new setting)} mapping, used by
710 `handle_old_config`, to convert settings from the old [options] section."""
713 The "[option]" section is deprecated. Support for old-format configuration
714 files may be removed in a future Docutils release. Please revise your
715 configuration files. See <http://docutils.sf.net/docs/user/config.html>,
716 section "Old-Format Configuration Files".
719 not_utf8_error
= """\
720 Unable to read configuration file "%s": content not encoded as UTF-8.
721 Skipping "%s" configuration file.
724 def __init__(self
, *args
, **kwargs
):
725 CP
.RawConfigParser
.__init
__(self
, *args
, **kwargs
)
728 """List of paths of configuration files read."""
730 self
._stderr
= ErrorOutput()
731 """Wrapper around sys.stderr catching en-/decoding errors"""
733 def read(self
, filenames
, option_parser
):
734 if type(filenames
) in (str, unicode):
735 filenames
= [filenames
]
736 for filename
in filenames
:
738 # Config files must be UTF-8-encoded:
739 fp
= codecs
.open(filename
, 'r', 'utf-8')
743 if sys
.version_info
< (3,2):
744 CP
.RawConfigParser
.readfp(self
, fp
, filename
)
746 CP
.RawConfigParser
.read_file(self
, fp
, filename
)
747 except UnicodeDecodeError:
748 self
._stderr
.write(self
.not_utf8_error
% (filename
, filename
))
752 self
._files
.append(filename
)
753 if self
.has_section('options'):
754 self
.handle_old_config(filename
)
755 self
.validate_settings(filename
, option_parser
)
757 def handle_old_config(self
, filename
):
758 warnings
.warn_explicit(self
.old_warning
, ConfigDeprecationWarning
,
760 options
= self
.get_section('options')
761 if not self
.has_section('general'):
762 self
.add_section('general')
763 for key
, value
in options
.items():
764 if key
in self
.old_settings
:
765 section
, setting
= self
.old_settings
[key
]
766 if not self
.has_section(section
):
767 self
.add_section(section
)
771 if not self
.has_option(section
, setting
):
772 self
.set(section
, setting
, value
)
773 self
.remove_section('options')
775 def validate_settings(self
, filename
, option_parser
):
777 Call the validator function and implement overrides on all applicable
780 for section
in self
.sections():
781 for setting
in self
.options(section
):
783 option
= option_parser
.get_option_by_dest(setting
)
787 value
= self
.get(section
, setting
)
789 new_value
= option
.validator(
790 setting
, value
, option_parser
,
791 config_parser
=self
, config_section
=section
)
792 except Exception, error
:
794 'Error in config file "%s", section "[%s]":\n'
797 % (filename
, section
, ErrorString(error
),
798 setting
, value
)), None, sys
.exc_info()[2])
799 self
.set(section
, setting
, new_value
)
801 self
.set(section
, option
.overrides
, None)
803 def optionxform(self
, optionstr
):
805 Transform '-' to '_' so the cmdline form of option names can be used.
807 return optionstr
.lower().replace('-', '_')
809 def get_section(self
, section
):
811 Return a given section as a dictionary (empty if the section
815 if self
.has_section(section
):
816 for option
in self
.options(section
):
817 section_dict
[option
] = self
.get(section
, option
)
821 class ConfigDeprecationWarning(DeprecationWarning):
822 """Warning for deprecated configuration file features."""