329
by Martin Pool
- refactor command functions into command classes |
1 |
# Copyright (C) 2004, 2005 by Canonical Ltd
|
1
by mbp at sourcefrog
import from baz patch-364 |
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 |
||
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
18 |
# TODO: probably should say which arguments are candidates for glob
|
19 |
# expansion on windows and do that at the command level.
|
|
20 |
||
1095
by Martin Pool
todo |
21 |
# TODO: Help messages for options.
|
22 |
||
23 |
# TODO: Define arguments by objects, rather than just using names.
|
|
24 |
# Those objects can specify the expected type of the argument, which
|
|
25 |
# would help with validation and shell completion.
|
|
26 |
||
27 |
||
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
28 |
import sys |
29 |
import os |
|
1
by mbp at sourcefrog
import from baz patch-364 |
30 |
|
31 |
import bzrlib |
|
1112
by Martin Pool
- disable standard logging to .bzr.log and stderr while running |
32 |
import bzrlib.trace |
897
by Martin Pool
- merge john's revision-naming code |
33 |
from bzrlib.trace import mutter, note, log_error, warning |
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
34 |
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError |
800
by Martin Pool
Merge John's import-speedup branch: |
35 |
from bzrlib.branch import find_branch |
36 |
from bzrlib import BZRDIR |
|
1
by mbp at sourcefrog
import from baz patch-364 |
37 |
|
38 |
||
731
by Martin Pool
- merge plugin patch from john |
39 |
plugin_cmds = {} |
40 |
||
41 |
||
759
by Martin Pool
- fix up register_command() names |
42 |
def register_command(cmd): |
731
by Martin Pool
- merge plugin patch from john |
43 |
"Utility function to help register a command"
|
44 |
global plugin_cmds |
|
45 |
k = cmd.__name__ |
|
46 |
if k.startswith("cmd_"): |
|
47 |
k_unsquished = _unsquish_command_name(k) |
|
48 |
else: |
|
49 |
k_unsquished = k |
|
50 |
if not plugin_cmds.has_key(k_unsquished): |
|
51 |
plugin_cmds[k_unsquished] = cmd |
|
1137
by Martin Pool
- additional trace messages for plugins |
52 |
mutter('registered plugin command %s', k_unsquished) |
731
by Martin Pool
- merge plugin patch from john |
53 |
else: |
54 |
log_error('Two plugins defined the same command: %r' % k) |
|
55 |
log_error('Not loading the one in %r' % sys.modules[cmd.__module__]) |
|
56 |
||
57 |
||
350
by Martin Pool
- refactor command aliases into command classes |
58 |
def _squish_command_name(cmd): |
59 |
return 'cmd_' + cmd.replace('-', '_') |
|
60 |
||
61 |
||
62 |
def _unsquish_command_name(cmd): |
|
63 |
assert cmd.startswith("cmd_") |
|
64 |
return cmd[4:].replace('_','-') |
|
65 |
||
914
by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch |
66 |
|
567
by Martin Pool
- New form 'bzr log -r FROM:TO' |
67 |
def _parse_revision_str(revstr): |
914
by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch |
68 |
"""This handles a revision string -> revno.
|
69 |
||
70 |
This always returns a list. The list will have one element for
|
|
567
by Martin Pool
- New form 'bzr log -r FROM:TO' |
71 |
|
897
by Martin Pool
- merge john's revision-naming code |
72 |
It supports integers directly, but everything else it
|
73 |
defers for passing to Branch.get_revision_info()
|
|
74 |
||
75 |
>>> _parse_revision_str('234')
|
|
76 |
[234]
|
|
77 |
>>> _parse_revision_str('234..567')
|
|
78 |
[234, 567]
|
|
79 |
>>> _parse_revision_str('..')
|
|
80 |
[None, None]
|
|
81 |
>>> _parse_revision_str('..234')
|
|
82 |
[None, 234]
|
|
83 |
>>> _parse_revision_str('234..')
|
|
84 |
[234, None]
|
|
85 |
>>> _parse_revision_str('234..456..789') # Maybe this should be an error
|
|
86 |
[234, 456, 789]
|
|
87 |
>>> _parse_revision_str('234....789') # Error?
|
|
88 |
[234, None, 789]
|
|
89 |
>>> _parse_revision_str('revid:test@other.com-234234')
|
|
90 |
['revid:test@other.com-234234']
|
|
91 |
>>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
|
|
92 |
['revid:test@other.com-234234', 'revid:test@other.com-234235']
|
|
93 |
>>> _parse_revision_str('revid:test@other.com-234234..23')
|
|
94 |
['revid:test@other.com-234234', 23]
|
|
95 |
>>> _parse_revision_str('date:2005-04-12')
|
|
96 |
['date:2005-04-12']
|
|
97 |
>>> _parse_revision_str('date:2005-04-12 12:24:33')
|
|
98 |
['date:2005-04-12 12:24:33']
|
|
99 |
>>> _parse_revision_str('date:2005-04-12T12:24:33')
|
|
100 |
['date:2005-04-12T12:24:33']
|
|
101 |
>>> _parse_revision_str('date:2005-04-12,12:24:33')
|
|
102 |
['date:2005-04-12,12:24:33']
|
|
103 |
>>> _parse_revision_str('-5..23')
|
|
104 |
[-5, 23]
|
|
105 |
>>> _parse_revision_str('-5')
|
|
106 |
[-5]
|
|
107 |
>>> _parse_revision_str('123a')
|
|
108 |
['123a']
|
|
109 |
>>> _parse_revision_str('abc')
|
|
110 |
['abc']
|
|
567
by Martin Pool
- New form 'bzr log -r FROM:TO' |
111 |
"""
|
897
by Martin Pool
- merge john's revision-naming code |
112 |
import re |
113 |
old_format_re = re.compile('\d*:\d*') |
|
114 |
m = old_format_re.match(revstr) |
|
115 |
if m: |
|
116 |
warning('Colon separator for revision numbers is deprecated.' |
|
117 |
' Use .. instead') |
|
118 |
revs = [] |
|
119 |
for rev in revstr.split(':'): |
|
120 |
if rev: |
|
121 |
revs.append(int(rev)) |
|
122 |
else: |
|
123 |
revs.append(None) |
|
124 |
return revs |
|
125 |
revs = [] |
|
126 |
for x in revstr.split('..'): |
|
127 |
if not x: |
|
128 |
revs.append(None) |
|
129 |
else: |
|
130 |
try: |
|
131 |
revs.append(int(x)) |
|
132 |
except ValueError: |
|
133 |
revs.append(x) |
|
567
by Martin Pool
- New form 'bzr log -r FROM:TO' |
134 |
return revs |
135 |
||
731
by Martin Pool
- merge plugin patch from john |
136 |
|
974.1.9
by Aaron Bentley
Added merge-type parameter to merge. |
137 |
def get_merge_type(typestring): |
138 |
"""Attempt to find the merge class/factory associated with a string."""
|
|
139 |
from merge import merge_types |
|
140 |
try: |
|
141 |
return merge_types[typestring][0] |
|
142 |
except KeyError: |
|
143 |
templ = '%s%%7s: %%s' % (' '*12) |
|
144 |
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()] |
|
145 |
type_list = '\n'.join(lines) |
|
146 |
msg = "No known merge type %s. Supported types are:\n%s" %\ |
|
147 |
(typestring, type_list) |
|
148 |
raise BzrCommandError(msg) |
|
149 |
||
150 |
||
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
151 |
def get_merge_type(typestring): |
152 |
"""Attempt to find the merge class/factory associated with a string."""
|
|
153 |
from merge import merge_types |
|
154 |
try: |
|
155 |
return merge_types[typestring][0] |
|
156 |
except KeyError: |
|
157 |
templ = '%s%%7s: %%s' % (' '*12) |
|
158 |
lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()] |
|
159 |
type_list = '\n'.join(lines) |
|
160 |
msg = "No known merge type %s. Supported types are:\n%s" %\ |
|
161 |
(typestring, type_list) |
|
162 |
raise BzrCommandError(msg) |
|
163 |
||
164 |
||
731
by Martin Pool
- merge plugin patch from john |
165 |
|
166 |
def _get_cmd_dict(plugins_override=True): |
|
1147
by Martin Pool
- split builtin commands into separate module bzrlib.builtins; |
167 |
import bzrlib.builtins |
168 |
||
641
by Martin Pool
- improved external-command patch from john |
169 |
d = {} |
1147
by Martin Pool
- split builtin commands into separate module bzrlib.builtins; |
170 |
builtins = bzrlib.builtins.__dict__ |
171 |
for name in builtins: |
|
172 |
if name.startswith("cmd_"): |
|
173 |
d[_unsquish_command_name(name)] = builtins[name] |
|
731
by Martin Pool
- merge plugin patch from john |
174 |
# If we didn't load plugins, the plugin_cmds dict will be empty
|
175 |
if plugins_override: |
|
176 |
d.update(plugin_cmds) |
|
177 |
else: |
|
178 |
d2 = plugin_cmds.copy() |
|
179 |
d2.update(d) |
|
180 |
d = d2 |
|
641
by Martin Pool
- improved external-command patch from john |
181 |
return d |
731
by Martin Pool
- merge plugin patch from john |
182 |
|
641
by Martin Pool
- improved external-command patch from john |
183 |
|
731
by Martin Pool
- merge plugin patch from john |
184 |
def get_all_cmds(plugins_override=True): |
641
by Martin Pool
- improved external-command patch from john |
185 |
"""Return canonical name and class for all registered commands."""
|
731
by Martin Pool
- merge plugin patch from john |
186 |
for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems(): |
641
by Martin Pool
- improved external-command patch from john |
187 |
yield k,v |
188 |
||
189 |
||
731
by Martin Pool
- merge plugin patch from john |
190 |
def get_cmd_class(cmd, plugins_override=True): |
350
by Martin Pool
- refactor command aliases into command classes |
191 |
"""Return the canonical name and command class for a command.
|
192 |
"""
|
|
193 |
cmd = str(cmd) # not unicode |
|
194 |
||
195 |
# first look up this command under the specified name
|
|
731
by Martin Pool
- merge plugin patch from john |
196 |
cmds = _get_cmd_dict(plugins_override=plugins_override) |
1137
by Martin Pool
- additional trace messages for plugins |
197 |
mutter("all commands: %r", cmds.keys()) |
272
by Martin Pool
- Add command aliases |
198 |
try: |
641
by Martin Pool
- improved external-command patch from john |
199 |
return cmd, cmds[cmd] |
272
by Martin Pool
- Add command aliases |
200 |
except KeyError: |
350
by Martin Pool
- refactor command aliases into command classes |
201 |
pass
|
202 |
||
203 |
# look for any command which claims this as an alias
|
|
641
by Martin Pool
- improved external-command patch from john |
204 |
for cmdname, cmdclass in cmds.iteritems(): |
350
by Martin Pool
- refactor command aliases into command classes |
205 |
if cmd in cmdclass.aliases: |
206 |
return cmdname, cmdclass |
|
422
by Martin Pool
- External-command patch from mpe |
207 |
|
208 |
cmdclass = ExternalCommand.find_command(cmd) |
|
209 |
if cmdclass: |
|
210 |
return cmd, cmdclass |
|
211 |
||
212 |
raise BzrCommandError("unknown command %r" % cmd) |
|
272
by Martin Pool
- Add command aliases |
213 |
|
329
by Martin Pool
- refactor command functions into command classes |
214 |
|
558
by Martin Pool
- All top-level classes inherit from object |
215 |
class Command(object): |
329
by Martin Pool
- refactor command functions into command classes |
216 |
"""Base class for commands.
|
217 |
||
218 |
The docstring for an actual command should give a single-line
|
|
219 |
summary, then a complete description of the command. A grammar
|
|
220 |
description will be inserted.
|
|
221 |
||
222 |
takes_args
|
|
223 |
List of argument forms, marked with whether they are optional,
|
|
224 |
repeated, etc.
|
|
225 |
||
226 |
takes_options
|
|
227 |
List of options that may be given for this command.
|
|
228 |
||
229 |
hidden
|
|
230 |
If true, this command isn't advertised.
|
|
231 |
"""
|
|
232 |
aliases = [] |
|
233 |
||
234 |
takes_args = [] |
|
235 |
takes_options = [] |
|
236 |
||
237 |
hidden = False |
|
238 |
||
239 |
def __init__(self, options, arguments): |
|
240 |
"""Construct and run the command.
|
|
241 |
||
242 |
Sets self.status to the return value of run()."""
|
|
243 |
assert isinstance(options, dict) |
|
244 |
assert isinstance(arguments, dict) |
|
245 |
cmdargs = options.copy() |
|
246 |
cmdargs.update(arguments) |
|
973
by Martin Pool
- various refactorings of command interpreter |
247 |
if self.__doc__ == Command.__doc__: |
248 |
from warnings import warn |
|
249 |
warn("No help message set for %r" % self) |
|
329
by Martin Pool
- refactor command functions into command classes |
250 |
self.status = self.run(**cmdargs) |
974
by Martin Pool
- start adding tests for commit in subdir |
251 |
if self.status is None: |
252 |
self.status = 0 |
|
329
by Martin Pool
- refactor command functions into command classes |
253 |
|
254 |
||
1147
by Martin Pool
- split builtin commands into separate module bzrlib.builtins; |
255 |
def run(self, *args, **kwargs): |
329
by Martin Pool
- refactor command functions into command classes |
256 |
"""Override this in sub-classes.
|
257 |
||
258 |
This is invoked with the options and arguments bound to
|
|
259 |
keyword parameters.
|
|
260 |
||
337
by Martin Pool
- Clarify return codes from command objects |
261 |
Return 0 or None if the command was successful, or a shell
|
262 |
error code if not.
|
|
329
by Martin Pool
- refactor command functions into command classes |
263 |
"""
|
1147
by Martin Pool
- split builtin commands into separate module bzrlib.builtins; |
264 |
raise NotImplementedError() |
329
by Martin Pool
- refactor command functions into command classes |
265 |
|
266 |
||
422
by Martin Pool
- External-command patch from mpe |
267 |
class ExternalCommand(Command): |
268 |
"""Class to wrap external commands.
|
|
269 |
||
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
270 |
We cheat a little here, when get_cmd_class() calls us we actually
|
271 |
give it back an object we construct that has the appropriate path,
|
|
272 |
help, options etc for the specified command.
|
|
273 |
||
274 |
When run_bzr() tries to instantiate that 'class' it gets caught by
|
|
275 |
the __call__ method, which we override to call the Command.__init__
|
|
276 |
method. That then calls our run method which is pretty straight
|
|
277 |
forward.
|
|
278 |
||
279 |
The only wrinkle is that we have to map bzr's dictionary of options
|
|
280 |
and arguments back into command line options and arguments for the
|
|
281 |
script.
|
|
422
by Martin Pool
- External-command patch from mpe |
282 |
"""
|
283 |
||
284 |
def find_command(cls, cmd): |
|
572
by Martin Pool
- trim imports |
285 |
import os.path |
422
by Martin Pool
- External-command patch from mpe |
286 |
bzrpath = os.environ.get('BZRPATH', '') |
287 |
||
641
by Martin Pool
- improved external-command patch from john |
288 |
for dir in bzrpath.split(os.pathsep): |
422
by Martin Pool
- External-command patch from mpe |
289 |
path = os.path.join(dir, cmd) |
290 |
if os.path.isfile(path): |
|
291 |
return ExternalCommand(path) |
|
292 |
||
293 |
return None |
|
294 |
||
295 |
find_command = classmethod(find_command) |
|
296 |
||
297 |
def __init__(self, path): |
|
298 |
self.path = path |
|
299 |
||
300 |
pipe = os.popen('%s --bzr-usage' % path, 'r') |
|
301 |
self.takes_options = pipe.readline().split() |
|
687
by Martin Pool
- trap more errors from external commands |
302 |
|
303 |
for opt in self.takes_options: |
|
304 |
if not opt in OPTIONS: |
|
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
305 |
raise BzrError("Unknown option '%s' returned by external command %s" |
306 |
% (opt, path)) |
|
687
by Martin Pool
- trap more errors from external commands |
307 |
|
308 |
# TODO: Is there any way to check takes_args is valid here?
|
|
422
by Martin Pool
- External-command patch from mpe |
309 |
self.takes_args = pipe.readline().split() |
687
by Martin Pool
- trap more errors from external commands |
310 |
|
311 |
if pipe.close() is not None: |
|
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
312 |
raise BzrError("Failed funning '%s --bzr-usage'" % path) |
422
by Martin Pool
- External-command patch from mpe |
313 |
|
314 |
pipe = os.popen('%s --bzr-help' % path, 'r') |
|
315 |
self.__doc__ = pipe.read() |
|
687
by Martin Pool
- trap more errors from external commands |
316 |
if pipe.close() is not None: |
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
317 |
raise BzrError("Failed funning '%s --bzr-help'" % path) |
422
by Martin Pool
- External-command patch from mpe |
318 |
|
319 |
def __call__(self, options, arguments): |
|
320 |
Command.__init__(self, options, arguments) |
|
321 |
return self |
|
322 |
||
323 |
def run(self, **kargs): |
|
324 |
opts = [] |
|
325 |
args = [] |
|
326 |
||
327 |
keys = kargs.keys() |
|
328 |
keys.sort() |
|
329 |
for name in keys: |
|
689
by Martin Pool
- make options with - work with external commands |
330 |
optname = name.replace('_','-') |
422
by Martin Pool
- External-command patch from mpe |
331 |
value = kargs[name] |
689
by Martin Pool
- make options with - work with external commands |
332 |
if OPTIONS.has_key(optname): |
422
by Martin Pool
- External-command patch from mpe |
333 |
# it's an option
|
689
by Martin Pool
- make options with - work with external commands |
334 |
opts.append('--%s' % optname) |
422
by Martin Pool
- External-command patch from mpe |
335 |
if value is not None and value is not True: |
336 |
opts.append(str(value)) |
|
337 |
else: |
|
338 |
# it's an arg, or arg list
|
|
339 |
if type(value) is not list: |
|
340 |
value = [value] |
|
341 |
for v in value: |
|
342 |
if v is not None: |
|
343 |
args.append(str(v)) |
|
344 |
||
345 |
self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args) |
|
346 |
return self.status |
|
347 |
||
329
by Martin Pool
- refactor command functions into command classes |
348 |
|
349 |
||
493
by Martin Pool
- Merge aaron's merge command |
350 |
def parse_spec(spec): |
622
by Martin Pool
Updated merge patch from Aaron |
351 |
"""
|
352 |
>>> parse_spec(None)
|
|
353 |
[None, None]
|
|
354 |
>>> parse_spec("./")
|
|
355 |
['./', None]
|
|
356 |
>>> parse_spec("../@")
|
|
357 |
['..', -1]
|
|
358 |
>>> parse_spec("../f/@35")
|
|
359 |
['../f', 35]
|
|
897
by Martin Pool
- merge john's revision-naming code |
360 |
>>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
|
361 |
['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
|
|
622
by Martin Pool
Updated merge patch from Aaron |
362 |
"""
|
363 |
if spec is None: |
|
364 |
return [None, None] |
|
493
by Martin Pool
- Merge aaron's merge command |
365 |
if '/@' in spec: |
366 |
parsed = spec.split('/@') |
|
367 |
assert len(parsed) == 2 |
|
368 |
if parsed[1] == "": |
|
369 |
parsed[1] = -1 |
|
370 |
else: |
|
897
by Martin Pool
- merge john's revision-naming code |
371 |
try: |
372 |
parsed[1] = int(parsed[1]) |
|
373 |
except ValueError: |
|
374 |
pass # We can allow stuff like ./@revid:blahblahblah |
|
375 |
else: |
|
376 |
assert parsed[1] >=0 |
|
493
by Martin Pool
- Merge aaron's merge command |
377 |
else: |
378 |
parsed = [spec, None] |
|
379 |
return parsed |
|
380 |
||
628
by Martin Pool
- merge aaron's updated merge/pull code |
381 |
|
382 |
||
755
by Martin Pool
- new 'plugins' command |
383 |
|
1
by mbp at sourcefrog
import from baz patch-364 |
384 |
# list of all available options; the rhs can be either None for an
|
385 |
# option that takes no argument, or a constructor function that checks
|
|
386 |
# the type.
|
|
387 |
OPTIONS = { |
|
388 |
'all': None, |
|
571
by Martin Pool
- new --diff-options to pass options through to external |
389 |
'diff-options': str, |
1
by mbp at sourcefrog
import from baz patch-364 |
390 |
'help': None, |
389
by Martin Pool
- new commit --file option! |
391 |
'file': unicode, |
628
by Martin Pool
- merge aaron's updated merge/pull code |
392 |
'force': None, |
678
by Martin Pool
- export to tarballs |
393 |
'format': unicode, |
545
by Martin Pool
- --forward option for log |
394 |
'forward': None, |
1
by mbp at sourcefrog
import from baz patch-364 |
395 |
'message': unicode, |
594
by Martin Pool
- add --no-recurse option for add command |
396 |
'no-recurse': None, |
137
by mbp at sourcefrog
new --profile option |
397 |
'profile': None, |
567
by Martin Pool
- New form 'bzr log -r FROM:TO' |
398 |
'revision': _parse_revision_str, |
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
399 |
'short': None, |
1
by mbp at sourcefrog
import from baz patch-364 |
400 |
'show-ids': None, |
12
by mbp at sourcefrog
new --timezone option for bzr log |
401 |
'timezone': str, |
1
by mbp at sourcefrog
import from baz patch-364 |
402 |
'verbose': None, |
403 |
'version': None, |
|
286
by Martin Pool
- New bzr whoami --email option |
404 |
'email': None, |
885
by Martin Pool
- commit command refuses unless something is changed or --unchanged is given |
405 |
'unchanged': None, |
674
by Martin Pool
- check command now also checks new inventory_sha1 and |
406 |
'update': None, |
807
by Martin Pool
- New log --long option |
407 |
'long': None, |
849
by Martin Pool
- Put files inside an exported tarball into a top-level directory rather than |
408 |
'root': str, |
974.1.8
by Aaron Bentley
Added default backups for merge-revert |
409 |
'no-backup': None, |
974.1.9
by Aaron Bentley
Added merge-type parameter to merge. |
410 |
'merge-type': get_merge_type, |
1092.1.20
by Robert Collins
import and use TestUtil to do regex based partial test runs |
411 |
'pattern': str, |
1
by mbp at sourcefrog
import from baz patch-364 |
412 |
}
|
413 |
||
414 |
SHORT_OPTIONS = { |
|
583
by Martin Pool
- add -h as short name for --help |
415 |
'F': 'file', |
416 |
'h': 'help', |
|
1
by mbp at sourcefrog
import from baz patch-364 |
417 |
'm': 'message', |
418 |
'r': 'revision', |
|
419 |
'v': 'verbose', |
|
807
by Martin Pool
- New log --long option |
420 |
'l': 'long', |
1
by mbp at sourcefrog
import from baz patch-364 |
421 |
}
|
422 |
||
423 |
||
424 |
def parse_args(argv): |
|
425 |
"""Parse command line.
|
|
426 |
|
|
427 |
Arguments and options are parsed at this level before being passed
|
|
428 |
down to specific command handlers. This routine knows, from a
|
|
429 |
lookup table, something about the available options, what optargs
|
|
430 |
they take, and which commands will accept them.
|
|
431 |
||
31
by Martin Pool
fix up parse_args doctest |
432 |
>>> parse_args('--help'.split())
|
1
by mbp at sourcefrog
import from baz patch-364 |
433 |
([], {'help': True})
|
1144
by Martin Pool
- accept -- to terminate options |
434 |
>>> parse_args('help -- --invalidcmd'.split())
|
435 |
(['help', '--invalidcmd'], {})
|
|
31
by Martin Pool
fix up parse_args doctest |
436 |
>>> parse_args('--version'.split())
|
1
by mbp at sourcefrog
import from baz patch-364 |
437 |
([], {'version': True})
|
31
by Martin Pool
fix up parse_args doctest |
438 |
>>> parse_args('status --all'.split())
|
1
by mbp at sourcefrog
import from baz patch-364 |
439 |
(['status'], {'all': True})
|
31
by Martin Pool
fix up parse_args doctest |
440 |
>>> parse_args('commit --message=biter'.split())
|
17
by mbp at sourcefrog
allow --option=ARG syntax |
441 |
(['commit'], {'message': u'biter'})
|
683
by Martin Pool
- short option stacking patch from John A Meinel |
442 |
>>> parse_args('log -r 500'.split())
|
897
by Martin Pool
- merge john's revision-naming code |
443 |
(['log'], {'revision': [500]})
|
444 |
>>> parse_args('log -r500..600'.split())
|
|
683
by Martin Pool
- short option stacking patch from John A Meinel |
445 |
(['log'], {'revision': [500, 600]})
|
897
by Martin Pool
- merge john's revision-naming code |
446 |
>>> parse_args('log -vr500..600'.split())
|
683
by Martin Pool
- short option stacking patch from John A Meinel |
447 |
(['log'], {'verbose': True, 'revision': [500, 600]})
|
897
by Martin Pool
- merge john's revision-naming code |
448 |
>>> parse_args('log -rv500..600'.split()) #the r takes an argument
|
449 |
(['log'], {'revision': ['v500', 600]})
|
|
1
by mbp at sourcefrog
import from baz patch-364 |
450 |
"""
|
451 |
args = [] |
|
452 |
opts = {} |
|
453 |
||
1144
by Martin Pool
- accept -- to terminate options |
454 |
argsover = False |
26
by mbp at sourcefrog
fix StopIteration error on python2.3(?) |
455 |
while argv: |
456 |
a = argv.pop(0) |
|
1144
by Martin Pool
- accept -- to terminate options |
457 |
if not argsover and a[0] == '-': |
264
by Martin Pool
parse_args: option names must be ascii |
458 |
# option names must not be unicode
|
459 |
a = str(a) |
|
17
by mbp at sourcefrog
allow --option=ARG syntax |
460 |
optarg = None |
1
by mbp at sourcefrog
import from baz patch-364 |
461 |
if a[1] == '-': |
1144
by Martin Pool
- accept -- to terminate options |
462 |
if a == '--': |
463 |
# We've received a standalone -- No more flags
|
|
464 |
argsover = True |
|
465 |
continue
|
|
1
by mbp at sourcefrog
import from baz patch-364 |
466 |
mutter(" got option %r" % a) |
17
by mbp at sourcefrog
allow --option=ARG syntax |
467 |
if '=' in a: |
468 |
optname, optarg = a[2:].split('=', 1) |
|
469 |
else: |
|
470 |
optname = a[2:] |
|
1
by mbp at sourcefrog
import from baz patch-364 |
471 |
if optname not in OPTIONS: |
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
472 |
raise BzrError('unknown long option %r' % a) |
1
by mbp at sourcefrog
import from baz patch-364 |
473 |
else: |
474 |
shortopt = a[1:] |
|
683
by Martin Pool
- short option stacking patch from John A Meinel |
475 |
if shortopt in SHORT_OPTIONS: |
476 |
# Multi-character options must have a space to delimit
|
|
477 |
# their value
|
|
478 |
optname = SHORT_OPTIONS[shortopt] |
|
479 |
else: |
|
480 |
# Single character short options, can be chained,
|
|
481 |
# and have their value appended to their name
|
|
482 |
shortopt = a[1:2] |
|
483 |
if shortopt not in SHORT_OPTIONS: |
|
484 |
# We didn't find the multi-character name, and we
|
|
485 |
# didn't find the single char name
|
|
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
486 |
raise BzrError('unknown short option %r' % a) |
683
by Martin Pool
- short option stacking patch from John A Meinel |
487 |
optname = SHORT_OPTIONS[shortopt] |
488 |
||
489 |
if a[2:]: |
|
490 |
# There are extra things on this option
|
|
491 |
# see if it is the value, or if it is another
|
|
492 |
# short option
|
|
493 |
optargfn = OPTIONS[optname] |
|
494 |
if optargfn is None: |
|
495 |
# This option does not take an argument, so the
|
|
496 |
# next entry is another short option, pack it back
|
|
497 |
# into the list
|
|
498 |
argv.insert(0, '-' + a[2:]) |
|
499 |
else: |
|
500 |
# This option takes an argument, so pack it
|
|
501 |
# into the array
|
|
502 |
optarg = a[2:] |
|
1
by mbp at sourcefrog
import from baz patch-364 |
503 |
|
504 |
if optname in opts: |
|
505 |
# XXX: Do we ever want to support this, e.g. for -r?
|
|
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
506 |
raise BzrError('repeated option %r' % a) |
17
by mbp at sourcefrog
allow --option=ARG syntax |
507 |
|
1
by mbp at sourcefrog
import from baz patch-364 |
508 |
optargfn = OPTIONS[optname] |
509 |
if optargfn: |
|
17
by mbp at sourcefrog
allow --option=ARG syntax |
510 |
if optarg == None: |
26
by mbp at sourcefrog
fix StopIteration error on python2.3(?) |
511 |
if not argv: |
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
512 |
raise BzrError('option %r needs an argument' % a) |
17
by mbp at sourcefrog
allow --option=ARG syntax |
513 |
else: |
26
by mbp at sourcefrog
fix StopIteration error on python2.3(?) |
514 |
optarg = argv.pop(0) |
17
by mbp at sourcefrog
allow --option=ARG syntax |
515 |
opts[optname] = optargfn(optarg) |
1
by mbp at sourcefrog
import from baz patch-364 |
516 |
else: |
17
by mbp at sourcefrog
allow --option=ARG syntax |
517 |
if optarg != None: |
694
by Martin Pool
- weed out all remaining calls to bailout() and remove the function |
518 |
raise BzrError('option %r takes no argument' % optname) |
1
by mbp at sourcefrog
import from baz patch-364 |
519 |
opts[optname] = True |
520 |
else: |
|
521 |
args.append(a) |
|
522 |
||
523 |
return args, opts |
|
524 |
||
525 |
||
526 |
||
527 |
||
329
by Martin Pool
- refactor command functions into command classes |
528 |
def _match_argform(cmd, takes_args, args): |
1
by mbp at sourcefrog
import from baz patch-364 |
529 |
argdict = {} |
26
by mbp at sourcefrog
fix StopIteration error on python2.3(?) |
530 |
|
329
by Martin Pool
- refactor command functions into command classes |
531 |
# step through args and takes_args, allowing appropriate 0-many matches
|
532 |
for ap in takes_args: |
|
1
by mbp at sourcefrog
import from baz patch-364 |
533 |
argname = ap[:-1] |
534 |
if ap[-1] == '?': |
|
62
by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron |
535 |
if args: |
536 |
argdict[argname] = args.pop(0) |
|
196
by mbp at sourcefrog
selected-file diff |
537 |
elif ap[-1] == '*': # all remaining arguments |
538 |
if args: |
|
539 |
argdict[argname + '_list'] = args[:] |
|
540 |
args = [] |
|
541 |
else: |
|
542 |
argdict[argname + '_list'] = None |
|
1
by mbp at sourcefrog
import from baz patch-364 |
543 |
elif ap[-1] == '+': |
544 |
if not args: |
|
329
by Martin Pool
- refactor command functions into command classes |
545 |
raise BzrCommandError("command %r needs one or more %s" |
1
by mbp at sourcefrog
import from baz patch-364 |
546 |
% (cmd, argname.upper())) |
547 |
else: |
|
548 |
argdict[argname + '_list'] = args[:] |
|
549 |
args = [] |
|
160
by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think |
550 |
elif ap[-1] == '$': # all but one |
551 |
if len(args) < 2: |
|
329
by Martin Pool
- refactor command functions into command classes |
552 |
raise BzrCommandError("command %r needs one or more %s" |
160
by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think |
553 |
% (cmd, argname.upper())) |
554 |
argdict[argname + '_list'] = args[:-1] |
|
555 |
args[:-1] = [] |
|
1
by mbp at sourcefrog
import from baz patch-364 |
556 |
else: |
557 |
# just a plain arg
|
|
558 |
argname = ap |
|
559 |
if not args: |
|
329
by Martin Pool
- refactor command functions into command classes |
560 |
raise BzrCommandError("command %r requires argument %s" |
1
by mbp at sourcefrog
import from baz patch-364 |
561 |
% (cmd, argname.upper())) |
562 |
else: |
|
563 |
argdict[argname] = args.pop(0) |
|
564 |
||
565 |
if args: |
|
329
by Martin Pool
- refactor command functions into command classes |
566 |
raise BzrCommandError("extra argument to command %s: %s" |
567 |
% (cmd, args[0])) |
|
1
by mbp at sourcefrog
import from baz patch-364 |
568 |
|
569 |
return argdict |
|
570 |
||
571 |
||
572 |
||
573 |
def run_bzr(argv): |
|
574 |
"""Execute a command.
|
|
575 |
||
576 |
This is similar to main(), but without all the trappings for
|
|
245
by mbp at sourcefrog
- control files always in utf-8-unix format |
577 |
logging and error handling.
|
973
by Martin Pool
- various refactorings of command interpreter |
578 |
|
579 |
argv
|
|
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
580 |
The command-line arguments, without the program name from argv[0]
|
973
by Martin Pool
- various refactorings of command interpreter |
581 |
|
582 |
Returns a command status or raises an exception.
|
|
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
583 |
|
584 |
Special master options: these must come before the command because
|
|
585 |
they control how the command is interpreted.
|
|
586 |
||
587 |
--no-plugins
|
|
588 |
Do not load plugin modules at all
|
|
589 |
||
590 |
--builtin
|
|
591 |
Only use builtin commands. (Plugins are still allowed to change
|
|
592 |
other behaviour.)
|
|
593 |
||
594 |
--profile
|
|
595 |
Run under the Python profiler.
|
|
1
by mbp at sourcefrog
import from baz patch-364 |
596 |
"""
|
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
597 |
|
251
by mbp at sourcefrog
- factor out locale.getpreferredencoding() |
598 |
argv = [a.decode(bzrlib.user_encoding) for a in argv] |
973
by Martin Pool
- various refactorings of command interpreter |
599 |
|
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
600 |
opt_profile = opt_no_plugins = opt_builtin = False |
601 |
||
602 |
# --no-plugins is handled specially at a very early stage. We need
|
|
603 |
# to load plugins before doing other command parsing so that they
|
|
604 |
# can override commands, but this needs to happen first.
|
|
605 |
||
606 |
for a in argv[:]: |
|
607 |
if a == '--profile': |
|
608 |
opt_profile = True |
|
609 |
elif a == '--no-plugins': |
|
610 |
opt_no_plugins = True |
|
611 |
elif a == '--builtin': |
|
612 |
opt_builtin = True |
|
613 |
else: |
|
614 |
break
|
|
615 |
argv.remove(a) |
|
616 |
||
617 |
if not opt_no_plugins: |
|
973
by Martin Pool
- various refactorings of command interpreter |
618 |
from bzrlib.plugin import load_plugins |
619 |
load_plugins() |
|
620 |
||
621 |
args, opts = parse_args(argv) |
|
622 |
||
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
623 |
if 'help' in opts: |
973
by Martin Pool
- various refactorings of command interpreter |
624 |
from bzrlib.help import help |
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
625 |
if args: |
626 |
help(args[0]) |
|
973
by Martin Pool
- various refactorings of command interpreter |
627 |
else: |
628 |
help() |
|
629 |
return 0 |
|
630 |
||
631 |
if 'version' in opts: |
|
1147
by Martin Pool
- split builtin commands into separate module bzrlib.builtins; |
632 |
from bzrlib.builtins import show_version |
973
by Martin Pool
- various refactorings of command interpreter |
633 |
show_version() |
634 |
return 0 |
|
635 |
||
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
636 |
if not args: |
1099
by Martin Pool
- 'bzr' with no arguments shows the summary help. |
637 |
from bzrlib.help import help |
638 |
help(None) |
|
639 |
return 0 |
|
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
640 |
|
641 |
cmd = str(args.pop(0)) |
|
642 |
||
643 |
canonical_cmd, cmd_class = \ |
|
644 |
get_cmd_class(cmd, plugins_override=not opt_builtin) |
|
1
by mbp at sourcefrog
import from baz patch-364 |
645 |
|
646 |
# check options are reasonable
|
|
329
by Martin Pool
- refactor command functions into command classes |
647 |
allowed = cmd_class.takes_options |
1
by mbp at sourcefrog
import from baz patch-364 |
648 |
for oname in opts: |
649 |
if oname not in allowed: |
|
381
by Martin Pool
- Better message when a wrong argument is given |
650 |
raise BzrCommandError("option '--%s' is not allowed for command %r" |
329
by Martin Pool
- refactor command functions into command classes |
651 |
% (oname, cmd)) |
176
by mbp at sourcefrog
New cat command contributed by janmar. |
652 |
|
137
by mbp at sourcefrog
new --profile option |
653 |
# mix arguments and options into one dictionary
|
329
by Martin Pool
- refactor command functions into command classes |
654 |
cmdargs = _match_argform(cmd, cmd_class.takes_args, args) |
655 |
cmdopts = {} |
|
136
by mbp at sourcefrog
new --show-ids option for 'deleted' command |
656 |
for k, v in opts.items(): |
329
by Martin Pool
- refactor command functions into command classes |
657 |
cmdopts[k.replace('-', '_')] = v |
1
by mbp at sourcefrog
import from baz patch-364 |
658 |
|
974.1.26
by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472 |
659 |
if opt_profile: |
338
by Martin Pool
- cleanup of some imports |
660 |
import hotshot, tempfile |
239
by mbp at sourcefrog
- remove profiler temporary file when done |
661 |
pffileno, pfname = tempfile.mkstemp() |
662 |
try: |
|
663 |
prof = hotshot.Profile(pfname) |
|
329
by Martin Pool
- refactor command functions into command classes |
664 |
ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0 |
239
by mbp at sourcefrog
- remove profiler temporary file when done |
665 |
prof.close() |
666 |
||
667 |
import hotshot.stats |
|
668 |
stats = hotshot.stats.load(pfname) |
|
669 |
#stats.strip_dirs()
|
|
670 |
stats.sort_stats('time') |
|
671 |
## XXX: Might like to write to stderr or the trace file instead but
|
|
672 |
## print_stats seems hardcoded to stdout
|
|
673 |
stats.print_stats(20) |
|
674 |
||
337
by Martin Pool
- Clarify return codes from command objects |
675 |
return ret.status |
239
by mbp at sourcefrog
- remove profiler temporary file when done |
676 |
|
677 |
finally: |
|
678 |
os.close(pffileno) |
|
679 |
os.remove(pfname) |
|
137
by mbp at sourcefrog
new --profile option |
680 |
else: |
500
by Martin Pool
- fix return value from run_bzr |
681 |
return cmd_class(cmdopts, cmdargs).status |
1
by mbp at sourcefrog
import from baz patch-364 |
682 |
|
683 |
||
684 |
def main(argv): |
|
1104
by Martin Pool
- Add a simple UIFactory |
685 |
import bzrlib.ui |
1111
by Martin Pool
- add functions to enable and disable default logging, so that we can |
686 |
bzrlib.trace.log_startup(argv) |
1104
by Martin Pool
- Add a simple UIFactory |
687 |
bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory() |
688 |
||
1
by mbp at sourcefrog
import from baz patch-364 |
689 |
try: |
260
by Martin Pool
- remove atexit() dependency for writing out execution times |
690 |
try: |
1097
by Martin Pool
- send trace messages out through python logging module |
691 |
return run_bzr(argv[1:]) |
692 |
finally: |
|
693 |
# do this here inside the exception wrappers to catch EPIPE
|
|
694 |
sys.stdout.flush() |
|
695 |
except BzrCommandError, e: |
|
696 |
# command line syntax error, etc
|
|
697 |
log_error(str(e)) |
|
698 |
return 1 |
|
699 |
except BzrError, e: |
|
700 |
bzrlib.trace.log_exception() |
|
701 |
return 1 |
|
702 |
except AssertionError, e: |
|
703 |
bzrlib.trace.log_exception('assertion failed: ' + str(e)) |
|
704 |
return 3 |
|
705 |
except KeyboardInterrupt, e: |
|
706 |
bzrlib.trace.note('interrupted') |
|
707 |
return 2 |
|
708 |
except Exception, e: |
|
709 |
import errno |
|
710 |
if (isinstance(e, IOError) |
|
711 |
and hasattr(e, 'errno') |
|
712 |
and e.errno == errno.EPIPE): |
|
713 |
bzrlib.trace.note('broken pipe') |
|
714 |
return 2 |
|
715 |
else: |
|
1108
by Martin Pool
- more cleanups of error reporting |
716 |
bzrlib.trace.log_exception() |
1097
by Martin Pool
- send trace messages out through python logging module |
717 |
return 2 |
1
by mbp at sourcefrog
import from baz patch-364 |
718 |
|
719 |
||
720 |
if __name__ == '__main__': |
|
721 |
sys.exit(main(sys.argv)) |