~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/option.py

  • Committer: Aaron Bentley
  • Date: 2006-11-10 01:55:55 UTC
  • mto: This revision was merged to the branch mainline in revision 2127.
  • Revision ID: aaron.bentley@utoronto.ca-20061110015555-f48202744b630209
Ignore html docs (both kinds)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 by Canonical Ltd
2
 
 
 
1
# Copyright (C) 2004, 2005, 2006 Canonical Ltd
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
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.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
 
17
# TODO: For things like --diff-prefix, we want a way to customize the display
 
18
# of the option argument.
17
19
 
18
20
import re
19
21
 
20
 
import bzrlib.commands
21
 
from bzrlib.trace import warning, mutter
22
 
from bzrlib.revisionspec import RevisionSpec
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
import optparse
 
25
 
 
26
from bzrlib import (
 
27
    errors,
 
28
    revisionspec,
 
29
    )
 
30
""")
 
31
from bzrlib.trace import warning
23
32
 
24
33
 
25
34
def _parse_revision_str(revstr):
29
38
    each revision specifier supplied.
30
39
 
31
40
    >>> _parse_revision_str('234')
32
 
    [<RevisionSpec_int 234>]
 
41
    [<RevisionSpec_revno 234>]
33
42
    >>> _parse_revision_str('234..567')
34
 
    [<RevisionSpec_int 234>, <RevisionSpec_int 567>]
 
43
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
35
44
    >>> _parse_revision_str('..')
36
45
    [<RevisionSpec None>, <RevisionSpec None>]
37
46
    >>> _parse_revision_str('..234')
38
 
    [<RevisionSpec None>, <RevisionSpec_int 234>]
 
47
    [<RevisionSpec None>, <RevisionSpec_revno 234>]
39
48
    >>> _parse_revision_str('234..')
40
 
    [<RevisionSpec_int 234>, <RevisionSpec None>]
 
49
    [<RevisionSpec_revno 234>, <RevisionSpec None>]
41
50
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
42
 
    [<RevisionSpec_int 234>, <RevisionSpec_int 456>, <RevisionSpec_int 789>]
 
51
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
43
52
    >>> _parse_revision_str('234....789') #Error ?
44
 
    [<RevisionSpec_int 234>, <RevisionSpec None>, <RevisionSpec_int 789>]
 
53
    [<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
45
54
    >>> _parse_revision_str('revid:test@other.com-234234')
46
55
    [<RevisionSpec_revid revid:test@other.com-234234>]
47
56
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
48
57
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revid revid:test@other.com-234235>]
49
58
    >>> _parse_revision_str('revid:test@other.com-234234..23')
50
 
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_int 23>]
 
59
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
51
60
    >>> _parse_revision_str('date:2005-04-12')
52
61
    [<RevisionSpec_date date:2005-04-12>]
53
62
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
57
66
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
58
67
    [<RevisionSpec_date date:2005-04-12,12:24:33>]
59
68
    >>> _parse_revision_str('-5..23')
60
 
    [<RevisionSpec_int -5>, <RevisionSpec_int 23>]
 
69
    [<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
61
70
    >>> _parse_revision_str('-5')
62
 
    [<RevisionSpec_int -5>]
 
71
    [<RevisionSpec_revno -5>]
63
72
    >>> _parse_revision_str('123a')
64
73
    Traceback (most recent call last):
65
74
      ...
66
 
    BzrError: No namespace registered for string: '123a'
 
75
    NoSuchRevisionSpec: No namespace registered for string: '123a'
67
76
    >>> _parse_revision_str('abc')
68
77
    Traceback (most recent call last):
69
78
      ...
70
 
    BzrError: No namespace registered for string: 'abc'
 
79
    NoSuchRevisionSpec: No namespace registered for string: 'abc'
71
80
    >>> _parse_revision_str('branch:../branch2')
72
81
    [<RevisionSpec_branch branch:../branch2>]
 
82
    >>> _parse_revision_str('branch:../../branch2')
 
83
    [<RevisionSpec_branch branch:../../branch2>]
 
84
    >>> _parse_revision_str('branch:../../branch2..23')
 
85
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 23>]
73
86
    """
74
87
    # TODO: Maybe move this into revisionspec.py
75
 
    old_format_re = re.compile('\d*:\d*')
76
 
    m = old_format_re.match(revstr)
77
88
    revs = []
78
 
    if m:
79
 
        warning('Colon separator for revision numbers is deprecated.'
80
 
                ' Use .. instead')
81
 
        for rev in revstr.split(':'):
82
 
            if rev:
83
 
                revs.append(RevisionSpec(int(rev)))
84
 
            else:
85
 
                revs.append(RevisionSpec(None))
86
 
    else:
87
 
        next_prefix = None
88
 
        for x in revstr.split('..'):
89
 
            if not x:
90
 
                revs.append(RevisionSpec(None))
91
 
            elif x[-1] == ':':
92
 
                # looks like a namespace:.. has happened
93
 
                next_prefix = x + '..'
94
 
            else:
95
 
                if next_prefix is not None:
96
 
                    x = next_prefix + x
97
 
                revs.append(RevisionSpec(x))
98
 
                next_prefix = None
99
 
        if next_prefix is not None:
100
 
            revs.append(RevisionSpec(next_prefix))
 
89
    # split on the first .. that is not followed by a / ?
 
90
    sep = re.compile("\\.\\.(?!/)")
 
91
    for x in sep.split(revstr):
 
92
        revs.append(revisionspec.RevisionSpec.from_string(x or None))
101
93
    return revs
102
94
 
103
95
 
104
96
def _parse_merge_type(typestring):
105
 
    return bzrlib.commands.get_merge_type(typestring)
 
97
    return get_merge_type(typestring)
106
98
 
 
99
def get_merge_type(typestring):
 
100
    """Attempt to find the merge class/factory associated with a string."""
 
101
    from merge import merge_types
 
102
    try:
 
103
        return merge_types[typestring][0]
 
104
    except KeyError:
 
105
        templ = '%s%%7s: %%s' % (' '*12)
 
106
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
107
        type_list = '\n'.join(lines)
 
108
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
109
            (typestring, type_list)
 
110
        raise errors.BzrCommandError(msg)
107
111
 
108
112
class Option(object):
109
113
    """Description of a command line option"""
127
131
        argname -- name of option argument, if any
128
132
        """
129
133
        # TODO: perhaps a subclass that automatically does 
130
 
        # --option, --no-option for reversable booleans
 
134
        # --option, --no-option for reversible booleans
131
135
        self.name = name
132
136
        self.help = help
133
137
        self.type = type
142
146
 
143
147
        Short options are globally registered.
144
148
        """
145
 
        return Option.SHORT_OPTIONS.get(self.name)
 
149
        for short, option in Option.SHORT_OPTIONS.iteritems():
 
150
            if option is self:
 
151
                return short
 
152
 
 
153
    def get_negation_name(self):
 
154
        if self.name.startswith('no-'):
 
155
            return self.name[3:]
 
156
        else:
 
157
            return 'no-' + self.name
 
158
 
 
159
    def add_option(self, parser, short_name):
 
160
        """Add this option to an Optparse parser"""
 
161
        option_strings = ['--%s' % self.name]
 
162
        if short_name is not None:
 
163
            option_strings.append('-%s' % short_name)
 
164
        optargfn = self.type
 
165
        if optargfn is None:
 
166
            parser.add_option(action='store_true', dest=self.name, 
 
167
                              help=self.help,
 
168
                              default=OptionParser.DEFAULT_VALUE,
 
169
                              *option_strings)
 
170
            negation_strings = ['--%s' % self.get_negation_name()]
 
171
            parser.add_option(action='store_false', dest=self.name, 
 
172
                              help=optparse.SUPPRESS_HELP, *negation_strings)
 
173
        else:
 
174
            parser.add_option(action='callback', 
 
175
                              callback=self._optparse_callback, 
 
176
                              type='string', metavar=self.argname.upper(),
 
177
                              help=self.help,
 
178
                              default=OptionParser.DEFAULT_VALUE, 
 
179
                              *option_strings)
 
180
 
 
181
    def _optparse_callback(self, option, opt, value, parser):
 
182
        setattr(parser.values, self.name, self.type(value))
 
183
 
 
184
    def iter_switches(self):
 
185
        """Iterate through the list of switches provided by the option
 
186
        
 
187
        :return: an iterator of (name, short_name, argname, help)
 
188
        """
 
189
        argname =  self.argname
 
190
        if argname is not None:
 
191
            argname = argname.upper()
 
192
        yield self.name, self.short_name(), argname, self.help
 
193
 
 
194
 
 
195
class OptionParser(optparse.OptionParser):
 
196
    """OptionParser that raises exceptions instead of exiting"""
 
197
 
 
198
    DEFAULT_VALUE = object()
 
199
 
 
200
    def error(self, message):
 
201
        raise errors.BzrCommandError(message)
 
202
 
 
203
 
 
204
def get_optparser(options):
 
205
    """Generate an optparse parser for bzrlib-style options"""
 
206
 
 
207
    parser = OptionParser()
 
208
    parser.remove_option('--help')
 
209
    short_options = dict((k.name, v) for v, k in 
 
210
                         Option.SHORT_OPTIONS.iteritems())
 
211
    for option in options.itervalues():
 
212
        option.add_option(parser, short_options.get(option.name))
 
213
    return parser
146
214
 
147
215
 
148
216
def _global_option(name, **kwargs):
150
218
    Option.OPTIONS[name] = Option(name, **kwargs)
151
219
 
152
220
_global_option('all')
153
 
_global_option('clobber')
 
221
_global_option('overwrite', help='Ignore differences between branches and '
 
222
               'overwrite unconditionally')
154
223
_global_option('basis', type=str)
 
224
_global_option('bound')
155
225
_global_option('diff-options', type=str)
156
226
_global_option('help',
157
227
               help='show help message')
161
231
_global_option('forward')
162
232
_global_option('message', type=unicode)
163
233
_global_option('no-recurse')
 
234
_global_option('prefix', type=str, 
 
235
               help='Set prefixes to added to old and new filenames, as '
 
236
                    'two values separated by a colon.')
164
237
_global_option('profile',
165
238
               help='show performance profiling information')
166
239
_global_option('revision', type=_parse_revision_str)
167
 
_global_option('short')
168
240
_global_option('show-ids', 
169
241
               help='show internal object ids')
170
242
_global_option('timezone', 
171
243
               type=str,
172
244
               help='display timezone as local, original, or utc')
 
245
_global_option('unbound')
173
246
_global_option('verbose',
174
247
               help='display more information')
175
248
_global_option('version')
176
249
_global_option('email')
177
250
_global_option('update')
178
 
_global_option('long')
 
251
_global_option('log-format', type=str, help="Use this log format")
 
252
_global_option('long', help='Use detailed log format. Same as --log-format long')
 
253
_global_option('short', help='Use moderately short log format. Same as --log-format short')
 
254
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
179
255
_global_option('root', type=str)
180
256
_global_option('no-backup')
181
 
_global_option('merge-type', type=_parse_merge_type)
 
257
_global_option('merge-type', type=_parse_merge_type, 
 
258
               help='Select a particular merge algorithm')
182
259
_global_option('pattern', type=str)
183
260
_global_option('quiet')
184
 
_global_option('remember')
 
261
_global_option('remember', help='Remember the specified location as a'
 
262
               ' default.')
 
263
_global_option('reprocess', help='Reprocess to reduce spurious conflicts')
 
264
_global_option('kind', type=str)
 
265
_global_option('dry-run',
 
266
               help="show what would be done, but don't actually do anything")
 
267
_global_option('name-from-revision', help='The path name in the old tree.')
185
268
 
186
269
 
187
270
def _global_short(short_name, long_name):
196
279
Option.SHORT_OPTIONS['v'] = Option.OPTIONS['verbose']
197
280
Option.SHORT_OPTIONS['l'] = Option.OPTIONS['long']
198
281
Option.SHORT_OPTIONS['q'] = Option.OPTIONS['quiet']
 
282
Option.SHORT_OPTIONS['p'] = Option.OPTIONS['prefix']