1
# Copyright (C) 2005-2010 Canonical Ltd
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
# TODO: For things like --diff-prefix, we want a way to customize the display
18
# of the option argument.
23
from bzrlib.lazy_import import lazy_import
24
lazy_import(globals(), """
33
registry as _mod_registry,
37
def _parse_revision_str(revstr):
38
"""This handles a revision string -> revno.
40
This always returns a list. The list will have one element for
41
each revision specifier supplied.
43
>>> _parse_revision_str('234')
44
[<RevisionSpec_dwim 234>]
45
>>> _parse_revision_str('234..567')
46
[<RevisionSpec_dwim 234>, <RevisionSpec_dwim 567>]
47
>>> _parse_revision_str('..')
48
[<RevisionSpec None>, <RevisionSpec None>]
49
>>> _parse_revision_str('..234')
50
[<RevisionSpec None>, <RevisionSpec_dwim 234>]
51
>>> _parse_revision_str('234..')
52
[<RevisionSpec_dwim 234>, <RevisionSpec None>]
53
>>> _parse_revision_str('234..456..789') # Maybe this should be an error
54
[<RevisionSpec_dwim 234>, <RevisionSpec_dwim 456>, <RevisionSpec_dwim 789>]
55
>>> _parse_revision_str('234....789') #Error ?
56
[<RevisionSpec_dwim 234>, <RevisionSpec None>, <RevisionSpec_dwim 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_dwim 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_dwim -5>, <RevisionSpec_dwim 23>]
73
>>> _parse_revision_str('-5')
74
[<RevisionSpec_dwim -5>]
75
>>> _parse_revision_str('123a')
76
[<RevisionSpec_dwim 123a>]
77
>>> _parse_revision_str('abc')
78
[<RevisionSpec_dwim abc>]
79
>>> _parse_revision_str('branch:../branch2')
80
[<RevisionSpec_branch branch:../branch2>]
81
>>> _parse_revision_str('branch:../../branch2')
82
[<RevisionSpec_branch branch:../../branch2>]
83
>>> _parse_revision_str('branch:../../branch2..23')
84
[<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_dwim 23>]
85
>>> _parse_revision_str('branch:..\\\\branch2')
86
[<RevisionSpec_branch branch:..\\branch2>]
87
>>> _parse_revision_str('branch:..\\\\..\\\\branch2..23')
88
[<RevisionSpec_branch branch:..\\..\\branch2>, <RevisionSpec_dwim 23>]
90
# TODO: Maybe move this into revisionspec.py
92
# split on .. that is not followed by a / or \
93
sep = re.compile(r'\.\.(?![\\/])')
94
for x in sep.split(revstr):
95
revs.append(revisionspec.RevisionSpec.from_string(x or None))
99
def _parse_change_str(revstr):
100
"""Parse the revision string and return a tuple with left-most
101
parent of the revision.
103
>>> _parse_change_str('123')
104
(<RevisionSpec_before before:123>, <RevisionSpec_dwim 123>)
105
>>> _parse_change_str('123..124')
106
Traceback (most recent call last):
108
RangeInChangeOption: Option --change does not accept revision ranges
110
revs = _parse_revision_str(revstr)
112
raise errors.RangeInChangeOption()
113
return (revisionspec.RevisionSpec.from_string('before:' + revstr),
117
def _parse_merge_type(typestring):
118
return get_merge_type(typestring)
120
def get_merge_type(typestring):
121
"""Attempt to find the merge class/factory associated with a string."""
122
from merge import merge_types
124
return merge_types[typestring][0]
126
templ = '%s%%7s: %%s' % (' '*12)
127
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
128
type_list = '\n'.join(lines)
129
msg = "No known merge type %s. Supported types are:\n%s" %\
130
(typestring, type_list)
131
raise errors.BzrCommandError(msg)
134
class Option(object):
135
"""Description of a command line option
137
:ivar _short_name: If this option has a single-letter name, this is it.
141
# The dictionary of standard options. These are always legal.
144
# The dictionary of commonly used options. these are only legal
145
# if a command explicitly references them by name in the list
146
# of supported options.
149
def __init__(self, name, help='', type=None, argname=None,
150
short_name=None, param_name=None, custom_callback=None,
152
"""Make a new command option.
154
:param name: regular name of the command, used in the double-dash
155
form and also as the parameter to the command's run()
156
method (unless param_name is specified).
158
:param help: help message displayed in command help
160
:param type: function called to parse the option argument, or
161
None (default) if this option doesn't take an argument.
163
:param argname: name of option argument, if any
165
:param short_name: short option code for use with a single -, e.g.
166
short_name="v" to enable parsing of -v.
168
:param param_name: name of the parameter which will be passed to
169
the command's run() method.
171
:param custom_callback: a callback routine to be called after normal
172
processing. The signature of the callback routine is
173
(option, name, new_value, parser).
174
:param hidden: If True, the option should be hidden in help and
180
self._short_name = short_name
183
raise ValueError('argname not valid for booleans')
184
elif argname is None:
186
self.argname = argname
187
if param_name is None:
188
self._param_name = self.name.replace('-', '_')
190
self._param_name = param_name
191
self.custom_callback = custom_callback
194
def short_name(self):
196
return self._short_name
198
def set_short_name(self, short_name):
199
self._short_name = short_name
201
def get_negation_name(self):
202
if self.name.startswith('no-'):
205
return 'no-' + self.name
207
def add_option(self, parser, short_name):
208
"""Add this option to an Optparse parser"""
209
option_strings = ['--%s' % self.name]
210
if short_name is not None:
211
option_strings.append('-%s' % short_name)
213
help = optparse.SUPPRESS_HELP
218
parser.add_option(action='callback',
219
callback=self._optparse_bool_callback,
220
callback_args=(True,),
223
negation_strings = ['--%s' % self.get_negation_name()]
224
parser.add_option(action='callback',
225
callback=self._optparse_bool_callback,
226
callback_args=(False,),
227
help=optparse.SUPPRESS_HELP, *negation_strings)
229
parser.add_option(action='callback',
230
callback=self._optparse_callback,
231
type='string', metavar=self.argname.upper(),
233
default=OptionParser.DEFAULT_VALUE,
236
def _optparse_bool_callback(self, option, opt_str, value, parser, bool_v):
237
setattr(parser.values, self._param_name, bool_v)
238
if self.custom_callback is not None:
239
self.custom_callback(option, self._param_name, bool_v, parser)
241
def _optparse_callback(self, option, opt, value, parser):
243
setattr(parser.values, self._param_name, v)
244
if self.custom_callback is not None:
245
self.custom_callback(option, self.name, v, parser)
247
def iter_switches(self):
248
"""Iterate through the list of switches provided by the option
250
:return: an iterator of (name, short_name, argname, help)
252
argname = self.argname
253
if argname is not None:
254
argname = argname.upper()
255
yield self.name, self.short_name(), argname, self.help
257
def is_hidden(self, name):
261
class ListOption(Option):
262
"""Option used to provide a list of values.
264
On the command line, arguments are specified by a repeated use of the
265
option. '-' is a special argument that resets the list. For example,
267
sets the value of the 'foo' option to ['a', 'b'], and
268
--foo=a --foo=b --foo=- --foo=c
269
sets the value of the 'foo' option to ['c'].
272
def add_option(self, parser, short_name):
273
"""Add this option to an Optparse parser."""
274
option_strings = ['--%s' % self.name]
275
if short_name is not None:
276
option_strings.append('-%s' % short_name)
277
parser.add_option(action='callback',
278
callback=self._optparse_callback,
279
type='string', metavar=self.argname.upper(),
280
help=self.help, dest=self._param_name, default=[],
283
def _optparse_callback(self, option, opt, value, parser):
284
values = getattr(parser.values, self._param_name)
288
values.append(self.type(value))
289
if self.custom_callback is not None:
290
self.custom_callback(option, self._param_name, values, parser)
293
class RegistryOption(Option):
294
"""Option based on a registry
296
The values for the options correspond to entries in the registry. Input
297
must be a registry key. After validation, it is converted into an object
298
using Registry.get or a caller-provided converter.
301
def validate_value(self, value):
302
"""Validate a value name"""
303
if value not in self.registry:
304
raise errors.BadOptionValue(self.name, value)
306
def convert(self, value):
307
"""Convert a value name into an output type"""
308
self.validate_value(value)
309
if self.converter is None:
310
return self.registry.get(value)
312
return self.converter(value)
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):
320
:param name: The option name.
321
:param help: Help for the option.
322
:param registry: A Registry containing the values
323
:param converter: Callable to invoke with the value name to produce
324
the value. If not supplied, self.registry.get is used.
325
:param value_switches: If true, each possible value is assigned its
326
own switch. For example, instead of '--format knit',
327
'--knit' can be used interchangeably.
328
:param enum_switch: If true, a switch is provided with the option name,
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
335
Option.__init__(self, name, help, type=self.convert,
336
short_name=short_name)
337
self._registry = registry
339
if lazy_registry is None:
340
raise AssertionError(
341
'One of registry or lazy_registry must be given.')
342
self._lazy_registry = _mod_registry._LazyObjectGetter(
344
if registry is not None and lazy_registry is not None:
345
raise AssertionError(
346
'registry and lazy_registry are mutually exclusive')
348
self.converter = converter
349
self.value_switches = value_switches
350
self.enum_switch = enum_switch
351
self.short_value_switches = short_value_switches
353
if self.title is None:
358
if self._registry is None:
359
self._registry = self._lazy_registry.get_obj()
360
return self._registry
363
def from_kwargs(name_, help=None, title=None, value_switches=False,
364
enum_switch=True, **kwargs):
365
"""Convenience method to generate string-map registry options
367
name, help, value_switches and enum_switch are passed to the
368
RegistryOption constructor. Any other keyword arguments are treated
369
as values for the option, and their value is treated as the help.
371
reg = _mod_registry.Registry()
372
for name, switch_help in sorted(kwargs.items()):
373
name = name.replace('_', '-')
374
reg.register(name, name, help=switch_help)
375
if not value_switches:
376
help = help + ' "' + name + '": ' + switch_help
377
if not help.endswith("."):
379
return RegistryOption(name_, help, reg, title=title,
380
value_switches=value_switches, enum_switch=enum_switch)
382
def add_option(self, parser, short_name):
383
"""Add this option to an Optparse parser"""
384
if self.value_switches:
385
parser = parser.add_option_group(self.title)
387
Option.add_option(self, parser, short_name)
388
if self.value_switches:
389
for key in self.registry.keys():
390
option_strings = ['--%s' % key]
391
if self.is_hidden(key):
392
help = optparse.SUPPRESS_HELP
394
help = self.registry.get_help(key)
395
if (self.short_value_switches and
396
key in self.short_value_switches):
397
option_strings.append('-%s' %
398
self.short_value_switches[key])
399
parser.add_option(action='callback',
400
callback=self._optparse_value_callback(key),
404
def _optparse_value_callback(self, cb_value):
405
def cb(option, opt, value, parser):
406
v = self.type(cb_value)
407
setattr(parser.values, self._param_name, v)
408
if self.custom_callback is not None:
409
self.custom_callback(option, self._param_name, v, parser)
412
def iter_switches(self):
413
"""Iterate through the list of switches provided by the option
415
:return: an iterator of (name, short_name, argname, help)
417
for value in Option.iter_switches(self):
419
if self.value_switches:
420
for key in sorted(self.registry.keys()):
421
yield key, None, None, self.registry.get_help(key)
423
def is_hidden(self, name):
424
if name == self.name:
425
return Option.is_hidden(self, name)
426
return getattr(self.registry.get_info(name), 'hidden', False)
429
class OptionParser(optparse.OptionParser):
430
"""OptionParser that raises exceptions instead of exiting"""
432
DEFAULT_VALUE = object()
435
optparse.OptionParser.__init__(self)
436
self.formatter = GettextIndentedHelpFormatter()
438
def error(self, message):
439
raise errors.BzrCommandError(message)
442
class GettextIndentedHelpFormatter(optparse.IndentedHelpFormatter):
443
"""Adds gettext() call to format_option()"""
445
optparse.IndentedHelpFormatter.__init__(self)
447
def format_option(self, option):
448
"""code taken from Python's optparse.py"""
450
option.help = i18n.gettext(option.help)
451
return optparse.IndentedHelpFormatter.format_option(self, option)
454
def get_optparser(options):
455
"""Generate an optparse parser for bzrlib-style options"""
457
parser = OptionParser()
458
parser.remove_option('--help')
459
for option in options.itervalues():
460
option.add_option(parser, option.short_name())
464
def custom_help(name, help):
465
"""Clone a common option overriding the help."""
467
o = copy.copy(Option.OPTIONS[name])
472
def _standard_option(name, **kwargs):
473
"""Register a standard option."""
474
# All standard options are implicitly 'global' ones
475
Option.STD_OPTIONS[name] = Option(name, **kwargs)
476
Option.OPTIONS[name] = Option.STD_OPTIONS[name]
478
def _standard_list_option(name, **kwargs):
479
"""Register a standard option."""
480
# All standard options are implicitly 'global' ones
481
Option.STD_OPTIONS[name] = ListOption(name, **kwargs)
482
Option.OPTIONS[name] = Option.STD_OPTIONS[name]
485
def _global_option(name, **kwargs):
486
"""Register a global option."""
487
Option.OPTIONS[name] = Option(name, **kwargs)
490
def _global_registry_option(name, help, registry=None, **kwargs):
491
Option.OPTIONS[name] = RegistryOption(name, help, registry, **kwargs)
494
# This is the verbosity level detected during command line parsing.
495
# Note that the final value is dependent on the order in which the
496
# various flags (verbose, quiet, no-verbose, no-quiet) are given.
497
# The final value will be one of the following:
505
def _verbosity_level_callback(option, opt_str, value, parser):
506
global _verbosity_level
508
# Either --no-verbose or --no-quiet was specified
510
elif opt_str == "verbose":
511
if _verbosity_level > 0:
512
_verbosity_level += 1
516
if _verbosity_level < 0:
517
_verbosity_level -= 1
519
_verbosity_level = -1
522
class MergeTypeRegistry(_mod_registry.Registry):
527
_merge_type_registry = MergeTypeRegistry()
528
_merge_type_registry.register_lazy('diff3', 'bzrlib.merge', 'Diff3Merger',
529
"Merge using external diff3")
530
_merge_type_registry.register_lazy('lca', 'bzrlib.merge', 'LCAMerger',
532
_merge_type_registry.register_lazy('merge3', 'bzrlib.merge', 'Merge3Merger',
533
"Native diff3-style merge")
534
_merge_type_registry.register_lazy('weave', 'bzrlib.merge', 'WeaveMerger',
537
# Declare the standard options
538
_standard_option('help', short_name='h',
539
help='Show help message.')
540
_standard_option('quiet', short_name='q',
541
help="Only display errors and warnings.",
542
custom_callback=_verbosity_level_callback)
543
_standard_option('usage',
544
help='Show usage message and options.')
545
_standard_option('verbose', short_name='v',
546
help='Display more information.',
547
custom_callback=_verbosity_level_callback)
549
# Declare commonly used options
550
_global_option('all')
551
_global_option('basis', type=str)
552
_global_option('bound')
553
_global_option('change',
554
type=_parse_change_str,
556
param_name='revision',
557
help='Select changes introduced by the specified revision. See also "help revisionspec".')
558
_global_option('diff-options', type=str)
559
_global_option('directory', short_name='d', type=unicode,
560
help='Branch to operate on, instead of working directory')
561
_global_option('dry-run',
562
help="Show what would be done, but don't actually do anything.")
563
_global_option('email')
564
_global_option('file', type=unicode, short_name='F')
565
_global_option('force')
566
_global_option('format', type=unicode)
567
_global_option('forward')
568
_global_option('kind', type=str)
569
_global_option('line', help='Use log format with one line per revision.'
570
' Same as --log-format line')
571
_global_registry_option('log-format', "Use specified log format.",
572
lazy_registry=('bzrlib.log', 'log_formatter_registry'),
573
value_switches=True, title='Log format',
574
short_value_switches={'short': 'S'})
575
_global_option('long', help='Use detailed log format.'
576
' Same as --log-format long',
578
_global_registry_option('merge-type', 'Select a particular merge algorithm.',
579
_merge_type_registry, value_switches=True,
580
title='Merge algorithm')
581
_global_option('message', type=unicode,
583
help='Message string.')
584
_global_option('name-from-revision', help='The path name in the old tree.')
585
_global_option('no-backup')
586
_global_option('no-recurse')
587
_global_option('null', short_name='0',
588
help='Use an ASCII NUL (\\0) separator rather than '
590
_global_option('overwrite', help='Ignore differences between branches and '
591
'overwrite unconditionally.')
592
_global_option('pattern', type=str)
593
_global_option('profile',
594
help='Show performance profiling information.')
595
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
596
_global_option('remember', help='Remember the specified location as a'
598
_global_option('revision',
599
type=_parse_revision_str,
601
help='See "help revisionspec" for details.')
602
_global_option('short', help='Use moderately short log format.'
603
' Same as --log-format short')
604
_global_option('show-ids',
605
help='Show internal object ids.')
606
_global_option('timezone',
608
help='Display timezone as local, original, or utc.')
609
_global_option('root', type=str)
610
_global_option('unbound')
611
_global_option('update')
612
_global_option('version')
614
diff_writer_registry = _mod_registry.Registry()
615
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')
616
diff_writer_registry.default_key = 'plain'