~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/option.py

Merge bzr.dev and tree-file-ids-as-tuples.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
 
20
22
import optparse
21
23
import re
22
24
 
25
27
from bzrlib import (
26
28
    errors,
27
29
    revisionspec,
 
30
    i18n,
28
31
    )
29
32
""")
30
33
 
40
43
    each revision specifier supplied.
41
44
 
42
45
    >>> _parse_revision_str('234')
43
 
    [<RevisionSpec_revno 234>]
 
46
    [<RevisionSpec_dwim 234>]
44
47
    >>> _parse_revision_str('234..567')
45
 
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
 
48
    [<RevisionSpec_dwim 234>, <RevisionSpec_dwim 567>]
46
49
    >>> _parse_revision_str('..')
47
50
    [<RevisionSpec None>, <RevisionSpec None>]
48
51
    >>> _parse_revision_str('..234')
49
 
    [<RevisionSpec None>, <RevisionSpec_revno 234>]
 
52
    [<RevisionSpec None>, <RevisionSpec_dwim 234>]
50
53
    >>> _parse_revision_str('234..')
51
 
    [<RevisionSpec_revno 234>, <RevisionSpec None>]
 
54
    [<RevisionSpec_dwim 234>, <RevisionSpec None>]
52
55
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
53
 
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
 
56
    [<RevisionSpec_dwim 234>, <RevisionSpec_dwim 456>, <RevisionSpec_dwim 789>]
54
57
    >>> _parse_revision_str('234....789') #Error ?
55
 
    [<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
 
58
    [<RevisionSpec_dwim 234>, <RevisionSpec None>, <RevisionSpec_dwim 789>]
56
59
    >>> _parse_revision_str('revid:test@other.com-234234')
57
60
    [<RevisionSpec_revid revid:test@other.com-234234>]
58
61
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
59
62
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
60
63
    >>> _parse_revision_str('revid:test@other.com-234234..23')
61
 
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
 
64
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_dwim 23>]
62
65
    >>> _parse_revision_str('date:2005-04-12')
63
66
    [<RevisionSpec_date date:2005-04-12>]
64
67
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
68
71
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
69
72
    [<RevisionSpec_date date:2005-04-12,12:24:33>]
70
73
    >>> _parse_revision_str('-5..23')
71
 
    [<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
 
74
    [<RevisionSpec_dwim -5>, <RevisionSpec_dwim 23>]
72
75
    >>> _parse_revision_str('-5')
73
 
    [<RevisionSpec_revno -5>]
 
76
    [<RevisionSpec_dwim -5>]
74
77
    >>> _parse_revision_str('123a')
75
 
    Traceback (most recent call last):
76
 
      ...
77
 
    NoSuchRevisionSpec: No namespace registered for string: '123a'
 
78
    [<RevisionSpec_dwim 123a>]
78
79
    >>> _parse_revision_str('abc')
79
 
    Traceback (most recent call last):
80
 
      ...
81
 
    NoSuchRevisionSpec: No namespace registered for string: 'abc'
 
80
    [<RevisionSpec_dwim abc>]
82
81
    >>> _parse_revision_str('branch:../branch2')
83
82
    [<RevisionSpec_branch branch:../branch2>]
84
83
    >>> _parse_revision_str('branch:../../branch2')
85
84
    [<RevisionSpec_branch branch:../../branch2>]
86
85
    >>> _parse_revision_str('branch:../../branch2..23')
87
 
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 23>]
 
86
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_dwim 23>]
88
87
    >>> _parse_revision_str('branch:..\\\\branch2')
89
88
    [<RevisionSpec_branch branch:..\\branch2>]
90
89
    >>> _parse_revision_str('branch:..\\\\..\\\\branch2..23')
91
 
    [<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_revno 23>]
 
90
    [<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_dwim 23>]
92
91
    """
93
92
    # TODO: Maybe move this into revisionspec.py
94
93
    revs = []
104
103
    parent of the revision.
105
104
 
106
105
    >>> _parse_change_str('123')
107
 
    (<RevisionSpec_before before:123>, <RevisionSpec_revno 123>)
 
106
    (<RevisionSpec_before before:123>, <RevisionSpec_dwim 123>)
108
107
    >>> _parse_change_str('123..124')
109
108
    Traceback (most recent call last):
110
109
      ...
136
135
 
137
136
class Option(object):
138
137
    """Description of a command line option
139
 
    
 
138
 
140
139
    :ivar _short_name: If this option has a single-letter name, this is it.
141
140
    Otherwise None.
142
141
    """
150
149
    OPTIONS = {}
151
150
 
152
151
    def __init__(self, name, help='', type=None, argname=None,
153
 
                 short_name=None, param_name=None, custom_callback=None):
 
152
                 short_name=None, param_name=None, custom_callback=None,
 
153
                 hidden=False):
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.
176
178
        """
177
179
        self.name = name
178
180
        self.help = help
189
191
        else:
190
192
            self._param_name = param_name
191
193
        self.custom_callback = custom_callback
 
194
        self.hidden = hidden
192
195
 
193
196
    def short_name(self):
194
197
        if self._short_name:
208
211
        option_strings = ['--%s' % self.name]
209
212
        if short_name is not None:
210
213
            option_strings.append('-%s' % short_name)
 
214
        if self.hidden:
 
215
            help = optparse.SUPPRESS_HELP
 
216
        else:
 
217
            help = self.help
211
218
        optargfn = self.type
212
219
        if optargfn is None:
213
220
            parser.add_option(action='callback',
214
221
                              callback=self._optparse_bool_callback,
215
222
                              callback_args=(True,),
216
 
                              help=self.help,
 
223
                              help=help,
217
224
                              *option_strings)
218
225
            negation_strings = ['--%s' % self.get_negation_name()]
219
226
            parser.add_option(action='callback',
224
231
            parser.add_option(action='callback',
225
232
                              callback=self._optparse_callback,
226
233
                              type='string', metavar=self.argname.upper(),
227
 
                              help=self.help,
 
234
                              help=help,
228
235
                              default=OptionParser.DEFAULT_VALUE,
229
236
                              *option_strings)
230
237
 
241
248
 
242
249
    def iter_switches(self):
243
250
        """Iterate through the list of switches provided by the option
244
 
        
 
251
 
245
252
        :return: an iterator of (name, short_name, argname, help)
246
253
        """
247
254
        argname =  self.argname
250
257
        yield self.name, self.short_name(), argname, self.help
251
258
 
252
259
    def is_hidden(self, name):
253
 
        return False
 
260
        return self.hidden
254
261
 
255
262
 
256
263
class ListOption(Option):
272
279
        parser.add_option(action='callback',
273
280
                          callback=self._optparse_callback,
274
281
                          type='string', metavar=self.argname.upper(),
275
 
                          help=self.help, default=[],
 
282
                          help=self.help, dest=self._param_name, default=[],
276
283
                          *option_strings)
277
284
 
278
285
    def _optparse_callback(self, option, opt, value, parser):
308
315
 
309
316
    def __init__(self, name, help, registry=None, converter=None,
310
317
        value_switches=False, title=None, enum_switch=True,
311
 
        lazy_registry=None):
 
318
        lazy_registry=None, short_name=None, short_value_switches=None):
312
319
        """
313
320
        Constructor.
314
321
 
324
331
            which takes a value.
325
332
        :param lazy_registry: A tuple of (module name, attribute name) for a
326
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
327
336
        """
328
 
        Option.__init__(self, name, help, type=self.convert)
 
337
        Option.__init__(self, name, help, type=self.convert,
 
338
                        short_name=short_name)
329
339
        self._registry = registry
330
340
        if registry is None:
331
341
            if lazy_registry is None:
340
350
        self.converter = converter
341
351
        self.value_switches = value_switches
342
352
        self.enum_switch = enum_switch
 
353
        self.short_value_switches = short_value_switches
343
354
        self.title = title
344
355
        if self.title is None:
345
356
            self.title = name
349
360
        if self._registry is None:
350
361
            self._registry = self._lazy_registry.get_obj()
351
362
        return self._registry
352
 
    
 
363
 
353
364
    @staticmethod
354
365
    def from_kwargs(name_, help=None, title=None, value_switches=False,
355
366
                    enum_switch=True, **kwargs):
357
368
 
358
369
        name, help, value_switches and enum_switch are passed to the
359
370
        RegistryOption constructor.  Any other keyword arguments are treated
360
 
        as values for the option, and they value is treated as the help.
 
371
        as values for the option, and their value is treated as the help.
361
372
        """
362
373
        reg = _mod_registry.Registry()
363
 
        for name, switch_help in kwargs.iteritems():
 
374
        for name, switch_help in sorted(kwargs.items()):
364
375
            name = name.replace('_', '-')
365
376
            reg.register(name, name, help=switch_help)
366
377
            if not value_switches:
383
394
                    help = optparse.SUPPRESS_HELP
384
395
                else:
385
396
                    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])
386
401
                parser.add_option(action='callback',
387
402
                              callback=self._optparse_value_callback(key),
388
403
                                  help=help,
418
433
 
419
434
    DEFAULT_VALUE = object()
420
435
 
 
436
    def __init__(self):
 
437
        optparse.OptionParser.__init__(self)
 
438
        self.formatter = GettextIndentedHelpFormatter()
 
439
 
421
440
    def error(self, message):
422
441
        raise errors.BzrCommandError(message)
423
442
 
424
443
 
 
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
 
425
456
def get_optparser(options):
426
457
    """Generate an optparse parser for bzrlib-style options"""
427
458
 
446
477
    Option.STD_OPTIONS[name] = Option(name, **kwargs)
447
478
    Option.OPTIONS[name] = Option.STD_OPTIONS[name]
448
479
 
 
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
 
449
486
 
450
487
def _global_option(name, **kwargs):
451
488
    """Register a global option."""
484
521
            _verbosity_level = -1
485
522
 
486
523
 
487
 
class MergeTypeRegistry(_mod_registry.Registry):
488
 
 
489
 
    pass
490
 
 
491
 
 
492
 
_merge_type_registry = MergeTypeRegistry()
493
 
_merge_type_registry.register_lazy('merge3', 'bzrlib.merge', 'Merge3Merger',
494
 
                                   "Native diff3-style merge")
495
 
_merge_type_registry.register_lazy('diff3', 'bzrlib.merge', 'Diff3Merger',
496
 
                                   "Merge using external diff3")
497
 
_merge_type_registry.register_lazy('weave', 'bzrlib.merge', 'WeaveMerger',
498
 
                                   "Weave-based merge")
499
 
_merge_type_registry.register_lazy('lca', 'bzrlib.merge', 'LCAMerger',
500
 
                                   "LCA-newness merge")
501
 
 
502
524
# Declare the standard options
503
525
_standard_option('help', short_name='h',
504
526
                 help='Show help message.')
 
527
_standard_option('quiet', short_name='q',
 
528
                 help="Only display errors and warnings.",
 
529
                 custom_callback=_verbosity_level_callback)
 
530
_standard_option('usage',
 
531
                 help='Show usage message and options.')
505
532
_standard_option('verbose', short_name='v',
506
533
                 help='Display more information.',
507
534
                 custom_callback=_verbosity_level_callback)
508
 
_standard_option('quiet', short_name='q',
509
 
                 help="Only display errors and warnings.",
510
 
                 custom_callback=_verbosity_level_callback)
511
535
 
512
536
# Declare commonly used options
513
 
_global_option('all')
514
 
_global_option('overwrite', help='Ignore differences between branches and '
515
 
               'overwrite unconditionally.')
516
 
_global_option('basis', type=str)
517
 
_global_option('bound')
518
 
_global_option('diff-options', type=str)
 
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.')
519
544
_global_option('file', type=unicode, short_name='F')
520
 
_global_option('force')
521
 
_global_option('format', type=unicode)
522
 
_global_option('forward')
 
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')
523
552
_global_option('message', type=unicode,
524
553
               short_name='m',
525
554
               help='Message string.')
526
 
_global_option('no-recurse')
527
 
_global_option('profile',
528
 
               help='Show performance profiling information.')
 
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.')
529
563
_global_option('revision',
530
564
               type=_parse_revision_str,
531
565
               short_name='r',
532
566
               help='See "help revisionspec" for details.')
533
 
_global_option('change',
534
 
               type=_parse_change_str,
535
 
               short_name='c',
536
 
               param_name='revision',
537
 
               help='Select changes introduced by the specified revision. See also "help revisionspec".')
538
567
_global_option('show-ids',
539
568
               help='Show internal object ids.')
540
569
_global_option('timezone',
541
570
               type=str,
542
571
               help='Display timezone as local, original, or utc.')
543
 
_global_option('unbound')
544
 
_global_option('version')
545
 
_global_option('email')
546
 
_global_option('update')
547
 
_global_registry_option('log-format', "Use specified log format.",
548
 
                        lazy_registry=('bzrlib.log', 'log_formatter_registry'),
549
 
                        value_switches=True, title='Log format')
550
 
_global_option('long', help='Use detailed log format. Same as --log-format long',
551
 
               short_name='l')
552
 
_global_option('short', help='Use moderately short log format. Same as --log-format short')
553
 
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
554
 
_global_option('root', type=str)
555
 
_global_option('no-backup')
556
 
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
557
 
                        _merge_type_registry, value_switches=True,
558
 
                        title='Merge algorithm')
559
 
_global_option('pattern', type=str)
560
 
_global_option('remember', help='Remember the specified location as a'
561
 
               ' default.')
562
 
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
563
 
_global_option('kind', type=str)
564
 
_global_option('dry-run',
565
 
               help="Show what would be done, but don't actually do anything.")
566
 
_global_option('name-from-revision', help='The path name in the old tree.')
 
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'