~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: 2008-03-13 23:45:11 UTC
  • mfrom: (3272.1.1 ianc-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080313234511-fkj5oa8gm3nrfcro
(Neil Martinsen-Burrell) Explain version-info --custom in the User
        Guide

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.
25
25
from bzrlib import (
26
26
    errors,
27
27
    revisionspec,
28
 
    i18n,
29
28
    )
30
29
""")
31
30
 
32
31
from bzrlib import (
33
 
    registry as _mod_registry,
 
32
    log,
 
33
    registry,
34
34
    )
35
35
 
36
 
 
37
36
def _parse_revision_str(revstr):
38
37
    """This handles a revision string -> revno.
39
38
 
41
40
    each revision specifier supplied.
42
41
 
43
42
    >>> _parse_revision_str('234')
44
 
    [<RevisionSpec_dwim 234>]
 
43
    [<RevisionSpec_revno 234>]
45
44
    >>> _parse_revision_str('234..567')
46
 
    [<RevisionSpec_dwim 234>, <RevisionSpec_dwim 567>]
 
45
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
47
46
    >>> _parse_revision_str('..')
48
47
    [<RevisionSpec None>, <RevisionSpec None>]
49
48
    >>> _parse_revision_str('..234')
50
 
    [<RevisionSpec None>, <RevisionSpec_dwim 234>]
 
49
    [<RevisionSpec None>, <RevisionSpec_revno 234>]
51
50
    >>> _parse_revision_str('234..')
52
 
    [<RevisionSpec_dwim 234>, <RevisionSpec None>]
 
51
    [<RevisionSpec_revno 234>, <RevisionSpec None>]
53
52
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
54
 
    [<RevisionSpec_dwim 234>, <RevisionSpec_dwim 456>, <RevisionSpec_dwim 789>]
 
53
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
55
54
    >>> _parse_revision_str('234....789') #Error ?
56
 
    [<RevisionSpec_dwim 234>, <RevisionSpec None>, <RevisionSpec_dwim 789>]
 
55
    [<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
57
56
    >>> _parse_revision_str('revid:test@other.com-234234')
58
57
    [<RevisionSpec_revid revid:test@other.com-234234>]
59
58
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
60
59
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
61
60
    >>> _parse_revision_str('revid:test@other.com-234234..23')
62
 
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_dwim 23>]
 
61
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
63
62
    >>> _parse_revision_str('date:2005-04-12')
64
63
    [<RevisionSpec_date date:2005-04-12>]
65
64
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
69
68
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
70
69
    [<RevisionSpec_date date:2005-04-12,12:24:33>]
71
70
    >>> _parse_revision_str('-5..23')
72
 
    [<RevisionSpec_dwim -5>, <RevisionSpec_dwim 23>]
 
71
    [<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
73
72
    >>> _parse_revision_str('-5')
74
 
    [<RevisionSpec_dwim -5>]
 
73
    [<RevisionSpec_revno -5>]
75
74
    >>> _parse_revision_str('123a')
76
 
    [<RevisionSpec_dwim 123a>]
 
75
    Traceback (most recent call last):
 
76
      ...
 
77
    NoSuchRevisionSpec: No namespace registered for string: '123a'
77
78
    >>> _parse_revision_str('abc')
78
 
    [<RevisionSpec_dwim abc>]
 
79
    Traceback (most recent call last):
 
80
      ...
 
81
    NoSuchRevisionSpec: No namespace registered for string: 'abc'
79
82
    >>> _parse_revision_str('branch:../branch2')
80
83
    [<RevisionSpec_branch branch:../branch2>]
81
84
    >>> _parse_revision_str('branch:../../branch2')
82
85
    [<RevisionSpec_branch branch:../../branch2>]
83
86
    >>> _parse_revision_str('branch:../../branch2..23')
84
 
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_dwim 23>]
 
87
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 23>]
85
88
    >>> _parse_revision_str('branch:..\\\\branch2')
86
89
    [<RevisionSpec_branch branch:..\\branch2>]
87
90
    >>> _parse_revision_str('branch:..\\\\..\\\\branch2..23')
88
 
    [<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_dwim 23>]
 
91
    [<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_revno 23>]
89
92
    """
90
93
    # TODO: Maybe move this into revisionspec.py
91
94
    revs = []
101
104
    parent of the revision.
102
105
 
103
106
    >>> _parse_change_str('123')
104
 
    (<RevisionSpec_before before:123>, <RevisionSpec_dwim 123>)
 
107
    (<RevisionSpec_before before:123>, <RevisionSpec_revno 123>)
105
108
    >>> _parse_change_str('123..124')
106
109
    Traceback (most recent call last):
107
110
      ...
133
136
 
134
137
class Option(object):
135
138
    """Description of a command line option
136
 
 
 
139
    
137
140
    :ivar _short_name: If this option has a single-letter name, this is it.
138
141
    Otherwise None.
139
142
    """
147
150
    OPTIONS = {}
148
151
 
149
152
    def __init__(self, name, help='', type=None, argname=None,
150
 
                 short_name=None, param_name=None, custom_callback=None,
151
 
                 hidden=False):
 
153
                 short_name=None, param_name=None, custom_callback=None):
152
154
        """Make a new command option.
153
155
 
154
156
        :param name: regular name of the command, used in the double-dash
155
 
            form and also as the parameter to the command's run()
 
157
            form and also as the parameter to the command's run() 
156
158
            method (unless param_name is specified).
157
159
 
158
160
        :param help: help message displayed in command help
159
161
 
160
 
        :param type: function called to parse the option argument, or
 
162
        :param type: function called to parse the option argument, or 
161
163
            None (default) if this option doesn't take an argument.
162
164
 
163
165
        :param argname: name of option argument, if any
171
173
        :param custom_callback: a callback routine to be called after normal
172
174
            processing. The signature of the callback routine is
173
175
            (option, name, new_value, parser).
174
 
        :param hidden: If True, the option should be hidden in help and
175
 
            documentation.
176
176
        """
177
177
        self.name = name
178
178
        self.help = help
179
179
        self.type = type
180
180
        self._short_name = short_name
181
181
        if type is None:
182
 
            if argname:
183
 
                raise ValueError('argname not valid for booleans')
 
182
            assert argname is None
184
183
        elif argname is None:
185
184
            argname = 'ARG'
186
185
        self.argname = argname
187
186
        if param_name is None:
188
 
            self._param_name = self.name.replace('-', '_')
 
187
            self._param_name = self.name
189
188
        else:
190
189
            self._param_name = param_name
191
190
        self.custom_callback = custom_callback
192
 
        self.hidden = hidden
193
191
 
194
192
    def short_name(self):
195
193
        if self._short_name:
209
207
        option_strings = ['--%s' % self.name]
210
208
        if short_name is not None:
211
209
            option_strings.append('-%s' % short_name)
212
 
        if self.hidden:
213
 
            help = optparse.SUPPRESS_HELP
214
 
        else:
215
 
            help = self.help
216
210
        optargfn = self.type
217
211
        if optargfn is None:
218
 
            parser.add_option(action='callback',
219
 
                              callback=self._optparse_bool_callback,
 
212
            parser.add_option(action='callback', 
 
213
                              callback=self._optparse_bool_callback, 
220
214
                              callback_args=(True,),
221
 
                              help=help,
 
215
                              help=self.help,
222
216
                              *option_strings)
223
217
            negation_strings = ['--%s' % self.get_negation_name()]
224
 
            parser.add_option(action='callback',
225
 
                              callback=self._optparse_bool_callback,
 
218
            parser.add_option(action='callback', 
 
219
                              callback=self._optparse_bool_callback, 
226
220
                              callback_args=(False,),
227
221
                              help=optparse.SUPPRESS_HELP, *negation_strings)
228
222
        else:
229
 
            parser.add_option(action='callback',
230
 
                              callback=self._optparse_callback,
 
223
            parser.add_option(action='callback', 
 
224
                              callback=self._optparse_callback, 
231
225
                              type='string', metavar=self.argname.upper(),
232
 
                              help=help,
233
 
                              default=OptionParser.DEFAULT_VALUE,
 
226
                              help=self.help,
 
227
                              default=OptionParser.DEFAULT_VALUE, 
234
228
                              *option_strings)
235
229
 
236
230
    def _optparse_bool_callback(self, option, opt_str, value, parser, bool_v):
246
240
 
247
241
    def iter_switches(self):
248
242
        """Iterate through the list of switches provided by the option
249
 
 
 
243
        
250
244
        :return: an iterator of (name, short_name, argname, help)
251
245
        """
252
246
        argname =  self.argname
255
249
        yield self.name, self.short_name(), argname, self.help
256
250
 
257
251
    def is_hidden(self, name):
258
 
        return self.hidden
 
252
        return False
259
253
 
260
254
 
261
255
class ListOption(Option):
277
271
        parser.add_option(action='callback',
278
272
                          callback=self._optparse_callback,
279
273
                          type='string', metavar=self.argname.upper(),
280
 
                          help=self.help, dest=self._param_name, default=[],
 
274
                          help=self.help, default=[],
281
275
                          *option_strings)
282
276
 
283
277
    def _optparse_callback(self, option, opt, value, parser):
311
305
        else:
312
306
            return self.converter(value)
313
307
 
314
 
    def __init__(self, name, help, registry=None, converter=None,
315
 
        value_switches=False, title=None, enum_switch=True,
316
 
        lazy_registry=None, short_name=None, short_value_switches=None):
 
308
    def __init__(self, name, help, registry, converter=None,
 
309
        value_switches=False, title=None, enum_switch=True):
317
310
        """
318
311
        Constructor.
319
312
 
327
320
            '--knit' can be used interchangeably.
328
321
        :param enum_switch: If true, a switch is provided with the option name,
329
322
            which takes a value.
330
 
        :param lazy_registry: A tuple of (module name, attribute name) for a
331
 
            registry to be lazily loaded.
332
 
        :param short_name: The short name for the enum switch, if any
333
 
        :param short_value_switches: A dict mapping values to short names
334
323
        """
335
 
        Option.__init__(self, name, help, type=self.convert, short_name=short_name)
336
 
        self._registry = registry
337
 
        if registry is None:
338
 
            if lazy_registry is None:
339
 
                raise AssertionError(
340
 
                    'One of registry or lazy_registry must be given.')
341
 
            self._lazy_registry = _mod_registry._LazyObjectGetter(
342
 
                *lazy_registry)
343
 
        if registry is not None and lazy_registry is not None:
344
 
            raise AssertionError(
345
 
                'registry and lazy_registry are mutually exclusive')
 
324
        Option.__init__(self, name, help, type=self.convert)
 
325
        self.registry = registry
346
326
        self.name = name
347
327
        self.converter = converter
348
328
        self.value_switches = value_switches
349
329
        self.enum_switch = enum_switch
350
 
        self.short_value_switches = short_value_switches
351
330
        self.title = title
352
331
        if self.title is None:
353
332
            self.title = name
354
333
 
355
 
    @property
356
 
    def registry(self):
357
 
        if self._registry is None:
358
 
            self._registry = self._lazy_registry.get_obj()
359
 
        return self._registry
360
 
 
361
334
    @staticmethod
362
335
    def from_kwargs(name_, help=None, title=None, value_switches=False,
363
336
                    enum_switch=True, **kwargs):
365
338
 
366
339
        name, help, value_switches and enum_switch are passed to the
367
340
        RegistryOption constructor.  Any other keyword arguments are treated
368
 
        as values for the option, and their value is treated as the help.
 
341
        as values for the option, and they value is treated as the help.
369
342
        """
370
 
        reg = _mod_registry.Registry()
371
 
        for name, switch_help in sorted(kwargs.items()):
 
343
        reg = registry.Registry()
 
344
        for name, switch_help in kwargs.iteritems():
372
345
            name = name.replace('_', '-')
373
346
            reg.register(name, name, help=switch_help)
374
 
            if not value_switches:
375
 
                help = help + '  "' + name + '": ' + switch_help
376
 
                if not help.endswith("."):
377
 
                    help = help + "."
378
347
        return RegistryOption(name_, help, reg, title=title,
379
348
            value_switches=value_switches, enum_switch=enum_switch)
380
349
 
391
360
                    help = optparse.SUPPRESS_HELP
392
361
                else:
393
362
                    help = self.registry.get_help(key)
394
 
                if (self.short_value_switches and
395
 
                    key in self.short_value_switches):
396
 
                    option_strings.append('-%s' %
397
 
                                          self.short_value_switches[key])
398
363
                parser.add_option(action='callback',
399
364
                              callback=self._optparse_value_callback(key),
400
365
                                  help=help,
430
395
 
431
396
    DEFAULT_VALUE = object()
432
397
 
433
 
    def __init__(self):
434
 
        optparse.OptionParser.__init__(self)
435
 
        self.formatter = GettextIndentedHelpFormatter()
436
 
 
437
398
    def error(self, message):
438
399
        raise errors.BzrCommandError(message)
439
400
 
440
 
class GettextIndentedHelpFormatter(optparse.IndentedHelpFormatter):
441
 
    """Adds gettext() call to format_option()"""
442
 
    def __init__(self):
443
 
        optparse.IndentedHelpFormatter.__init__(self)
444
 
 
445
 
    def format_option(self, option):
446
 
        """code taken from Python's optparse.py"""
447
 
        if option.help:
448
 
            option.help = i18n.gettext(option.help)
449
 
        return optparse.IndentedHelpFormatter.format_option(self, option)
450
401
 
451
402
def get_optparser(options):
452
403
    """Generate an optparse parser for bzrlib-style options"""
478
429
    Option.OPTIONS[name] = Option(name, **kwargs)
479
430
 
480
431
 
481
 
def _global_registry_option(name, help, registry=None, **kwargs):
 
432
def _global_registry_option(name, help, registry, **kwargs):
482
433
    Option.OPTIONS[name] = RegistryOption(name, help, registry, **kwargs)
483
434
 
484
435
 
 
436
class MergeTypeRegistry(registry.Registry):
 
437
 
 
438
    pass
 
439
 
 
440
 
485
441
# This is the verbosity level detected during command line parsing.
486
442
# Note that the final value is dependent on the order in which the
487
443
# various flags (verbose, quiet, no-verbose, no-quiet) are given.
510
466
            _verbosity_level = -1
511
467
 
512
468
 
513
 
class MergeTypeRegistry(_mod_registry.Registry):
514
 
 
515
 
    pass
516
 
 
517
 
 
518
469
_merge_type_registry = MergeTypeRegistry()
519
470
_merge_type_registry.register_lazy('merge3', 'bzrlib.merge', 'Merge3Merger',
520
471
                                   "Native diff3-style merge")
528
479
# Declare the standard options
529
480
_standard_option('help', short_name='h',
530
481
                 help='Show help message.')
531
 
_standard_option('usage',
532
 
                 help='Show usage message and options.')
533
482
_standard_option('verbose', short_name='v',
534
483
                 help='Display more information.',
535
484
                 custom_callback=_verbosity_level_callback)
552
501
               short_name='m',
553
502
               help='Message string.')
554
503
_global_option('no-recurse')
555
 
_global_option('null', short_name='0',
556
 
                 help='Use an ASCII NUL (\\0) separator rather than '
557
 
                      'a newline.')
558
504
_global_option('profile',
559
505
               help='Show performance profiling information.')
560
506
_global_option('revision',
568
514
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
569
515
_global_option('show-ids',
570
516
               help='Show internal object ids.')
571
 
_global_option('timezone',
 
517
_global_option('timezone', 
572
518
               type=str,
573
 
               help='Display timezone as local, original, or utc.')
 
519
               help='display timezone as local, original, or utc')
574
520
_global_option('unbound')
575
521
_global_option('version')
576
522
_global_option('email')
577
523
_global_option('update')
578
524
_global_registry_option('log-format', "Use specified log format.",
579
 
                        lazy_registry=('bzrlib.log', 'log_formatter_registry'),
580
 
                        value_switches=True, title='Log format',
581
 
                        short_value_switches={'short': 'S'})
 
525
                        log.log_formatter_registry, value_switches=True,
 
526
                        title='Log format')
582
527
_global_option('long', help='Use detailed log format. Same as --log-format long',
583
528
               short_name='l')
584
529
_global_option('short', help='Use moderately short log format. Same as --log-format short')
596
541
_global_option('dry-run',
597
542
               help="Show what would be done, but don't actually do anything.")
598
543
_global_option('name-from-revision', help='The path name in the old tree.')
599
 
_global_option('directory', short_name='d', type=unicode,
600
 
               help='Branch to operate on, instead of working directory')
601
 
 
602
 
diff_writer_registry = _mod_registry.Registry()
603
 
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')
604
 
diff_writer_registry.default_key = 'plain'