/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
1
# Copyright (C) 2004, 2005, 2006 by Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
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
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
17
# TODO: For things like --diff-prefix, we want a way to customize the display
18
# of the option argument.
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
19
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
20
import optparse
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
21
import re
22
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
23
from bzrlib.trace import warning
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
24
from bzrlib.revisionspec import RevisionSpec
1185.12.82 by Aaron Bentley
Fix missing import
25
from bzrlib.errors import BzrCommandError
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
26
27
28
def _parse_revision_str(revstr):
29
    """This handles a revision string -> revno.
30
31
    This always returns a list.  The list will have one element for
32
    each revision specifier supplied.
33
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):
68
      ...
69
    BzrError: No namespace registered for string: '123a'
70
    >>> _parse_revision_str('abc')
71
    Traceback (most recent call last):
72
      ...
73
    BzrError: No namespace registered for string: 'abc'
74
    >>> _parse_revision_str('branch:../branch2')
75
    [<RevisionSpec_branch branch:../branch2>]
1545.1.1 by Denys Duchier
distinguish ../ as path to branch and .. as revspec separator
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>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
80
    """
81
    # TODO: Maybe move this into revisionspec.py
82
    old_format_re = re.compile('\d*:\d*')
83
    m = old_format_re.match(revstr)
84
    revs = []
85
    if m:
86
        warning('Colon separator for revision numbers is deprecated.'
87
                ' Use .. instead')
88
        for rev in revstr.split(':'):
89
            if rev:
90
                revs.append(RevisionSpec(int(rev)))
91
            else:
92
                revs.append(RevisionSpec(None))
93
    else:
1545.1.1 by Denys Duchier
distinguish ../ as path to branch and .. as revspec separator
94
        sep = re.compile("\\.\\.(?!/)")
95
        for x in sep.split(revstr):
96
            revs.append(RevisionSpec(x or None))
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
97
    return revs
98
99
100
def _parse_merge_type(typestring):
1185.12.62 by Aaron Bentley
Restored merge-type selection
101
    return get_merge_type(typestring)
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
102
1185.12.62 by Aaron Bentley
Restored merge-type selection
103
def get_merge_type(typestring):
104
    """Attempt to find the merge class/factory associated with a string."""
105
    from merge import merge_types
106
    try:
107
        return merge_types[typestring][0]
108
    except KeyError:
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)
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
115
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
116
class EnumOption(object):
117
118
    def __init__(self, name, factory, choices):
119
        self.name = name
120
        self.factory = factory
121
        self.choices = choices 
122
        self.default = None
123
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
124
    def python_name(self):
1857.1.14 by Aaron Bentley
Fix man page generation
125
        """Conver a name with spaces and caps to a python variable name"""
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
126
        return self.name.lower().replace(' ', '_')
127
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
128
    def add_option(self, parser, short_name):
129
        """Add this option to an Optparse parser"""
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
130
        group = optparse.OptionGroup(parser, self.name)
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
131
        for name, help in self.choices:
132
            option_strings = ['--%s' % name]
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
133
            group.add_option(action='callback', 
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
134
                              callback=self._optparse_callback,
135
                              callback_args=(name,),
136
                              metavar=self.name,
137
                              help=help,
138
                              default=OptionParser.DEFAULT_VALUE,
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
139
                              dest=self.python_name(),
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
140
                              *option_strings)
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
141
        parser.add_option_group(group)
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
142
143
    def _optparse_callback(self, option, opt, value, parser, evalue):
144
        setattr(parser.values, option.dest, self.factory(evalue))
145
1857.1.14 by Aaron Bentley
Fix man page generation
146
    def iter_switches(self):
147
        """Iterate through the list of switches provided by the option
148
        
149
        :return: an iterator of (name, short_name, argname, help)
150
        """
151
        return ((n, None, None, h) for n, h in self.choices)
152
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
153
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
154
class Option(object):
1185.16.45 by Martin Pool
- refactor handling of short option names
155
    """Description of a command line option"""
156
    # TODO: Some way to show in help a description of the option argument
157
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
158
    OPTIONS = {}
159
    SHORT_OPTIONS = {}
160
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
161
    def __init__(self, name, help='', type=None, argname=None):
1185.16.45 by Martin Pool
- refactor handling of short option names
162
        """Make a new command option.
163
164
        name -- regular name of the command, used in the double-dash
165
            form and also as the parameter to the command's run() 
166
            method.
167
168
        help -- help message displayed in command help
169
170
        type -- function called to parse the option argument, or 
171
            None (default) if this option doesn't take an argument.
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
172
173
        argname -- name of option argument, if any
1185.16.45 by Martin Pool
- refactor handling of short option names
174
        """
175
        # TODO: perhaps a subclass that automatically does 
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
176
        # --option, --no-option for reversible booleans
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
177
        self.name = name
178
        self.help = help
179
        self.type = type
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
180
        if type is None:
181
            assert argname is None
182
        elif argname is None:
183
            argname = 'ARG'
184
        self.argname = argname
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
185
1185.16.45 by Martin Pool
- refactor handling of short option names
186
    def short_name(self):
187
        """Return the single character option for this command, if any.
188
189
        Short options are globally registered.
190
        """
1185.25.3 by Aaron Bentley
Restored short options in help
191
        for short, option in Option.SHORT_OPTIONS.iteritems():
192
            if option is self:
193
                return short
1185.16.45 by Martin Pool
- refactor handling of short option names
194
1857.1.9 by Aaron Bentley
Add hidden negation options
195
    def get_negation_name(self):
196
        if self.name.startswith('no-'):
197
            return self.name[3:]
198
        else:
199
            return 'no-' + self.name
200
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
201
    def add_option(self, parser, short_name):
202
        """Add this option to an Optparse parser"""
203
        option_strings = ['--%s' % self.name]
204
        if short_name is not None:
205
            option_strings.append('-%s' % short_name)
206
        optargfn = self.type
207
        if optargfn is None:
208
            parser.add_option(action='store_true', dest=self.name, 
209
                              help=self.help,
210
                              default=OptionParser.DEFAULT_VALUE,
211
                              *option_strings)
1857.1.9 by Aaron Bentley
Add hidden negation options
212
            negation_strings = ['--%s' % self.get_negation_name()]
213
            parser.add_option(action='store_const', dest=self.name, 
214
                              help=optparse.SUPPRESS_HELP,
215
                              const=OptionParser.DEFAULT_VALUE,
216
                              *negation_strings)
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
217
        else:
218
            parser.add_option(action='callback', 
219
                              callback=self._optparse_callback, 
1857.1.12 by Aaron Bentley
Fix a bunch of test cases that assumed --merge-type or log-format
220
                              type='string', metavar=self.argname.upper(),
1857.1.4 by Aaron Bentley
Set metavar according to option
221
                              help=self.help,
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
222
                              default=OptionParser.DEFAULT_VALUE, 
223
                              *option_strings)
224
225
    def _optparse_callback(self, option, opt, value, parser):
226
        setattr(parser.values, self.name, self.type(value))
227
1857.1.14 by Aaron Bentley
Fix man page generation
228
    def iter_switches(self):
229
        """Iterate through the list of switches provided by the option
230
        
231
        :return: an iterator of (name, short_name, argname, help)
232
        """
233
        argname =  self.argname
234
        if argname is not None:
235
            argname = argname.upper()
236
        yield self.name, self.short_name(), argname, self.help
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
237
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
238
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
239
class OptionParser(optparse.OptionParser):
240
    """OptionParser that raises exceptions instead of exiting"""
241
1857.1.6 by Aaron Bentley
Make the DEFAULT_VALUE an object instance
242
    DEFAULT_VALUE = object()
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
243
244
    def error(self, message):
245
        raise BzrCommandError(message)
246
247
248
def get_optparser(options):
249
    """Generate an optparse parser for bzrlib-style options"""
250
251
    parser = OptionParser()
252
    parser.remove_option('--help')
253
    short_options = dict((k.name, v) for v, k in 
254
                         Option.SHORT_OPTIONS.iteritems())
255
    for option in options.itervalues():
256
        option.add_option(parser, short_options.get(option.name))
257
    return parser
258
1185.16.45 by Martin Pool
- refactor handling of short option names
259
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
260
def _global_option(name, **kwargs):
261
    """Register o as a global option."""
262
    Option.OPTIONS[name] = Option(name, **kwargs)
263
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
264
Option.OPTIONS['merge-type']=EnumOption('Merge type', get_merge_type, [
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
265
                            ('merge3', 'Use built-in diff3-style merge'),
266
                            ('diff3', 'Use external diff3 merge'),
267
                            ('weave', 'Use knit merge')])
268
1857.1.8 by Aaron Bentley
Group enum options and add enum options to init and init-repo
269
Option.OPTIONS['log-format']=EnumOption('Log format', str, [
270
                            ('long', 'Multi-line logs with merges shown'),
271
                            ('short', 'Two-line logs'),
272
                            ('line', 'One-line logs')])
1857.1.7 by Aaron Bentley
Convert merge-type and log-format to enumerations
273
1185.16.45 by Martin Pool
- refactor handling of short option names
274
_global_option('all')
1185.12.92 by Aaron Bentley
Fixed pull help, renamed clobber to overwrite
275
_global_option('overwrite', help='Ignore differences between branches and '
276
               'overwrite unconditionally')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
277
_global_option('basis', type=str)
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
278
_global_option('bound')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
279
_global_option('diff-options', type=str)
1185.16.55 by mbp at sourcefrog
- more option help
280
_global_option('help',
281
               help='show help message')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
282
_global_option('file', type=unicode)
1185.16.45 by Martin Pool
- refactor handling of short option names
283
_global_option('force')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
284
_global_option('format', type=unicode)
1185.16.45 by Martin Pool
- refactor handling of short option names
285
_global_option('forward')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
286
_global_option('message', type=unicode)
1185.16.45 by Martin Pool
- refactor handling of short option names
287
_global_option('no-recurse')
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
288
_global_option('prefix', type=str, 
289
               help='Set prefixes to added to old and new filenames, as '
290
                    'two values separated by a colon.')
1185.16.55 by mbp at sourcefrog
- more option help
291
_global_option('profile',
292
               help='show performance profiling information')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
293
_global_option('revision', type=_parse_revision_str)
1185.16.47 by Martin Pool
- help for global options
294
_global_option('show-ids', 
295
               help='show internal object ids')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
296
_global_option('timezone', 
297
               type=str,
298
               help='display timezone as local, original, or utc')
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
299
_global_option('unbound')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
300
_global_option('verbose',
301
               help='display more information')
1185.16.45 by Martin Pool
- refactor handling of short option names
302
_global_option('version')
303
_global_option('email')
304
_global_option('update')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
305
_global_option('root', type=str)
1185.16.45 by Martin Pool
- refactor handling of short option names
306
_global_option('no-backup')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
307
_global_option('pattern', type=str)
1185.16.45 by Martin Pool
- refactor handling of short option names
308
_global_option('quiet')
1185.12.92 by Aaron Bentley
Fixed pull help, renamed clobber to overwrite
309
_global_option('remember', help='Remember the specified location as a'
310
               ' default.')
1185.24.3 by Aaron Bentley
Integrated reprocessing into the rest of the merge stuff
311
_global_option('reprocess', help='Reprocess to reduce spurious conflicts')
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
312
_global_option('kind', type=str)
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
313
_global_option('dry-run',
314
               help="show what would be done, but don't actually do anything")
1185.16.45 by Martin Pool
- refactor handling of short option names
315
316
317
def _global_short(short_name, long_name):
318
    assert short_name not in Option.SHORT_OPTIONS
319
    Option.SHORT_OPTIONS[short_name] = Option.OPTIONS[long_name]
320
    
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
321
322
Option.SHORT_OPTIONS['F'] = Option.OPTIONS['file']
323
Option.SHORT_OPTIONS['h'] = Option.OPTIONS['help']
324
Option.SHORT_OPTIONS['m'] = Option.OPTIONS['message']
325
Option.SHORT_OPTIONS['r'] = Option.OPTIONS['revision']
326
Option.SHORT_OPTIONS['v'] = Option.OPTIONS['verbose']
327
Option.SHORT_OPTIONS['q'] = Option.OPTIONS['quiet']
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
328
Option.SHORT_OPTIONS['p'] = Option.OPTIONS['prefix']