2005-06-01 10:57:53 +04:00
|
|
|
# ui.py - user interface bits for mercurial
|
|
|
|
#
|
2007-06-19 10:51:34 +04:00
|
|
|
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
|
2005-06-01 10:57:53 +04:00
|
|
|
#
|
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.
|
2005-06-01 10:57:53 +04:00
|
|
|
|
2015-08-09 04:25:41 +03:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2017-02-16 00:17:45 +03:00
|
|
|
import collections
|
2016-11-22 03:22:26 +03:00
|
|
|
import contextlib
|
2015-08-09 04:25:41 +03:00
|
|
|
import errno
|
|
|
|
import getpass
|
2015-06-19 21:19:45 +03:00
|
|
|
import inspect
|
2015-08-09 04:25:41 +03:00
|
|
|
import os
|
2015-11-30 22:47:29 +03:00
|
|
|
import re
|
2017-02-16 01:47:51 +03:00
|
|
|
import signal
|
2015-08-09 04:25:41 +03:00
|
|
|
import socket
|
2017-02-16 01:47:51 +03:00
|
|
|
import subprocess
|
2015-08-09 04:25:41 +03:00
|
|
|
import sys
|
|
|
|
import tempfile
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
from .i18n import _
|
|
|
|
from .node import hex
|
|
|
|
|
|
|
|
from . import (
|
2017-02-23 21:45:32 +03:00
|
|
|
color,
|
2015-08-09 04:25:41 +03:00
|
|
|
config,
|
2017-06-17 19:43:27 +03:00
|
|
|
configitems,
|
2016-11-03 00:42:57 +03:00
|
|
|
encoding,
|
2015-08-09 04:25:41 +03:00
|
|
|
error,
|
|
|
|
formatter,
|
|
|
|
progress,
|
2016-11-22 21:33:11 +03:00
|
|
|
pycompat,
|
2017-03-27 06:18:42 +03:00
|
|
|
rcutil,
|
2015-08-09 04:25:41 +03:00
|
|
|
scmutil,
|
|
|
|
util,
|
|
|
|
)
|
2009-04-24 00:40:10 +04:00
|
|
|
|
2016-06-09 12:41:36 +03:00
|
|
|
urlreq = util.urlreq
|
|
|
|
|
2017-02-16 00:29:12 +03:00
|
|
|
# for use with str.translate(None, _keepalnum), to keep just alphanumerics
|
2017-03-08 16:30:12 +03:00
|
|
|
_keepalnum = ''.join(c for c in map(pycompat.bytechr, range(256))
|
|
|
|
if not c.isalnum())
|
2017-02-16 00:29:12 +03:00
|
|
|
|
2017-06-15 03:56:34 +03:00
|
|
|
# The config knobs that will be altered (if unset) by ui.tweakdefaults.
|
|
|
|
tweakrc = """
|
|
|
|
[ui]
|
|
|
|
# The rollback command is dangerous. As a rule, don't use it.
|
|
|
|
rollback = False
|
|
|
|
|
|
|
|
[commands]
|
|
|
|
# Make `hg status` emit cwd-relative paths by default.
|
|
|
|
status.relative = yes
|
|
|
|
|
|
|
|
[diff]
|
|
|
|
git = 1
|
|
|
|
"""
|
|
|
|
|
2014-09-11 21:26:12 +04:00
|
|
|
samplehgrcs = {
|
|
|
|
'user':
|
2016-09-21 02:49:00 +03:00
|
|
|
"""# example user config (see 'hg help config' for more info)
|
2014-09-11 21:26:12 +04:00
|
|
|
[ui]
|
|
|
|
# name and email, e.g.
|
|
|
|
# username = Jane Doe <jdoe@example.com>
|
|
|
|
username =
|
|
|
|
|
2017-05-01 16:39:50 +03:00
|
|
|
# uncomment to disable color in command output
|
2017-05-01 16:40:41 +03:00
|
|
|
# (see 'hg help color' for details)
|
2017-05-01 16:39:50 +03:00
|
|
|
# color = never
|
2017-02-22 00:17:33 +03:00
|
|
|
|
2017-05-01 19:07:23 +03:00
|
|
|
# uncomment to disable command output pagination
|
|
|
|
# (see 'hg help pager' for details)
|
2017-05-01 17:36:50 +03:00
|
|
|
# paginate = never
|
2017-05-01 19:07:23 +03:00
|
|
|
|
2014-09-11 21:26:12 +04:00
|
|
|
[extensions]
|
|
|
|
# uncomment these lines to enable some popular extensions
|
2016-09-21 02:49:00 +03:00
|
|
|
# (see 'hg help extensions' for more info)
|
2014-09-11 21:26:12 +04:00
|
|
|
#
|
2017-05-01 16:51:47 +03:00
|
|
|
# churn =
|
2017-05-01 16:51:57 +03:00
|
|
|
""",
|
2014-09-11 21:26:12 +04:00
|
|
|
|
2014-10-07 00:35:02 +04:00
|
|
|
'cloned':
|
2016-09-21 02:49:00 +03:00
|
|
|
"""# example repository config (see 'hg help config' for more info)
|
2014-10-07 00:35:02 +04:00
|
|
|
[paths]
|
|
|
|
default = %s
|
|
|
|
|
|
|
|
# path aliases to other clones of this repo in URLs or filesystem paths
|
2016-09-21 02:49:00 +03:00
|
|
|
# (see 'hg help config.paths' for more info)
|
2014-10-07 00:35:02 +04:00
|
|
|
#
|
2017-02-25 14:27:21 +03:00
|
|
|
# default:pushurl = ssh://jdoe@example.net/hg/jdoes-fork
|
|
|
|
# my-fork = ssh://jdoe@example.net/hg/jdoes-fork
|
|
|
|
# my-clone = /home/jdoe/jdoes-clone
|
2014-10-07 00:35:02 +04:00
|
|
|
|
|
|
|
[ui]
|
|
|
|
# name and email (local to this repository, optional), e.g.
|
|
|
|
# username = Jane Doe <jdoe@example.com>
|
|
|
|
""",
|
|
|
|
|
2014-09-11 21:26:12 +04:00
|
|
|
'local':
|
2016-09-21 02:49:00 +03:00
|
|
|
"""# example repository config (see 'hg help config' for more info)
|
2014-10-08 15:45:51 +04:00
|
|
|
[paths]
|
|
|
|
# path aliases to other clones of this repo in URLs or filesystem paths
|
2016-09-21 02:49:00 +03:00
|
|
|
# (see 'hg help config.paths' for more info)
|
2014-10-08 15:45:51 +04:00
|
|
|
#
|
2017-02-25 14:27:21 +03:00
|
|
|
# default = http://example.com/hg/example-repo
|
|
|
|
# default:pushurl = ssh://jdoe@example.net/hg/jdoes-fork
|
|
|
|
# my-fork = ssh://jdoe@example.net/hg/jdoes-fork
|
|
|
|
# my-clone = /home/jdoe/jdoes-clone
|
2014-10-08 15:45:51 +04:00
|
|
|
|
|
|
|
[ui]
|
|
|
|
# name and email (local to this repository, optional), e.g.
|
|
|
|
# username = Jane Doe <jdoe@example.com>
|
2014-09-11 21:26:12 +04:00
|
|
|
""",
|
|
|
|
|
|
|
|
'global':
|
2016-09-21 02:49:00 +03:00
|
|
|
"""# example system-wide hg config (see 'hg help config' for more info)
|
2014-09-11 21:26:12 +04:00
|
|
|
|
2017-02-22 00:17:33 +03:00
|
|
|
[ui]
|
2017-05-01 16:39:50 +03:00
|
|
|
# uncomment to disable color in command output
|
2017-05-01 16:40:41 +03:00
|
|
|
# (see 'hg help color' for details)
|
2017-05-01 16:39:50 +03:00
|
|
|
# color = never
|
2017-02-22 00:17:33 +03:00
|
|
|
|
2017-05-01 19:07:23 +03:00
|
|
|
# uncomment to disable command output pagination
|
|
|
|
# (see 'hg help pager' for details)
|
2017-05-01 17:36:50 +03:00
|
|
|
# paginate = never
|
2017-05-01 19:07:23 +03:00
|
|
|
|
2014-09-11 21:26:12 +04:00
|
|
|
[extensions]
|
|
|
|
# uncomment these lines to enable some popular extensions
|
2016-09-21 02:49:00 +03:00
|
|
|
# (see 'hg help extensions' for more info)
|
2014-09-11 21:26:12 +04:00
|
|
|
#
|
|
|
|
# blackbox =
|
2017-05-01 16:51:47 +03:00
|
|
|
# churn =
|
2017-05-01 16:51:57 +03:00
|
|
|
""",
|
2014-09-11 21:26:12 +04:00
|
|
|
}
|
|
|
|
|
2017-02-12 14:06:38 +03:00
|
|
|
|
|
|
|
class httppasswordmgrdbproxy(object):
|
|
|
|
"""Delays loading urllib2 until it's needed."""
|
|
|
|
def __init__(self):
|
|
|
|
self._mgr = None
|
|
|
|
|
|
|
|
def _get_mgr(self):
|
|
|
|
if self._mgr is None:
|
|
|
|
self._mgr = urlreq.httppasswordmgrwithdefaultrealm()
|
|
|
|
return self._mgr
|
|
|
|
|
|
|
|
def add_password(self, *args, **kwargs):
|
|
|
|
return self._get_mgr().add_password(*args, **kwargs)
|
|
|
|
|
|
|
|
def find_user_password(self, *args, **kwargs):
|
|
|
|
return self._get_mgr().find_user_password(*args, **kwargs)
|
|
|
|
|
2017-02-16 01:47:51 +03:00
|
|
|
def _catchterm(*args):
|
|
|
|
raise error.SignalInterrupt
|
2017-02-12 14:06:38 +03:00
|
|
|
|
2017-06-17 13:51:11 +03:00
|
|
|
# unique object used to detect no default value has been provided when
|
|
|
|
# retrieving configuration value.
|
|
|
|
_unset = object()
|
|
|
|
|
2005-11-19 09:48:47 +03:00
|
|
|
class ui(object):
|
2009-04-27 01:50:43 +04:00
|
|
|
def __init__(self, src=None):
|
2016-10-22 08:35:10 +03:00
|
|
|
"""Create a fresh new ui object if no src given
|
|
|
|
|
|
|
|
Use uimod.ui.load() to create a ui which knows global and user configs.
|
|
|
|
In most cases, you should use ui.copy() to create a copy of an existing
|
|
|
|
ui object.
|
|
|
|
"""
|
2014-04-17 07:36:57 +04:00
|
|
|
# _buffers: used for temporary capture of output
|
2009-04-27 01:50:44 +04:00
|
|
|
self._buffers = []
|
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
|
|
|
# _exithandlers: callbacks run at the end of a request
|
|
|
|
self._exithandlers = []
|
2015-11-23 01:10:48 +03:00
|
|
|
# 3-tuple describing how each buffer in the stack behaves.
|
|
|
|
# Values are (capture stderr, capture subprocesses, apply labels).
|
2014-04-17 07:36:57 +04:00
|
|
|
self._bufferstates = []
|
2015-11-23 01:10:48 +03:00
|
|
|
# When a buffer is active, defines whether we are expanding labels.
|
|
|
|
# This exists to prevent an extra list lookup.
|
|
|
|
self._bufferapplylabels = None
|
2009-11-13 01:05:52 +03:00
|
|
|
self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
|
2009-04-27 01:50:44 +04:00
|
|
|
self._reportuntrusted = True
|
2017-06-17 19:43:27 +03:00
|
|
|
self._knownconfig = configitems.coreitems
|
2009-04-27 01:50:44 +04:00
|
|
|
self._ocfg = config.config() # overlay
|
|
|
|
self._tcfg = config.config() # trusted
|
|
|
|
self._ucfg = config.config() # untrusted
|
2009-05-17 18:20:27 +04:00
|
|
|
self._trustusers = set()
|
|
|
|
self._trustgroups = set()
|
2012-06-23 20:57:07 +04:00
|
|
|
self.callhooks = True
|
2016-05-05 10:33:38 +03:00
|
|
|
# Insecure server connections requested.
|
|
|
|
self.insecureconnections = False
|
2017-02-16 00:17:45 +03:00
|
|
|
# Blocked time
|
|
|
|
self.logblockedtimes = False
|
2017-02-21 20:22:07 +03:00
|
|
|
# color mode: see mercurial/color.py for possible value
|
|
|
|
self._colormode = None
|
2017-02-25 17:00:51 +03:00
|
|
|
self._terminfoparams = {}
|
2016-11-06 22:16:01 +03:00
|
|
|
self._styles = {}
|
2009-04-24 00:40:10 +04:00
|
|
|
|
2009-04-27 01:50:43 +04:00
|
|
|
if src:
|
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
|
|
|
self._exithandlers = src._exithandlers
|
2011-06-07 14:39:09 +04:00
|
|
|
self.fout = src.fout
|
|
|
|
self.ferr = src.ferr
|
|
|
|
self.fin = src.fin
|
2017-02-16 01:47:51 +03:00
|
|
|
self.pageractive = src.pageractive
|
2017-02-20 04:12:52 +03:00
|
|
|
self._disablepager = src._disablepager
|
2017-06-15 03:56:34 +03:00
|
|
|
self._tweaked = src._tweaked
|
2011-06-07 14:39:09 +04:00
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
self._tcfg = src._tcfg.copy()
|
|
|
|
self._ucfg = src._ucfg.copy()
|
|
|
|
self._ocfg = src._ocfg.copy()
|
2009-04-27 01:50:44 +04:00
|
|
|
self._trustusers = src._trustusers.copy()
|
|
|
|
self._trustgroups = src._trustgroups.copy()
|
2009-11-19 12:32:33 +03:00
|
|
|
self.environ = src.environ
|
2012-06-23 20:57:07 +04:00
|
|
|
self.callhooks = src.callhooks
|
2016-05-05 10:33:38 +03:00
|
|
|
self.insecureconnections = src.insecureconnections
|
2017-02-21 20:22:07 +03:00
|
|
|
self._colormode = src._colormode
|
2017-02-25 17:00:51 +03:00
|
|
|
self._terminfoparams = src._terminfoparams.copy()
|
2016-11-06 22:16:01 +03:00
|
|
|
self._styles = src._styles.copy()
|
2017-02-21 20:22:07 +03:00
|
|
|
|
2009-04-24 00:40:10 +04:00
|
|
|
self.fixconfig()
|
2016-06-09 12:41:36 +03:00
|
|
|
|
|
|
|
self.httppasswordmgrdb = src.httppasswordmgrdb
|
2017-02-16 00:17:45 +03:00
|
|
|
self._blockedtimes = src._blockedtimes
|
2009-04-24 00:40:10 +04:00
|
|
|
else:
|
2016-10-20 17:53:36 +03:00
|
|
|
self.fout = util.stdout
|
|
|
|
self.ferr = util.stderr
|
|
|
|
self.fin = util.stdin
|
2017-02-16 01:47:51 +03:00
|
|
|
self.pageractive = False
|
2017-02-20 04:12:52 +03:00
|
|
|
self._disablepager = False
|
2017-06-15 03:56:34 +03:00
|
|
|
self._tweaked = False
|
2011-06-07 14:39:09 +04:00
|
|
|
|
2009-11-19 12:32:33 +03:00
|
|
|
# shared read-only environment
|
2016-12-17 23:36:00 +03:00
|
|
|
self.environ = encoding.environ
|
2009-04-27 14:37:19 +04:00
|
|
|
|
2017-02-12 14:06:38 +03:00
|
|
|
self.httppasswordmgrdb = httppasswordmgrdbproxy()
|
2017-02-16 00:17:45 +03:00
|
|
|
self._blockedtimes = collections.defaultdict(int)
|
2016-06-09 12:41:36 +03:00
|
|
|
|
2017-01-18 07:05:12 +03:00
|
|
|
allowed = self.configlist('experimental', 'exportableenviron')
|
|
|
|
if '*' in allowed:
|
|
|
|
self._exportableenviron = self.environ
|
|
|
|
else:
|
|
|
|
self._exportableenviron = {}
|
|
|
|
for k in allowed:
|
|
|
|
if k in self.environ:
|
|
|
|
self._exportableenviron[k] = self.environ[k]
|
|
|
|
|
2016-10-22 08:35:10 +03:00
|
|
|
@classmethod
|
|
|
|
def load(cls):
|
|
|
|
"""Create a ui and load global and user configs"""
|
|
|
|
u = cls()
|
2017-03-27 07:33:37 +03:00
|
|
|
# we always trust global config files and environment variables
|
2017-03-27 07:04:29 +03:00
|
|
|
for t, f in rcutil.rccomponents():
|
|
|
|
if t == 'path':
|
|
|
|
u.readconfig(f, trust=True)
|
2017-03-27 07:33:37 +03:00
|
|
|
elif t == 'items':
|
|
|
|
sections = set()
|
|
|
|
for section, name, value, source in f:
|
|
|
|
# do not set u._ocfg
|
|
|
|
# XXX clean this up once immutable config object is a thing
|
|
|
|
u._tcfg.set(section, name, value, source)
|
|
|
|
u._ucfg.set(section, name, value, source)
|
|
|
|
sections.add(section)
|
|
|
|
for section in sections:
|
|
|
|
u.fixconfig(section=section)
|
2017-03-27 07:04:29 +03:00
|
|
|
else:
|
|
|
|
raise error.ProgrammingError('unknown rctype: %s' % t)
|
2017-06-15 03:56:34 +03:00
|
|
|
u._maybetweakdefaults()
|
2016-10-22 08:35:10 +03:00
|
|
|
return u
|
|
|
|
|
2017-06-15 03:56:34 +03:00
|
|
|
def _maybetweakdefaults(self):
|
|
|
|
if not self.configbool('ui', 'tweakdefaults'):
|
|
|
|
return
|
|
|
|
if self._tweaked or self.plain('tweakdefaults'):
|
|
|
|
return
|
|
|
|
|
|
|
|
# Note: it is SUPER IMPORTANT that you set self._tweaked to
|
|
|
|
# True *before* any calls to setconfig(), otherwise you'll get
|
|
|
|
# infinite recursion between setconfig and this method.
|
|
|
|
#
|
|
|
|
# TODO: We should extract an inner method in setconfig() to
|
|
|
|
# avoid this weirdness.
|
|
|
|
self._tweaked = True
|
|
|
|
tmpcfg = config.config()
|
|
|
|
tmpcfg.parse('<tweakdefaults>', tweakrc)
|
|
|
|
for section in tmpcfg:
|
|
|
|
for name, value in tmpcfg.items(section):
|
|
|
|
if not self.hasconfig(section, name):
|
|
|
|
self.setconfig(section, name, value, "<tweakdefaults>")
|
|
|
|
|
2009-04-27 01:50:43 +04:00
|
|
|
def copy(self):
|
2009-04-27 12:33:57 +04:00
|
|
|
return self.__class__(self)
|
2005-06-09 02:45:06 +04:00
|
|
|
|
2016-06-12 08:07:26 +03:00
|
|
|
def resetstate(self):
|
|
|
|
"""Clear internal state that shouldn't persist across commands"""
|
|
|
|
if self._progbar:
|
|
|
|
self._progbar.resetstate() # reset last-print time of progress bar
|
2017-02-12 14:06:38 +03:00
|
|
|
self.httppasswordmgrdb = httppasswordmgrdbproxy()
|
2016-06-12 08:07:26 +03:00
|
|
|
|
2017-02-16 00:17:45 +03:00
|
|
|
@contextlib.contextmanager
|
|
|
|
def timeblockedsection(self, key):
|
2017-02-16 00:50:06 +03:00
|
|
|
# this is open-coded below - search for timeblockedsection to find them
|
2017-02-16 00:17:45 +03:00
|
|
|
starttime = util.timer()
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
self._blockedtimes[key + '_blocked'] += \
|
|
|
|
(util.timer() - starttime) * 1000
|
|
|
|
|
2012-02-21 02:42:48 +04:00
|
|
|
def formatter(self, topic, opts):
|
2015-01-18 12:04:44 +03:00
|
|
|
return formatter.formatter(self, self, topic, opts)
|
2012-02-21 02:42:48 +04:00
|
|
|
|
2011-07-13 01:36:22 +04:00
|
|
|
def _trusted(self, fp, f):
|
2006-11-19 04:51:14 +03:00
|
|
|
st = util.fstat(fp)
|
2009-05-31 01:42:35 +04:00
|
|
|
if util.isowner(st):
|
2006-11-19 04:51:14 +03:00
|
|
|
return True
|
2009-04-24 00:40:10 +04:00
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
tusers, tgroups = self._trustusers, self._trustgroups
|
2009-04-24 00:40:10 +04:00
|
|
|
if '*' in tusers or '*' in tgroups:
|
|
|
|
return True
|
|
|
|
|
|
|
|
user = util.username(st.st_uid)
|
|
|
|
group = util.groupname(st.st_gid)
|
|
|
|
if user in tusers or group in tgroups or user == util.username():
|
|
|
|
return True
|
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
if self._reportuntrusted:
|
2012-06-12 16:18:18 +04:00
|
|
|
self.warn(_('not trusting file %s from untrusted '
|
2009-04-24 00:40:10 +04:00
|
|
|
'user %s, group %s\n') % (f, user, group))
|
|
|
|
return False
|
2006-10-26 21:25:44 +04:00
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
def readconfig(self, filename, root=None, trust=False,
|
2009-05-11 16:20:18 +04:00
|
|
|
sections=None, remap=None):
|
2009-04-24 00:40:10 +04:00
|
|
|
try:
|
2016-10-09 16:17:49 +03:00
|
|
|
fp = open(filename, u'rb')
|
2009-04-24 00:40:10 +04:00
|
|
|
except IOError:
|
|
|
|
if not sections: # ignore unless we were looking for something
|
|
|
|
return
|
|
|
|
raise
|
2006-10-26 21:25:45 +04:00
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
cfg = config.config()
|
2011-07-13 01:36:22 +04:00
|
|
|
trusted = sections or trust or self._trusted(fp, filename)
|
2006-10-26 21:25:45 +04:00
|
|
|
|
2009-04-24 00:40:10 +04:00
|
|
|
try:
|
2009-05-11 16:20:18 +04:00
|
|
|
cfg.read(filename, fp, sections=sections, remap=remap)
|
2011-11-03 20:24:55 +04:00
|
|
|
fp.close()
|
2015-06-24 08:20:08 +03:00
|
|
|
except error.ConfigError as inst:
|
2006-10-26 21:25:45 +04:00
|
|
|
if trusted:
|
2009-04-24 00:40:10 +04:00
|
|
|
raise
|
2012-06-12 16:18:18 +04:00
|
|
|
self.warn(_("ignored: %s\n") % str(inst))
|
2009-04-24 00:40:10 +04:00
|
|
|
|
2010-02-07 16:56:18 +03:00
|
|
|
if self.plain():
|
2010-02-19 00:51:39 +03:00
|
|
|
for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
|
2015-03-24 23:25:57 +03:00
|
|
|
'logtemplate', 'statuscopies', 'style',
|
2010-02-19 00:51:39 +03:00
|
|
|
'traceback', 'verbose'):
|
2010-02-07 16:56:18 +03:00
|
|
|
if k in cfg['ui']:
|
|
|
|
del cfg['ui'][k]
|
|
|
|
for k, v in cfg.items('defaults'):
|
|
|
|
del cfg['defaults'][k]
|
2017-03-22 07:26:52 +03:00
|
|
|
for k, v in cfg.items('commands'):
|
|
|
|
del cfg['commands'][k]
|
2011-05-17 02:17:52 +04:00
|
|
|
# Don't remove aliases from the configuration if in the exceptionlist
|
|
|
|
if self.plain('alias'):
|
|
|
|
for k, v in cfg.items('alias'):
|
|
|
|
del cfg['alias'][k]
|
2015-04-30 17:46:54 +03:00
|
|
|
if self.plain('revsetalias'):
|
|
|
|
for k, v in cfg.items('revsetalias'):
|
|
|
|
del cfg['revsetalias'][k]
|
2016-03-27 15:05:55 +03:00
|
|
|
if self.plain('templatealias'):
|
|
|
|
for k, v in cfg.items('templatealias'):
|
|
|
|
del cfg['templatealias'][k]
|
2010-02-07 16:56:18 +03:00
|
|
|
|
2009-04-24 00:40:10 +04:00
|
|
|
if trusted:
|
2009-04-27 01:50:44 +04:00
|
|
|
self._tcfg.update(cfg)
|
|
|
|
self._tcfg.update(self._ocfg)
|
|
|
|
self._ucfg.update(cfg)
|
|
|
|
self._ucfg.update(self._ocfg)
|
2009-04-24 00:40:10 +04:00
|
|
|
|
2006-10-11 01:43:20 +04:00
|
|
|
if root is None:
|
|
|
|
root = os.path.expanduser('~')
|
|
|
|
self.fixconfig(root=root)
|
2006-08-23 05:49:30 +04:00
|
|
|
|
2010-10-18 09:10:36 +04:00
|
|
|
def fixconfig(self, root=None, section=None):
|
|
|
|
if section in (None, 'paths'):
|
|
|
|
# expand vars and ~
|
|
|
|
# translate paths relative to root (or home) into absolute paths
|
2016-11-22 21:33:11 +03:00
|
|
|
root = root or pycompat.getcwd()
|
2010-10-18 09:10:36 +04:00
|
|
|
for c in self._tcfg, self._ucfg, self._ocfg:
|
|
|
|
for n, p in c.items('paths'):
|
2016-06-26 04:35:14 +03:00
|
|
|
# Ignore sub-options.
|
|
|
|
if ':' in n:
|
|
|
|
continue
|
2010-10-18 09:10:36 +04:00
|
|
|
if not p:
|
|
|
|
continue
|
|
|
|
if '%%' in p:
|
2016-10-23 11:47:00 +03:00
|
|
|
s = self.configsource('paths', n) or 'none'
|
2010-10-18 09:10:36 +04:00
|
|
|
self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
|
2016-10-23 11:47:00 +03:00
|
|
|
% (n, p, s))
|
2010-10-18 09:10:36 +04:00
|
|
|
p = p.replace('%%', '%')
|
|
|
|
p = util.expandpath(p)
|
2011-04-30 20:43:20 +04:00
|
|
|
if not util.hasscheme(p) and not os.path.isabs(p):
|
2010-10-18 09:10:36 +04:00
|
|
|
p = os.path.normpath(os.path.join(root, p))
|
|
|
|
c.set("paths", n, p)
|
|
|
|
|
|
|
|
if section in (None, 'ui'):
|
|
|
|
# update ui options
|
|
|
|
self.debugflag = self.configbool('ui', 'debug')
|
|
|
|
self.verbose = self.debugflag or self.configbool('ui', 'verbose')
|
|
|
|
self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
|
|
|
|
if self.verbose and self.quiet:
|
|
|
|
self.quiet = self.verbose = False
|
2011-02-26 08:26:24 +03:00
|
|
|
self._reportuntrusted = self.debugflag or self.configbool("ui",
|
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
|
|
|
"report_untrusted")
|
|
|
|
self.tracebackflag = self.configbool('ui', 'traceback')
|
2017-02-16 00:17:45 +03:00
|
|
|
self.logblockedtimes = self.configbool('ui', 'logblockedtimes')
|
2010-10-18 09:10:36 +04:00
|
|
|
|
|
|
|
if section in (None, 'trusted'):
|
|
|
|
# update trust information
|
|
|
|
self._trustusers.update(self.configlist('trusted', 'users'))
|
|
|
|
self._trustgroups.update(self.configlist('trusted', 'groups'))
|
2006-10-26 21:25:44 +04:00
|
|
|
|
2012-01-18 19:52:26 +04:00
|
|
|
def backupconfig(self, section, item):
|
|
|
|
return (self._ocfg.backup(section, item),
|
|
|
|
self._tcfg.backup(section, item),
|
|
|
|
self._ucfg.backup(section, item),)
|
|
|
|
def restoreconfig(self, data):
|
|
|
|
self._ocfg.restore(data[0])
|
|
|
|
self._tcfg.restore(data[1])
|
|
|
|
self._ucfg.restore(data[2])
|
|
|
|
|
2014-03-19 05:45:04 +04:00
|
|
|
def setconfig(self, section, name, value, source=''):
|
2014-03-19 04:59:15 +04:00
|
|
|
for cfg in (self._ocfg, self._tcfg, self._ucfg):
|
2014-03-19 05:45:04 +04:00
|
|
|
cfg.set(section, name, value, source)
|
2010-10-18 09:10:36 +04:00
|
|
|
self.fixconfig(section=section)
|
2017-06-15 03:56:34 +03:00
|
|
|
self._maybetweakdefaults()
|
2005-08-20 09:25:25 +04:00
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
def _data(self, untrusted):
|
2009-04-27 01:50:44 +04:00
|
|
|
return untrusted and self._ucfg or self._tcfg
|
2006-10-26 21:25:45 +04:00
|
|
|
|
2009-04-27 01:50:43 +04:00
|
|
|
def configsource(self, section, name, untrusted=False):
|
2016-10-23 11:47:00 +03:00
|
|
|
return self._data(untrusted).source(section, name)
|
2009-04-27 01:50:43 +04:00
|
|
|
|
2017-06-17 13:51:11 +03:00
|
|
|
def config(self, section, name, default=_unset, untrusted=False):
|
2017-06-25 15:34:34 +03:00
|
|
|
"""return the plain string version of a config"""
|
|
|
|
value = self._config(section, name, default=default,
|
|
|
|
untrusted=untrusted)
|
|
|
|
if value is _unset:
|
|
|
|
return None
|
|
|
|
return value
|
|
|
|
|
|
|
|
def _config(self, section, name, default=_unset, untrusted=False):
|
|
|
|
value = default
|
2017-07-07 09:33:10 +03:00
|
|
|
item = self._knownconfig.get(section, {}).get(name)
|
|
|
|
alternates = [(section, name)]
|
|
|
|
|
|
|
|
if item is not None:
|
|
|
|
alternates.extend(item.alias)
|
|
|
|
|
|
|
|
if default is _unset:
|
|
|
|
if item is None:
|
|
|
|
value = default
|
2017-07-13 00:36:10 +03:00
|
|
|
elif item.default is configitems.dynamicdefault:
|
|
|
|
value = None
|
|
|
|
msg = "config item requires an explicit default value: '%s.%s'"
|
|
|
|
msg %= (section, name)
|
|
|
|
self.develwarn(msg, 2, 'warn-config-default')
|
2017-07-07 09:33:10 +03:00
|
|
|
elif callable(item.default):
|
2017-06-28 14:50:20 +03:00
|
|
|
value = item.default()
|
2017-07-07 09:33:10 +03:00
|
|
|
else:
|
|
|
|
value = item.default
|
2017-07-13 00:36:10 +03:00
|
|
|
elif (item is not None
|
|
|
|
and item.default is not configitems.dynamicdefault):
|
2017-07-07 09:33:10 +03:00
|
|
|
msg = ("specifying a default value for a registered "
|
|
|
|
"config item: '%s.%s' '%s'")
|
|
|
|
msg %= (section, name, default)
|
|
|
|
self.develwarn(msg, 2, 'warn-config-default')
|
|
|
|
|
|
|
|
for s, n in alternates:
|
|
|
|
candidate = self._data(untrusted).get(s, n, None)
|
2017-06-25 15:34:34 +03:00
|
|
|
if candidate is not None:
|
|
|
|
value = candidate
|
2017-07-07 09:33:10 +03:00
|
|
|
section = s
|
2011-08-11 23:34:03 +04:00
|
|
|
name = n
|
|
|
|
break
|
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
if self.debugflag and not untrusted and self._reportuntrusted:
|
2017-07-07 09:33:10 +03:00
|
|
|
for s, n in alternates:
|
|
|
|
uvalue = self._ucfg.get(s, n)
|
2013-07-25 03:13:39 +04:00
|
|
|
if uvalue is not None and uvalue != value:
|
|
|
|
self.debug("ignoring untrusted configuration option "
|
2017-07-07 09:33:10 +03:00
|
|
|
"%s.%s = %s\n" % (s, n, uvalue))
|
2006-10-26 21:25:45 +04:00
|
|
|
return value
|
|
|
|
|
2017-06-17 13:51:37 +03:00
|
|
|
def configsuboptions(self, section, name, default=_unset, untrusted=False):
|
2015-12-06 07:20:57 +03:00
|
|
|
"""Get a config option and all sub-options.
|
|
|
|
|
|
|
|
Some config options have sub-options that are declared with the
|
|
|
|
format "key:opt = value". This method is used to return the main
|
|
|
|
option and all its declared sub-options.
|
|
|
|
|
|
|
|
Returns a 2-tuple of ``(option, sub-options)``, where `sub-options``
|
|
|
|
is a dict of defined sub-options where keys and values are strings.
|
|
|
|
"""
|
2017-06-17 19:28:20 +03:00
|
|
|
main = self.config(section, name, default, untrusted=untrusted)
|
2015-12-06 07:20:57 +03:00
|
|
|
data = self._data(untrusted)
|
|
|
|
sub = {}
|
|
|
|
prefix = '%s:' % name
|
|
|
|
for k, v in data.items(section):
|
|
|
|
if k.startswith(prefix):
|
|
|
|
sub[k[len(prefix):]] = v
|
|
|
|
|
|
|
|
if self.debugflag and not untrusted and self._reportuntrusted:
|
|
|
|
for k, v in sub.items():
|
|
|
|
uvalue = self._ucfg.get(section, '%s:%s' % (name, k))
|
|
|
|
if uvalue is not None and uvalue != v:
|
|
|
|
self.debug('ignoring untrusted configuration option '
|
|
|
|
'%s:%s.%s = %s\n' % (section, name, k, uvalue))
|
|
|
|
|
|
|
|
return main, sub
|
|
|
|
|
2017-06-17 13:52:02 +03:00
|
|
|
def configpath(self, section, name, default=_unset, untrusted=False):
|
2011-07-23 08:09:14 +04:00
|
|
|
'get a path config item, expanded relative to repo root or config file'
|
2011-01-07 02:04:33 +03:00
|
|
|
v = self.config(section, name, default, untrusted)
|
2011-07-23 08:08:52 +04:00
|
|
|
if v is None:
|
|
|
|
return None
|
2011-01-07 02:04:33 +03:00
|
|
|
if not os.path.isabs(v) or "://" not in v:
|
|
|
|
src = self.configsource(section, name, untrusted)
|
|
|
|
if ':' in src:
|
2011-07-23 08:08:49 +04:00
|
|
|
base = os.path.dirname(src.rsplit(':')[0])
|
2011-01-07 02:04:33 +03:00
|
|
|
v = os.path.join(base, os.path.expanduser(v))
|
|
|
|
return v
|
|
|
|
|
2017-06-17 13:52:16 +03:00
|
|
|
def configbool(self, section, name, default=_unset, untrusted=False):
|
2011-05-04 00:28:08 +04:00
|
|
|
"""parse a configuration element as a boolean
|
|
|
|
|
|
|
|
>>> u = ui(); s = 'foo'
|
|
|
|
>>> u.setconfig(s, 'true', 'yes')
|
|
|
|
>>> u.configbool(s, 'true')
|
|
|
|
True
|
|
|
|
>>> u.setconfig(s, 'false', 'no')
|
|
|
|
>>> u.configbool(s, 'false')
|
|
|
|
False
|
|
|
|
>>> u.configbool(s, 'unknown')
|
|
|
|
False
|
|
|
|
>>> u.configbool(s, 'unknown', True)
|
|
|
|
True
|
|
|
|
>>> u.setconfig(s, 'invalid', 'somevalue')
|
|
|
|
>>> u.configbool(s, 'invalid')
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ConfigError: foo.invalid is not a boolean ('somevalue')
|
|
|
|
"""
|
|
|
|
|
2017-06-25 15:38:56 +03:00
|
|
|
v = self._config(section, name, default, untrusted=untrusted)
|
2009-05-20 02:52:46 +04:00
|
|
|
if v is None:
|
2017-06-25 15:38:56 +03:00
|
|
|
return v
|
|
|
|
if v is _unset:
|
2017-06-17 13:52:16 +03:00
|
|
|
if default is _unset:
|
|
|
|
return False
|
2009-04-24 00:40:10 +04:00
|
|
|
return default
|
2010-01-13 13:53:55 +03:00
|
|
|
if isinstance(v, bool):
|
|
|
|
return v
|
2010-08-29 06:50:35 +04:00
|
|
|
b = util.parsebool(v)
|
|
|
|
if b is None:
|
2011-05-04 00:28:08 +04:00
|
|
|
raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
|
2009-04-24 00:40:10 +04:00
|
|
|
% (section, name, v))
|
2010-08-29 06:50:35 +04:00
|
|
|
return b
|
2006-10-26 21:25:45 +04:00
|
|
|
|
2017-06-17 13:52:31 +03:00
|
|
|
def configwith(self, convert, section, name, default=_unset,
|
2017-02-13 08:40:46 +03:00
|
|
|
desc=None, untrusted=False):
|
|
|
|
"""parse a configuration element with a conversion function
|
|
|
|
|
|
|
|
>>> u = ui(); s = 'foo'
|
|
|
|
>>> u.setconfig(s, 'float1', '42')
|
|
|
|
>>> u.configwith(float, s, 'float1')
|
|
|
|
42.0
|
2017-02-14 08:00:50 +03:00
|
|
|
>>> u.setconfig(s, 'float2', '-4.25')
|
2017-02-13 08:40:46 +03:00
|
|
|
>>> u.configwith(float, s, 'float2')
|
2017-02-14 08:00:50 +03:00
|
|
|
-4.25
|
2017-02-13 08:40:46 +03:00
|
|
|
>>> u.configwith(float, s, 'unknown', 7)
|
2017-06-17 13:52:31 +03:00
|
|
|
7.0
|
2017-02-13 08:40:46 +03:00
|
|
|
>>> u.setconfig(s, 'invalid', 'somevalue')
|
|
|
|
>>> u.configwith(float, s, 'invalid')
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ConfigError: foo.invalid is not a valid float ('somevalue')
|
|
|
|
>>> u.configwith(float, s, 'invalid', desc='womble')
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ConfigError: foo.invalid is not a valid womble ('somevalue')
|
|
|
|
"""
|
|
|
|
|
2017-06-17 13:52:31 +03:00
|
|
|
v = self.config(section, name, default, untrusted)
|
2017-02-13 08:40:46 +03:00
|
|
|
if v is None:
|
2017-06-17 13:52:31 +03:00
|
|
|
return v # do not attempt to convert None
|
2017-02-13 08:40:46 +03:00
|
|
|
try:
|
|
|
|
return convert(v)
|
2017-05-24 18:50:17 +03:00
|
|
|
except (ValueError, error.ParseError):
|
2017-02-13 08:40:46 +03:00
|
|
|
if desc is None:
|
|
|
|
desc = convert.__name__
|
|
|
|
raise error.ConfigError(_("%s.%s is not a valid %s ('%s')")
|
|
|
|
% (section, name, desc, v))
|
|
|
|
|
2017-06-17 13:53:40 +03:00
|
|
|
def configint(self, section, name, default=_unset, untrusted=False):
|
2011-05-04 00:28:08 +04:00
|
|
|
"""parse a configuration element as an integer
|
|
|
|
|
|
|
|
>>> u = ui(); s = 'foo'
|
|
|
|
>>> u.setconfig(s, 'int1', '42')
|
|
|
|
>>> u.configint(s, 'int1')
|
|
|
|
42
|
|
|
|
>>> u.setconfig(s, 'int2', '-42')
|
|
|
|
>>> u.configint(s, 'int2')
|
|
|
|
-42
|
|
|
|
>>> u.configint(s, 'unknown', 7)
|
|
|
|
7
|
|
|
|
>>> u.setconfig(s, 'invalid', 'somevalue')
|
|
|
|
>>> u.configint(s, 'invalid')
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2017-02-13 08:44:55 +03:00
|
|
|
ConfigError: foo.invalid is not a valid integer ('somevalue')
|
2011-05-04 00:28:08 +04:00
|
|
|
"""
|
|
|
|
|
2017-02-13 08:44:55 +03:00
|
|
|
return self.configwith(int, section, name, default, 'integer',
|
|
|
|
untrusted)
|
2011-05-04 00:28:08 +04:00
|
|
|
|
2017-06-17 13:53:51 +03:00
|
|
|
def configbytes(self, section, name, default=_unset, untrusted=False):
|
2013-04-18 23:58:28 +04:00
|
|
|
"""parse a configuration element as a quantity in bytes
|
|
|
|
|
|
|
|
Units can be specified as b (bytes), k or kb (kilobytes), m or
|
|
|
|
mb (megabytes), g or gb (gigabytes).
|
|
|
|
|
|
|
|
>>> u = ui(); s = 'foo'
|
|
|
|
>>> u.setconfig(s, 'val1', '42')
|
|
|
|
>>> u.configbytes(s, 'val1')
|
|
|
|
42
|
|
|
|
>>> u.setconfig(s, 'val2', '42.5 kb')
|
|
|
|
>>> u.configbytes(s, 'val2')
|
|
|
|
43520
|
|
|
|
>>> u.configbytes(s, 'unknown', '7 MB')
|
|
|
|
7340032
|
|
|
|
>>> u.setconfig(s, 'invalid', 'somevalue')
|
|
|
|
>>> u.configbytes(s, 'invalid')
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
ConfigError: foo.invalid is not a byte quantity ('somevalue')
|
|
|
|
"""
|
|
|
|
|
2017-06-25 15:41:12 +03:00
|
|
|
value = self._config(section, name, default, untrusted)
|
|
|
|
if value is _unset:
|
2017-06-17 13:53:51 +03:00
|
|
|
if default is _unset:
|
|
|
|
default = 0
|
2013-05-15 02:16:44 +04:00
|
|
|
value = default
|
2017-06-17 13:53:51 +03:00
|
|
|
if not isinstance(value, str):
|
|
|
|
return value
|
2013-04-18 23:58:28 +04:00
|
|
|
try:
|
2013-05-15 02:16:44 +04:00
|
|
|
return util.sizetoint(value)
|
|
|
|
except error.ParseError:
|
2013-04-18 23:58:28 +04:00
|
|
|
raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')")
|
2013-05-15 02:16:44 +04:00
|
|
|
% (section, name, value))
|
2013-04-18 23:58:28 +04:00
|
|
|
|
2017-06-17 13:54:04 +03:00
|
|
|
def configlist(self, section, name, default=_unset, untrusted=False):
|
2011-05-04 00:28:08 +04:00
|
|
|
"""parse a configuration element as a list of comma/space separated
|
|
|
|
strings
|
|
|
|
|
|
|
|
>>> u = ui(); s = 'foo'
|
|
|
|
>>> u.setconfig(s, 'list1', 'this,is "a small" ,test')
|
|
|
|
>>> u.configlist(s, 'list1')
|
|
|
|
['this', 'is', 'a small', 'test']
|
|
|
|
"""
|
2017-03-17 19:19:56 +03:00
|
|
|
# default is not always a list
|
2017-06-17 13:54:04 +03:00
|
|
|
v = self.configwith(config.parselist, section, name, default,
|
2017-03-17 19:19:56 +03:00
|
|
|
'list', untrusted)
|
2017-06-17 13:54:04 +03:00
|
|
|
if isinstance(v, bytes):
|
|
|
|
return config.parselist(v)
|
|
|
|
elif v is None:
|
|
|
|
return []
|
|
|
|
return v
|
2006-06-26 16:52:26 +04:00
|
|
|
|
2017-06-17 13:54:45 +03:00
|
|
|
def configdate(self, section, name, default=_unset, untrusted=False):
|
2017-05-19 13:07:41 +03:00
|
|
|
"""parse a configuration element as a tuple of ints
|
|
|
|
|
|
|
|
>>> u = ui(); s = 'foo'
|
|
|
|
>>> u.setconfig(s, 'date', '0 0')
|
|
|
|
>>> u.configdate(s, 'date')
|
|
|
|
(0, 0)
|
|
|
|
"""
|
|
|
|
if self.config(section, name, default, untrusted):
|
2017-05-24 18:50:17 +03:00
|
|
|
return self.configwith(util.parsedate, section, name, default,
|
2017-05-19 13:07:41 +03:00
|
|
|
'date', untrusted)
|
2017-06-17 13:54:45 +03:00
|
|
|
if default is _unset:
|
|
|
|
return None
|
2017-05-19 13:07:41 +03:00
|
|
|
return default
|
|
|
|
|
2016-01-08 06:45:03 +03:00
|
|
|
def hasconfig(self, section, name, untrusted=False):
|
|
|
|
return self._data(untrusted).hasitem(section, name)
|
|
|
|
|
2007-05-28 00:50:59 +04:00
|
|
|
def has_section(self, section, untrusted=False):
|
2006-05-24 01:57:45 +04:00
|
|
|
'''tell whether section exists in config.'''
|
2009-04-27 01:50:44 +04:00
|
|
|
return section in self._data(untrusted)
|
2006-10-26 21:25:45 +04:00
|
|
|
|
2015-12-06 07:24:39 +03:00
|
|
|
def configitems(self, section, untrusted=False, ignoresub=False):
|
2009-04-27 01:50:44 +04:00
|
|
|
items = self._data(untrusted).items(section)
|
2015-12-06 07:24:39 +03:00
|
|
|
if ignoresub:
|
|
|
|
newitems = {}
|
|
|
|
for k, v in items:
|
|
|
|
if ':' not in k:
|
|
|
|
newitems[k] = v
|
|
|
|
items = newitems.items()
|
2009-04-27 01:50:44 +04:00
|
|
|
if self.debugflag and not untrusted and self._reportuntrusted:
|
2009-04-27 14:37:19 +04:00
|
|
|
for k, v in self._ucfg.items(section):
|
2009-04-27 01:50:44 +04:00
|
|
|
if self._tcfg.get(section, k) != v:
|
2011-06-21 20:35:13 +04:00
|
|
|
self.debug("ignoring untrusted configuration option "
|
|
|
|
"%s.%s = %s\n" % (section, k, v))
|
2009-04-24 00:40:10 +04:00
|
|
|
return items
|
2006-03-06 19:47:41 +03:00
|
|
|
|
2006-10-26 21:25:45 +04:00
|
|
|
def walkconfig(self, untrusted=False):
|
2009-04-27 01:50:44 +04:00
|
|
|
cfg = self._data(untrusted)
|
|
|
|
for section in cfg.sections():
|
2006-10-26 21:25:45 +04:00
|
|
|
for name, value in self.configitems(section, untrusted):
|
2011-03-10 18:49:37 +03:00
|
|
|
yield section, name, value
|
2005-08-24 08:30:12 +04:00
|
|
|
|
2011-05-17 02:08:51 +04:00
|
|
|
def plain(self, feature=None):
|
2010-06-07 18:14:12 +04:00
|
|
|
'''is plain mode active?
|
|
|
|
|
2011-01-04 16:18:36 +03:00
|
|
|
Plain mode means that all configuration variables which affect
|
|
|
|
the behavior and output of Mercurial should be
|
|
|
|
ignored. Additionally, the output should be stable,
|
|
|
|
reproducible and suitable for use in scripts or applications.
|
2010-06-07 18:14:12 +04:00
|
|
|
|
2011-01-04 16:18:36 +03:00
|
|
|
The only way to trigger plain mode is by setting either the
|
|
|
|
`HGPLAIN' or `HGPLAINEXCEPT' environment variables.
|
|
|
|
|
2011-05-17 02:08:51 +04:00
|
|
|
The return value can either be
|
|
|
|
- False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
|
|
|
|
- True otherwise
|
2010-06-07 18:14:12 +04:00
|
|
|
'''
|
2016-11-03 00:42:57 +03:00
|
|
|
if ('HGPLAIN' not in encoding.environ and
|
|
|
|
'HGPLAINEXCEPT' not in encoding.environ):
|
2011-01-04 16:18:36 +03:00
|
|
|
return False
|
2016-11-03 00:42:57 +03:00
|
|
|
exceptions = encoding.environ.get('HGPLAINEXCEPT',
|
|
|
|
'').strip().split(',')
|
2011-05-17 02:08:51 +04:00
|
|
|
if feature and exceptions:
|
|
|
|
return feature not in exceptions
|
|
|
|
return True
|
2010-02-07 16:56:18 +03:00
|
|
|
|
2005-07-04 09:51:09 +04:00
|
|
|
def username(self):
|
2006-03-21 17:33:29 +03:00
|
|
|
"""Return default username to be used in commits.
|
|
|
|
|
|
|
|
Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
|
|
|
|
and stop searching if one of these is set.
|
2008-08-06 17:10:05 +04:00
|
|
|
If not found and ui.askusername is True, ask the user, else use
|
|
|
|
($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
|
2006-03-21 17:33:29 +03:00
|
|
|
"""
|
2016-11-03 00:42:57 +03:00
|
|
|
user = encoding.environ.get("HGUSER")
|
2006-03-21 17:33:29 +03:00
|
|
|
if user is None:
|
2017-07-07 09:33:10 +03:00
|
|
|
user = self.config("ui", "username")
|
2010-05-27 01:03:29 +04:00
|
|
|
if user is not None:
|
|
|
|
user = os.path.expandvars(user)
|
2006-03-21 17:33:29 +03:00
|
|
|
if user is None:
|
2016-11-03 00:42:57 +03:00
|
|
|
user = encoding.environ.get("EMAIL")
|
2008-08-06 17:10:05 +04:00
|
|
|
if user is None and self.configbool("ui", "askusername"):
|
2009-01-03 19:15:21 +03:00
|
|
|
user = self.prompt(_("enter a commit username:"), default=None)
|
2009-10-20 02:17:36 +04:00
|
|
|
if user is None and not self.interactive():
|
2006-11-28 23:16:05 +03:00
|
|
|
try:
|
|
|
|
user = '%s@%s' % (util.getuser(), socket.getfqdn())
|
2012-06-12 16:18:18 +04:00
|
|
|
self.warn(_("no username found, using '%s' instead\n") % user)
|
2006-11-28 23:16:05 +03:00
|
|
|
except KeyError:
|
2007-01-25 01:04:51 +03:00
|
|
|
pass
|
|
|
|
if not user:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_('no username supplied'),
|
2016-04-14 18:18:59 +03:00
|
|
|
hint=_("use 'hg config --edit' "
|
2014-02-28 01:14:37 +04:00
|
|
|
'to set your username'))
|
2008-03-22 21:50:59 +03:00
|
|
|
if "\n" in user:
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_("username %s contains a newline\n")
|
|
|
|
% repr(user))
|
2006-03-21 17:33:29 +03:00
|
|
|
return user
|
2005-07-04 09:51:09 +04:00
|
|
|
|
2005-08-28 19:29:28 +04:00
|
|
|
def shortuser(self, user):
|
|
|
|
"""Return a short representation of a user name or email address."""
|
2010-01-25 09:05:27 +03:00
|
|
|
if not self.verbose:
|
|
|
|
user = util.shortuser(user)
|
2005-08-28 19:29:28 +04:00
|
|
|
return user
|
|
|
|
|
2006-06-24 05:09:44 +04:00
|
|
|
def expandpath(self, loc, default=None):
|
2006-03-12 20:05:13 +03:00
|
|
|
"""Return repository location relative to cwd or from [paths]"""
|
2015-09-06 21:28:48 +03:00
|
|
|
try:
|
|
|
|
p = self.paths.getpath(loc)
|
|
|
|
if p:
|
|
|
|
return p.rawloc
|
|
|
|
except error.RepoError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
if default:
|
|
|
|
try:
|
|
|
|
p = self.paths.getpath(default)
|
|
|
|
if p:
|
|
|
|
return p.rawloc
|
|
|
|
except error.RepoError:
|
|
|
|
pass
|
|
|
|
|
2015-02-07 23:42:10 +03:00
|
|
|
return loc
|
|
|
|
|
|
|
|
@util.propertycache
|
|
|
|
def paths(self):
|
|
|
|
return paths(self)
|
2005-06-28 14:30:36 +04:00
|
|
|
|
2015-11-23 01:10:48 +03:00
|
|
|
def pushbuffer(self, error=False, subproc=False, labeled=False):
|
2014-04-18 00:47:38 +04:00
|
|
|
"""install a buffer to capture standard output of the ui object
|
2014-04-17 07:36:57 +04:00
|
|
|
|
2015-04-23 16:57:39 +03:00
|
|
|
If error is True, the error output will be captured too.
|
|
|
|
|
|
|
|
If subproc is True, output from subprocesses (typically hooks) will be
|
2015-11-23 01:10:48 +03:00
|
|
|
captured too.
|
|
|
|
|
|
|
|
If labeled is True, any labels associated with buffered
|
|
|
|
output will be handled. By default, this has no effect
|
|
|
|
on the output returned, but extensions and GUI tools may
|
|
|
|
handle this argument and returned styled output. If output
|
|
|
|
is being buffered so it can be captured and parsed or
|
|
|
|
processed, labeled should not be set to True.
|
|
|
|
"""
|
2009-04-27 01:50:44 +04:00
|
|
|
self._buffers.append([])
|
2015-11-23 01:10:48 +03:00
|
|
|
self._bufferstates.append((error, subproc, labeled))
|
|
|
|
self._bufferapplylabels = labeled
|
2006-12-01 10:28:18 +03:00
|
|
|
|
2015-11-24 22:23:10 +03:00
|
|
|
def popbuffer(self):
|
|
|
|
'''pop the last buffer and return the buffered output'''
|
2014-04-17 07:36:57 +04:00
|
|
|
self._bufferstates.pop()
|
2015-11-23 01:10:48 +03:00
|
|
|
if self._bufferstates:
|
|
|
|
self._bufferapplylabels = self._bufferstates[-1][2]
|
|
|
|
else:
|
|
|
|
self._bufferapplylabels = None
|
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
return "".join(self._buffers.pop())
|
2006-12-01 10:28:18 +03:00
|
|
|
|
2010-04-03 00:22:00 +04:00
|
|
|
def write(self, *args, **opts):
|
|
|
|
'''write args to output
|
|
|
|
|
2017-02-20 14:31:39 +03:00
|
|
|
By default, this method simply writes to the buffer or stdout.
|
|
|
|
Color mode can be set on the UI class to have the output decorated
|
|
|
|
with color modifier before being written to stdout.
|
2010-04-03 00:22:00 +04:00
|
|
|
|
2017-02-20 14:31:39 +03:00
|
|
|
The color used is controlled by an optional keyword argument, "label".
|
|
|
|
This should be a string containing label names separated by space.
|
|
|
|
Label names take the form of "topic.type". For example, ui.debug()
|
|
|
|
issues a label of "ui.debug".
|
2010-04-03 00:22:00 +04:00
|
|
|
|
|
|
|
When labeling output for a specific command, a label of
|
|
|
|
"cmdname.type" is recommended. For example, status issues
|
|
|
|
a label of "status.modified" for modified files.
|
|
|
|
'''
|
2016-03-26 00:51:00 +03:00
|
|
|
if self._buffers and not opts.get('prompt', False):
|
2017-02-20 14:31:39 +03:00
|
|
|
if self._bufferapplylabels:
|
|
|
|
label = opts.get('label', '')
|
|
|
|
self._buffers[-1].extend(self.label(a, label) for a in args)
|
|
|
|
else:
|
|
|
|
self._buffers[-1].extend(args)
|
|
|
|
elif self._colormode == 'win32':
|
|
|
|
# windows color printing is its own can of crab, defer to
|
|
|
|
# the color module and that is it.
|
2016-11-06 22:10:53 +03:00
|
|
|
color.win32print(self, self._write, *args, **opts)
|
2006-12-01 10:28:18 +03:00
|
|
|
else:
|
2017-02-20 14:31:39 +03:00
|
|
|
msgs = args
|
|
|
|
if self._colormode is not None:
|
|
|
|
label = opts.get('label', '')
|
|
|
|
msgs = [self.label(a, label) for a in args]
|
|
|
|
self._write(*msgs, **opts)
|
2017-02-24 21:27:00 +03:00
|
|
|
|
|
|
|
def _write(self, *msgs, **opts):
|
2017-02-25 08:09:55 +03:00
|
|
|
self._progclear()
|
|
|
|
# opencode timeblockedsection because this is a critical path
|
|
|
|
starttime = util.timer()
|
|
|
|
try:
|
|
|
|
for a in msgs:
|
|
|
|
self.fout.write(a)
|
2017-04-12 00:54:12 +03:00
|
|
|
except IOError as err:
|
|
|
|
raise error.StdioError(err)
|
2017-02-25 08:09:55 +03:00
|
|
|
finally:
|
|
|
|
self._blockedtimes['stdio_blocked'] += \
|
|
|
|
(util.timer() - starttime) * 1000
|
2005-07-02 02:18:02 +04:00
|
|
|
|
2010-04-03 00:22:00 +04:00
|
|
|
def write_err(self, *args, **opts):
|
2015-06-08 03:50:56 +03:00
|
|
|
self._progclear()
|
2017-02-24 21:28:45 +03:00
|
|
|
if self._bufferstates and self._bufferstates[-1][0]:
|
2017-02-20 14:42:23 +03:00
|
|
|
self.write(*args, **opts)
|
|
|
|
elif self._colormode == 'win32':
|
|
|
|
# windows color printing is its own can of crab, defer to
|
|
|
|
# the color module and that is it.
|
2016-11-06 22:10:53 +03:00
|
|
|
color.win32print(self, self._write_err, *args, **opts)
|
2017-02-20 14:42:23 +03:00
|
|
|
else:
|
|
|
|
msgs = args
|
|
|
|
if self._colormode is not None:
|
|
|
|
label = opts.get('label', '')
|
|
|
|
msgs = [self.label(a, label) for a in args]
|
|
|
|
self._write_err(*msgs, **opts)
|
2017-02-24 21:53:41 +03:00
|
|
|
|
|
|
|
def _write_err(self, *msgs, **opts):
|
2006-03-24 01:16:41 +03:00
|
|
|
try:
|
2017-02-16 00:50:06 +03:00
|
|
|
with self.timeblockedsection('stdio'):
|
|
|
|
if not getattr(self.fout, 'closed', False):
|
|
|
|
self.fout.flush()
|
2017-02-24 21:53:41 +03:00
|
|
|
for a in msgs:
|
2017-02-16 00:50:06 +03:00
|
|
|
self.ferr.write(a)
|
|
|
|
# stderr may be buffered under win32 when redirected to files,
|
|
|
|
# including stdout.
|
|
|
|
if not getattr(self.ferr, 'closed', False):
|
|
|
|
self.ferr.flush()
|
2015-06-24 08:20:08 +03:00
|
|
|
except IOError as inst:
|
2017-04-12 00:54:12 +03:00
|
|
|
raise error.StdioError(inst)
|
2005-07-02 02:18:02 +04:00
|
|
|
|
2006-03-06 19:35:15 +03:00
|
|
|
def flush(self):
|
2017-02-16 00:50:06 +03:00
|
|
|
# opencode timeblockedsection because this is a critical path
|
|
|
|
starttime = util.timer()
|
|
|
|
try:
|
2017-04-12 00:54:12 +03:00
|
|
|
try:
|
|
|
|
self.fout.flush()
|
|
|
|
except IOError as err:
|
|
|
|
raise error.StdioError(err)
|
|
|
|
finally:
|
|
|
|
try:
|
|
|
|
self.ferr.flush()
|
|
|
|
except IOError as err:
|
|
|
|
raise error.StdioError(err)
|
2017-02-16 00:50:06 +03:00
|
|
|
finally:
|
|
|
|
self._blockedtimes['stdio_blocked'] += \
|
|
|
|
(util.timer() - starttime) * 1000
|
2006-03-06 19:35:15 +03:00
|
|
|
|
2012-05-20 23:31:56 +04:00
|
|
|
def _isatty(self, fh):
|
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 self.configbool('ui', 'nontty'):
|
2012-05-20 23:31:56 +04:00
|
|
|
return False
|
|
|
|
return util.isatty(fh)
|
|
|
|
|
2017-02-20 04:12:52 +03:00
|
|
|
def disablepager(self):
|
|
|
|
self._disablepager = True
|
2017-02-16 01:48:03 +03:00
|
|
|
|
2017-02-16 01:47:51 +03:00
|
|
|
def pager(self, command):
|
|
|
|
"""Start a pager for subsequent command output.
|
|
|
|
|
|
|
|
Commands which produce a long stream of output should call
|
|
|
|
this function to activate the user's preferred pagination
|
|
|
|
mechanism (which may be no pager). Calling this function
|
|
|
|
precludes any future use of interactive functionality, such as
|
|
|
|
prompting the user or activating curses.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
command: The full, non-aliased name of the command. That is, "log"
|
|
|
|
not "history, "summary" not "summ", etc.
|
|
|
|
"""
|
2017-02-20 04:12:52 +03:00
|
|
|
if (self._disablepager
|
2017-02-16 01:48:03 +03:00
|
|
|
or self.pageractive
|
2017-02-07 07:21:45 +03:00
|
|
|
or command in self.configlist('pager', 'ignore')
|
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
|
|
|
or not self.configbool('ui', 'paginate')
|
2017-02-07 07:42:04 +03:00
|
|
|
or not self.configbool('pager', 'attend-' + command, True)
|
2017-02-16 01:47:51 +03:00
|
|
|
# TODO: if we want to allow HGPLAINEXCEPT=pager,
|
|
|
|
# formatted() will need some adjustment.
|
|
|
|
or not self.formatted()
|
|
|
|
or self.plain()
|
|
|
|
# TODO: expose debugger-enabled on the UI object
|
2017-03-12 04:51:09 +03:00
|
|
|
or '--debugger' in pycompat.sysargv):
|
2017-02-16 01:47:51 +03:00
|
|
|
# We only want to paginate if the ui appears to be
|
|
|
|
# interactive, the user didn't say HGPLAIN or
|
|
|
|
# HGPLAINEXCEPT=pager, and the user didn't specify --debug.
|
|
|
|
return
|
|
|
|
|
2017-04-28 14:51:14 +03:00
|
|
|
pagercmd = self.config('pager', 'pager', rcutil.fallbackpager)
|
2017-02-23 15:27:25 +03:00
|
|
|
if not pagercmd:
|
|
|
|
return
|
|
|
|
|
2017-04-13 18:27:19 +03:00
|
|
|
pagerenv = {}
|
|
|
|
for name, value in rcutil.defaultpagerenv().items():
|
|
|
|
if name not in encoding.environ:
|
|
|
|
pagerenv[name] = value
|
|
|
|
|
2017-02-23 15:27:25 +03:00
|
|
|
self.debug('starting pager for command %r\n' % command)
|
2017-02-25 11:29:30 +03:00
|
|
|
self.flush()
|
ui: defer setting pager related properties until the pager has spawned
When --pager=on is given, dispatch.py spawns a pager before setting up color.
If the pager failed to launch, ui.pageractive was left set to True, so color
configured itself based on 'color.pagermode'. A typical MSYS setting would be
'color.mode=auto, color.pagermode=ansi'. In the failure case, this would print
a warning, disable the pager, and then print the raw ANSI codes to the terminal.
Care needs to be taken, because it appears that leaving ui.pageractive=True was
the only thing that prevented an attempt at running the pager again from inside
the command. This results in a double warning message, so pager is simply
disabled on failure.
The ui config settings didn't need to be moved to fix this, but it seemed like
the right thing to do for consistency.
2017-03-26 04:12:00 +03:00
|
|
|
|
|
|
|
wasformatted = self.formatted()
|
2017-02-16 01:47:51 +03:00
|
|
|
if util.safehasattr(signal, "SIGPIPE"):
|
|
|
|
signal.signal(signal.SIGPIPE, _catchterm)
|
2017-04-13 18:27:19 +03:00
|
|
|
if self._runpager(pagercmd, pagerenv):
|
ui: defer setting pager related properties until the pager has spawned
When --pager=on is given, dispatch.py spawns a pager before setting up color.
If the pager failed to launch, ui.pageractive was left set to True, so color
configured itself based on 'color.pagermode'. A typical MSYS setting would be
'color.mode=auto, color.pagermode=ansi'. In the failure case, this would print
a warning, disable the pager, and then print the raw ANSI codes to the terminal.
Care needs to be taken, because it appears that leaving ui.pageractive=True was
the only thing that prevented an attempt at running the pager again from inside
the command. This results in a double warning message, so pager is simply
disabled on failure.
The ui config settings didn't need to be moved to fix this, but it seemed like
the right thing to do for consistency.
2017-03-26 04:12:00 +03:00
|
|
|
self.pageractive = True
|
|
|
|
# Preserve the formatted-ness of the UI. This is important
|
|
|
|
# because we mess with stdout, which might confuse
|
|
|
|
# auto-detection of things being formatted.
|
|
|
|
self.setconfig('ui', 'formatted', wasformatted, 'pager')
|
|
|
|
self.setconfig('ui', 'interactive', False, 'pager')
|
2017-03-26 02:17:11 +03:00
|
|
|
|
|
|
|
# If pagermode differs from color.mode, reconfigure color now that
|
|
|
|
# pageractive is set.
|
|
|
|
cm = self._colormode
|
|
|
|
if cm != self.config('color', 'pagermode', cm):
|
|
|
|
color.setup(self)
|
ui: defer setting pager related properties until the pager has spawned
When --pager=on is given, dispatch.py spawns a pager before setting up color.
If the pager failed to launch, ui.pageractive was left set to True, so color
configured itself based on 'color.pagermode'. A typical MSYS setting would be
'color.mode=auto, color.pagermode=ansi'. In the failure case, this would print
a warning, disable the pager, and then print the raw ANSI codes to the terminal.
Care needs to be taken, because it appears that leaving ui.pageractive=True was
the only thing that prevented an attempt at running the pager again from inside
the command. This results in a double warning message, so pager is simply
disabled on failure.
The ui config settings didn't need to be moved to fix this, but it seemed like
the right thing to do for consistency.
2017-03-26 04:12:00 +03:00
|
|
|
else:
|
|
|
|
# If the pager can't be spawned in dispatch when --pager=on is
|
|
|
|
# given, don't try again when the command runs, to avoid a duplicate
|
|
|
|
# warning about a missing pager command.
|
|
|
|
self.disablepager()
|
2017-02-16 01:47:51 +03:00
|
|
|
|
2017-04-13 18:27:19 +03:00
|
|
|
def _runpager(self, command, env=None):
|
2017-02-16 01:47:51 +03:00
|
|
|
"""Actually start the pager and set up file descriptors.
|
|
|
|
|
|
|
|
This is separate in part so that extensions (like chg) can
|
|
|
|
override how a pager is invoked.
|
|
|
|
"""
|
2017-03-16 03:34:26 +03:00
|
|
|
if command == 'cat':
|
|
|
|
# Save ourselves some work.
|
ui: defer setting pager related properties until the pager has spawned
When --pager=on is given, dispatch.py spawns a pager before setting up color.
If the pager failed to launch, ui.pageractive was left set to True, so color
configured itself based on 'color.pagermode'. A typical MSYS setting would be
'color.mode=auto, color.pagermode=ansi'. In the failure case, this would print
a warning, disable the pager, and then print the raw ANSI codes to the terminal.
Care needs to be taken, because it appears that leaving ui.pageractive=True was
the only thing that prevented an attempt at running the pager again from inside
the command. This results in a double warning message, so pager is simply
disabled on failure.
The ui config settings didn't need to be moved to fix this, but it seemed like
the right thing to do for consistency.
2017-03-26 04:12:00 +03:00
|
|
|
return False
|
2017-03-16 03:33:47 +03:00
|
|
|
# If the command doesn't contain any of these characters, we
|
|
|
|
# assume it's a binary and exec it directly. This means for
|
|
|
|
# simple pager command configurations, we can degrade
|
|
|
|
# gracefully and tell the user about their broken pager.
|
|
|
|
shell = any(c in command for c in "|&;<>()$`\\\"' \t\n*?[#~=%")
|
2017-03-25 05:40:08 +03:00
|
|
|
|
|
|
|
if pycompat.osname == 'nt' and not shell:
|
|
|
|
# Window's built-in `more` cannot be invoked with shell=False, but
|
|
|
|
# its `more.com` can. Hide this implementation detail from the
|
|
|
|
# user so we can also get sane bad PAGER behavior. MSYS has
|
|
|
|
# `more.exe`, so do a cmd.exe style resolution of the executable to
|
|
|
|
# determine which one to use.
|
|
|
|
fullcmd = util.findexe(command)
|
|
|
|
if not fullcmd:
|
|
|
|
self.warn(_("missing pager command '%s', skipping pager\n")
|
|
|
|
% command)
|
ui: defer setting pager related properties until the pager has spawned
When --pager=on is given, dispatch.py spawns a pager before setting up color.
If the pager failed to launch, ui.pageractive was left set to True, so color
configured itself based on 'color.pagermode'. A typical MSYS setting would be
'color.mode=auto, color.pagermode=ansi'. In the failure case, this would print
a warning, disable the pager, and then print the raw ANSI codes to the terminal.
Care needs to be taken, because it appears that leaving ui.pageractive=True was
the only thing that prevented an attempt at running the pager again from inside
the command. This results in a double warning message, so pager is simply
disabled on failure.
The ui config settings didn't need to be moved to fix this, but it seemed like
the right thing to do for consistency.
2017-03-26 04:12:00 +03:00
|
|
|
return False
|
2017-03-25 05:40:08 +03:00
|
|
|
|
|
|
|
command = fullcmd
|
|
|
|
|
2017-03-16 03:33:47 +03:00
|
|
|
try:
|
|
|
|
pager = subprocess.Popen(
|
|
|
|
command, shell=shell, bufsize=-1,
|
|
|
|
close_fds=util.closefds, stdin=subprocess.PIPE,
|
2017-04-13 18:27:19 +03:00
|
|
|
stdout=util.stdout, stderr=util.stderr,
|
|
|
|
env=util.shellenviron(env))
|
2017-03-16 03:33:47 +03:00
|
|
|
except OSError as e:
|
|
|
|
if e.errno == errno.ENOENT and not shell:
|
|
|
|
self.warn(_("missing pager command '%s', skipping pager\n")
|
|
|
|
% command)
|
ui: defer setting pager related properties until the pager has spawned
When --pager=on is given, dispatch.py spawns a pager before setting up color.
If the pager failed to launch, ui.pageractive was left set to True, so color
configured itself based on 'color.pagermode'. A typical MSYS setting would be
'color.mode=auto, color.pagermode=ansi'. In the failure case, this would print
a warning, disable the pager, and then print the raw ANSI codes to the terminal.
Care needs to be taken, because it appears that leaving ui.pageractive=True was
the only thing that prevented an attempt at running the pager again from inside
the command. This results in a double warning message, so pager is simply
disabled on failure.
The ui config settings didn't need to be moved to fix this, but it seemed like
the right thing to do for consistency.
2017-03-26 04:12:00 +03:00
|
|
|
return False
|
2017-03-16 03:33:47 +03:00
|
|
|
raise
|
2017-02-16 01:47:51 +03:00
|
|
|
|
|
|
|
# back up original file descriptors
|
|
|
|
stdoutfd = os.dup(util.stdout.fileno())
|
|
|
|
stderrfd = os.dup(util.stderr.fileno())
|
|
|
|
|
|
|
|
os.dup2(pager.stdin.fileno(), util.stdout.fileno())
|
|
|
|
if self._isatty(util.stderr):
|
|
|
|
os.dup2(pager.stdin.fileno(), util.stderr.fileno())
|
|
|
|
|
2017-04-12 00:54:12 +03:00
|
|
|
@self.atexit
|
2017-02-16 01:47:51 +03:00
|
|
|
def killpager():
|
|
|
|
if util.safehasattr(signal, "SIGINT"):
|
|
|
|
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
|
|
|
# restore original fds, closing pager.stdin copies in the process
|
|
|
|
os.dup2(stdoutfd, util.stdout.fileno())
|
|
|
|
os.dup2(stderrfd, util.stderr.fileno())
|
|
|
|
pager.stdin.close()
|
|
|
|
pager.wait()
|
|
|
|
|
ui: defer setting pager related properties until the pager has spawned
When --pager=on is given, dispatch.py spawns a pager before setting up color.
If the pager failed to launch, ui.pageractive was left set to True, so color
configured itself based on 'color.pagermode'. A typical MSYS setting would be
'color.mode=auto, color.pagermode=ansi'. In the failure case, this would print
a warning, disable the pager, and then print the raw ANSI codes to the terminal.
Care needs to be taken, because it appears that leaving ui.pageractive=True was
the only thing that prevented an attempt at running the pager again from inside
the command. This results in a double warning message, so pager is simply
disabled on failure.
The ui config settings didn't need to be moved to fix this, but it seemed like
the right thing to do for consistency.
2017-03-26 04:12:00 +03:00
|
|
|
return True
|
|
|
|
|
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 atexit(self, func, *args, **kwargs):
|
|
|
|
'''register a function to run after dispatching a request
|
|
|
|
|
|
|
|
Handlers do not stay registered across request boundaries.'''
|
|
|
|
self._exithandlers.append((func, args, kwargs))
|
|
|
|
return func
|
|
|
|
|
2016-03-14 18:01:27 +03:00
|
|
|
def interface(self, feature):
|
|
|
|
"""what interface to use for interactive console features?
|
|
|
|
|
|
|
|
The interface is controlled by the value of `ui.interface` but also by
|
|
|
|
the value of feature-specific configuration. For example:
|
|
|
|
|
|
|
|
ui.interface.histedit = text
|
|
|
|
ui.interface.chunkselector = curses
|
|
|
|
|
|
|
|
Here the features are "histedit" and "chunkselector".
|
|
|
|
|
|
|
|
The configuration above means that the default interfaces for commands
|
|
|
|
is curses, the interface for histedit is text and the interface for
|
|
|
|
selecting chunk is crecord (the best curses interface available).
|
|
|
|
|
2016-10-18 00:16:55 +03:00
|
|
|
Consider the following example:
|
2016-03-14 18:01:27 +03:00
|
|
|
ui.interface = curses
|
|
|
|
ui.interface.histedit = text
|
|
|
|
|
|
|
|
Then histedit will use the text interface and chunkselector will use
|
|
|
|
the default curses interface (crecord at the moment).
|
|
|
|
"""
|
|
|
|
alldefaults = frozenset(["text", "curses"])
|
|
|
|
|
|
|
|
featureinterfaces = {
|
|
|
|
"chunkselector": [
|
|
|
|
"text",
|
|
|
|
"curses",
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
# Feature-specific interface
|
|
|
|
if feature not in featureinterfaces.keys():
|
|
|
|
# Programming error, not user error
|
|
|
|
raise ValueError("Unknown feature requested %s" % feature)
|
|
|
|
|
|
|
|
availableinterfaces = frozenset(featureinterfaces[feature])
|
|
|
|
if alldefaults > availableinterfaces:
|
|
|
|
# Programming error, not user error. We need a use case to
|
|
|
|
# define the right thing to do here.
|
|
|
|
raise ValueError(
|
|
|
|
"Feature %s does not handle all default interfaces" %
|
|
|
|
feature)
|
|
|
|
|
|
|
|
if self.plain():
|
|
|
|
return "text"
|
|
|
|
|
|
|
|
# Default interface for all the features
|
|
|
|
defaultinterface = "text"
|
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
|
|
|
i = self.config("ui", "interface")
|
2016-03-14 18:01:27 +03:00
|
|
|
if i in alldefaults:
|
|
|
|
defaultinterface = i
|
|
|
|
|
|
|
|
choseninterface = defaultinterface
|
|
|
|
f = self.config("ui", "interface.%s" % feature, None)
|
|
|
|
if f in availableinterfaces:
|
|
|
|
choseninterface = f
|
|
|
|
|
|
|
|
if i is not None and defaultinterface != i:
|
|
|
|
if f is not None:
|
|
|
|
self.warn(_("invalid value for ui.interface: %s\n") %
|
|
|
|
(i,))
|
|
|
|
else:
|
|
|
|
self.warn(_("invalid value for ui.interface: %s (using %s)\n") %
|
|
|
|
(i, choseninterface))
|
|
|
|
if f is not None and choseninterface != f:
|
|
|
|
self.warn(_("invalid value for ui.interface.%s: %s (using %s)\n") %
|
|
|
|
(feature, f, choseninterface))
|
|
|
|
|
|
|
|
return choseninterface
|
|
|
|
|
2009-04-27 01:50:44 +04:00
|
|
|
def interactive(self):
|
2010-06-07 18:14:12 +04:00
|
|
|
'''is interactive input allowed?
|
|
|
|
|
|
|
|
An interactive session is a session where input can be reasonably read
|
|
|
|
from `sys.stdin'. If this function returns false, any attempt to read
|
|
|
|
from stdin should fail with an error, unless a sensible default has been
|
|
|
|
specified.
|
|
|
|
|
|
|
|
Interactiveness is triggered by the value of the `ui.interactive'
|
|
|
|
configuration variable or - if it is unset - when `sys.stdin' points
|
|
|
|
to a terminal device.
|
|
|
|
|
|
|
|
This function refers to input only; for output, see `ui.formatted()'.
|
|
|
|
'''
|
2017-06-23 18:19:29 +03:00
|
|
|
i = self.configbool("ui", "interactive")
|
2009-05-21 22:59:36 +04:00
|
|
|
if i is None:
|
2011-06-02 01:43:34 +04:00
|
|
|
# some environments replace stdin without implementing isatty
|
|
|
|
# usually those are non-interactive
|
2012-05-20 23:31:56 +04:00
|
|
|
return self._isatty(self.fin)
|
2009-12-13 20:29:16 +03:00
|
|
|
|
2009-05-21 22:59:36 +04:00
|
|
|
return i
|
2009-04-27 01:50:44 +04:00
|
|
|
|
2010-10-10 19:06:36 +04:00
|
|
|
def termwidth(self):
|
|
|
|
'''how wide is the terminal in columns?
|
|
|
|
'''
|
2016-11-03 00:42:57 +03:00
|
|
|
if 'COLUMNS' in encoding.environ:
|
2010-10-10 19:06:36 +04:00
|
|
|
try:
|
2016-11-03 00:42:57 +03:00
|
|
|
return int(encoding.environ['COLUMNS'])
|
2010-10-10 19:06:36 +04:00
|
|
|
except ValueError:
|
|
|
|
pass
|
2016-10-20 17:09:05 +03:00
|
|
|
return scmutil.termsize(self)[0]
|
2010-10-10 19:06:36 +04:00
|
|
|
|
2010-06-07 16:59:52 +04:00
|
|
|
def formatted(self):
|
2010-06-07 18:14:12 +04:00
|
|
|
'''should formatted output be used?
|
|
|
|
|
|
|
|
It is often desirable to format the output to suite the output medium.
|
|
|
|
Examples of this are truncating long lines or colorizing messages.
|
|
|
|
However, this is not often not desirable when piping output into other
|
|
|
|
utilities, e.g. `grep'.
|
|
|
|
|
|
|
|
Formatted output is triggered by the value of the `ui.formatted'
|
|
|
|
configuration variable or - if it is unset - when `sys.stdout' points
|
|
|
|
to a terminal device. Please note that `ui.formatted' should be
|
|
|
|
considered an implementation detail; it is not intended for use outside
|
|
|
|
Mercurial or its extensions.
|
|
|
|
|
|
|
|
This function refers to output only; for input, see `ui.interactive()'.
|
|
|
|
This function always returns false when in plain mode, see `ui.plain()'.
|
|
|
|
'''
|
2010-06-07 16:59:52 +04:00
|
|
|
if self.plain():
|
|
|
|
return False
|
|
|
|
|
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
|
|
|
i = self.configbool("ui", "formatted")
|
2010-06-07 16:59:52 +04:00
|
|
|
if i is None:
|
2011-06-02 01:43:34 +04:00
|
|
|
# some environments replace stdout without implementing isatty
|
|
|
|
# usually those are non-interactive
|
2012-05-20 23:31:56 +04:00
|
|
|
return self._isatty(self.fout)
|
2010-06-07 16:59:52 +04:00
|
|
|
|
|
|
|
return i
|
|
|
|
|
2007-09-25 21:05:34 +04:00
|
|
|
def _readline(self, prompt=''):
|
2012-05-20 23:31:56 +04:00
|
|
|
if self._isatty(self.fin):
|
2007-08-01 03:28:05 +04:00
|
|
|
try:
|
|
|
|
# magically add command line editing support, where
|
|
|
|
# available
|
|
|
|
import readline
|
|
|
|
# force demandimport to really load the module
|
|
|
|
readline.read_history_file
|
2008-12-10 04:01:14 +03:00
|
|
|
# windows sometimes raises something other than ImportError
|
|
|
|
except Exception:
|
2007-08-01 03:28:05 +04:00
|
|
|
pass
|
2011-06-08 02:39:20 +04:00
|
|
|
|
2011-08-01 20:53:00 +04:00
|
|
|
# call write() so output goes through subclassed implementation
|
|
|
|
# e.g. color extension on Windows
|
2016-03-26 00:51:00 +03:00
|
|
|
self.write(prompt, prompt=True)
|
2011-08-01 20:53:00 +04:00
|
|
|
|
2011-08-30 16:18:58 +04:00
|
|
|
# instead of trying to emulate raw_input, swap (self.fin,
|
|
|
|
# self.fout) with (sys.stdin, sys.stdout)
|
|
|
|
oldin = sys.stdin
|
|
|
|
oldout = sys.stdout
|
2011-08-01 20:53:00 +04:00
|
|
|
sys.stdin = self.fin
|
2011-08-30 16:18:58 +04:00
|
|
|
sys.stdout = self.fout
|
2014-08-24 07:35:53 +04:00
|
|
|
# prompt ' ' must exist; otherwise readline may delete entire line
|
|
|
|
# - http://bugs.python.org/issue12833
|
2017-02-16 00:50:06 +03:00
|
|
|
with self.timeblockedsection('stdio'):
|
|
|
|
line = raw_input(' ')
|
2011-08-30 16:18:58 +04:00
|
|
|
sys.stdin = oldin
|
|
|
|
sys.stdout = oldout
|
2011-06-08 02:39:20 +04:00
|
|
|
|
2007-12-04 02:28:26 +03:00
|
|
|
# When stdin is in binary mode on Windows, it can cause
|
|
|
|
# raw_input() to emit an extra trailing carriage return
|
2017-03-29 15:23:28 +03:00
|
|
|
if pycompat.oslinesep == '\r\n' and line and line[-1] == '\r':
|
2007-12-04 02:28:26 +03:00
|
|
|
line = line[:-1]
|
|
|
|
return line
|
2007-08-01 03:28:05 +04:00
|
|
|
|
2009-06-21 03:13:19 +04:00
|
|
|
def prompt(self, msg, default="y"):
|
|
|
|
"""Prompt user with msg, read response.
|
|
|
|
If ui is not interactive, the default is returned.
|
2007-12-28 09:03:55 +03:00
|
|
|
"""
|
2009-04-27 01:50:44 +04:00
|
|
|
if not self.interactive():
|
2016-02-06 14:43:20 +03:00
|
|
|
self.write(msg, ' ', default or '', "\n")
|
2008-11-07 12:27:39 +03:00
|
|
|
return default
|
2009-06-21 03:13:19 +04:00
|
|
|
try:
|
2011-08-25 23:06:03 +04:00
|
|
|
r = self._readline(self.label(msg, 'ui.prompt'))
|
2009-06-21 03:13:19 +04:00
|
|
|
if not r:
|
2014-10-01 03:04:18 +04:00
|
|
|
r = default
|
2014-10-21 18:16:46 +04:00
|
|
|
if self.configbool('ui', 'promptecho'):
|
2014-10-01 03:04:18 +04:00
|
|
|
self.write(r, "\n")
|
2009-06-21 03:13:19 +04:00
|
|
|
return r
|
|
|
|
except EOFError:
|
2015-11-10 11:46:45 +03:00
|
|
|
raise error.ResponseExpected()
|
2009-06-21 03:13:19 +04:00
|
|
|
|
2013-12-01 19:50:29 +04:00
|
|
|
@staticmethod
|
|
|
|
def extractchoices(prompt):
|
|
|
|
"""Extract prompt message and list of choices from specified prompt.
|
|
|
|
|
|
|
|
This returns tuple "(message, choices)", and "choices" is the
|
|
|
|
list of tuple "(response character, text without &)".
|
2015-11-30 22:47:29 +03:00
|
|
|
|
|
|
|
>>> ui.extractchoices("awake? $$ &Yes $$ &No")
|
|
|
|
('awake? ', [('y', 'Yes'), ('n', 'No')])
|
|
|
|
>>> ui.extractchoices("line\\nbreak? $$ &Yes $$ &No")
|
|
|
|
('line\\nbreak? ', [('y', 'Yes'), ('n', 'No')])
|
|
|
|
>>> ui.extractchoices("want lots of $$money$$?$$Ye&s$$N&o")
|
|
|
|
('want lots of $$money$$?', [('s', 'Yes'), ('o', 'No')])
|
2013-12-01 19:50:29 +04:00
|
|
|
"""
|
2015-11-30 22:47:29 +03:00
|
|
|
|
|
|
|
# Sadly, the prompt string may have been built with a filename
|
|
|
|
# containing "$$" so let's try to find the first valid-looking
|
|
|
|
# prompt to start parsing. Sadly, we also can't rely on
|
|
|
|
# choices containing spaces, ASCII, or basically anything
|
|
|
|
# except an ampersand followed by a character.
|
2017-06-25 00:41:55 +03:00
|
|
|
m = re.match(br'(?s)(.+?)\$\$([^\$]*&[^ \$].*)', prompt)
|
2015-11-30 22:47:29 +03:00
|
|
|
msg = m.group(1)
|
|
|
|
choices = [p.strip(' ') for p in m.group(2).split('$$')]
|
2013-12-01 19:50:29 +04:00
|
|
|
return (msg,
|
|
|
|
[(s[s.index('&') + 1].lower(), s.replace('&', '', 1))
|
|
|
|
for s in choices])
|
|
|
|
|
2013-05-23 02:31:43 +04:00
|
|
|
def promptchoice(self, prompt, default=0):
|
|
|
|
"""Prompt user with a message, read response, and ensure it matches
|
|
|
|
one of the provided choices. The prompt is formatted as follows:
|
|
|
|
|
|
|
|
"would you like fries with that (Yn)? $$ &Yes $$ &No"
|
|
|
|
|
|
|
|
The index of the choice is returned. Responses are case
|
|
|
|
insensitive. If ui is not interactive, the default is
|
|
|
|
returned.
|
2009-06-21 03:13:19 +04:00
|
|
|
"""
|
2013-05-23 02:31:43 +04:00
|
|
|
|
2013-12-01 19:50:29 +04:00
|
|
|
msg, choices = self.extractchoices(prompt)
|
|
|
|
resps = [r for r, t in choices]
|
2007-12-27 12:32:33 +03:00
|
|
|
while True:
|
2009-06-21 03:13:19 +04:00
|
|
|
r = self.prompt(msg, resps[default])
|
|
|
|
if r.lower() in resps:
|
|
|
|
return resps.index(r.lower())
|
|
|
|
self.write(_("unrecognized response\n"))
|
|
|
|
|
2006-05-15 04:37:17 +04:00
|
|
|
def getpass(self, prompt=None, default=None):
|
2010-01-25 09:05:27 +03:00
|
|
|
if not self.interactive():
|
|
|
|
return default
|
2009-02-22 02:46:06 +03:00
|
|
|
try:
|
2013-10-09 22:27:59 +04:00
|
|
|
self.write_err(self.label(prompt or _('password: '), 'ui.prompt'))
|
2014-04-26 13:13:06 +04:00
|
|
|
# disable getpass() only if explicitly specified. it's still valid
|
|
|
|
# to interact with tty even if fin is not a tty.
|
2017-02-16 00:50:06 +03:00
|
|
|
with self.timeblockedsection('stdio'):
|
|
|
|
if self.configbool('ui', 'nontty'):
|
|
|
|
l = self.fin.readline()
|
|
|
|
if not l:
|
|
|
|
raise EOFError
|
|
|
|
return l.rstrip('\n')
|
|
|
|
else:
|
|
|
|
return getpass.getpass('')
|
2009-02-22 02:46:06 +03:00
|
|
|
except EOFError:
|
2015-11-10 11:46:45 +03:00
|
|
|
raise error.ResponseExpected()
|
2010-04-03 00:22:00 +04:00
|
|
|
def status(self, *msg, **opts):
|
|
|
|
'''write status message to output (if ui.quiet is False)
|
|
|
|
|
|
|
|
This adds an output label of "ui.status".
|
|
|
|
'''
|
2010-01-25 09:05:27 +03:00
|
|
|
if not self.quiet:
|
2017-03-03 22:08:24 +03:00
|
|
|
opts[r'label'] = opts.get(r'label', '') + ' ui.status'
|
2010-04-03 00:22:00 +04:00
|
|
|
self.write(*msg, **opts)
|
|
|
|
def warn(self, *msg, **opts):
|
|
|
|
'''write warning message to output (stderr)
|
|
|
|
|
|
|
|
This adds an output label of "ui.warning".
|
|
|
|
'''
|
2017-03-03 22:08:24 +03:00
|
|
|
opts[r'label'] = opts.get(r'label', '') + ' ui.warning'
|
2010-04-03 00:22:00 +04:00
|
|
|
self.write_err(*msg, **opts)
|
|
|
|
def note(self, *msg, **opts):
|
|
|
|
'''write note to output (if ui.verbose is True)
|
|
|
|
|
|
|
|
This adds an output label of "ui.note".
|
|
|
|
'''
|
2010-01-25 09:05:27 +03:00
|
|
|
if self.verbose:
|
2017-03-03 22:08:24 +03:00
|
|
|
opts[r'label'] = opts.get(r'label', '') + ' ui.note'
|
2010-04-03 00:22:00 +04:00
|
|
|
self.write(*msg, **opts)
|
|
|
|
def debug(self, *msg, **opts):
|
|
|
|
'''write debug message to output (if ui.debugflag is True)
|
|
|
|
|
|
|
|
This adds an output label of "ui.debug".
|
|
|
|
'''
|
2010-01-25 09:05:27 +03:00
|
|
|
if self.debugflag:
|
2017-03-03 22:08:24 +03:00
|
|
|
opts[r'label'] = opts.get(r'label', '') + ' ui.debug'
|
2010-04-03 00:22:00 +04:00
|
|
|
self.write(*msg, **opts)
|
cmdutil: make in-memory changes visible to external editor (issue4378)
Before this patch, external editor process for the commit log can't
view some in-memory changes (especially, of dirstate), because they
aren't written out until the end of transaction (or wlock).
This causes unexpected output of Mercurial commands spawned from that
editor process.
To make in-memory changes visible to external editor process, this
patch does:
- write (or schedule to write) in-memory dirstate changes, and
- set HG_PENDING environment variable, if:
- a transaction is running, and
- there are in-memory changes to be visible
"hg diff" spawned from external editor process for "hg qrefresh"
shows:
- "changes newly imported into the topmost" before ab68b153ce34(*)
- "all changes recorded in the topmost by refreshing" after this patch
(*) ab68b153ce34 changed steps invoking editor process
Even though backward compatibility may be broken, the latter behavior
looks reasonable, because "hg diff" spawned from the editor process
consistently shows "what changes new revision records" regardless of
invocation context.
In fact, issue4378 itself should be resolved by b46029eb5b29, which
made 'repo.transaction()' write in-memory dirstate changes out
explicitly before starting transaction. It also made "hg qrefresh"
imply 'dirstate.write()' before external editor invocation in call
chain below.
- mq.queue.refresh
- strip.strip
- repair.strip
- localrepository.transaction
- dirstate.write
- localrepository.commit
- invoke external editor
Though, this patch has '(issue4378)' in own summary line to indicate
that issues like issue4378 should be fixed by this.
BTW, this patch adds '-m' option to a 'hg ci --amend' execution in
'test-commit-amend.t', to avoid invoking external editor process.
In this case, "unsure" states may be changed to "clean" according to
timestamp or so on. These changes should be written into pending file,
if external editor invocation is required,
Then, writing dirstate changes out breaks stability of test, because
it shows "transaction abort!/rollback completed" occasionally.
Aborting after editor process invocation while commands below may
cause similar instability of tests, too (AFAIK, there is no more such
one, at this revision)
- commit --amend
- without --message/--logfile
- import
- without --message/--logfile,
- without --no-commit,
- without --bypass,
- one of below, and
- patch has no description text, or
- with --edit
- aborting at the 1st patch, which adds or removes file(s)
- if it only changes existing files, status is checked only for
changed files by 'scmutil.matchfiles()', and transition from
"unsure" to "normal" in dirstate doesn't occur (= dirstate
isn't changed, and written out)
- aborting at the 2nd or later patch implies other pending
changes (e.g. changelog), and always causes showing
"transaction abort!/rollback completed"
2015-10-16 19:15:34 +03:00
|
|
|
|
2017-01-17 08:05:22 +03:00
|
|
|
def edit(self, text, user, extra=None, editform=None, pending=None,
|
2017-01-19 05:25:51 +03:00
|
|
|
repopath=None):
|
2016-03-20 20:55:41 +03:00
|
|
|
extra_defaults = {
|
|
|
|
'prefix': 'editor',
|
|
|
|
'suffix': '.txt',
|
|
|
|
}
|
2015-11-21 23:04:09 +03:00
|
|
|
if extra is not None:
|
|
|
|
extra_defaults.update(extra)
|
|
|
|
extra = extra_defaults
|
2017-01-17 08:05:22 +03:00
|
|
|
|
2017-01-19 05:25:51 +03:00
|
|
|
rdir = None
|
2017-01-17 08:05:22 +03:00
|
|
|
if self.configbool('experimental', 'editortmpinhg'):
|
2017-01-19 05:25:51 +03:00
|
|
|
rdir = repopath
|
2015-11-21 23:04:09 +03:00
|
|
|
(fd, name) = tempfile.mkstemp(prefix='hg-' + extra['prefix'] + '-',
|
2017-03-29 15:43:38 +03:00
|
|
|
suffix=extra['suffix'],
|
2017-01-19 05:25:51 +03:00
|
|
|
dir=rdir)
|
2006-03-21 14:54:32 +03:00
|
|
|
try:
|
2017-03-29 15:43:38 +03:00
|
|
|
f = os.fdopen(fd, r'wb')
|
|
|
|
f.write(util.tonativeeol(text))
|
2006-03-21 14:54:32 +03:00
|
|
|
f.close()
|
|
|
|
|
2014-02-06 12:21:20 +04:00
|
|
|
environ = {'HGUSER': user}
|
2014-02-10 07:13:10 +04:00
|
|
|
if 'transplant_source' in extra:
|
|
|
|
environ.update({'HGREVISION': hex(extra['transplant_source'])})
|
2015-04-10 08:05:50 +03:00
|
|
|
for label in ('intermediate-source', 'source', 'rebase_source'):
|
2014-02-06 12:21:20 +04:00
|
|
|
if label in extra:
|
|
|
|
environ.update({'HGREVISION': extra[label]})
|
|
|
|
break
|
2014-08-15 18:05:53 +04:00
|
|
|
if editform:
|
|
|
|
environ.update({'HGEDITFORM': editform})
|
cmdutil: make in-memory changes visible to external editor (issue4378)
Before this patch, external editor process for the commit log can't
view some in-memory changes (especially, of dirstate), because they
aren't written out until the end of transaction (or wlock).
This causes unexpected output of Mercurial commands spawned from that
editor process.
To make in-memory changes visible to external editor process, this
patch does:
- write (or schedule to write) in-memory dirstate changes, and
- set HG_PENDING environment variable, if:
- a transaction is running, and
- there are in-memory changes to be visible
"hg diff" spawned from external editor process for "hg qrefresh"
shows:
- "changes newly imported into the topmost" before ab68b153ce34(*)
- "all changes recorded in the topmost by refreshing" after this patch
(*) ab68b153ce34 changed steps invoking editor process
Even though backward compatibility may be broken, the latter behavior
looks reasonable, because "hg diff" spawned from the editor process
consistently shows "what changes new revision records" regardless of
invocation context.
In fact, issue4378 itself should be resolved by b46029eb5b29, which
made 'repo.transaction()' write in-memory dirstate changes out
explicitly before starting transaction. It also made "hg qrefresh"
imply 'dirstate.write()' before external editor invocation in call
chain below.
- mq.queue.refresh
- strip.strip
- repair.strip
- localrepository.transaction
- dirstate.write
- localrepository.commit
- invoke external editor
Though, this patch has '(issue4378)' in own summary line to indicate
that issues like issue4378 should be fixed by this.
BTW, this patch adds '-m' option to a 'hg ci --amend' execution in
'test-commit-amend.t', to avoid invoking external editor process.
In this case, "unsure" states may be changed to "clean" according to
timestamp or so on. These changes should be written into pending file,
if external editor invocation is required,
Then, writing dirstate changes out breaks stability of test, because
it shows "transaction abort!/rollback completed" occasionally.
Aborting after editor process invocation while commands below may
cause similar instability of tests, too (AFAIK, there is no more such
one, at this revision)
- commit --amend
- without --message/--logfile
- import
- without --message/--logfile,
- without --no-commit,
- without --bypass,
- one of below, and
- patch has no description text, or
- with --edit
- aborting at the 1st patch, which adds or removes file(s)
- if it only changes existing files, status is checked only for
changed files by 'scmutil.matchfiles()', and transition from
"unsure" to "normal" in dirstate doesn't occur (= dirstate
isn't changed, and written out)
- aborting at the 2nd or later patch implies other pending
changes (e.g. changelog), and always causes showing
"transaction abort!/rollback completed"
2015-10-16 19:15:34 +03:00
|
|
|
if pending:
|
|
|
|
environ.update({'HG_PENDING': pending})
|
2014-02-06 12:21:20 +04:00
|
|
|
|
2007-12-05 14:40:01 +03:00
|
|
|
editor = self.geteditor()
|
2006-03-21 14:54:32 +03:00
|
|
|
|
2014-11-08 06:57:42 +03:00
|
|
|
self.system("%s \"%s\"" % (editor, name),
|
2014-02-06 12:21:20 +04:00
|
|
|
environ=environ,
|
2017-02-16 00:38:00 +03:00
|
|
|
onerr=error.Abort, errprefix=_("edit failed"),
|
|
|
|
blockedtag='editor')
|
2006-03-21 14:54:32 +03:00
|
|
|
|
2017-03-29 15:43:38 +03:00
|
|
|
f = open(name, r'rb')
|
|
|
|
t = util.fromnativeeol(f.read())
|
2006-03-21 14:54:32 +03:00
|
|
|
f.close()
|
|
|
|
finally:
|
|
|
|
os.unlink(name)
|
2005-07-11 04:00:17 +04:00
|
|
|
|
2005-06-01 10:57:53 +04:00
|
|
|
return t
|
2006-05-04 23:23:01 +04:00
|
|
|
|
2017-02-16 00:29:12 +03:00
|
|
|
def system(self, cmd, environ=None, cwd=None, onerr=None, errprefix=None,
|
|
|
|
blockedtag=None):
|
2014-11-08 06:57:42 +03:00
|
|
|
'''execute shell command with appropriate output stream. command
|
|
|
|
output will be redirected if fout is not stdout.
|
2017-02-18 19:16:45 +03:00
|
|
|
|
|
|
|
if command fails and onerr is None, return status, else raise onerr
|
|
|
|
object as exception.
|
2014-11-08 06:57:42 +03:00
|
|
|
'''
|
2017-02-16 00:29:12 +03:00
|
|
|
if blockedtag is None:
|
2017-03-20 15:08:21 +03:00
|
|
|
# Long cmds tend to be because of an absolute path on cmd. Keep
|
|
|
|
# the tail end instead
|
|
|
|
cmdsuffix = cmd.translate(None, _keepalnum)[-85:]
|
|
|
|
blockedtag = 'unknown_system_' + cmdsuffix
|
2015-04-23 16:57:39 +03:00
|
|
|
out = self.fout
|
2015-05-16 21:30:07 +03:00
|
|
|
if any(s[1] for s in self._bufferstates):
|
2015-04-23 16:57:39 +03:00
|
|
|
out = self
|
2017-02-16 00:29:12 +03:00
|
|
|
with self.timeblockedsection(blockedtag):
|
2017-02-18 19:16:45 +03:00
|
|
|
rc = self._runsystem(cmd, environ=environ, cwd=cwd, out=out)
|
|
|
|
if rc and onerr:
|
|
|
|
errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
|
|
|
|
util.explainexit(rc)[0])
|
|
|
|
if errprefix:
|
|
|
|
errmsg = '%s: %s' % (errprefix, errmsg)
|
|
|
|
raise onerr(errmsg)
|
|
|
|
return rc
|
|
|
|
|
|
|
|
def _runsystem(self, cmd, environ, cwd, out):
|
2017-02-18 19:00:10 +03:00
|
|
|
"""actually execute the given shell command (can be overridden by
|
|
|
|
extensions like chg)"""
|
2017-02-18 19:16:45 +03:00
|
|
|
return util.system(cmd, environ=environ, cwd=cwd, out=out)
|
2014-11-08 06:57:42 +03:00
|
|
|
|
2013-02-09 23:22:52 +04:00
|
|
|
def traceback(self, exc=None, force=False):
|
|
|
|
'''print exception traceback if traceback printing enabled or forced.
|
2006-05-22 19:47:53 +04:00
|
|
|
only to call in exception handler. returns true if traceback
|
|
|
|
printed.'''
|
2013-02-09 23:22:52 +04:00
|
|
|
if self.tracebackflag or force:
|
2013-02-09 23:15:34 +04:00
|
|
|
if exc is None:
|
|
|
|
exc = sys.exc_info()
|
|
|
|
cause = getattr(exc[1], 'cause', None)
|
|
|
|
|
|
|
|
if cause is not None:
|
|
|
|
causetb = traceback.format_tb(cause[2])
|
|
|
|
exctb = traceback.format_tb(exc[2])
|
|
|
|
exconly = traceback.format_exception_only(cause[0], cause[1])
|
|
|
|
|
|
|
|
# exclude frame where 'exc' was chained and rethrown from exctb
|
|
|
|
self.write_err('Traceback (most recent call last):\n',
|
|
|
|
''.join(exctb[:-1]),
|
|
|
|
''.join(causetb),
|
|
|
|
''.join(exconly))
|
|
|
|
else:
|
2015-06-13 05:09:41 +03:00
|
|
|
output = traceback.format_exception(exc[0], exc[1], exc[2])
|
2017-03-03 22:09:14 +03:00
|
|
|
data = r''.join(output)
|
|
|
|
if pycompat.ispy3:
|
|
|
|
enc = pycompat.sysstr(encoding.encoding)
|
|
|
|
data = data.encode(enc, errors=r'replace')
|
|
|
|
self.write_err(data)
|
2013-02-09 23:22:52 +04:00
|
|
|
return self.tracebackflag or force
|
2007-12-05 14:40:01 +03:00
|
|
|
|
|
|
|
def geteditor(self):
|
|
|
|
'''return editor to use'''
|
2016-12-18 23:45:24 +03:00
|
|
|
if pycompat.sysplatform == 'plan9':
|
2012-04-08 23:43:41 +04:00
|
|
|
# vi is the MIPS instruction simulator on Plan 9. We
|
|
|
|
# instead default to E to plumb commit messages to
|
|
|
|
# avoid confusion.
|
|
|
|
editor = 'E'
|
|
|
|
else:
|
|
|
|
editor = 'vi'
|
2016-11-03 00:42:57 +03:00
|
|
|
return (encoding.environ.get("HGEDITOR") or
|
2017-03-27 07:41:42 +03:00
|
|
|
self.config("ui", "editor", editor))
|
2009-07-16 23:49:52 +04:00
|
|
|
|
2015-06-08 03:50:56 +03:00
|
|
|
@util.propertycache
|
|
|
|
def _progbar(self):
|
|
|
|
"""setup the progbar singleton to the ui object"""
|
|
|
|
if (self.quiet or self.debugflag
|
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
|
|
|
or self.configbool('progress', 'disable')
|
2015-06-08 03:50:56 +03:00
|
|
|
or not progress.shouldprint(self)):
|
|
|
|
return None
|
|
|
|
return getprogbar(self)
|
|
|
|
|
|
|
|
def _progclear(self):
|
|
|
|
"""clear progress bar output if any. use it before any output"""
|
2015-10-17 01:58:46 +03:00
|
|
|
if '_progbar' not in vars(self): # nothing loaded yet
|
2015-06-08 03:50:56 +03:00
|
|
|
return
|
|
|
|
if self._progbar is not None and self._progbar.printed:
|
|
|
|
self._progbar.clear()
|
|
|
|
|
2009-07-16 23:49:52 +04:00
|
|
|
def progress(self, topic, pos, item="", unit="", total=None):
|
|
|
|
'''show a progress message
|
|
|
|
|
2016-03-17 21:34:32 +03:00
|
|
|
By default a textual progress bar will be displayed if an operation
|
|
|
|
takes too long. 'topic' is the current operation, 'item' is a
|
2012-08-16 00:38:42 +04:00
|
|
|
non-numeric marker of the current position (i.e. the currently
|
|
|
|
in-process file), 'pos' is the current numeric position (i.e.
|
2009-08-18 22:47:41 +04:00
|
|
|
revision, bytes, etc.), unit is a corresponding unit label,
|
2009-07-16 23:49:52 +04:00
|
|
|
and total is the highest expected pos.
|
|
|
|
|
2010-02-07 19:25:18 +03:00
|
|
|
Multiple nested topics may be active at a time.
|
|
|
|
|
|
|
|
All topics should be marked closed by setting pos to None at
|
|
|
|
termination.
|
2009-07-16 23:49:52 +04:00
|
|
|
'''
|
2015-06-08 03:50:56 +03:00
|
|
|
if self._progbar is not None:
|
|
|
|
self._progbar.progress(topic, pos, item=item, unit=unit,
|
|
|
|
total=total)
|
2015-05-10 09:40:40 +03:00
|
|
|
if pos is None or not self.configbool('progress', 'debug'):
|
2009-07-16 23:49:52 +04:00
|
|
|
return
|
|
|
|
|
2009-08-18 22:47:41 +04:00
|
|
|
if unit:
|
|
|
|
unit = ' ' + unit
|
2009-07-16 23:49:52 +04:00
|
|
|
if item:
|
|
|
|
item = ' ' + item
|
|
|
|
|
|
|
|
if total:
|
|
|
|
pct = 100.0 * pos / total
|
2010-01-09 01:15:24 +03:00
|
|
|
self.debug('%s:%s %s/%s%s (%4.2f%%)\n'
|
2009-08-18 22:47:41 +04:00
|
|
|
% (topic, item, pos, total, unit, pct))
|
2009-07-16 23:49:52 +04:00
|
|
|
else:
|
2009-11-06 00:40:48 +03:00
|
|
|
self.debug('%s:%s %s%s\n' % (topic, item, pos, unit))
|
2010-04-03 00:22:00 +04:00
|
|
|
|
2013-02-13 02:08:33 +04:00
|
|
|
def log(self, service, *msg, **opts):
|
2010-08-19 20:14:02 +04:00
|
|
|
'''hook for logging facility extensions
|
|
|
|
|
|
|
|
service should be a readily-identifiable subsystem, which will
|
|
|
|
allow filtering.
|
2015-09-10 17:50:03 +03:00
|
|
|
|
|
|
|
*msg should be a newline-terminated format string to log, and
|
|
|
|
then any values to %-format into that format string.
|
|
|
|
|
|
|
|
**opts currently has no defined meanings.
|
2010-08-19 20:14:02 +04:00
|
|
|
'''
|
|
|
|
|
2010-04-03 00:22:00 +04:00
|
|
|
def label(self, msg, label):
|
|
|
|
'''style msg based on supplied label
|
|
|
|
|
2017-02-23 21:45:32 +03:00
|
|
|
If some color mode is enabled, this will add the necessary control
|
|
|
|
characters to apply such color. In addition, 'debug' color mode adds
|
|
|
|
markup showing which label affects a piece of text.
|
2010-04-03 00:22:00 +04:00
|
|
|
|
|
|
|
ui.write(s, 'label') is equivalent to
|
|
|
|
ui.write(ui.label(s, 'label')).
|
|
|
|
'''
|
2017-02-23 21:45:32 +03:00
|
|
|
if self._colormode is not None:
|
|
|
|
return color.colorlabel(self, msg, label)
|
2010-04-03 00:22:00 +04:00
|
|
|
return msg
|
2015-02-07 23:42:10 +03:00
|
|
|
|
2016-05-08 11:43:41 +03:00
|
|
|
def develwarn(self, msg, stacklevel=1, config=None):
|
2015-12-06 10:05:33 +03:00
|
|
|
"""issue a developer warning message
|
|
|
|
|
|
|
|
Use 'stacklevel' to report the offender some layers further up in the
|
|
|
|
stack.
|
|
|
|
"""
|
2016-05-08 11:43:41 +03:00
|
|
|
if not self.configbool('devel', 'all-warnings'):
|
|
|
|
if config is not None and not self.configbool('devel', config):
|
|
|
|
return
|
2015-06-19 21:19:45 +03:00
|
|
|
msg = 'devel-warn: ' + msg
|
2015-12-06 10:05:33 +03:00
|
|
|
stacklevel += 1 # get in develwarn
|
2015-06-19 21:19:45 +03:00
|
|
|
if self.tracebackflag:
|
2015-12-06 10:05:33 +03:00
|
|
|
util.debugstacktrace(msg, stacklevel, self.ferr, self.fout)
|
2016-01-29 17:37:16 +03:00
|
|
|
self.log('develwarn', '%s at:\n%s' %
|
|
|
|
(msg, ''.join(util.getstackframes(stacklevel))))
|
2015-06-19 21:19:45 +03:00
|
|
|
else:
|
|
|
|
curframe = inspect.currentframe()
|
|
|
|
calframe = inspect.getouterframes(curframe, 2)
|
2015-12-06 10:05:33 +03:00
|
|
|
self.write_err('%s at: %s:%s (%s)\n'
|
|
|
|
% ((msg,) + calframe[stacklevel][1:4]))
|
2016-01-29 17:37:16 +03:00
|
|
|
self.log('develwarn', '%s at: %s:%s (%s)\n',
|
|
|
|
msg, *calframe[stacklevel][1:4])
|
2016-08-10 17:05:20 +03:00
|
|
|
curframe = calframe = None # avoid cycles
|
2015-06-19 21:19:45 +03:00
|
|
|
|
2015-12-06 10:05:49 +03:00
|
|
|
def deprecwarn(self, msg, version):
|
|
|
|
"""issue a deprecation warning
|
|
|
|
|
|
|
|
- msg: message explaining what is deprecated and how to upgrade,
|
|
|
|
- version: last version where the API will be supported,
|
|
|
|
"""
|
2016-05-05 17:29:31 +03:00
|
|
|
if not (self.configbool('devel', 'all-warnings')
|
|
|
|
or self.configbool('devel', 'deprec-warn')):
|
|
|
|
return
|
2015-12-06 10:05:49 +03:00
|
|
|
msg += ("\n(compatibility will be dropped after Mercurial-%s,"
|
|
|
|
" update your code.)") % version
|
2016-05-08 11:43:41 +03:00
|
|
|
self.develwarn(msg, stacklevel=2, config='deprec-warn')
|
2015-12-06 10:05:49 +03:00
|
|
|
|
2017-01-18 07:05:12 +03:00
|
|
|
def exportableenviron(self):
|
|
|
|
"""The environment variables that are safe to export, e.g. through
|
|
|
|
hgweb.
|
|
|
|
"""
|
|
|
|
return self._exportableenviron
|
|
|
|
|
2016-11-22 03:22:26 +03:00
|
|
|
@contextlib.contextmanager
|
|
|
|
def configoverride(self, overrides, source=""):
|
|
|
|
"""Context manager for temporary config overrides
|
|
|
|
`overrides` must be a dict of the following structure:
|
|
|
|
{(section, name) : value}"""
|
|
|
|
backups = {}
|
2016-11-26 20:14:41 +03:00
|
|
|
try:
|
|
|
|
for (section, name), value in overrides.items():
|
|
|
|
backups[(section, name)] = self.backupconfig(section, name)
|
|
|
|
self.setconfig(section, name, value, source)
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
for __, backup in backups.items():
|
|
|
|
self.restoreconfig(backup)
|
|
|
|
# just restoring ui.quiet config to the previous value is not enough
|
|
|
|
# as it does not update ui.quiet class member
|
|
|
|
if ('ui', 'quiet') in overrides:
|
|
|
|
self.fixconfig(section='ui')
|
2016-11-22 03:22:26 +03:00
|
|
|
|
2015-02-07 23:42:10 +03:00
|
|
|
class paths(dict):
|
|
|
|
"""Represents a collection of paths and their configs.
|
|
|
|
|
|
|
|
Data is initially derived from ui instances and the config files they have
|
|
|
|
loaded.
|
|
|
|
"""
|
|
|
|
def __init__(self, ui):
|
|
|
|
dict.__init__(self)
|
|
|
|
|
2015-12-06 08:11:04 +03:00
|
|
|
for name, loc in ui.configitems('paths', ignoresub=True):
|
2015-02-07 23:42:10 +03:00
|
|
|
# No location is the same as not existing.
|
|
|
|
if not loc:
|
|
|
|
continue
|
2015-12-06 08:11:04 +03:00
|
|
|
loc, sub = ui.configsuboptions('paths', name)
|
|
|
|
self[name] = path(ui, name, rawloc=loc, suboptions=sub)
|
2015-02-07 23:42:10 +03:00
|
|
|
|
|
|
|
def getpath(self, name, default=None):
|
2015-12-26 10:10:39 +03:00
|
|
|
"""Return a ``path`` from a string, falling back to default.
|
2015-08-08 10:16:02 +03:00
|
|
|
|
|
|
|
``name`` can be a named path or locations. Locations are filesystem
|
|
|
|
paths or URIs.
|
2015-02-07 23:42:10 +03:00
|
|
|
|
2015-09-06 21:28:48 +03:00
|
|
|
Returns None if ``name`` is not a registered path, a URI, or a local
|
|
|
|
path to a repo.
|
2015-02-07 23:42:10 +03:00
|
|
|
"""
|
2015-09-06 21:28:48 +03:00
|
|
|
# Only fall back to default if no path was requested.
|
|
|
|
if name is None:
|
2015-12-26 10:10:39 +03:00
|
|
|
if not default:
|
|
|
|
default = ()
|
|
|
|
elif not isinstance(default, (tuple, list)):
|
|
|
|
default = (default,)
|
|
|
|
for k in default:
|
2015-09-06 21:28:48 +03:00
|
|
|
try:
|
2015-12-26 10:10:39 +03:00
|
|
|
return self[k]
|
2015-09-06 21:28:48 +03:00
|
|
|
except KeyError:
|
2015-12-26 10:10:39 +03:00
|
|
|
continue
|
|
|
|
return None
|
2015-09-06 21:28:48 +03:00
|
|
|
|
|
|
|
# Most likely empty string.
|
|
|
|
# This may need to raise in the future.
|
|
|
|
if not name:
|
|
|
|
return None
|
|
|
|
|
2015-02-07 23:42:10 +03:00
|
|
|
try:
|
|
|
|
return self[name]
|
|
|
|
except KeyError:
|
2015-08-08 10:16:02 +03:00
|
|
|
# Try to resolve as a local path or URI.
|
|
|
|
try:
|
2015-12-06 23:31:46 +03:00
|
|
|
# We don't pass sub-options in, so no need to pass ui instance.
|
|
|
|
return path(None, None, rawloc=name)
|
2015-08-08 10:16:02 +03:00
|
|
|
except ValueError:
|
2015-09-06 21:28:48 +03:00
|
|
|
raise error.RepoError(_('repository %s does not exist') %
|
|
|
|
name)
|
2015-02-07 23:42:10 +03:00
|
|
|
|
2015-12-06 08:11:04 +03:00
|
|
|
_pathsuboptions = {}
|
|
|
|
|
|
|
|
def pathsuboption(option, attr):
|
|
|
|
"""Decorator used to declare a path sub-option.
|
|
|
|
|
|
|
|
Arguments are the sub-option name and the attribute it should set on
|
|
|
|
``path`` instances.
|
|
|
|
|
|
|
|
The decorated function will receive as arguments a ``ui`` instance,
|
|
|
|
``path`` instance, and the string value of this option from the config.
|
|
|
|
The function should return the value that will be set on the ``path``
|
|
|
|
instance.
|
|
|
|
|
|
|
|
This decorator can be used to perform additional verification of
|
|
|
|
sub-options and to change the type of sub-options.
|
|
|
|
"""
|
|
|
|
def register(func):
|
|
|
|
_pathsuboptions[option] = (attr, func)
|
|
|
|
return func
|
|
|
|
return register
|
|
|
|
|
|
|
|
@pathsuboption('pushurl', 'pushloc')
|
|
|
|
def pushurlpathoption(ui, path, value):
|
|
|
|
u = util.url(value)
|
|
|
|
# Actually require a URL.
|
|
|
|
if not u.scheme:
|
|
|
|
ui.warn(_('(paths.%s:pushurl not a URL; ignoring)\n') % path.name)
|
|
|
|
return None
|
|
|
|
|
|
|
|
# Don't support the #foo syntax in the push URL to declare branch to
|
|
|
|
# push.
|
|
|
|
if u.fragment:
|
|
|
|
ui.warn(_('("#fragment" in paths.%s:pushurl not supported; '
|
|
|
|
'ignoring)\n') % path.name)
|
|
|
|
u.fragment = None
|
|
|
|
|
|
|
|
return str(u)
|
|
|
|
|
2016-06-26 17:59:02 +03:00
|
|
|
@pathsuboption('pushrev', 'pushrev')
|
|
|
|
def pushrevpathoption(ui, path, value):
|
|
|
|
return value
|
|
|
|
|
2015-02-07 23:42:10 +03:00
|
|
|
class path(object):
|
|
|
|
"""Represents an individual path and its configuration."""
|
|
|
|
|
2015-12-06 08:11:04 +03:00
|
|
|
def __init__(self, ui, name, rawloc=None, suboptions=None):
|
2015-02-07 23:42:10 +03:00
|
|
|
"""Construct a path from its config options.
|
|
|
|
|
2015-12-06 23:31:46 +03:00
|
|
|
``ui`` is the ``ui`` instance the path is coming from.
|
2015-02-07 23:42:10 +03:00
|
|
|
``name`` is the symbolic name of the path.
|
|
|
|
``rawloc`` is the raw location, as defined in the config.
|
2015-08-08 07:53:34 +03:00
|
|
|
``pushloc`` is the raw locations pushes should be made to.
|
2015-08-08 10:16:02 +03:00
|
|
|
|
|
|
|
If ``name`` is not defined, we require that the location be a) a local
|
|
|
|
filesystem path with a .hg directory or b) a URL. If not,
|
|
|
|
``ValueError`` is raised.
|
2015-02-07 23:42:10 +03:00
|
|
|
"""
|
2015-08-08 10:16:02 +03:00
|
|
|
if not rawloc:
|
|
|
|
raise ValueError('rawloc must be defined')
|
|
|
|
|
|
|
|
# Locations may define branches via syntax <base>#<branch>.
|
|
|
|
u = util.url(rawloc)
|
|
|
|
branch = None
|
|
|
|
if u.fragment:
|
|
|
|
branch = u.fragment
|
|
|
|
u.fragment = None
|
|
|
|
|
|
|
|
self.url = u
|
|
|
|
self.branch = branch
|
|
|
|
|
2015-02-07 23:42:10 +03:00
|
|
|
self.name = name
|
2015-08-08 10:16:02 +03:00
|
|
|
self.rawloc = rawloc
|
2017-03-12 09:59:23 +03:00
|
|
|
self.loc = '%s' % u
|
2015-08-08 10:16:02 +03:00
|
|
|
|
|
|
|
# When given a raw location but not a symbolic name, validate the
|
|
|
|
# location is valid.
|
2015-08-25 05:33:36 +03:00
|
|
|
if not name and not u.scheme and not self._isvalidlocalpath(self.loc):
|
2015-08-08 10:16:02 +03:00
|
|
|
raise ValueError('location is not a URL or path to a local '
|
|
|
|
'repo: %s' % rawloc)
|
2015-06-08 03:26:34 +03:00
|
|
|
|
2015-12-06 08:11:04 +03:00
|
|
|
suboptions = suboptions or {}
|
|
|
|
|
|
|
|
# Now process the sub-options. If a sub-option is registered, its
|
|
|
|
# attribute will always be present. The value will be None if there
|
|
|
|
# was no valid sub-option.
|
|
|
|
for suboption, (attr, func) in _pathsuboptions.iteritems():
|
|
|
|
if suboption not in suboptions:
|
|
|
|
setattr(self, attr, None)
|
|
|
|
continue
|
|
|
|
|
|
|
|
value = func(ui, self, suboptions[suboption])
|
|
|
|
setattr(self, attr, value)
|
|
|
|
|
2015-08-25 05:33:36 +03:00
|
|
|
def _isvalidlocalpath(self, path):
|
|
|
|
"""Returns True if the given path is a potentially valid repository.
|
|
|
|
This is its own function so that extensions can change the definition of
|
|
|
|
'valid' in this case (like when pulling from a git repo into a hg
|
|
|
|
one)."""
|
|
|
|
return os.path.isdir(os.path.join(path, '.hg'))
|
|
|
|
|
2015-12-06 08:11:04 +03:00
|
|
|
@property
|
|
|
|
def suboptions(self):
|
|
|
|
"""Return sub-options and their values for this path.
|
|
|
|
|
|
|
|
This is intended to be used for presentation purposes.
|
|
|
|
"""
|
|
|
|
d = {}
|
|
|
|
for subopt, (attr, _func) in _pathsuboptions.iteritems():
|
|
|
|
value = getattr(self, attr)
|
|
|
|
if value is not None:
|
|
|
|
d[subopt] = value
|
|
|
|
return d
|
|
|
|
|
2015-06-08 03:26:34 +03:00
|
|
|
# we instantiate one globally shared progress bar to avoid
|
|
|
|
# competing progress bars when multiple UI objects get created
|
|
|
|
_progresssingleton = None
|
|
|
|
|
|
|
|
def getprogbar(ui):
|
|
|
|
global _progresssingleton
|
|
|
|
if _progresssingleton is None:
|
|
|
|
# passing 'ui' object to the singleton is fishy,
|
|
|
|
# this is how the extension used to work but feel free to rework it.
|
|
|
|
_progresssingleton = progress.progbar(ui)
|
|
|
|
return _progresssingleton
|