~bzr-pqm/bzr/bzr.dev

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
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
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')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
35
    [<RevisionSpec_revno 234>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
36
    >>> _parse_revision_str('234..567')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
37
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 567>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
38
    >>> _parse_revision_str('..')
39
    [<RevisionSpec None>, <RevisionSpec None>]
40
    >>> _parse_revision_str('..234')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
41
    [<RevisionSpec None>, <RevisionSpec_revno 234>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
42
    >>> _parse_revision_str('234..')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
43
    [<RevisionSpec_revno 234>, <RevisionSpec None>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
44
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
45
    [<RevisionSpec_revno 234>, <RevisionSpec_revno 456>, <RevisionSpec_revno 789>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
46
    >>> _parse_revision_str('234....789') #Error ?
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
47
    [<RevisionSpec_revno 234>, <RevisionSpec None>, <RevisionSpec_revno 789>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
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')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
53
    [<RevisionSpec_revid revid:test@other.com-234234>, <RevisionSpec_revno 23>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
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')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
63
    [<RevisionSpec_revno -5>, <RevisionSpec_revno 23>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
64
    >>> _parse_revision_str('-5')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
65
    [<RevisionSpec_revno -5>]
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
66
    >>> _parse_revision_str('123a')
67
    Traceback (most recent call last):
68
      ...
1948.4.32 by John Arbash Meinel
Clean up __repr__, as well as add tests that we can handle -r12:branch/
69
    NoSuchRevisionSpec: No namespace registered for string: '123a'
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
70
    >>> _parse_revision_str('abc')
71
    Traceback (most recent call last):
72
      ...
1948.4.32 by John Arbash Meinel
Clean up __repr__, as well as add tests that we can handle -r12:branch/
73
    NoSuchRevisionSpec: No namespace registered for string: 'abc'
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
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')
1948.4.31 by John Arbash Meinel
fix bugs in the test_annonate.py suite, which was passing '-r 3' as n argument not '-r3' or '-r', '3'
79
    [<RevisionSpec_branch branch:../../branch2>, <RevisionSpec_revno 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
    revs = []
1948.4.28 by John Arbash Meinel
Remove some places that were directly instantiating a RevisionSpec object. Also get rid of support for --revision 1:2, it has been deprecated for a long time
83
    sep = re.compile("\\.\\.(?!/)")
84
    for x in sep.split(revstr):
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
85
        revs.append(RevisionSpec.from_string(x or None))
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
86
    return revs
87
88
89
def _parse_merge_type(typestring):
1185.12.62 by Aaron Bentley
Restored merge-type selection
90
    return get_merge_type(typestring)
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
91
1185.12.62 by Aaron Bentley
Restored merge-type selection
92
def get_merge_type(typestring):
93
    """Attempt to find the merge class/factory associated with a string."""
94
    from merge import merge_types
95
    try:
96
        return merge_types[typestring][0]
97
    except KeyError:
98
        templ = '%s%%7s: %%s' % (' '*12)
99
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
100
        type_list = '\n'.join(lines)
101
        msg = "No known merge type %s. Supported types are:\n%s" %\
102
            (typestring, type_list)
103
        raise BzrCommandError(msg)
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
104
105
class Option(object):
1185.16.45 by Martin Pool
- refactor handling of short option names
106
    """Description of a command line option"""
107
    # TODO: Some way to show in help a description of the option argument
108
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
109
    OPTIONS = {}
110
    SHORT_OPTIONS = {}
111
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
112
    def __init__(self, name, help='', type=None, argname=None):
1185.16.45 by Martin Pool
- refactor handling of short option names
113
        """Make a new command option.
114
115
        name -- regular name of the command, used in the double-dash
116
            form and also as the parameter to the command's run() 
117
            method.
118
119
        help -- help message displayed in command help
120
121
        type -- function called to parse the option argument, or 
122
            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
123
124
        argname -- name of option argument, if any
1185.16.45 by Martin Pool
- refactor handling of short option names
125
        """
126
        # TODO: perhaps a subclass that automatically does 
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
127
        # --option, --no-option for reversible booleans
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
128
        self.name = name
129
        self.help = help
130
        self.type = type
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
131
        if type is None:
132
            assert argname is None
133
        elif argname is None:
134
            argname = 'ARG'
135
        self.argname = argname
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
136
1185.16.45 by Martin Pool
- refactor handling of short option names
137
    def short_name(self):
138
        """Return the single character option for this command, if any.
139
140
        Short options are globally registered.
141
        """
1185.25.3 by Aaron Bentley
Restored short options in help
142
        for short, option in Option.SHORT_OPTIONS.iteritems():
143
            if option is self:
144
                return short
1185.16.45 by Martin Pool
- refactor handling of short option names
145
1857.1.9 by Aaron Bentley
Add hidden negation options
146
    def get_negation_name(self):
147
        if self.name.startswith('no-'):
148
            return self.name[3:]
149
        else:
150
            return 'no-' + self.name
151
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
152
    def add_option(self, parser, short_name):
153
        """Add this option to an Optparse parser"""
154
        option_strings = ['--%s' % self.name]
155
        if short_name is not None:
156
            option_strings.append('-%s' % short_name)
157
        optargfn = self.type
158
        if optargfn is None:
159
            parser.add_option(action='store_true', dest=self.name, 
160
                              help=self.help,
161
                              default=OptionParser.DEFAULT_VALUE,
162
                              *option_strings)
1857.1.9 by Aaron Bentley
Add hidden negation options
163
            negation_strings = ['--%s' % self.get_negation_name()]
1857.1.22 by Aaron Bentley
Negations set value to False, instead of Optparser.DEFAULT_VALUE
164
            parser.add_option(action='store_false', dest=self.name, 
165
                              help=optparse.SUPPRESS_HELP, *negation_strings)
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
166
        else:
167
            parser.add_option(action='callback', 
168
                              callback=self._optparse_callback, 
1857.1.12 by Aaron Bentley
Fix a bunch of test cases that assumed --merge-type or log-format
169
                              type='string', metavar=self.argname.upper(),
1857.1.4 by Aaron Bentley
Set metavar according to option
170
                              help=self.help,
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
171
                              default=OptionParser.DEFAULT_VALUE, 
172
                              *option_strings)
173
174
    def _optparse_callback(self, option, opt, value, parser):
175
        setattr(parser.values, self.name, self.type(value))
176
1857.1.14 by Aaron Bentley
Fix man page generation
177
    def iter_switches(self):
178
        """Iterate through the list of switches provided by the option
179
        
180
        :return: an iterator of (name, short_name, argname, help)
181
        """
182
        argname =  self.argname
183
        if argname is not None:
184
            argname = argname.upper()
185
        yield self.name, self.short_name(), argname, self.help
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
186
1857.1.15 by Aaron Bentley
Add tests for generating an option parser
187
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
188
class OptionParser(optparse.OptionParser):
189
    """OptionParser that raises exceptions instead of exiting"""
190
1857.1.6 by Aaron Bentley
Make the DEFAULT_VALUE an object instance
191
    DEFAULT_VALUE = object()
1857.1.3 by Aaron Bentley
Make option adding depend on Option type
192
193
    def error(self, message):
194
        raise BzrCommandError(message)
195
196
197
def get_optparser(options):
198
    """Generate an optparse parser for bzrlib-style options"""
199
200
    parser = OptionParser()
201
    parser.remove_option('--help')
202
    short_options = dict((k.name, v) for v, k in 
203
                         Option.SHORT_OPTIONS.iteritems())
204
    for option in options.itervalues():
205
        option.add_option(parser, short_options.get(option.name))
206
    return parser
207
1185.16.45 by Martin Pool
- refactor handling of short option names
208
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
209
def _global_option(name, **kwargs):
210
    """Register o as a global option."""
211
    Option.OPTIONS[name] = Option(name, **kwargs)
212
1185.16.45 by Martin Pool
- refactor handling of short option names
213
_global_option('all')
1185.12.92 by Aaron Bentley
Fixed pull help, renamed clobber to overwrite
214
_global_option('overwrite', help='Ignore differences between branches and '
215
               'overwrite unconditionally')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
216
_global_option('basis', type=str)
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
217
_global_option('bound')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
218
_global_option('diff-options', type=str)
1185.16.55 by mbp at sourcefrog
- more option help
219
_global_option('help',
220
               help='show help message')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
221
_global_option('file', type=unicode)
1185.16.45 by Martin Pool
- refactor handling of short option names
222
_global_option('force')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
223
_global_option('format', type=unicode)
1185.16.45 by Martin Pool
- refactor handling of short option names
224
_global_option('forward')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
225
_global_option('message', type=unicode)
1185.16.45 by Martin Pool
- refactor handling of short option names
226
_global_option('no-recurse')
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
227
_global_option('prefix', type=str, 
228
               help='Set prefixes to added to old and new filenames, as '
229
                    'two values separated by a colon.')
1185.16.55 by mbp at sourcefrog
- more option help
230
_global_option('profile',
231
               help='show performance profiling information')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
232
_global_option('revision', type=_parse_revision_str)
1185.16.47 by Martin Pool
- help for global options
233
_global_option('show-ids', 
234
               help='show internal object ids')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
235
_global_option('timezone', 
236
               type=str,
237
               help='display timezone as local, original, or utc')
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
238
_global_option('unbound')
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
239
_global_option('verbose',
240
               help='display more information')
1185.16.45 by Martin Pool
- refactor handling of short option names
241
_global_option('version')
242
_global_option('email')
243
_global_option('update')
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
244
_global_option('log-format', type=str, help="Use this log format")
245
_global_option('long', help='Use detailed log format. Same as --log-format long')
246
_global_option('short', help='Use moderately short log format. Same as --log-format short')
247
_global_option('line', help='Use log format with one line per revision. Same as --log-format line')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
248
_global_option('root', type=str)
1185.16.45 by Martin Pool
- refactor handling of short option names
249
_global_option('no-backup')
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
250
_global_option('merge-type', type=_parse_merge_type, 
251
               help='Select a particular merge algorithm')
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
252
_global_option('pattern', type=str)
1185.16.45 by Martin Pool
- refactor handling of short option names
253
_global_option('quiet')
1185.12.92 by Aaron Bentley
Fixed pull help, renamed clobber to overwrite
254
_global_option('remember', help='Remember the specified location as a'
255
               ' default.')
1185.24.3 by Aaron Bentley
Integrated reprocessing into the rest of the merge stuff
256
_global_option('reprocess', help='Reprocess to reduce spurious conflicts')
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
257
_global_option('kind', type=str)
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
258
_global_option('dry-run',
259
               help="show what would be done, but don't actually do anything")
1185.16.45 by Martin Pool
- refactor handling of short option names
260
261
262
def _global_short(short_name, long_name):
263
    assert short_name not in Option.SHORT_OPTIONS
264
    Option.SHORT_OPTIONS[short_name] = Option.OPTIONS[long_name]
265
    
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
266
267
Option.SHORT_OPTIONS['F'] = Option.OPTIONS['file']
268
Option.SHORT_OPTIONS['h'] = Option.OPTIONS['help']
269
Option.SHORT_OPTIONS['m'] = Option.OPTIONS['message']
270
Option.SHORT_OPTIONS['r'] = Option.OPTIONS['revision']
271
Option.SHORT_OPTIONS['v'] = Option.OPTIONS['verbose']
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
272
Option.SHORT_OPTIONS['l'] = Option.OPTIONS['long']
1185.16.41 by Martin Pool
[patch] define cli options as objects, not strings
273
Option.SHORT_OPTIONS['q'] = Option.OPTIONS['quiet']
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
274
Option.SHORT_OPTIONS['p'] = Option.OPTIONS['prefix']