/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/option.py

[merge] bzr.dev 2255

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006 by Canonical Ltd
 
1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
# TODO: For things like --diff-prefix, we want a way to customize the display
18
18
# of the option argument.
19
19
 
 
20
import re
 
21
 
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
20
24
import optparse
21
 
import re
22
25
 
 
26
from bzrlib import (
 
27
    errors,
 
28
    revisionspec,
 
29
    symbol_versioning,
 
30
    )
 
31
""")
23
32
from bzrlib.trace import warning
24
 
from bzrlib.revisionspec import RevisionSpec
25
 
from bzrlib.errors import BzrCommandError
26
33
 
27
34
 
28
35
def _parse_revision_str(revstr):
80
87
    """
81
88
    # TODO: Maybe move this into revisionspec.py
82
89
    revs = []
 
90
    # split on the first .. that is not followed by a / ?
83
91
    sep = re.compile("\\.\\.(?!/)")
84
92
    for x in sep.split(revstr):
85
 
        revs.append(RevisionSpec.from_string(x or None))
 
93
        revs.append(revisionspec.RevisionSpec.from_string(x or None))
86
94
    return revs
87
95
 
88
96
 
100
108
        type_list = '\n'.join(lines)
101
109
        msg = "No known merge type %s. Supported types are:\n%s" %\
102
110
            (typestring, type_list)
103
 
        raise BzrCommandError(msg)
 
111
        raise errors.BzrCommandError(msg)
 
112
 
104
113
 
105
114
class Option(object):
106
 
    """Description of a command line option"""
 
115
    """Description of a command line option
 
116
    
 
117
    :ivar _short_name: If this option has a single-letter name, this is it.
 
118
    Otherwise None.
 
119
    """
 
120
 
107
121
    # TODO: Some way to show in help a description of the option argument
108
122
 
109
123
    OPTIONS = {}
110
 
    SHORT_OPTIONS = {}
111
124
 
112
 
    def __init__(self, name, help='', type=None, argname=None):
 
125
    def __init__(self, name, help='', type=None, argname=None,
 
126
                 short_name=None):
113
127
        """Make a new command option.
114
128
 
115
129
        name -- regular name of the command, used in the double-dash
123
137
 
124
138
        argname -- name of option argument, if any
125
139
        """
126
 
        # TODO: perhaps a subclass that automatically does 
127
 
        # --option, --no-option for reversible booleans
128
140
        self.name = name
129
141
        self.help = help
130
142
        self.type = type
 
143
        self._short_name = short_name
131
144
        if type is None:
132
145
            assert argname is None
133
146
        elif argname is None:
135
148
        self.argname = argname
136
149
 
137
150
    def short_name(self):
138
 
        """Return the single character option for this command, if any.
 
151
        if self._short_name:
 
152
            return self._short_name
 
153
        else:
 
154
            # remove this when SHORT_OPTIONS is removed
 
155
            # XXX: This is accessing a DeprecatedDict, so we call the super 
 
156
            # method to avoid warnings
 
157
            for (k, v) in dict.iteritems(Option.SHORT_OPTIONS):
 
158
                if v == self:
 
159
                    return k
139
160
 
140
 
        Short options are globally registered.
141
 
        """
142
 
        for short, option in Option.SHORT_OPTIONS.iteritems():
143
 
            if option is self:
144
 
                return short
 
161
    def set_short_name(self, short_name):
 
162
        self._short_name = short_name
145
163
 
146
164
    def get_negation_name(self):
147
165
        if self.name.startswith('no-'):
185
203
        yield self.name, self.short_name(), argname, self.help
186
204
 
187
205
 
 
206
class RegistryOption(Option):
 
207
    """Option based on a registry
 
208
 
 
209
    The values for the options correspond to entries in the registry.  Input
 
210
    must be a registry key.  After validation, it is converted into an object
 
211
    using Registry.get or a caller-provided converter.
 
212
    """
 
213
 
 
214
    def validate_value(self, value):
 
215
        """Validate a value name"""
 
216
        if value not in self.registry:
 
217
            raise errors.BadOptionValue(self.name, value)
 
218
 
 
219
    def convert(self, value):
 
220
        """Convert a value name into an output type"""
 
221
        self.validate_value(value)
 
222
        if self.converter is None:
 
223
            return self.registry.get(value)
 
224
        else:
 
225
            return self.converter(value)
 
226
 
 
227
    def __init__(self, name, help, registry, converter=None,
 
228
        value_switches=False):
 
229
        """
 
230
        Constructor.
 
231
 
 
232
        :param name: The option name.
 
233
        :param help: Help for the option.
 
234
        :param registry: A Registry containing the values
 
235
        :param converter: Callable to invoke with the value name to produce
 
236
            the value.  If not supplied, self.registry.get is used.
 
237
        :param value_switches: If true, each possible value is assigned its
 
238
            own switch.  For example, instead of '--format metaweave',
 
239
            '--metaweave' can be used interchangeably.
 
240
        """
 
241
        Option.__init__(self, name, help, type=self.convert)
 
242
        self.registry = registry
 
243
        self.name = name
 
244
        self.converter = converter
 
245
        self.value_switches = value_switches
 
246
 
 
247
    def add_option(self, parser, short_name):
 
248
        """Add this option to an Optparse parser"""
 
249
        Option.add_option(self, parser, short_name)
 
250
        if self.value_switches:
 
251
            for key in self.registry.keys():
 
252
                option_strings = ['--%s' % key]
 
253
                parser.add_option(action='callback',
 
254
                              callback=self._optparse_value_callback(key),
 
255
                                  help=self.registry.get_help(key),
 
256
                                  *option_strings)
 
257
 
 
258
    def _optparse_value_callback(self, cb_value):
 
259
        def cb(option, opt, value, parser):
 
260
            setattr(parser.values, self.name, self.type(cb_value))
 
261
        return cb
 
262
 
 
263
    def iter_switches(self):
 
264
        """Iterate through the list of switches provided by the option
 
265
 
 
266
        :return: an iterator of (name, short_name, argname, help)
 
267
        """
 
268
        for value in Option.iter_switches(self):
 
269
            yield value
 
270
        if self.value_switches:
 
271
            for key in sorted(self.registry.keys()):
 
272
                yield key, None, None, self.registry.get_help(key)
 
273
 
 
274
 
188
275
class OptionParser(optparse.OptionParser):
189
276
    """OptionParser that raises exceptions instead of exiting"""
190
277
 
191
278
    DEFAULT_VALUE = object()
192
279
 
193
280
    def error(self, message):
194
 
        raise BzrCommandError(message)
 
281
        raise errors.BzrCommandError(message)
195
282
 
196
283
 
197
284
def get_optparser(options):
199
286
 
200
287
    parser = OptionParser()
201
288
    parser.remove_option('--help')
202
 
    short_options = dict((k.name, v) for v, k in 
203
 
                         Option.SHORT_OPTIONS.iteritems())
204
289
    for option in options.itervalues():
205
 
        option.add_option(parser, short_options.get(option.name))
 
290
        option.add_option(parser, option.short_name())
206
291
    return parser
207
292
 
208
293
 
217
302
_global_option('bound')
218
303
_global_option('diff-options', type=str)
219
304
_global_option('help',
220
 
               help='show help message')
221
 
_global_option('file', type=unicode)
 
305
               help='show help message',
 
306
               short_name='h')
 
307
_global_option('file', type=unicode, short_name='F')
222
308
_global_option('force')
223
309
_global_option('format', type=unicode)
224
310
_global_option('forward')
225
 
_global_option('message', type=unicode)
 
311
_global_option('message', type=unicode,
 
312
               short_name='m')
226
313
_global_option('no-recurse')
227
 
_global_option('prefix', type=str, 
228
 
               help='Set prefixes to added to old and new filenames, as '
229
 
                    'two values separated by a colon.')
230
314
_global_option('profile',
231
315
               help='show performance profiling information')
232
 
_global_option('revision', type=_parse_revision_str)
 
316
_global_option('revision',
 
317
               type=_parse_revision_str,
 
318
               short_name='r',
 
319
               help='See \'help revisionspec\' for details')
233
320
_global_option('show-ids', 
234
321
               help='show internal object ids')
235
322
_global_option('timezone', 
237
324
               help='display timezone as local, original, or utc')
238
325
_global_option('unbound')
239
326
_global_option('verbose',
240
 
               help='display more information')
 
327
               help='display more information',
 
328
               short_name='v')
241
329
_global_option('version')
242
330
_global_option('email')
243
331
_global_option('update')
244
332
_global_option('log-format', type=str, help="Use this log format")
245
 
_global_option('long', help='Use detailed log format. Same as --log-format long')
 
333
_global_option('long', help='Use detailed log format. Same as --log-format long',
 
334
               short_name='l')
246
335
_global_option('short', help='Use moderately short log format. Same as --log-format short')
247
336
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
248
337
_global_option('root', type=str)
250
339
_global_option('merge-type', type=_parse_merge_type, 
251
340
               help='Select a particular merge algorithm')
252
341
_global_option('pattern', type=str)
253
 
_global_option('quiet')
 
342
_global_option('quiet', short_name='q')
254
343
_global_option('remember', help='Remember the specified location as a'
255
344
               ' default.')
256
345
_global_option('reprocess', help='Reprocess to reduce spurious conflicts')
257
346
_global_option('kind', type=str)
258
347
_global_option('dry-run',
259
348
               help="show what would be done, but don't actually do anything")
260
 
 
261
 
 
262
 
def _global_short(short_name, long_name):
263
 
    assert short_name not in Option.SHORT_OPTIONS
264
 
    Option.SHORT_OPTIONS[short_name] = Option.OPTIONS[long_name]
265
 
    
266
 
 
267
 
Option.SHORT_OPTIONS['F'] = Option.OPTIONS['file']
268
 
Option.SHORT_OPTIONS['h'] = Option.OPTIONS['help']
269
 
Option.SHORT_OPTIONS['m'] = Option.OPTIONS['message']
270
 
Option.SHORT_OPTIONS['r'] = Option.OPTIONS['revision']
271
 
Option.SHORT_OPTIONS['v'] = Option.OPTIONS['verbose']
272
 
Option.SHORT_OPTIONS['l'] = Option.OPTIONS['long']
273
 
Option.SHORT_OPTIONS['q'] = Option.OPTIONS['quiet']
274
 
Option.SHORT_OPTIONS['p'] = Option.OPTIONS['prefix']
 
349
_global_option('name-from-revision', help='The path name in the old tree.')
 
350
 
 
351
 
 
352
# prior to 0.14 these were always globally registered; the old dict is
 
353
# available for plugins that use it but it should not be used.
 
354
Option.SHORT_OPTIONS = symbol_versioning.DeprecatedDict(
 
355
    symbol_versioning.zero_fourteen,
 
356
    'SHORT_OPTIONS',
 
357
    {
 
358
        'F': Option.OPTIONS['file'],
 
359
        'h': Option.OPTIONS['help'],
 
360
        'm': Option.OPTIONS['message'],
 
361
        'r': Option.OPTIONS['revision'],
 
362
        'v': Option.OPTIONS['verbose'],
 
363
        'l': Option.OPTIONS['long'],
 
364
        'q': Option.OPTIONS['quiet'],
 
365
    },
 
366
    'Set the short option name when constructing the Option.',
 
367
    )