1
# Copyright (C) 2004, 2005, 2006 by 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., 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.
23
from bzrlib.trace import warning
24
from bzrlib.revisionspec import RevisionSpec
25
from bzrlib.errors import BzrCommandError
28
def _parse_revision_str(revstr):
29
"""This handles a revision string -> revno.
31
This always returns a list. The list will have one element for
32
each revision specifier supplied.
34
>>> _parse_revision_str('234')
35
[<RevisionSpec_int 234>]
36
>>> _parse_revision_str('234..567')
37
[<RevisionSpec_int 234>, <RevisionSpec_int 567>]
38
>>> _parse_revision_str('..')
39
[<RevisionSpec None>, <RevisionSpec None>]
40
>>> _parse_revision_str('..234')
41
[<RevisionSpec None>, <RevisionSpec_int 234>]
42
>>> _parse_revision_str('234..')
43
[<RevisionSpec_int 234>, <RevisionSpec None>]
44
>>> _parse_revision_str('234..456..789') # Maybe this should be an error
45
[<RevisionSpec_int 234>, <RevisionSpec_int 456>, <RevisionSpec_int 789>]
46
>>> _parse_revision_str('234....789') #Error ?
47
[<RevisionSpec_int 234>, <RevisionSpec None>, <RevisionSpec_int 789>]
48
>>> _parse_revision_str('revid:test@other.com-234234')
49
[<RevisionSpec_revid revid:test@other.com-234234>]
50
>>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
51
[<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
52
>>> _parse_revision_str('revid:test@other.com-234234..23')
53
[<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_int 23>]
54
>>> _parse_revision_str('date:2005-04-12')
55
[<RevisionSpec_date date:2005-04-12>]
56
>>> _parse_revision_str('date:2005-04-12 12:24:33')
57
[<RevisionSpec_date date:2005-04-12 12:24:33>]
58
>>> _parse_revision_str('date:2005-04-12T12:24:33')
59
[<RevisionSpec_date date:2005-04-12T12:24:33>]
60
>>> _parse_revision_str('date:2005-04-12,12:24:33')
61
[<RevisionSpec_date date:2005-04-12,12:24:33>]
62
>>> _parse_revision_str('-5..23')
63
[<RevisionSpec_int -5>, <RevisionSpec_int 23>]
64
>>> _parse_revision_str('-5')
65
[<RevisionSpec_int -5>]
66
>>> _parse_revision_str('123a')
67
Traceback (most recent call last):
69
BzrError: No namespace registered for string: '123a'
70
>>> _parse_revision_str('abc')
71
Traceback (most recent call last):
73
BzrError: No namespace registered for string: 'abc'
74
>>> _parse_revision_str('branch:../branch2')
75
[<RevisionSpec_branch branch:../branch2>]
76
>>> _parse_revision_str('branch:../../branch2')
77
[<RevisionSpec_branch branch:../../branch2>]
78
>>> _parse_revision_str('branch:../../branch2..23')
79
[<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_int 23>]
81
# TODO: Maybe move this into revisionspec.py
82
old_format_re = re.compile('\d*:\d*')
83
m = old_format_re.match(revstr)
86
warning('Colon separator for revision numbers is deprecated.'
88
for rev in revstr.split(':'):
90
revs.append(RevisionSpec(int(rev)))
92
revs.append(RevisionSpec(None))
94
sep = re.compile("\\.\\.(?!/)")
95
for x in sep.split(revstr):
96
revs.append(RevisionSpec(x or None))
100
def _parse_merge_type(typestring):
101
return get_merge_type(typestring)
103
def get_merge_type(typestring):
104
"""Attempt to find the merge class/factory associated with a string."""
105
from merge import merge_types
107
return merge_types[typestring][0]
109
templ = '%s%%7s: %%s' % (' '*12)
110
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
111
type_list = '\n'.join(lines)
112
msg = "No known merge type %s. Supported types are:\n%s" %\
113
(typestring, type_list)
114
raise BzrCommandError(msg)
116
class EnumOption(object):
118
def __init__(self, name, factory, choices):
120
self.factory = factory
121
self.choices = choices
124
def python_name(self):
125
return self.name.lower().replace(' ', '_')
127
def add_option(self, parser, short_name):
128
"""Add this option to an Optparse parser"""
129
group = optparse.OptionGroup(parser, self.name)
130
for name, help in self.choices:
131
option_strings = ['--%s' % name]
132
group.add_option(action='callback',
133
callback=self._optparse_callback,
134
callback_args=(name,),
137
default=OptionParser.DEFAULT_VALUE,
138
dest=self.python_name(),
140
parser.add_option_group(group)
142
def _optparse_callback(self, option, opt, value, parser, evalue):
143
setattr(parser.values, option.dest, self.factory(evalue))
146
class Option(object):
147
"""Description of a command line option"""
148
# TODO: Some way to show in help a description of the option argument
153
def __init__(self, name, help='', type=None, argname=None):
154
"""Make a new command option.
156
name -- regular name of the command, used in the double-dash
157
form and also as the parameter to the command's run()
160
help -- help message displayed in command help
162
type -- function called to parse the option argument, or
163
None (default) if this option doesn't take an argument.
165
argname -- name of option argument, if any
167
# TODO: perhaps a subclass that automatically does
168
# --option, --no-option for reversible booleans
173
assert argname is None
174
elif argname is None:
176
self.argname = argname
178
def short_name(self):
179
"""Return the single character option for this command, if any.
181
Short options are globally registered.
183
for short, option in Option.SHORT_OPTIONS.iteritems():
187
def get_negation_name(self):
188
if self.name.startswith('no-'):
191
return 'no-' + self.name
193
def add_option(self, parser, short_name):
194
"""Add this option to an Optparse parser"""
195
option_strings = ['--%s' % self.name]
196
if short_name is not None:
197
option_strings.append('-%s' % short_name)
200
parser.add_option(action='store_true', dest=self.name,
202
default=OptionParser.DEFAULT_VALUE,
204
negation_strings = ['--%s' % self.get_negation_name()]
205
parser.add_option(action='store_const', dest=self.name,
206
help=optparse.SUPPRESS_HELP,
207
const=OptionParser.DEFAULT_VALUE,
210
parser.add_option(action='callback',
211
callback=self._optparse_callback,
212
type='string', metavar=self.argname,
214
default=OptionParser.DEFAULT_VALUE,
217
def _optparse_callback(self, option, opt, value, parser):
218
setattr(parser.values, self.name, self.type(value))
221
class OptionParser(optparse.OptionParser):
222
"""OptionParser that raises exceptions instead of exiting"""
224
DEFAULT_VALUE = object()
226
def error(self, message):
227
raise BzrCommandError(message)
230
def get_optparser(options):
231
"""Generate an optparse parser for bzrlib-style options"""
233
parser = OptionParser()
234
parser.remove_option('--help')
235
short_options = dict((k.name, v) for v, k in
236
Option.SHORT_OPTIONS.iteritems())
237
for option in options.itervalues():
238
option.add_option(parser, short_options.get(option.name))
242
def _global_option(name, **kwargs):
243
"""Register o as a global option."""
244
Option.OPTIONS[name] = Option(name, **kwargs)
246
Option.OPTIONS['merge-type']=EnumOption('Merge type', get_merge_type, [
247
('merge3', 'Use built-in diff3-style merge'),
248
('diff3', 'Use external diff3 merge'),
249
('weave', 'Use knit merge')])
251
Option.OPTIONS['log-format']=EnumOption('Log format', str, [
252
('long', 'Multi-line logs with merges shown'),
253
('short', 'Two-line logs'),
254
('line', 'One-line logs')])
256
_global_option('all')
257
_global_option('overwrite', help='Ignore differences between branches and '
258
'overwrite unconditionally')
259
_global_option('basis', type=str)
260
_global_option('bound')
261
_global_option('diff-options', type=str)
262
_global_option('help',
263
help='show help message')
264
_global_option('file', type=unicode)
265
_global_option('force')
266
_global_option('format', type=unicode)
267
_global_option('forward')
268
_global_option('message', type=unicode)
269
_global_option('no-recurse')
270
_global_option('prefix', type=str,
271
help='Set prefixes to added to old and new filenames, as '
272
'two values separated by a colon.')
273
_global_option('profile',
274
help='show performance profiling information')
275
_global_option('revision', type=_parse_revision_str)
276
_global_option('show-ids',
277
help='show internal object ids')
278
_global_option('timezone',
280
help='display timezone as local, original, or utc')
281
_global_option('unbound')
282
_global_option('verbose',
283
help='display more information')
284
_global_option('version')
285
_global_option('email')
286
_global_option('update')
287
_global_option('root', type=str)
288
_global_option('no-backup')
289
#_global_option('merge-type', type=_parse_merge_type,
290
# help='Select a particular merge algorithm')
291
_global_option('pattern', type=str)
292
_global_option('quiet')
293
_global_option('remember', help='Remember the specified location as a'
295
_global_option('reprocess', help='Reprocess to reduce spurious conflicts')
296
_global_option('kind', type=str)
297
_global_option('dry-run',
298
help="show what would be done, but don't actually do anything")
301
def _global_short(short_name, long_name):
302
assert short_name not in Option.SHORT_OPTIONS
303
Option.SHORT_OPTIONS[short_name] = Option.OPTIONS[long_name]
306
Option.SHORT_OPTIONS['F'] = Option.OPTIONS['file']
307
Option.SHORT_OPTIONS['h'] = Option.OPTIONS['help']
308
Option.SHORT_OPTIONS['m'] = Option.OPTIONS['message']
309
Option.SHORT_OPTIONS['r'] = Option.OPTIONS['revision']
310
Option.SHORT_OPTIONS['v'] = Option.OPTIONS['verbose']
311
#Option.SHORT_OPTIONS['l'] = Option.OPTIONS['long']
312
Option.SHORT_OPTIONS['q'] = Option.OPTIONS['quiet']
313
Option.SHORT_OPTIONS['p'] = Option.OPTIONS['prefix']