ui: factor out ui.load() to create a ui without loading configs (API)

This allows us to write doctests depending on a ui object, but not on global
configs.

ui.load() is a class method so we can do wsgiui.load(). All ui() calls but
for doctests are replaced with ui.load(). Some of them could be changed to
not load configs later.
This commit is contained in:
Yuya Nishihara 2016-10-22 14:35:10 +09:00
parent 35a3247fa1
commit 1d44bd2bbb
34 changed files with 55 additions and 44 deletions

View File

@ -50,7 +50,7 @@ outputre = re.compile((r'! wall (\d+.\d+) comb \d+.\d+ user \d+.\d+ sys '
def runperfcommand(reponame, command, *args, **kwargs): def runperfcommand(reponame, command, *args, **kwargs):
os.environ["HGRCPATH"] = os.environ.get("ASVHGRCPATH", "") os.environ["HGRCPATH"] = os.environ.get("ASVHGRCPATH", "")
ui = uimod.ui() ui = uimod.ui.load()
repo = hg.repository(ui, os.path.join(reposdir, reponame)) repo = hg.repository(ui, os.path.join(reposdir, reponame))
perfext = extensions.load(ui, 'perfext', perfext = extensions.load(ui, 'perfext',
os.path.join(basedir, 'contrib', 'perf.py')) os.path.join(basedir, 'contrib', 'perf.py'))

View File

@ -54,7 +54,7 @@ try:
sys.exit(0) sys.exit(0)
if len(args) != 3: if len(args) != 3:
raise ParseError(_('wrong number of arguments')) raise ParseError(_('wrong number of arguments'))
sys.exit(simplemerge.simplemerge(ui.ui(), *args, **opts)) sys.exit(simplemerge.simplemerge(ui.ui.load(), *args, **opts))
except ParseError as e: except ParseError as e:
sys.stdout.write("%s: %s\n" % (sys.argv[0], e)) sys.stdout.write("%s: %s\n" % (sys.argv[0], e))
showhelp() showhelp()

View File

@ -158,7 +158,7 @@ option.
(options, args) = optparser.parse_args() (options, args) = optparser.parse_args()
ui = uimod.ui() ui = uimod.ui.load()
ui.setconfig('ui', 'verbose', options.verbose, '--verbose') ui.setconfig('ui', 'verbose', options.verbose, '--verbose')
ui.setconfig('ui', 'debug', options.debug, '--debug') ui.setconfig('ui', 'debug', options.debug, '--debug')

View File

@ -217,7 +217,7 @@ if __name__ == "__main__":
if len(sys.argv) > 1: if len(sys.argv) > 1:
doc = sys.argv[1] doc = sys.argv[1]
ui = uimod.ui() ui = uimod.ui.load()
if doc == 'hg.1.gendoc': if doc == 'hg.1.gendoc':
showdoc(ui) showdoc(ui)
else: else:

View File

@ -101,7 +101,7 @@ def dispatch(req):
try: try:
if not req.ui: if not req.ui:
req.ui = uimod.ui() req.ui = uimod.ui.load()
if '--traceback' in req.args: if '--traceback' in req.args:
req.ui.setconfig('ui', 'traceback', 'on', '--traceback') req.ui.setconfig('ui', 'traceback', 'on', '--traceback')

View File

@ -224,7 +224,7 @@ class hgweb(object):
if baseui: if baseui:
u = baseui.copy() u = baseui.copy()
else: else:
u = uimod.ui() u = uimod.ui.load()
r = hg.repository(u, repo) r = hg.repository(u, repo)
else: else:
# we trust caller to give us a private copy # we trust caller to give us a private copy
@ -467,4 +467,3 @@ def getwebview(repo):
return repo.filtered(viewconfig) return repo.filtered(viewconfig)
else: else:
return repo.filtered('served') return repo.filtered('served')

View File

@ -136,7 +136,7 @@ class hgwebdir(object):
if self.baseui: if self.baseui:
u = self.baseui.copy() u = self.baseui.copy()
else: else:
u = uimod.ui() u = uimod.ui.load()
u.setconfig('ui', 'report_untrusted', 'off', 'hgwebdir') u.setconfig('ui', 'report_untrusted', 'off', 'hgwebdir')
u.setconfig('ui', 'nontty', 'true', 'hgwebdir') u.setconfig('ui', 'nontty', 'true', 'hgwebdir')
# displaying bundling progress bar while serving feels wrong and may # displaying bundling progress bar while serving feels wrong and may

View File

@ -1302,7 +1302,7 @@ def help(web, req, tmpl):
return tmpl('helptopics', topics=topics, title=topicname, return tmpl('helptopics', topics=topics, title=topicname,
subindex=True) subindex=True)
u = webutil.wsgiui() u = webutil.wsgiui.load()
u.verbose = True u.verbose = True
# Render a page from a sub-topic. # Render a page from a sub-topic.

View File

@ -96,6 +96,12 @@ default = %s
class ui(object): class ui(object):
def __init__(self, src=None): def __init__(self, src=None):
"""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.
"""
# _buffers: used for temporary capture of output # _buffers: used for temporary capture of output
self._buffers = [] self._buffers = []
# 3-tuple describing how each buffer in the stack behaves. # 3-tuple describing how each buffer in the stack behaves.
@ -138,12 +144,18 @@ class ui(object):
# shared read-only environment # shared read-only environment
self.environ = os.environ self.environ = os.environ
# we always trust global config files
for f in scmutil.rcpath():
self.readconfig(f, trust=True)
self.httppasswordmgrdb = urlreq.httppasswordmgrwithdefaultrealm() self.httppasswordmgrdb = urlreq.httppasswordmgrwithdefaultrealm()
@classmethod
def load(cls):
"""Create a ui and load global and user configs"""
u = cls()
# we always trust global config files
for f in scmutil.rcpath():
u.readconfig(f, trust=True)
return u
def copy(self): def copy(self):
return self.__class__(self) return self.__class__(self)

View File

@ -37,7 +37,7 @@ class dummysmtpsecureserver(dummysmtpserver):
if not pair: if not pair:
return return
conn, addr = pair conn, addr = pair
ui = uimod.ui() ui = uimod.ui.load()
try: try:
# wrap_socket() would block, but we don't care # wrap_socket() would block, but we don't care
conn = sslutil.wrapserversocket(conn, ui, certfile=self._certfile) conn = sslutil.wrapserversocket(conn, ui, certfile=self._certfile)

View File

@ -449,7 +449,7 @@ def has_sslcontext():
@check("defaultcacerts", "can verify SSL certs by system's CA certs store") @check("defaultcacerts", "can verify SSL certs by system's CA certs store")
def has_defaultcacerts(): def has_defaultcacerts():
from mercurial import sslutil, ui as uimod from mercurial import sslutil, ui as uimod
ui = uimod.ui() ui = uimod.ui.load()
return sslutil._defaultcacerts(ui) or sslutil._canloaddefaultcerts return sslutil._defaultcacerts(ui) or sslutil._canloaddefaultcerts
@check("defaultcacertsloaded", "detected presence of loaded system CA certs") @check("defaultcacertsloaded", "detected presence of loaded system CA certs")
@ -462,7 +462,7 @@ def has_defaultcacertsloaded():
if not has_sslcontext(): if not has_sslcontext():
return False return False
ui = uimod.ui() ui = uimod.ui.load()
cafile = sslutil._defaultcacerts(ui) cafile = sslutil._defaultcacerts(ui)
ctx = ssl.create_default_context() ctx = ssl.create_default_context()
if cafile: if cafile:

View File

@ -218,7 +218,7 @@ dagtests = [
'+3*3/*2*2/*4*4/*4/2*4/2*2', '+3*3/*2*2/*4*4/*4/2*4/2*2',
] ]
def test_gca(): def test_gca():
u = uimod.ui() u = uimod.ui.load()
for i, dag in enumerate(dagtests): for i, dag in enumerate(dagtests):
repo = hg.repository(u, 'gca%d' % i, create=1) repo = hg.repository(u, 'gca%d' % i, create=1)
cl = repo.changelog cl = repo.changelog

View File

@ -34,7 +34,7 @@ Verify that updating to revision 0 via commands.update() works properly
$ cat <<EOF > update_to_rev0.py $ cat <<EOF > update_to_rev0.py
> from mercurial import ui, hg, commands > from mercurial import ui, hg, commands
> myui = ui.ui() > myui = ui.ui.load()
> repo = hg.repository(myui, path='.') > repo = hg.repository(myui, path='.')
> commands.update(myui, repo, rev=0) > commands.update(myui, repo, rev=0)
> EOF > EOF

View File

@ -456,7 +456,7 @@ test bisecting command
> #!/usr/bin/env python > #!/usr/bin/env python
> import sys > import sys
> from mercurial import ui, hg > from mercurial import ui, hg
> repo = hg.repository(ui.ui(), '.') > repo = hg.repository(ui.ui.load(), '.')
> if repo['.'].rev() < 6: > if repo['.'].rev() < 6:
> sys.exit(1) > sys.exit(1)
> EOF > EOF

View File

@ -515,7 +515,7 @@ iterable in addbranchrevs()
$ cat <<EOF > simpleclone.py $ cat <<EOF > simpleclone.py
> from mercurial import ui, hg > from mercurial import ui, hg
> myui = ui.ui() > myui = ui.ui.load()
> repo = hg.repository(myui, 'a') > repo = hg.repository(myui, 'a')
> hg.clone(myui, {}, repo, dest="ua") > hg.clone(myui, {}, repo, dest="ua")
> EOF > EOF
@ -528,7 +528,7 @@ iterable in addbranchrevs()
$ cat <<EOF > branchclone.py $ cat <<EOF > branchclone.py
> from mercurial import ui, hg, extensions > from mercurial import ui, hg, extensions
> myui = ui.ui() > myui = ui.ui.load()
> extensions.loadall(myui) > extensions.loadall(myui)
> repo = hg.repository(myui, 'a') > repo = hg.repository(myui, 'a')
> hg.clone(myui, {}, repo, dest="ua", branch=["stable",]) > hg.clone(myui, {}, repo, dest="ua", branch=["stable",])

View File

@ -325,7 +325,7 @@ The default interface is text
$ chunkselectorinterface() { $ chunkselectorinterface() {
> python <<EOF > python <<EOF
> from mercurial import hg, ui, parsers;\ > from mercurial import hg, ui, parsers;\
> repo = hg.repository(ui.ui(), ".");\ > repo = hg.repository(ui.ui.load(), ".");\
> print repo.ui.interface("chunkselector") > print repo.ui.interface("chunkselector")
> EOF > EOF
> } > }

View File

@ -92,7 +92,7 @@ now test that we fixed the bug for all scripts/extensions
> def printfiles(repo, rev): > def printfiles(repo, rev):
> print "revision %s files: %s" % (rev, repo[rev].files()) > print "revision %s files: %s" % (rev, repo[rev].files())
> >
> repo = hg.repository(ui.ui(), '.') > repo = hg.repository(ui.ui.load(), '.')
> assert len(repo) == 6, \ > assert len(repo) == 6, \
> "initial: len(repo): %d, expected: 6" % len(repo) > "initial: len(repo): %d, expected: 6" % len(repo)
> >

View File

@ -609,7 +609,7 @@ verify pathauditor blocks evil filepaths
$ cat > evil-commit.py <<EOF $ cat > evil-commit.py <<EOF
> from mercurial import ui, hg, context, node > from mercurial import ui, hg, context, node
> notrc = u".h\u200cg".encode('utf-8') + '/hgrc' > notrc = u".h\u200cg".encode('utf-8') + '/hgrc'
> u = ui.ui() > u = ui.ui.load()
> r = hg.repository(u, '.') > r = hg.repository(u, '.')
> def filectxfn(repo, memctx, path): > def filectxfn(repo, memctx, path):
> return context.memfilectx(repo, path, '[hooks]\nupdate = echo owned') > return context.memfilectx(repo, path, '[hooks]\nupdate = echo owned')
@ -633,7 +633,7 @@ verify pathauditor blocks evil filepaths
$ cat > evil-commit.py <<EOF $ cat > evil-commit.py <<EOF
> from mercurial import ui, hg, context, node > from mercurial import ui, hg, context, node
> notrc = "HG~1/hgrc" > notrc = "HG~1/hgrc"
> u = ui.ui() > u = ui.ui.load()
> r = hg.repository(u, '.') > r = hg.repository(u, '.')
> def filectxfn(repo, memctx, path): > def filectxfn(repo, memctx, path):
> return context.memfilectx(repo, path, '[hooks]\nupdate = echo owned') > return context.memfilectx(repo, path, '[hooks]\nupdate = echo owned')
@ -651,7 +651,7 @@ verify pathauditor blocks evil filepaths
$ cat > evil-commit.py <<EOF $ cat > evil-commit.py <<EOF
> from mercurial import ui, hg, context, node > from mercurial import ui, hg, context, node
> notrc = "HG8B6C~2/hgrc" > notrc = "HG8B6C~2/hgrc"
> u = ui.ui() > u = ui.ui.load()
> r = hg.repository(u, '.') > r = hg.repository(u, '.')
> def filectxfn(repo, memctx, path): > def filectxfn(repo, memctx, path):
> return context.memfilectx(repo, path, '[hooks]\nupdate = echo owned') > return context.memfilectx(repo, path, '[hooks]\nupdate = echo owned')

View File

@ -7,7 +7,7 @@ from mercurial import (
ui as uimod, ui as uimod,
) )
u = uimod.ui() u = uimod.ui.load()
repo = hg.repository(u, 'test1', create=1) repo = hg.repository(u, 'test1', create=1)
os.chdir('test1') os.chdir('test1')

View File

@ -21,7 +21,7 @@ for ext in disabled:
hgrc.close() hgrc.close()
u = uimod.ui() u = uimod.ui.load()
extensions.loadall(u) extensions.loadall(u)
globalshort = set() globalshort = set()

View File

@ -141,7 +141,7 @@ def fakeuncacheable():
def test_filecache_synced(): def test_filecache_synced():
# test old behavior that caused filecached properties to go out of sync # test old behavior that caused filecached properties to go out of sync
os.system('hg init && echo a >> a && hg ci -qAm.') os.system('hg init && echo a >> a && hg ci -qAm.')
repo = hg.repository(uimod.ui()) repo = hg.repository(uimod.ui.load())
# first rollback clears the filecache, but changelog to stays in __dict__ # first rollback clears the filecache, but changelog to stays in __dict__
repo.rollback() repo.rollback()
repo.commit('.') repo.commit('.')

View File

@ -13,7 +13,7 @@ from mercurial import (
ui as uimod, ui as uimod,
) )
myui = uimod.ui() myui = uimod.ui.load()
repo = hg.repository(myui, path='.', create=True) repo = hg.repository(myui, path='.', create=True)
fl = repo.file('foobar') fl = repo.file('foobar')

View File

@ -15,7 +15,7 @@ class myui(uimod.ui):
def interactive(self): def interactive(self):
return False return False
origui = myui() origui = myui.load()
def writeauth(items): def writeauth(items):
ui = origui.copy() ui = origui.copy()

View File

@ -15,7 +15,7 @@ os.chdir('webdir')
webdir = os.path.realpath('.') webdir = os.path.realpath('.')
u = uimod.ui() u = uimod.ui.load()
hg.repository(u, 'a', create=1) hg.repository(u, 'a', create=1)
hg.repository(u, 'b', create=1) hg.repository(u, 'b', create=1)
os.chdir('b') os.chdir('b')

View File

@ -81,7 +81,7 @@ verify 7e7d56fe4833 (encoding fallback in branchmap to maintain compatibility wi
> sys.stdout = StdoutWrapper(sys.stdout) > sys.stdout = StdoutWrapper(sys.stdout)
> sys.stderr = StdoutWrapper(sys.stderr) > sys.stderr = StdoutWrapper(sys.stderr)
> >
> myui = ui.ui() > myui = ui.ui.load()
> repo = hg.repository(myui, 'a') > repo = hg.repository(myui, 'a')
> commands.serve(myui, repo, stdio=True, cmdserver=False) > commands.serve(myui, repo, stdio=True, cmdserver=False)
> EOF > EOF

View File

@ -46,7 +46,7 @@ localrepo.localrepository.testcachedunfifoobar = testcachedunfifoobar
# these tests on the real object to detect regression. # these tests on the real object to detect regression.
repopath = os.path.join(os.environ['TESTTMP'], 'repo') repopath = os.path.join(os.environ['TESTTMP'], 'repo')
assert subprocess.call(['hg', 'init', repopath]) == 0 assert subprocess.call(['hg', 'init', repopath]) == 0
ui = uimod.ui() ui = uimod.ui.load()
repo = hg.repository(ui, path=repopath).unfiltered() repo = hg.repository(ui, path=repopath).unfiltered()

View File

@ -6,7 +6,7 @@ from mercurial import (
ui as uimod, ui as uimod,
) )
u = uimod.ui() u = uimod.ui.load()
repo = hg.repository(u, 'test1', create=1) repo = hg.repository(u, 'test1', create=1)
os.chdir('test1') os.chdir('test1')

View File

@ -7,7 +7,7 @@ from mercurial import (
ui as uimod, ui as uimod,
) )
u = uimod.ui() u = uimod.ui.load()
print('% creating repo') print('% creating repo')
repo = localrepo.localrepository(u, '.', create=True) repo = localrepo.localrepository(u, '.', create=True)

View File

@ -17,7 +17,7 @@ BUNDLEPATH = os.path.join(TESTDIR, 'bundles', 'test-no-symlinks.hg')
if not getattr(os, "symlink", False): if not getattr(os, "symlink", False):
sys.exit(80) # SKIPPED_STATUS defined in run-tests.py sys.exit(80) # SKIPPED_STATUS defined in run-tests.py
u = uimod.ui() u = uimod.ui.load()
# hide outer repo # hide outer repo
hg.peer(u, {}, '.', create=True) hg.peer(u, {}, '.', create=True)
@ -48,10 +48,10 @@ for f in 'test0/a.lnk', 'test0/d/b.lnk':
fp.close() fp.close()
# reload repository # reload repository
u = uimod.ui() u = uimod.ui.load()
repo = hg.repository(u, 'test0') repo = hg.repository(u, 'test0')
commands.status(u, repo) commands.status(u, repo)
# try cloning a repo which contains symlinks # try cloning a repo which contains symlinks
u = uimod.ui() u = uimod.ui.load()
hg.clone(u, {}, BUNDLEPATH, 'test1') hg.clone(u, {}, BUNDLEPATH, 'test1')

View File

@ -66,7 +66,7 @@ def testui(user='foo', group='bar', tusers=(), tgroups=(),
print('# %s user, %s group%s' % (kind[user == cuser], kind[group == cgroup], print('# %s user, %s group%s' % (kind[user == cuser], kind[group == cgroup],
trusted)) trusted))
u = uimod.ui() u = uimod.ui.load()
u.setconfig('ui', 'debug', str(bool(debug))) u.setconfig('ui', 'debug', str(bool(debug)))
u.setconfig('ui', 'report_untrusted', str(bool(report))) u.setconfig('ui', 'report_untrusted', str(bool(report)))
u.readconfig('.hg/hgrc') u.readconfig('.hg/hgrc')
@ -156,7 +156,7 @@ print(u.config('foobar', 'baz'))
print() print()
print("# read trusted, untrusted, new ui, trusted") print("# read trusted, untrusted, new ui, trusted")
u = uimod.ui() u = uimod.ui.load()
u.setconfig('ui', 'debug', 'on') u.setconfig('ui', 'debug', 'on')
u.readconfig(filename) u.readconfig(filename)
u2 = u.copy() u2 = u.copy()

View File

@ -23,7 +23,7 @@ hgrc.write('[extensions]\n')
hgrc.write('color=\n') hgrc.write('color=\n')
hgrc.close() hgrc.close()
ui_ = uimod.ui() ui_ = uimod.ui.load()
ui_.setconfig('ui', 'formatted', 'True') ui_.setconfig('ui', 'formatted', 'True')
# we're not interested in the output, so write that to devnull # we're not interested in the output, so write that to devnull

View File

@ -5,7 +5,7 @@ from mercurial import (
ui as uimod, ui as uimod,
) )
testui = uimod.ui() testui = uimod.ui.load()
parsed = dispatch._parseconfig(testui, [ parsed = dispatch._parseconfig(testui, [
'values.string=string value', 'values.string=string value',
'values.bool1=true', 'values.bool1=true',

View File

@ -32,7 +32,7 @@ for i in xrange(64):
f.write('debug = True\n') f.write('debug = True\n')
f.close() f.close()
u = uimod.ui() u = uimod.ui.load()
if cmd_quiet or cmd_debug or cmd_verbose: if cmd_quiet or cmd_debug or cmd_verbose:
u.setconfig('ui', 'quiet', str(bool(cmd_quiet))) u.setconfig('ui', 'quiet', str(bool(cmd_quiet)))
u.setconfig('ui', 'verbose', str(bool(cmd_verbose))) u.setconfig('ui', 'verbose', str(bool(cmd_verbose)))

View File

@ -16,7 +16,7 @@ pjoin = os.path.join
walkrepos = scmutil.walkrepos walkrepos = scmutil.walkrepos
checklink = util.checklink checklink = util.checklink
u = uimod.ui() u = uimod.ui.load()
sym = checklink('.') sym = checklink('.')
hg.repository(u, 'top1', create=1) hg.repository(u, 'top1', create=1)