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 # TODO fix here or in buildhtml or process
176 # values=frontend.Values()
178 # optparse _process_args, _process_long_opt
179 # but then value is NOT unicode but str in python2
180 if isinstance(value
, unicode):
182 # this function is called for every option added to `value`
183 # -> split the last item and append the result:
185 classes
= [cls
.strip(u
' \t\n') for cls
in last
.split(',')
186 if cls
.strip(u
' \t\n')]
187 value
.extend(classes
)
190 def validate_url_trailing_slash(
191 setting
, value
, option_parser
, config_parser
=None, config_section
=None):
194 elif value
.endswith('/'):
199 def validate_dependency_file(setting
, value
, option_parser
,
200 config_parser
=None, config_section
=None):
202 return docutils
.utils
.DependencyList(value
)
204 return docutils
.utils
.DependencyList(None)
206 def validate_strip_class(setting
, value
, option_parser
,
207 config_parser
=None, config_section
=None):
208 # value is a comma separated string list:
209 value
= validate_comma_separated_list(setting
, value
, option_parser
,
210 config_parser
, config_section
)
211 # validate list elements:
213 normalized
= docutils
.nodes
.make_id(cls
)
214 if cls
!= normalized
:
215 raise ValueError('invalid class value %r (perhaps %r?)'
219 def make_paths_absolute(pathdict
, keys
, base_path
=None):
221 Interpret filesystem path settings relative to the `base_path` given.
223 Paths are values in `pathdict` whose keys are in `keys`. Get `keys` from
224 `OptionParser.relative_path_settings`.
226 if base_path
is None:
227 base_path
= os
.getcwdu() # type(base_path) == unicode
228 # to allow combining non-ASCII cwd with unicode values in `pathdict`
231 value
= pathdict
[key
]
232 if isinstance(value
, list):
233 value
= [make_one_path_absolute(base_path
, path
)
236 value
= make_one_path_absolute(base_path
, value
)
237 pathdict
[key
] = value
239 def make_one_path_absolute(base_path
, path
):
240 return os
.path
.abspath(os
.path
.join(base_path
, path
))
242 def filter_settings_spec(settings_spec
, *exclude
, **replace
):
243 """Return a copy of `settings_spec` excluding/replacing some settings.
245 `settings_spec` is a tuple of configuration settings with a structure
246 described for docutils.SettingsSpec.settings_spec.
248 Optional positional arguments are names of to-be-excluded settings.
249 Keyword arguments are option specification replacements.
250 (See the html4strict writer for an example.)
252 settings
= list(settings_spec
)
253 # every third item is a sequence of option tuples
254 for i
in range(2, len(settings
), 3):
256 for opt_spec
in settings
[i
]:
257 # opt_spec is ("<help>", [<option strings>], {<keyword args>})
258 opt_name
= [opt_string
[2:].replace('-', '_')
259 for opt_string
in opt_spec
[1]
260 if opt_string
.startswith('--')
262 if opt_name
in exclude
:
264 if opt_name
in replace
.keys():
265 newopts
.append(replace
[opt_name
])
267 newopts
.append(opt_spec
)
268 settings
[i
] = tuple(newopts
)
269 return tuple(settings
)
272 class Values(optparse
.Values
):
275 Updates list attributes by extension rather than by replacement.
276 Works in conjunction with the `OptionParser.lists` instance attribute.
279 def __init__(self
, *args
, **kwargs
):
280 optparse
.Values
.__init
__(self
, *args
, **kwargs
)
281 if (not hasattr(self
, 'record_dependencies')
282 or self
.record_dependencies
is None):
283 # Set up dependency list, in case it is needed.
284 self
.record_dependencies
= docutils
.utils
.DependencyList()
286 def update(self
, other_dict
, option_parser
):
287 if isinstance(other_dict
, Values
):
288 other_dict
= other_dict
.__dict
__
289 other_dict
= other_dict
.copy()
290 for setting
in option_parser
.lists
.keys():
291 if (hasattr(self
, setting
) and setting
in other_dict
):
292 value
= getattr(self
, setting
)
294 value
+= other_dict
[setting
]
295 del other_dict
[setting
]
296 self
._update
_loose
(other_dict
)
299 """Return a shallow copy of `self`."""
300 return self
.__class
__(defaults
=self
.__dict
__)
303 class Option(optparse
.Option
):
305 ATTRS
= optparse
.Option
.ATTRS
+ ['validator', 'overrides']
307 def process(self
, opt
, value
, values
, parser
):
309 Call the validator function on applicable settings and
310 evaluate the 'overrides' option.
311 Extends `optparse.Option.process`.
313 result
= optparse
.Option
.process(self
, opt
, value
, values
, parser
)
317 value
= getattr(values
, setting
)
319 new_value
= self
.validator(setting
, value
, parser
)
320 except Exception, error
:
321 raise (optparse
.OptionValueError(
322 'Error in option "%s":\n %s'
323 % (opt
, ErrorString(error
))),
324 None, sys
.exc_info()[2])
325 setattr(values
, setting
, new_value
)
327 setattr(values
, self
.overrides
, None)
331 class OptionParser(optparse
.OptionParser
, docutils
.SettingsSpec
):
334 Parser for command-line and library use. The `settings_spec`
335 specification here and in other Docutils components are merged to build
336 the set of command-line options and runtime settings for this process.
338 Common settings (defined below) and component-specific settings must not
339 conflict. Short options are reserved for common settings, and components
340 are restrict to using long options.
343 standard_config_files
= [
344 '/etc/docutils.conf', # system-wide
345 './docutils.conf', # project-specific
346 '~/.docutils'] # user-specific
347 """Docutils configuration files, using ConfigParser syntax. Filenames
348 will be tilde-expanded later. Later files override earlier ones."""
350 threshold_choices
= 'info 1 warning 2 error 3 severe 4 none 5'.split()
351 """Possible inputs for for --report and --halt threshold values."""
353 thresholds
= {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
354 """Lookup table for --report and --halt threshold values."""
356 booleans
={'1': True, 'on': True, 'yes': True, 'true': True,
357 '0': False, 'off': False, 'no': False, 'false': False, '': False}
358 """Lookup table for boolean configuration file settings."""
360 default_error_encoding
= getattr(sys
.stderr
, 'encoding',
361 None) or locale_encoding
or 'ascii'
363 default_error_encoding_error_handler
= 'backslashreplace'
366 'General Docutils Options',
368 (('Specify the document title as metadata.',
370 ('Include a "Generated by Docutils" credit and link.',
371 ['--generator', '-g'], {'action': 'store_true',
372 'validator': validate_boolean
}),
373 ('Do not include a generator credit.',
374 ['--no-generator'], {'action': 'store_false', 'dest': 'generator'}),
375 ('Include the date at the end of the document (UTC).',
376 ['--date', '-d'], {'action': 'store_const', 'const': '%Y-%m-%d',
377 'dest': 'datestamp'}),
378 ('Include the time & date (UTC).',
379 ['--time', '-t'], {'action': 'store_const',
380 'const': '%Y-%m-%d %H:%M UTC',
381 'dest': 'datestamp'}),
382 ('Do not include a datestamp of any kind.',
383 ['--no-datestamp'], {'action': 'store_const', 'const': None,
384 'dest': 'datestamp'}),
385 ('Include a "View document source" link.',
386 ['--source-link', '-s'], {'action': 'store_true',
387 'validator': validate_boolean
}),
388 ('Use <URL> for a source link; implies --source-link.',
389 ['--source-url'], {'metavar': '<URL>'}),
390 ('Do not include a "View document source" link.',
391 ['--no-source-link'],
392 {'action': 'callback', 'callback': store_multiple
,
393 'callback_args': ('source_link', 'source_url')}),
394 ('Link from section headers to TOC entries. (default)',
395 ['--toc-entry-backlinks'],
396 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'entry',
397 'default': 'entry'}),
398 ('Link from section headers to the top of the TOC.',
399 ['--toc-top-backlinks'],
400 {'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
401 ('Disable backlinks to the table of contents.',
402 ['--no-toc-backlinks'],
403 {'dest': 'toc_backlinks', 'action': 'store_false'}),
404 ('Link from footnotes/citations to references. (default)',
405 ['--footnote-backlinks'],
406 {'action': 'store_true', 'default': 1,
407 'validator': validate_boolean
}),
408 ('Disable backlinks from footnotes and citations.',
409 ['--no-footnote-backlinks'],
410 {'dest': 'footnote_backlinks', 'action': 'store_false'}),
411 ('Enable section numbering by Docutils. (default)',
412 ['--section-numbering'],
413 {'action': 'store_true', 'dest': 'sectnum_xform',
414 'default': 1, 'validator': validate_boolean
}),
415 ('Disable section numbering by Docutils.',
416 ['--no-section-numbering'],
417 {'action': 'store_false', 'dest': 'sectnum_xform'}),
418 ('Remove comment elements from the document tree.',
419 ['--strip-comments'],
420 {'action': 'store_true', 'validator': validate_boolean
}),
421 ('Leave comment elements in the document tree. (default)',
422 ['--leave-comments'],
423 {'action': 'store_false', 'dest': 'strip_comments'}),
424 ('Remove all elements with classes="<class>" from the document tree. '
425 'Warning: potentially dangerous; use with caution. '
426 '(Multiple-use option.)',
427 ['--strip-elements-with-class'],
428 {'action': 'append', 'dest': 'strip_elements_with_classes',
429 'metavar': '<class>', 'validator': validate_strip_class
}),
430 ('Remove all classes="<class>" attributes from elements in the '
431 'document tree. Warning: potentially dangerous; use with caution. '
432 '(Multiple-use option.)',
434 {'action': 'append', 'dest': 'strip_classes',
435 'metavar': '<class>', 'validator': validate_strip_class
}),
436 ('Report system messages at or higher than <level>: "info" or "1", '
437 '"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
438 ['--report', '-r'], {'choices': threshold_choices
, 'default': 2,
439 'dest': 'report_level', 'metavar': '<level>',
440 'validator': validate_threshold
}),
441 ('Report all system messages. (Same as "--report=1".)',
442 ['--verbose', '-v'], {'action': 'store_const', 'const': 1,
443 'dest': 'report_level'}),
444 ('Report no system messages. (Same as "--report=5".)',
445 ['--quiet', '-q'], {'action': 'store_const', 'const': 5,
446 'dest': 'report_level'}),
447 ('Halt execution at system messages at or above <level>. '
448 'Levels as in --report. Default: 4 (severe).',
449 ['--halt'], {'choices': threshold_choices
, 'dest': 'halt_level',
450 'default': 4, 'metavar': '<level>',
451 'validator': validate_threshold
}),
452 ('Halt at the slightest problem. Same as "--halt=info".',
453 ['--strict'], {'action': 'store_const', 'const': 1,
454 'dest': 'halt_level'}),
455 ('Enable a non-zero exit status for non-halting system messages at '
456 'or above <level>. Default: 5 (disabled).',
457 ['--exit-status'], {'choices': threshold_choices
,
458 'dest': 'exit_status_level',
459 'default': 5, 'metavar': '<level>',
460 'validator': validate_threshold
}),
461 ('Enable debug-level system messages and diagnostics.',
462 ['--debug'], {'action': 'store_true', 'validator': validate_boolean
}),
463 ('Disable debug output. (default)',
464 ['--no-debug'], {'action': 'store_false', 'dest': 'debug'}),
465 ('Send the output of system messages to <file>.',
466 ['--warnings'], {'dest': 'warning_stream', 'metavar': '<file>'}),
467 ('Enable Python tracebacks when Docutils is halted.',
468 ['--traceback'], {'action': 'store_true', 'default': None,
469 'validator': validate_boolean
}),
470 ('Disable Python tracebacks. (default)',
471 ['--no-traceback'], {'dest': 'traceback', 'action': 'store_false'}),
472 ('Specify the encoding and optionally the '
473 'error handler of input text. Default: <locale-dependent>:strict.',
474 ['--input-encoding', '-i'],
475 {'metavar': '<name[:handler]>',
476 'validator': validate_encoding_and_error_handler
}),
477 ('Specify the error handler for undecodable characters. '
478 'Choices: "strict" (default), "ignore", and "replace".',
479 ['--input-encoding-error-handler'],
480 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
481 ('Specify the text encoding and optionally the error handler for '
482 'output. Default: UTF-8:strict.',
483 ['--output-encoding', '-o'],
484 {'metavar': '<name[:handler]>', 'default': 'utf-8',
485 'validator': validate_encoding_and_error_handler
}),
486 ('Specify error handler for unencodable output characters; '
487 '"strict" (default), "ignore", "replace", '
488 '"xmlcharrefreplace", "backslashreplace".',
489 ['--output-encoding-error-handler'],
490 {'default': 'strict', 'validator': validate_encoding_error_handler
}),
491 ('Specify text encoding and error handler for error output. '
493 % (default_error_encoding
, default_error_encoding_error_handler
),
494 ['--error-encoding', '-e'],
495 {'metavar': '<name[:handler]>', 'default': default_error_encoding
,
496 'validator': validate_encoding_and_error_handler
}),
497 ('Specify the error handler for unencodable characters in '
498 'error output. Default: %s.'
499 % default_error_encoding_error_handler
,
500 ['--error-encoding-error-handler'],
501 {'default': default_error_encoding_error_handler
,
502 'validator': validate_encoding_error_handler
}),
503 ('Specify the language (as BCP 47 language tag). Default: en.',
504 ['--language', '-l'], {'dest': 'language_code', 'default': 'en',
505 'metavar': '<name>'}),
506 ('Write output file dependencies to <file>.',
507 ['--record-dependencies'],
508 {'metavar': '<file>', 'validator': validate_dependency_file
,
509 'default': None}), # default set in Values class
510 ('Read configuration settings from <file>, if it exists.',
511 ['--config'], {'metavar': '<file>', 'type': 'string',
512 'action': 'callback', 'callback': read_config_file
}),
513 ("Show this program's version number and exit.",
514 ['--version', '-V'], {'action': 'version'}),
515 ('Show this help message and exit.',
516 ['--help', '-h'], {'action': 'help'}),
517 # Typically not useful for non-programmatical use:
518 (SUPPRESS_HELP
, ['--id-prefix'], {'default': ''}),
519 (SUPPRESS_HELP
, ['--auto-id-prefix'], {'default': 'id'}),
520 # Hidden options, for development use only:
521 (SUPPRESS_HELP
, ['--dump-settings'], {'action': 'store_true'}),
522 (SUPPRESS_HELP
, ['--dump-internals'], {'action': 'store_true'}),
523 (SUPPRESS_HELP
, ['--dump-transforms'], {'action': 'store_true'}),
524 (SUPPRESS_HELP
, ['--dump-pseudo-xml'], {'action': 'store_true'}),
525 (SUPPRESS_HELP
, ['--expose-internal-attribute'],
526 {'action': 'append', 'dest': 'expose_internals',
527 'validator': validate_colon_separated_string_list
}),
528 (SUPPRESS_HELP
, ['--strict-visitor'], {'action': 'store_true'}),
530 """Runtime settings and command-line options common to all Docutils front
531 ends. Setting specs specific to individual Docutils components are also
532 used (see `populate_from_components()`)."""
534 settings_defaults
= {'_disable_config': None,
536 '_destination': None,
537 '_config_files': None}
538 """Defaults for settings that don't have command-line option equivalents."""
540 relative_path_settings
= ('warning_stream',)
542 config_section
= 'general'
544 version_template
= ('%%prog (Docutils %s [%s], Python %s, on %s)'
545 % (docutils
.__version
__, docutils
.__version
_details
__,
546 sys
.version
.split()[0], sys
.platform
))
547 """Default version message."""
549 def __init__(self
, components
=(), defaults
=None, read_config_files
=None,
552 `components` is a list of Docutils components each containing a
553 ``.settings_spec`` attribute. `defaults` is a mapping of setting
558 """Set of list-type settings."""
560 self
.config_files
= []
561 """List of paths of applied configuration files."""
563 optparse
.OptionParser
.__init
__(
564 self
, option_class
=Option
, add_help_option
=None,
565 formatter
=optparse
.TitledHelpFormatter(width
=78),
568 self
.version
= self
.version_template
569 # Make an instance copy (it will be modified):
570 self
.relative_path_settings
= list(self
.relative_path_settings
)
571 self
.components
= (self
,) + tuple(components
)
572 self
.populate_from_components(self
.components
)
573 self
.set_defaults_from_dict(defaults
or {})
574 if read_config_files
and not self
.defaults
['_disable_config']:
576 config_settings
= self
.get_standard_config_settings()
577 except ValueError, error
:
579 self
.set_defaults_from_dict(config_settings
.__dict
__)
581 def populate_from_components(self
, components
):
583 For each component, first populate from the `SettingsSpec.settings_spec`
584 structure, then from the `SettingsSpec.settings_defaults` dictionary.
585 After all components have been processed, check for and populate from
586 each component's `SettingsSpec.settings_default_overrides` dictionary.
588 for component
in components
:
589 if component
is None:
591 settings_spec
= component
.settings_spec
592 self
.relative_path_settings
.extend(
593 component
.relative_path_settings
)
594 for i
in range(0, len(settings_spec
), 3):
595 title
, description
, option_spec
= settings_spec
[i
:i
+3]
597 group
= optparse
.OptionGroup(self
, title
, description
)
598 self
.add_option_group(group
)
600 group
= self
# single options
601 for (help_text
, option_strings
, kwargs
) in option_spec
:
602 option
= group
.add_option(help=help_text
, *option_strings
,
604 if kwargs
.get('action') == 'append':
605 self
.lists
[option
.dest
] = 1
606 if component
.settings_defaults
:
607 self
.defaults
.update(component
.settings_defaults
)
608 for component
in components
:
609 if component
and component
.settings_default_overrides
:
610 self
.defaults
.update(component
.settings_default_overrides
)
612 def get_standard_config_files(self
):
613 """Return list of config files, from environment or standard."""
615 config_files
= os
.environ
['DOCUTILSCONFIG'].split(os
.pathsep
)
617 config_files
= self
.standard_config_files
619 # If 'HOME' is not set, expandvars() requires the 'pwd' module which is
620 # not available under certain environments, for example, within
621 # mod_python. The publisher ends up in here, and we need to publish
622 # from within mod_python. Therefore we need to avoid expanding when we
623 # are in those environments.
624 expand
= os
.path
.expanduser
625 if 'HOME' not in os
.environ
:
630 return [expand(f
) for f
in config_files
if f
.strip()]
632 def get_standard_config_settings(self
):
634 for filename
in self
.get_standard_config_files():
635 settings
.update(self
.get_config_file_settings(filename
), self
)
638 def get_config_file_settings(self
, config_file
):
639 """Returns a dictionary containing appropriate config file settings."""
640 parser
= ConfigParser()
641 parser
.read(config_file
, self
)
642 self
.config_files
.extend(parser
._files
)
643 base_path
= os
.path
.dirname(config_file
)
646 for component
in self
.components
:
649 for section
in (tuple(component
.config_section_dependencies
or ())
650 + (component
.config_section
,)):
651 if section
in applied
:
654 settings
.update(parser
.get_section(section
), self
)
656 settings
.__dict
__, self
.relative_path_settings
, base_path
)
657 return settings
.__dict
__
659 def check_values(self
, values
, args
):
660 """Store positional arguments as runtime settings."""
661 values
._source
, values
._destination
= self
.check_args(args
)
662 make_paths_absolute(values
.__dict
__, self
.relative_path_settings
)
663 values
._config
_files
= self
.config_files
666 def check_args(self
, args
):
667 source
= destination
= None
670 if source
== '-': # means stdin
673 destination
= args
.pop(0)
674 if destination
== '-': # means stdout
677 self
.error('Maximum 2 arguments allowed.')
678 if source
and source
== destination
:
679 self
.error('Do not specify the same file for both source and '
680 'destination. It will clobber the source file.')
681 return source
, destination
683 def set_defaults_from_dict(self
, defaults
):
684 self
.defaults
.update(defaults
)
686 def get_default_values(self
):
687 """Needed to get custom `Values` instances."""
688 defaults
= Values(self
.defaults
)
689 defaults
._config
_files
= self
.config_files
692 def get_option_by_dest(self
, dest
):
694 Get an option by its dest.
696 If you're supplying a dest which is shared by several options,
697 it is undefined which option of those is returned.
699 A KeyError is raised if there is no option with the supplied
702 for group
in self
.option_groups
+ [self
]:
703 for option
in group
.option_list
:
704 if option
.dest
== dest
:
706 raise KeyError('No option with dest == %r.' % dest
)
709 class ConfigParser(CP
.RawConfigParser
):
712 'pep_stylesheet': ('pep_html writer', 'stylesheet'),
713 'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
714 'pep_template': ('pep_html writer', 'template')}
715 """{old setting: (new section, new setting)} mapping, used by
716 `handle_old_config`, to convert settings from the old [options] section."""
719 The "[option]" section is deprecated. Support for old-format configuration
720 files may be removed in a future Docutils release. Please revise your
721 configuration files. See <http://docutils.sf.net/docs/user/config.html>,
722 section "Old-Format Configuration Files".
725 not_utf8_error
= """\
726 Unable to read configuration file "%s": content not encoded as UTF-8.
727 Skipping "%s" configuration file.
730 def __init__(self
, *args
, **kwargs
):
731 CP
.RawConfigParser
.__init
__(self
, *args
, **kwargs
)
734 """List of paths of configuration files read."""
736 self
._stderr
= ErrorOutput()
737 """Wrapper around sys.stderr catching en-/decoding errors"""
739 def read(self
, filenames
, option_parser
):
740 if type(filenames
) in (str, unicode):
741 filenames
= [filenames
]
742 for filename
in filenames
:
744 # Config files must be UTF-8-encoded:
745 fp
= codecs
.open(filename
, 'r', 'utf-8')
749 if sys
.version_info
< (3,2):
750 CP
.RawConfigParser
.readfp(self
, fp
, filename
)
752 CP
.RawConfigParser
.read_file(self
, fp
, filename
)
753 except UnicodeDecodeError:
754 self
._stderr
.write(self
.not_utf8_error
% (filename
, filename
))
758 self
._files
.append(filename
)
759 if self
.has_section('options'):
760 self
.handle_old_config(filename
)
761 self
.validate_settings(filename
, option_parser
)
763 def handle_old_config(self
, filename
):
764 warnings
.warn_explicit(self
.old_warning
, ConfigDeprecationWarning
,
766 options
= self
.get_section('options')
767 if not self
.has_section('general'):
768 self
.add_section('general')
769 for key
, value
in options
.items():
770 if key
in self
.old_settings
:
771 section
, setting
= self
.old_settings
[key
]
772 if not self
.has_section(section
):
773 self
.add_section(section
)
777 if not self
.has_option(section
, setting
):
778 self
.set(section
, setting
, value
)
779 self
.remove_section('options')
781 def validate_settings(self
, filename
, option_parser
):
783 Call the validator function and implement overrides on all applicable
786 for section
in self
.sections():
787 for setting
in self
.options(section
):
789 option
= option_parser
.get_option_by_dest(setting
)
793 value
= self
.get(section
, setting
)
795 new_value
= option
.validator(
796 setting
, value
, option_parser
,
797 config_parser
=self
, config_section
=section
)
798 except Exception, error
:
800 'Error in config file "%s", section "[%s]":\n'
803 % (filename
, section
, ErrorString(error
),
804 setting
, value
)), None, sys
.exc_info()[2])
805 self
.set(section
, setting
, new_value
)
807 self
.set(section
, option
.overrides
, None)
809 def optionxform(self
, optionstr
):
811 Transform '-' to '_' so the cmdline form of option names can be used.
813 return optionstr
.lower().replace('-', '_')
815 def get_section(self
, section
):
817 Return a given section as a dictionary (empty if the section
821 if self
.has_section(section
):
822 for option
in self
.options(section
):
823 section_dict
[option
] = self
.get(section
, option
)
827 class ConfigDeprecationWarning(DeprecationWarning):
828 """Warning for deprecated configuration file features."""