/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/option.py

  • Committer: v.ladeuil+lp at free
  • Date: 2006-10-12 14:29:32 UTC
  • mto: (2145.1.1 keepalive)
  • mto: This revision was merged to the branch mainline in revision 2146.
  • Revision ID: v.ladeuil+lp@free.fr-20061012142932-7221fe16d2b48fa3
Shuffle http related test code. Hopefully it ends up at the right place :)

* bzrlib/tests/HttpServer.py: 
New file. bzrlib.tests.ChrootedTestCase use HttpServer. So the
class can't be defined in bzrlib.tests.HTTPUtils because it
creates a circular dependency (bzrlib.tests.HTTPUtils needs to
import bzrlib.tests).

* bzrlib/transport/http/_urllib.py: 
Transfer test server definition to bzrlib.tests.HttpServer. Clean
up imports.

* bzrlib/transport/http/_pycurl.py: 
Transfer test server definition to bzrlib.tests.HttpServer. Clean
up imports.

* bzrlib/transport/http/__init__.py: 
Transfer all test related code to either bzrlib.tests.HttpServer
and bzrlib.tests.HTTPUtils.
Fix all use of TransportNotPossible and InvalidURL by prefixing it
by 'errors.' (this seems to be the preferred way in the rest of
bzr).
Get rid of unused imports.

* bzrlib/tests/test_transport.py:
(ReadonlyDecoratorTransportTest.test_local_parameters,
FakeNFSDecoratorTests.test_http_parameters): Use HttpServer from
bzrlib.tests.HttpServer instead of bzrlib.transport.http.

* bzrlib/tests/test_sftp_transport.py:
(set_test_transport_to_sftp): Use HttpServer from
bzrlib.tests.HttpServer instead of bzrlib.transport.http.

* bzrlib/tests/test_selftest.py:
(TestTestCaseWithTransport.test_get_readonly_url_http): Use
HttpServer from bzrlib.tests.HttpServer instead of
bzrlib.transport.http.

* bzrlib/tests/test_repository.py: 
Does *not* use HttpServer.

* bzrlib/tests/test_http.py: 
Build on top of bzrlib.tests.HttpServer and bzrlib.tests.HTTPUtils
instead of bzrlib.transport.http.

* bzrlib/tests/test_bzrdir.py:
(ChrootedTests.setUp): Use HttpServer from bzrlib.tests.HttpServer
instead of bzrlib.transport.http.

* bzrlib/tests/branch_implementations/test_http.py:
(HTTPBranchTests.setUp): Use HttpServer from bzrlib.tests.HttpServer
instead of bzrlib.transport.http.

* bzrlib/tests/branch_implementations/test_branch.py:
(ChrootedTests.setUp): Use HttpServer from bzrlib.tests.HttpServer
instead of bzrlib.transport.http.

* bzrlib/tests/__init__.py:
(ChrootedTestCase.setUp): Use HttpServer from
bzrlib.tests.HttpServer instead of bzrlib.transport.http.

Show diffs side-by-side

added added

removed removed

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