##// END OF EJS Templates
dispatch: set config options on the request repo.ui
Idan Kamara -
r14754:189a7562 stable
parent child Browse files
Show More
@@ -1,723 +1,727
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 of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from i18n import _
8 from i18n import _
9 import os, sys, atexit, signal, pdb, socket, errno, shlex, time, traceback, re
9 import os, sys, atexit, signal, pdb, socket, errno, shlex, time, traceback, re
10 import util, commands, hg, fancyopts, extensions, hook, error
10 import util, commands, hg, fancyopts, extensions, hook, error
11 import cmdutil, encoding
11 import cmdutil, encoding
12 import ui as uimod
12 import ui as uimod
13
13
14 class request(object):
14 class request(object):
15 def __init__(self, args, ui=None, repo=None, fin=None, fout=None, ferr=None):
15 def __init__(self, args, ui=None, repo=None, fin=None, fout=None, ferr=None):
16 self.args = args
16 self.args = args
17 self.ui = ui
17 self.ui = ui
18 self.repo = repo
18 self.repo = repo
19
19
20 # input/output/error streams
20 # input/output/error streams
21 self.fin = fin
21 self.fin = fin
22 self.fout = fout
22 self.fout = fout
23 self.ferr = ferr
23 self.ferr = ferr
24
24
25 def run():
25 def run():
26 "run the command in sys.argv"
26 "run the command in sys.argv"
27 sys.exit(dispatch(request(sys.argv[1:])))
27 sys.exit(dispatch(request(sys.argv[1:])))
28
28
29 def dispatch(req):
29 def dispatch(req):
30 "run the command specified in req.args"
30 "run the command specified in req.args"
31 if req.ferr:
31 if req.ferr:
32 ferr = req.ferr
32 ferr = req.ferr
33 elif req.ui:
33 elif req.ui:
34 ferr = req.ui.ferr
34 ferr = req.ui.ferr
35 else:
35 else:
36 ferr = sys.stderr
36 ferr = sys.stderr
37
37
38 try:
38 try:
39 if not req.ui:
39 if not req.ui:
40 req.ui = uimod.ui()
40 req.ui = uimod.ui()
41 if '--traceback' in req.args:
41 if '--traceback' in req.args:
42 req.ui.setconfig('ui', 'traceback', 'on')
42 req.ui.setconfig('ui', 'traceback', 'on')
43
43
44 # set ui streams from the request
44 # set ui streams from the request
45 if req.fin:
45 if req.fin:
46 req.ui.fin = req.fin
46 req.ui.fin = req.fin
47 if req.fout:
47 if req.fout:
48 req.ui.fout = req.fout
48 req.ui.fout = req.fout
49 if req.ferr:
49 if req.ferr:
50 req.ui.ferr = req.ferr
50 req.ui.ferr = req.ferr
51 except util.Abort, inst:
51 except util.Abort, inst:
52 ferr.write(_("abort: %s\n") % inst)
52 ferr.write(_("abort: %s\n") % inst)
53 if inst.hint:
53 if inst.hint:
54 ferr.write(_("(%s)\n") % inst.hint)
54 ferr.write(_("(%s)\n") % inst.hint)
55 return -1
55 return -1
56 except error.ParseError, inst:
56 except error.ParseError, inst:
57 if len(inst.args) > 1:
57 if len(inst.args) > 1:
58 ferr.write(_("hg: parse error at %s: %s\n") %
58 ferr.write(_("hg: parse error at %s: %s\n") %
59 (inst.args[1], inst.args[0]))
59 (inst.args[1], inst.args[0]))
60 else:
60 else:
61 ferr.write(_("hg: parse error: %s\n") % inst.args[0])
61 ferr.write(_("hg: parse error: %s\n") % inst.args[0])
62 return -1
62 return -1
63
63
64 return _runcatch(req)
64 return _runcatch(req)
65
65
66 def _runcatch(req):
66 def _runcatch(req):
67 def catchterm(*args):
67 def catchterm(*args):
68 raise error.SignalInterrupt
68 raise error.SignalInterrupt
69
69
70 ui = req.ui
70 ui = req.ui
71 try:
71 try:
72 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
72 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
73 num = getattr(signal, name, None)
73 num = getattr(signal, name, None)
74 if num:
74 if num:
75 signal.signal(num, catchterm)
75 signal.signal(num, catchterm)
76 except ValueError:
76 except ValueError:
77 pass # happens if called in a thread
77 pass # happens if called in a thread
78
78
79 try:
79 try:
80 try:
80 try:
81 # enter the debugger before command execution
81 # enter the debugger before command execution
82 if '--debugger' in req.args:
82 if '--debugger' in req.args:
83 ui.warn(_("entering debugger - "
83 ui.warn(_("entering debugger - "
84 "type c to continue starting hg or h for help\n"))
84 "type c to continue starting hg or h for help\n"))
85 pdb.set_trace()
85 pdb.set_trace()
86 try:
86 try:
87 return _dispatch(req)
87 return _dispatch(req)
88 finally:
88 finally:
89 ui.flush()
89 ui.flush()
90 except:
90 except:
91 # enter the debugger when we hit an exception
91 # enter the debugger when we hit an exception
92 if '--debugger' in req.args:
92 if '--debugger' in req.args:
93 traceback.print_exc()
93 traceback.print_exc()
94 pdb.post_mortem(sys.exc_info()[2])
94 pdb.post_mortem(sys.exc_info()[2])
95 ui.traceback()
95 ui.traceback()
96 raise
96 raise
97
97
98 # Global exception handling, alphabetically
98 # Global exception handling, alphabetically
99 # Mercurial-specific first, followed by built-in and library exceptions
99 # Mercurial-specific first, followed by built-in and library exceptions
100 except error.AmbiguousCommand, inst:
100 except error.AmbiguousCommand, inst:
101 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
101 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
102 (inst.args[0], " ".join(inst.args[1])))
102 (inst.args[0], " ".join(inst.args[1])))
103 except error.ParseError, inst:
103 except error.ParseError, inst:
104 if len(inst.args) > 1:
104 if len(inst.args) > 1:
105 ui.warn(_("hg: parse error at %s: %s\n") %
105 ui.warn(_("hg: parse error at %s: %s\n") %
106 (inst.args[1], inst.args[0]))
106 (inst.args[1], inst.args[0]))
107 else:
107 else:
108 ui.warn(_("hg: parse error: %s\n") % inst.args[0])
108 ui.warn(_("hg: parse error: %s\n") % inst.args[0])
109 return -1
109 return -1
110 except error.LockHeld, inst:
110 except error.LockHeld, inst:
111 if inst.errno == errno.ETIMEDOUT:
111 if inst.errno == errno.ETIMEDOUT:
112 reason = _('timed out waiting for lock held by %s') % inst.locker
112 reason = _('timed out waiting for lock held by %s') % inst.locker
113 else:
113 else:
114 reason = _('lock held by %s') % inst.locker
114 reason = _('lock held by %s') % inst.locker
115 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
115 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
116 except error.LockUnavailable, inst:
116 except error.LockUnavailable, inst:
117 ui.warn(_("abort: could not lock %s: %s\n") %
117 ui.warn(_("abort: could not lock %s: %s\n") %
118 (inst.desc or inst.filename, inst.strerror))
118 (inst.desc or inst.filename, inst.strerror))
119 except error.CommandError, inst:
119 except error.CommandError, inst:
120 if inst.args[0]:
120 if inst.args[0]:
121 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
121 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
122 commands.help_(ui, inst.args[0], full=False, command=True)
122 commands.help_(ui, inst.args[0], full=False, command=True)
123 else:
123 else:
124 ui.warn(_("hg: %s\n") % inst.args[1])
124 ui.warn(_("hg: %s\n") % inst.args[1])
125 commands.help_(ui, 'shortlist')
125 commands.help_(ui, 'shortlist')
126 except error.RepoError, inst:
126 except error.RepoError, inst:
127 ui.warn(_("abort: %s!\n") % inst)
127 ui.warn(_("abort: %s!\n") % inst)
128 except error.ResponseError, inst:
128 except error.ResponseError, inst:
129 ui.warn(_("abort: %s") % inst.args[0])
129 ui.warn(_("abort: %s") % inst.args[0])
130 if not isinstance(inst.args[1], basestring):
130 if not isinstance(inst.args[1], basestring):
131 ui.warn(" %r\n" % (inst.args[1],))
131 ui.warn(" %r\n" % (inst.args[1],))
132 elif not inst.args[1]:
132 elif not inst.args[1]:
133 ui.warn(_(" empty string\n"))
133 ui.warn(_(" empty string\n"))
134 else:
134 else:
135 ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
135 ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
136 except error.RevlogError, inst:
136 except error.RevlogError, inst:
137 ui.warn(_("abort: %s!\n") % inst)
137 ui.warn(_("abort: %s!\n") % inst)
138 except error.SignalInterrupt:
138 except error.SignalInterrupt:
139 ui.warn(_("killed!\n"))
139 ui.warn(_("killed!\n"))
140 except error.UnknownCommand, inst:
140 except error.UnknownCommand, inst:
141 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
141 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
142 try:
142 try:
143 # check if the command is in a disabled extension
143 # check if the command is in a disabled extension
144 # (but don't check for extensions themselves)
144 # (but don't check for extensions themselves)
145 commands.help_(ui, inst.args[0], unknowncmd=True)
145 commands.help_(ui, inst.args[0], unknowncmd=True)
146 except error.UnknownCommand:
146 except error.UnknownCommand:
147 commands.help_(ui, 'shortlist')
147 commands.help_(ui, 'shortlist')
148 except util.Abort, inst:
148 except util.Abort, inst:
149 ui.warn(_("abort: %s\n") % inst)
149 ui.warn(_("abort: %s\n") % inst)
150 if inst.hint:
150 if inst.hint:
151 ui.warn(_("(%s)\n") % inst.hint)
151 ui.warn(_("(%s)\n") % inst.hint)
152 except ImportError, inst:
152 except ImportError, inst:
153 ui.warn(_("abort: %s!\n") % inst)
153 ui.warn(_("abort: %s!\n") % inst)
154 m = str(inst).split()[-1]
154 m = str(inst).split()[-1]
155 if m in "mpatch bdiff".split():
155 if m in "mpatch bdiff".split():
156 ui.warn(_("(did you forget to compile extensions?)\n"))
156 ui.warn(_("(did you forget to compile extensions?)\n"))
157 elif m in "zlib".split():
157 elif m in "zlib".split():
158 ui.warn(_("(is your Python install correct?)\n"))
158 ui.warn(_("(is your Python install correct?)\n"))
159 except IOError, inst:
159 except IOError, inst:
160 if hasattr(inst, "code"):
160 if hasattr(inst, "code"):
161 ui.warn(_("abort: %s\n") % inst)
161 ui.warn(_("abort: %s\n") % inst)
162 elif hasattr(inst, "reason"):
162 elif hasattr(inst, "reason"):
163 try: # usually it is in the form (errno, strerror)
163 try: # usually it is in the form (errno, strerror)
164 reason = inst.reason.args[1]
164 reason = inst.reason.args[1]
165 except (AttributeError, IndexError):
165 except (AttributeError, IndexError):
166 # it might be anything, for example a string
166 # it might be anything, for example a string
167 reason = inst.reason
167 reason = inst.reason
168 ui.warn(_("abort: error: %s\n") % reason)
168 ui.warn(_("abort: error: %s\n") % reason)
169 elif hasattr(inst, "args") and inst.args[0] == errno.EPIPE:
169 elif hasattr(inst, "args") and inst.args[0] == errno.EPIPE:
170 if ui.debugflag:
170 if ui.debugflag:
171 ui.warn(_("broken pipe\n"))
171 ui.warn(_("broken pipe\n"))
172 elif getattr(inst, "strerror", None):
172 elif getattr(inst, "strerror", None):
173 if getattr(inst, "filename", None):
173 if getattr(inst, "filename", None):
174 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
174 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
175 else:
175 else:
176 ui.warn(_("abort: %s\n") % inst.strerror)
176 ui.warn(_("abort: %s\n") % inst.strerror)
177 else:
177 else:
178 raise
178 raise
179 except OSError, inst:
179 except OSError, inst:
180 if getattr(inst, "filename", None):
180 if getattr(inst, "filename", None):
181 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
181 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
182 else:
182 else:
183 ui.warn(_("abort: %s\n") % inst.strerror)
183 ui.warn(_("abort: %s\n") % inst.strerror)
184 except KeyboardInterrupt:
184 except KeyboardInterrupt:
185 try:
185 try:
186 ui.warn(_("interrupted!\n"))
186 ui.warn(_("interrupted!\n"))
187 except IOError, inst:
187 except IOError, inst:
188 if inst.errno == errno.EPIPE:
188 if inst.errno == errno.EPIPE:
189 if ui.debugflag:
189 if ui.debugflag:
190 ui.warn(_("\nbroken pipe\n"))
190 ui.warn(_("\nbroken pipe\n"))
191 else:
191 else:
192 raise
192 raise
193 except MemoryError:
193 except MemoryError:
194 ui.warn(_("abort: out of memory\n"))
194 ui.warn(_("abort: out of memory\n"))
195 except SystemExit, inst:
195 except SystemExit, inst:
196 # Commands shouldn't sys.exit directly, but give a return code.
196 # Commands shouldn't sys.exit directly, but give a return code.
197 # Just in case catch this and and pass exit code to caller.
197 # Just in case catch this and and pass exit code to caller.
198 return inst.code
198 return inst.code
199 except socket.error, inst:
199 except socket.error, inst:
200 ui.warn(_("abort: %s\n") % inst.args[-1])
200 ui.warn(_("abort: %s\n") % inst.args[-1])
201 except:
201 except:
202 ui.warn(_("** unknown exception encountered,"
202 ui.warn(_("** unknown exception encountered,"
203 " please report by visiting\n"))
203 " please report by visiting\n"))
204 ui.warn(_("** http://mercurial.selenic.com/wiki/BugTracker\n"))
204 ui.warn(_("** http://mercurial.selenic.com/wiki/BugTracker\n"))
205 ui.warn(_("** Python %s\n") % sys.version.replace('\n', ''))
205 ui.warn(_("** Python %s\n") % sys.version.replace('\n', ''))
206 ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
206 ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
207 % util.version())
207 % util.version())
208 ui.warn(_("** Extensions loaded: %s\n")
208 ui.warn(_("** Extensions loaded: %s\n")
209 % ", ".join([x[0] for x in extensions.extensions()]))
209 % ", ".join([x[0] for x in extensions.extensions()]))
210 raise
210 raise
211
211
212 return -1
212 return -1
213
213
214 def aliasargs(fn, givenargs):
214 def aliasargs(fn, givenargs):
215 args = getattr(fn, 'args', [])
215 args = getattr(fn, 'args', [])
216 if args and givenargs:
216 if args and givenargs:
217 cmd = ' '.join(map(util.shellquote, args))
217 cmd = ' '.join(map(util.shellquote, args))
218
218
219 nums = []
219 nums = []
220 def replacer(m):
220 def replacer(m):
221 num = int(m.group(1)) - 1
221 num = int(m.group(1)) - 1
222 nums.append(num)
222 nums.append(num)
223 return givenargs[num]
223 return givenargs[num]
224 cmd = re.sub(r'\$(\d+|\$)', replacer, cmd)
224 cmd = re.sub(r'\$(\d+|\$)', replacer, cmd)
225 givenargs = [x for i, x in enumerate(givenargs)
225 givenargs = [x for i, x in enumerate(givenargs)
226 if i not in nums]
226 if i not in nums]
227 args = shlex.split(cmd)
227 args = shlex.split(cmd)
228 return args + givenargs
228 return args + givenargs
229
229
230 class cmdalias(object):
230 class cmdalias(object):
231 def __init__(self, name, definition, cmdtable):
231 def __init__(self, name, definition, cmdtable):
232 self.name = self.cmd = name
232 self.name = self.cmd = name
233 self.cmdname = ''
233 self.cmdname = ''
234 self.definition = definition
234 self.definition = definition
235 self.args = []
235 self.args = []
236 self.opts = []
236 self.opts = []
237 self.help = ''
237 self.help = ''
238 self.norepo = True
238 self.norepo = True
239 self.badalias = False
239 self.badalias = False
240
240
241 try:
241 try:
242 aliases, entry = cmdutil.findcmd(self.name, cmdtable)
242 aliases, entry = cmdutil.findcmd(self.name, cmdtable)
243 for alias, e in cmdtable.iteritems():
243 for alias, e in cmdtable.iteritems():
244 if e is entry:
244 if e is entry:
245 self.cmd = alias
245 self.cmd = alias
246 break
246 break
247 self.shadows = True
247 self.shadows = True
248 except error.UnknownCommand:
248 except error.UnknownCommand:
249 self.shadows = False
249 self.shadows = False
250
250
251 if not self.definition:
251 if not self.definition:
252 def fn(ui, *args):
252 def fn(ui, *args):
253 ui.warn(_("no definition for alias '%s'\n") % self.name)
253 ui.warn(_("no definition for alias '%s'\n") % self.name)
254 return 1
254 return 1
255 self.fn = fn
255 self.fn = fn
256 self.badalias = True
256 self.badalias = True
257
257
258 return
258 return
259
259
260 if self.definition.startswith('!'):
260 if self.definition.startswith('!'):
261 self.shell = True
261 self.shell = True
262 def fn(ui, *args):
262 def fn(ui, *args):
263 env = {'HG_ARGS': ' '.join((self.name,) + args)}
263 env = {'HG_ARGS': ' '.join((self.name,) + args)}
264 def _checkvar(m):
264 def _checkvar(m):
265 if m.groups()[0] == '$':
265 if m.groups()[0] == '$':
266 return m.group()
266 return m.group()
267 elif int(m.groups()[0]) <= len(args):
267 elif int(m.groups()[0]) <= len(args):
268 return m.group()
268 return m.group()
269 else:
269 else:
270 ui.debug("No argument found for substitution "
270 ui.debug("No argument found for substitution "
271 "of %i variable in alias '%s' definition."
271 "of %i variable in alias '%s' definition."
272 % (int(m.groups()[0]), self.name))
272 % (int(m.groups()[0]), self.name))
273 return ''
273 return ''
274 cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
274 cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
275 replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
275 replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
276 replace['0'] = self.name
276 replace['0'] = self.name
277 replace['@'] = ' '.join(args)
277 replace['@'] = ' '.join(args)
278 cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
278 cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
279 return util.system(cmd, environ=env, out=ui.fout)
279 return util.system(cmd, environ=env, out=ui.fout)
280 self.fn = fn
280 self.fn = fn
281 return
281 return
282
282
283 args = shlex.split(self.definition)
283 args = shlex.split(self.definition)
284 self.cmdname = cmd = args.pop(0)
284 self.cmdname = cmd = args.pop(0)
285 args = map(util.expandpath, args)
285 args = map(util.expandpath, args)
286
286
287 for invalidarg in ("--cwd", "-R", "--repository", "--repo"):
287 for invalidarg in ("--cwd", "-R", "--repository", "--repo"):
288 if _earlygetopt([invalidarg], args):
288 if _earlygetopt([invalidarg], args):
289 def fn(ui, *args):
289 def fn(ui, *args):
290 ui.warn(_("error in definition for alias '%s': %s may only "
290 ui.warn(_("error in definition for alias '%s': %s may only "
291 "be given on the command line\n")
291 "be given on the command line\n")
292 % (self.name, invalidarg))
292 % (self.name, invalidarg))
293 return 1
293 return 1
294
294
295 self.fn = fn
295 self.fn = fn
296 self.badalias = True
296 self.badalias = True
297 return
297 return
298
298
299 try:
299 try:
300 tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
300 tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
301 if len(tableentry) > 2:
301 if len(tableentry) > 2:
302 self.fn, self.opts, self.help = tableentry
302 self.fn, self.opts, self.help = tableentry
303 else:
303 else:
304 self.fn, self.opts = tableentry
304 self.fn, self.opts = tableentry
305
305
306 self.args = aliasargs(self.fn, args)
306 self.args = aliasargs(self.fn, args)
307 if cmd not in commands.norepo.split(' '):
307 if cmd not in commands.norepo.split(' '):
308 self.norepo = False
308 self.norepo = False
309 if self.help.startswith("hg " + cmd):
309 if self.help.startswith("hg " + cmd):
310 # drop prefix in old-style help lines so hg shows the alias
310 # drop prefix in old-style help lines so hg shows the alias
311 self.help = self.help[4 + len(cmd):]
311 self.help = self.help[4 + len(cmd):]
312 self.__doc__ = self.fn.__doc__
312 self.__doc__ = self.fn.__doc__
313
313
314 except error.UnknownCommand:
314 except error.UnknownCommand:
315 def fn(ui, *args):
315 def fn(ui, *args):
316 ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
316 ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
317 % (self.name, cmd))
317 % (self.name, cmd))
318 try:
318 try:
319 # check if the command is in a disabled extension
319 # check if the command is in a disabled extension
320 commands.help_(ui, cmd, unknowncmd=True)
320 commands.help_(ui, cmd, unknowncmd=True)
321 except error.UnknownCommand:
321 except error.UnknownCommand:
322 pass
322 pass
323 return 1
323 return 1
324 self.fn = fn
324 self.fn = fn
325 self.badalias = True
325 self.badalias = True
326 except error.AmbiguousCommand:
326 except error.AmbiguousCommand:
327 def fn(ui, *args):
327 def fn(ui, *args):
328 ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
328 ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
329 % (self.name, cmd))
329 % (self.name, cmd))
330 return 1
330 return 1
331 self.fn = fn
331 self.fn = fn
332 self.badalias = True
332 self.badalias = True
333
333
334 def __call__(self, ui, *args, **opts):
334 def __call__(self, ui, *args, **opts):
335 if self.shadows:
335 if self.shadows:
336 ui.debug("alias '%s' shadows command '%s'\n" %
336 ui.debug("alias '%s' shadows command '%s'\n" %
337 (self.name, self.cmdname))
337 (self.name, self.cmdname))
338
338
339 if hasattr(self, 'shell'):
339 if hasattr(self, 'shell'):
340 return self.fn(ui, *args, **opts)
340 return self.fn(ui, *args, **opts)
341 else:
341 else:
342 try:
342 try:
343 util.checksignature(self.fn)(ui, *args, **opts)
343 util.checksignature(self.fn)(ui, *args, **opts)
344 except error.SignatureError:
344 except error.SignatureError:
345 args = ' '.join([self.cmdname] + self.args)
345 args = ' '.join([self.cmdname] + self.args)
346 ui.debug("alias '%s' expands to '%s'\n" % (self.name, args))
346 ui.debug("alias '%s' expands to '%s'\n" % (self.name, args))
347 raise
347 raise
348
348
349 def addaliases(ui, cmdtable):
349 def addaliases(ui, cmdtable):
350 # aliases are processed after extensions have been loaded, so they
350 # aliases are processed after extensions have been loaded, so they
351 # may use extension commands. Aliases can also use other alias definitions,
351 # may use extension commands. Aliases can also use other alias definitions,
352 # but only if they have been defined prior to the current definition.
352 # but only if they have been defined prior to the current definition.
353 for alias, definition in ui.configitems('alias'):
353 for alias, definition in ui.configitems('alias'):
354 aliasdef = cmdalias(alias, definition, cmdtable)
354 aliasdef = cmdalias(alias, definition, cmdtable)
355 cmdtable[aliasdef.cmd] = (aliasdef, aliasdef.opts, aliasdef.help)
355 cmdtable[aliasdef.cmd] = (aliasdef, aliasdef.opts, aliasdef.help)
356 if aliasdef.norepo:
356 if aliasdef.norepo:
357 commands.norepo += ' %s' % alias
357 commands.norepo += ' %s' % alias
358
358
359 def _parse(ui, args):
359 def _parse(ui, args):
360 options = {}
360 options = {}
361 cmdoptions = {}
361 cmdoptions = {}
362
362
363 try:
363 try:
364 args = fancyopts.fancyopts(args, commands.globalopts, options)
364 args = fancyopts.fancyopts(args, commands.globalopts, options)
365 except fancyopts.getopt.GetoptError, inst:
365 except fancyopts.getopt.GetoptError, inst:
366 raise error.CommandError(None, inst)
366 raise error.CommandError(None, inst)
367
367
368 if args:
368 if args:
369 cmd, args = args[0], args[1:]
369 cmd, args = args[0], args[1:]
370 aliases, entry = cmdutil.findcmd(cmd, commands.table,
370 aliases, entry = cmdutil.findcmd(cmd, commands.table,
371 ui.config("ui", "strict"))
371 ui.config("ui", "strict"))
372 cmd = aliases[0]
372 cmd = aliases[0]
373 args = aliasargs(entry[0], args)
373 args = aliasargs(entry[0], args)
374 defaults = ui.config("defaults", cmd)
374 defaults = ui.config("defaults", cmd)
375 if defaults:
375 if defaults:
376 args = map(util.expandpath, shlex.split(defaults)) + args
376 args = map(util.expandpath, shlex.split(defaults)) + args
377 c = list(entry[1])
377 c = list(entry[1])
378 else:
378 else:
379 cmd = None
379 cmd = None
380 c = []
380 c = []
381
381
382 # combine global options into local
382 # combine global options into local
383 for o in commands.globalopts:
383 for o in commands.globalopts:
384 c.append((o[0], o[1], options[o[1]], o[3]))
384 c.append((o[0], o[1], options[o[1]], o[3]))
385
385
386 try:
386 try:
387 args = fancyopts.fancyopts(args, c, cmdoptions, True)
387 args = fancyopts.fancyopts(args, c, cmdoptions, True)
388 except fancyopts.getopt.GetoptError, inst:
388 except fancyopts.getopt.GetoptError, inst:
389 raise error.CommandError(cmd, inst)
389 raise error.CommandError(cmd, inst)
390
390
391 # separate global options back out
391 # separate global options back out
392 for o in commands.globalopts:
392 for o in commands.globalopts:
393 n = o[1]
393 n = o[1]
394 options[n] = cmdoptions[n]
394 options[n] = cmdoptions[n]
395 del cmdoptions[n]
395 del cmdoptions[n]
396
396
397 return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
397 return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
398
398
399 def _parseconfig(ui, config):
399 def _parseconfig(ui, config):
400 """parse the --config options from the command line"""
400 """parse the --config options from the command line"""
401 configs = []
401 configs = []
402
402
403 for cfg in config:
403 for cfg in config:
404 try:
404 try:
405 name, value = cfg.split('=', 1)
405 name, value = cfg.split('=', 1)
406 section, name = name.split('.', 1)
406 section, name = name.split('.', 1)
407 if not section or not name:
407 if not section or not name:
408 raise IndexError
408 raise IndexError
409 ui.setconfig(section, name, value)
409 ui.setconfig(section, name, value)
410 configs.append((section, name, value))
410 configs.append((section, name, value))
411 except (IndexError, ValueError):
411 except (IndexError, ValueError):
412 raise util.Abort(_('malformed --config option: %r '
412 raise util.Abort(_('malformed --config option: %r '
413 '(use --config section.name=value)') % cfg)
413 '(use --config section.name=value)') % cfg)
414
414
415 return configs
415 return configs
416
416
417 def _earlygetopt(aliases, args):
417 def _earlygetopt(aliases, args):
418 """Return list of values for an option (or aliases).
418 """Return list of values for an option (or aliases).
419
419
420 The values are listed in the order they appear in args.
420 The values are listed in the order they appear in args.
421 The options and values are removed from args.
421 The options and values are removed from args.
422 """
422 """
423 try:
423 try:
424 argcount = args.index("--")
424 argcount = args.index("--")
425 except ValueError:
425 except ValueError:
426 argcount = len(args)
426 argcount = len(args)
427 shortopts = [opt for opt in aliases if len(opt) == 2]
427 shortopts = [opt for opt in aliases if len(opt) == 2]
428 values = []
428 values = []
429 pos = 0
429 pos = 0
430 while pos < argcount:
430 while pos < argcount:
431 if args[pos] in aliases:
431 if args[pos] in aliases:
432 if pos + 1 >= argcount:
432 if pos + 1 >= argcount:
433 # ignore and let getopt report an error if there is no value
433 # ignore and let getopt report an error if there is no value
434 break
434 break
435 del args[pos]
435 del args[pos]
436 values.append(args.pop(pos))
436 values.append(args.pop(pos))
437 argcount -= 2
437 argcount -= 2
438 elif args[pos][:2] in shortopts:
438 elif args[pos][:2] in shortopts:
439 # short option can have no following space, e.g. hg log -Rfoo
439 # short option can have no following space, e.g. hg log -Rfoo
440 values.append(args.pop(pos)[2:])
440 values.append(args.pop(pos)[2:])
441 argcount -= 1
441 argcount -= 1
442 else:
442 else:
443 pos += 1
443 pos += 1
444 return values
444 return values
445
445
446 def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
446 def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
447 # run pre-hook, and abort if it fails
447 # run pre-hook, and abort if it fails
448 ret = hook.hook(lui, repo, "pre-%s" % cmd, False, args=" ".join(fullargs),
448 ret = hook.hook(lui, repo, "pre-%s" % cmd, False, args=" ".join(fullargs),
449 pats=cmdpats, opts=cmdoptions)
449 pats=cmdpats, opts=cmdoptions)
450 if ret:
450 if ret:
451 return ret
451 return ret
452 ret = _runcommand(ui, options, cmd, d)
452 ret = _runcommand(ui, options, cmd, d)
453 # run post-hook, passing command result
453 # run post-hook, passing command result
454 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
454 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
455 result=ret, pats=cmdpats, opts=cmdoptions)
455 result=ret, pats=cmdpats, opts=cmdoptions)
456 return ret
456 return ret
457
457
458 def _getlocal(ui, rpath):
458 def _getlocal(ui, rpath):
459 """Return (path, local ui object) for the given target path.
459 """Return (path, local ui object) for the given target path.
460
460
461 Takes paths in [cwd]/.hg/hgrc into account."
461 Takes paths in [cwd]/.hg/hgrc into account."
462 """
462 """
463 try:
463 try:
464 wd = os.getcwd()
464 wd = os.getcwd()
465 except OSError, e:
465 except OSError, e:
466 raise util.Abort(_("error getting current working directory: %s") %
466 raise util.Abort(_("error getting current working directory: %s") %
467 e.strerror)
467 e.strerror)
468 path = cmdutil.findrepo(wd) or ""
468 path = cmdutil.findrepo(wd) or ""
469 if not path:
469 if not path:
470 lui = ui
470 lui = ui
471 else:
471 else:
472 lui = ui.copy()
472 lui = ui.copy()
473 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
473 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
474
474
475 if rpath:
475 if rpath:
476 path = lui.expandpath(rpath[-1])
476 path = lui.expandpath(rpath[-1])
477 lui = ui.copy()
477 lui = ui.copy()
478 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
478 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
479
479
480 return path, lui
480 return path, lui
481
481
482 def _checkshellalias(ui, args):
482 def _checkshellalias(ui, args):
483 cwd = os.getcwd()
483 cwd = os.getcwd()
484 norepo = commands.norepo
484 norepo = commands.norepo
485 options = {}
485 options = {}
486
486
487 try:
487 try:
488 args = fancyopts.fancyopts(args, commands.globalopts, options)
488 args = fancyopts.fancyopts(args, commands.globalopts, options)
489 except fancyopts.getopt.GetoptError:
489 except fancyopts.getopt.GetoptError:
490 return
490 return
491
491
492 if not args:
492 if not args:
493 return
493 return
494
494
495 _parseconfig(ui, options['config'])
495 _parseconfig(ui, options['config'])
496 if options['cwd']:
496 if options['cwd']:
497 os.chdir(options['cwd'])
497 os.chdir(options['cwd'])
498
498
499 path, lui = _getlocal(ui, [options['repository']])
499 path, lui = _getlocal(ui, [options['repository']])
500
500
501 cmdtable = commands.table.copy()
501 cmdtable = commands.table.copy()
502 addaliases(lui, cmdtable)
502 addaliases(lui, cmdtable)
503
503
504 cmd = args[0]
504 cmd = args[0]
505 try:
505 try:
506 aliases, entry = cmdutil.findcmd(cmd, cmdtable, lui.config("ui", "strict"))
506 aliases, entry = cmdutil.findcmd(cmd, cmdtable, lui.config("ui", "strict"))
507 except (error.AmbiguousCommand, error.UnknownCommand):
507 except (error.AmbiguousCommand, error.UnknownCommand):
508 commands.norepo = norepo
508 commands.norepo = norepo
509 os.chdir(cwd)
509 os.chdir(cwd)
510 return
510 return
511
511
512 cmd = aliases[0]
512 cmd = aliases[0]
513 fn = entry[0]
513 fn = entry[0]
514
514
515 if cmd and hasattr(fn, 'shell'):
515 if cmd and hasattr(fn, 'shell'):
516 d = lambda: fn(ui, *args[1:])
516 d = lambda: fn(ui, *args[1:])
517 return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [], {})
517 return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [], {})
518
518
519 commands.norepo = norepo
519 commands.norepo = norepo
520 os.chdir(cwd)
520 os.chdir(cwd)
521
521
522 _loaded = set()
522 _loaded = set()
523 def _dispatch(req):
523 def _dispatch(req):
524 args = req.args
524 args = req.args
525 ui = req.ui
525 ui = req.ui
526
526
527 shellaliasfn = _checkshellalias(ui, args)
527 shellaliasfn = _checkshellalias(ui, args)
528 if shellaliasfn:
528 if shellaliasfn:
529 return shellaliasfn()
529 return shellaliasfn()
530
530
531 # read --config before doing anything else
531 # read --config before doing anything else
532 # (e.g. to change trust settings for reading .hg/hgrc)
532 # (e.g. to change trust settings for reading .hg/hgrc)
533 _parseconfig(ui, _earlygetopt(['--config'], args))
533 cfgs = _parseconfig(ui, _earlygetopt(['--config'], args))
534
534
535 # check for cwd
535 # check for cwd
536 cwd = _earlygetopt(['--cwd'], args)
536 cwd = _earlygetopt(['--cwd'], args)
537 if cwd:
537 if cwd:
538 os.chdir(cwd[-1])
538 os.chdir(cwd[-1])
539
539
540 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
540 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
541 path, lui = _getlocal(ui, rpath)
541 path, lui = _getlocal(ui, rpath)
542
542
543 # Configure extensions in phases: uisetup, extsetup, cmdtable, and
543 # Configure extensions in phases: uisetup, extsetup, cmdtable, and
544 # reposetup. Programs like TortoiseHg will call _dispatch several
544 # reposetup. Programs like TortoiseHg will call _dispatch several
545 # times so we keep track of configured extensions in _loaded.
545 # times so we keep track of configured extensions in _loaded.
546 extensions.loadall(lui)
546 extensions.loadall(lui)
547 exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
547 exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
548 # Propagate any changes to lui.__class__ by extensions
548 # Propagate any changes to lui.__class__ by extensions
549 ui.__class__ = lui.__class__
549 ui.__class__ = lui.__class__
550
550
551 # (uisetup and extsetup are handled in extensions.loadall)
551 # (uisetup and extsetup are handled in extensions.loadall)
552
552
553 for name, module in exts:
553 for name, module in exts:
554 cmdtable = getattr(module, 'cmdtable', {})
554 cmdtable = getattr(module, 'cmdtable', {})
555 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
555 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
556 if overrides:
556 if overrides:
557 ui.warn(_("extension '%s' overrides commands: %s\n")
557 ui.warn(_("extension '%s' overrides commands: %s\n")
558 % (name, " ".join(overrides)))
558 % (name, " ".join(overrides)))
559 commands.table.update(cmdtable)
559 commands.table.update(cmdtable)
560 _loaded.add(name)
560 _loaded.add(name)
561
561
562 # (reposetup is handled in hg.repository)
562 # (reposetup is handled in hg.repository)
563
563
564 addaliases(lui, commands.table)
564 addaliases(lui, commands.table)
565
565
566 # check for fallback encoding
566 # check for fallback encoding
567 fallback = lui.config('ui', 'fallbackencoding')
567 fallback = lui.config('ui', 'fallbackencoding')
568 if fallback:
568 if fallback:
569 encoding.fallbackencoding = fallback
569 encoding.fallbackencoding = fallback
570
570
571 fullargs = args
571 fullargs = args
572 cmd, func, args, options, cmdoptions = _parse(lui, args)
572 cmd, func, args, options, cmdoptions = _parse(lui, args)
573
573
574 if options["config"]:
574 if options["config"]:
575 raise util.Abort(_("option --config may not be abbreviated!"))
575 raise util.Abort(_("option --config may not be abbreviated!"))
576 if options["cwd"]:
576 if options["cwd"]:
577 raise util.Abort(_("option --cwd may not be abbreviated!"))
577 raise util.Abort(_("option --cwd may not be abbreviated!"))
578 if options["repository"]:
578 if options["repository"]:
579 raise util.Abort(_(
579 raise util.Abort(_(
580 "Option -R has to be separated from other options (e.g. not -qR) "
580 "Option -R has to be separated from other options (e.g. not -qR) "
581 "and --repository may only be abbreviated as --repo!"))
581 "and --repository may only be abbreviated as --repo!"))
582
582
583 if options["encoding"]:
583 if options["encoding"]:
584 encoding.encoding = options["encoding"]
584 encoding.encoding = options["encoding"]
585 if options["encodingmode"]:
585 if options["encodingmode"]:
586 encoding.encodingmode = options["encodingmode"]
586 encoding.encodingmode = options["encodingmode"]
587 if options["time"]:
587 if options["time"]:
588 def get_times():
588 def get_times():
589 t = os.times()
589 t = os.times()
590 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
590 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
591 t = (t[0], t[1], t[2], t[3], time.clock())
591 t = (t[0], t[1], t[2], t[3], time.clock())
592 return t
592 return t
593 s = get_times()
593 s = get_times()
594 def print_time():
594 def print_time():
595 t = get_times()
595 t = get_times()
596 ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
596 ui.warn(_("Time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
597 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
597 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
598 atexit.register(print_time)
598 atexit.register(print_time)
599
599
600 uis = set([ui, lui])
600 uis = set([ui, lui])
601
601
602 if req.repo:
602 if req.repo:
603 uis.add(req.repo.ui)
603 uis.add(req.repo.ui)
604
604
605 # copy configs that were passed on the cmdline (--config) to the repo ui
606 for cfg in cfgs:
607 req.repo.ui.setconfig(*cfg)
608
605 for opt in ('verbose', 'debug', 'quiet', 'traceback'):
609 for opt in ('verbose', 'debug', 'quiet', 'traceback'):
606 val = bool(options[opt])
610 val = bool(options[opt])
607 if val:
611 if val:
608 for ui_ in uis:
612 for ui_ in uis:
609 ui_.setconfig('ui', opt, str(val))
613 ui_.setconfig('ui', opt, str(val))
610
614
611 if options['noninteractive']:
615 if options['noninteractive']:
612 for ui_ in uis:
616 for ui_ in uis:
613 ui_.setconfig('ui', 'interactive', 'off')
617 ui_.setconfig('ui', 'interactive', 'off')
614
618
615 if cmdoptions.get('insecure', False):
619 if cmdoptions.get('insecure', False):
616 for ui_ in uis:
620 for ui_ in uis:
617 ui_.setconfig('web', 'cacerts', '')
621 ui_.setconfig('web', 'cacerts', '')
618
622
619 if options['help']:
623 if options['help']:
620 return commands.help_(ui, cmd, options['version'])
624 return commands.help_(ui, cmd, options['version'])
621 elif options['version']:
625 elif options['version']:
622 return commands.version_(ui)
626 return commands.version_(ui)
623 elif not cmd:
627 elif not cmd:
624 return commands.help_(ui, 'shortlist')
628 return commands.help_(ui, 'shortlist')
625
629
626 repo = None
630 repo = None
627 cmdpats = args[:]
631 cmdpats = args[:]
628 if cmd not in commands.norepo.split():
632 if cmd not in commands.norepo.split():
629 # use the repo from the request only if we don't have -R
633 # use the repo from the request only if we don't have -R
630 if not rpath:
634 if not rpath:
631 repo = req.repo
635 repo = req.repo
632
636
633 if repo:
637 if repo:
634 # set the descriptors of the repo ui to those of ui
638 # set the descriptors of the repo ui to those of ui
635 repo.ui.fin = ui.fin
639 repo.ui.fin = ui.fin
636 repo.ui.fout = ui.fout
640 repo.ui.fout = ui.fout
637 repo.ui.ferr = ui.ferr
641 repo.ui.ferr = ui.ferr
638 else:
642 else:
639 try:
643 try:
640 repo = hg.repository(ui, path=path)
644 repo = hg.repository(ui, path=path)
641 if not repo.local():
645 if not repo.local():
642 raise util.Abort(_("repository '%s' is not local") % path)
646 raise util.Abort(_("repository '%s' is not local") % path)
643 repo.ui.setconfig("bundle", "mainreporoot", repo.root)
647 repo.ui.setconfig("bundle", "mainreporoot", repo.root)
644 except error.RequirementError:
648 except error.RequirementError:
645 raise
649 raise
646 except error.RepoError:
650 except error.RepoError:
647 if cmd not in commands.optionalrepo.split():
651 if cmd not in commands.optionalrepo.split():
648 if args and not path: # try to infer -R from command args
652 if args and not path: # try to infer -R from command args
649 repos = map(cmdutil.findrepo, args)
653 repos = map(cmdutil.findrepo, args)
650 guess = repos[0]
654 guess = repos[0]
651 if guess and repos.count(guess) == len(repos):
655 if guess and repos.count(guess) == len(repos):
652 req.args = ['--repository', guess] + fullargs
656 req.args = ['--repository', guess] + fullargs
653 return _dispatch(req)
657 return _dispatch(req)
654 if not path:
658 if not path:
655 raise error.RepoError(_("no repository found in %r"
659 raise error.RepoError(_("no repository found in %r"
656 " (.hg not found)") % os.getcwd())
660 " (.hg not found)") % os.getcwd())
657 raise
661 raise
658 if repo:
662 if repo:
659 ui = repo.ui
663 ui = repo.ui
660 args.insert(0, repo)
664 args.insert(0, repo)
661 elif rpath:
665 elif rpath:
662 ui.warn(_("warning: --repository ignored\n"))
666 ui.warn(_("warning: --repository ignored\n"))
663
667
664 msg = ' '.join(' ' in a and repr(a) or a for a in fullargs)
668 msg = ' '.join(' ' in a and repr(a) or a for a in fullargs)
665 ui.log("command", msg + "\n")
669 ui.log("command", msg + "\n")
666 d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
670 d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
667 try:
671 try:
668 return runcommand(lui, repo, cmd, fullargs, ui, options, d,
672 return runcommand(lui, repo, cmd, fullargs, ui, options, d,
669 cmdpats, cmdoptions)
673 cmdpats, cmdoptions)
670 finally:
674 finally:
671 if repo and repo != req.repo:
675 if repo and repo != req.repo:
672 repo.close()
676 repo.close()
673
677
674 def _runcommand(ui, options, cmd, cmdfunc):
678 def _runcommand(ui, options, cmd, cmdfunc):
675 def checkargs():
679 def checkargs():
676 try:
680 try:
677 return cmdfunc()
681 return cmdfunc()
678 except error.SignatureError:
682 except error.SignatureError:
679 raise error.CommandError(cmd, _("invalid arguments"))
683 raise error.CommandError(cmd, _("invalid arguments"))
680
684
681 if options['profile']:
685 if options['profile']:
682 format = ui.config('profiling', 'format', default='text')
686 format = ui.config('profiling', 'format', default='text')
683
687
684 if not format in ['text', 'kcachegrind']:
688 if not format in ['text', 'kcachegrind']:
685 ui.warn(_("unrecognized profiling format '%s'"
689 ui.warn(_("unrecognized profiling format '%s'"
686 " - Ignored\n") % format)
690 " - Ignored\n") % format)
687 format = 'text'
691 format = 'text'
688
692
689 output = ui.config('profiling', 'output')
693 output = ui.config('profiling', 'output')
690
694
691 if output:
695 if output:
692 path = ui.expandpath(output)
696 path = ui.expandpath(output)
693 ostream = open(path, 'wb')
697 ostream = open(path, 'wb')
694 else:
698 else:
695 ostream = sys.stderr
699 ostream = sys.stderr
696
700
697 try:
701 try:
698 from mercurial import lsprof
702 from mercurial import lsprof
699 except ImportError:
703 except ImportError:
700 raise util.Abort(_(
704 raise util.Abort(_(
701 'lsprof not available - install from '
705 'lsprof not available - install from '
702 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
706 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
703 p = lsprof.Profiler()
707 p = lsprof.Profiler()
704 p.enable(subcalls=True)
708 p.enable(subcalls=True)
705 try:
709 try:
706 return checkargs()
710 return checkargs()
707 finally:
711 finally:
708 p.disable()
712 p.disable()
709
713
710 if format == 'kcachegrind':
714 if format == 'kcachegrind':
711 import lsprofcalltree
715 import lsprofcalltree
712 calltree = lsprofcalltree.KCacheGrind(p)
716 calltree = lsprofcalltree.KCacheGrind(p)
713 calltree.output(ostream)
717 calltree.output(ostream)
714 else:
718 else:
715 # format == 'text'
719 # format == 'text'
716 stats = lsprof.Stats(p.getstats())
720 stats = lsprof.Stats(p.getstats())
717 stats.sort()
721 stats.sort()
718 stats.pprint(top=10, file=ostream, climit=5)
722 stats.pprint(top=10, file=ostream, climit=5)
719
723
720 if output:
724 if output:
721 ostream.close()
725 ostream.close()
722 else:
726 else:
723 return checkargs()
727 return checkargs()
General Comments 0
You need to be logged in to leave comments. Login now