2007-08-16 01:55:13 +04:00
|
|
|
# dispatch.py - command dispatching for mercurial
|
|
|
|
#
|
|
|
|
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
|
|
|
|
#
|
2009-04-26 03:08:54 +04:00
|
|
|
# This software may be used and distributed according to the terms of the
|
2010-01-20 07:20:08 +03:00
|
|
|
# GNU General Public License version 2 or any later version.
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2018-02-02 23:18:00 +03:00
|
|
|
from __future__ import absolute_import
|
2015-08-09 00:42:48 +03:00
|
|
|
|
2015-01-26 23:43:13 +03:00
|
|
|
import difflib
|
2015-08-09 00:42:48 +03:00
|
|
|
import errno
|
2016-12-06 03:57:58 +03:00
|
|
|
import getopt
|
2015-08-09 00:42:48 +03:00
|
|
|
import os
|
|
|
|
import pdb
|
|
|
|
import re
|
|
|
|
import signal
|
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
from .i18n import _
|
|
|
|
|
|
|
|
from . import (
|
|
|
|
cmdutil,
|
2016-11-18 20:18:15 +03:00
|
|
|
color,
|
2015-08-09 00:42:48 +03:00
|
|
|
commands,
|
|
|
|
demandimport,
|
|
|
|
encoding,
|
|
|
|
error,
|
|
|
|
extensions,
|
|
|
|
fancyopts,
|
2017-02-21 22:20:05 +03:00
|
|
|
help,
|
2015-08-09 00:42:48 +03:00
|
|
|
hg,
|
2018-04-07 10:36:43 +03:00
|
|
|
hintutil,
|
2015-08-09 00:42:48 +03:00
|
|
|
hook,
|
2016-08-15 02:30:44 +03:00
|
|
|
profiling,
|
2016-11-21 13:05:22 +03:00
|
|
|
pycompat,
|
2017-09-20 02:17:43 +03:00
|
|
|
registrar,
|
2016-11-24 03:48:40 +03:00
|
|
|
scmutil,
|
2015-08-09 00:42:48 +03:00
|
|
|
ui as uimod,
|
|
|
|
util,
|
|
|
|
)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2017-09-20 02:17:43 +03:00
|
|
|
unrecoverablewrite = registrar.command.unrecoverablewrite
|
2018-02-09 00:21:47 +03:00
|
|
|
_entrypoint = None # record who calls "run"
|
2017-09-20 02:17:43 +03:00
|
|
|
|
2011-05-26 01:44:11 +04:00
|
|
|
class request(object):
|
2012-05-12 17:54:54 +04:00
|
|
|
def __init__(self, args, ui=None, repo=None, fin=None, fout=None,
|
2017-04-30 07:39:47 +03:00
|
|
|
ferr=None, prereposetups=None):
|
2011-05-26 01:44:11 +04:00
|
|
|
self.args = args
|
2011-05-26 01:53:23 +04:00
|
|
|
self.ui = ui
|
2011-06-02 01:43:34 +04:00
|
|
|
self.repo = repo
|
2011-05-26 01:44:11 +04:00
|
|
|
|
2011-06-07 14:39:09 +04:00
|
|
|
# input/output/error streams
|
|
|
|
self.fin = fin
|
|
|
|
self.fout = fout
|
|
|
|
self.ferr = ferr
|
|
|
|
|
2017-11-23 16:23:59 +03:00
|
|
|
# remember options pre-parsed by _earlyparseopts()
|
2017-11-11 08:02:41 +03:00
|
|
|
self.earlyoptions = {}
|
|
|
|
|
2017-04-30 07:39:47 +03:00
|
|
|
# reposetups which run before extensions, useful for chg to pre-fill
|
|
|
|
# low-level repo state (for example, changelog) before extensions.
|
|
|
|
self.prereposetups = prereposetups or []
|
|
|
|
|
ui: add special-purpose atexit functionality
In spite of its longstanding use, Python's built-in atexit code is
not suitable for Mercurial's purposes, for several reasons:
* Handlers run after application code has finished.
* Because of this, the code that runs handlers swallows exceptions
(since there's no possible stacktrace to associate errors with).
If we're lucky, we'll get something spat out to stderr (if stderr
still works), which of course isn't any use in a big deployment
where it's important that exceptions get logged and aggregated.
* Mercurial's current atexit handlers make unfortunate assumptions
about process state (specifically stdio) that, coupled with the
above problems, make it impossible to deal with certain categories
of error (try "hg status > /dev/full" on a Linux box).
* In Python 3, the atexit implementation is completely hidden, so
we can't hijack the platform's atexit code to run handlers at a
time of our choosing.
As a result, here's a perfectly cromulent atexit-like implementation
over which we have control. This lets us decide exactly when the
handlers run (after each request has completed), and control what
the process state is when that occurs (and afterwards).
2017-04-12 00:54:12 +03:00
|
|
|
def _runexithandlers(self):
|
|
|
|
exc = None
|
|
|
|
handlers = self.ui._exithandlers
|
|
|
|
try:
|
|
|
|
while handlers:
|
|
|
|
func, args, kwargs = handlers.pop()
|
|
|
|
try:
|
|
|
|
func(*args, **kwargs)
|
|
|
|
except: # re-raises below
|
|
|
|
if exc is None:
|
|
|
|
exc = sys.exc_info()[1]
|
|
|
|
self.ui.warn(('error in exit handlers:\n'))
|
|
|
|
self.ui.traceback(force=True)
|
|
|
|
finally:
|
|
|
|
if exc is not None:
|
|
|
|
raise exc
|
|
|
|
|
2018-02-09 00:21:47 +03:00
|
|
|
def run(entrypoint='hg'):
|
2007-08-16 01:55:13 +04:00
|
|
|
"run the command in sys.argv"
|
2018-02-09 00:21:47 +03:00
|
|
|
global _entrypoint
|
|
|
|
_entrypoint = entrypoint
|
2017-10-02 09:18:24 +03:00
|
|
|
_initstdio()
|
2017-04-12 00:54:12 +03:00
|
|
|
req = request(pycompat.sysargv[1:])
|
|
|
|
err = None
|
|
|
|
try:
|
|
|
|
status = (dispatch(req) or 0) & 255
|
2017-10-02 08:52:10 +03:00
|
|
|
except error.StdioError as e:
|
|
|
|
err = e
|
2017-04-12 00:54:12 +03:00
|
|
|
status = -1
|
|
|
|
if util.safehasattr(req.ui, 'fout'):
|
|
|
|
try:
|
2017-04-22 18:31:29 +03:00
|
|
|
req.ui.fout.flush()
|
2017-10-02 08:52:10 +03:00
|
|
|
except IOError as e:
|
|
|
|
err = e
|
2017-04-12 00:54:12 +03:00
|
|
|
status = -1
|
|
|
|
if util.safehasattr(req.ui, 'ferr'):
|
|
|
|
if err is not None and err.errno != errno.EPIPE:
|
2017-08-23 03:03:07 +03:00
|
|
|
req.ui.ferr.write('abort: %s\n' %
|
|
|
|
encoding.strtolocal(err.strerror))
|
2017-04-22 18:31:29 +03:00
|
|
|
req.ui.ferr.flush()
|
2017-04-12 00:54:12 +03:00
|
|
|
sys.exit(status & 255)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2018-02-09 00:21:47 +03:00
|
|
|
def getentrypoint():
|
|
|
|
global _entrypoint
|
|
|
|
return _entrypoint
|
|
|
|
|
2017-10-02 09:18:24 +03:00
|
|
|
def _initstdio():
|
|
|
|
for fp in (sys.stdin, sys.stdout, sys.stderr):
|
|
|
|
util.setbinary(fp)
|
|
|
|
|
2015-01-26 23:43:13 +03:00
|
|
|
def _getsimilar(symbols, value):
|
|
|
|
sim = lambda x: difflib.SequenceMatcher(None, value, x).ratio()
|
|
|
|
# The cutoff for similarity here is pretty arbitrary. It should
|
|
|
|
# probably be investigated and tweaked.
|
|
|
|
return [s for s in symbols if sim(s) > 0.6]
|
|
|
|
|
2016-01-05 08:52:44 +03:00
|
|
|
def _reportsimilar(write, similar):
|
|
|
|
if len(similar) == 1:
|
|
|
|
write(_("(did you mean %s?)\n") % similar[0])
|
|
|
|
elif similar:
|
|
|
|
ss = ", ".join(sorted(similar))
|
|
|
|
write(_("(did you mean one of %s?)\n") % ss)
|
|
|
|
|
2015-01-26 22:50:36 +03:00
|
|
|
def _formatparse(write, inst):
|
2015-01-26 23:43:13 +03:00
|
|
|
similar = []
|
|
|
|
if isinstance(inst, error.UnknownIdentifier):
|
|
|
|
# make sure to check fileset first, as revset can invoke fileset
|
|
|
|
similar = _getsimilar(inst.symbols, inst.function)
|
2015-01-26 22:50:36 +03:00
|
|
|
if len(inst.args) > 1:
|
|
|
|
write(_("hg: parse error at %s: %s\n") %
|
|
|
|
(inst.args[1], inst.args[0]))
|
|
|
|
if (inst.args[0][0] == ' '):
|
|
|
|
write(_("unexpected leading whitespace\n"))
|
|
|
|
else:
|
|
|
|
write(_("hg: parse error: %s\n") % inst.args[0])
|
2016-01-05 08:52:44 +03:00
|
|
|
_reportsimilar(write, similar)
|
2016-03-14 15:32:09 +03:00
|
|
|
if inst.hint:
|
|
|
|
write(_("(%s)\n") % inst.hint)
|
2015-01-26 22:50:36 +03:00
|
|
|
|
2017-03-19 07:18:53 +03:00
|
|
|
def _formatargs(args):
|
2017-03-19 21:23:30 +03:00
|
|
|
return ' '.join(util.shellquote(a) for a in args)
|
2017-03-19 07:18:53 +03:00
|
|
|
|
2011-05-26 01:44:11 +04:00
|
|
|
def dispatch(req):
|
|
|
|
"run the command specified in req.args"
|
2011-06-08 15:54:47 +04:00
|
|
|
if req.ferr:
|
|
|
|
ferr = req.ferr
|
|
|
|
elif req.ui:
|
|
|
|
ferr = req.ui.ferr
|
|
|
|
else:
|
2016-10-20 17:53:36 +03:00
|
|
|
ferr = util.stderr
|
2011-06-08 15:54:47 +04:00
|
|
|
|
2007-08-16 01:55:13 +04:00
|
|
|
try:
|
2011-05-26 01:53:23 +04:00
|
|
|
if not req.ui:
|
2016-10-22 08:35:10 +03:00
|
|
|
req.ui = uimod.ui.load()
|
2017-11-23 16:23:59 +03:00
|
|
|
req.earlyoptions.update(_earlyparseopts(req.ui, req.args))
|
|
|
|
if req.earlyoptions['traceback']:
|
2014-03-19 05:45:04 +04:00
|
|
|
req.ui.setconfig('ui', 'traceback', 'on', '--traceback')
|
2011-06-08 15:54:47 +04:00
|
|
|
|
|
|
|
# set ui streams from the request
|
|
|
|
if req.fin:
|
|
|
|
req.ui.fin = req.fin
|
|
|
|
if req.fout:
|
|
|
|
req.ui.fout = req.fout
|
|
|
|
if req.ferr:
|
|
|
|
req.ui.ferr = req.ferr
|
2015-10-08 22:55:45 +03:00
|
|
|
except error.Abort as inst:
|
2011-06-08 15:54:47 +04:00
|
|
|
ferr.write(_("abort: %s\n") % inst)
|
2010-07-15 16:41:22 +04:00
|
|
|
if inst.hint:
|
2011-06-08 15:54:47 +04:00
|
|
|
ferr.write(_("(%s)\n") % inst.hint)
|
2007-08-16 01:55:13 +04:00
|
|
|
return -1
|
2015-06-24 08:20:08 +03:00
|
|
|
except error.ParseError as inst:
|
2015-01-26 22:50:36 +03:00
|
|
|
_formatparse(ferr.write, inst)
|
2009-09-19 15:52:54 +04:00
|
|
|
return -1
|
2011-06-08 15:54:47 +04:00
|
|
|
|
2017-03-19 07:18:53 +03:00
|
|
|
msg = _formatargs(req.args)
|
2017-02-16 00:17:39 +03:00
|
|
|
starttime = util.timer()
|
2013-05-23 04:31:47 +04:00
|
|
|
ret = None
|
|
|
|
try:
|
2018-02-07 03:49:55 +03:00
|
|
|
def blockedtimeslogger():
|
|
|
|
req.ui.log('uiblocked', 'ui blocked ms',
|
|
|
|
**pycompat.strkwargs(req.ui._blockedtimes))
|
|
|
|
|
|
|
|
if req.ui.logblockedtimes:
|
|
|
|
# by registering this exit handler here, we guarantee that it runs
|
|
|
|
# after other exithandlers, like the killpager one
|
|
|
|
req.ui.atexit(blockedtimeslogger)
|
|
|
|
|
2013-05-23 04:31:47 +04:00
|
|
|
ret = _runcatch(req)
|
2017-05-14 09:41:27 +03:00
|
|
|
except error.ProgrammingError as inst:
|
|
|
|
req.ui.warn(_('** ProgrammingError: %s\n') % inst)
|
|
|
|
if inst.hint:
|
|
|
|
req.ui.warn(_('** (%s)\n') % inst.hint)
|
|
|
|
raise
|
2017-04-23 01:00:17 +03:00
|
|
|
except KeyboardInterrupt as inst:
|
2015-12-27 07:38:46 +03:00
|
|
|
try:
|
2017-04-23 01:00:17 +03:00
|
|
|
if isinstance(inst, error.SignalInterrupt):
|
|
|
|
msg = _("killed!\n")
|
|
|
|
else:
|
|
|
|
msg = _("interrupted!\n")
|
|
|
|
req.ui.warn(msg)
|
dispatch: ignore further SIGPIPE while handling KeyboardInterrupt
I got the following error by running "hg log" and quitting the pager
immediately. Any output here may trigger another SIGPIPE, so only thing
we can do is to swallow the exception and exit with an error status.
Traceback (most recent call last):
File "./hg", line 45, in <module>
mercurial.dispatch.run()
File "mercurial/dispatch.py", line 83, in run
status = (dispatch(req) or 0) & 255
File "mercurial/dispatch.py", line 167, in dispatch
req.ui.warn(_("interrupted!\n"))
File "mercurial/ui.py", line 1224, in warn
self.write_err(*msg, **opts)
File "mercurial/ui.py", line 790, in write_err
self._write_err(*msgs, **opts)
File "mercurial/ui.py", line 798, in _write_err
self.ferr.write(a)
File "mercurial/ui.py", line 129, in _catchterm
raise error.SignalInterrupt
mercurial.error.SignalInterrupt
Perhaps this wasn't visible before ee4f321cd621 because the original stderr
handle was restored very late.
2017-04-17 17:53:19 +03:00
|
|
|
except error.SignalInterrupt:
|
|
|
|
# maybe pager would quit without consuming all the output, and
|
|
|
|
# SIGPIPE was raised. we cannot print anything in this case.
|
|
|
|
pass
|
2015-12-27 07:38:46 +03:00
|
|
|
except IOError as inst:
|
|
|
|
if inst.errno != errno.EPIPE:
|
|
|
|
raise
|
|
|
|
ret = -1
|
2013-05-23 04:31:47 +04:00
|
|
|
finally:
|
2017-02-16 00:17:39 +03:00
|
|
|
duration = util.timer() - starttime
|
2016-03-14 14:06:34 +03:00
|
|
|
req.ui.flush()
|
2017-04-20 22:43:18 +03:00
|
|
|
req.ui.log("commandfinish", "%s exited %d after %0.2f seconds\n",
|
2013-05-23 04:31:47 +04:00
|
|
|
msg, ret or 0, duration)
|
2018-02-07 03:49:55 +03:00
|
|
|
req.ui._blockedtimes['command_duration'] = duration * 1000
|
|
|
|
|
ui: add special-purpose atexit functionality
In spite of its longstanding use, Python's built-in atexit code is
not suitable for Mercurial's purposes, for several reasons:
* Handlers run after application code has finished.
* Because of this, the code that runs handlers swallows exceptions
(since there's no possible stacktrace to associate errors with).
If we're lucky, we'll get something spat out to stderr (if stderr
still works), which of course isn't any use in a big deployment
where it's important that exceptions get logged and aggregated.
* Mercurial's current atexit handlers make unfortunate assumptions
about process state (specifically stdio) that, coupled with the
above problems, make it impossible to deal with certain categories
of error (try "hg status > /dev/full" on a Linux box).
* In Python 3, the atexit implementation is completely hidden, so
we can't hijack the platform's atexit code to run handlers at a
time of our choosing.
As a result, here's a perfectly cromulent atexit-like implementation
over which we have control. This lets us decide exactly when the
handlers run (after each request has completed), and control what
the process state is when that occurs (and afterwards).
2017-04-12 00:54:12 +03:00
|
|
|
try:
|
|
|
|
req._runexithandlers()
|
|
|
|
except: # exiting, so no re-raises
|
|
|
|
ret = ret or -1
|
2015-12-27 07:38:46 +03:00
|
|
|
return ret
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2011-05-26 01:53:23 +04:00
|
|
|
def _runcatch(req):
|
2007-08-16 01:55:13 +04:00
|
|
|
def catchterm(*args):
|
2009-01-12 20:48:05 +03:00
|
|
|
raise error.SignalInterrupt
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2011-05-26 01:53:23 +04:00
|
|
|
ui = req.ui
|
2010-04-07 04:41:22 +04:00
|
|
|
try:
|
|
|
|
for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
|
|
|
|
num = getattr(signal, name, None)
|
|
|
|
if num:
|
|
|
|
signal.signal(num, catchterm)
|
|
|
|
except ValueError:
|
|
|
|
pass # happens if called in a thread
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2016-08-09 18:45:28 +03:00
|
|
|
def _runcatchfunc():
|
2017-04-12 21:23:55 +03:00
|
|
|
realcmd = None
|
|
|
|
try:
|
|
|
|
cmdargs = fancyopts.fancyopts(req.args[:], commands.globalopts, {})
|
|
|
|
cmd = cmdargs[0]
|
|
|
|
aliases, entry = cmdutil.findcmd(cmd, commands.table, False)
|
|
|
|
realcmd = aliases[0]
|
|
|
|
except (error.UnknownCommand, error.AmbiguousCommand,
|
|
|
|
IndexError, getopt.GetoptError):
|
|
|
|
# Don't handle this here. We know the command is
|
|
|
|
# invalid, but all we're worried about for now is that
|
|
|
|
# it's not a command that server operators expect to
|
|
|
|
# be safe to offer to users in a sandbox.
|
|
|
|
pass
|
2018-01-03 16:35:56 +03:00
|
|
|
|
|
|
|
if realcmd == 'serve' and '--read-only' in req.args:
|
|
|
|
req.args.remove('--read-only')
|
|
|
|
|
|
|
|
if not req.ui:
|
|
|
|
req.ui = uimod.ui.load()
|
|
|
|
req.ui.setconfig('hooks', 'pretxnopen.readonlyrejectpush',
|
|
|
|
rejectpush, 'dispatch')
|
|
|
|
req.ui.setconfig('hooks', 'prepushkey.readonlyrejectpush',
|
|
|
|
rejectpush, 'dispatch')
|
|
|
|
|
2017-04-12 21:23:55 +03:00
|
|
|
if realcmd == 'serve' and '--stdio' in cmdargs:
|
|
|
|
# We want to constrain 'hg serve --stdio' instances pretty
|
|
|
|
# closely, as many shared-ssh access tools want to grant
|
|
|
|
# access to run *only* 'hg -R $repo serve --stdio'. We
|
|
|
|
# restrict to exactly that set of arguments, and prohibit
|
|
|
|
# any repo name that starts with '--' to prevent
|
|
|
|
# shenanigans wherein a user does something like pass
|
|
|
|
# --debugger or --config=ui.debugger=1 as a repo
|
|
|
|
# name. This used to actually run the debugger.
|
|
|
|
if (len(req.args) != 4 or
|
|
|
|
req.args[0] != '-R' or
|
|
|
|
req.args[1].startswith('--') or
|
|
|
|
req.args[2] != 'serve' or
|
|
|
|
req.args[3] != '--stdio'):
|
|
|
|
raise error.Abort(
|
|
|
|
_('potentially unsafe serve --stdio invocation: %r') %
|
|
|
|
(req.args,))
|
|
|
|
|
2007-08-16 01:55:13 +04:00
|
|
|
try:
|
2013-07-26 07:28:34 +04:00
|
|
|
debugger = 'pdb'
|
|
|
|
debugtrace = {
|
2017-09-29 18:48:34 +03:00
|
|
|
'pdb': pdb.set_trace
|
2013-07-26 07:28:34 +04:00
|
|
|
}
|
|
|
|
debugmortem = {
|
2017-09-29 18:48:34 +03:00
|
|
|
'pdb': pdb.post_mortem
|
2013-07-26 07:28:34 +04:00
|
|
|
}
|
2013-07-14 01:33:07 +04:00
|
|
|
|
2018-03-20 02:20:55 +03:00
|
|
|
# --config takes prescendence over --configfile, so process
|
|
|
|
# --configfile first --config second.
|
|
|
|
for configfile in req.earlyoptions['configfile']:
|
|
|
|
req.ui.readconfig(configfile)
|
|
|
|
|
2013-07-14 01:33:07 +04:00
|
|
|
# read --config before doing anything else
|
|
|
|
# (e.g. to change trust settings for reading .hg/hgrc)
|
2017-11-23 16:23:59 +03:00
|
|
|
cfgs = _parseconfig(req.ui, req.earlyoptions['config'])
|
2013-07-14 01:33:07 +04:00
|
|
|
|
|
|
|
if req.repo:
|
2018-03-20 02:20:55 +03:00
|
|
|
for configfile in req.earlyoptions['configfile']:
|
|
|
|
req.repo.ui.readconfig(configfile)
|
2013-07-14 01:33:07 +04:00
|
|
|
# copy configs that were passed on the cmdline (--config) to
|
|
|
|
# the repo ui
|
2014-03-20 03:04:03 +04:00
|
|
|
for sec, name, val in cfgs:
|
|
|
|
req.repo.ui.setconfig(sec, name, val, source='--config')
|
2013-07-14 01:33:07 +04:00
|
|
|
|
2015-06-26 01:45:49 +03:00
|
|
|
# developer config: ui.debugger
|
2013-07-26 07:28:34 +04:00
|
|
|
debugger = ui.config("ui", "debugger")
|
2014-03-07 23:06:52 +04:00
|
|
|
debugmod = pdb
|
2013-11-25 21:20:39 +04:00
|
|
|
if not debugger or ui.plain():
|
2015-06-26 01:45:49 +03:00
|
|
|
# if we are in HGPLAIN mode, then disable custom debugging
|
2013-07-26 07:28:34 +04:00
|
|
|
debugger = 'pdb'
|
2017-11-23 16:23:59 +03:00
|
|
|
elif req.earlyoptions['debugger']:
|
2014-03-07 23:06:52 +04:00
|
|
|
# This import can be slow for fancy debuggers, so only
|
|
|
|
# do it when absolutely necessary, i.e. when actual
|
|
|
|
# debugging has been requested
|
dispatch: disable demandimport for the --debugger option
Something in Python 2.7.9 or so broke the --debugger option with
ui.debugger = ipdb. I get the traceback below. There is some apparent
confusion with demandimport. This should be disabled anyway for the
--debugger option. The debugger must be imported right away, before
any other dispatch. There's no benefit in delaying the debugger
import.
This patch uses the demandimport.deactivated() context manager.
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 121, in _runcatch
debugmod = __import__(debugger)
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 115, in _demandimport
return _hgextimport(_import, name, globals, locals, fromlist, level)
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
File "/usr/lib/python2.7/dist-packages/ipdb/__init__.py", line 16, in <module>
from ipdb.__main__ import set_trace, post_mortem, pm, run, runcall, runeval, launch_ipdb_on_exception
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 134, in _demandimport
mod = _hgextimport(_origimport, name, globals, locals)
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
File "/usr/lib/python2.7/dist-packages/ipdb/__main__.py", line 29, in <module>
if IPython.__version__ > '0.10.2':
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 106, in __getattribute__
self._load()
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 78, in _load
mod = _hgextimport(_import, head, globals, locals, None, level)
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
File "/usr/lib/python2.7/dist-packages/IPython/__init__.py", line 45, in <module>
from .config.loader import Config
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 132, in _demandimport
return _origimport(name, globals, locals, fromlist, level)
File "/usr/lib/python2.7/dist-packages/IPython/config/__init__.py", line 16, in <module>
from .application import *
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 115, in _demandimport
return _hgextimport(_import, name, globals, locals, fromlist, level)
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
File "/usr/lib/python2.7/dist-packages/IPython/config/application.py", line 30, in <module>
from IPython.external.decorator import decorator
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 134, in _demandimport
mod = _hgextimport(_origimport, name, globals, locals)
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
File "/usr/lib/python2.7/dist-packages/IPython/external/decorator/__init__.py", line 2, in <module>
from decorator import *
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 115, in _demandimport
return _hgextimport(_import, name, globals, locals, fromlist, level)
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 47, in _hgextimport
return importfunc(name, globals, *args)
File "/usr/lib/python2.7/dist-packages/decorator.py", line 240, in <module>
'ContextManager', (_GeneratorContextManager,), dict(__call__=__call__))
2015-05-28 23:42:21 +03:00
|
|
|
with demandimport.deactivated():
|
|
|
|
try:
|
|
|
|
debugmod = __import__(debugger)
|
|
|
|
except ImportError:
|
|
|
|
pass # Leave debugmod = pdb
|
2013-07-26 07:28:34 +04:00
|
|
|
|
|
|
|
debugtrace[debugger] = debugmod.set_trace
|
|
|
|
debugmortem[debugger] = debugmod.post_mortem
|
|
|
|
|
2007-08-16 01:55:13 +04:00
|
|
|
# enter the debugger before command execution
|
2017-11-23 16:23:59 +03:00
|
|
|
if req.earlyoptions['debugger']:
|
2010-06-30 19:23:16 +04:00
|
|
|
ui.warn(_("entering debugger - "
|
|
|
|
"type c to continue starting hg or h for help\n"))
|
2013-07-26 07:28:34 +04:00
|
|
|
|
|
|
|
if (debugger != 'pdb' and
|
|
|
|
debugtrace[debugger] == debugtrace['pdb']):
|
|
|
|
ui.warn(_("%s debugger specified "
|
|
|
|
"but its module was not found\n") % debugger)
|
2015-09-13 23:30:21 +03:00
|
|
|
with demandimport.deactivated():
|
2015-09-10 16:30:10 +03:00
|
|
|
debugtrace[debugger]()
|
2007-08-16 01:55:13 +04:00
|
|
|
try:
|
2011-05-26 01:53:23 +04:00
|
|
|
return _dispatch(req)
|
2007-08-16 01:55:13 +04:00
|
|
|
finally:
|
|
|
|
ui.flush()
|
2012-05-13 15:18:06 +04:00
|
|
|
except: # re-raises
|
2007-08-16 01:55:13 +04:00
|
|
|
# enter the debugger when we hit an exception
|
2017-11-23 16:23:59 +03:00
|
|
|
if req.earlyoptions['debugger']:
|
2010-06-30 19:20:42 +04:00
|
|
|
traceback.print_exc()
|
2013-07-26 07:28:34 +04:00
|
|
|
debugmortem[debugger](sys.exc_info()[2])
|
2007-08-16 01:55:13 +04:00
|
|
|
raise
|
|
|
|
|
2017-04-15 06:58:06 +03:00
|
|
|
return _callcatch(ui, _runcatchfunc)
|
2016-08-09 18:45:28 +03:00
|
|
|
|
2017-04-15 06:58:06 +03:00
|
|
|
def _callcatch(ui, func):
|
2016-11-24 03:48:40 +03:00
|
|
|
"""like scmutil.callcatch but handles more high-level exceptions about
|
|
|
|
config parsing and commands. besides, use handlecommandexception to handle
|
|
|
|
uncaught exceptions.
|
2016-08-09 18:45:28 +03:00
|
|
|
"""
|
|
|
|
try:
|
2016-11-24 03:48:40 +03:00
|
|
|
return scmutil.callcatch(ui, func)
|
2015-06-24 08:20:08 +03:00
|
|
|
except error.AmbiguousCommand as inst:
|
2007-08-16 01:55:13 +04:00
|
|
|
ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
|
|
|
|
(inst.args[0], " ".join(inst.args[1])))
|
2015-06-24 08:20:08 +03:00
|
|
|
except error.CommandError as inst:
|
2009-01-12 22:35:35 +03:00
|
|
|
if inst.args[0]:
|
2017-03-09 02:32:42 +03:00
|
|
|
ui.pager('help')
|
2017-05-28 22:47:00 +03:00
|
|
|
msgbytes = pycompat.bytestr(inst.args[1])
|
|
|
|
ui.warn(_("hg %s: %s\n") % (inst.args[0], msgbytes))
|
2011-05-10 16:42:53 +04:00
|
|
|
commands.help_(ui, inst.args[0], full=False, command=True)
|
2009-01-12 22:35:35 +03:00
|
|
|
else:
|
2017-03-09 02:32:42 +03:00
|
|
|
ui.pager('help')
|
2009-01-12 22:35:35 +03:00
|
|
|
ui.warn(_("hg: %s\n") % inst.args[1])
|
|
|
|
commands.help_(ui, 'shortlist')
|
2016-11-24 03:48:40 +03:00
|
|
|
except error.ParseError as inst:
|
|
|
|
_formatparse(ui.warn, inst)
|
|
|
|
return -1
|
2015-06-24 08:20:08 +03:00
|
|
|
except error.UnknownCommand as inst:
|
2017-02-21 22:20:05 +03:00
|
|
|
nocmdmsg = _("hg: unknown command '%s'\n") % inst.args[0]
|
2010-02-07 16:01:43 +03:00
|
|
|
try:
|
|
|
|
# check if the command is in a disabled extension
|
|
|
|
# (but don't check for extensions themselves)
|
2017-05-21 10:57:32 +03:00
|
|
|
formatted = help.formattedhelp(ui, commands, inst.args[0],
|
|
|
|
unknowncmd=True)
|
2017-02-21 22:20:05 +03:00
|
|
|
ui.warn(nocmdmsg)
|
|
|
|
ui.write(formatted)
|
2015-10-08 22:55:45 +03:00
|
|
|
except (error.UnknownCommand, error.Abort):
|
2015-02-10 23:59:12 +03:00
|
|
|
suggested = False
|
|
|
|
if len(inst.args) == 2:
|
|
|
|
sim = _getsimilar(inst.args[1], inst.args[0])
|
|
|
|
if sim:
|
2017-02-21 22:20:05 +03:00
|
|
|
ui.warn(nocmdmsg)
|
2016-01-05 08:52:44 +03:00
|
|
|
_reportsimilar(ui.warn, sim)
|
2015-02-10 23:59:12 +03:00
|
|
|
suggested = True
|
|
|
|
if not suggested:
|
2017-02-21 22:20:05 +03:00
|
|
|
ui.pager('help')
|
|
|
|
ui.warn(nocmdmsg)
|
2015-02-10 23:59:12 +03:00
|
|
|
commands.help_(ui, 'shortlist')
|
2016-11-24 03:48:40 +03:00
|
|
|
except IOError:
|
|
|
|
raise
|
2009-01-12 22:35:35 +03:00
|
|
|
except KeyboardInterrupt:
|
2015-12-27 07:38:46 +03:00
|
|
|
raise
|
2016-11-24 03:48:40 +03:00
|
|
|
except: # probably re-raises
|
2016-04-04 19:27:37 +03:00
|
|
|
if not handlecommandexception(ui):
|
|
|
|
raise
|
2007-08-16 01:55:13 +04:00
|
|
|
|
|
|
|
return -1
|
|
|
|
|
2011-05-01 14:29:32 +04:00
|
|
|
def aliasargs(fn, givenargs):
|
wrapfunction: use functools.partial if possible
Every `extensions.bind` call inserts a frame in traceback:
... in closure
return func(*(args + a), **kw)
which makes traceback noisy.
The Python stdlib has a `functools.partial` which is backed by C code and
does not pollute traceback. However it does not support instancemethod and
sets `args` attribute which could be problematic for alias handling.
This patch makes `wrapfunction` use `functools.partial` if we are wrapping a
function directly exported by a module (so it's impossible to be a class or
instance method), and special handles `wrapfunction` results so alias
handling code could handle `args` just fine.
As an example, `hg rebase -s . -d . --traceback` got 6 lines removed in my
setup:
File "hg/mercurial/dispatch.py", line 898, in _dispatch
cmdpats, cmdoptions)
-File "hg/mercurial/extensions.py", line 333, in closure
- return func(*(args + a), **kw)
File "hg/hgext/journal.py", line 84, in runcommand
return orig(lui, repo, cmd, fullargs, *args)
-File "hg/mercurial/extensions.py", line 333, in closure
- return func(*(args + a), **kw)
File "fb-hgext/hgext3rd/fbamend/hiddenoverride.py", line 119, in runcommand
result = orig(lui, repo, cmd, fullargs, *args)
File "hg/mercurial/dispatch.py", line 660, in runcommand
ret = _runcommand(ui, options, cmd, d)
-File "hg/mercurial/extensions.py", line 333, in closure
- return func(*(args + a), **kw)
File "hg/hgext/pager.py", line 69, in pagecmd
return orig(ui, options, cmd, cmdfunc)
....
Differential Revision: https://phab.mercurial-scm.org/D632
2017-09-05 23:37:36 +03:00
|
|
|
args = []
|
|
|
|
# only care about alias 'args', ignore 'args' set by extensions.wrapfunction
|
|
|
|
if not util.safehasattr(fn, '_origfunc'):
|
|
|
|
args = getattr(fn, 'args', args)
|
2012-03-28 01:13:59 +04:00
|
|
|
if args:
|
2011-05-01 14:29:32 +04:00
|
|
|
cmd = ' '.join(map(util.shellquote, args))
|
|
|
|
|
|
|
|
nums = []
|
|
|
|
def replacer(m):
|
|
|
|
num = int(m.group(1)) - 1
|
|
|
|
nums.append(num)
|
2012-03-23 02:07:39 +04:00
|
|
|
if num < len(givenargs):
|
|
|
|
return givenargs[num]
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_('too few arguments for command alias'))
|
2017-03-17 02:40:58 +03:00
|
|
|
cmd = re.sub(br'\$(\d+|\$)', replacer, cmd)
|
2011-05-01 14:29:32 +04:00
|
|
|
givenargs = [x for i, x in enumerate(givenargs)
|
|
|
|
if i not in nums]
|
2016-12-25 00:36:55 +03:00
|
|
|
args = pycompat.shlexsplit(cmd)
|
2011-05-01 14:29:32 +04:00
|
|
|
return args + givenargs
|
2009-05-30 22:32:23 +04:00
|
|
|
|
2014-08-14 10:21:52 +04:00
|
|
|
def aliasinterpolate(name, args, cmd):
|
|
|
|
'''interpolate args into cmd for shell aliases
|
|
|
|
|
|
|
|
This also handles $0, $@ and "$@".
|
|
|
|
'''
|
|
|
|
# util.interpolate can't deal with "$@" (with quotes) because it's only
|
|
|
|
# built to match prefix + patterns.
|
|
|
|
replacemap = dict(('$%d' % (i + 1), arg) for i, arg in enumerate(args))
|
|
|
|
replacemap['$0'] = name
|
|
|
|
replacemap['$$'] = '$'
|
|
|
|
replacemap['$@'] = ' '.join(args)
|
|
|
|
# Typical Unix shells interpolate "$@" (with quotes) as all the positional
|
|
|
|
# parameters, separated out into words. Emulate the same behavior here by
|
|
|
|
# quoting the arguments individually. POSIX shells will then typically
|
|
|
|
# tokenize each argument into exactly one word.
|
|
|
|
replacemap['"$@"'] = ' '.join(util.shellquote(arg) for arg in args)
|
|
|
|
# escape '\$' for regex
|
2017-11-29 02:17:27 +03:00
|
|
|
regex = '|'.join(replacemap.keys()).replace('$', br'\$')
|
2014-08-14 10:21:52 +04:00
|
|
|
r = re.compile(regex)
|
|
|
|
return r.sub(lambda x: replacemap[x.group()], cmd)
|
|
|
|
|
2009-05-30 22:32:23 +04:00
|
|
|
class cmdalias(object):
|
2016-04-08 21:35:49 +03:00
|
|
|
def __init__(self, name, definition, cmdtable, source):
|
2010-08-22 06:48:14 +04:00
|
|
|
self.name = self.cmd = name
|
2010-08-28 04:45:11 +04:00
|
|
|
self.cmdname = ''
|
2009-05-30 22:32:23 +04:00
|
|
|
self.definition = definition
|
2014-05-17 16:13:31 +04:00
|
|
|
self.fn = None
|
2016-05-07 02:16:58 +03:00
|
|
|
self.givenargs = []
|
2009-05-30 22:32:23 +04:00
|
|
|
self.opts = []
|
|
|
|
self.help = ''
|
2014-05-17 16:13:31 +04:00
|
|
|
self.badalias = None
|
2014-08-13 14:28:42 +04:00
|
|
|
self.unknowncmd = False
|
2016-04-08 21:35:49 +03:00
|
|
|
self.source = source
|
2009-05-30 22:32:23 +04:00
|
|
|
|
|
|
|
try:
|
2010-08-22 06:48:14 +04:00
|
|
|
aliases, entry = cmdutil.findcmd(self.name, cmdtable)
|
|
|
|
for alias, e in cmdtable.iteritems():
|
|
|
|
if e is entry:
|
|
|
|
self.cmd = alias
|
|
|
|
break
|
2009-05-30 22:32:23 +04:00
|
|
|
self.shadows = True
|
|
|
|
except error.UnknownCommand:
|
|
|
|
self.shadows = False
|
|
|
|
|
|
|
|
if not self.definition:
|
2014-05-17 16:13:31 +04:00
|
|
|
self.badalias = _("no definition for alias '%s'") % self.name
|
2009-05-30 22:32:23 +04:00
|
|
|
return
|
|
|
|
|
2010-07-08 02:49:43 +04:00
|
|
|
if self.definition.startswith('!'):
|
2010-08-25 02:25:33 +04:00
|
|
|
self.shell = True
|
2010-07-08 02:49:43 +04:00
|
|
|
def fn(ui, *args):
|
2010-08-19 02:56:44 +04:00
|
|
|
env = {'HG_ARGS': ' '.join((self.name,) + args)}
|
|
|
|
def _checkvar(m):
|
2011-02-11 03:32:40 +03:00
|
|
|
if m.groups()[0] == '$':
|
|
|
|
return m.group()
|
|
|
|
elif int(m.groups()[0]) <= len(args):
|
2010-08-19 02:56:44 +04:00
|
|
|
return m.group()
|
|
|
|
else:
|
2011-06-21 20:35:13 +04:00
|
|
|
ui.debug("No argument found for substitution "
|
|
|
|
"of %i variable in alias '%s' definition."
|
2011-02-11 03:46:28 +03:00
|
|
|
% (int(m.groups()[0]), self.name))
|
2010-08-19 02:56:44 +04:00
|
|
|
return ''
|
2017-11-29 02:17:27 +03:00
|
|
|
cmd = re.sub(br'\$(\d+|\$)', _checkvar, self.definition[1:])
|
2014-08-14 10:21:52 +04:00
|
|
|
cmd = aliasinterpolate(self.name, args, cmd)
|
2017-03-06 14:25:44 +03:00
|
|
|
return ui.system(cmd, environ=env,
|
|
|
|
blockedtag='alias_%s' % self.name)
|
2010-07-08 02:49:43 +04:00
|
|
|
self.fn = fn
|
|
|
|
return
|
|
|
|
|
2014-05-17 08:06:16 +04:00
|
|
|
try:
|
2016-12-25 00:36:55 +03:00
|
|
|
args = pycompat.shlexsplit(self.definition)
|
2015-06-24 08:20:08 +03:00
|
|
|
except ValueError as inst:
|
2014-05-17 16:13:31 +04:00
|
|
|
self.badalias = (_("error in definition for alias '%s': %s")
|
|
|
|
% (self.name, inst))
|
2014-05-17 08:06:16 +04:00
|
|
|
return
|
2017-11-23 17:18:56 +03:00
|
|
|
earlyopts, args = _earlysplitopts(args)
|
|
|
|
if earlyopts:
|
|
|
|
self.badalias = (_("error in definition for alias '%s': %s may "
|
|
|
|
"only be given on the command line")
|
|
|
|
% (self.name, '/'.join(zip(*earlyopts)[0])))
|
|
|
|
return
|
2010-08-28 04:45:11 +04:00
|
|
|
self.cmdname = cmd = args.pop(0)
|
2016-05-07 02:16:58 +03:00
|
|
|
self.givenargs = args
|
2009-05-30 22:32:23 +04:00
|
|
|
|
|
|
|
try:
|
2009-12-03 08:14:44 +03:00
|
|
|
tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
|
|
|
|
if len(tableentry) > 2:
|
|
|
|
self.fn, self.opts, self.help = tableentry
|
|
|
|
else:
|
|
|
|
self.fn, self.opts = tableentry
|
|
|
|
|
2009-11-11 19:48:00 +03:00
|
|
|
if self.help.startswith("hg " + cmd):
|
|
|
|
# drop prefix in old-style help lines so hg shows the alias
|
|
|
|
self.help = self.help[4 + len(cmd):]
|
2010-03-01 17:27:44 +03:00
|
|
|
self.__doc__ = self.fn.__doc__
|
2009-11-11 19:48:00 +03:00
|
|
|
|
2009-05-30 22:32:23 +04:00
|
|
|
except error.UnknownCommand:
|
2014-05-17 16:13:31 +04:00
|
|
|
self.badalias = (_("alias '%s' resolves to unknown command '%s'")
|
|
|
|
% (self.name, cmd))
|
2014-08-13 14:28:42 +04:00
|
|
|
self.unknowncmd = True
|
2009-05-30 22:32:23 +04:00
|
|
|
except error.AmbiguousCommand:
|
2014-05-17 16:13:31 +04:00
|
|
|
self.badalias = (_("alias '%s' resolves to ambiguous command '%s'")
|
|
|
|
% (self.name, cmd))
|
2009-05-30 22:32:23 +04:00
|
|
|
|
2016-05-07 02:16:58 +03:00
|
|
|
@property
|
|
|
|
def args(self):
|
2017-03-26 18:19:18 +03:00
|
|
|
args = pycompat.maplist(util.expandpath, self.givenargs)
|
2016-05-07 02:16:58 +03:00
|
|
|
return aliasargs(self.fn, args)
|
|
|
|
|
2016-03-13 18:06:52 +03:00
|
|
|
def __getattr__(self, name):
|
2017-09-20 02:17:43 +03:00
|
|
|
adefaults = {r'norepo': True, r'cmdtype': unrecoverablewrite,
|
2017-05-03 22:14:53 +03:00
|
|
|
r'optionalrepo': False, r'inferrepo': False}
|
2016-03-13 18:06:52 +03:00
|
|
|
if name not in adefaults:
|
|
|
|
raise AttributeError(name)
|
|
|
|
if self.badalias or util.safehasattr(self, 'shell'):
|
|
|
|
return adefaults[name]
|
|
|
|
return getattr(self.fn, name)
|
|
|
|
|
2009-05-30 22:32:23 +04:00
|
|
|
def __call__(self, ui, *args, **opts):
|
2014-05-17 16:13:31 +04:00
|
|
|
if self.badalias:
|
2014-08-13 17:22:24 +04:00
|
|
|
hint = None
|
2014-08-13 14:28:42 +04:00
|
|
|
if self.unknowncmd:
|
|
|
|
try:
|
|
|
|
# check if the command is in a disabled extension
|
2014-08-13 17:18:28 +04:00
|
|
|
cmd, ext = extensions.disabledcmd(ui, self.cmdname)[:2]
|
2014-08-13 17:22:24 +04:00
|
|
|
hint = _("'%s' is provided by '%s' extension") % (cmd, ext)
|
2014-08-13 14:28:42 +04:00
|
|
|
except error.UnknownCommand:
|
|
|
|
pass
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(self.badalias, hint=hint)
|
2009-05-30 22:32:23 +04:00
|
|
|
if self.shadows:
|
2011-06-21 16:57:17 +04:00
|
|
|
ui.debug("alias '%s' shadows command '%s'\n" %
|
2010-08-28 04:45:11 +04:00
|
|
|
(self.name, self.cmdname))
|
2009-05-30 22:32:23 +04:00
|
|
|
|
2016-08-23 23:40:08 +03:00
|
|
|
ui.log('commandalias', "alias '%s' expands to '%s'\n",
|
|
|
|
self.name, self.definition)
|
2011-07-26 00:17:47 +04:00
|
|
|
if util.safehasattr(self, 'shell'):
|
2010-08-19 02:56:44 +04:00
|
|
|
return self.fn(ui, *args, **opts)
|
|
|
|
else:
|
2010-08-28 04:45:18 +04:00
|
|
|
try:
|
2014-05-17 09:43:06 +04:00
|
|
|
return util.checksignature(self.fn)(ui, *args, **opts)
|
2010-08-28 04:45:18 +04:00
|
|
|
except error.SignatureError:
|
|
|
|
args = ' '.join([self.cmdname] + self.args)
|
2011-06-21 16:57:17 +04:00
|
|
|
ui.debug("alias '%s' expands to '%s'\n" % (self.name, args))
|
2010-08-28 04:45:18 +04:00
|
|
|
raise
|
2009-05-30 22:32:23 +04:00
|
|
|
|
2017-09-23 23:46:12 +03:00
|
|
|
class lazyaliasentry(object):
|
|
|
|
"""like a typical command entry (func, opts, help), but is lazy"""
|
|
|
|
|
|
|
|
def __init__(self, name, definition, cmdtable, source):
|
|
|
|
self.name = name
|
|
|
|
self.definition = definition
|
|
|
|
self.cmdtable = cmdtable.copy()
|
|
|
|
self.source = source
|
|
|
|
|
|
|
|
@util.propertycache
|
|
|
|
def _aliasdef(self):
|
|
|
|
return cmdalias(self.name, self.definition, self.cmdtable, self.source)
|
|
|
|
|
|
|
|
def __getitem__(self, n):
|
|
|
|
aliasdef = self._aliasdef
|
2018-03-01 13:12:01 +03:00
|
|
|
l = [aliasdef, aliasdef.opts, aliasdef.help]
|
|
|
|
return l[n]
|
2017-09-23 23:46:12 +03:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for i in range(3):
|
|
|
|
yield self[i]
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return 3
|
|
|
|
|
2009-05-30 22:32:23 +04:00
|
|
|
def addaliases(ui, cmdtable):
|
|
|
|
# aliases are processed after extensions have been loaded, so they
|
|
|
|
# may use extension commands. Aliases can also use other alias definitions,
|
|
|
|
# but only if they have been defined prior to the current definition.
|
|
|
|
for alias, definition in ui.configitems('alias'):
|
2011-08-04 20:41:23 +04:00
|
|
|
try:
|
2017-09-23 23:46:12 +03:00
|
|
|
if cmdtable[alias].definition == definition:
|
2011-08-04 20:41:23 +04:00
|
|
|
continue
|
|
|
|
except (KeyError, AttributeError):
|
|
|
|
# definition might not exist or it might not be a cmdalias
|
|
|
|
pass
|
|
|
|
|
2017-09-23 23:31:09 +03:00
|
|
|
source = ui.configsource('alias', alias)
|
2017-09-23 23:46:12 +03:00
|
|
|
entry = lazyaliasentry(alias, definition, cmdtable, source)
|
|
|
|
cmdtable[alias] = entry
|
2009-05-30 22:32:23 +04:00
|
|
|
|
2007-08-16 01:55:13 +04:00
|
|
|
def _parse(ui, args):
|
|
|
|
options = {}
|
|
|
|
cmdoptions = {}
|
|
|
|
|
|
|
|
try:
|
|
|
|
args = fancyopts.fancyopts(args, commands.globalopts, options)
|
2016-12-06 03:57:58 +03:00
|
|
|
except getopt.GetoptError as inst:
|
2010-06-05 05:19:53 +04:00
|
|
|
raise error.CommandError(None, inst)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
|
|
|
if args:
|
|
|
|
cmd, args = args[0], args[1:]
|
2009-11-13 17:38:27 +03:00
|
|
|
aliases, entry = cmdutil.findcmd(cmd, commands.table,
|
2012-05-06 18:58:04 +04:00
|
|
|
ui.configbool("ui", "strict"))
|
2007-08-16 01:55:13 +04:00
|
|
|
cmd = aliases[0]
|
2011-05-01 14:29:32 +04:00
|
|
|
args = aliasargs(entry[0], args)
|
2007-08-16 01:55:13 +04:00
|
|
|
defaults = ui.config("defaults", cmd)
|
|
|
|
if defaults:
|
2017-03-19 21:17:07 +03:00
|
|
|
args = pycompat.maplist(
|
|
|
|
util.expandpath, pycompat.shlexsplit(defaults)) + args
|
2009-11-13 17:38:27 +03:00
|
|
|
c = list(entry[1])
|
2007-08-16 01:55:13 +04:00
|
|
|
else:
|
|
|
|
cmd = None
|
|
|
|
c = []
|
|
|
|
|
|
|
|
# combine global options into local
|
|
|
|
for o in commands.globalopts:
|
|
|
|
c.append((o[0], o[1], options[o[1]], o[3]))
|
|
|
|
|
|
|
|
try:
|
2016-08-18 18:32:02 +03:00
|
|
|
args = fancyopts.fancyopts(args, c, cmdoptions, gnu=True)
|
2016-12-06 03:57:58 +03:00
|
|
|
except getopt.GetoptError as inst:
|
2010-06-05 05:19:53 +04:00
|
|
|
raise error.CommandError(cmd, inst)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
|
|
|
# separate global options back out
|
|
|
|
for o in commands.globalopts:
|
|
|
|
n = o[1]
|
|
|
|
options[n] = cmdoptions[n]
|
|
|
|
del cmdoptions[n]
|
|
|
|
|
2009-11-13 17:38:27 +03:00
|
|
|
return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2009-04-24 00:40:10 +04:00
|
|
|
def _parseconfig(ui, config):
|
2007-08-16 01:55:13 +04:00
|
|
|
"""parse the --config options from the command line"""
|
2011-06-24 20:44:59 +04:00
|
|
|
configs = []
|
|
|
|
|
2007-08-16 01:55:13 +04:00
|
|
|
for cfg in config:
|
|
|
|
try:
|
2016-02-09 02:35:30 +03:00
|
|
|
name, value = [cfgelem.strip()
|
|
|
|
for cfgelem in cfg.split('=', 1)]
|
2007-08-16 01:55:13 +04:00
|
|
|
section, name = name.split('.', 1)
|
|
|
|
if not section or not name:
|
|
|
|
raise IndexError
|
2014-03-19 05:45:04 +04:00
|
|
|
ui.setconfig(section, name, value, '--config')
|
2011-06-24 20:44:59 +04:00
|
|
|
configs.append((section, name, value))
|
2007-08-16 01:55:13 +04:00
|
|
|
except (IndexError, ValueError):
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_('malformed --config option: %r '
|
2009-11-04 22:44:15 +03:00
|
|
|
'(use --config section.name=value)') % cfg)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2011-06-24 20:44:59 +04:00
|
|
|
return configs
|
|
|
|
|
2017-11-23 16:23:59 +03:00
|
|
|
def _earlyparseopts(ui, args):
|
2017-11-23 16:17:03 +03:00
|
|
|
options = {}
|
|
|
|
fancyopts.fancyopts(args, commands.globalopts, options,
|
2017-11-23 16:23:59 +03:00
|
|
|
gnu=not ui.plain('strictflags'), early=True,
|
2017-11-25 11:03:52 +03:00
|
|
|
optaliases={'repository': ['repo']})
|
2017-11-23 16:17:03 +03:00
|
|
|
return options
|
|
|
|
|
2017-11-23 17:18:56 +03:00
|
|
|
def _earlysplitopts(args):
|
|
|
|
"""Split args into a list of possible early options and remainder args"""
|
|
|
|
shortoptions = 'R:'
|
|
|
|
# TODO: perhaps 'debugger' should be included
|
|
|
|
longoptions = ['cwd=', 'repository=', 'repo=', 'config=']
|
|
|
|
return fancyopts.earlygetopt(args, shortoptions, longoptions,
|
|
|
|
gnu=True, keepsep=True)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2010-06-10 20:32:19 +04:00
|
|
|
def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
|
2009-02-12 19:36:15 +03:00
|
|
|
# run pre-hook, and abort if it fails
|
2013-04-17 01:39:37 +04:00
|
|
|
hook.hook(lui, repo, "pre-%s" % cmd, True, args=" ".join(fullargs),
|
|
|
|
pats=cmdpats, opts=cmdoptions)
|
2016-04-28 17:37:47 +03:00
|
|
|
try:
|
|
|
|
ret = _runcommand(ui, options, cmd, d)
|
|
|
|
# run post-hook, passing command result
|
|
|
|
hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
|
|
|
|
result=ret, pats=cmdpats, opts=cmdoptions)
|
2018-04-07 10:36:43 +03:00
|
|
|
hintutil.show(lui)
|
2016-04-28 17:37:47 +03:00
|
|
|
except Exception:
|
|
|
|
# run failure hook and re-raise
|
|
|
|
hook.hook(lui, repo, "fail-%s" % cmd, False, args=" ".join(fullargs),
|
|
|
|
pats=cmdpats, opts=cmdoptions)
|
|
|
|
raise
|
2009-02-12 19:36:15 +03:00
|
|
|
return ret
|
|
|
|
|
2016-02-26 18:07:58 +03:00
|
|
|
def _getlocal(ui, rpath, wd=None):
|
2010-08-25 02:25:33 +04:00
|
|
|
"""Return (path, local ui object) for the given target path.
|
2010-10-20 12:13:04 +04:00
|
|
|
|
2010-08-25 02:25:33 +04:00
|
|
|
Takes paths in [cwd]/.hg/hgrc into account."
|
|
|
|
"""
|
2016-02-26 18:07:58 +03:00
|
|
|
if wd is None:
|
|
|
|
try:
|
2016-11-22 16:16:50 +03:00
|
|
|
wd = pycompat.getcwd()
|
2016-02-26 18:07:58 +03:00
|
|
|
except OSError as e:
|
|
|
|
raise error.Abort(_("error getting current working directory: %s") %
|
2017-08-23 03:03:07 +03:00
|
|
|
encoding.strtolocal(e.strerror))
|
2010-07-24 02:38:08 +04:00
|
|
|
path = cmdutil.findrepo(wd) or ""
|
2007-08-16 01:55:13 +04:00
|
|
|
if not path:
|
|
|
|
lui = ui
|
2009-09-09 13:12:36 +04:00
|
|
|
else:
|
2010-10-04 23:26:38 +04:00
|
|
|
lui = ui.copy()
|
2010-10-05 00:07:12 +04:00
|
|
|
lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2017-11-11 11:55:15 +03:00
|
|
|
if rpath:
|
|
|
|
path = lui.expandpath(rpath)
|
2009-04-27 01:50:43 +04:00
|
|
|
lui = ui.copy()
|
2010-10-05 00:07:12 +04:00
|
|
|
lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2010-08-25 02:25:33 +04:00
|
|
|
return path, lui
|
|
|
|
|
2016-05-07 16:12:23 +03:00
|
|
|
def _checkshellalias(lui, ui, args):
|
|
|
|
"""Return the function to run the shell alias, if it is required"""
|
2010-08-25 02:25:33 +04:00
|
|
|
options = {}
|
2010-10-17 21:24:37 +04:00
|
|
|
|
|
|
|
try:
|
|
|
|
args = fancyopts.fancyopts(args, commands.globalopts, options)
|
2016-12-06 03:57:58 +03:00
|
|
|
except getopt.GetoptError:
|
2010-10-17 21:24:37 +04:00
|
|
|
return
|
2010-08-25 02:25:33 +04:00
|
|
|
|
|
|
|
if not args:
|
|
|
|
return
|
|
|
|
|
2016-05-07 16:12:23 +03:00
|
|
|
cmdtable = commands.table
|
2010-08-25 02:25:33 +04:00
|
|
|
|
|
|
|
cmd = args[0]
|
|
|
|
try:
|
2016-05-07 16:12:23 +03:00
|
|
|
strict = ui.configbool("ui", "strict")
|
2014-09-09 19:41:44 +04:00
|
|
|
aliases, entry = cmdutil.findcmd(cmd, cmdtable, strict)
|
2010-11-05 22:54:32 +03:00
|
|
|
except (error.AmbiguousCommand, error.UnknownCommand):
|
2010-08-25 02:25:33 +04:00
|
|
|
return
|
|
|
|
|
|
|
|
cmd = aliases[0]
|
|
|
|
fn = entry[0]
|
|
|
|
|
2011-07-26 00:17:47 +04:00
|
|
|
if cmd and util.safehasattr(fn, 'shell'):
|
2017-11-11 06:40:13 +03:00
|
|
|
# shell alias shouldn't receive early options which are consumed by hg
|
2017-11-23 17:18:56 +03:00
|
|
|
_earlyopts, args = _earlysplitopts(args)
|
2010-08-25 02:25:33 +04:00
|
|
|
d = lambda: fn(ui, *args[1:])
|
2012-05-12 17:54:54 +04:00
|
|
|
return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d,
|
|
|
|
[], {})
|
2010-08-25 02:25:33 +04:00
|
|
|
|
2011-05-26 01:53:23 +04:00
|
|
|
def _dispatch(req):
|
2011-05-26 01:44:11 +04:00
|
|
|
args = req.args
|
2011-05-26 01:53:23 +04:00
|
|
|
ui = req.ui
|
|
|
|
|
2010-08-25 02:25:33 +04:00
|
|
|
# check for cwd
|
2017-11-23 16:23:59 +03:00
|
|
|
cwd = req.earlyoptions['cwd']
|
2010-08-25 02:25:33 +04:00
|
|
|
if cwd:
|
2017-11-11 11:55:15 +03:00
|
|
|
os.chdir(cwd)
|
2010-08-25 02:25:33 +04:00
|
|
|
|
2017-11-23 16:23:59 +03:00
|
|
|
rpath = req.earlyoptions['repository']
|
2010-08-25 02:25:33 +04:00
|
|
|
path, lui = _getlocal(ui, rpath)
|
|
|
|
|
2017-02-11 03:56:29 +03:00
|
|
|
uis = {ui, lui}
|
2011-06-24 20:44:58 +04:00
|
|
|
|
|
|
|
if req.repo:
|
|
|
|
uis.add(req.repo.ui)
|
|
|
|
|
2017-11-23 16:23:59 +03:00
|
|
|
if req.earlyoptions['profile']:
|
2016-08-15 02:35:58 +03:00
|
|
|
for ui_ in uis:
|
|
|
|
ui_.setconfig('profiling', 'enabled', 'true', '--profile')
|
|
|
|
|
2017-06-09 14:29:29 +03:00
|
|
|
profile = lui.configbool('profiling', 'enabled')
|
|
|
|
with profiling.profile(lui, enabled=profile) as profiler:
|
2017-02-14 07:47:41 +03:00
|
|
|
# Configure extensions in phases: uisetup, extsetup, cmdtable, and
|
2017-06-23 20:39:21 +03:00
|
|
|
# reposetup
|
2017-02-14 07:47:41 +03:00
|
|
|
extensions.loadall(lui)
|
|
|
|
# Propagate any changes to lui.__class__ by extensions
|
|
|
|
ui.__class__ = lui.__class__
|
|
|
|
|
|
|
|
# (uisetup and extsetup are handled in extensions.loadall)
|
|
|
|
|
|
|
|
# (reposetup is handled in hg.repository)
|
|
|
|
|
|
|
|
addaliases(lui, commands.table)
|
|
|
|
|
|
|
|
# All aliases and commands are completely defined, now.
|
|
|
|
# Check abbreviation/ambiguity of shell alias.
|
|
|
|
shellaliasfn = _checkshellalias(lui, ui, args)
|
|
|
|
if shellaliasfn:
|
2016-09-22 22:36:30 +03:00
|
|
|
return shellaliasfn()
|
2011-06-24 13:16:14 +04:00
|
|
|
|
2017-02-14 07:47:41 +03:00
|
|
|
# check for fallback encoding
|
|
|
|
fallback = lui.config('ui', 'fallbackencoding')
|
|
|
|
if fallback:
|
|
|
|
encoding.fallbackencoding = fallback
|
|
|
|
|
|
|
|
fullargs = args
|
|
|
|
cmd, func, args, options, cmdoptions = _parse(lui, args)
|
|
|
|
|
2017-11-11 06:40:13 +03:00
|
|
|
if options["config"] != req.earlyoptions["config"]:
|
2017-02-14 07:47:41 +03:00
|
|
|
raise error.Abort(_("option --config may not be abbreviated!"))
|
2018-03-20 02:20:55 +03:00
|
|
|
if options["configfile"] != req.earlyoptions["configfile"]:
|
|
|
|
raise error.Abort(_("option --configfile may not be abbreviated!"))
|
2017-11-11 06:40:13 +03:00
|
|
|
if options["cwd"] != req.earlyoptions["cwd"]:
|
2017-02-14 07:47:41 +03:00
|
|
|
raise error.Abort(_("option --cwd may not be abbreviated!"))
|
2017-11-11 06:40:13 +03:00
|
|
|
if options["repository"] != req.earlyoptions["repository"]:
|
2017-02-14 07:47:41 +03:00
|
|
|
raise error.Abort(_(
|
|
|
|
"option -R has to be separated from other options (e.g. not "
|
|
|
|
"-qR) and --repository may only be abbreviated as --repo!"))
|
2017-11-11 08:02:41 +03:00
|
|
|
if options["debugger"] != req.earlyoptions["debugger"]:
|
|
|
|
raise error.Abort(_("option --debugger may not be abbreviated!"))
|
|
|
|
# don't validate --profile/--traceback, which can be enabled from now
|
2017-02-14 07:47:41 +03:00
|
|
|
|
|
|
|
if options["encoding"]:
|
|
|
|
encoding.encoding = options["encoding"]
|
|
|
|
if options["encodingmode"]:
|
|
|
|
encoding.encodingmode = options["encodingmode"]
|
|
|
|
if options["time"]:
|
|
|
|
def get_times():
|
|
|
|
t = os.times()
|
|
|
|
if t[4] == 0.0:
|
|
|
|
# Windows leaves this as zero, so use time.clock()
|
|
|
|
t = (t[0], t[1], t[2], t[3], time.clock())
|
|
|
|
return t
|
|
|
|
s = get_times()
|
|
|
|
def print_time():
|
|
|
|
t = get_times()
|
|
|
|
ui.warn(
|
|
|
|
_("time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
|
|
|
|
(t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
|
2017-04-12 00:54:12 +03:00
|
|
|
ui.atexit(print_time)
|
2017-06-09 14:36:07 +03:00
|
|
|
if options["profile"]:
|
|
|
|
profiler.start()
|
2017-02-14 07:47:41 +03:00
|
|
|
|
|
|
|
if options['verbose'] or options['debug'] or options['quiet']:
|
|
|
|
for opt in ('verbose', 'debug', 'quiet'):
|
|
|
|
val = str(bool(options[opt]))
|
2017-03-03 22:43:27 +03:00
|
|
|
if pycompat.ispy3:
|
|
|
|
val = val.encode('ascii')
|
2017-02-14 07:47:41 +03:00
|
|
|
for ui_ in uis:
|
|
|
|
ui_.setconfig('ui', opt, val, '--' + opt)
|
|
|
|
|
|
|
|
if options['traceback']:
|
2011-06-24 20:44:58 +04:00
|
|
|
for ui_ in uis:
|
2017-02-14 07:47:41 +03:00
|
|
|
ui_.setconfig('ui', 'traceback', 'on', '--traceback')
|
2011-01-29 17:23:24 +03:00
|
|
|
|
2017-02-14 07:47:41 +03:00
|
|
|
if options['noninteractive']:
|
|
|
|
for ui_ in uis:
|
|
|
|
ui_.setconfig('ui', 'interactive', 'off', '-y')
|
2011-01-29 17:23:24 +03:00
|
|
|
|
2017-02-14 07:47:41 +03:00
|
|
|
if cmdoptions.get('insecure', False):
|
|
|
|
for ui_ in uis:
|
|
|
|
ui_.insecureconnections = True
|
2007-08-16 01:55:13 +04:00
|
|
|
|
dispatch: setup color before pager for correct console information on windows
Before this patch, "hg CMD --pager on" on Windows shows output
unintentionally decorated with ANSI color escape sequences, if color
mode is "auto". This issue occurs in steps below.
1. dispatch() invokes ui.pager() at detection of "--pager on"
2. stdout of hg process is redirected into stdin of pager process
3. "ui.formatted" = True, because isatty(stdout) is so before (2)
4. color module is loaded for colorization
5. color.w32effects = None, because GetConsoleScreenBufferInfo()
fails on stdout redirected at (2)
6. "ansi" color mode is chosen, because of "not w32effects"
7. output is colorized in "ansi" mode because of "ui.formatted" = True
Even if "ansi" color mode is chosen, ordinarily redirected stdout
makes ui.formatted() return False, and colorization is avoided. But in
this issue case, "ui.formatted" = True at (3) forces output to be
colorized.
For correct console information on win32, it is needed to ensure that
color module is loaded before redirection of stdout for pagination.
BTW, if any of enabled extensions has "colortable" attribute, this
issue is avoided even before this patch, because color module is
imported as a part of loading such extension, and extension loading
occurs before setting up pager. For example, mq and keyword have
"colortable".
2017-05-22 21:29:23 +03:00
|
|
|
# setup color handling before pager, because setting up pager
|
|
|
|
# might cause incorrect console information
|
2017-02-25 21:44:23 +03:00
|
|
|
coloropt = options['color']
|
2011-06-24 20:44:58 +04:00
|
|
|
for ui_ in uis:
|
2017-02-25 21:44:23 +03:00
|
|
|
if coloropt:
|
|
|
|
ui_.setconfig('ui', 'color', coloropt, '--color')
|
|
|
|
color.setup(ui_)
|
2007-08-16 01:55:13 +04:00
|
|
|
|
dispatch: setup color before pager for correct console information on windows
Before this patch, "hg CMD --pager on" on Windows shows output
unintentionally decorated with ANSI color escape sequences, if color
mode is "auto". This issue occurs in steps below.
1. dispatch() invokes ui.pager() at detection of "--pager on"
2. stdout of hg process is redirected into stdin of pager process
3. "ui.formatted" = True, because isatty(stdout) is so before (2)
4. color module is loaded for colorization
5. color.w32effects = None, because GetConsoleScreenBufferInfo()
fails on stdout redirected at (2)
6. "ansi" color mode is chosen, because of "not w32effects"
7. output is colorized in "ansi" mode because of "ui.formatted" = True
Even if "ansi" color mode is chosen, ordinarily redirected stdout
makes ui.formatted() return False, and colorization is avoided. But in
this issue case, "ui.formatted" = True at (3) forces output to be
colorized.
For correct console information on win32, it is needed to ensure that
color module is loaded before redirection of stdout for pagination.
BTW, if any of enabled extensions has "colortable" attribute, this
issue is avoided even before this patch, because color module is
imported as a part of loading such extension, and extension loading
occurs before setting up pager. For example, mq and keyword have
"colortable".
2017-05-22 21:29:23 +03:00
|
|
|
if util.parsebool(options['pager']):
|
2017-08-01 12:52:52 +03:00
|
|
|
# ui.pager() expects 'internal-always-' prefix in this case
|
dispatch: setup color before pager for correct console information on windows
Before this patch, "hg CMD --pager on" on Windows shows output
unintentionally decorated with ANSI color escape sequences, if color
mode is "auto". This issue occurs in steps below.
1. dispatch() invokes ui.pager() at detection of "--pager on"
2. stdout of hg process is redirected into stdin of pager process
3. "ui.formatted" = True, because isatty(stdout) is so before (2)
4. color module is loaded for colorization
5. color.w32effects = None, because GetConsoleScreenBufferInfo()
fails on stdout redirected at (2)
6. "ansi" color mode is chosen, because of "not w32effects"
7. output is colorized in "ansi" mode because of "ui.formatted" = True
Even if "ansi" color mode is chosen, ordinarily redirected stdout
makes ui.formatted() return False, and colorization is avoided. But in
this issue case, "ui.formatted" = True at (3) forces output to be
colorized.
For correct console information on win32, it is needed to ensure that
color module is loaded before redirection of stdout for pagination.
BTW, if any of enabled extensions has "colortable" attribute, this
issue is avoided even before this patch, because color module is
imported as a part of loading such extension, and extension loading
occurs before setting up pager. For example, mq and keyword have
"colortable".
2017-05-22 21:29:23 +03:00
|
|
|
ui.pager('internal-always-' + cmd)
|
|
|
|
elif options['pager'] != 'auto':
|
2017-10-09 22:42:28 +03:00
|
|
|
for ui_ in uis:
|
|
|
|
ui_.disablepager()
|
dispatch: setup color before pager for correct console information on windows
Before this patch, "hg CMD --pager on" on Windows shows output
unintentionally decorated with ANSI color escape sequences, if color
mode is "auto". This issue occurs in steps below.
1. dispatch() invokes ui.pager() at detection of "--pager on"
2. stdout of hg process is redirected into stdin of pager process
3. "ui.formatted" = True, because isatty(stdout) is so before (2)
4. color module is loaded for colorization
5. color.w32effects = None, because GetConsoleScreenBufferInfo()
fails on stdout redirected at (2)
6. "ansi" color mode is chosen, because of "not w32effects"
7. output is colorized in "ansi" mode because of "ui.formatted" = True
Even if "ansi" color mode is chosen, ordinarily redirected stdout
makes ui.formatted() return False, and colorization is avoided. But in
this issue case, "ui.formatted" = True at (3) forces output to be
colorized.
For correct console information on win32, it is needed to ensure that
color module is loaded before redirection of stdout for pagination.
BTW, if any of enabled extensions has "colortable" attribute, this
issue is avoided even before this patch, because color module is
imported as a part of loading such extension, and extension loading
occurs before setting up pager. For example, mq and keyword have
"colortable".
2017-05-22 21:29:23 +03:00
|
|
|
|
2017-02-14 07:47:41 +03:00
|
|
|
if options['version']:
|
|
|
|
return commands.version_(ui)
|
|
|
|
if options['help']:
|
|
|
|
return commands.help_(ui, cmd, command=cmd is not None)
|
|
|
|
elif not cmd:
|
|
|
|
return commands.help_(ui, 'shortlist')
|
2007-08-16 01:55:13 +04:00
|
|
|
|
2016-09-22 22:19:48 +03:00
|
|
|
repo = None
|
|
|
|
cmdpats = args[:]
|
2016-11-22 05:51:23 +03:00
|
|
|
if not func.norepo:
|
2016-09-22 22:19:48 +03:00
|
|
|
# use the repo from the request only if we don't have -R
|
|
|
|
if not rpath and not cwd:
|
|
|
|
repo = req.repo
|
|
|
|
|
|
|
|
if repo:
|
|
|
|
# set the descriptors of the repo ui to those of ui
|
|
|
|
repo.ui.fin = ui.fin
|
|
|
|
repo.ui.fout = ui.fout
|
|
|
|
repo.ui.ferr = ui.ferr
|
|
|
|
else:
|
|
|
|
try:
|
2017-04-30 07:39:47 +03:00
|
|
|
repo = hg.repository(ui, path=path,
|
|
|
|
presetupfuncs=req.prereposetups)
|
2016-09-22 22:19:48 +03:00
|
|
|
if not repo.local():
|
|
|
|
raise error.Abort(_("repository '%s' is not local")
|
|
|
|
% path)
|
|
|
|
repo.ui.setconfig("bundle", "mainreporoot", repo.root,
|
|
|
|
'repo')
|
|
|
|
except error.RequirementError:
|
2011-06-02 01:43:34 +04:00
|
|
|
raise
|
2016-09-22 22:19:48 +03:00
|
|
|
except error.RepoError:
|
2017-11-11 11:55:15 +03:00
|
|
|
if rpath: # invalid -R path
|
2016-09-22 22:19:48 +03:00
|
|
|
raise
|
2016-11-22 05:51:23 +03:00
|
|
|
if not func.optionalrepo:
|
|
|
|
if func.inferrepo and args and not path:
|
2016-09-22 22:19:48 +03:00
|
|
|
# try to infer -R from command args
|
2017-11-29 06:10:58 +03:00
|
|
|
repos = pycompat.maplist(cmdutil.findrepo, args)
|
2016-09-22 22:19:48 +03:00
|
|
|
guess = repos[0]
|
|
|
|
if guess and repos.count(guess) == len(repos):
|
|
|
|
req.args = ['--repository', guess] + fullargs
|
2017-11-23 16:23:59 +03:00
|
|
|
req.earlyoptions['repository'] = guess
|
2016-09-22 22:19:48 +03:00
|
|
|
return _dispatch(req)
|
|
|
|
if not path:
|
|
|
|
raise error.RepoError(_("no repository found in"
|
|
|
|
" '%s' (.hg not found)")
|
2016-11-22 21:33:11 +03:00
|
|
|
% pycompat.getcwd())
|
2016-09-22 22:19:48 +03:00
|
|
|
raise
|
|
|
|
if repo:
|
|
|
|
ui = repo.ui
|
|
|
|
if options['hidden']:
|
|
|
|
repo = repo.unfiltered()
|
|
|
|
args.insert(0, repo)
|
|
|
|
elif rpath:
|
|
|
|
ui.warn(_("warning: --repository ignored\n"))
|
|
|
|
|
2018-03-04 01:11:24 +03:00
|
|
|
from . import mdiff
|
|
|
|
mdiff.init(ui)
|
|
|
|
|
2017-03-19 07:18:53 +03:00
|
|
|
msg = _formatargs(fullargs)
|
2016-09-22 22:19:48 +03:00
|
|
|
ui.log("command", '%s\n', msg)
|
2016-12-13 18:23:40 +03:00
|
|
|
strcmdopt = pycompat.strkwargs(cmdoptions)
|
|
|
|
d = lambda: util.checksignature(func)(ui, *args, **strcmdopt)
|
2016-09-22 22:19:48 +03:00
|
|
|
try:
|
|
|
|
return runcommand(lui, repo, cmd, fullargs, ui, options, d,
|
|
|
|
cmdpats, cmdoptions)
|
|
|
|
finally:
|
|
|
|
if repo and repo != req.repo:
|
|
|
|
repo.close()
|
2007-08-16 01:55:13 +04:00
|
|
|
|
|
|
|
def _runcommand(ui, options, cmd, cmdfunc):
|
2016-08-15 03:51:12 +03:00
|
|
|
"""Run a command function, possibly with profiling enabled."""
|
2016-09-22 22:36:30 +03:00
|
|
|
try:
|
|
|
|
return cmdfunc()
|
|
|
|
except error.SignatureError:
|
|
|
|
raise error.CommandError(cmd, _('invalid arguments'))
|
2016-04-04 19:27:37 +03:00
|
|
|
|
2016-04-05 22:01:23 +03:00
|
|
|
def _exceptionwarning(ui):
|
|
|
|
"""Produce a warning message for the current active exception"""
|
2016-04-04 19:27:37 +03:00
|
|
|
|
|
|
|
# For compatibility checking, we discard the portion of the hg
|
|
|
|
# version after the + on the assumption that if a "normal
|
|
|
|
# user" is running a build with a + in it the packager
|
|
|
|
# probably built from fairly close to a tag and anyone with a
|
|
|
|
# 'make local' copy of hg (where the version number can be out
|
|
|
|
# of date) will be clueful enough to notice the implausible
|
|
|
|
# version number and try updating.
|
|
|
|
ct = util.versiontuple(n=2)
|
|
|
|
worst = None, ct, ''
|
codemod: register core configitems using a script
This is done by a script [2] using RedBaron [1], a tool designed for doing
code refactoring. All "default" values are decided by the script and are
strongly consistent with the existing code.
There are 2 changes done manually to fix tests:
[warn] mercurial/exchange.py: experimental.bundle2-output-capture: default needs manual removal
[warn] mercurial/localrepo.py: experimental.hook-track-tags: default needs manual removal
Since RedBaron is not confident about how to indent things [2].
[1]: https://github.com/PyCQA/redbaron
[2]: https://github.com/PyCQA/redbaron/issues/100
[3]:
#!/usr/bin/env python
# codemod_configitems.py - codemod tool to fill configitems
#
# Copyright 2017 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import, print_function
import os
import sys
import redbaron
def readpath(path):
with open(path) as f:
return f.read()
def writepath(path, content):
with open(path, 'w') as f:
f.write(content)
_configmethods = {'config', 'configbool', 'configint', 'configbytes',
'configlist', 'configdate'}
def extractstring(rnode):
"""get the string from a RedBaron string or call_argument node"""
while rnode.type != 'string':
rnode = rnode.value
return rnode.value[1:-1] # unquote, "'str'" -> "str"
def uiconfigitems(red):
"""match *.ui.config* pattern, yield (node, method, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
obj = node[-3].value
method = node[-2].value
args = node[-1]
section = args[0].value
name = args[1].value
if (obj in ('ui', 'self') and method in _configmethods
and section.type == 'string' and name.type == 'string'):
entry = (node, method, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def coreconfigitems(red):
"""match coreconfigitem(...) pattern, yield (node, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
args = node[1]
section = args[0].value
name = args[1].value
if (node[0].value == 'coreconfigitem' and section.type == 'string'
and name.type == 'string'):
entry = (node, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def registercoreconfig(cfgred, section, name, defaultrepr):
"""insert coreconfigitem to cfgred AST
section and name are plain string, defaultrepr is a string
"""
# find a place to insert the "coreconfigitem" item
entries = list(coreconfigitems(cfgred))
for node, args, nodesection, nodename in reversed(entries):
if (nodesection, nodename) < (section, name):
# insert after this entry
node.insert_after(
'coreconfigitem(%r, %r,\n'
' default=%s,\n'
')' % (section, name, defaultrepr))
return
def main(argv):
if not argv:
print('Usage: codemod_configitems.py FILES\n'
'For example, FILES could be "{hgext,mercurial}/*/**.py"')
dirname = os.path.dirname
reporoot = dirname(dirname(dirname(os.path.abspath(__file__))))
# register configitems to this destination
cfgpath = os.path.join(reporoot, 'mercurial', 'configitems.py')
cfgred = redbaron.RedBaron(readpath(cfgpath))
# state about what to do
registered = set((s, n) for n, a, s, n in coreconfigitems(cfgred))
toregister = {} # {(section, name): defaultrepr}
coreconfigs = set() # {(section, name)}, whether it's used in core
# first loop: scan all files before taking any action
for i, path in enumerate(argv):
print('(%d/%d) scanning %s' % (i + 1, len(argv), path))
iscore = ('mercurial' in path) and ('hgext' not in path)
red = redbaron.RedBaron(readpath(path))
# find all repo.ui.config* and ui.config* calls, and collect their
# section, name and default value information.
for node, method, args, section, name in uiconfigitems(red):
if section == 'web':
# [web] section has some weirdness, ignore them for now
continue
defaultrepr = None
key = (section, name)
if len(args) == 2:
if key in registered:
continue
if method == 'configlist':
defaultrepr = 'list'
elif method == 'configbool':
defaultrepr = 'False'
else:
defaultrepr = 'None'
elif len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
# try to understand the "default" value
dnode = args[2].value
if dnode.type == 'name':
if dnode.value in {'None', 'True', 'False'}:
defaultrepr = dnode.value
elif dnode.type == 'string':
defaultrepr = repr(dnode.value[1:-1])
elif dnode.type in ('int', 'float'):
defaultrepr = dnode.value
# inconsistent default
if key in toregister and toregister[key] != defaultrepr:
defaultrepr = None
# interesting to rewrite
if key not in registered:
if defaultrepr is None:
print('[note] %s: %s.%s: unsupported default'
% (path, section, name))
registered.add(key) # skip checking it again
else:
toregister[key] = defaultrepr
if iscore:
coreconfigs.add(key)
# second loop: rewrite files given "toregister" result
for path in argv:
# reconstruct redbaron - trade CPU for memory
red = redbaron.RedBaron(readpath(path))
changed = False
for node, method, args, section, name in uiconfigitems(red):
key = (section, name)
defaultrepr = toregister.get(key)
if defaultrepr is None or key not in coreconfigs:
continue
if len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
try:
del args[2]
changed = True
except Exception:
# redbaron fails to do the rewrite due to indentation
# see https://github.com/PyCQA/redbaron/issues/100
print('[warn] %s: %s.%s: default needs manual removal'
% (path, section, name))
if key not in registered:
print('registering %s.%s' % (section, name))
registercoreconfig(cfgred, section, name, defaultrepr)
registered.add(key)
if changed:
print('updating %s' % path)
writepath(path, red.dumps())
if toregister:
print('updating configitems.py')
writepath(cfgpath, cfgred.dumps())
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
2017-07-15 00:22:40 +03:00
|
|
|
if ui.config('ui', 'supportcontact') is None:
|
2016-04-04 19:27:37 +03:00
|
|
|
for name, mod in extensions.extensions():
|
|
|
|
testedwith = getattr(mod, 'testedwith', '')
|
2017-03-03 21:29:25 +03:00
|
|
|
if pycompat.ispy3 and isinstance(testedwith, str):
|
|
|
|
testedwith = testedwith.encode(u'utf-8')
|
2016-04-04 19:27:37 +03:00
|
|
|
report = getattr(mod, 'buglink', _('the extension author.'))
|
|
|
|
if not testedwith.strip():
|
|
|
|
# We found an untested extension. It's likely the culprit.
|
|
|
|
worst = name, 'unknown', report
|
|
|
|
break
|
|
|
|
|
|
|
|
# Never blame on extensions bundled with Mercurial.
|
2016-08-26 18:00:28 +03:00
|
|
|
if extensions.ismoduleinternal(mod):
|
2016-04-04 19:27:37 +03:00
|
|
|
continue
|
|
|
|
|
|
|
|
tested = [util.versiontuple(t, 2) for t in testedwith.split()]
|
|
|
|
if ct in tested:
|
|
|
|
continue
|
|
|
|
|
|
|
|
lower = [t for t in tested if t < ct]
|
|
|
|
nearest = max(lower or tested)
|
|
|
|
if worst[0] is None or nearest < worst[1]:
|
|
|
|
worst = name, nearest, report
|
|
|
|
if worst[0] is not None:
|
|
|
|
name, testedwith, report = worst
|
2017-03-03 21:29:25 +03:00
|
|
|
if not isinstance(testedwith, (bytes, str)):
|
2016-04-04 19:27:37 +03:00
|
|
|
testedwith = '.'.join([str(c) for c in testedwith])
|
|
|
|
warning = (_('** Unknown exception encountered with '
|
2018-01-15 01:53:52 +03:00
|
|
|
'possibly-broken third-party extension %s.\n'
|
2016-04-04 19:27:37 +03:00
|
|
|
'** Please disable %s and try your action again.\n'
|
|
|
|
'** If that fixes the bug please report it to %s\n')
|
2018-01-15 01:53:52 +03:00
|
|
|
% (name, name, report))
|
2016-04-04 19:27:37 +03:00
|
|
|
else:
|
codemod: register core configitems using a script
This is done by a script [2] using RedBaron [1], a tool designed for doing
code refactoring. All "default" values are decided by the script and are
strongly consistent with the existing code.
There are 2 changes done manually to fix tests:
[warn] mercurial/exchange.py: experimental.bundle2-output-capture: default needs manual removal
[warn] mercurial/localrepo.py: experimental.hook-track-tags: default needs manual removal
Since RedBaron is not confident about how to indent things [2].
[1]: https://github.com/PyCQA/redbaron
[2]: https://github.com/PyCQA/redbaron/issues/100
[3]:
#!/usr/bin/env python
# codemod_configitems.py - codemod tool to fill configitems
#
# Copyright 2017 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import, print_function
import os
import sys
import redbaron
def readpath(path):
with open(path) as f:
return f.read()
def writepath(path, content):
with open(path, 'w') as f:
f.write(content)
_configmethods = {'config', 'configbool', 'configint', 'configbytes',
'configlist', 'configdate'}
def extractstring(rnode):
"""get the string from a RedBaron string or call_argument node"""
while rnode.type != 'string':
rnode = rnode.value
return rnode.value[1:-1] # unquote, "'str'" -> "str"
def uiconfigitems(red):
"""match *.ui.config* pattern, yield (node, method, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
obj = node[-3].value
method = node[-2].value
args = node[-1]
section = args[0].value
name = args[1].value
if (obj in ('ui', 'self') and method in _configmethods
and section.type == 'string' and name.type == 'string'):
entry = (node, method, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def coreconfigitems(red):
"""match coreconfigitem(...) pattern, yield (node, args, section, name)"""
for node in red.find_all('atomtrailers'):
entry = None
try:
args = node[1]
section = args[0].value
name = args[1].value
if (node[0].value == 'coreconfigitem' and section.type == 'string'
and name.type == 'string'):
entry = (node, args, extractstring(section),
extractstring(name))
except Exception:
pass
else:
if entry:
yield entry
def registercoreconfig(cfgred, section, name, defaultrepr):
"""insert coreconfigitem to cfgred AST
section and name are plain string, defaultrepr is a string
"""
# find a place to insert the "coreconfigitem" item
entries = list(coreconfigitems(cfgred))
for node, args, nodesection, nodename in reversed(entries):
if (nodesection, nodename) < (section, name):
# insert after this entry
node.insert_after(
'coreconfigitem(%r, %r,\n'
' default=%s,\n'
')' % (section, name, defaultrepr))
return
def main(argv):
if not argv:
print('Usage: codemod_configitems.py FILES\n'
'For example, FILES could be "{hgext,mercurial}/*/**.py"')
dirname = os.path.dirname
reporoot = dirname(dirname(dirname(os.path.abspath(__file__))))
# register configitems to this destination
cfgpath = os.path.join(reporoot, 'mercurial', 'configitems.py')
cfgred = redbaron.RedBaron(readpath(cfgpath))
# state about what to do
registered = set((s, n) for n, a, s, n in coreconfigitems(cfgred))
toregister = {} # {(section, name): defaultrepr}
coreconfigs = set() # {(section, name)}, whether it's used in core
# first loop: scan all files before taking any action
for i, path in enumerate(argv):
print('(%d/%d) scanning %s' % (i + 1, len(argv), path))
iscore = ('mercurial' in path) and ('hgext' not in path)
red = redbaron.RedBaron(readpath(path))
# find all repo.ui.config* and ui.config* calls, and collect their
# section, name and default value information.
for node, method, args, section, name in uiconfigitems(red):
if section == 'web':
# [web] section has some weirdness, ignore them for now
continue
defaultrepr = None
key = (section, name)
if len(args) == 2:
if key in registered:
continue
if method == 'configlist':
defaultrepr = 'list'
elif method == 'configbool':
defaultrepr = 'False'
else:
defaultrepr = 'None'
elif len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
# try to understand the "default" value
dnode = args[2].value
if dnode.type == 'name':
if dnode.value in {'None', 'True', 'False'}:
defaultrepr = dnode.value
elif dnode.type == 'string':
defaultrepr = repr(dnode.value[1:-1])
elif dnode.type in ('int', 'float'):
defaultrepr = dnode.value
# inconsistent default
if key in toregister and toregister[key] != defaultrepr:
defaultrepr = None
# interesting to rewrite
if key not in registered:
if defaultrepr is None:
print('[note] %s: %s.%s: unsupported default'
% (path, section, name))
registered.add(key) # skip checking it again
else:
toregister[key] = defaultrepr
if iscore:
coreconfigs.add(key)
# second loop: rewrite files given "toregister" result
for path in argv:
# reconstruct redbaron - trade CPU for memory
red = redbaron.RedBaron(readpath(path))
changed = False
for node, method, args, section, name in uiconfigitems(red):
key = (section, name)
defaultrepr = toregister.get(key)
if defaultrepr is None or key not in coreconfigs:
continue
if len(args) >= 3 and (args[2].target is None or
args[2].target.value == 'default'):
try:
del args[2]
changed = True
except Exception:
# redbaron fails to do the rewrite due to indentation
# see https://github.com/PyCQA/redbaron/issues/100
print('[warn] %s: %s.%s: default needs manual removal'
% (path, section, name))
if key not in registered:
print('registering %s.%s' % (section, name))
registercoreconfig(cfgred, section, name, defaultrepr)
registered.add(key)
if changed:
print('updating %s' % path)
writepath(path, red.dumps())
if toregister:
print('updating configitems.py')
writepath(cfgpath, cfgred.dumps())
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
2017-07-15 00:22:40 +03:00
|
|
|
bugtracker = ui.config('ui', 'supportcontact')
|
2016-04-04 19:27:37 +03:00
|
|
|
if bugtracker is None:
|
|
|
|
bugtracker = _("https://mercurial-scm.org/wiki/BugTracker")
|
|
|
|
warning = (_("** unknown exception encountered, "
|
|
|
|
"please report by visiting\n** ") + bugtracker + '\n')
|
2017-03-03 21:29:50 +03:00
|
|
|
if pycompat.ispy3:
|
|
|
|
sysversion = sys.version.encode(u'utf-8')
|
|
|
|
else:
|
|
|
|
sysversion = sys.version
|
|
|
|
sysversion = sysversion.replace('\n', '')
|
|
|
|
warning += ((_("** Python %s\n") % sysversion) +
|
2016-04-04 19:27:37 +03:00
|
|
|
(_("** Mercurial Distributed SCM (version %s)\n") %
|
|
|
|
util.version()) +
|
|
|
|
(_("** Extensions loaded: %s\n") %
|
|
|
|
", ".join([x[0] for x in extensions.extensions()])))
|
2016-04-05 22:01:23 +03:00
|
|
|
return warning
|
|
|
|
|
|
|
|
def handlecommandexception(ui):
|
|
|
|
"""Produce a warning message for broken commands
|
|
|
|
|
|
|
|
Called when handling an exception; the exception is reraised if
|
|
|
|
this function returns False, ignored otherwise.
|
|
|
|
"""
|
|
|
|
warning = _exceptionwarning(ui)
|
2016-04-04 19:27:37 +03:00
|
|
|
ui.log("commandexception", "%s\n%s\n", warning, traceback.format_exc())
|
|
|
|
ui.warn(warning)
|
|
|
|
return False # re-raise the exception
|
2018-01-03 16:35:56 +03:00
|
|
|
|
|
|
|
def rejectpush(ui, **kwargs):
|
|
|
|
ui.warn(("Permission denied\n"))
|
|
|
|
# mercurial hooks use unix process conventions for hook return values
|
|
|
|
# so a truthy return means failure
|
|
|
|
return True
|