1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd
1
# Copyright (C) 2004, 2005 by Canonical Ltd
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
# TODO: For things like --diff-prefix, we want a way to customize the display
18
# of the option argument.
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
32
from bzrlib.trace import warning
20
import bzrlib.commands
21
from bzrlib.trace import warning, mutter
22
from bzrlib.revisionspec import RevisionSpec
35
25
def _parse_revision_str(revstr):
39
29
each revision specifier supplied.
41
31
>>> _parse_revision_str('234')
42
[<RevisionSpec_revno 234>]
32
[<RevisionSpec_int 234>]
43
33
>>> _parse_revision_str('234..567')
44
[<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
34
[<RevisionSpec_int 234>, <RevisionSpec_int 567>]
45
35
>>> _parse_revision_str('..')
46
36
[<RevisionSpec None>, <RevisionSpec None>]
47
37
>>> _parse_revision_str('..234')
48
[<RevisionSpec None>, <RevisionSpec_revno 234>]
38
[<RevisionSpec None>, <RevisionSpec_int 234>]
49
39
>>> _parse_revision_str('234..')
50
[<RevisionSpec_revno 234>, <RevisionSpec None>]
40
[<RevisionSpec_int 234>, <RevisionSpec None>]
51
41
>>> _parse_revision_str('234..456..789') # Maybe this should be an error
52
[<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
42
[<RevisionSpec_int 234>, <RevisionSpec_int 456>, <RevisionSpec_int 789>]
53
43
>>> _parse_revision_str('234....789') #Error ?
54
[<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
44
[<RevisionSpec_int 234>, <RevisionSpec None>, <RevisionSpec_int 789>]
55
45
>>> _parse_revision_str('revid:test@other.com-234234')
56
46
[<RevisionSpec_revid revid:test@other.com-234234>]
57
47
>>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
58
48
[<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
59
49
>>> _parse_revision_str('revid:test@other.com-234234..23')
60
[<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
50
[<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_int 23>]
61
51
>>> _parse_revision_str('date:2005-04-12')
62
52
[<RevisionSpec_date date:2005-04-12>]
63
53
>>> _parse_revision_str('date:2005-04-12 12:24:33')
67
57
>>> _parse_revision_str('date:2005-04-12,12:24:33')
68
58
[<RevisionSpec_date date:2005-04-12,12:24:33>]
69
59
>>> _parse_revision_str('-5..23')
70
[<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
60
[<RevisionSpec_int -5>, <RevisionSpec_int 23>]
71
61
>>> _parse_revision_str('-5')
72
[<RevisionSpec_revno -5>]
62
[<RevisionSpec_int -5>]
73
63
>>> _parse_revision_str('123a')
74
64
Traceback (most recent call last):
76
NoSuchRevisionSpec: No namespace registered for string: '123a'
66
BzrError: No namespace registered for string: '123a'
77
67
>>> _parse_revision_str('abc')
78
68
Traceback (most recent call last):
80
NoSuchRevisionSpec: No namespace registered for string: 'abc'
70
BzrError: No namespace registered for string: 'abc'
81
71
>>> _parse_revision_str('branch:../branch2')
82
72
[<RevisionSpec_branch branch:../branch2>]
83
>>> _parse_revision_str('branch:../../branch2')
84
[<RevisionSpec_branch branch:../../branch2>]
85
>>> _parse_revision_str('branch:../../branch2..23')
86
[<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 23>]
88
74
# TODO: Maybe move this into revisionspec.py
75
old_format_re = re.compile('\d*:\d*')
76
m = old_format_re.match(revstr)
90
# split on the first .. that is not followed by a / ?
91
sep = re.compile("\\.\\.(?!/)")
92
for x in sep.split(revstr):
93
revs.append(revisionspec.RevisionSpec.from_string(x or None))
79
warning('Colon separator for revision numbers is deprecated.'
81
for rev in revstr.split(':'):
83
revs.append(RevisionSpec(int(rev)))
85
revs.append(RevisionSpec(None))
88
for x in revstr.split('..'):
90
revs.append(RevisionSpec(None))
92
# looks like a namespace:.. has happened
93
next_prefix = x + '..'
95
if next_prefix is not None:
97
revs.append(RevisionSpec(x))
99
if next_prefix is not None:
100
revs.append(RevisionSpec(next_prefix))
97
104
def _parse_merge_type(typestring):
98
return get_merge_type(typestring)
100
def get_merge_type(typestring):
101
"""Attempt to find the merge class/factory associated with a string."""
102
from merge import merge_types
104
return merge_types[typestring][0]
106
templ = '%s%%7s: %%s' % (' '*12)
107
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
108
type_list = '\n'.join(lines)
109
msg = "No known merge type %s. Supported types are:\n%s" %\
110
(typestring, type_list)
111
raise errors.BzrCommandError(msg)
105
return bzrlib.commands.get_merge_type(typestring)
114
108
class Option(object):
115
"""Description of a command line option
117
:ivar _short_name: If this option has a single-letter name, this is it.
109
"""Description of a command line option"""
121
110
# TODO: Some way to show in help a description of the option argument
125
def __init__(self, name, help='', type=None, argname=None,
115
def __init__(self, name, help='', type=None, argname=None):
127
116
"""Make a new command option.
129
118
name -- regular name of the command, used in the double-dash
148
138
self.argname = argname
150
140
def short_name(self):
152
return self._short_name
154
# remove this when SHORT_OPTIONS is removed
155
# XXX: This is accessing a DeprecatedDict, so we call the super
156
# method to avoid warnings
157
for (k, v) in dict.iteritems(Option.SHORT_OPTIONS):
161
def set_short_name(self, short_name):
162
self._short_name = short_name
164
def get_negation_name(self):
165
if self.name.startswith('no-'):
168
return 'no-' + self.name
170
def add_option(self, parser, short_name):
171
"""Add this option to an Optparse parser"""
172
option_strings = ['--%s' % self.name]
173
if short_name is not None:
174
option_strings.append('-%s' % short_name)
177
parser.add_option(action='store_true', dest=self.name,
179
default=OptionParser.DEFAULT_VALUE,
181
negation_strings = ['--%s' % self.get_negation_name()]
182
parser.add_option(action='store_false', dest=self.name,
183
help=optparse.SUPPRESS_HELP, *negation_strings)
185
parser.add_option(action='callback',
186
callback=self._optparse_callback,
187
type='string', metavar=self.argname.upper(),
189
default=OptionParser.DEFAULT_VALUE,
192
def _optparse_callback(self, option, opt, value, parser):
193
setattr(parser.values, self.name, self.type(value))
195
def iter_switches(self):
196
"""Iterate through the list of switches provided by the option
198
:return: an iterator of (name, short_name, argname, help)
200
argname = self.argname
201
if argname is not None:
202
argname = argname.upper()
203
yield self.name, self.short_name(), argname, self.help
206
class RegistryOption(Option):
207
"""Option based on a registry
209
The values for the options correspond to entries in the registry. Input
210
must be a registry key. After validation, it is converted into an object
211
using Registry.get or a caller-provided converter.
214
def validate_value(self, value):
215
"""Validate a value name"""
216
if value not in self.registry:
217
raise errors.BadOptionValue(self.name, value)
219
def convert(self, value):
220
"""Convert a value name into an output type"""
221
self.validate_value(value)
222
if self.converter is None:
223
return self.registry.get(value)
225
return self.converter(value)
227
def __init__(self, name, help, registry, converter=None,
228
value_switches=False):
232
:param name: The option name.
233
:param help: Help for the option.
234
:param registry: A Registry containing the values
235
:param converter: Callable to invoke with the value name to produce
236
the value. If not supplied, self.registry.get is used.
237
:param value_switches: If true, each possible value is assigned its
238
own switch. For example, instead of '--format metaweave',
239
'--metaweave' can be used interchangeably.
241
Option.__init__(self, name, help, type=self.convert)
242
self.registry = registry
244
self.converter = converter
245
self.value_switches = value_switches
247
def add_option(self, parser, short_name):
248
"""Add this option to an Optparse parser"""
249
Option.add_option(self, parser, short_name)
250
if self.value_switches:
251
for key in self.registry.keys():
252
option_strings = ['--%s' % key]
253
parser.add_option(action='callback',
254
callback=self._optparse_value_callback(key),
255
help=self.registry.get_help(key),
258
def _optparse_value_callback(self, cb_value):
259
def cb(option, opt, value, parser):
260
setattr(parser.values, self.name, self.type(cb_value))
263
def iter_switches(self):
264
"""Iterate through the list of switches provided by the option
266
:return: an iterator of (name, short_name, argname, help)
268
for value in Option.iter_switches(self):
270
if self.value_switches:
271
for key in sorted(self.registry.keys()):
272
yield key, None, None, self.registry.get_help(key)
275
class OptionParser(optparse.OptionParser):
276
"""OptionParser that raises exceptions instead of exiting"""
278
DEFAULT_VALUE = object()
280
def error(self, message):
281
raise errors.BzrCommandError(message)
284
def get_optparser(options):
285
"""Generate an optparse parser for bzrlib-style options"""
287
parser = OptionParser()
288
parser.remove_option('--help')
289
for option in options.itervalues():
290
option.add_option(parser, option.short_name())
141
"""Return the single character option for this command, if any.
143
Short options are globally registered.
145
return Option.SHORT_OPTIONS.get(self.name)
294
148
def _global_option(name, **kwargs):
296
150
Option.OPTIONS[name] = Option(name, **kwargs)
298
152
_global_option('all')
299
_global_option('overwrite', help='Ignore differences between branches and '
300
'overwrite unconditionally')
153
_global_option('clobber')
301
154
_global_option('basis', type=str)
302
_global_option('bound')
303
155
_global_option('diff-options', type=str)
304
156
_global_option('help',
305
help='show help message',
307
_global_option('file', type=unicode, short_name='F')
157
help='show help message')
158
_global_option('file', type=unicode)
308
159
_global_option('force')
309
160
_global_option('format', type=unicode)
310
161
_global_option('forward')
311
_global_option('message', type=unicode,
162
_global_option('message', type=unicode)
313
163
_global_option('no-recurse')
314
164
_global_option('profile',
315
165
help='show performance profiling information')
316
_global_option('revision',
317
type=_parse_revision_str,
319
help='See \'help revisionspec\' for details')
166
_global_option('revision', type=_parse_revision_str)
167
_global_option('short')
320
168
_global_option('show-ids',
321
169
help='show internal object ids')
322
170
_global_option('timezone',
324
172
help='display timezone as local, original, or utc')
325
_global_option('unbound')
326
173
_global_option('verbose',
327
help='display more information',
174
help='display more information')
329
175
_global_option('version')
330
176
_global_option('email')
331
177
_global_option('update')
332
_global_option('log-format', type=str, help="Use this log format")
333
_global_option('long', help='Use detailed log format. Same as --log-format long',
335
_global_option('short', help='Use moderately short log format. Same as --log-format short')
336
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
178
_global_option('long')
337
179
_global_option('root', type=str)
338
180
_global_option('no-backup')
339
_global_option('merge-type', type=_parse_merge_type,
340
help='Select a particular merge algorithm')
181
_global_option('merge-type', type=_parse_merge_type)
341
182
_global_option('pattern', type=str)
342
_global_option('quiet', short_name='q')
343
_global_option('remember', help='Remember the specified location as a'
345
_global_option('reprocess', help='Reprocess to reduce spurious conflicts')
346
_global_option('kind', type=str)
347
_global_option('dry-run',
348
help="show what would be done, but don't actually do anything")
349
_global_option('name-from-revision', help='The path name in the old tree.')
352
# prior to 0.14 these were always globally registered; the old dict is
353
# available for plugins that use it but it should not be used.
354
Option.SHORT_OPTIONS = symbol_versioning.DeprecatedDict(
355
symbol_versioning.zero_fourteen,
358
'F': Option.OPTIONS['file'],
359
'h': Option.OPTIONS['help'],
360
'm': Option.OPTIONS['message'],
361
'r': Option.OPTIONS['revision'],
362
'v': Option.OPTIONS['verbose'],
363
'l': Option.OPTIONS['long'],
364
'q': Option.OPTIONS['quiet'],
366
'Set the short option name when constructing the Option.',
183
_global_option('quiet')
184
_global_option('remember')
187
def _global_short(short_name, long_name):
188
assert short_name not in Option.SHORT_OPTIONS
189
Option.SHORT_OPTIONS[short_name] = Option.OPTIONS[long_name]
192
Option.SHORT_OPTIONS['F'] = Option.OPTIONS['file']
193
Option.SHORT_OPTIONS['h'] = Option.OPTIONS['help']
194
Option.SHORT_OPTIONS['m'] = Option.OPTIONS['message']
195
Option.SHORT_OPTIONS['r'] = Option.OPTIONS['revision']
196
Option.SHORT_OPTIONS['v'] = Option.OPTIONS['verbose']
197
Option.SHORT_OPTIONS['l'] = Option.OPTIONS['long']
198
Option.SHORT_OPTIONS['q'] = Option.OPTIONS['quiet']