/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

  • Committer: Andrew Bennetts
  • Date: 2008-02-18 08:30:38 UTC
  • mto: This revision was merged to the branch mainline in revision 3756.
  • Revision ID: andrew.bennetts@canonical.com-20080218083038-tts55zsx5xrz3l2e
Lots of assorted hackery to reduce the number of imports for common operations.  Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
# TODO: For things like --diff-prefix, we want a way to customize the display
 
18
# of the option argument.
 
19
 
 
20
import re
 
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 as _mod_registry,
 
30
    revisionspec,
 
31
    symbol_versioning,
 
32
    )
 
33
""")
 
34
from bzrlib.trace import warning
 
35
 
 
36
 
 
37
def _parse_revision_str(revstr):
 
38
    """This handles a revision string -> revno.
 
39
 
 
40
    This always returns a list.  The list will have one element for
 
41
    each revision specifier supplied.
 
42
 
 
43
    >>> _parse_revision_str('234')
 
44
    [<RevisionSpec_revno 234>]
 
45
    >>> _parse_revision_str('234..567')
 
46
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
 
47
    >>> _parse_revision_str('..')
 
48
    [<RevisionSpec None>, <RevisionSpec None>]
 
49
    >>> _parse_revision_str('..234')
 
50
    [<RevisionSpec None>, <RevisionSpec_revno 234>]
 
51
    >>> _parse_revision_str('234..')
 
52
    [<RevisionSpec_revno 234>, <RevisionSpec None>]
 
53
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
54
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
 
55
    >>> _parse_revision_str('234....789') #Error ?
 
56
    [<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
 
57
    >>> _parse_revision_str('revid:test@other.com-234234')
 
58
    [<RevisionSpec_revid revid:test@other.com-234234>]
 
59
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
60
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
 
61
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
62
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
 
63
    >>> _parse_revision_str('date:2005-04-12')
 
64
    [<RevisionSpec_date date:2005-04-12>]
 
65
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
66
    [<RevisionSpec_date date:2005-04-12 12:24:33>]
 
67
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
68
    [<RevisionSpec_date date:2005-04-12T12:24:33>]
 
69
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
70
    [<RevisionSpec_date date:2005-04-12,12:24:33>]
 
71
    >>> _parse_revision_str('-5..23')
 
72
    [<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
 
73
    >>> _parse_revision_str('-5')
 
74
    [<RevisionSpec_revno -5>]
 
75
    >>> _parse_revision_str('123a')
 
76
    Traceback (most recent call last):
 
77
      ...
 
78
    NoSuchRevisionSpec: No namespace registered for string: '123a'
 
79
    >>> _parse_revision_str('abc')
 
80
    Traceback (most recent call last):
 
81
      ...
 
82
    NoSuchRevisionSpec: No namespace registered for string: 'abc'
 
83
    >>> _parse_revision_str('branch:../branch2')
 
84
    [<RevisionSpec_branch branch:../branch2>]
 
85
    >>> _parse_revision_str('branch:../../branch2')
 
86
    [<RevisionSpec_branch branch:../../branch2>]
 
87
    >>> _parse_revision_str('branch:../../branch2..23')
 
88
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 23>]
 
89
    >>> _parse_revision_str('branch:..\\\\branch2')
 
90
    [<RevisionSpec_branch branch:..\\branch2>]
 
91
    >>> _parse_revision_str('branch:..\\\\..\\\\branch2..23')
 
92
    [<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_revno 23>]
 
93
    """
 
94
    # TODO: Maybe move this into revisionspec.py
 
95
    revs = []
 
96
    # split on .. that is not followed by a / or \
 
97
    sep = re.compile(r'\.\.(?![\\/])')
 
98
    for x in sep.split(revstr):
 
99
        revs.append(revisionspec.RevisionSpec.from_string(x or None))
 
100
    return revs
 
101
 
 
102
 
 
103
def _parse_change_str(revstr):
 
104
    """Parse the revision string and return a tuple with left-most
 
105
    parent of the revision.
 
106
 
 
107
    >>> _parse_change_str('123')
 
108
    (<RevisionSpec_before before:123>, <RevisionSpec_revno 123>)
 
109
    >>> _parse_change_str('123..124')
 
110
    Traceback (most recent call last):
 
111
      ...
 
112
    RangeInChangeOption: Option --change does not accept revision ranges
 
113
    """
 
114
    revs = _parse_revision_str(revstr)
 
115
    if len(revs) > 1:
 
116
        raise errors.RangeInChangeOption()
 
117
    return (revisionspec.RevisionSpec.from_string('before:' + revstr),
 
118
            revs[0])
 
119
 
 
120
 
 
121
def _parse_merge_type(typestring):
 
122
    return get_merge_type(typestring)
 
123
 
 
124
def get_merge_type(typestring):
 
125
    """Attempt to find the merge class/factory associated with a string."""
 
126
    from merge import merge_types
 
127
    try:
 
128
        return merge_types[typestring][0]
 
129
    except KeyError:
 
130
        templ = '%s%%7s: %%s' % (' '*12)
 
131
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
132
        type_list = '\n'.join(lines)
 
133
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
134
            (typestring, type_list)
 
135
        raise errors.BzrCommandError(msg)
 
136
 
 
137
 
 
138
class Option(object):
 
139
    """Description of a command line option
 
140
    
 
141
    :ivar _short_name: If this option has a single-letter name, this is it.
 
142
    Otherwise None.
 
143
    """
 
144
 
 
145
    # The dictionary of standard options. These are always legal.
 
146
    STD_OPTIONS = {}
 
147
 
 
148
    # The dictionary of commonly used options. these are only legal
 
149
    # if a command explicitly references them by name in the list
 
150
    # of supported options.
 
151
    OPTIONS = {}
 
152
 
 
153
    def __init__(self, name, help='', type=None, argname=None,
 
154
                 short_name=None, param_name=None, custom_callback=None):
 
155
        """Make a new command option.
 
156
 
 
157
        :param name: regular name of the command, used in the double-dash
 
158
            form and also as the parameter to the command's run() 
 
159
            method (unless param_name is specified).
 
160
 
 
161
        :param help: help message displayed in command help
 
162
 
 
163
        :param type: function called to parse the option argument, or 
 
164
            None (default) if this option doesn't take an argument.
 
165
 
 
166
        :param argname: name of option argument, if any
 
167
 
 
168
        :param short_name: short option code for use with a single -, e.g.
 
169
            short_name="v" to enable parsing of -v.
 
170
 
 
171
        :param param_name: name of the parameter which will be passed to
 
172
            the command's run() method.
 
173
 
 
174
        :param custom_callback: a callback routine to be called after normal
 
175
            processing. The signature of the callback routine is
 
176
            (option, name, new_value, parser).
 
177
        """
 
178
        self.name = name
 
179
        self.help = help
 
180
        self.type = type
 
181
        self._short_name = short_name
 
182
        if type is None:
 
183
            assert argname is None
 
184
        elif argname is None:
 
185
            argname = 'ARG'
 
186
        self.argname = argname
 
187
        if param_name is None:
 
188
            self._param_name = self.name
 
189
        else:
 
190
            self._param_name = param_name
 
191
        self.custom_callback = custom_callback
 
192
 
 
193
    def short_name(self):
 
194
        if self._short_name:
 
195
            return self._short_name
 
196
 
 
197
    def set_short_name(self, short_name):
 
198
        self._short_name = short_name
 
199
 
 
200
    def get_negation_name(self):
 
201
        if self.name.startswith('no-'):
 
202
            return self.name[3:]
 
203
        else:
 
204
            return 'no-' + self.name
 
205
 
 
206
    def add_option(self, parser, short_name):
 
207
        """Add this option to an Optparse parser"""
 
208
        option_strings = ['--%s' % self.name]
 
209
        if short_name is not None:
 
210
            option_strings.append('-%s' % short_name)
 
211
        optargfn = self.type
 
212
        if optargfn is None:
 
213
            parser.add_option(action='callback', 
 
214
                              callback=self._optparse_bool_callback, 
 
215
                              callback_args=(True,),
 
216
                              help=self.help,
 
217
                              *option_strings)
 
218
            negation_strings = ['--%s' % self.get_negation_name()]
 
219
            parser.add_option(action='callback', 
 
220
                              callback=self._optparse_bool_callback, 
 
221
                              callback_args=(False,),
 
222
                              help=optparse.SUPPRESS_HELP, *negation_strings)
 
223
        else:
 
224
            parser.add_option(action='callback', 
 
225
                              callback=self._optparse_callback, 
 
226
                              type='string', metavar=self.argname.upper(),
 
227
                              help=self.help,
 
228
                              default=OptionParser.DEFAULT_VALUE, 
 
229
                              *option_strings)
 
230
 
 
231
    def _optparse_bool_callback(self, option, opt_str, value, parser, bool_v):
 
232
        setattr(parser.values, self._param_name, bool_v)
 
233
        if self.custom_callback is not None:
 
234
            self.custom_callback(option, self._param_name, bool_v, parser)
 
235
 
 
236
    def _optparse_callback(self, option, opt, value, parser):
 
237
        v = self.type(value)
 
238
        setattr(parser.values, self._param_name, v)
 
239
        if self.custom_callback is not None:
 
240
            self.custom_callback(option, self.name, v, parser)
 
241
 
 
242
    def iter_switches(self):
 
243
        """Iterate through the list of switches provided by the option
 
244
        
 
245
        :return: an iterator of (name, short_name, argname, help)
 
246
        """
 
247
        argname =  self.argname
 
248
        if argname is not None:
 
249
            argname = argname.upper()
 
250
        yield self.name, self.short_name(), argname, self.help
 
251
 
 
252
    def is_hidden(self, name):
 
253
        return False
 
254
 
 
255
 
 
256
class ListOption(Option):
 
257
    """Option used to provide a list of values.
 
258
 
 
259
    On the command line, arguments are specified by a repeated use of the
 
260
    option. '-' is a special argument that resets the list. For example,
 
261
      --foo=a --foo=b
 
262
    sets the value of the 'foo' option to ['a', 'b'], and
 
263
      --foo=a --foo=b --foo=- --foo=c
 
264
    sets the value of the 'foo' option to ['c'].
 
265
    """
 
266
 
 
267
    def add_option(self, parser, short_name):
 
268
        """Add this option to an Optparse parser."""
 
269
        option_strings = ['--%s' % self.name]
 
270
        if short_name is not None:
 
271
            option_strings.append('-%s' % short_name)
 
272
        parser.add_option(action='callback',
 
273
                          callback=self._optparse_callback,
 
274
                          type='string', metavar=self.argname.upper(),
 
275
                          help=self.help, default=[],
 
276
                          *option_strings)
 
277
 
 
278
    def _optparse_callback(self, option, opt, value, parser):
 
279
        values = getattr(parser.values, self._param_name)
 
280
        if value == '-':
 
281
            del values[:]
 
282
        else:
 
283
            values.append(self.type(value))
 
284
        if self.custom_callback is not None:
 
285
            self.custom_callback(option, self._param_name, values, parser)
 
286
 
 
287
 
 
288
class RegistryOption(Option):
 
289
    """Option based on a registry
 
290
 
 
291
    The values for the options correspond to entries in the registry.  Input
 
292
    must be a registry key.  After validation, it is converted into an object
 
293
    using Registry.get or a caller-provided converter.
 
294
    """
 
295
 
 
296
    def validate_value(self, value):
 
297
        """Validate a value name"""
 
298
        if value not in self.registry:
 
299
            raise errors.BadOptionValue(self.name, value)
 
300
 
 
301
    def convert(self, value):
 
302
        """Convert a value name into an output type"""
 
303
        self.validate_value(value)
 
304
        if self.converter is None:
 
305
            return self.registry.get(value)
 
306
        else:
 
307
            return self.converter(value)
 
308
 
 
309
    def __init__(self, name, help, registry=None, converter=None,
 
310
        value_switches=False, title=None, enum_switch=True,
 
311
        lazy_registry=None):
 
312
        """
 
313
        Constructor.
 
314
 
 
315
        :param name: The option name.
 
316
        :param help: Help for the option.
 
317
        :param registry: A Registry containing the values
 
318
        :param converter: Callable to invoke with the value name to produce
 
319
            the value.  If not supplied, self.registry.get is used.
 
320
        :param value_switches: If true, each possible value is assigned its
 
321
            own switch.  For example, instead of '--format knit',
 
322
            '--knit' can be used interchangeably.
 
323
        :param enum_switch: If true, a switch is provided with the option name,
 
324
            which takes a value.
 
325
        :param lazy_registry: A tuple of (module name, attribute name) for a
 
326
            registry to be lazily loaded.
 
327
        """
 
328
        Option.__init__(self, name, help, type=self.convert)
 
329
        self._registry = registry
 
330
        if registry is None:
 
331
            assert lazy_registry is not None, (
 
332
                'One of registry or lazy_registry must be given.')
 
333
            self._lazy_registry = _mod_registry._LazyObjectGetter(
 
334
                *lazy_registry)
 
335
        self.name = name
 
336
        self.converter = converter
 
337
        self.value_switches = value_switches
 
338
        self.enum_switch = enum_switch
 
339
        self.title = title
 
340
        if self.title is None:
 
341
            self.title = name
 
342
 
 
343
    @property
 
344
    def registry(self):
 
345
        if self._registry is not None:
 
346
            return self._registry
 
347
        else:
 
348
            return self._lazy_registry.get_obj()
 
349
    
 
350
    @staticmethod
 
351
    def from_kwargs(name_, help=None, title=None, value_switches=False,
 
352
                    enum_switch=True, **kwargs):
 
353
        """Convenience method to generate string-map registry options
 
354
 
 
355
        name, help, value_switches and enum_switch are passed to the
 
356
        RegistryOption constructor.  Any other keyword arguments are treated
 
357
        as values for the option, and they value is treated as the help.
 
358
        """
 
359
        reg = _mod_registry.Registry()
 
360
        for name, switch_help in kwargs.iteritems():
 
361
            name = name.replace('_', '-')
 
362
            reg.register(name, name, help=switch_help)
 
363
        return RegistryOption(name_, help, reg, title=title,
 
364
            value_switches=value_switches, enum_switch=enum_switch)
 
365
 
 
366
    def add_option(self, parser, short_name):
 
367
        """Add this option to an Optparse parser"""
 
368
        if self.value_switches:
 
369
            parser = parser.add_option_group(self.title)
 
370
        if self.enum_switch:
 
371
            Option.add_option(self, parser, short_name)
 
372
        if self.value_switches:
 
373
            for key in self.registry.keys():
 
374
                option_strings = ['--%s' % key]
 
375
                if self.is_hidden(key):
 
376
                    help = optparse.SUPPRESS_HELP
 
377
                else:
 
378
                    help = self.registry.get_help(key)
 
379
                parser.add_option(action='callback',
 
380
                              callback=self._optparse_value_callback(key),
 
381
                                  help=help,
 
382
                                  *option_strings)
 
383
 
 
384
    def _optparse_value_callback(self, cb_value):
 
385
        def cb(option, opt, value, parser):
 
386
            v = self.type(cb_value)
 
387
            setattr(parser.values, self._param_name, v)
 
388
            if self.custom_callback is not None:
 
389
                self.custom_callback(option, self._param_name, v, parser)
 
390
        return cb
 
391
 
 
392
    def iter_switches(self):
 
393
        """Iterate through the list of switches provided by the option
 
394
 
 
395
        :return: an iterator of (name, short_name, argname, help)
 
396
        """
 
397
        for value in Option.iter_switches(self):
 
398
            yield value
 
399
        if self.value_switches:
 
400
            for key in sorted(self.registry.keys()):
 
401
                yield key, None, None, self.registry.get_help(key)
 
402
 
 
403
    def is_hidden(self, name):
 
404
        if name == self.name:
 
405
            return Option.is_hidden(self, name)
 
406
        return getattr(self.registry.get_info(name), 'hidden', False)
 
407
 
 
408
 
 
409
class OptionParser(optparse.OptionParser):
 
410
    """OptionParser that raises exceptions instead of exiting"""
 
411
 
 
412
    DEFAULT_VALUE = object()
 
413
 
 
414
    def error(self, message):
 
415
        raise errors.BzrCommandError(message)
 
416
 
 
417
 
 
418
def get_optparser(options):
 
419
    """Generate an optparse parser for bzrlib-style options"""
 
420
 
 
421
    parser = OptionParser()
 
422
    parser.remove_option('--help')
 
423
    for option in options.itervalues():
 
424
        option.add_option(parser, option.short_name())
 
425
    return parser
 
426
 
 
427
 
 
428
def custom_help(name, help):
 
429
    """Clone a common option overriding the help."""
 
430
    import copy
 
431
    o = copy.copy(Option.OPTIONS[name])
 
432
    o.help = help
 
433
    return o
 
434
 
 
435
 
 
436
def _standard_option(name, **kwargs):
 
437
    """Register a standard option."""
 
438
    # All standard options are implicitly 'global' ones
 
439
    Option.STD_OPTIONS[name] = Option(name, **kwargs)
 
440
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
 
441
 
 
442
 
 
443
def _global_option(name, **kwargs):
 
444
    """Register a global option."""
 
445
    Option.OPTIONS[name] = Option(name, **kwargs)
 
446
 
 
447
 
 
448
def _global_registry_option(name, help, registry, **kwargs):
 
449
    Option.OPTIONS[name] = RegistryOption(name, help, registry, **kwargs)
 
450
 
 
451
 
 
452
class MergeTypeRegistry(_mod_registry.Registry):
 
453
 
 
454
    pass
 
455
 
 
456
 
 
457
# This is the verbosity level detected during command line parsing.
 
458
# Note that the final value is dependent on the order in which the
 
459
# various flags (verbose, quiet, no-verbose, no-quiet) are given.
 
460
# The final value will be one of the following:
 
461
#
 
462
# * -ve for quiet
 
463
# * 0 for normal
 
464
# * +ve for verbose
 
465
_verbosity_level = 0
 
466
 
 
467
 
 
468
def _verbosity_level_callback(option, opt_str, value, parser):
 
469
    global _verbosity_level
 
470
    if not value:
 
471
        # Either --no-verbose or --no-quiet was specified
 
472
        _verbosity_level = 0
 
473
    elif opt_str == "verbose":
 
474
        if _verbosity_level > 0:
 
475
            _verbosity_level += 1
 
476
        else:
 
477
            _verbosity_level = 1
 
478
    else:
 
479
        if _verbosity_level < 0:
 
480
            _verbosity_level -= 1
 
481
        else:
 
482
            _verbosity_level = -1
 
483
 
 
484
 
 
485
_merge_type_registry = MergeTypeRegistry()
 
486
_merge_type_registry.register_lazy('merge3', 'bzrlib.merge', 'Merge3Merger',
 
487
                                   "Native diff3-style merge")
 
488
_merge_type_registry.register_lazy('diff3', 'bzrlib.merge', 'Diff3Merger',
 
489
                                   "Merge using external diff3")
 
490
_merge_type_registry.register_lazy('weave', 'bzrlib.merge', 'WeaveMerger',
 
491
                                   "Weave-based merge")
 
492
_merge_type_registry.register_lazy('lca', 'bzrlib.merge', 'LCAMerger',
 
493
                                   "LCA-newness merge")
 
494
 
 
495
# Declare the standard options
 
496
_standard_option('help', short_name='h',
 
497
                 help='Show help message.')
 
498
_standard_option('verbose', short_name='v',
 
499
                 help='Display more information.',
 
500
                 custom_callback=_verbosity_level_callback)
 
501
_standard_option('quiet', short_name='q',
 
502
                 help="Only display errors and warnings.",
 
503
                 custom_callback=_verbosity_level_callback)
 
504
 
 
505
# Declare commonly used options
 
506
_global_option('all')
 
507
_global_option('overwrite', help='Ignore differences between branches and '
 
508
               'overwrite unconditionally.')
 
509
_global_option('basis', type=str)
 
510
_global_option('bound')
 
511
_global_option('diff-options', type=str)
 
512
_global_option('file', type=unicode, short_name='F')
 
513
_global_option('force')
 
514
_global_option('format', type=unicode)
 
515
_global_option('forward')
 
516
_global_option('message', type=unicode,
 
517
               short_name='m',
 
518
               help='Message string.')
 
519
_global_option('no-recurse')
 
520
_global_option('profile',
 
521
               help='Show performance profiling information.')
 
522
_global_option('revision',
 
523
               type=_parse_revision_str,
 
524
               short_name='r',
 
525
               help='See "help revisionspec" for details.')
 
526
_global_option('change',
 
527
               type=_parse_change_str,
 
528
               short_name='c',
 
529
               param_name='revision',
 
530
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
 
531
_global_option('show-ids',
 
532
               help='Show internal object ids.')
 
533
_global_option('timezone', 
 
534
               type=str,
 
535
               help='display timezone as local, original, or utc')
 
536
_global_option('unbound')
 
537
_global_option('version')
 
538
_global_option('email')
 
539
_global_option('update')
 
540
_global_registry_option('log-format', "Use specified log format.",
 
541
                        log.log_formatter_registry, value_switches=True,
 
542
                        title='Log format')
 
543
_global_option('long', help='Use detailed log format. Same as --log-format long',
 
544
               short_name='l')
 
545
_global_option('short', help='Use moderately short log format. Same as --log-format short')
 
546
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
 
547
_global_option('root', type=str)
 
548
_global_option('no-backup')
 
549
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
 
550
                        _merge_type_registry, value_switches=True,
 
551
                        title='Merge algorithm')
 
552
_global_option('pattern', type=str)
 
553
_global_option('remember', help='Remember the specified location as a'
 
554
               ' default.')
 
555
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
 
556
_global_option('kind', type=str)
 
557
_global_option('dry-run',
 
558
               help="Show what would be done, but don't actually do anything.")
 
559
_global_option('name-from-revision', help='The path name in the old tree.')