##// END OF EJS Templates
Minor cleanup: Add missing space forgotten in recent change.
Thomas Arendsen Hein -
r7224:12a90281 default
parent child Browse files
Show More
@@ -1,420 +1,420 b''
1 # dispatch.py - command dispatching for mercurial
1 # dispatch.py - command dispatching for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from i18n import _
8 from i18n import _
9 from repo import RepoError
9 from repo import RepoError
10 import os, sys, atexit, signal, pdb, traceback, socket, errno, shlex, time
10 import os, sys, atexit, signal, pdb, traceback, socket, errno, shlex, time
11 import util, commands, hg, lock, fancyopts, revlog, version, extensions, hook
11 import util, commands, hg, lock, fancyopts, revlog, version, extensions, hook
12 import cmdutil
12 import cmdutil
13 import ui as _ui
13 import ui as _ui
14
14
15 class ParseError(Exception):
15 class ParseError(Exception):
16 """Exception raised on errors in parsing the command line."""
16 """Exception raised on errors in parsing the command line."""
17
17
18 def run():
18 def run():
19 "run the command in sys.argv"
19 "run the command in sys.argv"
20 sys.exit(dispatch(sys.argv[1:]))
20 sys.exit(dispatch(sys.argv[1:]))
21
21
22 def dispatch(args):
22 def dispatch(args):
23 "run the command specified in args"
23 "run the command specified in args"
24 try:
24 try:
25 u = _ui.ui(traceback='--traceback' in args)
25 u = _ui.ui(traceback='--traceback' in args)
26 except util.Abort, inst:
26 except util.Abort, inst:
27 sys.stderr.write(_("abort: %s\n") % inst)
27 sys.stderr.write(_("abort: %s\n") % inst)
28 return -1
28 return -1
29 return _runcatch(u, args)
29 return _runcatch(u, args)
30
30
31 def _runcatch(ui, args):
31 def _runcatch(ui, args):
32 def catchterm(*args):
32 def catchterm(*args):
33 raise util.SignalInterrupt
33 raise util.SignalInterrupt
34
34
35 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
35 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
36 num = getattr(signal, name, None)
36 num = getattr(signal, name, None)
37 if num: signal.signal(num, catchterm)
37 if num: signal.signal(num, catchterm)
38
38
39 try:
39 try:
40 try:
40 try:
41 # enter the debugger before command execution
41 # enter the debugger before command execution
42 if '--debugger' in args:
42 if '--debugger' in args:
43 pdb.set_trace()
43 pdb.set_trace()
44 try:
44 try:
45 return _dispatch(ui, args)
45 return _dispatch(ui, args)
46 finally:
46 finally:
47 ui.flush()
47 ui.flush()
48 except:
48 except:
49 # enter the debugger when we hit an exception
49 # enter the debugger when we hit an exception
50 if '--debugger' in args:
50 if '--debugger' in args:
51 pdb.post_mortem(sys.exc_info()[2])
51 pdb.post_mortem(sys.exc_info()[2])
52 ui.print_exc()
52 ui.print_exc()
53 raise
53 raise
54
54
55 except ParseError, inst:
55 except ParseError, inst:
56 if inst.args[0]:
56 if inst.args[0]:
57 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
57 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
58 commands.help_(ui, inst.args[0])
58 commands.help_(ui, inst.args[0])
59 else:
59 else:
60 ui.warn(_("hg: %s\n") % inst.args[1])
60 ui.warn(_("hg: %s\n") % inst.args[1])
61 commands.help_(ui, 'shortlist')
61 commands.help_(ui, 'shortlist')
62 except cmdutil.AmbiguousCommand, inst:
62 except cmdutil.AmbiguousCommand, inst:
63 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
63 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
64 (inst.args[0], " ".join(inst.args[1])))
64 (inst.args[0], " ".join(inst.args[1])))
65 except cmdutil.UnknownCommand, inst:
65 except cmdutil.UnknownCommand, inst:
66 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
66 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
67 commands.help_(ui, 'shortlist')
67 commands.help_(ui, 'shortlist')
68 except RepoError, inst:
68 except RepoError, inst:
69 ui.warn(_("abort: %s!\n") % inst)
69 ui.warn(_("abort: %s!\n") % inst)
70 except lock.LockHeld, inst:
70 except lock.LockHeld, inst:
71 if inst.errno == errno.ETIMEDOUT:
71 if inst.errno == errno.ETIMEDOUT:
72 reason = _('timed out waiting for lock held by %s') % inst.locker
72 reason = _('timed out waiting for lock held by %s') % inst.locker
73 else:
73 else:
74 reason = _('lock held by %s') % inst.locker
74 reason = _('lock held by %s') % inst.locker
75 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
75 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
76 except lock.LockUnavailable, inst:
76 except lock.LockUnavailable, inst:
77 ui.warn(_("abort: could not lock %s: %s\n") %
77 ui.warn(_("abort: could not lock %s: %s\n") %
78 (inst.desc or inst.filename, inst.strerror))
78 (inst.desc or inst.filename, inst.strerror))
79 except revlog.RevlogError, inst:
79 except revlog.RevlogError, inst:
80 ui.warn(_("abort: %s!\n") % inst)
80 ui.warn(_("abort: %s!\n") % inst)
81 except util.SignalInterrupt:
81 except util.SignalInterrupt:
82 ui.warn(_("killed!\n"))
82 ui.warn(_("killed!\n"))
83 except KeyboardInterrupt:
83 except KeyboardInterrupt:
84 try:
84 try:
85 ui.warn(_("interrupted!\n"))
85 ui.warn(_("interrupted!\n"))
86 except IOError, inst:
86 except IOError, inst:
87 if inst.errno == errno.EPIPE:
87 if inst.errno == errno.EPIPE:
88 if ui.debugflag:
88 if ui.debugflag:
89 ui.warn(_("\nbroken pipe\n"))
89 ui.warn(_("\nbroken pipe\n"))
90 else:
90 else:
91 raise
91 raise
92 except socket.error, inst:
92 except socket.error, inst:
93 ui.warn(_("abort: %s\n") % inst[-1])
93 ui.warn(_("abort: %s\n") % inst[-1])
94 except IOError, inst:
94 except IOError, inst:
95 if hasattr(inst, "code"):
95 if hasattr(inst, "code"):
96 ui.warn(_("abort: %s\n") % inst)
96 ui.warn(_("abort: %s\n") % inst)
97 elif hasattr(inst, "reason"):
97 elif hasattr(inst, "reason"):
98 try: # usually it is in the form (errno, strerror)
98 try: # usually it is in the form (errno, strerror)
99 reason = inst.reason.args[1]
99 reason = inst.reason.args[1]
100 except: # it might be anything, for example a string
100 except: # it might be anything, for example a string
101 reason = inst.reason
101 reason = inst.reason
102 ui.warn(_("abort: error: %s\n") % reason)
102 ui.warn(_("abort: error: %s\n") % reason)
103 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
103 elif hasattr(inst, "args") and inst[0] == errno.EPIPE:
104 if ui.debugflag:
104 if ui.debugflag:
105 ui.warn(_("broken pipe\n"))
105 ui.warn(_("broken pipe\n"))
106 elif getattr(inst, "strerror", None):
106 elif getattr(inst, "strerror", None):
107 if getattr(inst, "filename", None):
107 if getattr(inst, "filename", None):
108 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
108 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
109 else:
109 else:
110 ui.warn(_("abort: %s\n") % inst.strerror)
110 ui.warn(_("abort: %s\n") % inst.strerror)
111 else:
111 else:
112 raise
112 raise
113 except OSError, inst:
113 except OSError, inst:
114 if getattr(inst, "filename", None):
114 if getattr(inst, "filename", None):
115 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
115 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
116 else:
116 else:
117 ui.warn(_("abort: %s\n") % inst.strerror)
117 ui.warn(_("abort: %s\n") % inst.strerror)
118 except util.UnexpectedOutput, inst:
118 except util.UnexpectedOutput, inst:
119 ui.warn(_("abort: %s") % inst[0])
119 ui.warn(_("abort: %s") % inst[0])
120 if not isinstance(inst[1], basestring):
120 if not isinstance(inst[1], basestring):
121 ui.warn(" %r\n" % (inst[1],))
121 ui.warn(" %r\n" % (inst[1],))
122 elif not inst[1]:
122 elif not inst[1]:
123 ui.warn(_(" empty string\n"))
123 ui.warn(_(" empty string\n"))
124 else:
124 else:
125 ui.warn("\n%r\n" % util.ellipsis(inst[1]))
125 ui.warn("\n%r\n" % util.ellipsis(inst[1]))
126 except ImportError, inst:
126 except ImportError, inst:
127 m = str(inst).split()[-1]
127 m = str(inst).split()[-1]
128 ui.warn(_("abort: could not import module %s!\n") % m)
128 ui.warn(_("abort: could not import module %s!\n") % m)
129 if m in "mpatch bdiff".split():
129 if m in "mpatch bdiff".split():
130 ui.warn(_("(did you forget to compile extensions?)\n"))
130 ui.warn(_("(did you forget to compile extensions?)\n"))
131 elif m in "zlib".split():
131 elif m in "zlib".split():
132 ui.warn(_("(is your Python install correct?)\n"))
132 ui.warn(_("(is your Python install correct?)\n"))
133
133
134 except util.Abort, inst:
134 except util.Abort, inst:
135 ui.warn(_("abort: %s\n") % inst)
135 ui.warn(_("abort: %s\n") % inst)
136 except MemoryError:
136 except MemoryError:
137 ui.warn(_("abort: out of memory\n"))
137 ui.warn(_("abort: out of memory\n"))
138 except SystemExit, inst:
138 except SystemExit, inst:
139 # Commands shouldn't sys.exit directly, but give a return code.
139 # Commands shouldn't sys.exit directly, but give a return code.
140 # Just in case catch this and and pass exit code to caller.
140 # Just in case catch this and and pass exit code to caller.
141 return inst.code
141 return inst.code
142 except:
142 except:
143 ui.warn(_("** unknown exception encountered, details follow\n"))
143 ui.warn(_("** unknown exception encountered, details follow\n"))
144 ui.warn(_("** report bug details to "
144 ui.warn(_("** report bug details to "
145 "http://www.selenic.com/mercurial/bts\n"))
145 "http://www.selenic.com/mercurial/bts\n"))
146 ui.warn(_("** or mercurial@selenic.com\n"))
146 ui.warn(_("** or mercurial@selenic.com\n"))
147 ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
147 ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
148 % version.get_version())
148 % version.get_version())
149 ui.warn(_("** Extensions loaded: %s\n")
149 ui.warn(_("** Extensions loaded: %s\n")
150 % ", ".join([x[0] for x in extensions.extensions()]))
150 % ", ".join([x[0] for x in extensions.extensions()]))
151 raise
151 raise
152
152
153 return -1
153 return -1
154
154
155 def _findrepo(p):
155 def _findrepo(p):
156 while not os.path.isdir(os.path.join(p, ".hg")):
156 while not os.path.isdir(os.path.join(p, ".hg")):
157 oldp, p = p, os.path.dirname(p)
157 oldp, p = p, os.path.dirname(p)
158 if p == oldp:
158 if p == oldp:
159 return None
159 return None
160
160
161 return p
161 return p
162
162
163 def _parse(ui, args):
163 def _parse(ui, args):
164 options = {}
164 options = {}
165 cmdoptions = {}
165 cmdoptions = {}
166
166
167 try:
167 try:
168 args = fancyopts.fancyopts(args, commands.globalopts, options)
168 args = fancyopts.fancyopts(args, commands.globalopts, options)
169 except fancyopts.getopt.GetoptError, inst:
169 except fancyopts.getopt.GetoptError, inst:
170 raise ParseError(None, inst)
170 raise ParseError(None, inst)
171
171
172 if args:
172 if args:
173 cmd, args = args[0], args[1:]
173 cmd, args = args[0], args[1:]
174 aliases, i = cmdutil.findcmd(cmd, commands.table,
174 aliases, i = cmdutil.findcmd(cmd, commands.table,
175 ui.config("ui","strict"))
175 ui.config("ui", "strict"))
176 cmd = aliases[0]
176 cmd = aliases[0]
177 defaults = ui.config("defaults", cmd)
177 defaults = ui.config("defaults", cmd)
178 if defaults:
178 if defaults:
179 args = shlex.split(defaults) + args
179 args = shlex.split(defaults) + args
180 c = list(i[1])
180 c = list(i[1])
181 else:
181 else:
182 cmd = None
182 cmd = None
183 c = []
183 c = []
184
184
185 # combine global options into local
185 # combine global options into local
186 for o in commands.globalopts:
186 for o in commands.globalopts:
187 c.append((o[0], o[1], options[o[1]], o[3]))
187 c.append((o[0], o[1], options[o[1]], o[3]))
188
188
189 try:
189 try:
190 args = fancyopts.fancyopts(args, c, cmdoptions)
190 args = fancyopts.fancyopts(args, c, cmdoptions)
191 except fancyopts.getopt.GetoptError, inst:
191 except fancyopts.getopt.GetoptError, inst:
192 raise ParseError(cmd, inst)
192 raise ParseError(cmd, inst)
193
193
194 # separate global options back out
194 # separate global options back out
195 for o in commands.globalopts:
195 for o in commands.globalopts:
196 n = o[1]
196 n = o[1]
197 options[n] = cmdoptions[n]
197 options[n] = cmdoptions[n]
198 del cmdoptions[n]
198 del cmdoptions[n]
199
199
200 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
200 return (cmd, cmd and i[0] or None, args, options, cmdoptions)
201
201
202 def _parseconfig(config):
202 def _parseconfig(config):
203 """parse the --config options from the command line"""
203 """parse the --config options from the command line"""
204 parsed = []
204 parsed = []
205 for cfg in config:
205 for cfg in config:
206 try:
206 try:
207 name, value = cfg.split('=', 1)
207 name, value = cfg.split('=', 1)
208 section, name = name.split('.', 1)
208 section, name = name.split('.', 1)
209 if not section or not name:
209 if not section or not name:
210 raise IndexError
210 raise IndexError
211 parsed.append((section, name, value))
211 parsed.append((section, name, value))
212 except (IndexError, ValueError):
212 except (IndexError, ValueError):
213 raise util.Abort(_('malformed --config option: %s') % cfg)
213 raise util.Abort(_('malformed --config option: %s') % cfg)
214 return parsed
214 return parsed
215
215
216 def _earlygetopt(aliases, args):
216 def _earlygetopt(aliases, args):
217 """Return list of values for an option (or aliases).
217 """Return list of values for an option (or aliases).
218
218
219 The values are listed in the order they appear in args.
219 The values are listed in the order they appear in args.
220 The options and values are removed from args.
220 The options and values are removed from args.
221 """
221 """
222 try:
222 try:
223 argcount = args.index("--")
223 argcount = args.index("--")
224 except ValueError:
224 except ValueError:
225 argcount = len(args)
225 argcount = len(args)
226 shortopts = [opt for opt in aliases if len(opt) == 2]
226 shortopts = [opt for opt in aliases if len(opt) == 2]
227 values = []
227 values = []
228 pos = 0
228 pos = 0
229 while pos < argcount:
229 while pos < argcount:
230 if args[pos] in aliases:
230 if args[pos] in aliases:
231 if pos + 1 >= argcount:
231 if pos + 1 >= argcount:
232 # ignore and let getopt report an error if there is no value
232 # ignore and let getopt report an error if there is no value
233 break
233 break
234 del args[pos]
234 del args[pos]
235 values.append(args.pop(pos))
235 values.append(args.pop(pos))
236 argcount -= 2
236 argcount -= 2
237 elif args[pos][:2] in shortopts:
237 elif args[pos][:2] in shortopts:
238 # short option can have no following space, e.g. hg log -Rfoo
238 # short option can have no following space, e.g. hg log -Rfoo
239 values.append(args.pop(pos)[2:])
239 values.append(args.pop(pos)[2:])
240 argcount -= 1
240 argcount -= 1
241 else:
241 else:
242 pos += 1
242 pos += 1
243 return values
243 return values
244
244
245 _loaded = {}
245 _loaded = {}
246 def _dispatch(ui, args):
246 def _dispatch(ui, args):
247 # read --config before doing anything else
247 # read --config before doing anything else
248 # (e.g. to change trust settings for reading .hg/hgrc)
248 # (e.g. to change trust settings for reading .hg/hgrc)
249 config = _earlygetopt(['--config'], args)
249 config = _earlygetopt(['--config'], args)
250 if config:
250 if config:
251 ui.updateopts(config=_parseconfig(config))
251 ui.updateopts(config=_parseconfig(config))
252
252
253 # check for cwd
253 # check for cwd
254 cwd = _earlygetopt(['--cwd'], args)
254 cwd = _earlygetopt(['--cwd'], args)
255 if cwd:
255 if cwd:
256 os.chdir(cwd[-1])
256 os.chdir(cwd[-1])
257
257
258 # read the local repository .hgrc into a local ui object
258 # read the local repository .hgrc into a local ui object
259 path = _findrepo(os.getcwd()) or ""
259 path = _findrepo(os.getcwd()) or ""
260 if not path:
260 if not path:
261 lui = ui
261 lui = ui
262 if path:
262 if path:
263 try:
263 try:
264 lui = _ui.ui(parentui=ui)
264 lui = _ui.ui(parentui=ui)
265 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
265 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
266 except IOError:
266 except IOError:
267 pass
267 pass
268
268
269 # now we can expand paths, even ones in .hg/hgrc
269 # now we can expand paths, even ones in .hg/hgrc
270 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
270 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
271 if rpath:
271 if rpath:
272 path = lui.expandpath(rpath[-1])
272 path = lui.expandpath(rpath[-1])
273 lui = _ui.ui(parentui=ui)
273 lui = _ui.ui(parentui=ui)
274 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
274 lui.readconfig(os.path.join(path, ".hg", "hgrc"))
275
275
276 extensions.loadall(lui)
276 extensions.loadall(lui)
277 for name, module in extensions.extensions():
277 for name, module in extensions.extensions():
278 if name in _loaded:
278 if name in _loaded:
279 continue
279 continue
280
280
281 # setup extensions
281 # setup extensions
282 # TODO this should be generalized to scheme, where extensions can
282 # TODO this should be generalized to scheme, where extensions can
283 # redepend on other extensions. then we should toposort them, and
283 # redepend on other extensions. then we should toposort them, and
284 # do initialization in correct order
284 # do initialization in correct order
285 extsetup = getattr(module, 'extsetup', None)
285 extsetup = getattr(module, 'extsetup', None)
286 if extsetup:
286 if extsetup:
287 extsetup()
287 extsetup()
288
288
289 cmdtable = getattr(module, 'cmdtable', {})
289 cmdtable = getattr(module, 'cmdtable', {})
290 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
290 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
291 if overrides:
291 if overrides:
292 ui.warn(_("extension '%s' overrides commands: %s\n")
292 ui.warn(_("extension '%s' overrides commands: %s\n")
293 % (name, " ".join(overrides)))
293 % (name, " ".join(overrides)))
294 commands.table.update(cmdtable)
294 commands.table.update(cmdtable)
295 _loaded[name] = 1
295 _loaded[name] = 1
296 # check for fallback encoding
296 # check for fallback encoding
297 fallback = lui.config('ui', 'fallbackencoding')
297 fallback = lui.config('ui', 'fallbackencoding')
298 if fallback:
298 if fallback:
299 util._fallbackencoding = fallback
299 util._fallbackencoding = fallback
300
300
301 fullargs = args
301 fullargs = args
302 cmd, func, args, options, cmdoptions = _parse(lui, args)
302 cmd, func, args, options, cmdoptions = _parse(lui, args)
303
303
304 if options["config"]:
304 if options["config"]:
305 raise util.Abort(_("Option --config may not be abbreviated!"))
305 raise util.Abort(_("Option --config may not be abbreviated!"))
306 if options["cwd"]:
306 if options["cwd"]:
307 raise util.Abort(_("Option --cwd may not be abbreviated!"))
307 raise util.Abort(_("Option --cwd may not be abbreviated!"))
308 if options["repository"]:
308 if options["repository"]:
309 raise util.Abort(_(
309 raise util.Abort(_(
310 "Option -R has to be separated from other options (i.e. not -qR) "
310 "Option -R has to be separated from other options (i.e. not -qR) "
311 "and --repository may only be abbreviated as --repo!"))
311 "and --repository may only be abbreviated as --repo!"))
312
312
313 if options["encoding"]:
313 if options["encoding"]:
314 util._encoding = options["encoding"]
314 util._encoding = options["encoding"]
315 if options["encodingmode"]:
315 if options["encodingmode"]:
316 util._encodingmode = options["encodingmode"]
316 util._encodingmode = options["encodingmode"]
317 if options["time"]:
317 if options["time"]:
318 def get_times():
318 def get_times():
319 t = os.times()
319 t = os.times()
320 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
320 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
321 t = (t[0], t[1], t[2], t[3], time.clock())
321 t = (t[0], t[1], t[2], t[3], time.clock())
322 return t
322 return t
323 s = get_times()
323 s = get_times()
324 def print_time():
324 def print_time():
325 t = get_times()
325 t = get_times()
326 ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
326 ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
327 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
327 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
328 atexit.register(print_time)
328 atexit.register(print_time)
329
329
330 ui.updateopts(options["verbose"], options["debug"], options["quiet"],
330 ui.updateopts(options["verbose"], options["debug"], options["quiet"],
331 not options["noninteractive"], options["traceback"])
331 not options["noninteractive"], options["traceback"])
332
332
333 if options['help']:
333 if options['help']:
334 return commands.help_(ui, cmd, options['version'])
334 return commands.help_(ui, cmd, options['version'])
335 elif options['version']:
335 elif options['version']:
336 return commands.version_(ui)
336 return commands.version_(ui)
337 elif not cmd:
337 elif not cmd:
338 return commands.help_(ui, 'shortlist')
338 return commands.help_(ui, 'shortlist')
339
339
340 repo = None
340 repo = None
341 if cmd not in commands.norepo.split():
341 if cmd not in commands.norepo.split():
342 try:
342 try:
343 repo = hg.repository(ui, path=path)
343 repo = hg.repository(ui, path=path)
344 ui = repo.ui
344 ui = repo.ui
345 if not repo.local():
345 if not repo.local():
346 raise util.Abort(_("repository '%s' is not local") % path)
346 raise util.Abort(_("repository '%s' is not local") % path)
347 ui.setconfig("bundle", "mainreporoot", repo.root)
347 ui.setconfig("bundle", "mainreporoot", repo.root)
348 except RepoError:
348 except RepoError:
349 if cmd not in commands.optionalrepo.split():
349 if cmd not in commands.optionalrepo.split():
350 if args and not path: # try to infer -R from command args
350 if args and not path: # try to infer -R from command args
351 repos = map(_findrepo, args)
351 repos = map(_findrepo, args)
352 guess = repos[0]
352 guess = repos[0]
353 if guess and repos.count(guess) == len(repos):
353 if guess and repos.count(guess) == len(repos):
354 return _dispatch(ui, ['--repository', guess] + fullargs)
354 return _dispatch(ui, ['--repository', guess] + fullargs)
355 if not path:
355 if not path:
356 raise RepoError(_("There is no Mercurial repository here"
356 raise RepoError(_("There is no Mercurial repository here"
357 " (.hg not found)"))
357 " (.hg not found)"))
358 raise
358 raise
359 d = lambda: func(ui, repo, *args, **cmdoptions)
359 d = lambda: func(ui, repo, *args, **cmdoptions)
360 else:
360 else:
361 d = lambda: func(ui, *args, **cmdoptions)
361 d = lambda: func(ui, *args, **cmdoptions)
362
362
363 # run pre-hook, and abort if it fails
363 # run pre-hook, and abort if it fails
364 ret = hook.hook(lui, repo, "pre-%s" % cmd, False, args=" ".join(fullargs))
364 ret = hook.hook(lui, repo, "pre-%s" % cmd, False, args=" ".join(fullargs))
365 if ret:
365 if ret:
366 return ret
366 return ret
367 ret = _runcommand(ui, options, cmd, d)
367 ret = _runcommand(ui, options, cmd, d)
368 # run post-hook, passing command result
368 # run post-hook, passing command result
369 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
369 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
370 result = ret)
370 result = ret)
371 return ret
371 return ret
372
372
373 def _runcommand(ui, options, cmd, cmdfunc):
373 def _runcommand(ui, options, cmd, cmdfunc):
374 def checkargs():
374 def checkargs():
375 try:
375 try:
376 return cmdfunc()
376 return cmdfunc()
377 except TypeError, inst:
377 except TypeError, inst:
378 # was this an argument error?
378 # was this an argument error?
379 tb = traceback.extract_tb(sys.exc_info()[2])
379 tb = traceback.extract_tb(sys.exc_info()[2])
380 if len(tb) != 2: # no
380 if len(tb) != 2: # no
381 raise
381 raise
382 raise ParseError(cmd, _("invalid arguments"))
382 raise ParseError(cmd, _("invalid arguments"))
383
383
384 if options['profile']:
384 if options['profile']:
385 import hotshot, hotshot.stats
385 import hotshot, hotshot.stats
386 prof = hotshot.Profile("hg.prof")
386 prof = hotshot.Profile("hg.prof")
387 try:
387 try:
388 try:
388 try:
389 return prof.runcall(checkargs)
389 return prof.runcall(checkargs)
390 except:
390 except:
391 try:
391 try:
392 ui.warn(_('exception raised - generating '
392 ui.warn(_('exception raised - generating '
393 'profile anyway\n'))
393 'profile anyway\n'))
394 except:
394 except:
395 pass
395 pass
396 raise
396 raise
397 finally:
397 finally:
398 prof.close()
398 prof.close()
399 stats = hotshot.stats.load("hg.prof")
399 stats = hotshot.stats.load("hg.prof")
400 stats.strip_dirs()
400 stats.strip_dirs()
401 stats.sort_stats('time', 'calls')
401 stats.sort_stats('time', 'calls')
402 stats.print_stats(40)
402 stats.print_stats(40)
403 elif options['lsprof']:
403 elif options['lsprof']:
404 try:
404 try:
405 from mercurial import lsprof
405 from mercurial import lsprof
406 except ImportError:
406 except ImportError:
407 raise util.Abort(_(
407 raise util.Abort(_(
408 'lsprof not available - install from '
408 'lsprof not available - install from '
409 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
409 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
410 p = lsprof.Profiler()
410 p = lsprof.Profiler()
411 p.enable(subcalls=True)
411 p.enable(subcalls=True)
412 try:
412 try:
413 return checkargs()
413 return checkargs()
414 finally:
414 finally:
415 p.disable()
415 p.disable()
416 stats = lsprof.Stats(p.getstats())
416 stats = lsprof.Stats(p.getstats())
417 stats.sort()
417 stats.sort()
418 stats.pprint(top=10, file=sys.stderr, climit=5)
418 stats.pprint(top=10, file=sys.stderr, climit=5)
419 else:
419 else:
420 return checkargs()
420 return checkargs()
General Comments 0
You need to be logged in to leave comments. Login now