~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/option.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2004, 2005, 2006, 2007 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
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
 
from __future__ import absolute_import
21
 
 
22
20
import optparse
23
21
import re
24
22
 
27
25
from bzrlib import (
28
26
    errors,
29
27
    revisionspec,
30
 
    i18n,
31
28
    )
32
29
""")
33
30
 
34
31
from bzrlib import (
35
 
    registry as _mod_registry,
 
32
    log,
 
33
    registry,
36
34
    )
37
35
 
38
 
 
39
36
def _parse_revision_str(revstr):
40
37
    """This handles a revision string -> revno.
41
38
 
43
40
    each revision specifier supplied.
44
41
 
45
42
    >>> _parse_revision_str('234')
46
 
    [<RevisionSpec_dwim 234>]
 
43
    [<RevisionSpec_revno 234>]
47
44
    >>> _parse_revision_str('234..567')
48
 
    [<RevisionSpec_dwim 234>, <RevisionSpec_dwim 567>]
 
45
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
49
46
    >>> _parse_revision_str('..')
50
47
    [<RevisionSpec None>, <RevisionSpec None>]
51
48
    >>> _parse_revision_str('..234')
52
 
    [<RevisionSpec None>, <RevisionSpec_dwim 234>]
 
49
    [<RevisionSpec None>, <RevisionSpec_revno 234>]
53
50
    >>> _parse_revision_str('234..')
54
 
    [<RevisionSpec_dwim 234>, <RevisionSpec None>]
 
51
    [<RevisionSpec_revno 234>, <RevisionSpec None>]
55
52
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
56
 
    [<RevisionSpec_dwim 234>, <RevisionSpec_dwim 456>, <RevisionSpec_dwim 789>]
 
53
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
57
54
    >>> _parse_revision_str('234....789') #Error ?
58
 
    [<RevisionSpec_dwim 234>, <RevisionSpec None>, <RevisionSpec_dwim 789>]
 
55
    [<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
59
56
    >>> _parse_revision_str('revid:test@other.com-234234')
60
57
    [<RevisionSpec_revid revid:test@other.com-234234>]
61
58
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
62
59
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
63
60
    >>> _parse_revision_str('revid:test@other.com-234234..23')
64
 
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_dwim 23>]
 
61
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
65
62
    >>> _parse_revision_str('date:2005-04-12')
66
63
    [<RevisionSpec_date date:2005-04-12>]
67
64
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
71
68
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
72
69
    [<RevisionSpec_date date:2005-04-12,12:24:33>]
73
70
    >>> _parse_revision_str('-5..23')
74
 
    [<RevisionSpec_dwim -5>, <RevisionSpec_dwim 23>]
 
71
    [<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
75
72
    >>> _parse_revision_str('-5')
76
 
    [<RevisionSpec_dwim -5>]
 
73
    [<RevisionSpec_revno -5>]
77
74
    >>> _parse_revision_str('123a')
78
 
    [<RevisionSpec_dwim 123a>]
 
75
    Traceback (most recent call last):
 
76
      ...
 
77
    NoSuchRevisionSpec: No namespace registered for string: '123a'
79
78
    >>> _parse_revision_str('abc')
80
 
    [<RevisionSpec_dwim abc>]
 
79
    Traceback (most recent call last):
 
80
      ...
 
81
    NoSuchRevisionSpec: No namespace registered for string: 'abc'
81
82
    >>> _parse_revision_str('branch:../branch2')
82
83
    [<RevisionSpec_branch branch:../branch2>]
83
84
    >>> _parse_revision_str('branch:../../branch2')
84
85
    [<RevisionSpec_branch branch:../../branch2>]
85
86
    >>> _parse_revision_str('branch:../../branch2..23')
86
 
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_dwim 23>]
 
87
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 23>]
87
88
    >>> _parse_revision_str('branch:..\\\\branch2')
88
89
    [<RevisionSpec_branch branch:..\\branch2>]
89
90
    >>> _parse_revision_str('branch:..\\\\..\\\\branch2..23')
90
 
    [<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_dwim 23>]
 
91
    [<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_revno 23>]
91
92
    """
92
93
    # TODO: Maybe move this into revisionspec.py
93
94
    revs = []
103
104
    parent of the revision.
104
105
 
105
106
    >>> _parse_change_str('123')
106
 
    (<RevisionSpec_before before:123>, <RevisionSpec_dwim 123>)
 
107
    (<RevisionSpec_before before:123>, <RevisionSpec_revno 123>)
107
108
    >>> _parse_change_str('123..124')
108
109
    Traceback (most recent call last):
109
110
      ...
135
136
 
136
137
class Option(object):
137
138
    """Description of a command line option
138
 
 
 
139
    
139
140
    :ivar _short_name: If this option has a single-letter name, this is it.
140
141
    Otherwise None.
141
142
    """
149
150
    OPTIONS = {}
150
151
 
151
152
    def __init__(self, name, help='', type=None, argname=None,
152
 
                 short_name=None, param_name=None, custom_callback=None,
153
 
                 hidden=False):
 
153
                 short_name=None, param_name=None, custom_callback=None):
154
154
        """Make a new command option.
155
155
 
156
156
        :param name: regular name of the command, used in the double-dash
157
 
            form and also as the parameter to the command's run()
 
157
            form and also as the parameter to the command's run() 
158
158
            method (unless param_name is specified).
159
159
 
160
160
        :param help: help message displayed in command help
161
161
 
162
 
        :param type: function called to parse the option argument, or
 
162
        :param type: function called to parse the option argument, or 
163
163
            None (default) if this option doesn't take an argument.
164
164
 
165
165
        :param argname: name of option argument, if any
173
173
        :param custom_callback: a callback routine to be called after normal
174
174
            processing. The signature of the callback routine is
175
175
            (option, name, new_value, parser).
176
 
        :param hidden: If True, the option should be hidden in help and
177
 
            documentation.
178
176
        """
179
177
        self.name = name
180
178
        self.help = help
191
189
        else:
192
190
            self._param_name = param_name
193
191
        self.custom_callback = custom_callback
194
 
        self.hidden = hidden
195
192
 
196
193
    def short_name(self):
197
194
        if self._short_name:
211
208
        option_strings = ['--%s' % self.name]
212
209
        if short_name is not None:
213
210
            option_strings.append('-%s' % short_name)
214
 
        if self.hidden:
215
 
            help = optparse.SUPPRESS_HELP
216
 
        else:
217
 
            help = self.help
218
211
        optargfn = self.type
219
212
        if optargfn is None:
220
213
            parser.add_option(action='callback',
221
214
                              callback=self._optparse_bool_callback,
222
215
                              callback_args=(True,),
223
 
                              help=help,
 
216
                              help=self.help,
224
217
                              *option_strings)
225
218
            negation_strings = ['--%s' % self.get_negation_name()]
226
219
            parser.add_option(action='callback',
231
224
            parser.add_option(action='callback',
232
225
                              callback=self._optparse_callback,
233
226
                              type='string', metavar=self.argname.upper(),
234
 
                              help=help,
 
227
                              help=self.help,
235
228
                              default=OptionParser.DEFAULT_VALUE,
236
229
                              *option_strings)
237
230
 
248
241
 
249
242
    def iter_switches(self):
250
243
        """Iterate through the list of switches provided by the option
251
 
 
 
244
        
252
245
        :return: an iterator of (name, short_name, argname, help)
253
246
        """
254
247
        argname =  self.argname
257
250
        yield self.name, self.short_name(), argname, self.help
258
251
 
259
252
    def is_hidden(self, name):
260
 
        return self.hidden
 
253
        return False
261
254
 
262
255
 
263
256
class ListOption(Option):
279
272
        parser.add_option(action='callback',
280
273
                          callback=self._optparse_callback,
281
274
                          type='string', metavar=self.argname.upper(),
282
 
                          help=self.help, dest=self._param_name, default=[],
 
275
                          help=self.help, default=[],
283
276
                          *option_strings)
284
277
 
285
278
    def _optparse_callback(self, option, opt, value, parser):
313
306
        else:
314
307
            return self.converter(value)
315
308
 
316
 
    def __init__(self, name, help, registry=None, converter=None,
317
 
        value_switches=False, title=None, enum_switch=True,
318
 
        lazy_registry=None, short_name=None, short_value_switches=None):
 
309
    def __init__(self, name, help, registry, converter=None,
 
310
        value_switches=False, title=None, enum_switch=True):
319
311
        """
320
312
        Constructor.
321
313
 
329
321
            '--knit' can be used interchangeably.
330
322
        :param enum_switch: If true, a switch is provided with the option name,
331
323
            which takes a value.
332
 
        :param lazy_registry: A tuple of (module name, attribute name) for a
333
 
            registry to be lazily loaded.
334
 
        :param short_name: The short name for the enum switch, if any
335
 
        :param short_value_switches: A dict mapping values to short names
336
324
        """
337
 
        Option.__init__(self, name, help, type=self.convert,
338
 
                        short_name=short_name)
339
 
        self._registry = registry
340
 
        if registry is None:
341
 
            if lazy_registry is None:
342
 
                raise AssertionError(
343
 
                    'One of registry or lazy_registry must be given.')
344
 
            self._lazy_registry = _mod_registry._LazyObjectGetter(
345
 
                *lazy_registry)
346
 
        if registry is not None and lazy_registry is not None:
347
 
            raise AssertionError(
348
 
                'registry and lazy_registry are mutually exclusive')
 
325
        Option.__init__(self, name, help, type=self.convert)
 
326
        self.registry = registry
349
327
        self.name = name
350
328
        self.converter = converter
351
329
        self.value_switches = value_switches
352
330
        self.enum_switch = enum_switch
353
 
        self.short_value_switches = short_value_switches
354
331
        self.title = title
355
332
        if self.title is None:
356
333
            self.title = name
357
334
 
358
 
    @property
359
 
    def registry(self):
360
 
        if self._registry is None:
361
 
            self._registry = self._lazy_registry.get_obj()
362
 
        return self._registry
363
 
 
364
335
    @staticmethod
365
336
    def from_kwargs(name_, help=None, title=None, value_switches=False,
366
337
                    enum_switch=True, **kwargs):
368
339
 
369
340
        name, help, value_switches and enum_switch are passed to the
370
341
        RegistryOption constructor.  Any other keyword arguments are treated
371
 
        as values for the option, and their value is treated as the help.
 
342
        as values for the option, and they value is treated as the help.
372
343
        """
373
 
        reg = _mod_registry.Registry()
374
 
        for name, switch_help in sorted(kwargs.items()):
 
344
        reg = registry.Registry()
 
345
        for name, switch_help in kwargs.iteritems():
375
346
            name = name.replace('_', '-')
376
347
            reg.register(name, name, help=switch_help)
377
348
            if not value_switches:
394
365
                    help = optparse.SUPPRESS_HELP
395
366
                else:
396
367
                    help = self.registry.get_help(key)
397
 
                if (self.short_value_switches and
398
 
                    key in self.short_value_switches):
399
 
                    option_strings.append('-%s' %
400
 
                                          self.short_value_switches[key])
401
368
                parser.add_option(action='callback',
402
369
                              callback=self._optparse_value_callback(key),
403
370
                                  help=help,
433
400
 
434
401
    DEFAULT_VALUE = object()
435
402
 
436
 
    def __init__(self):
437
 
        optparse.OptionParser.__init__(self)
438
 
        self.formatter = GettextIndentedHelpFormatter()
439
 
 
440
403
    def error(self, message):
441
404
        raise errors.BzrCommandError(message)
442
405
 
443
406
 
444
 
class GettextIndentedHelpFormatter(optparse.IndentedHelpFormatter):
445
 
    """Adds gettext() call to format_option()"""
446
 
    def __init__(self):
447
 
        optparse.IndentedHelpFormatter.__init__(self)
448
 
 
449
 
    def format_option(self, option):
450
 
        """code taken from Python's optparse.py"""
451
 
        if option.help:
452
 
            option.help = i18n.gettext(option.help)
453
 
        return optparse.IndentedHelpFormatter.format_option(self, option)
454
 
 
455
 
 
456
407
def get_optparser(options):
457
408
    """Generate an optparse parser for bzrlib-style options"""
458
409
 
477
428
    Option.STD_OPTIONS[name] = Option(name, **kwargs)
478
429
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
479
430
 
480
 
def _standard_list_option(name, **kwargs):
481
 
    """Register a standard option."""
482
 
    # All standard options are implicitly 'global' ones
483
 
    Option.STD_OPTIONS[name] = ListOption(name, **kwargs)
484
 
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
485
 
 
486
431
 
487
432
def _global_option(name, **kwargs):
488
433
    """Register a global option."""
489
434
    Option.OPTIONS[name] = Option(name, **kwargs)
490
435
 
491
436
 
492
 
def _global_registry_option(name, help, registry=None, **kwargs):
 
437
def _global_registry_option(name, help, registry, **kwargs):
493
438
    Option.OPTIONS[name] = RegistryOption(name, help, registry, **kwargs)
494
439
 
495
440
 
 
441
class MergeTypeRegistry(registry.Registry):
 
442
 
 
443
    pass
 
444
 
 
445
 
496
446
# This is the verbosity level detected during command line parsing.
497
447
# Note that the final value is dependent on the order in which the
498
448
# various flags (verbose, quiet, no-verbose, no-quiet) are given.
521
471
            _verbosity_level = -1
522
472
 
523
473
 
 
474
_merge_type_registry = MergeTypeRegistry()
 
475
_merge_type_registry.register_lazy('merge3', 'bzrlib.merge', 'Merge3Merger',
 
476
                                   "Native diff3-style merge")
 
477
_merge_type_registry.register_lazy('diff3', 'bzrlib.merge', 'Diff3Merger',
 
478
                                   "Merge using external diff3")
 
479
_merge_type_registry.register_lazy('weave', 'bzrlib.merge', 'WeaveMerger',
 
480
                                   "Weave-based merge")
 
481
_merge_type_registry.register_lazy('lca', 'bzrlib.merge', 'LCAMerger',
 
482
                                   "LCA-newness merge")
 
483
 
524
484
# Declare the standard options
525
485
_standard_option('help', short_name='h',
526
486
                 help='Show help message.')
 
487
_standard_option('verbose', short_name='v',
 
488
                 help='Display more information.',
 
489
                 custom_callback=_verbosity_level_callback)
527
490
_standard_option('quiet', short_name='q',
528
491
                 help="Only display errors and warnings.",
529
492
                 custom_callback=_verbosity_level_callback)
530
 
_standard_option('usage',
531
 
                 help='Show usage message and options.')
532
 
_standard_option('verbose', short_name='v',
533
 
                 help='Display more information.',
534
 
                 custom_callback=_verbosity_level_callback)
535
493
 
536
494
# Declare commonly used options
537
 
_global_option('change',
538
 
               type=_parse_change_str,
539
 
               short_name='c',
540
 
               param_name='revision',
541
 
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
542
 
_global_option('directory', short_name='d', type=unicode,
543
 
               help='Branch to operate on, instead of working directory.')
 
495
_global_option('all')
 
496
_global_option('overwrite', help='Ignore differences between branches and '
 
497
               'overwrite unconditionally.')
 
498
_global_option('basis', type=str)
 
499
_global_option('bound')
 
500
_global_option('diff-options', type=str)
544
501
_global_option('file', type=unicode, short_name='F')
545
 
_global_registry_option('log-format', "Use specified log format.",
546
 
                        lazy_registry=('bzrlib.log', 'log_formatter_registry'),
547
 
                        value_switches=True, title='Log format',
548
 
                        short_value_switches={'short': 'S'})
549
 
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
550
 
                        lazy_registry=('bzrlib.merge', 'merge_type_registry'),
551
 
                        value_switches=True, title='Merge algorithm')
 
502
_global_option('force')
 
503
_global_option('format', type=unicode)
 
504
_global_option('forward')
552
505
_global_option('message', type=unicode,
553
506
               short_name='m',
554
507
               help='Message string.')
555
 
_global_option('null', short_name='0',
556
 
                 help='Use an ASCII NUL (\\0) separator rather than '
557
 
                      'a newline.')
558
 
_global_option('overwrite', help='Ignore differences between branches and '
559
 
               'overwrite unconditionally.')
560
 
_global_option('remember', help='Remember the specified location as a'
561
 
               ' default.')
562
 
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
 
508
_global_option('no-recurse')
 
509
_global_option('profile',
 
510
               help='Show performance profiling information.')
563
511
_global_option('revision',
564
512
               type=_parse_revision_str,
565
513
               short_name='r',
566
514
               help='See "help revisionspec" for details.')
 
515
_global_option('change',
 
516
               type=_parse_change_str,
 
517
               short_name='c',
 
518
               param_name='revision',
 
519
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
567
520
_global_option('show-ids',
568
521
               help='Show internal object ids.')
569
 
_global_option('timezone',
 
522
_global_option('timezone', 
570
523
               type=str,
571
 
               help='Display timezone as local, original, or utc.')
572
 
 
573
 
diff_writer_registry = _mod_registry.Registry()
574
 
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')
575
 
diff_writer_registry.default_key = 'plain'
 
524
               help='display timezone as local, original, or utc')
 
525
_global_option('unbound')
 
526
_global_option('version')
 
527
_global_option('email')
 
528
_global_option('update')
 
529
_global_registry_option('log-format', "Use specified log format.",
 
530
                        log.log_formatter_registry, value_switches=True,
 
531
                        title='Log format')
 
532
_global_option('long', help='Use detailed log format. Same as --log-format long',
 
533
               short_name='l')
 
534
_global_option('short', help='Use moderately short log format. Same as --log-format short')
 
535
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
 
536
_global_option('root', type=str)
 
537
_global_option('no-backup')
 
538
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
 
539
                        _merge_type_registry, value_switches=True,
 
540
                        title='Merge algorithm')
 
541
_global_option('pattern', type=str)
 
542
_global_option('remember', help='Remember the specified location as a'
 
543
               ' default.')
 
544
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
 
545
_global_option('kind', type=str)
 
546
_global_option('dry-run',
 
547
               help="Show what would be done, but don't actually do anything.")
 
548
_global_option('name-from-revision', help='The path name in the old tree.')