sapling/mercurial/localrepo.py

2032 lines
76 KiB
Python
Raw Normal View History

# localrepo.py - read/write repository class for mercurial
#
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
#
# 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.
2015-12-23 23:30:14 +03:00
from __future__ import absolute_import
import errno
import hashlib
2015-12-23 23:30:14 +03:00
import inspect
import os
import random
import time
import weakref
from .i18n import _
from .node import (
hex,
nullid,
short,
wdirrev,
)
from . import (
bookmarks,
branchmap,
bundle2,
changegroup,
changelog,
context,
dirstate,
dirstateguard,
2015-12-23 23:30:14 +03:00
encoding,
error,
exchange,
extensions,
filelog,
hook,
lock as lockmod,
manifest,
match as matchmod,
merge as mergemod,
mergeutil,
2015-12-23 23:30:14 +03:00
namespaces,
obsolete,
pathutil,
peer,
phases,
pushkey,
repoview,
revset,
scmutil,
store,
subrepo,
tags as tagsmod,
transaction,
util,
)
release = lockmod.release
urlerr = util.urlerr
urlreq = util.urlreq
class repofilecache(scmutil.filecache):
"""All filecache usage on repo are done for logic that should be unfiltered
"""
def __get__(self, repo, type=None):
if repo is None:
return self
return super(repofilecache, self).__get__(repo.unfiltered(), type)
def __set__(self, repo, value):
return super(repofilecache, self).__set__(repo.unfiltered(), value)
def __delete__(self, repo):
return super(repofilecache, self).__delete__(repo.unfiltered())
class storecache(repofilecache):
"""filecache for files in the store"""
def join(self, obj, fname):
return obj.sjoin(fname)
class unfilteredpropertycache(util.propertycache):
"""propertycache that apply to unfiltered repo only"""
def __get__(self, repo, type=None):
unfi = repo.unfiltered()
if unfi is repo:
return super(unfilteredpropertycache, self).__get__(unfi)
return getattr(unfi, self.name)
class filteredpropertycache(util.propertycache):
"""propertycache that must take filtering in account"""
def cachevalue(self, obj, value):
object.__setattr__(obj, self.name, value)
def hasunfilteredcache(repo, name):
"""check if a repo has an unfilteredpropertycache value for <name>"""
return name in vars(repo.unfiltered())
def unfilteredmethod(orig):
"""decorate method that always need to be run on unfiltered version"""
def wrapper(repo, *args, **kwargs):
return orig(repo.unfiltered(), *args, **kwargs)
return wrapper
moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
'unbundle'))
legacycaps = moderncaps.union(set(['changegroupsubset']))
class localpeer(peer.peerrepository):
'''peer for a local repo; reflects only the most recent API'''
def __init__(self, repo, caps=moderncaps):
peer.peerrepository.__init__(self)
self._repo = repo.filtered('served')
self.ui = repo.ui
self._caps = repo._restrictcapabilities(caps)
self.requirements = repo.requirements
self.supportedformats = repo.supportedformats
def close(self):
self._repo.close()
def _capabilities(self):
return self._caps
def local(self):
return self._repo
def canpush(self):
return True
def url(self):
return self._repo.url()
def lookup(self, key):
return self._repo.lookup(key)
def branchmap(self):
return self._repo.branchmap()
def heads(self):
return self._repo.heads()
def known(self, nodes):
return self._repo.known(nodes)
def getbundle(self, source, heads=None, common=None, bundlecaps=None,
**kwargs):
exchange: refactor APIs to obtain bundle data (API) Currently, exchange.getbundle() returns either a cg1unpacker or a util.chunkbuffer (in the case of bundle2). This is kinda OK, as both expose a .read() to consumers. However, localpeer.getbundle() has code inferring what the response type is based on arguments and converts the util.chunkbuffer returned in the bundle2 case to a bundle2.unbundle20 instance. This is a sign that the API for exchange.getbundle() is not ideal because it doesn't consistently return an "unbundler" instance. In addition, unbundlers mask the fact that there is an underlying generator of changegroup data. In both cg1 and bundle2, this generator is being fed into a util.chunkbuffer so it can be re-exposed as a file object. util.chunkbuffer is a nice abstraction. However, it should only be used "at the edges." This is because keeping data as a generator is more efficient than converting it to a chunkbuffer, especially if we convert that chunkbuffer back to a generator (as is the case in some code paths currently). This patch refactors exchange.getbundle() into exchange.getbundlechunks(). The new API returns an iterator of chunks instead of a file-like object. Callers of exchange.getbundle() have been updated to use the new API. There is a minor change of behavior in test-getbundle.t. This is because `hg debuggetbundle` isn't defining bundlecaps. As a result, a cg1 data stream and unpacker is being produced. This is getting fed into a new bundle20 instance via bundle2.writebundle(), which uses a backchannel mechanism between changegroup generation to add the "nbchanges" part parameter. I never liked this backchannel mechanism and I plan to remove it someday. `hg bundle` still produces the "nbchanges" part parameter, so there should be no user-visible change of behavior. I consider this "regression" a bug in `hg debuggetbundle`. And that bug is captured by an existing "TODO" in the code to use bundle2 capabilities.
2016-10-16 20:38:52 +03:00
chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
common=common, bundlecaps=bundlecaps,
**kwargs)
cb = util.chunkbuffer(chunks)
if bundlecaps is not None and 'HG20' in bundlecaps:
# When requesting a bundle2, getbundle returns a stream to make the
# wire level function happier. We need to build a proper object
# from it in local peer.
exchange: refactor APIs to obtain bundle data (API) Currently, exchange.getbundle() returns either a cg1unpacker or a util.chunkbuffer (in the case of bundle2). This is kinda OK, as both expose a .read() to consumers. However, localpeer.getbundle() has code inferring what the response type is based on arguments and converts the util.chunkbuffer returned in the bundle2 case to a bundle2.unbundle20 instance. This is a sign that the API for exchange.getbundle() is not ideal because it doesn't consistently return an "unbundler" instance. In addition, unbundlers mask the fact that there is an underlying generator of changegroup data. In both cg1 and bundle2, this generator is being fed into a util.chunkbuffer so it can be re-exposed as a file object. util.chunkbuffer is a nice abstraction. However, it should only be used "at the edges." This is because keeping data as a generator is more efficient than converting it to a chunkbuffer, especially if we convert that chunkbuffer back to a generator (as is the case in some code paths currently). This patch refactors exchange.getbundle() into exchange.getbundlechunks(). The new API returns an iterator of chunks instead of a file-like object. Callers of exchange.getbundle() have been updated to use the new API. There is a minor change of behavior in test-getbundle.t. This is because `hg debuggetbundle` isn't defining bundlecaps. As a result, a cg1 data stream and unpacker is being produced. This is getting fed into a new bundle20 instance via bundle2.writebundle(), which uses a backchannel mechanism between changegroup generation to add the "nbchanges" part parameter. I never liked this backchannel mechanism and I plan to remove it someday. `hg bundle` still produces the "nbchanges" part parameter, so there should be no user-visible change of behavior. I consider this "regression" a bug in `hg debuggetbundle`. And that bug is captured by an existing "TODO" in the code to use bundle2 capabilities.
2016-10-16 20:38:52 +03:00
return bundle2.getunbundler(self.ui, cb)
else:
return changegroup.getunbundler('01', cb, None)
# TODO We might want to move the next two calls into legacypeer and add
# unbundle instead.
def unbundle(self, cg, heads, url):
"""apply a bundle on a repo
This function handles the repo locking itself."""
try:
try:
cg = exchange.readbundle(self.ui, cg, None)
ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
if util.safehasattr(ret, 'getchunks'):
# This is a bundle20 object, turn it into an unbundler.
# This little dance should be dropped eventually when the
# API is finally improved.
stream = util.chunkbuffer(ret.getchunks())
ret = bundle2.getunbundler(self.ui, stream)
return ret
except Exception as exc:
# If the exception contains output salvaged from a bundle2
# reply, we need to make sure it is printed before continuing
# to fail. So we build a bundle2 with such output and consume
# it directly.
#
# This is not very elegant but allows a "simple" solution for
# issue4594
output = getattr(exc, '_bundle2salvagedoutput', ())
if output:
bundler = bundle2.bundle20(self._repo.ui)
for out in output:
bundler.addpart(out)
stream = util.chunkbuffer(bundler.getchunks())
b = bundle2.getunbundler(self.ui, stream)
bundle2.processbundle(self._repo, b)
raise
except error.PushRaced as exc:
raise error.ResponseError(_('push failed:'), str(exc))
def lock(self):
return self._repo.lock()
def addchangegroup(self, cg, source, url):
return cg.apply(self._repo, source, url)
def pushkey(self, namespace, key, old, new):
return self._repo.pushkey(namespace, key, old, new)
def listkeys(self, namespace):
return self._repo.listkeys(namespace)
def debugwireargs(self, one, two, three=None, four=None, five=None):
'''used to test argument passing over the wire'''
return "%s %s %s %s %s" % (one, two, three, four, five)
class locallegacypeer(localpeer):
'''peer extension which implements legacy methods too; used for tests with
restricted capabilities'''
def __init__(self, repo):
localpeer.__init__(self, repo, caps=legacycaps)
def branches(self, nodes):
return self._repo.branches(nodes)
def between(self, pairs):
return self._repo.between(pairs)
def changegroup(self, basenodes, source):
return changegroup.changegroup(self._repo, basenodes, source)
def changegroupsubset(self, bases, heads, source):
return changegroup.changegroupsubset(self._repo, bases, heads, source)
class localrepository(object):
supportedformats = set(('revlogv1', 'generaldelta', 'treemanifest',
'manifestv2'))
localrepo: make supported features manageable in each repositories individually Before this patch, all localrepositories support same features, because supported features are managed by the class variable "supported" of "localrepository". For example, "largefiles" feature provided by largefiles extension is recognized as supported, by adding the feature name to "supported" of "localrepository". So, commands handling multiple repositories at a time like below misunderstand that such features are supported also in repositories not enabling corresponded extensions: - clone/pull from or push to localhost - recursive execution in subrepo tree "reposetup()" can't be used to fix this problem, because it is invoked after checking whether supported features satisfy ones required in the target repository. So, this patch adds the set object named as "featuresetupfuncs" to "localrepository" to manage hook functions to setup supported features of each repositories. If any functions are added to "featuresetupfuncs", they are invoked, and information about supported features is managed in each repositories individually. This patch also adds checking below: - pull from localhost: whether features supported in the local(= dst) repository satisfies ones required in the remote(= src) - push to localhost: whether features supported in the remote(= dst) repository satisfies ones required in the local(= src) Managing supported features by the class variable means that there is no difference of supported features between each instances of "localrepository" in the same Python process, so such checking is not needed before this patch. Even with this patch, if intermediate bundlefile is used as pulling source, pulling indirectly from the remote repository, which requires features more than ones supported in the local, can't be prevented, because bundlefile has no information about "required features" in it.
2013-09-21 16:33:29 +04:00
_basesupported = supportedformats | set(('store', 'fncache', 'shared',
'dotencode'))
openerreqs = set(('revlogv1', 'generaldelta', 'treemanifest', 'manifestv2'))
filtername = None
# a list of (ui, featureset) functions.
# only functions defined in module of enabled extensions are invoked
localrepo: make supported features manageable in each repositories individually Before this patch, all localrepositories support same features, because supported features are managed by the class variable "supported" of "localrepository". For example, "largefiles" feature provided by largefiles extension is recognized as supported, by adding the feature name to "supported" of "localrepository". So, commands handling multiple repositories at a time like below misunderstand that such features are supported also in repositories not enabling corresponded extensions: - clone/pull from or push to localhost - recursive execution in subrepo tree "reposetup()" can't be used to fix this problem, because it is invoked after checking whether supported features satisfy ones required in the target repository. So, this patch adds the set object named as "featuresetupfuncs" to "localrepository" to manage hook functions to setup supported features of each repositories. If any functions are added to "featuresetupfuncs", they are invoked, and information about supported features is managed in each repositories individually. This patch also adds checking below: - pull from localhost: whether features supported in the local(= dst) repository satisfies ones required in the remote(= src) - push to localhost: whether features supported in the remote(= dst) repository satisfies ones required in the local(= src) Managing supported features by the class variable means that there is no difference of supported features between each instances of "localrepository" in the same Python process, so such checking is not needed before this patch. Even with this patch, if intermediate bundlefile is used as pulling source, pulling indirectly from the remote repository, which requires features more than ones supported in the local, can't be prevented, because bundlefile has no information about "required features" in it.
2013-09-21 16:33:29 +04:00
featuresetupfuncs = set()
def __init__(self, baseui, path, create=False):
self.requirements = set()
self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
self.wopener = self.wvfs
self.root = self.wvfs.base
self.path = self.wvfs.join(".hg")
2006-12-10 02:06:45 +03:00
self.origroot = path
self.auditor = pathutil.pathauditor(self.root, self._checknested)
self.nofsauditor = pathutil.pathauditor(self.root, self._checknested,
realfs=False)
self.vfs = scmutil.vfs(self.path)
self.opener = self.vfs
2009-06-13 23:44:59 +04:00
self.baseui = baseui
self.ui = baseui.copy()
self.ui.copy = baseui.copy # prevent copying repo configuration
# A list of callback to shape the phase if no data were found.
# Callback are in the form: func(repo, roots) --> processed root.
# This list it to be filled by extension during repo setup
self._phasedefaults = []
2009-06-13 23:44:59 +04:00
try:
self.ui.readconfig(self.join("hgrc"), self.root)
extensions.loadall(self.ui)
except IOError:
pass
localrepo: make supported features manageable in each repositories individually Before this patch, all localrepositories support same features, because supported features are managed by the class variable "supported" of "localrepository". For example, "largefiles" feature provided by largefiles extension is recognized as supported, by adding the feature name to "supported" of "localrepository". So, commands handling multiple repositories at a time like below misunderstand that such features are supported also in repositories not enabling corresponded extensions: - clone/pull from or push to localhost - recursive execution in subrepo tree "reposetup()" can't be used to fix this problem, because it is invoked after checking whether supported features satisfy ones required in the target repository. So, this patch adds the set object named as "featuresetupfuncs" to "localrepository" to manage hook functions to setup supported features of each repositories. If any functions are added to "featuresetupfuncs", they are invoked, and information about supported features is managed in each repositories individually. This patch also adds checking below: - pull from localhost: whether features supported in the local(= dst) repository satisfies ones required in the remote(= src) - push to localhost: whether features supported in the remote(= dst) repository satisfies ones required in the local(= src) Managing supported features by the class variable means that there is no difference of supported features between each instances of "localrepository" in the same Python process, so such checking is not needed before this patch. Even with this patch, if intermediate bundlefile is used as pulling source, pulling indirectly from the remote repository, which requires features more than ones supported in the local, can't be prevented, because bundlefile has no information about "required features" in it.
2013-09-21 16:33:29 +04:00
if self.featuresetupfuncs:
self.supported = set(self._basesupported) # use private copy
extmods = set(m.__name__ for n, m
in extensions.extensions(self.ui))
localrepo: make supported features manageable in each repositories individually Before this patch, all localrepositories support same features, because supported features are managed by the class variable "supported" of "localrepository". For example, "largefiles" feature provided by largefiles extension is recognized as supported, by adding the feature name to "supported" of "localrepository". So, commands handling multiple repositories at a time like below misunderstand that such features are supported also in repositories not enabling corresponded extensions: - clone/pull from or push to localhost - recursive execution in subrepo tree "reposetup()" can't be used to fix this problem, because it is invoked after checking whether supported features satisfy ones required in the target repository. So, this patch adds the set object named as "featuresetupfuncs" to "localrepository" to manage hook functions to setup supported features of each repositories. If any functions are added to "featuresetupfuncs", they are invoked, and information about supported features is managed in each repositories individually. This patch also adds checking below: - pull from localhost: whether features supported in the local(= dst) repository satisfies ones required in the remote(= src) - push to localhost: whether features supported in the remote(= dst) repository satisfies ones required in the local(= src) Managing supported features by the class variable means that there is no difference of supported features between each instances of "localrepository" in the same Python process, so such checking is not needed before this patch. Even with this patch, if intermediate bundlefile is used as pulling source, pulling indirectly from the remote repository, which requires features more than ones supported in the local, can't be prevented, because bundlefile has no information about "required features" in it.
2013-09-21 16:33:29 +04:00
for setupfunc in self.featuresetupfuncs:
if setupfunc.__module__ in extmods:
setupfunc(self.ui, self.supported)
localrepo: make supported features manageable in each repositories individually Before this patch, all localrepositories support same features, because supported features are managed by the class variable "supported" of "localrepository". For example, "largefiles" feature provided by largefiles extension is recognized as supported, by adding the feature name to "supported" of "localrepository". So, commands handling multiple repositories at a time like below misunderstand that such features are supported also in repositories not enabling corresponded extensions: - clone/pull from or push to localhost - recursive execution in subrepo tree "reposetup()" can't be used to fix this problem, because it is invoked after checking whether supported features satisfy ones required in the target repository. So, this patch adds the set object named as "featuresetupfuncs" to "localrepository" to manage hook functions to setup supported features of each repositories. If any functions are added to "featuresetupfuncs", they are invoked, and information about supported features is managed in each repositories individually. This patch also adds checking below: - pull from localhost: whether features supported in the local(= dst) repository satisfies ones required in the remote(= src) - push to localhost: whether features supported in the remote(= dst) repository satisfies ones required in the local(= src) Managing supported features by the class variable means that there is no difference of supported features between each instances of "localrepository" in the same Python process, so such checking is not needed before this patch. Even with this patch, if intermediate bundlefile is used as pulling source, pulling indirectly from the remote repository, which requires features more than ones supported in the local, can't be prevented, because bundlefile has no information about "required features" in it.
2013-09-21 16:33:29 +04:00
else:
self.supported = self._basesupported
localrepo: experimental support for non-zlib revlog compression The final part of integrating the compression manager APIs into revlog storage is the plumbing for repositories to advertise they are using non-zlib storage and for revlogs to instantiate a non-zlib compression engine. The main intent of the compression manager work was to zstd all of the things. Adding zstd to revlogs has proved to be more involved than other places because revlogs are... special. Very small inputs and the use of delta chains (which are themselves a form of compression) are a completely different use case from streaming compression, which bundles and the wire protocol employ. I've conducted numerous experiments with zstd in revlogs and have yet to formalize compression settings and a storage architecture that I'm confident I won't regret later. In other words, I'm not yet ready to commit to a new mechanism for using zstd - or any other compression format - in revlogs. That being said, having some support for zstd (and other compression formats) in revlogs in core is beneficial. It can allow others to conduct experiments. This patch introduces *highly experimental* support for non-zlib compression formats in revlogs. Introduced is a config option to control which compression engine to use. Also introduced is a namespace of "exp-compression-*" requirements to denote support for non-zlib compression in revlogs. I've prefixed the namespace with "exp-" (short for "experimental") because I'm not confident of the requirements "schema" and in no way want to give the illusion of supporting these requirements in the future. I fully intend to drop support for these requirements once we figure out what we're doing with zstd in revlogs. A good portion of the patch is teaching the requirements system about registered compression engines and passing the requested compression engine as an opener option so revlogs can instantiate the proper compression engine for new operations. That's a verbose way of saying "we can now use zstd in revlogs!" On an `hg pull` conversion of the mozilla-unified repo with no extra redelta settings (like aggressivemergedeltas), we can see the impact of zstd vs zlib in revlogs: $ hg perfrevlogchunks -c ! chunk ! wall 2.032052 comb 2.040000 user 1.990000 sys 0.050000 (best of 5) ! wall 1.866360 comb 1.860000 user 1.820000 sys 0.040000 (best of 6) ! chunk batch ! wall 1.877261 comb 1.870000 user 1.860000 sys 0.010000 (best of 6) ! wall 1.705410 comb 1.710000 user 1.690000 sys 0.020000 (best of 6) $ hg perfrevlogchunks -m ! chunk ! wall 2.721427 comb 2.720000 user 2.640000 sys 0.080000 (best of 4) ! wall 2.035076 comb 2.030000 user 1.950000 sys 0.080000 (best of 5) ! chunk batch ! wall 2.614561 comb 2.620000 user 2.580000 sys 0.040000 (best of 4) ! wall 1.910252 comb 1.910000 user 1.880000 sys 0.030000 (best of 6) $ hg perfrevlog -c -d 1 ! wall 4.812885 comb 4.820000 user 4.800000 sys 0.020000 (best of 3) ! wall 4.699621 comb 4.710000 user 4.700000 sys 0.010000 (best of 3) $ hg perfrevlog -m -d 1000 ! wall 34.252800 comb 34.250000 user 33.730000 sys 0.520000 (best of 3) ! wall 24.094999 comb 24.090000 user 23.320000 sys 0.770000 (best of 3) Only modest wins for the changelog. But manifest reading is significantly faster. What's going on? One reason might be data volume. zstd decompresses faster. So given more bytes, it will put more distance between it and zlib. Another reason is size. In the current design, zstd revlogs are *larger*: debugcreatestreamclonebundle (size in bytes) zlib: 1,638,852,492 zstd: 1,680,601,332 I haven't investigated this fully, but I reckon a significant cause of larger revlogs is that the zstd frame/header has more bytes than zlib's. For very small inputs or data that doesn't compress well, we'll tend to store more uncompressed chunks than with zlib (because the compressed size isn't smaller than original). This will make revlog reading faster because it is doing less decompression. Moving on to bundle performance: $ hg bundle -a -t none-v2 (total CPU time) zlib: 102.79s zstd: 97.75s So, marginal CPU decrease for reading all chunks in all revlogs (this is somewhat disappointing). $ hg bundle -a -t <engine>-v2 (total CPU time) zlib: 191.59s zstd: 115.36s This last test effectively measures the difference between zlib->zlib and zstd->zstd for revlogs to bundle. This is a rough approximation of what a server does during `hg clone`. There are some promising results for zstd. But not enough for me to feel comfortable advertising it to users. We'll get there...
2017-01-14 07:16:56 +03:00
# Add compression engines.
for name in util.compengines:
engine = util.compengines[name]
if engine.revlogheader():
self.supported.add('exp-compression-%s' % name)
if not self.vfs.isdir():
if create:
2016-02-16 00:20:20 +03:00
self.requirements = newreporequirements(self)
if not self.wvfs.exists():
self.wvfs.makedirs()
self.vfs.makedir(notindexed=True)
2016-02-16 00:20:20 +03:00
if 'store' in self.requirements:
self.vfs.mkdir("store")
# create an invalid changelog
self.vfs.append(
"00changelog.i",
'\0\0\0\2' # represents revlogv2
' dummy changelog to prevent using the old repo layout'
)
else:
raise error.RepoError(_("repository %s not found") % path)
elif create:
raise error.RepoError(_("repository %s already exists") % path)
else:
try:
self.requirements = scmutil.readrequires(
self.vfs, self.supported)
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
self.sharedpath = self.path
try:
vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
realpath=True)
s = vfs.base
if not vfs.exists():
raise error.RepoError(
2009-06-19 10:28:29 +04:00
_('.hg/sharedpath points to nonexistent directory %s') % s)
self.sharedpath = s
except IOError as inst:
if inst.errno != errno.ENOENT:
raise
self.store = store.store(
self.requirements, self.sharedpath, scmutil.vfs)
self.spath = self.store.path
self.svfs = self.store.vfs
self.sjoin = self.store.join
self.vfs.createmode = self.store.createmode
self._applyopenerreqs()
if create:
self._writerequirements()
self._dirstatevalidatewarned = False
self._branchcaches = {}
self._revbranchcache = None
2006-12-30 05:04:31 +03:00
self.filterpats = {}
self._datafilters = {}
self._transref = self._lockref = self._wlockref = None
# A cache for various files under .hg/ that tracks file changes,
# (used by the filecache decorator)
#
# Maps a property name to its util.filecacheentry
self._filecache = {}
# hold sets of revision to be filtered
# should be cleared when something might have changed the filter value:
# - new changesets,
# - phase change,
# - new obsolescence marker,
# - working directory parent change,
# - bookmark changes
self.filteredrevcache = {}
# generic mapping between names and nodes
self.names = namespaces.namespaces()
def close(self):
self._writecaches()
def _writecaches(self):
if self._revbranchcache:
self._revbranchcache.write()
def _restrictcapabilities(self, caps):
if self.ui.configbool('experimental', 'bundle2-advertise', True):
caps = set(caps)
capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
caps.add('bundle2=' + urlreq.quote(capsblob))
return caps
def _applyopenerreqs(self):
self.svfs.options = dict((r, 1) for r in self.requirements
if r in self.openerreqs)
2015-06-26 01:50:27 +03:00
# experimental config: format.chunkcachesize
chunkcachesize = self.ui.configint('format', 'chunkcachesize')
if chunkcachesize is not None:
self.svfs.options['chunkcachesize'] = chunkcachesize
2015-06-26 01:50:27 +03:00
# experimental config: format.maxchainlen
maxchainlen = self.ui.configint('format', 'maxchainlen')
if maxchainlen is not None:
self.svfs.options['maxchainlen'] = maxchainlen
2015-06-26 01:50:27 +03:00
# experimental config: format.manifestcachesize
manifestcachesize = self.ui.configint('format', 'manifestcachesize')
if manifestcachesize is not None:
self.svfs.options['manifestcachesize'] = manifestcachesize
# experimental config: format.aggressivemergedeltas
aggressivemergedeltas = self.ui.configbool('format',
'aggressivemergedeltas', False)
self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
localrepo: experimental support for non-zlib revlog compression The final part of integrating the compression manager APIs into revlog storage is the plumbing for repositories to advertise they are using non-zlib storage and for revlogs to instantiate a non-zlib compression engine. The main intent of the compression manager work was to zstd all of the things. Adding zstd to revlogs has proved to be more involved than other places because revlogs are... special. Very small inputs and the use of delta chains (which are themselves a form of compression) are a completely different use case from streaming compression, which bundles and the wire protocol employ. I've conducted numerous experiments with zstd in revlogs and have yet to formalize compression settings and a storage architecture that I'm confident I won't regret later. In other words, I'm not yet ready to commit to a new mechanism for using zstd - or any other compression format - in revlogs. That being said, having some support for zstd (and other compression formats) in revlogs in core is beneficial. It can allow others to conduct experiments. This patch introduces *highly experimental* support for non-zlib compression formats in revlogs. Introduced is a config option to control which compression engine to use. Also introduced is a namespace of "exp-compression-*" requirements to denote support for non-zlib compression in revlogs. I've prefixed the namespace with "exp-" (short for "experimental") because I'm not confident of the requirements "schema" and in no way want to give the illusion of supporting these requirements in the future. I fully intend to drop support for these requirements once we figure out what we're doing with zstd in revlogs. A good portion of the patch is teaching the requirements system about registered compression engines and passing the requested compression engine as an opener option so revlogs can instantiate the proper compression engine for new operations. That's a verbose way of saying "we can now use zstd in revlogs!" On an `hg pull` conversion of the mozilla-unified repo with no extra redelta settings (like aggressivemergedeltas), we can see the impact of zstd vs zlib in revlogs: $ hg perfrevlogchunks -c ! chunk ! wall 2.032052 comb 2.040000 user 1.990000 sys 0.050000 (best of 5) ! wall 1.866360 comb 1.860000 user 1.820000 sys 0.040000 (best of 6) ! chunk batch ! wall 1.877261 comb 1.870000 user 1.860000 sys 0.010000 (best of 6) ! wall 1.705410 comb 1.710000 user 1.690000 sys 0.020000 (best of 6) $ hg perfrevlogchunks -m ! chunk ! wall 2.721427 comb 2.720000 user 2.640000 sys 0.080000 (best of 4) ! wall 2.035076 comb 2.030000 user 1.950000 sys 0.080000 (best of 5) ! chunk batch ! wall 2.614561 comb 2.620000 user 2.580000 sys 0.040000 (best of 4) ! wall 1.910252 comb 1.910000 user 1.880000 sys 0.030000 (best of 6) $ hg perfrevlog -c -d 1 ! wall 4.812885 comb 4.820000 user 4.800000 sys 0.020000 (best of 3) ! wall 4.699621 comb 4.710000 user 4.700000 sys 0.010000 (best of 3) $ hg perfrevlog -m -d 1000 ! wall 34.252800 comb 34.250000 user 33.730000 sys 0.520000 (best of 3) ! wall 24.094999 comb 24.090000 user 23.320000 sys 0.770000 (best of 3) Only modest wins for the changelog. But manifest reading is significantly faster. What's going on? One reason might be data volume. zstd decompresses faster. So given more bytes, it will put more distance between it and zlib. Another reason is size. In the current design, zstd revlogs are *larger*: debugcreatestreamclonebundle (size in bytes) zlib: 1,638,852,492 zstd: 1,680,601,332 I haven't investigated this fully, but I reckon a significant cause of larger revlogs is that the zstd frame/header has more bytes than zlib's. For very small inputs or data that doesn't compress well, we'll tend to store more uncompressed chunks than with zlib (because the compressed size isn't smaller than original). This will make revlog reading faster because it is doing less decompression. Moving on to bundle performance: $ hg bundle -a -t none-v2 (total CPU time) zlib: 102.79s zstd: 97.75s So, marginal CPU decrease for reading all chunks in all revlogs (this is somewhat disappointing). $ hg bundle -a -t <engine>-v2 (total CPU time) zlib: 191.59s zstd: 115.36s This last test effectively measures the difference between zlib->zlib and zstd->zstd for revlogs to bundle. This is a rough approximation of what a server does during `hg clone`. There are some promising results for zstd. But not enough for me to feel comfortable advertising it to users. We'll get there...
2017-01-14 07:16:56 +03:00
for r in self.requirements:
if r.startswith('exp-compression-'):
self.svfs.options['compengine'] = r[len('exp-compression-'):]
def _writerequirements(self):
scmutil.writerequires(self.vfs, self.requirements)
def _checknested(self, path):
"""Determine if path is a legal nested repository."""
if not path.startswith(self.root):
return False
subpath = path[len(self.root) + 1:]
normsubpath = util.pconvert(subpath)
# XXX: Checking against the current working copy is wrong in
# the sense that it can reject things like
#
# $ hg cat -r 10 sub/x.txt
#
# if sub/ is no longer a subrepository in the working copy
# parent revision.
#
# However, it can of course also allow things that would have
# been rejected before, such as the above cat command if sub/
# is a subrepository now, but was a normal directory before.
# The old path auditor would have rejected by mistake since it
# panics when it sees sub/.hg/.
#
# All in all, checking against the working copy seems sensible
# since we want to prevent access to nested repositories on
# the filesystem *now*.
ctx = self[None]
parts = util.splitpath(subpath)
while parts:
prefix = '/'.join(parts)
if prefix in ctx.substate:
if prefix == normsubpath:
return True
else:
sub = ctx.sub(prefix)
return sub.checknested(subpath[len(prefix) + 1:])
else:
parts.pop()
return False
def peer(self):
return localpeer(self) # not cached to avoid reference cycle
def unfiltered(self):
"""Return unfiltered version of the repository
Intended to be overwritten by filtered repo."""
return self
def filtered(self, name):
"""Return a filtered version of a repository"""
# build a new class with the mixin and the current class
# (possibly subclass of the repo)
class proxycls(repoview.repoview, self.unfiltered().__class__):
pass
return proxycls(self, name)
@repofilecache('bookmarks', 'bookmarks.current')
def _bookmarks(self):
return bookmarks.bmstore(self)
@property
def _activebookmark(self):
return self._bookmarks.active
def bookmarkheads(self, bookmark):
name = bookmark.split('@', 1)[0]
heads = []
for mark, n in self._bookmarks.iteritems():
if mark.split('@', 1)[0] == name:
heads.append(n)
return heads
# _phaserevs and _phasesets depend on changelog. what we need is to
# call _phasecache.invalidate() if '00changelog.i' was changed, but it
# can't be easily expressed in filecache mechanism.
@storecache('phaseroots', '00changelog.i')
def _phasecache(self):
return phases.phasecache(self, self._phasedefaults)
@storecache('obsstore')
def obsstore(self):
# read default format for new obsstore.
2015-06-26 01:50:27 +03:00
# developer config: format.obsstore-version
defaultformat = self.ui.configint('format', 'obsstore-version', None)
# rely on obsstore class default when possible.
kwargs = {}
if defaultformat is not None:
kwargs['defaultformat'] = defaultformat
readonly = not obsolete.isenabled(self, obsolete.createmarkersopt)
store = obsolete.obsstore(self.svfs, readonly=readonly,
**kwargs)
if store and readonly:
self.ui.warn(
_('obsolete feature not enabled but %i markers found!\n')
% len(list(store)))
return store
@storecache('00changelog.i')
2009-04-30 05:47:15 +04:00
def changelog(self):
c = changelog.changelog(self.svfs)
if 'HG_PENDING' in encoding.environ:
p = encoding.environ['HG_PENDING']
2009-04-30 05:47:15 +04:00
if p.startswith(self.root):
c.readpending('00changelog.i.a')
return c
def _constructmanifest(self):
# This is a temporary function while we migrate from manifest to
# manifestlog. It allows bundlerepo and unionrepo to intercept the
# manifest creation.
return manifest.manifestrevlog(self.svfs)
2009-04-30 05:47:15 +04:00
@storecache('00manifest.i')
def manifestlog(self):
return manifest.manifestlog(self.svfs, self)
@repofilecache('dirstate')
2009-04-30 05:47:15 +04:00
def dirstate(self):
return dirstate.dirstate(self.vfs, self.ui, self.root,
self._dirstatevalidate)
def _dirstatevalidate(self, node):
try:
self.changelog.rev(node)
return node
except error.LookupError:
if not self._dirstatevalidatewarned:
self._dirstatevalidatewarned = True
self.ui.warn(_("warning: ignoring unknown"
" working parent %s!\n") % short(node))
return nullid
2008-06-26 23:35:46 +04:00
def __getitem__(self, changeid):
if changeid is None or changeid == wdirrev:
2008-06-26 23:35:46 +04:00
return context.workingctx(self)
if isinstance(changeid, slice):
return [context.changectx(self, i)
for i in xrange(*changeid.indices(len(self)))
if i not in self.changelog.filteredrevs]
2008-06-26 23:35:46 +04:00
return context.changectx(self, changeid)
def __contains__(self, changeid):
try:
self[changeid]
return True
except error.RepoLookupError:
return False
def __nonzero__(self):
return True
def __len__(self):
return len(self.changelog)
def __iter__(self):
return iter(self.changelog)
2011-11-02 22:37:34 +04:00
def revs(self, expr, *args):
'''Find revisions matching a revset.
The revset is specified as a string ``expr`` that may contain
%-formatting to escape certain types. See ``revset.formatspec``.
Revset aliases from the configuration are not expanded. To expand
user aliases, consider calling ``scmutil.revrange()``.
Returns a revset.abstractsmartset, which is a list-like interface
that contains integer revisions.
'''
2011-11-02 22:37:34 +04:00
expr = revset.formatspec(expr, *args)
m = revset.match(None, expr)
return m(self)
2011-11-02 22:37:34 +04:00
def set(self, expr, *args):
'''Find revisions matching a revset and emit changectx instances.
This is a convenience wrapper around ``revs()`` that iterates the
result and is a generator of changectx instances.
Revset aliases from the configuration are not expanded. To expand
user aliases, consider calling ``scmutil.revrange()``.
'''
2011-11-02 22:37:34 +04:00
for r in self.revs(expr, *args):
yield self[r]
def url(self):
return 'file:' + self.root
def hook(self, name, throw=False, **args):
2014-07-12 21:52:58 +04:00
"""Call a hook, passing this repo instance.
This a convenience method to aid invoking hooks. Extensions likely
won't call this unless they have registered a custom hook or are
replacing code that is expected to call a hook.
"""
return hook.hook(self.ui, self, name, throw, **args)
@unfilteredmethod
def _tag(self, names, node, message, local, user, date, extra=None,
editor=False):
if isinstance(names, str):
names = (names,)
branches = self.branchmap()
for name in names:
self.hook('pretag', throw=True, node=hex(node), tag=name,
local=local)
if name in branches:
self.ui.warn(_("warning: tag %s conflicts with existing"
" branch name\n") % name)
def writetags(fp, names, munge, prevtags):
fp.seek(0, 2)
if prevtags and prevtags[-1] != '\n':
fp.write('\n')
for name in names:
if munge:
m = munge(name)
else:
m = name
2012-05-12 17:54:54 +04:00
if (self._tagscache.tagtypes and
name in self._tagscache.tagtypes):
old = self.tags().get(name, nullid)
fp.write('%s %s\n' % (hex(old), m))
fp.write('%s %s\n' % (hex(node), m))
fp.close()
prevtags = ''
if local:
try:
fp = self.vfs('localtags', 'r+')
2009-03-23 15:13:06 +03:00
except IOError:
fp = self.vfs('localtags', 'a')
else:
prevtags = fp.read()
# local tags are stored in the current charset
writetags(fp, names, None, prevtags)
for name in names:
self.hook('tag', node=hex(node), tag=name, local=local)
return
try:
fp = self.wfile('.hgtags', 'rb+')
except IOError as e:
if e.errno != errno.ENOENT:
raise
fp = self.wfile('.hgtags', 'ab')
else:
prevtags = fp.read()
# committed tags are stored in UTF-8
writetags(fp, names, encoding.fromlocal, prevtags)
fp.close()
self.invalidatecaches()
if '.hgtags' not in self.dirstate:
self[None].add(['.hgtags'])
m = matchmod.exact(self.root, '', ['.hgtags'])
tagnode = self.commit(message, user, date, extra=extra, match=m,
editor=editor)
for name in names:
self.hook('tag', node=hex(node), tag=name, local=local)
return tagnode
def tag(self, names, node, message, local, user, date, editor=False):
'''tag a revision with one or more symbolic names.
names is a list of strings or, when adding a single tag, names may be a
string.
2008-03-21 02:39:39 +03:00
if local is True, the tags are stored in a per-repository file.
otherwise, they are stored in the .hgtags file, and a new
changeset is committed with the change.
keyword arguments:
local: whether to store tags in non-version-controlled file
(default False)
message: commit message to use if committing
user: name of user to use if committing
date: date tuple to use if committing'''
if not local:
2014-10-03 03:38:10 +04:00
m = matchmod.exact(self.root, '', ['.hgtags'])
if any(self.status(match=m, unknown=True, ignored=True)):
raise error.Abort(_('working copy of .hgtags is changed'),
2014-10-03 03:39:57 +04:00
hint=_('please commit .hgtags manually'))
2009-03-03 04:19:09 +03:00
self.tags() # instantiate the cache
self._tag(names, node, message, local, user, date, editor=editor)
@filteredpropertycache
def _tagscache(self):
2012-05-12 17:54:54 +04:00
'''Returns a tagscache object that contains various tags related
caches.'''
# This simplifies its cache management by having one decorated
# function (this one) and the rest simply fetch things from it.
class tagscache(object):
def __init__(self):
# These two define the set of tags for this repository. tags
# maps tag name to node; tagtypes maps tag name to 'global' or
# 'local'. (Global tags are defined by .hgtags across all
# heads, and local tags are defined in .hg/localtags.)
# They constitute the in-memory cache of tags.
self.tags = self.tagtypes = None
self.nodetagscache = self.tagslist = None
cache = tagscache()
cache.tags, cache.tagtypes = self._findtags()
return cache
def tags(self):
'''return a mapping of tag to node'''
t = {}
if self.changelog.filteredrevs:
tags, tt = self._findtags()
else:
tags = self._tagscache.tags
for k, v in tags.iteritems():
try:
# ignore tags to unknown nodes
self.changelog.rev(v)
t[k] = v
except (error.LookupError, ValueError):
pass
return t
def _findtags(self):
'''Do the hard work of finding tags. Return a pair of dicts
(tags, tagtypes) where tags maps tag name to node, and tagtypes
maps tag name to a string like \'global\' or \'local\'.
Subclasses or extensions are free to add their own tags, but
should be aware that the returned dicts will be retained for the
duration of the localrepo object.'''
# XXX what tagtype should subclasses/extensions use? Currently
# mq and bookmarks add tags, but do not set the tagtype at all.
# Should each extension invent its own tag type? Should there
# be one tagtype for all such "virtual" tags? Or is the status
# quo fine?
alltags = {} # map tag name to (node, hist)
tagtypes = {}
tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
# Build the return dicts. Have to re-encode tag names because
# the tags module always uses UTF-8 (in order not to lose info
# writing to the cache), but the rest of Mercurial wants them in
# local encoding.
tags = {}
for (name, (node, hist)) in alltags.iteritems():
if node != nullid:
tags[encoding.tolocal(name)] = node
tags['tip'] = self.changelog.tip()
tagtypes = dict([(encoding.tolocal(name), value)
for (name, value) in tagtypes.iteritems()])
return (tags, tagtypes)
def tagtype(self, tagname):
'''
return the type of the given tag. result can be:
'local' : a local tag
'global' : a global tag
None : tag does not exist
'''
return self._tagscache.tagtypes.get(tagname)
def tagslist(self):
'''return a list of tags ordered by revision'''
if not self._tagscache.tagslist:
l = []
for t, n in self.tags().iteritems():
l.append((self.changelog.rev(n), t, n))
self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
return self._tagscache.tagslist
def nodetags(self, node):
'''return the tags associated with a node'''
if not self._tagscache.nodetagscache:
nodetagscache = {}
for t, n in self._tagscache.tags.iteritems():
nodetagscache.setdefault(n, []).append(t)
for tags in nodetagscache.itervalues():
tags.sort()
self._tagscache.nodetagscache = nodetagscache
return self._tagscache.nodetagscache.get(node, [])
def nodebookmarks(self, node):
2015-11-12 04:02:05 +03:00
"""return the list of bookmarks pointing to the specified node"""
marks = []
for bookmark, n in self._bookmarks.iteritems():
if n == node:
marks.append(bookmark)
return sorted(marks)
def branchmap(self):
'''returns a dictionary {branch: [branchheads]} with branchheads
ordered by increasing revision number'''
branchmap.updatecache(self)
return self._branchcaches[self.filtername]
@unfilteredmethod
def revbranchcache(self):
if not self._revbranchcache:
self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
return self._revbranchcache
def branchtip(self, branch, ignoremissing=False):
'''return the tip node for a given branch
If ignoremissing is True, then this method will not raise an error.
This is helpful for callers that only expect None for a missing branch
(e.g. namespace).
'''
try:
return self.branchmap().branchtip(branch)
except KeyError:
if not ignoremissing:
raise error.RepoLookupError(_("unknown branch '%s'") % branch)
else:
pass
localrepo: add branchtip() method for faster single-branch lookups For the PyPy repo with 744 branches and 843 branch heads, this brings hg log -r default over NFS from: CallCount Recursive Total(ms) Inline(ms) module:lineno(function) 3249 0 1.3222 1.3222 <open> 3244 0 0.6211 0.6211 <method 'close' of 'file' objects> 3243 0 0.0800 0.0800 <method 'read' of 'file' objects> 3241 0 0.0660 0.0660 <method 'seek' of 'file' objects> 3905 0 0.0476 0.0476 <zlib.decompress> 3281 0 2.6756 0.0472 mercurial.changelog:182(read) +3281 0 2.5256 0.0453 +mercurial.revlog:881(revision) +3276 0 0.0389 0.0196 +mercurial.changelog:28(decodeextra) +6562 0 0.0123 0.0123 +<method 'split' of 'str' objects> +6562 0 0.0408 0.0073 +mercurial.encoding:61(tolocal) +3281 0 0.0054 0.0054 +<method 'index' of 'str' objects> 3241 0 2.2464 0.0456 mercurial.revlog:818(_loadchunk) +3241 0 0.6205 0.6205 +<method 'close' of 'file' objects> +3241 0 0.0765 0.0765 +<method 'read' of 'file' objects> +3241 0 0.0660 0.0660 +<method 'seek' of 'file' objects> +3241 0 1.4209 0.0135 +mercurial.store:374(__call__) +3241 0 0.0122 0.0107 +mercurial.revlog:810(_addchunk) 3281 0 2.5256 0.0453 mercurial.revlog:881(revision) +3280 0 0.0175 0.0175 +mercurial.revlog:305(rev) +3281 0 2.2819 0.0119 +mercurial.revlog:847(_chunkraw) +3281 0 0.0603 0.0083 +mercurial.revlog:945(_checkhash) +3281 0 0.0051 0.0051 +mercurial.revlog:349(flags) +3281 0 0.0040 0.0040 +<mercurial.mpatch.patches> 13682 0 0.0479 0.0248 <method 'decode' of 'str' objects> +7418 0 0.0228 0.0076 +encodings.utf_8:15(decode) +1 0 0.0003 0.0000 +encodings:71(search_function) 3248 0 1.3995 0.0246 mercurial.scmutil:218(__call__) +3248 0 1.3222 1.3222 +<open> +3248 0 0.0235 0.0184 +os.path:80(split) +3248 0 0.0084 0.0068 +mercurial.scmutil:92(__call__) Time: real 2.750 secs (user 0.680+0.000 sys 0.360+0.000) down to: CallCount Recursive Total(ms) Inline(ms) module:lineno(function) 55 31 0.0197 0.0163 <__import__> +1 0 0.0006 0.0002 +mercurial.context:8(<module>) +1 0 0.0042 0.0001 +mercurial.revlog:12(<module>) +1 0 0.0002 0.0001 +mercurial.match:8(<module>) +1 0 0.0003 0.0001 +mercurial.dirstate:7(<module>) +1 0 0.0057 0.0001 +mercurial.changelog:8(<module>) 1 0 0.0117 0.0032 mercurial.localrepo:525(_readbranchcache) +844 0 0.0015 0.0015 +<binascii.unhexlify> +845 0 0.0010 0.0010 +<method 'split' of 'str' objects> +843 0 0.0045 0.0009 +mercurial.encoding:61(tolocal) +843 0 0.0004 0.0004 +<method 'setdefault' of 'dict' objects> +1 0 0.0003 0.0003 +<method 'close' of 'file' objects> 3 0 0.0029 0.0029 <method 'read' of 'file' objects> 9 0 0.0018 0.0018 <open> 990 0 0.0017 0.0017 <binascii.unhexlify> 53 0 0.0016 0.0016 mercurial.demandimport:43(__init__) 862 0 0.0015 0.0015 <_codecs.utf_8_decode> 862 0 0.0037 0.0014 <method 'decode' of 'str' objects> +862 0 0.0023 0.0008 +encodings.utf_8:15(decode) 981 0 0.0011 0.0011 <method 'split' of 'str' objects> 861 0 0.0046 0.0009 mercurial.encoding:61(tolocal) +861 0 0.0037 0.0014 +<method 'decode' of 'str' objects> 862 0 0.0023 0.0008 encodings.utf_8:15(decode) +862 0 0.0015 0.0015 +<_codecs.utf_8_decode> 4 0 0.0008 0.0008 <method 'close' of 'file' objects> 179 154 0.0202 0.0004 mercurial.demandimport:83(__getattribute__) +36 11 0.0199 0.0003 +mercurial.demandimport:55(_load) +72 0 0.0001 0.0001 +mercurial.demandimport:83(__getattribute__) +36 0 0.0000 0.0000 +<getattr> 1 0 0.0015 0.0004 mercurial.tags:148(_readtagcache) Time: real 0.060 secs (user 0.030+0.000 sys 0.010+0.000)
2012-05-13 16:04:04 +04:00
def lookup(self, key):
return self[key].node()
def lookupbranch(self, key, remote=None):
repo = remote or self
if key in repo.branchmap():
return key
repo = (remote and remote.local()) and remote or self
return repo[key].branch()
def known(self, nodes):
cl = self.changelog
nm = cl.nodemap
filtered = cl.filteredrevs
result = []
for n in nodes:
r = nm.get(n)
resp = not (r is None or r in filtered)
result.append(resp)
return result
def local(self):
return self
def publishing(self):
# it's safe (and desirable) to trust the publish flag unconditionally
# so that we don't finalize changes shared between users via ssh or nfs
return self.ui.configbool('phases', 'publish', True, untrusted=True)
def cancopy(self):
# so statichttprepo's override of local() works
if not self.local():
return False
2015-06-18 23:34:22 +03:00
if not self.publishing():
return True
# if publishing we can't copy if there is filtered content
return not self.filtered('visible').changelog.filteredrevs
def shared(self):
'''the type of shared repository (None if not shared)'''
if self.sharedpath != self.path:
return 'store'
return None
def join(self, f, *insidef):
return self.vfs.join(os.path.join(f, *insidef))
def wjoin(self, f, *insidef):
return self.vfs.reljoin(self.root, f, *insidef)
def file(self, f):
if f[0] == '/':
f = f[1:]
return filelog.filelog(self.svfs, f)
def changectx(self, changeid):
2008-06-26 23:35:46 +04:00
return self[changeid]
def setparents(self, p1, p2=nullid):
self.dirstate.beginparentchange()
copies = self.dirstate.setparents(p1, p2)
pctx = self[p1]
if copies:
# Adjust copy records, the dirstate cannot do it, it
# requires access to parents manifests. Preserve them
# only for entries added to first parent.
for f in copies:
if f not in pctx and copies[f] in pctx:
self.dirstate.copy(copies[f], f)
if p2 == nullid:
for f, s in sorted(self.dirstate.copies().items()):
if f not in pctx and s not in pctx:
self.dirstate.copy(None, f)
self.dirstate.endparentchange()
def filectx(self, path, changeid=None, fileid=None):
"""changeid can be a changeset revision, node, or tag.
fileid can be a file revision or node."""
return context.filectx(self, path, changeid, fileid)
def getcwd(self):
return self.dirstate.getcwd()
def pathto(self, f, cwd=None):
return self.dirstate.pathto(f, cwd)
def wfile(self, f, mode='r'):
return self.wvfs(f, mode)
def _link(self, f):
return self.wvfs.islink(f)
def _loadfilter(self, filter):
2006-12-30 05:04:31 +03:00
if filter not in self.filterpats:
2005-09-15 11:59:16 +04:00
l = []
2006-12-30 05:04:31 +03:00
for pat, cmd in self.ui.configitems(filter):
if cmd == '!':
continue
mf = matchmod.match(self.root, '', [pat])
fn = None
params = cmd
for name, filterfn in self._datafilters.iteritems():
if cmd.startswith(name):
fn = filterfn
params = cmd[len(name):].lstrip()
break
if not fn:
fn = lambda s, c, **kwargs: util.filter(s, c)
# Wrap old filters not supporting keyword arguments
if not inspect.getargspec(fn)[2]:
oldfn = fn
fn = lambda s, c, **kwargs: oldfn(s, c)
l.append((mf, fn, params))
2006-12-30 05:04:31 +03:00
self.filterpats[filter] = l
return self.filterpats[filter]
2005-09-15 11:59:16 +04:00
def _filter(self, filterpats, filename, data):
for mf, fn, cmd in filterpats:
2005-09-15 11:59:16 +04:00
if mf(filename):
self.ui.debug("filtering %s through %s\n" % (filename, cmd))
data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
2005-09-15 11:59:16 +04:00
break
return data
@unfilteredpropertycache
def _encodefilterpats(self):
return self._loadfilter('encode')
@unfilteredpropertycache
def _decodefilterpats(self):
return self._loadfilter('decode')
def adddatafilter(self, name, filter):
self._datafilters[name] = filter
2006-12-30 05:04:31 +03:00
def wread(self, filename):
if self._link(filename):
data = self.wvfs.readlink(filename)
2006-12-30 05:04:31 +03:00
else:
data = self.wvfs.read(filename)
return self._filter(self._encodefilterpats, filename, data)
2005-09-15 11:59:16 +04:00
def wwrite(self, filename, data, flags, backgroundclose=False):
"""write ``data`` into ``filename`` in the working directory
This returns length of written (maybe decoded) data.
"""
data = self._filter(self._decodefilterpats, filename, data)
if 'l' in flags:
self.wvfs.symlink(data, filename)
else:
self.wvfs.write(filename, data, backgroundclose=backgroundclose)
if 'x' in flags:
self.wvfs.setflags(filename, False, True)
return len(data)
def wwritedata(self, filename, data):
return self._filter(self._decodefilterpats, filename, data)
def currenttransaction(self):
"""return the current transaction or None if non exists"""
if self._transref:
tr = self._transref()
else:
tr = None
if tr and tr.running():
return tr
return None
def transaction(self, desc, report=None):
if (self.ui.configbool('devel', 'all-warnings')
or self.ui.configbool('devel', 'check-locks')):
if self._currentlock(self._lockref) is None:
raise error.ProgrammingError('transaction requires locking')
tr = self.currenttransaction()
if tr is not None:
return tr.nest()
# abort here if the journal already exists
if self.svfs.exists("journal"):
2010-01-25 09:05:27 +03:00
raise error.RepoError(
_("abandoned transaction found"),
hint=_("run 'hg recover' to clean up transaction"))
idbase = "%.40f#%f" % (random.random(), time.time())
txnid = 'TXN:' + hashlib.sha1(idbase).hexdigest()
self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
self._writejournal(desc)
renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
if report:
rp = report
else:
rp = self.ui.warn
vfsmap = {'plain': self.vfs} # root of .hg/
# we must avoid cyclic reference between repo and transaction.
reporef = weakref.ref(self)
def validate(tr):
"""will run pre-closing hooks"""
reporef().hook('pretxnclose', throw=True,
txnname=desc, **tr.hookargs)
def releasefn(tr, success):
repo = reporef()
if success:
# this should be explicitly invoked here, because
# in-memory changes aren't written out at closing
# transaction, if tr.addfilegenerator (via
# dirstate.write or so) isn't invoked while
# transaction running
repo.dirstate.write(None)
else:
# discard all changes (including ones already written
# out) in this transaction
repo.dirstate.restorebackup(None, prefix='journal.')
localrepo: discard objects in _filecache at transaction failure (issue4876) 'repo.invalidate()' deletes 'filecache'-ed properties by 'filecache.__delete__()' below via 'delattr(unfiltered, k)'. But cached objects are still kept in 'repo._filecache'. def __delete__(self, obj): try: del obj.__dict__[self.name] except KeyError: raise AttributeError(self.name) If 'repo' object is reused even after failure of command execution, referring 'filecache'-ed property may reuse one kept in 'repo._filecache', even if reloading from a file is expected. Executing command sequence on command server is a typical case of this situation (e0a0f9ad3e4c also tried to fix this issue). For example: 1. start a command execution 2. 'changelog.delayupdate()' is invoked in a transaction scope This replaces own 'opener' by '_divertopener()' for additional accessing to '00changelog.i.a' (aka "pending file"). 3. transaction is aborted, and command (1) execution is ended After 'repo.invalidate()' at releasing store lock, changelog object above (= 'opener' of it is still replaced) is deleted from 'repo.__dict__', but still kept in 'repo._filecache'. 4. start next command execution with same 'repo' 5. referring 'repo.changelog' may reuse changelog object kept in 'repo._filecache' according to timestamp of '00changelog.i' '00changelog.i' is truncated at transaction failure (even though this truncation is unintentional one, as described later), and 'st_mtime' of it is changed. But 'st_mtime' doesn't have enough resolution to always detect this truncation, and invalid changelog object kept in 'repo._filecache' is reused occasionally. Then, "No such file or directory" error occurs for '00changelog.i.a', which is already removed at (3). This patch discards objects in '_filecache' other than dirstate at transaction failure. Changes in 'invalidate()' can't be simplified by 'self._filecache = {}', because 'invalidate()' should keep dirstate in 'self._filecache' 'repo.invalidate()' at "hg qpush" failure is removed in this patch, because now it is redundant. This patch doesn't make 'repo.invalidate()' always discard objects in '_filecache', because 'repo.invalidate()' is invoked also at unlocking store lock. - "always discard objects in filecache at unlocking" may cause serious performance problem for subsequent procedures at normal execution - but it is impossible to "discard objects in filecache at unlocking only at failure", because 'releasefn' of lock can't know whether a lock scope is terminated normally or not BTW, using "with" statement described in PEP343 for lock may resolve this ? After this patch, truncation of '00changelog.i' still occurs at transaction failure, even though newly added revisions exist only in '00changelog.i.a' and size of '00changelog.i' isn't changed by this truncation. Updating 'st_mtime' of '00changelog.i' implied by this redundant truncation also affects cache behavior as described above. This will be fixed by dropping '00changelog.i' at aborting from the list of files to be truncated in transaction.
2015-10-24 12:58:57 +03:00
repo.invalidate(clearfilecache=True)
tr = transaction.transaction(rp, self.svfs, vfsmap,
"journal",
"undo",
aftertrans(renames),
self.store.createmode,
validator=validate,
releasefn=releasefn)
tr.hookargs['txnid'] = txnid
# note: writing the fncache only during finalize mean that the file is
# outdated when running hooks. As fncache is used for streaming clone,
# this is not expected to break anything that happen during the hooks.
tr.addfinalize('flush-fncache', self.store.write)
def txnclosehook(tr2):
"""To be run if transaction is successful, will schedule a hook run
"""
# Don't reference tr2 in hook() so we don't hold a reference.
# This reduces memory consumption when there are multiple
# transactions per lock. This can likely go away if issue5045
# fixes the function accumulation.
hookargs = tr2.hookargs
def hook():
reporef().hook('txnclose', throw=False, txnname=desc,
**hookargs)
reporef()._afterlock(hook)
tr.addfinalize('txnclose-hook', txnclosehook)
def txnaborthook(tr2):
"""To be run if transaction is aborted
"""
reporef().hook('txnabort', throw=False, txnname=desc,
**tr2.hookargs)
tr.addabort('txnabort-hook', txnaborthook)
# avoid eager cache invalidation. in-memory data should be identical
# to stored data if transaction has no error.
tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
self._transref = weakref.ref(tr)
return tr
def _journalfiles(self):
return ((self.svfs, 'journal'),
(self.vfs, 'journal.dirstate'),
(self.vfs, 'journal.branch'),
(self.vfs, 'journal.desc'),
(self.vfs, 'journal.bookmarks'),
(self.svfs, 'journal.phaseroots'))
def undofiles(self):
return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
def _writejournal(self, desc):
self.dirstate.savebackup(None, prefix='journal.')
self.vfs.write("journal.branch",
encoding.fromlocal(self.dirstate.branch()))
self.vfs.write("journal.desc",
"%d\n%s\n" % (len(self), desc))
self.vfs.write("journal.bookmarks",
self.vfs.tryread("bookmarks"))
self.svfs.write("journal.phaseroots",
self.svfs.tryread("phaseroots"))
def recover(self):
with self.lock():
if self.svfs.exists("journal"):
self.ui.status(_("rolling back interrupted transaction\n"))
vfsmap = {'': self.svfs,
'plain': self.vfs,}
transaction.rollback(self.svfs, vfsmap, "journal",
2010-01-25 09:05:27 +03:00
self.ui.warn)
self.invalidate()
return True
else:
self.ui.warn(_("no interrupted transaction available\n"))
return False
def rollback(self, dryrun=False, force=False):
localrepo: restore dirstate to one before rollbacking if not parent-gone 'localrepository.rollback()' explicilty restores dirstate, only if at least one of current parents of the working directory is removed at rollbacking (a.k.a "parent-gone"). After DirstateTransactionPlan, 'dirstate.write()' will cause marking '.hg/dirstate' as a file to be restored at rollbacking. https://mercurial.selenic.com/wiki/DirstateTransactionPlan Then, 'transaction.rollback()' restores '.hg/dirstate' regardless of parents of the working directory at that time, and this causes unexpected dirstate changes if not "parent-gone" (e.g. "hg update" to another branch after "hg commit" or so, then "hg rollback"). To avoid such situation, this patch restores dirstate to one before rollbacking if not "parent-gone". before: b1. restore dirstate explicitly, if "parent-gone" after: a1. save dirstate before actual rollbacking via dirstateguard a2. restore dirstate via 'transaction.rollback()' a3. if "parent-gone" - discard backup (a1) - restore dirstate from 'undo.dirstate' a4. otherwise, restore dirstate from backup (a1) Even though restoring dirstate at (a3) after (a2) seems redundant, this patch keeps this existing code path, because: - it isn't ensured that 'dirstate.write()' was invoked at least once while transaction running If not, '.hg/dirstate' isn't restored at (a2). In addition to it, rude 3rd party extension invoking 'dirstate.write()' without 'repo' while transaction running (see subsequent patches for detail) may break consistency of a file backup-ed by transaction. - this patch mainly focuses on changes for DirstateTransactionPlan Restoring dirstate at (a3) itself should be cheaper enough than rollbacking itself. Redundancy will be removed in next step. Newly added test is almost meaningless at this point. It will be used to detect regression while implementing delayed dirstate write out.
2015-10-13 22:25:43 +03:00
wlock = lock = dsguard = None
try:
wlock = self.wlock()
lock = self.lock()
if self.svfs.exists("undo"):
dsguard = dirstateguard.dirstateguard(self, 'rollback')
localrepo: restore dirstate to one before rollbacking if not parent-gone 'localrepository.rollback()' explicilty restores dirstate, only if at least one of current parents of the working directory is removed at rollbacking (a.k.a "parent-gone"). After DirstateTransactionPlan, 'dirstate.write()' will cause marking '.hg/dirstate' as a file to be restored at rollbacking. https://mercurial.selenic.com/wiki/DirstateTransactionPlan Then, 'transaction.rollback()' restores '.hg/dirstate' regardless of parents of the working directory at that time, and this causes unexpected dirstate changes if not "parent-gone" (e.g. "hg update" to another branch after "hg commit" or so, then "hg rollback"). To avoid such situation, this patch restores dirstate to one before rollbacking if not "parent-gone". before: b1. restore dirstate explicitly, if "parent-gone" after: a1. save dirstate before actual rollbacking via dirstateguard a2. restore dirstate via 'transaction.rollback()' a3. if "parent-gone" - discard backup (a1) - restore dirstate from 'undo.dirstate' a4. otherwise, restore dirstate from backup (a1) Even though restoring dirstate at (a3) after (a2) seems redundant, this patch keeps this existing code path, because: - it isn't ensured that 'dirstate.write()' was invoked at least once while transaction running If not, '.hg/dirstate' isn't restored at (a2). In addition to it, rude 3rd party extension invoking 'dirstate.write()' without 'repo' while transaction running (see subsequent patches for detail) may break consistency of a file backup-ed by transaction. - this patch mainly focuses on changes for DirstateTransactionPlan Restoring dirstate at (a3) itself should be cheaper enough than rollbacking itself. Redundancy will be removed in next step. Newly added test is almost meaningless at this point. It will be used to detect regression while implementing delayed dirstate write out.
2015-10-13 22:25:43 +03:00
return self._rollback(dryrun, force, dsguard)
else:
self.ui.warn(_("no rollback information available\n"))
return 1
finally:
localrepo: restore dirstate to one before rollbacking if not parent-gone 'localrepository.rollback()' explicilty restores dirstate, only if at least one of current parents of the working directory is removed at rollbacking (a.k.a "parent-gone"). After DirstateTransactionPlan, 'dirstate.write()' will cause marking '.hg/dirstate' as a file to be restored at rollbacking. https://mercurial.selenic.com/wiki/DirstateTransactionPlan Then, 'transaction.rollback()' restores '.hg/dirstate' regardless of parents of the working directory at that time, and this causes unexpected dirstate changes if not "parent-gone" (e.g. "hg update" to another branch after "hg commit" or so, then "hg rollback"). To avoid such situation, this patch restores dirstate to one before rollbacking if not "parent-gone". before: b1. restore dirstate explicitly, if "parent-gone" after: a1. save dirstate before actual rollbacking via dirstateguard a2. restore dirstate via 'transaction.rollback()' a3. if "parent-gone" - discard backup (a1) - restore dirstate from 'undo.dirstate' a4. otherwise, restore dirstate from backup (a1) Even though restoring dirstate at (a3) after (a2) seems redundant, this patch keeps this existing code path, because: - it isn't ensured that 'dirstate.write()' was invoked at least once while transaction running If not, '.hg/dirstate' isn't restored at (a2). In addition to it, rude 3rd party extension invoking 'dirstate.write()' without 'repo' while transaction running (see subsequent patches for detail) may break consistency of a file backup-ed by transaction. - this patch mainly focuses on changes for DirstateTransactionPlan Restoring dirstate at (a3) itself should be cheaper enough than rollbacking itself. Redundancy will be removed in next step. Newly added test is almost meaningless at this point. It will be used to detect regression while implementing delayed dirstate write out.
2015-10-13 22:25:43 +03:00
release(dsguard, lock, wlock)
@unfilteredmethod # Until we get smarter cache management
localrepo: restore dirstate to one before rollbacking if not parent-gone 'localrepository.rollback()' explicilty restores dirstate, only if at least one of current parents of the working directory is removed at rollbacking (a.k.a "parent-gone"). After DirstateTransactionPlan, 'dirstate.write()' will cause marking '.hg/dirstate' as a file to be restored at rollbacking. https://mercurial.selenic.com/wiki/DirstateTransactionPlan Then, 'transaction.rollback()' restores '.hg/dirstate' regardless of parents of the working directory at that time, and this causes unexpected dirstate changes if not "parent-gone" (e.g. "hg update" to another branch after "hg commit" or so, then "hg rollback"). To avoid such situation, this patch restores dirstate to one before rollbacking if not "parent-gone". before: b1. restore dirstate explicitly, if "parent-gone" after: a1. save dirstate before actual rollbacking via dirstateguard a2. restore dirstate via 'transaction.rollback()' a3. if "parent-gone" - discard backup (a1) - restore dirstate from 'undo.dirstate' a4. otherwise, restore dirstate from backup (a1) Even though restoring dirstate at (a3) after (a2) seems redundant, this patch keeps this existing code path, because: - it isn't ensured that 'dirstate.write()' was invoked at least once while transaction running If not, '.hg/dirstate' isn't restored at (a2). In addition to it, rude 3rd party extension invoking 'dirstate.write()' without 'repo' while transaction running (see subsequent patches for detail) may break consistency of a file backup-ed by transaction. - this patch mainly focuses on changes for DirstateTransactionPlan Restoring dirstate at (a3) itself should be cheaper enough than rollbacking itself. Redundancy will be removed in next step. Newly added test is almost meaningless at this point. It will be used to detect regression while implementing delayed dirstate write out.
2015-10-13 22:25:43 +03:00
def _rollback(self, dryrun, force, dsguard):
ui = self.ui
try:
args = self.vfs.read('undo.desc').splitlines()
(oldlen, desc, detail) = (int(args[0]), args[1], None)
if len(args) >= 3:
detail = args[2]
oldtip = oldlen - 1
if detail and ui.verbose:
msg = (_('repository tip rolled back to revision %s'
' (undo %s: %s)\n')
% (oldtip, desc, detail))
else:
msg = (_('repository tip rolled back to revision %s'
' (undo %s)\n')
% (oldtip, desc))
except IOError:
msg = _('rolling back unknown transaction\n')
desc = None
if not force and self['.'] != self['tip'] and desc == 'commit':
raise error.Abort(
_('rollback of last commit while not checked out '
2011-10-02 01:18:51 +04:00
'may lose data'), hint=_('use -f to force'))
ui.status(msg)
if dryrun:
return 0
parents = self.dirstate.parents()
self.destroying()
vfsmap = {'plain': self.vfs, '': self.svfs}
transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn)
if self.vfs.exists('undo.bookmarks'):
self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
if self.svfs.exists('undo.phaseroots'):
self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
self.invalidate()
parentgone = (parents[0] not in self.changelog.nodemap or
parents[1] not in self.changelog.nodemap)
if parentgone:
localrepo: restore dirstate to one before rollbacking if not parent-gone 'localrepository.rollback()' explicilty restores dirstate, only if at least one of current parents of the working directory is removed at rollbacking (a.k.a "parent-gone"). After DirstateTransactionPlan, 'dirstate.write()' will cause marking '.hg/dirstate' as a file to be restored at rollbacking. https://mercurial.selenic.com/wiki/DirstateTransactionPlan Then, 'transaction.rollback()' restores '.hg/dirstate' regardless of parents of the working directory at that time, and this causes unexpected dirstate changes if not "parent-gone" (e.g. "hg update" to another branch after "hg commit" or so, then "hg rollback"). To avoid such situation, this patch restores dirstate to one before rollbacking if not "parent-gone". before: b1. restore dirstate explicitly, if "parent-gone" after: a1. save dirstate before actual rollbacking via dirstateguard a2. restore dirstate via 'transaction.rollback()' a3. if "parent-gone" - discard backup (a1) - restore dirstate from 'undo.dirstate' a4. otherwise, restore dirstate from backup (a1) Even though restoring dirstate at (a3) after (a2) seems redundant, this patch keeps this existing code path, because: - it isn't ensured that 'dirstate.write()' was invoked at least once while transaction running If not, '.hg/dirstate' isn't restored at (a2). In addition to it, rude 3rd party extension invoking 'dirstate.write()' without 'repo' while transaction running (see subsequent patches for detail) may break consistency of a file backup-ed by transaction. - this patch mainly focuses on changes for DirstateTransactionPlan Restoring dirstate at (a3) itself should be cheaper enough than rollbacking itself. Redundancy will be removed in next step. Newly added test is almost meaningless at this point. It will be used to detect regression while implementing delayed dirstate write out.
2015-10-13 22:25:43 +03:00
# prevent dirstateguard from overwriting already restored one
dsguard.close()
self.dirstate.restorebackup(None, prefix='undo.')
try:
branch = self.vfs.read('undo.branch')
self.dirstate.setbranch(encoding.tolocal(branch))
except IOError:
ui.warn(_('named branch could not be reset: '
'current branch is still \'%s\'\n')
% self.dirstate.branch())
parents = tuple([p.rev() for p in self[None].parents()])
if len(parents) > 1:
ui.status(_('working directory now based on '
'revisions %d and %d\n') % parents)
else:
ui.status(_('working directory now based on '
'revision %d\n') % parents)
mergemod.mergestate.clean(self, self['.'].node())
# TODO: if we know which new heads may result from this rollback, pass
# them to destroy(), which will prevent the branchhead cache from being
# invalidated.
self.destroyed()
return 0
def invalidatecaches(self):
if '_tagscache' in vars(self):
# can't use delattr on proxy
del self.__dict__['_tagscache']
self.unfiltered()._branchcaches.clear()
self.invalidatevolatilesets()
def invalidatevolatilesets(self):
self.filteredrevcache.clear()
obsolete.clearobscaches(self)
def invalidatedirstate(self):
'''Invalidates the dirstate, causing the next call to dirstate
to check if it was modified since the last time it was read,
rereading it if it has.
This is different to dirstate.invalidate() that it doesn't always
rereads the dirstate. Use dirstate.invalidate() if you want to
explicitly read the dirstate again (i.e. restoring it to a previous
known good state).'''
if hasunfilteredcache(self, 'dirstate'):
2012-03-01 19:39:58 +04:00
for k in self.dirstate._filecache:
try:
delattr(self.dirstate, k)
except AttributeError:
pass
delattr(self.unfiltered(), 'dirstate')
localrepo: discard objects in _filecache at transaction failure (issue4876) 'repo.invalidate()' deletes 'filecache'-ed properties by 'filecache.__delete__()' below via 'delattr(unfiltered, k)'. But cached objects are still kept in 'repo._filecache'. def __delete__(self, obj): try: del obj.__dict__[self.name] except KeyError: raise AttributeError(self.name) If 'repo' object is reused even after failure of command execution, referring 'filecache'-ed property may reuse one kept in 'repo._filecache', even if reloading from a file is expected. Executing command sequence on command server is a typical case of this situation (e0a0f9ad3e4c also tried to fix this issue). For example: 1. start a command execution 2. 'changelog.delayupdate()' is invoked in a transaction scope This replaces own 'opener' by '_divertopener()' for additional accessing to '00changelog.i.a' (aka "pending file"). 3. transaction is aborted, and command (1) execution is ended After 'repo.invalidate()' at releasing store lock, changelog object above (= 'opener' of it is still replaced) is deleted from 'repo.__dict__', but still kept in 'repo._filecache'. 4. start next command execution with same 'repo' 5. referring 'repo.changelog' may reuse changelog object kept in 'repo._filecache' according to timestamp of '00changelog.i' '00changelog.i' is truncated at transaction failure (even though this truncation is unintentional one, as described later), and 'st_mtime' of it is changed. But 'st_mtime' doesn't have enough resolution to always detect this truncation, and invalid changelog object kept in 'repo._filecache' is reused occasionally. Then, "No such file or directory" error occurs for '00changelog.i.a', which is already removed at (3). This patch discards objects in '_filecache' other than dirstate at transaction failure. Changes in 'invalidate()' can't be simplified by 'self._filecache = {}', because 'invalidate()' should keep dirstate in 'self._filecache' 'repo.invalidate()' at "hg qpush" failure is removed in this patch, because now it is redundant. This patch doesn't make 'repo.invalidate()' always discard objects in '_filecache', because 'repo.invalidate()' is invoked also at unlocking store lock. - "always discard objects in filecache at unlocking" may cause serious performance problem for subsequent procedures at normal execution - but it is impossible to "discard objects in filecache at unlocking only at failure", because 'releasefn' of lock can't know whether a lock scope is terminated normally or not BTW, using "with" statement described in PEP343 for lock may resolve this ? After this patch, truncation of '00changelog.i' still occurs at transaction failure, even though newly added revisions exist only in '00changelog.i.a' and size of '00changelog.i' isn't changed by this truncation. Updating 'st_mtime' of '00changelog.i' implied by this redundant truncation also affects cache behavior as described above. This will be fixed by dropping '00changelog.i' at aborting from the list of files to be truncated in transaction.
2015-10-24 12:58:57 +03:00
def invalidate(self, clearfilecache=False):
'''Invalidates both store and non-store parts other than dirstate
If a transaction is running, invalidation of store is omitted,
because discarding in-memory changes might cause inconsistency
(e.g. incomplete fncache causes unintentional failure, but
redundant one doesn't).
'''
unfiltered = self.unfiltered() # all file caches are stored unfiltered
localrepo: discard objects in _filecache at transaction failure (issue4876) 'repo.invalidate()' deletes 'filecache'-ed properties by 'filecache.__delete__()' below via 'delattr(unfiltered, k)'. But cached objects are still kept in 'repo._filecache'. def __delete__(self, obj): try: del obj.__dict__[self.name] except KeyError: raise AttributeError(self.name) If 'repo' object is reused even after failure of command execution, referring 'filecache'-ed property may reuse one kept in 'repo._filecache', even if reloading from a file is expected. Executing command sequence on command server is a typical case of this situation (e0a0f9ad3e4c also tried to fix this issue). For example: 1. start a command execution 2. 'changelog.delayupdate()' is invoked in a transaction scope This replaces own 'opener' by '_divertopener()' for additional accessing to '00changelog.i.a' (aka "pending file"). 3. transaction is aborted, and command (1) execution is ended After 'repo.invalidate()' at releasing store lock, changelog object above (= 'opener' of it is still replaced) is deleted from 'repo.__dict__', but still kept in 'repo._filecache'. 4. start next command execution with same 'repo' 5. referring 'repo.changelog' may reuse changelog object kept in 'repo._filecache' according to timestamp of '00changelog.i' '00changelog.i' is truncated at transaction failure (even though this truncation is unintentional one, as described later), and 'st_mtime' of it is changed. But 'st_mtime' doesn't have enough resolution to always detect this truncation, and invalid changelog object kept in 'repo._filecache' is reused occasionally. Then, "No such file or directory" error occurs for '00changelog.i.a', which is already removed at (3). This patch discards objects in '_filecache' other than dirstate at transaction failure. Changes in 'invalidate()' can't be simplified by 'self._filecache = {}', because 'invalidate()' should keep dirstate in 'self._filecache' 'repo.invalidate()' at "hg qpush" failure is removed in this patch, because now it is redundant. This patch doesn't make 'repo.invalidate()' always discard objects in '_filecache', because 'repo.invalidate()' is invoked also at unlocking store lock. - "always discard objects in filecache at unlocking" may cause serious performance problem for subsequent procedures at normal execution - but it is impossible to "discard objects in filecache at unlocking only at failure", because 'releasefn' of lock can't know whether a lock scope is terminated normally or not BTW, using "with" statement described in PEP343 for lock may resolve this ? After this patch, truncation of '00changelog.i' still occurs at transaction failure, even though newly added revisions exist only in '00changelog.i.a' and size of '00changelog.i' isn't changed by this truncation. Updating 'st_mtime' of '00changelog.i' implied by this redundant truncation also affects cache behavior as described above. This will be fixed by dropping '00changelog.i' at aborting from the list of files to be truncated in transaction.
2015-10-24 12:58:57 +03:00
for k in self._filecache.keys():
# dirstate is invalidated separately in invalidatedirstate()
if k == 'dirstate':
continue
localrepo: discard objects in _filecache at transaction failure (issue4876) 'repo.invalidate()' deletes 'filecache'-ed properties by 'filecache.__delete__()' below via 'delattr(unfiltered, k)'. But cached objects are still kept in 'repo._filecache'. def __delete__(self, obj): try: del obj.__dict__[self.name] except KeyError: raise AttributeError(self.name) If 'repo' object is reused even after failure of command execution, referring 'filecache'-ed property may reuse one kept in 'repo._filecache', even if reloading from a file is expected. Executing command sequence on command server is a typical case of this situation (e0a0f9ad3e4c also tried to fix this issue). For example: 1. start a command execution 2. 'changelog.delayupdate()' is invoked in a transaction scope This replaces own 'opener' by '_divertopener()' for additional accessing to '00changelog.i.a' (aka "pending file"). 3. transaction is aborted, and command (1) execution is ended After 'repo.invalidate()' at releasing store lock, changelog object above (= 'opener' of it is still replaced) is deleted from 'repo.__dict__', but still kept in 'repo._filecache'. 4. start next command execution with same 'repo' 5. referring 'repo.changelog' may reuse changelog object kept in 'repo._filecache' according to timestamp of '00changelog.i' '00changelog.i' is truncated at transaction failure (even though this truncation is unintentional one, as described later), and 'st_mtime' of it is changed. But 'st_mtime' doesn't have enough resolution to always detect this truncation, and invalid changelog object kept in 'repo._filecache' is reused occasionally. Then, "No such file or directory" error occurs for '00changelog.i.a', which is already removed at (3). This patch discards objects in '_filecache' other than dirstate at transaction failure. Changes in 'invalidate()' can't be simplified by 'self._filecache = {}', because 'invalidate()' should keep dirstate in 'self._filecache' 'repo.invalidate()' at "hg qpush" failure is removed in this patch, because now it is redundant. This patch doesn't make 'repo.invalidate()' always discard objects in '_filecache', because 'repo.invalidate()' is invoked also at unlocking store lock. - "always discard objects in filecache at unlocking" may cause serious performance problem for subsequent procedures at normal execution - but it is impossible to "discard objects in filecache at unlocking only at failure", because 'releasefn' of lock can't know whether a lock scope is terminated normally or not BTW, using "with" statement described in PEP343 for lock may resolve this ? After this patch, truncation of '00changelog.i' still occurs at transaction failure, even though newly added revisions exist only in '00changelog.i.a' and size of '00changelog.i' isn't changed by this truncation. Updating 'st_mtime' of '00changelog.i' implied by this redundant truncation also affects cache behavior as described above. This will be fixed by dropping '00changelog.i' at aborting from the list of files to be truncated in transaction.
2015-10-24 12:58:57 +03:00
if clearfilecache:
del self._filecache[k]
try:
delattr(unfiltered, k)
except AttributeError:
pass
self.invalidatecaches()
if not self.currenttransaction():
# TODO: Changing contents of store outside transaction
# causes inconsistency. We should make in-memory store
# changes detectable, and abort if changed.
self.store.invalidatecaches()
def invalidateall(self):
'''Fully invalidates both store and non-store parts, causing the
subsequent operation to reread any outside changes.'''
# extension should hook this to invalidate its caches
self.invalidate()
self.invalidatedirstate()
@unfilteredmethod
def _refreshfilecachestats(self, tr):
"""Reload stats of cached files so that they are flagged as valid"""
for k, ce in self._filecache.items():
if k == 'dirstate' or k not in self.__dict__:
continue
ce.refresh()
def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
inheritchecker=None, parentenvvar=None):
parentlock = None
# the contents of parentenvvar are used by the underlying lock to
# determine whether it can be inherited
if parentenvvar is not None:
parentlock = encoding.environ.get(parentenvvar)
try:
l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
acquirefn=acquirefn, desc=desc,
inheritchecker=inheritchecker,
parentlock=parentlock)
except error.LockHeld as inst:
if not wait:
raise
# show more details for new-style locks
if ':' in inst.locker:
host, pid = inst.locker.split(":", 1)
self.ui.warn(
_("waiting for lock on %s held by process %r "
"on host %r\n") % (desc, pid, host))
else:
self.ui.warn(_("waiting for lock on %s held by %r\n") %
(desc, inst.locker))
# default to 600 seconds timeout
l = lockmod.lock(vfs, lockname,
int(self.ui.config("ui", "timeout", "600")),
releasefn=releasefn, acquirefn=acquirefn,
desc=desc)
self.ui.warn(_("got lock after %s seconds\n") % l.delay)
return l
def _afterlock(self, callback):
"""add a callback to be run when the repository is fully unlocked
The callback will be executed when the outermost lock is released
(with wlock being higher level than 'lock')."""
for ref in (self._wlockref, self._lockref):
l = ref and ref()
if l and l.held:
l.postrelease.append(callback)
break
else: # no lock have been found.
callback()
2007-07-22 01:02:09 +04:00
def lock(self, wait=True):
'''Lock the repository store (.hg/store) and return a weak reference
to the lock. Use this before modifying the store (e.g. committing or
stripping). If you are opening a transaction, get a lock as well.)
If both 'lock' and 'wlock' must be acquired, ensure you always acquires
'wlock' first to avoid a dead-lock hazard.'''
l = self._currentlock(self._lockref)
if l is not None:
l.lock()
return l
l = self._lock(self.svfs, "lock", wait, None,
self.invalidate, _('repository %s') % self.origroot)
self._lockref = weakref.ref(l)
return l
def _wlockchecktransaction(self):
if self.currenttransaction() is not None:
raise error.LockInheritanceContractViolation(
'wlock cannot be inherited in the middle of a transaction')
2007-07-22 01:02:09 +04:00
def wlock(self, wait=True):
'''Lock the non-store parts of the repository (everything under
.hg except .hg/store) and return a weak reference to the lock.
Use this before modifying files in .hg.
If both 'lock' and 'wlock' must be acquired, ensure you always acquires
'wlock' first to avoid a dead-lock hazard.'''
l = self._wlockref and self._wlockref()
if l is not None and l.held:
l.lock()
return l
2015-10-17 01:58:46 +03:00
# We do not need to check for non-waiting lock acquisition. Such
# acquisition would not cause dead-lock as they would just fail.
if wait and (self.ui.configbool('devel', 'all-warnings')
or self.ui.configbool('devel', 'check-locks')):
if self._currentlock(self._lockref) is not None:
self.ui.develwarn('"wlock" acquired after "lock"')
def unlock():
if self.dirstate.pendingparentchange():
self.dirstate.invalidate()
else:
self.dirstate.write(None)
self._filecache['dirstate'].refresh()
l = self._lock(self.vfs, "wlock", wait, unlock,
self.invalidatedirstate, _('working directory of %s') %
self.origroot,
inheritchecker=self._wlockchecktransaction,
parentenvvar='HG_WLOCK_LOCKER')
self._wlockref = weakref.ref(l)
return l
def _currentlock(self, lockref):
"""Returns the lock if it's held, or None if it's not."""
if lockref is None:
return None
l = lockref()
if l is None or not l.held:
return None
return l
def currentwlock(self):
"""Returns the wlock if it's held, or None if it's not."""
return self._currentlock(self._wlockref)
def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
"""
2006-10-09 23:02:01 +04:00
commit an individual file as part of a larger transaction
"""
2006-10-09 23:02:01 +04:00
fname = fctx.path()
fparent1 = manifest1.get(fname, nullid)
fparent2 = manifest2.get(fname, nullid)
if isinstance(fctx, context.filectx):
node = fctx.filenode()
if node in [fparent1, fparent2]:
self.ui.debug('reusing %s filelog entry\n' % fname)
if manifest1.flags(fname) != fctx.flags():
changelist.append(fname)
return node
flog = self.file(fname)
meta = {}
copy = fctx.renamed()
if copy and copy[0] != fname:
# Mark the new revision of this file as a copy of another
# file. This copy data will effectively act as a parent
# of this new revision. If this is a merge, the first
# parent will be the nullid (meaning "look up the copy data")
# and the second one will be the other parent. For example:
#
# 0 --- 1 --- 3 rev1 changes file foo
# \ / rev2 renames foo to bar and changes it
# \- 2 -/ rev3 should have bar with all changes and
# should record that bar descends from
# bar in rev2 and foo in rev1
#
# this allows this merge to succeed:
#
# 0 --- 1 --- 3 rev4 reverts the content change from rev2
# \ / merging rev3 and rev4 should use bar@rev2
# \- 2 --- 4 as the merge base
#
2008-08-11 03:01:03 +04:00
cfname = copy[0]
crev = manifest1.get(cfname)
newfparent = fparent2
2008-08-11 03:01:03 +04:00
if manifest2: # branch merge
if fparent2 == nullid or crev is None: # copied on remote side
if cfname in manifest2:
crev = manifest2[cfname]
newfparent = fparent1
2008-08-11 03:01:03 +04:00
# Here, we used to search backwards through history to try to find
# where the file copy came from if the source of a copy was not in
# the parent directory. However, this doesn't actually make sense to
# do (what does a copy from something not in your working copy even
# mean?) and it causes bugs (eg, issue4476). Instead, we will warn
# the user that copy information was dropped, so if they didn't
# expect this outcome it can be fixed, but this is the correct
# behavior in this circumstance.
if crev:
self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
meta["copy"] = cfname
meta["copyrev"] = hex(crev)
fparent1, fparent2 = nullid, newfparent
else:
self.ui.warn(_("warning: can't find ancestor for '%s' "
"copied from '%s'!\n") % (fname, cfname))
elif fparent1 == nullid:
fparent1, fparent2 = fparent2, nullid
elif fparent2 != nullid:
# is one parent an ancestor of the other?
fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
if fparent1 in fparentancestors:
fparent1, fparent2 = fparent2, nullid
elif fparent2 in fparentancestors:
fparent2 = nullid
# is the file changed?
text = fctx.data()
if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
changelist.append(fname)
return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
# are just the flags changed during merge?
elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
changelist.append(fname)
return fparent1
def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
"""check for commit arguments that aren't committable"""
if match.isexact() or match.prefix():
matched = set(status.modified + status.added + status.removed)
for f in match.files():
f = self.dirstate.normalize(f)
if f == '.' or f in matched or f in wctx.substate:
continue
if f in status.deleted:
fail(f, _('file not found!'))
if f in vdirs: # visited directory
d = f + '/'
for mf in matched:
if mf.startswith(d):
break
else:
fail(f, _("no match under directory!"))
elif f not in self.dirstate:
fail(f, _("file not tracked!"))
@unfilteredmethod
def commit(self, text="", user=None, date=None, match=None, force=False,
editor=False, extra=None):
2009-05-19 13:39:12 +04:00
"""Add a new revision to current repository.
Revision information is gathered from the working directory,
match can be used to filter the committed files. If editor is
supplied, it is called to get a commit message.
2009-05-19 13:39:12 +04:00
"""
if extra is None:
extra = {}
def fail(f, msg):
raise error.Abort('%s: %s' % (f, msg))
if not match:
match = matchmod.always(self.root, '')
if not force:
vdirs = []
match.explicitdir = vdirs.append
match.bad = fail
wlock = lock = tr = None
try:
wlock = self.wlock()
lock = self.lock() # for recent changelog (see issue4368)
2009-06-15 11:45:38 +04:00
wctx = self[None]
merge = len(wctx.parents()) > 1
2009-05-14 22:20:40 +04:00
if not force and merge and match.ispartial():
raise error.Abort(_('cannot partially commit a merge '
2009-05-14 22:20:40 +04:00
'(do not specify files or patterns)'))
status = self.status(match=match, clean=force)
if force:
status.modified.extend(status.clean) # mq may commit clean files
2009-06-15 11:45:38 +04:00
# check subrepos
subs = []
commitsubs = set()
newstate = wctx.substate.copy()
# only manage subrepos and .hgsubstate if .hgsub is present
if '.hgsub' in wctx:
# we'll decide whether to track this ourselves, thanks
for c in status.modified, status.added, status.removed:
localrepo: omit ".hgsubstate" also from "added" files Before this patch, "localrepository.commit()" omits ".hgsubstate" from "modified" (changes[0]) and "removed" (changes[2]) file list before checking subrepositories, but leaves one in "added" (changes[1]) as it is. Then, "localrepository.commit()" adds ".hgsubstate" into "modified" or "removed" list forcibly, according to subrepository statuses. If "added" contains ".hgsubstate", the committed context will contain two ".hgsubstate" in its "files": one from "added" (not omitted one), and another from "modified" or "removed" (newly added one). How many times ".hgsubstate" appears in "files" changes node hash, even though revision content is same, because node hash calculation uses the specified "files" directly (without duplication check or so). This means that node hash of committed revision changes according to existence of ".hgsubstate" in "added" at "localrepository.commit()". ".hgsubstate" is treated as "added", not only in accidental cases, but also in the case of "qpush" for the patch adding ".hgsubstate". This patch omits ".hgsubstate" also from "added" files before checking subrepositories. This patch also omits ".hgsubstate" exclusion in "qnew"/"qrefresh" introduced by changeset bbb8109a634f, because this patch makes them meaningless. "hg parents --template '{files}\n'" newly added to "test-mq-subrepo.t" enhances checking unexpected multiple appearances of ".hgsubstate" in "files" of created/refreshed MQ revisions.
2014-03-22 18:39:51 +04:00
if '.hgsubstate' in c:
c.remove('.hgsubstate')
# compare current state to last committed state
# build new substate based on last committed state
oldstate = wctx.p1().substate
for s in sorted(newstate.keys()):
if not match(s):
# ignore working copy, use old state if present
if s in oldstate:
newstate[s] = oldstate[s]
continue
if not force:
raise error.Abort(
_("commit with new subrepo %s excluded") % s)
dirtyreason = wctx.sub(s).dirtyreason(True)
if dirtyreason:
if not self.ui.configbool('ui', 'commitsubrepos'):
raise error.Abort(dirtyreason,
hint=_("use --subrepos for recursive commit"))
subs.append(s)
commitsubs.add(s)
else:
bs = wctx.sub(s).basestate()
newstate[s] = (newstate[s][0], bs, newstate[s][2])
if oldstate.get(s, (None, None, None))[1] != bs:
subs.append(s)
# check for removed subrepos
for p in wctx.parents():
r = [s for s in p.substate if s not in newstate]
subs += [s for s in r if match(s)]
if subs:
if (not match('.hgsub') and
'.hgsub' in (wctx.modified() + wctx.added())):
raise error.Abort(
_("can't commit subrepos without .hgsub"))
status.modified.insert(0, '.hgsubstate')
elif '.hgsub' in status.removed:
# clean up .hgsubstate when .hgsub is removed
if ('.hgsubstate' in wctx and
'.hgsubstate' not in (status.modified + status.added +
status.removed)):
status.removed.insert(0, '.hgsubstate')
2009-06-15 11:45:38 +04:00
# make sure all explicit patterns are matched
if not force:
self.checkcommitpatterns(wctx, vdirs, match, status, fail)
cctx = context.workingcommitctx(self, status,
text, user, date, extra)
2015-06-26 01:51:02 +03:00
# internal config: ui.allowemptycommit
allowemptycommit = (wctx.branch() != wctx.p1().branch()
or extra.get('close') or merge or cctx.files()
or self.ui.configbool('ui', 'allowemptycommit'))
if not allowemptycommit:
return None
if merge and cctx.deleted():
raise error.Abort(_("cannot commit merge with missing files"))
ms = mergemod.mergestate.read(self)
mergeutil.checkunresolved(ms)
if editor:
cctx._text = editor(self, cctx, subs)
edited = (text != cctx._text)
2009-06-15 11:45:38 +04:00
# Save commit message in case this transaction gets rolled back
# (e.g. by a pretxncommit hook). Leave the content alone on
# the assumption that the user will use the same editor again.
msgfn = self.savecommitmessage(cctx._text)
# commit subs and write new state
if subs:
for s in sorted(commitsubs):
sub = wctx.sub(s)
self.ui.status(_('committing subrepository %s\n') %
subrepo.subrelpath(sub))
sr = sub.commit(cctx._text, user, date)
newstate[s] = (newstate[s][0], sr)
subrepo.writestate(self, newstate)
2009-06-15 11:45:38 +04:00
p1, p2 = self.dirstate.parents()
hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
try:
2012-05-12 17:54:54 +04:00
self.hook("precommit", throw=True, parent1=hookp1,
parent2=hookp2)
tr = self.transaction('commit')
ret = self.commitctx(cctx, True)
except: # re-raises
if edited:
self.ui.write(
_('note: commit message saved in %s\n') % msgfn)
raise
# update bookmarks, dirstate and mergestate
bookmarks.update(self, [p1, p2], ret)
cctx.markcommitted(ret)
2009-05-19 02:36:24 +04:00
ms.reset()
tr.close()
finally:
lockmod.release(tr, lock, wlock)
def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
# hack for command that use a temporary commit (eg: histedit)
# temporary commit got stripped before hook release
localrepo: use changelog.hasnode instead of self.__contains__ Before this patch, releasing the store lock implies the actions below, when the transaction is aborted: 1. "commithook()" scheduled in "localrepository.commit()" is invoked 2. "changectx.__init__()" is invoked via "self.__contains__()" 3. specified ID is examined against "repo.dirstate.p1()" 4. validation function is invoked in "dirstate.p1()" In subsequent patches, "dirstate.invalidate()" invocations for discarding changes are replaced with "dirstateguard", but discarding changes by "dirstateguard" is executed after releasing the store lock: resources are acquired in "wlock => dirstateguard => store lock" order, and are released in reverse order. This may cause that "dirstate.p1()" still refers to the changeset to be rolled-back at (4) above: pushing multiple patches by "hg qpush" is a typical case. When releasing the store lock, such changesets are: - not contained in "repo.changelog", if it is reloaded from ".hg/00changelog.i", as that file was already truncated by "transaction.abort()" - still contained in it, otherwise (this "dirty read" problem is discussed in "Transaction Plan" http://mercurial.selenic.com/wiki/TransactionPlan) Validation function shows "unknown working parent" warning in the former case, but reloading "repo.changelog" depends on the timestamp of ".hg/00changelog.i". This causes occasional test failures. In the case of scheduled "commithook()", it just wants to examine whether "node ID" of committed changeset is still valid or not. Other examinations implied in "changectx.__init__()" are meaningless. To avoid showing the "unknown working parent" warning irregularly, this patch uses "changelog.hasnode()" instead of "node in self" to examine existence of committed changeset.
2015-05-07 06:07:10 +03:00
if self.changelog.hasnode(ret):
self.hook("commit", node=node, parent1=parent1,
parent2=parent2)
self._afterlock(commithook)
return ret
@unfilteredmethod
def commitctx(self, ctx, error=False):
2008-10-11 15:07:29 +04:00
"""Add a new revision to current repository.
Revision information is passed via the context argument.
2008-10-11 15:07:29 +04:00
"""
2008-06-19 02:14:23 +04:00
tr = None
2009-05-14 22:24:26 +04:00
p1, p2 = ctx.p1(), ctx.p2()
2009-05-14 22:21:20 +04:00
user = ctx.user()
lock = self.lock()
try:
tr = self.transaction("commit")
trp = weakref.proxy(tr)
if ctx.manifestnode():
# reuse an existing manifest revision
mn = ctx.manifestnode()
files = ctx.files()
elif ctx.files():
m1ctx = p1.manifestctx()
m2ctx = p2.manifestctx()
mctx = m1ctx.copy()
m = mctx.read()
m1 = m1ctx.read()
m2 = m2ctx.read()
# check in files
added = []
changed = []
removed = list(ctx.removed())
linkrev = len(self)
self.ui.note(_("committing files:\n"))
for f in sorted(ctx.modified() + ctx.added()):
self.ui.note(f + "\n")
try:
fctx = ctx[f]
if fctx is None:
removed.append(f)
else:
added.append(f)
m[f] = self._filecommit(fctx, m1, m2, linkrev,
trp, changed)
m.setflag(f, fctx.flags())
except OSError as inst:
self.ui.warn(_("trouble committing %s!\n") % f)
raise
except IOError as inst:
errcode = getattr(inst, 'errno', errno.ENOENT)
if error or errcode and errcode != errno.ENOENT:
self.ui.warn(_("trouble committing %s!\n") % f)
raise
# update manifest
self.ui.note(_("committing manifest\n"))
removed = [f for f in sorted(removed) if f in m1 or f in m2]
drop = [f for f in removed if f in m]
for f in drop:
del m[f]
mn = mctx.write(trp, linkrev,
p1.manifestnode(), p2.manifestnode(),
added, drop)
files = changed + removed
else:
mn = p1.manifestnode()
files = []
# update changelog
self.ui.note(_("committing changelog\n"))
self.changelog.delayupdate(tr)
n = self.changelog.add(mn, files, ctx.description(),
trp, p1.node(), p2.node(),
2009-05-14 22:21:20 +04:00
user, ctx.date(), ctx.extra().copy())
xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
parent2=xp2)
# set the new commit is proper phase
targetphase = subrepo.newcommitphase(self.ui, ctx)
if targetphase:
# retract boundary do not alter parent changeset.
# if a parent have higher the resulting phase will
# be compliant anyway
#
# if minimal phase was 0 we don't need to retract anything
phases.retractboundary(self, tr, targetphase, [n])
tr.close()
branchmap.updatecache(self.filtered('served'))
return n
finally:
if tr:
tr.release()
lock.release()
@unfilteredmethod
def destroying(self):
'''Inform the repository that nodes are about to be destroyed.
Intended for use by strip and rollback, so there's a common
place for anything that has to be done before destroying history.
This is mostly useful for saving state that is in memory and waiting
to be flushed when the current lock is released. Because a call to
destroyed is imminent, the repo will be invalidated causing those
changes to stay in memory (waiting for the next unlock), or vanish
completely.
'''
# When using the same lock to commit and strip, the phasecache is left
# dirty after committing. Then when we strip, the repo is invalidated,
# causing those changes to disappear.
if '_phasecache' in vars(self):
self._phasecache.write()
@unfilteredmethod
def destroyed(self):
'''Inform the repository that nodes have been destroyed.
Intended for use by strip and rollback, so there's a common
place for anything that has to be done after destroying history.
'''
# When one tries to:
# 1) destroy nodes thus calling this method (e.g. strip)
# 2) use phasecache somewhere (e.g. commit)
#
# then 2) will fail because the phasecache contains nodes that were
# removed. We can either remove phasecache from the filecache,
# causing it to reload next time it is accessed, or simply filter
# the removed nodes now and write the updated cache.
self._phasecache.filterunknown(self)
self._phasecache.write()
# update the 'served' branch cache to help read only server process
# Thanks to branchcache collaboration this is done from the nearest
# filtered subset and it is expected to be fast.
branchmap.updatecache(self.filtered('served'))
# Ensure the persistent tag cache is updated. Doing it now
# means that the tag cache only has to worry about destroyed
# heads immediately after a strip/rollback. That in turn
# guarantees that "cachetip == currenttip" (comparing both rev
# and node) always means no nodes have been added or destroyed.
# XXX this is suboptimal when qrefresh'ing: we strip the current
# head, refresh the tag cache, then immediately add a new head.
# But I think doing it this way is necessary for the "instant
# tag cache retrieval" case to work.
self.invalidate()
2008-05-12 20:37:08 +04:00
def walk(self, match, node=None):
2006-10-27 20:24:10 +04:00
'''
walk recursively through the directory tree or a given
changeset, finding all files matched by the match
function
'''
2008-06-28 04:25:48 +04:00
return self[node].walk(match)
2006-10-27 20:24:10 +04:00
2008-07-12 03:46:02 +04:00
def status(self, node1='.', node2=None, match=None,
ignored=False, clean=False, unknown=False,
listsubrepos=False):
'''a convenience method that calls node1.status(node2)'''
return self[node1].status(node2, match, ignored, clean, unknown,
listsubrepos)
def heads(self, start=None):
if start is None:
cl = self.changelog
headrevs = sorted(cl.headrevs(), reverse=True)
return [cl.node(rev) for rev in headrevs]
heads = self.changelog.heads(start)
# sort the output in rev descending order
return sorted(heads, key=self.changelog.rev, reverse=True)
def branchheads(self, branch=None, start=None, closed=False):
'''return a (possibly filtered) list of heads for the given branch
Heads are returned in topological order, from newest to oldest.
If branch is None, use the dirstate branch.
If start is not None, return only heads reachable from start.
If closed is True, return heads that are marked as closed as well.
'''
2008-06-26 23:35:46 +04:00
if branch is None:
branch = self[None].branch()
branches = self.branchmap()
if branch not in branches:
return []
# the cache returns heads ordered lowest to highest
bheads = list(reversed(branches.branchheads(branch, closed=closed)))
if start is not None:
# filter out the heads that cannot be reached from startrev
fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
bheads = [h for h in bheads if h in fbheads]
return bheads
def branches(self, nodes):
if not nodes:
nodes = [self.changelog.tip()]
b = []
for n in nodes:
t = n
while True:
p = self.changelog.parents(n)
if p[1] != nullid or p[0] == nullid:
b.append((t, n, p[0], p[1]))
break
n = p[0]
return b
def between(self, pairs):
r = []
for top, bottom in pairs:
n, l, i = top, [], 0
f = 1
while n != bottom and n != nullid:
p = self.changelog.parents(n)[0]
if i == f:
l.append(n)
f = f * 2
n = p
i += 1
r.append(l)
return r
def checkpush(self, pushop):
"""Extensions can override this function if additional checks have
to be performed before pushing, or call it if they override push
command.
"""
pass
@unfilteredpropertycache
def prepushoutgoinghooks(self):
"""Return util.hooks consists of a pushop with repo, remote, outgoing
methods, which are called before pushing changesets.
"""
return util.hooks()
2010-06-17 01:04:46 +04:00
def pushkey(self, namespace, key, old, new):
try:
tr = self.currenttransaction()
hookargs = {}
if tr is not None:
hookargs.update(tr.hookargs)
hookargs['namespace'] = namespace
hookargs['key'] = key
hookargs['old'] = old
hookargs['new'] = new
self.hook('prepushkey', throw=True, **hookargs)
except error.HookAbort as exc:
self.ui.write_err(_("pushkey-abort: %s\n") % exc)
if exc.hint:
self.ui.write_err(_("(%s)\n") % exc.hint)
return False
self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
ret = pushkey.push(self, namespace, key, old, new)
def runhook():
self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
ret=ret)
self._afterlock(runhook)
return ret
2010-06-17 01:04:46 +04:00
def listkeys(self, namespace):
self.hook('prelistkeys', throw=True, namespace=namespace)
self.ui.debug('listing keys for "%s"\n' % namespace)
values = pushkey.list(self, namespace)
self.hook('listkeys', namespace=namespace, values=values)
return values
2010-06-17 01:04:46 +04:00
def debugwireargs(self, one, two, three=None, four=None, five=None):
'''used to test argument passing over the wire'''
return "%s %s %s %s %s" % (one, two, three, four, five)
def savecommitmessage(self, text):
fp = self.vfs('last-message.txt', 'wb')
try:
fp.write(text)
finally:
fp.close()
return self.pathto(fp.name[len(self.root) + 1:])
# used to avoid circular references so destructors work
def aftertrans(files):
renamefiles = [tuple(t) for t in files]
def a():
for vfs, src, dest in renamefiles:
try:
vfs.rename(src, dest)
except OSError: # journal file does not yet exist
pass
return a
def undoname(fn):
base, name = os.path.split(fn)
assert name.startswith('journal')
return os.path.join(base, name.replace('journal', 'undo', 1))
def instance(ui, path, create):
return localrepository(ui, util.urllocalpath(path), create)
2006-10-01 21:26:33 +04:00
def islocal(path):
return True
2016-02-16 00:20:20 +03:00
def newreporequirements(repo):
"""Determine the set of requirements for a new local repository.
Extensions can wrap this function to specify custom requirements for
new repositories.
"""
ui = repo.ui
requirements = set(['revlogv1'])
if ui.configbool('format', 'usestore', True):
requirements.add('store')
if ui.configbool('format', 'usefncache', True):
requirements.add('fncache')
if ui.configbool('format', 'dotencode', True):
requirements.add('dotencode')
localrepo: experimental support for non-zlib revlog compression The final part of integrating the compression manager APIs into revlog storage is the plumbing for repositories to advertise they are using non-zlib storage and for revlogs to instantiate a non-zlib compression engine. The main intent of the compression manager work was to zstd all of the things. Adding zstd to revlogs has proved to be more involved than other places because revlogs are... special. Very small inputs and the use of delta chains (which are themselves a form of compression) are a completely different use case from streaming compression, which bundles and the wire protocol employ. I've conducted numerous experiments with zstd in revlogs and have yet to formalize compression settings and a storage architecture that I'm confident I won't regret later. In other words, I'm not yet ready to commit to a new mechanism for using zstd - or any other compression format - in revlogs. That being said, having some support for zstd (and other compression formats) in revlogs in core is beneficial. It can allow others to conduct experiments. This patch introduces *highly experimental* support for non-zlib compression formats in revlogs. Introduced is a config option to control which compression engine to use. Also introduced is a namespace of "exp-compression-*" requirements to denote support for non-zlib compression in revlogs. I've prefixed the namespace with "exp-" (short for "experimental") because I'm not confident of the requirements "schema" and in no way want to give the illusion of supporting these requirements in the future. I fully intend to drop support for these requirements once we figure out what we're doing with zstd in revlogs. A good portion of the patch is teaching the requirements system about registered compression engines and passing the requested compression engine as an opener option so revlogs can instantiate the proper compression engine for new operations. That's a verbose way of saying "we can now use zstd in revlogs!" On an `hg pull` conversion of the mozilla-unified repo with no extra redelta settings (like aggressivemergedeltas), we can see the impact of zstd vs zlib in revlogs: $ hg perfrevlogchunks -c ! chunk ! wall 2.032052 comb 2.040000 user 1.990000 sys 0.050000 (best of 5) ! wall 1.866360 comb 1.860000 user 1.820000 sys 0.040000 (best of 6) ! chunk batch ! wall 1.877261 comb 1.870000 user 1.860000 sys 0.010000 (best of 6) ! wall 1.705410 comb 1.710000 user 1.690000 sys 0.020000 (best of 6) $ hg perfrevlogchunks -m ! chunk ! wall 2.721427 comb 2.720000 user 2.640000 sys 0.080000 (best of 4) ! wall 2.035076 comb 2.030000 user 1.950000 sys 0.080000 (best of 5) ! chunk batch ! wall 2.614561 comb 2.620000 user 2.580000 sys 0.040000 (best of 4) ! wall 1.910252 comb 1.910000 user 1.880000 sys 0.030000 (best of 6) $ hg perfrevlog -c -d 1 ! wall 4.812885 comb 4.820000 user 4.800000 sys 0.020000 (best of 3) ! wall 4.699621 comb 4.710000 user 4.700000 sys 0.010000 (best of 3) $ hg perfrevlog -m -d 1000 ! wall 34.252800 comb 34.250000 user 33.730000 sys 0.520000 (best of 3) ! wall 24.094999 comb 24.090000 user 23.320000 sys 0.770000 (best of 3) Only modest wins for the changelog. But manifest reading is significantly faster. What's going on? One reason might be data volume. zstd decompresses faster. So given more bytes, it will put more distance between it and zlib. Another reason is size. In the current design, zstd revlogs are *larger*: debugcreatestreamclonebundle (size in bytes) zlib: 1,638,852,492 zstd: 1,680,601,332 I haven't investigated this fully, but I reckon a significant cause of larger revlogs is that the zstd frame/header has more bytes than zlib's. For very small inputs or data that doesn't compress well, we'll tend to store more uncompressed chunks than with zlib (because the compressed size isn't smaller than original). This will make revlog reading faster because it is doing less decompression. Moving on to bundle performance: $ hg bundle -a -t none-v2 (total CPU time) zlib: 102.79s zstd: 97.75s So, marginal CPU decrease for reading all chunks in all revlogs (this is somewhat disappointing). $ hg bundle -a -t <engine>-v2 (total CPU time) zlib: 191.59s zstd: 115.36s This last test effectively measures the difference between zlib->zlib and zstd->zstd for revlogs to bundle. This is a rough approximation of what a server does during `hg clone`. There are some promising results for zstd. But not enough for me to feel comfortable advertising it to users. We'll get there...
2017-01-14 07:16:56 +03:00
compengine = ui.config('experimental', 'format.compression', 'zlib')
if compengine not in util.compengines:
raise error.Abort(_('compression engine %s defined by '
'experimental.format.compression not available') %
compengine,
hint=_('run "hg debuginstall" to list available '
'compression engines'))
# zlib is the historical default and doesn't need an explicit requirement.
if compengine != 'zlib':
requirements.add('exp-compression-%s' % compengine)
2016-02-16 00:20:20 +03:00
if scmutil.gdinitconfig(ui):
requirements.add('generaldelta')
if ui.configbool('experimental', 'treemanifest', False):
requirements.add('treemanifest')
if ui.configbool('experimental', 'manifestv2', False):
requirements.add('manifestv2')
return requirements