root/galaxy-central/eggs/docutils-0.4-py2.6.egg/docutils/frontend.py

リビジョン 3, 31.3 KB (コミッタ: kohda, 14 年 前)

Install Unix tools  http://hannonlab.cshl.edu/galaxy_unix_tools/galaxy.html

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