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