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 None: any other value (including '')
134 if isinstance(value
, bool) or value
is None:
139 return option_parser
.booleans
[value
.strip().lower()]
143 def validate_nonnegative_int(setting
, value
, option_parser
,
144 config_parser
=None, config_section
=None):
147 raise ValueError('negative value; must be positive or zero')
150 def validate_threshold(setting
, value
, option_parser
,
151 config_parser
=None, config_section
=None):
156 return option_parser
.thresholds
[value
.lower()]
157 except (KeyError, AttributeError):
158 raise (LookupError('unknown threshold: %r.' % value
),
159 None, sys
.exc_info
[2])
161 def validate_colon_separated_string_list(
162 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
163 if isinstance(value
, unicode):
164 value
= value
.split(':')
167 value
.extend(last
.split(':'))
170 def validate_comma_separated_list(setting
, value
, option_parser
,
171 config_parser
=None, config_section
=None):
172 """Check/normalize list arguments (split at "," and strip whitespace).
174 # `value` is already a list when given as command line option
175 # and "action" is "append"
176 if isinstance(value
, unicode):
178 # this function is called for every option added to `value`
179 # -> split the last item and apped the result:
181 classes
= [cls
.strip(u
' \t\n') for cls
in last
.split(',')
182 if cls
.strip(u
' \t\n')]
183 value
.extend(classes
)
186 def validate_url_trailing_slash(
187 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
190 elif value
.endswith('/'):
195 def validate_dependency_file(setting
, value
, option_parser
,
196 config_parser
=None, config_section
=None):
198 return docutils
.utils
.DependencyList(value
)
200 return docutils
.utils
.DependencyList(None)
202 def validate_strip_class(setting
, value
, option_parser
,
203 config_parser
=None, config_section
=None):
204 # value is a comma separated string list:
205 value
= validate_comma_separated_list(setting
, value
, option_parser
,
206 config_parser
, config_section
)
207 # validate list elements:
209 normalized
= docutils
.nodes
.make_id(cls
)
210 if cls
!= normalized
:
211 raise ValueError('invalid class value %r (perhaps %r?)'
215 def make_paths_absolute(pathdict
, keys
, base_path
=None):
217 Interpret filesystem path settings relative to the `base_path` given.
219 Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
220 `OptionParser.relative_path_settings`.
222 if base_path
is None:
223 base_path
= os
.getcwdu() # type(base_path) == unicode
224 # to allow combining non-ASCII cwd with unicode values in `pathdict`
227 value
= pathdict
[key
]
228 if isinstance(value
, list):
229 value
= [make_one_path_absolute(base_path
, path
)
232 value
= make_one_path_absolute(base_path
, value
)
233 pathdict
[key
] = value
235 def make_one_path_absolute(base_path
, path
):
236 return os
.path
.abspath(os
.path
.join(base_path
, path
))
238 def filter_settings_spec(settings_spec
, *exclude
, **replace
):
239 """Return a copy of `settings_spec` excluding/replacing some settings.
241 `settings_spec` is a tuple of configuration settings with a structure
242 described for docutils.SettingsSpec.settings_spec.
244 Optional positional arguments are names of to-be-excluded settings.
245 Keyword arguments are option specification replacements.
246 (See the html4strict writer for an example.)
248 settings
= list(settings_spec
)
249 # every third item is a sequence of option tuples
250 for i
in range(2, len(settings
), 3):
252 for opt_spec
in settings
[i
]:
253 # opt_spec is ("<help>", [<option strings>], {<keyword args>})
254 opt_name
= [opt_string
[2:].replace('-', '_')
255 for opt_string
in opt_spec
[1]
256 if opt_string
.startswith('--')
258 if opt_name
in exclude
:
260 if opt_name
in replace
.keys():
261 newopts
.append(replace
[opt_name
])
263 newopts
.append(opt_spec
)
264 settings
[i
] = tuple(newopts
)
265 return tuple(settings
)
268 class Values(optparse
.Values
):
271 Updates list attributes by extension rather than by replacement.
272 Works in conjunction with the `OptionParser.lists` instance attribute.
275 def __init__(self
, *args
, **kwargs
):
276 optparse
.Values
.__init
__(self
, *args
, **kwargs
)
277 if (not hasattr(self
, 'record_dependencies')
278 or self
.record_dependencies
is None):
279 # Set up dependency list, in case it is needed.
280 self
.record_dependencies
= docutils
.utils
.DependencyList()
282 def update(self
, other_dict
, option_parser
):
283 if isinstance(other_dict
, Values
):
284 other_dict
= other_dict
.__dict
__
285 other_dict
= other_dict
.copy()
286 for setting
in option_parser
.lists
.keys():
287 if (hasattr(self
, setting
) and setting
in other_dict
):
288 value
= getattr(self
, setting
)
290 value
+= other_dict
[setting
]
291 del other_dict
[setting
]
292 self
._update
_loose
(other_dict
)
295 """Return a shallow copy of `self`."""
296 return self
.__class
__(defaults
=self
.__dict
__)
299 class Option(optparse
.Option
):
301 ATTRS
= optparse
.Option
.ATTRS
+ ['validator', 'overrides']
303 def process(self
, opt
, value
, values
, parser
):
305 Call the validator function on applicable settings and
306 evaluate the 'overrides' option.
307 Extends `optparse.Option.process`.
309 result
= optparse
.Option
.process(self
, opt
, value
, values
, parser
)
313 value
= getattr(values
, setting
)
315 new_value
= self
.validator(setting
, value
, parser
)
316 except Exception, error
:
317 raise (optparse
.OptionValueError(
318 'Error in option "%s":\n %s'
319 % (opt
, ErrorString(error
))),
320 None, sys
.exc_info()[2])
321 setattr(values
, setting
, new_value
)
323 setattr(values
, self
.overrides
, None)
327 class OptionParser(optparse
.OptionParser
, docutils
.SettingsSpec
):
330 Parser for command-line and library use. The `settings_spec`
331 specification here and in other Docutils components are merged to build
332 the set of command-line options and runtime settings for this process.
334 Common settings (defined below) and component-specific settings must not
335 conflict. Short options are reserved for common settings, and components
336 are restrict to using long options.
339 standard_config_files
= [
340 '/etc/docutils.conf', # system-wide
341 './docutils.conf', # project-specific
342 '~/.docutils'] # user-specific
343 """Docutils configuration files, using ConfigParser syntax. Filenames
344 will be tilde-expanded later. Later files override earlier ones."""
346 threshold_choices
= 'info 1 warning 2 error 3 severe 4 none 5'.split()
347 """Possible inputs for for --report and --halt threshold values."""
349 thresholds
= {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
350 """Lookup table for --report and --halt threshold values."""
352 booleans
={'1': 1, 'on': 1, 'yes': 1, 'true': 1,
353 '0': 0, 'off': 0, 'no': 0, 'false': 0, '': 0}
354 """Lookup table for boolean configuration file settings."""
356 default_error_encoding
= getattr(sys
.stderr
, 'encoding',
357 None) or locale_encoding
or 'ascii'
359 default_error_encoding_error_handler
= 'backslashreplace'
362 'General Docutils Options',
364 (('Specify the document title as metadata.',
366 ('Include a "Generated by Docutils" credit and link.',
367 ['--generator', '-g'], {'action': 'store_true',
368 'validator': validate_boolean
}),
369 ('Do not include a generator credit.',
370 ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
371 ('Include the date at the end of the document (UTC).',
372 ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
373 'dest': 'datestamp'}),
374 ('Include the time & date (UTC).',
375 ['--time', '-t'], {'action': 'store_const',
376 'const': '%Y-%m-%d %H:%M UTC',
377 'dest': 'datestamp'}),
378 ('Do not include a datestamp of any kind.',
379 ['--no-datestamp'], {'action': 'store_const', 'const': None,
380 'dest': 'datestamp'}),
381 ('Include a "View document source" link.',
382 ['--source-link', '-s'], {'action': 'store_true',
383 'validator': validate_boolean
}),
384 ('Use <URL> for a source link; implies --source-link.',
385 ['--source-url'], {'metavar': '<URL>'}),
386 ('Do not include a "View document source" link.',
387 ['--no-source-link'],
388 {'action': 'callback', 'callback': store_multiple
,
389 'callback_args': ('source_link', 'source_url')}),
390 ('Link from section headers to TOC entries. (default)',
391 ['--toc-entry-backlinks'],
392 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
393 'default': 'entry'}),
394 ('Link from section headers to the top of the TOC.',
395 ['--toc-top-backlinks'],
396 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
397 ('Disable backlinks to the table of contents.',
398 ['--no-toc-backlinks'],
399 {'dest': 'toc_backlinks', 'action': 'store_false'}),
400 ('Link from footnotes/citations to references. (default)',
401 ['--footnote-backlinks'],
402 {'action': 'store_true', 'default': 1,
403 'validator': validate_boolean
}),
404 ('Disable backlinks from footnotes and citations.',
405 ['--no-footnote-backlinks'],
406 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
407 ('Enable section numbering by Docutils. (default)',
408 ['--section-numbering'],
409 {'action': 'store_true', 'dest': 'sectnum_xform',
410 'default': 1, 'validator': validate_boolean
}),
411 ('Disable section numbering by Docutils.',
412 ['--no-section-numbering'],
413 {'action': 'store_false', 'dest': 'sectnum_xform'}),
414 ('Remove comment elements from the document tree.',
415 ['--strip-comments'],
416 {'action': 'store_true', 'validator': validate_boolean
}),
417 ('Leave comment elements in the document tree. (default)',
418 ['--leave-comments'],
419 {'action': 'store_false', 'dest': 'strip_comments'}),
420 ('Remove all elements with classes="<class>" from the document tree. '
421 'Warning: potentially dangerous; use with caution. '
422 '(Multiple-use option.)',
423 ['--strip-elements-with-class'],
424 {'action': 'append', 'dest': 'strip_elements_with_classes',
425 'metavar': '<class>', 'validator': validate_strip_class
}),
426 ('Remove all classes="<class>" attributes from elements in the '
427 'document tree. Warning: potentially dangerous; use with caution. '
428 '(Multiple-use option.)',
430 {'action': 'append', 'dest': 'strip_classes',
431 'metavar': '<class>', 'validator': validate_strip_class
}),
432 ('Report system messages at or higher than <level>: "info" or "1", '
433 '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
434 ['--report', '-r'], {'choices': threshold_choices
, 'default': 2,
435 'dest': 'report_level', 'metavar': '<level>',
436 'validator': validate_threshold
}),
437 ('Report all system messages. (Same as "--report=1".)',
438 ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
439 'dest': 'report_level'}),
440 ('Report no system messages. (Same as "--report=5".)',
441 ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
442 'dest': 'report_level'}),
443 ('Halt execution at system messages at or above <level>. '
444 'Levels as in --report. Default: 4 (severe).',
445 ['--halt'], {'choices': threshold_choices
, 'dest': 'halt_level',
446 'default': 4, 'metavar': '<level>',
447 'validator': validate_threshold
}),
448 ('Halt at the slightest problem. Same as "--halt=info".',
449 ['--strict'], {'action': 'store_const', 'const': 1,
450 'dest': 'halt_level'}),
451 ('Enable a non-zero exit status for non-halting system messages at '
452 'or above <level>. Default: 5 (disabled).',
453 ['--exit-status'], {'choices': threshold_choices
,
454 'dest': 'exit_status_level',
455 'default': 5, 'metavar': '<level>',
456 'validator': validate_threshold
}),
457 ('Enable debug-level system messages and diagnostics.',
458 ['--debug'], {'action': 'store_true', 'validator': validate_boolean
}),
459 ('Disable debug output. (default)',
460 ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
461 ('Send the output of system messages to <file>.',
462 ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
463 ('Enable Python tracebacks when Docutils is halted.',
464 ['--traceback'], {'action': 'store_true', 'default': None,
465 'validator': validate_boolean
}),
466 ('Disable Python tracebacks. (default)',
467 ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
468 ('Specify the encoding and optionally the '
469 'error handler of input text. Default: <locale-dependent>:strict.',
470 ['--input-encoding', '-i'],
471 {'metavar': '<name[:handler]>',
472 'validator': validate_encoding_and_error_handler
}),
473 ('Specify the error handler for undecodable characters. '
474 'Choices: "strict" (default), "ignore", and "replace".',
475 ['--input-encoding-error-handler'],
476 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
477 ('Specify the text encoding and optionally the error handler for '
478 'output. Default: UTF-8:strict.',
479 ['--output-encoding', '-o'],
480 {'metavar': '<name[:handler]>', 'default': 'utf-8',
481 'validator': validate_encoding_and_error_handler
}),
482 ('Specify error handler for unencodable output characters; '
483 '"strict" (default), "ignore", "replace", '
484 '"xmlcharrefreplace", "backslashreplace".',
485 ['--output-encoding-error-handler'],
486 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
487 ('Specify text encoding and error handler for error output. '
489 % (default_error_encoding
, default_error_encoding_error_handler
),
490 ['--error-encoding', '-e'],
491 {'metavar': '<name[:handler]>', 'default': default_error_encoding
,
492 'validator': validate_encoding_and_error_handler
}),
493 ('Specify the error handler for unencodable characters in '
494 'error output. Default: %s.'
495 % default_error_encoding_error_handler
,
496 ['--error-encoding-error-handler'],
497 {'default': default_error_encoding_error_handler
,
498 'validator': validate_encoding_error_handler
}),
499 ('Specify the language (as BCP 47 language tag). Default: en.',
500 ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
501 'metavar': '<name>'}),
502 ('Write output file dependencies to <file>.',
503 ['--record-dependencies'],
504 {'metavar': '<file>', 'validator': validate_dependency_file
,
505 'default': None}), # default set in Values class
506 ('Read configuration settings from <file>, if it exists.',
507 ['--config'], {'metavar': '<file>', 'type': 'string',
508 'action': 'callback', 'callback': read_config_file
}),
509 ("Show this program's version number and exit.",
510 ['--version', '-V'], {'action': 'version'}),
511 ('Show this help message and exit.',
512 ['--help', '-h'], {'action': 'help'}),
513 # Typically not useful for non-programmatical use:
514 (SUPPRESS_HELP
, ['--id-prefix'], {'default': ''}),
515 (SUPPRESS_HELP
, ['--auto-id-prefix'], {'default': 'id'}),
516 # Hidden options, for development use only:
517 (SUPPRESS_HELP
, ['--dump-settings'], {'action': 'store_true'}),
518 (SUPPRESS_HELP
, ['--dump-internals'], {'action': 'store_true'}),
519 (SUPPRESS_HELP
, ['--dump-transforms'], {'action': 'store_true'}),
520 (SUPPRESS_HELP
, ['--dump-pseudo-xml'], {'action': 'store_true'}),
521 (SUPPRESS_HELP
, ['--expose-internal-attribute'],
522 {'action': 'append', 'dest': 'expose_internals',
523 'validator': validate_colon_separated_string_list
}),
524 (SUPPRESS_HELP
, ['--strict-visitor'], {'action': 'store_true'}),
526 """Runtime settings and command-line options common to all Docutils front
527 ends. Setting specs specific to individual Docutils components are also
528 used (see `populate_from_components()`)."""
530 settings_defaults
= {'_disable_config': None,
532 '_destination': None,
533 '_config_files': None}
534 """Defaults for settings that don't have command-line option equivalents."""
536 relative_path_settings
= ('warning_stream',)
538 config_section
= 'general'
540 version_template
= ('%%prog (Docutils %s [%s], Python %s, on %s)'
541 % (docutils
.__version
__, docutils
.__version
_details
__,
542 sys
.version
.split()[0], sys
.platform
))
543 """Default version message."""
545 def __init__(self
, components
=(), defaults
=None, read_config_files
=None,
548 `components` is a list of Docutils components each containing a
549 ``.settings_spec`` attribute. `defaults` is a mapping of setting
554 """Set of list-type settings."""
556 self
.config_files
= []
557 """List of paths of applied configuration files."""
559 optparse
.OptionParser
.__init
__(
560 self
, option_class
=Option
, add_help_option
=None,
561 formatter
=optparse
.TitledHelpFormatter(width
=78),
564 self
.version
= self
.version_template
565 # Make an instance copy (it will be modified):
566 self
.relative_path_settings
= list(self
.relative_path_settings
)
567 self
.components
= (self
,) + tuple(components
)
568 self
.populate_from_components(self
.components
)
569 self
.set_defaults_from_dict(defaults
or {})
570 if read_config_files
and not self
.defaults
['_disable_config']:
572 config_settings
= self
.get_standard_config_settings()
573 except ValueError, error
:
575 self
.set_defaults_from_dict(config_settings
.__dict
__)
577 def populate_from_components(self
, components
):
579 For each component, first populate from the `SettingsSpec.settings_spec`
580 structure, then from the `SettingsSpec.settings_defaults` dictionary.
581 After all components have been processed, check for and populate from
582 each component's `SettingsSpec.settings_default_overrides` dictionary.
584 for component
in components
:
585 if component
is None:
587 settings_spec
= component
.settings_spec
588 self
.relative_path_settings
.extend(
589 component
.relative_path_settings
)
590 for i
in range(0, len(settings_spec
), 3):
591 title
, description
, option_spec
= settings_spec
[i
:i
+3]
593 group
= optparse
.OptionGroup(self
, title
, description
)
594 self
.add_option_group(group
)
596 group
= self
# single options
597 for (help_text
, option_strings
, kwargs
) in option_spec
:
598 option
= group
.add_option(help=help_text
, *option_strings
,
600 if kwargs
.get('action') == 'append':
601 self
.lists
[option
.dest
] = 1
602 if component
.settings_defaults
:
603 self
.defaults
.update(component
.settings_defaults
)
604 for component
in components
:
605 if component
and component
.settings_default_overrides
:
606 self
.defaults
.update(component
.settings_default_overrides
)
608 def get_standard_config_files(self
):
609 """Return list of config files, from environment or standard."""
611 config_files
= os
.environ
['DOCUTILSCONFIG'].split(os
.pathsep
)
613 config_files
= self
.standard_config_files
615 # If 'HOME' is not set, expandvars() requires the 'pwd' module which is
616 # not available under certain environments, for example, within
617 # mod_python. The publisher ends up in here, and we need to publish
618 # from within mod_python. Therefore we need to avoid expanding when we
619 # are in those environments.
620 expand
= os
.path
.expanduser
621 if 'HOME' not in os
.environ
:
626 return [expand(f
) for f
in config_files
if f
.strip()]
628 def get_standard_config_settings(self
):
630 for filename
in self
.get_standard_config_files():
631 settings
.update(self
.get_config_file_settings(filename
), self
)
634 def get_config_file_settings(self
, config_file
):
635 """Returns a dictionary containing appropriate config file settings."""
636 parser
= ConfigParser()
637 parser
.read(config_file
, self
)
638 self
.config_files
.extend(parser
._files
)
639 base_path
= os
.path
.dirname(config_file
)
642 for component
in self
.components
:
645 for section
in (tuple(component
.config_section_dependencies
or ())
646 + (component
.config_section
,)):
647 if section
in applied
:
650 settings
.update(parser
.get_section(section
), self
)
652 settings
.__dict
__, self
.relative_path_settings
, base_path
)
653 return settings
.__dict
__
655 def check_values(self
, values
, args
):
656 """Store positional arguments as runtime settings."""
657 values
._source
, values
._destination
= self
.check_args(args
)
658 make_paths_absolute(values
.__dict
__, self
.relative_path_settings
)
659 values
._config
_files
= self
.config_files
662 def check_args(self
, args
):
663 source
= destination
= None
666 if source
== '-': # means stdin
669 destination
= args
.pop(0)
670 if destination
== '-': # means stdout
673 self
.error('Maximum 2 arguments allowed.')
674 if source
and source
== destination
:
675 self
.error('Do not specify the same file for both source and '
676 'destination. It will clobber the source file.')
677 return source
, destination
679 def set_defaults_from_dict(self
, defaults
):
680 self
.defaults
.update(defaults
)
682 def get_default_values(self
):
683 """Needed to get custom `Values` instances."""
684 defaults
= Values(self
.defaults
)
685 defaults
._config
_files
= self
.config_files
688 def get_option_by_dest(self
, dest
):
690 Get an option by its dest.
692 If you're supplying a dest which is shared by several options,
693 it is undefined which option of those is returned.
695 A KeyError is raised if there is no option with the supplied
698 for group
in self
.option_groups
+ [self
]:
699 for option
in group
.option_list
:
700 if option
.dest
== dest
:
702 raise KeyError('No option with dest == %r.' % dest
)
705 class ConfigParser(CP
.RawConfigParser
):
708 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
709 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
710 'pep_template': ('pep_html writer', 'template')}
711 """{old setting: (new section, new setting)} mapping, used by
712 `handle_old_config`, to convert settings from the old [options] section."""
715 The "[option]" section is deprecated. Support for old-format configuration
716 files may be removed in a future Docutils release. Please revise your
717 configuration files. See <http://docutils.sf.net/docs/user/config.html>,
718 section "Old-Format Configuration Files".
721 not_utf8_error
= """\
722 Unable to read configuration file "%s": content not encoded as UTF-8.
723 Skipping "%s" configuration file.
726 def __init__(self
, *args
, **kwargs
):
727 CP
.RawConfigParser
.__init
__(self
, *args
, **kwargs
)
730 """List of paths of configuration files read."""
732 self
._stderr
= ErrorOutput()
733 """Wrapper around sys.stderr catching en-/decoding errors"""
735 def read(self
, filenames
, option_parser
):
736 if type(filenames
) in (str, unicode):
737 filenames
= [filenames
]
738 for filename
in filenames
:
740 # Config files must be UTF-8-encoded:
741 fp
= codecs
.open(filename
, 'r', 'utf-8')
745 if sys
.version_info
< (3,2):
746 CP
.RawConfigParser
.readfp(self
, fp
, filename
)
748 CP
.RawConfigParser
.read_file(self
, fp
, filename
)
749 except UnicodeDecodeError:
750 self
._stderr
.write(self
.not_utf8_error
% (filename
, filename
))
754 self
._files
.append(filename
)
755 if self
.has_section('options'):
756 self
.handle_old_config(filename
)
757 self
.validate_settings(filename
, option_parser
)
759 def handle_old_config(self
, filename
):
760 warnings
.warn_explicit(self
.old_warning
, ConfigDeprecationWarning
,
762 options
= self
.get_section('options')
763 if not self
.has_section('general'):
764 self
.add_section('general')
765 for key
, value
in options
.items():
766 if key
in self
.old_settings
:
767 section
, setting
= self
.old_settings
[key
]
768 if not self
.has_section(section
):
769 self
.add_section(section
)
773 if not self
.has_option(section
, setting
):
774 self
.set(section
, setting
, value
)
775 self
.remove_section('options')
777 def validate_settings(self
, filename
, option_parser
):
779 Call the validator function and implement overrides on all applicable
782 for section
in self
.sections():
783 for setting
in self
.options(section
):
785 option
= option_parser
.get_option_by_dest(setting
)
789 value
= self
.get(section
, setting
)
791 new_value
= option
.validator(
792 setting
, value
, option_parser
,
793 config_parser
=self
, config_section
=section
)
794 except Exception, error
:
796 'Error in config file "%s", section "[%s]":\n'
799 % (filename
, section
, ErrorString(error
),
800 setting
, value
)), None, sys
.exc_info()[2])
801 self
.set(section
, setting
, new_value
)
803 self
.set(section
, option
.overrides
, None)
805 def optionxform(self
, optionstr
):
807 Transform '-' to '_' so the cmdline form of option names can be used.
809 return optionstr
.lower().replace('-', '_')
811 def get_section(self
, section
):
813 Return a given section as a dictionary (empty if the section
817 if self
.has_section(section
):
818 for option
in self
.options(section
):
819 section_dict
[option
] = self
.get(section
, option
)
823 class ConfigDeprecationWarning(DeprecationWarning):
824 """Warning for deprecated configuration file features."""