~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/option.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-04-17 08:04:15 UTC
  • mfrom: (2423.1.2 benchmarks)
  • Revision ID: pqm@pqm.ubuntu.com-20070417080415-5vn25svmf95ki88z
Also clear SmartTCPServer hooks from TestCase._clear_hooks

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
19
19
 
20
20
import re
21
21
 
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
import optparse
 
25
 
 
26
from bzrlib import (
 
27
    errors,
 
28
    log,
 
29
    registry,
 
30
    revisionspec,
 
31
    symbol_versioning,
 
32
    )
 
33
""")
22
34
from bzrlib.trace import warning
23
 
from bzrlib.revisionspec import RevisionSpec
24
 
from bzrlib.errors import BzrCommandError
25
35
 
26
36
 
27
37
def _parse_revision_str(revstr):
31
41
    each revision specifier supplied.
32
42
 
33
43
    >>> _parse_revision_str('234')
34
 
    [<RevisionSpec_int 234>]
 
44
    [<RevisionSpec_revno 234>]
35
45
    >>> _parse_revision_str('234..567')
36
 
    [<RevisionSpec_int 234>, <RevisionSpec_int 567>]
 
46
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
37
47
    >>> _parse_revision_str('..')
38
48
    [<RevisionSpec None>, <RevisionSpec None>]
39
49
    >>> _parse_revision_str('..234')
40
 
    [<RevisionSpec None>, <RevisionSpec_int 234>]
 
50
    [<RevisionSpec None>, <RevisionSpec_revno 234>]
41
51
    >>> _parse_revision_str('234..')
42
 
    [<RevisionSpec_int 234>, <RevisionSpec None>]
 
52
    [<RevisionSpec_revno 234>, <RevisionSpec None>]
43
53
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
44
 
    [<RevisionSpec_int 234>, <RevisionSpec_int 456>, <RevisionSpec_int 789>]
 
54
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
45
55
    >>> _parse_revision_str('234....789') #Error ?
46
 
    [<RevisionSpec_int 234>, <RevisionSpec None>, <RevisionSpec_int 789>]
 
56
    [<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
47
57
    >>> _parse_revision_str('revid:test@other.com-234234')
48
58
    [<RevisionSpec_revid revid:test@other.com-234234>]
49
59
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
50
60
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
51
61
    >>> _parse_revision_str('revid:test@other.com-234234..23')
52
 
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_int 23>]
 
62
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
53
63
    >>> _parse_revision_str('date:2005-04-12')
54
64
    [<RevisionSpec_date date:2005-04-12>]
55
65
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
59
69
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
60
70
    [<RevisionSpec_date date:2005-04-12,12:24:33>]
61
71
    >>> _parse_revision_str('-5..23')
62
 
    [<RevisionSpec_int -5>, <RevisionSpec_int 23>]
 
72
    [<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
63
73
    >>> _parse_revision_str('-5')
64
 
    [<RevisionSpec_int -5>]
 
74
    [<RevisionSpec_revno -5>]
65
75
    >>> _parse_revision_str('123a')
66
76
    Traceback (most recent call last):
67
77
      ...
68
 
    BzrError: No namespace registered for string: '123a'
 
78
    NoSuchRevisionSpec: No namespace registered for string: '123a'
69
79
    >>> _parse_revision_str('abc')
70
80
    Traceback (most recent call last):
71
81
      ...
72
 
    BzrError: No namespace registered for string: 'abc'
 
82
    NoSuchRevisionSpec: No namespace registered for string: 'abc'
73
83
    >>> _parse_revision_str('branch:../branch2')
74
84
    [<RevisionSpec_branch branch:../branch2>]
75
85
    >>> _parse_revision_str('branch:../../branch2')
76
86
    [<RevisionSpec_branch branch:../../branch2>]
77
87
    >>> _parse_revision_str('branch:../../branch2..23')
78
 
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_int 23>]
 
88
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 23>]
79
89
    """
80
90
    # TODO: Maybe move this into revisionspec.py
81
 
    old_format_re = re.compile('\d*:\d*')
82
 
    m = old_format_re.match(revstr)
83
91
    revs = []
84
 
    if m:
85
 
        warning('Colon separator for revision numbers is deprecated.'
86
 
                ' Use .. instead')
87
 
        for rev in revstr.split(':'):
88
 
            if rev:
89
 
                revs.append(RevisionSpec(int(rev)))
90
 
            else:
91
 
                revs.append(RevisionSpec(None))
92
 
    else:
93
 
        sep = re.compile("\\.\\.(?!/)")
94
 
        for x in sep.split(revstr):
95
 
            revs.append(RevisionSpec(x or None))
 
92
    # split on the first .. that is not followed by a / ?
 
93
    sep = re.compile("\\.\\.(?!/)")
 
94
    for x in sep.split(revstr):
 
95
        revs.append(revisionspec.RevisionSpec.from_string(x or None))
96
96
    return revs
97
97
 
98
98
 
110
110
        type_list = '\n'.join(lines)
111
111
        msg = "No known merge type %s. Supported types are:\n%s" %\
112
112
            (typestring, type_list)
113
 
        raise BzrCommandError(msg)
 
113
        raise errors.BzrCommandError(msg)
 
114
 
114
115
 
115
116
class Option(object):
116
 
    """Description of a command line option"""
 
117
    """Description of a command line option
 
118
    
 
119
    :ivar _short_name: If this option has a single-letter name, this is it.
 
120
    Otherwise None.
 
121
    """
 
122
 
117
123
    # TODO: Some way to show in help a description of the option argument
118
124
 
119
125
    OPTIONS = {}
120
 
    SHORT_OPTIONS = {}
121
126
 
122
 
    def __init__(self, name, help='', type=None, argname=None):
 
127
    def __init__(self, name, help='', type=None, argname=None,
 
128
                 short_name=None):
123
129
        """Make a new command option.
124
130
 
125
131
        name -- regular name of the command, used in the double-dash
133
139
 
134
140
        argname -- name of option argument, if any
135
141
        """
136
 
        # TODO: perhaps a subclass that automatically does 
137
 
        # --option, --no-option for reversible booleans
138
142
        self.name = name
139
143
        self.help = help
140
144
        self.type = type
 
145
        self._short_name = short_name
141
146
        if type is None:
142
147
            assert argname is None
143
148
        elif argname is None:
145
150
        self.argname = argname
146
151
 
147
152
    def short_name(self):
148
 
        """Return the single character option for this command, if any.
149
 
 
150
 
        Short options are globally registered.
151
 
        """
152
 
        for short, option in Option.SHORT_OPTIONS.iteritems():
153
 
            if option is self:
154
 
                return short
 
153
        if self._short_name:
 
154
            return self._short_name
 
155
        else:
 
156
            # remove this when SHORT_OPTIONS is removed
 
157
            # XXX: This is accessing a DeprecatedDict, so we call the super 
 
158
            # method to avoid warnings
 
159
            for (k, v) in dict.iteritems(Option.SHORT_OPTIONS):
 
160
                if v == self:
 
161
                    return k
 
162
 
 
163
    def set_short_name(self, short_name):
 
164
        self._short_name = short_name
 
165
 
 
166
    def get_negation_name(self):
 
167
        if self.name.startswith('no-'):
 
168
            return self.name[3:]
 
169
        else:
 
170
            return 'no-' + self.name
 
171
 
 
172
    def add_option(self, parser, short_name):
 
173
        """Add this option to an Optparse parser"""
 
174
        option_strings = ['--%s' % self.name]
 
175
        if short_name is not None:
 
176
            option_strings.append('-%s' % short_name)
 
177
        optargfn = self.type
 
178
        if optargfn is None:
 
179
            parser.add_option(action='store_true', dest=self.name, 
 
180
                              help=self.help,
 
181
                              default=OptionParser.DEFAULT_VALUE,
 
182
                              *option_strings)
 
183
            negation_strings = ['--%s' % self.get_negation_name()]
 
184
            parser.add_option(action='store_false', dest=self.name, 
 
185
                              help=optparse.SUPPRESS_HELP, *negation_strings)
 
186
        else:
 
187
            parser.add_option(action='callback', 
 
188
                              callback=self._optparse_callback, 
 
189
                              type='string', metavar=self.argname.upper(),
 
190
                              help=self.help,
 
191
                              default=OptionParser.DEFAULT_VALUE, 
 
192
                              *option_strings)
 
193
 
 
194
    def _optparse_callback(self, option, opt, value, parser):
 
195
        setattr(parser.values, self.name, self.type(value))
 
196
 
 
197
    def iter_switches(self):
 
198
        """Iterate through the list of switches provided by the option
 
199
        
 
200
        :return: an iterator of (name, short_name, argname, help)
 
201
        """
 
202
        argname =  self.argname
 
203
        if argname is not None:
 
204
            argname = argname.upper()
 
205
        yield self.name, self.short_name(), argname, self.help
 
206
 
 
207
 
 
208
class RegistryOption(Option):
 
209
    """Option based on a registry
 
210
 
 
211
    The values for the options correspond to entries in the registry.  Input
 
212
    must be a registry key.  After validation, it is converted into an object
 
213
    using Registry.get or a caller-provided converter.
 
214
    """
 
215
 
 
216
    def validate_value(self, value):
 
217
        """Validate a value name"""
 
218
        if value not in self.registry:
 
219
            raise errors.BadOptionValue(self.name, value)
 
220
 
 
221
    def convert(self, value):
 
222
        """Convert a value name into an output type"""
 
223
        self.validate_value(value)
 
224
        if self.converter is None:
 
225
            return self.registry.get(value)
 
226
        else:
 
227
            return self.converter(value)
 
228
 
 
229
    def __init__(self, name, help, registry, converter=None,
 
230
        value_switches=False, title=None, enum_switch=True):
 
231
        """
 
232
        Constructor.
 
233
 
 
234
        :param name: The option name.
 
235
        :param help: Help for the option.
 
236
        :param registry: A Registry containing the values
 
237
        :param converter: Callable to invoke with the value name to produce
 
238
            the value.  If not supplied, self.registry.get is used.
 
239
        :param value_switches: If true, each possible value is assigned its
 
240
            own switch.  For example, instead of '--format knit',
 
241
            '--knit' can be used interchangeably.
 
242
        :param enum_switch: If true, a switch is provided with the option name,
 
243
            which takes a value.
 
244
        """
 
245
        Option.__init__(self, name, help, type=self.convert)
 
246
        self.registry = registry
 
247
        self.name = name
 
248
        self.converter = converter
 
249
        self.value_switches = value_switches
 
250
        self.enum_switch = enum_switch
 
251
        self.title = title
 
252
        if self.title is None:
 
253
            self.title = name
 
254
 
 
255
    @staticmethod
 
256
    def from_kwargs(name_, help=None, title=None, value_switches=False,
 
257
                    enum_switch=True, **kwargs):
 
258
        """Convenience method to generate string-map registry options
 
259
 
 
260
        name, help, value_switches and enum_switch are passed to the
 
261
        RegistryOption constructor.  Any other keyword arguments are treated
 
262
        as values for the option, and they value is treated as the help.
 
263
        """
 
264
        reg = registry.Registry()
 
265
        for name, help in kwargs.iteritems():
 
266
            name = name.replace('_', '-')
 
267
            reg.register(name, name, help=help)
 
268
        return RegistryOption(name_, help, reg, title=title,
 
269
            value_switches=value_switches, enum_switch=enum_switch)
 
270
 
 
271
    def add_option(self, parser, short_name):
 
272
        """Add this option to an Optparse parser"""
 
273
        if self.value_switches:
 
274
            parser = parser.add_option_group(self.title)
 
275
        if self.enum_switch:
 
276
            Option.add_option(self, parser, short_name)
 
277
        if self.value_switches:
 
278
            for key in self.registry.keys():
 
279
                option_strings = ['--%s' % key]
 
280
                if getattr(self.registry.get_info(key), 'hidden', False):
 
281
                    help = optparse.SUPPRESS_HELP
 
282
                else:
 
283
                    help = self.registry.get_help(key)
 
284
                parser.add_option(action='callback',
 
285
                              callback=self._optparse_value_callback(key),
 
286
                                  help=help,
 
287
                                  *option_strings)
 
288
 
 
289
    def _optparse_value_callback(self, cb_value):
 
290
        def cb(option, opt, value, parser):
 
291
            setattr(parser.values, self.name, self.type(cb_value))
 
292
        return cb
 
293
 
 
294
    def iter_switches(self):
 
295
        """Iterate through the list of switches provided by the option
 
296
 
 
297
        :return: an iterator of (name, short_name, argname, help)
 
298
        """
 
299
        for value in Option.iter_switches(self):
 
300
            yield value
 
301
        if self.value_switches:
 
302
            for key in sorted(self.registry.keys()):
 
303
                yield key, None, None, self.registry.get_help(key)
 
304
 
 
305
 
 
306
class OptionParser(optparse.OptionParser):
 
307
    """OptionParser that raises exceptions instead of exiting"""
 
308
 
 
309
    DEFAULT_VALUE = object()
 
310
 
 
311
    def error(self, message):
 
312
        raise errors.BzrCommandError(message)
 
313
 
 
314
 
 
315
def get_optparser(options):
 
316
    """Generate an optparse parser for bzrlib-style options"""
 
317
 
 
318
    parser = OptionParser()
 
319
    parser.remove_option('--help')
 
320
    for option in options.itervalues():
 
321
        option.add_option(parser, option.short_name())
 
322
    return parser
155
323
 
156
324
 
157
325
def _global_option(name, **kwargs):
158
326
    """Register o as a global option."""
159
327
    Option.OPTIONS[name] = Option(name, **kwargs)
160
328
 
 
329
 
 
330
def _global_registry_option(name, help, registry, **kwargs):
 
331
    Option.OPTIONS[name] = RegistryOption(name, help, registry, **kwargs)
 
332
 
 
333
 
 
334
class MergeTypeRegistry(registry.Registry):
 
335
 
 
336
    pass
 
337
 
 
338
 
 
339
_merge_type_registry = MergeTypeRegistry()
 
340
_merge_type_registry.register_lazy('merge3', 'bzrlib.merge', 'Merge3Merger',
 
341
                                   "Native diff3-style merge")
 
342
_merge_type_registry.register_lazy('diff3', 'bzrlib.merge', 'Diff3Merger',
 
343
                                   "Merge using external diff3")
 
344
_merge_type_registry.register_lazy('weave', 'bzrlib.merge', 'WeaveMerger',
 
345
                                   "Weave-based merge")
 
346
 
161
347
_global_option('all')
162
348
_global_option('overwrite', help='Ignore differences between branches and '
163
349
               'overwrite unconditionally')
165
351
_global_option('bound')
166
352
_global_option('diff-options', type=str)
167
353
_global_option('help',
168
 
               help='show help message')
169
 
_global_option('file', type=unicode)
 
354
               help='show help message',
 
355
               short_name='h')
 
356
_global_option('file', type=unicode, short_name='F')
170
357
_global_option('force')
171
358
_global_option('format', type=unicode)
172
359
_global_option('forward')
173
 
_global_option('message', type=unicode)
 
360
_global_option('message', type=unicode,
 
361
               short_name='m')
174
362
_global_option('no-recurse')
175
 
_global_option('prefix', type=str, 
176
 
               help='Set prefixes to added to old and new filenames, as '
177
 
                    'two values separated by a colon.')
178
363
_global_option('profile',
179
364
               help='show performance profiling information')
180
 
_global_option('revision', type=_parse_revision_str)
 
365
_global_option('revision',
 
366
               type=_parse_revision_str,
 
367
               short_name='r',
 
368
               help='See \'help revisionspec\' for details')
181
369
_global_option('show-ids', 
182
370
               help='show internal object ids')
183
371
_global_option('timezone', 
185
373
               help='display timezone as local, original, or utc')
186
374
_global_option('unbound')
187
375
_global_option('verbose',
188
 
               help='display more information')
 
376
               help='display more information',
 
377
               short_name='v')
189
378
_global_option('version')
190
379
_global_option('email')
191
380
_global_option('update')
192
 
_global_option('log-format', type=str, help="Use this log format")
193
 
_global_option('long', help='Use detailed log format. Same as --log-format long')
 
381
_global_registry_option('log-format', "Use this log format",
 
382
                        log.log_formatter_registry, value_switches=True,
 
383
                        title='Log format')
 
384
_global_option('long', help='Use detailed log format. Same as --log-format long',
 
385
               short_name='l')
194
386
_global_option('short', help='Use moderately short log format. Same as --log-format short')
195
387
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
196
388
_global_option('root', type=str)
197
389
_global_option('no-backup')
198
 
_global_option('merge-type', type=_parse_merge_type, 
199
 
               help='Select a particular merge algorithm')
 
390
_global_registry_option('merge-type', 'Select a particular merge algorithm',
 
391
                        _merge_type_registry, value_switches=True,
 
392
                        title='Merge algorithm')
200
393
_global_option('pattern', type=str)
201
 
_global_option('quiet')
 
394
_global_option('quiet', short_name='q')
202
395
_global_option('remember', help='Remember the specified location as a'
203
396
               ' default.')
204
397
_global_option('reprocess', help='Reprocess to reduce spurious conflicts')
205
398
_global_option('kind', type=str)
206
399
_global_option('dry-run',
207
400
               help="show what would be done, but don't actually do anything")
208
 
 
209
 
 
210
 
def _global_short(short_name, long_name):
211
 
    assert short_name not in Option.SHORT_OPTIONS
212
 
    Option.SHORT_OPTIONS[short_name] = Option.OPTIONS[long_name]
213
 
    
214
 
 
215
 
Option.SHORT_OPTIONS['F'] = Option.OPTIONS['file']
216
 
Option.SHORT_OPTIONS['h'] = Option.OPTIONS['help']
217
 
Option.SHORT_OPTIONS['m'] = Option.OPTIONS['message']
218
 
Option.SHORT_OPTIONS['r'] = Option.OPTIONS['revision']
219
 
Option.SHORT_OPTIONS['v'] = Option.OPTIONS['verbose']
220
 
Option.SHORT_OPTIONS['l'] = Option.OPTIONS['long']
221
 
Option.SHORT_OPTIONS['q'] = Option.OPTIONS['quiet']
222
 
Option.SHORT_OPTIONS['p'] = Option.OPTIONS['prefix']
 
401
_global_option('name-from-revision', help='The path name in the old tree.')
 
402
 
 
403
 
 
404
# prior to 0.14 these were always globally registered; the old dict is
 
405
# available for plugins that use it but it should not be used.
 
406
Option.SHORT_OPTIONS = symbol_versioning.DeprecatedDict(
 
407
    symbol_versioning.zero_fourteen,
 
408
    'SHORT_OPTIONS',
 
409
    {
 
410
        'F': Option.OPTIONS['file'],
 
411
        'h': Option.OPTIONS['help'],
 
412
        'm': Option.OPTIONS['message'],
 
413
        'r': Option.OPTIONS['revision'],
 
414
        'v': Option.OPTIONS['verbose'],
 
415
        'l': Option.OPTIONS['long'],
 
416
        'q': Option.OPTIONS['quiet'],
 
417
    },
 
418
    'Set the short option name when constructing the Option.',
 
419
    )