##// END OF EJS Templates
cachevfs: add a devel warning for cache access though 'vfs'...
Boris Feld -
r33538:54b36d3f default
parent child Browse files
Show More
@@ -1,2249 +1,2252 b''
1 # localrepo.py - read/write repository class for mercurial
1 # localrepo.py - read/write repository class for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import hashlib
11 import hashlib
12 import inspect
12 import inspect
13 import os
13 import os
14 import random
14 import random
15 import time
15 import time
16 import weakref
16 import weakref
17
17
18 from .i18n import _
18 from .i18n import _
19 from .node import (
19 from .node import (
20 hex,
20 hex,
21 nullid,
21 nullid,
22 short,
22 short,
23 )
23 )
24 from . import (
24 from . import (
25 bookmarks,
25 bookmarks,
26 branchmap,
26 branchmap,
27 bundle2,
27 bundle2,
28 changegroup,
28 changegroup,
29 changelog,
29 changelog,
30 color,
30 color,
31 context,
31 context,
32 dirstate,
32 dirstate,
33 dirstateguard,
33 dirstateguard,
34 encoding,
34 encoding,
35 error,
35 error,
36 exchange,
36 exchange,
37 extensions,
37 extensions,
38 filelog,
38 filelog,
39 hook,
39 hook,
40 lock as lockmod,
40 lock as lockmod,
41 manifest,
41 manifest,
42 match as matchmod,
42 match as matchmod,
43 merge as mergemod,
43 merge as mergemod,
44 mergeutil,
44 mergeutil,
45 namespaces,
45 namespaces,
46 obsolete,
46 obsolete,
47 pathutil,
47 pathutil,
48 peer,
48 peer,
49 phases,
49 phases,
50 pushkey,
50 pushkey,
51 pycompat,
51 pycompat,
52 repoview,
52 repoview,
53 revset,
53 revset,
54 revsetlang,
54 revsetlang,
55 scmutil,
55 scmutil,
56 sparse,
56 sparse,
57 store,
57 store,
58 subrepo,
58 subrepo,
59 tags as tagsmod,
59 tags as tagsmod,
60 transaction,
60 transaction,
61 txnutil,
61 txnutil,
62 util,
62 util,
63 vfs as vfsmod,
63 vfs as vfsmod,
64 )
64 )
65
65
66 release = lockmod.release
66 release = lockmod.release
67 urlerr = util.urlerr
67 urlerr = util.urlerr
68 urlreq = util.urlreq
68 urlreq = util.urlreq
69
69
70 # set of (path, vfs-location) tuples. vfs-location is:
70 # set of (path, vfs-location) tuples. vfs-location is:
71 # - 'plain for vfs relative paths
71 # - 'plain for vfs relative paths
72 # - '' for svfs relative paths
72 # - '' for svfs relative paths
73 _cachedfiles = set()
73 _cachedfiles = set()
74
74
75 class _basefilecache(scmutil.filecache):
75 class _basefilecache(scmutil.filecache):
76 """All filecache usage on repo are done for logic that should be unfiltered
76 """All filecache usage on repo are done for logic that should be unfiltered
77 """
77 """
78 def __get__(self, repo, type=None):
78 def __get__(self, repo, type=None):
79 if repo is None:
79 if repo is None:
80 return self
80 return self
81 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
81 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
82 def __set__(self, repo, value):
82 def __set__(self, repo, value):
83 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
83 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
84 def __delete__(self, repo):
84 def __delete__(self, repo):
85 return super(_basefilecache, self).__delete__(repo.unfiltered())
85 return super(_basefilecache, self).__delete__(repo.unfiltered())
86
86
87 class repofilecache(_basefilecache):
87 class repofilecache(_basefilecache):
88 """filecache for files in .hg but outside of .hg/store"""
88 """filecache for files in .hg but outside of .hg/store"""
89 def __init__(self, *paths):
89 def __init__(self, *paths):
90 super(repofilecache, self).__init__(*paths)
90 super(repofilecache, self).__init__(*paths)
91 for path in paths:
91 for path in paths:
92 _cachedfiles.add((path, 'plain'))
92 _cachedfiles.add((path, 'plain'))
93
93
94 def join(self, obj, fname):
94 def join(self, obj, fname):
95 return obj.vfs.join(fname)
95 return obj.vfs.join(fname)
96
96
97 class storecache(_basefilecache):
97 class storecache(_basefilecache):
98 """filecache for files in the store"""
98 """filecache for files in the store"""
99 def __init__(self, *paths):
99 def __init__(self, *paths):
100 super(storecache, self).__init__(*paths)
100 super(storecache, self).__init__(*paths)
101 for path in paths:
101 for path in paths:
102 _cachedfiles.add((path, ''))
102 _cachedfiles.add((path, ''))
103
103
104 def join(self, obj, fname):
104 def join(self, obj, fname):
105 return obj.sjoin(fname)
105 return obj.sjoin(fname)
106
106
107 def isfilecached(repo, name):
107 def isfilecached(repo, name):
108 """check if a repo has already cached "name" filecache-ed property
108 """check if a repo has already cached "name" filecache-ed property
109
109
110 This returns (cachedobj-or-None, iscached) tuple.
110 This returns (cachedobj-or-None, iscached) tuple.
111 """
111 """
112 cacheentry = repo.unfiltered()._filecache.get(name, None)
112 cacheentry = repo.unfiltered()._filecache.get(name, None)
113 if not cacheentry:
113 if not cacheentry:
114 return None, False
114 return None, False
115 return cacheentry.obj, True
115 return cacheentry.obj, True
116
116
117 class unfilteredpropertycache(util.propertycache):
117 class unfilteredpropertycache(util.propertycache):
118 """propertycache that apply to unfiltered repo only"""
118 """propertycache that apply to unfiltered repo only"""
119
119
120 def __get__(self, repo, type=None):
120 def __get__(self, repo, type=None):
121 unfi = repo.unfiltered()
121 unfi = repo.unfiltered()
122 if unfi is repo:
122 if unfi is repo:
123 return super(unfilteredpropertycache, self).__get__(unfi)
123 return super(unfilteredpropertycache, self).__get__(unfi)
124 return getattr(unfi, self.name)
124 return getattr(unfi, self.name)
125
125
126 class filteredpropertycache(util.propertycache):
126 class filteredpropertycache(util.propertycache):
127 """propertycache that must take filtering in account"""
127 """propertycache that must take filtering in account"""
128
128
129 def cachevalue(self, obj, value):
129 def cachevalue(self, obj, value):
130 object.__setattr__(obj, self.name, value)
130 object.__setattr__(obj, self.name, value)
131
131
132
132
133 def hasunfilteredcache(repo, name):
133 def hasunfilteredcache(repo, name):
134 """check if a repo has an unfilteredpropertycache value for <name>"""
134 """check if a repo has an unfilteredpropertycache value for <name>"""
135 return name in vars(repo.unfiltered())
135 return name in vars(repo.unfiltered())
136
136
137 def unfilteredmethod(orig):
137 def unfilteredmethod(orig):
138 """decorate method that always need to be run on unfiltered version"""
138 """decorate method that always need to be run on unfiltered version"""
139 def wrapper(repo, *args, **kwargs):
139 def wrapper(repo, *args, **kwargs):
140 return orig(repo.unfiltered(), *args, **kwargs)
140 return orig(repo.unfiltered(), *args, **kwargs)
141 return wrapper
141 return wrapper
142
142
143 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
143 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
144 'unbundle'}
144 'unbundle'}
145 legacycaps = moderncaps.union({'changegroupsubset'})
145 legacycaps = moderncaps.union({'changegroupsubset'})
146
146
147 class localpeer(peer.peerrepository):
147 class localpeer(peer.peerrepository):
148 '''peer for a local repo; reflects only the most recent API'''
148 '''peer for a local repo; reflects only the most recent API'''
149
149
150 def __init__(self, repo, caps=None):
150 def __init__(self, repo, caps=None):
151 if caps is None:
151 if caps is None:
152 caps = moderncaps.copy()
152 caps = moderncaps.copy()
153 peer.peerrepository.__init__(self)
153 peer.peerrepository.__init__(self)
154 self._repo = repo.filtered('served')
154 self._repo = repo.filtered('served')
155 self.ui = repo.ui
155 self.ui = repo.ui
156 self._caps = repo._restrictcapabilities(caps)
156 self._caps = repo._restrictcapabilities(caps)
157 self.requirements = repo.requirements
157 self.requirements = repo.requirements
158 self.supportedformats = repo.supportedformats
158 self.supportedformats = repo.supportedformats
159
159
160 def close(self):
160 def close(self):
161 self._repo.close()
161 self._repo.close()
162
162
163 def _capabilities(self):
163 def _capabilities(self):
164 return self._caps
164 return self._caps
165
165
166 def local(self):
166 def local(self):
167 return self._repo
167 return self._repo
168
168
169 def canpush(self):
169 def canpush(self):
170 return True
170 return True
171
171
172 def url(self):
172 def url(self):
173 return self._repo.url()
173 return self._repo.url()
174
174
175 def lookup(self, key):
175 def lookup(self, key):
176 return self._repo.lookup(key)
176 return self._repo.lookup(key)
177
177
178 def branchmap(self):
178 def branchmap(self):
179 return self._repo.branchmap()
179 return self._repo.branchmap()
180
180
181 def heads(self):
181 def heads(self):
182 return self._repo.heads()
182 return self._repo.heads()
183
183
184 def known(self, nodes):
184 def known(self, nodes):
185 return self._repo.known(nodes)
185 return self._repo.known(nodes)
186
186
187 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
187 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
188 **kwargs):
188 **kwargs):
189 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
189 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
190 common=common, bundlecaps=bundlecaps,
190 common=common, bundlecaps=bundlecaps,
191 **kwargs)
191 **kwargs)
192 cb = util.chunkbuffer(chunks)
192 cb = util.chunkbuffer(chunks)
193
193
194 if exchange.bundle2requested(bundlecaps):
194 if exchange.bundle2requested(bundlecaps):
195 # When requesting a bundle2, getbundle returns a stream to make the
195 # When requesting a bundle2, getbundle returns a stream to make the
196 # wire level function happier. We need to build a proper object
196 # wire level function happier. We need to build a proper object
197 # from it in local peer.
197 # from it in local peer.
198 return bundle2.getunbundler(self.ui, cb)
198 return bundle2.getunbundler(self.ui, cb)
199 else:
199 else:
200 return changegroup.getunbundler('01', cb, None)
200 return changegroup.getunbundler('01', cb, None)
201
201
202 # TODO We might want to move the next two calls into legacypeer and add
202 # TODO We might want to move the next two calls into legacypeer and add
203 # unbundle instead.
203 # unbundle instead.
204
204
205 def unbundle(self, cg, heads, url):
205 def unbundle(self, cg, heads, url):
206 """apply a bundle on a repo
206 """apply a bundle on a repo
207
207
208 This function handles the repo locking itself."""
208 This function handles the repo locking itself."""
209 try:
209 try:
210 try:
210 try:
211 cg = exchange.readbundle(self.ui, cg, None)
211 cg = exchange.readbundle(self.ui, cg, None)
212 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
212 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
213 if util.safehasattr(ret, 'getchunks'):
213 if util.safehasattr(ret, 'getchunks'):
214 # This is a bundle20 object, turn it into an unbundler.
214 # This is a bundle20 object, turn it into an unbundler.
215 # This little dance should be dropped eventually when the
215 # This little dance should be dropped eventually when the
216 # API is finally improved.
216 # API is finally improved.
217 stream = util.chunkbuffer(ret.getchunks())
217 stream = util.chunkbuffer(ret.getchunks())
218 ret = bundle2.getunbundler(self.ui, stream)
218 ret = bundle2.getunbundler(self.ui, stream)
219 return ret
219 return ret
220 except Exception as exc:
220 except Exception as exc:
221 # If the exception contains output salvaged from a bundle2
221 # If the exception contains output salvaged from a bundle2
222 # reply, we need to make sure it is printed before continuing
222 # reply, we need to make sure it is printed before continuing
223 # to fail. So we build a bundle2 with such output and consume
223 # to fail. So we build a bundle2 with such output and consume
224 # it directly.
224 # it directly.
225 #
225 #
226 # This is not very elegant but allows a "simple" solution for
226 # This is not very elegant but allows a "simple" solution for
227 # issue4594
227 # issue4594
228 output = getattr(exc, '_bundle2salvagedoutput', ())
228 output = getattr(exc, '_bundle2salvagedoutput', ())
229 if output:
229 if output:
230 bundler = bundle2.bundle20(self._repo.ui)
230 bundler = bundle2.bundle20(self._repo.ui)
231 for out in output:
231 for out in output:
232 bundler.addpart(out)
232 bundler.addpart(out)
233 stream = util.chunkbuffer(bundler.getchunks())
233 stream = util.chunkbuffer(bundler.getchunks())
234 b = bundle2.getunbundler(self.ui, stream)
234 b = bundle2.getunbundler(self.ui, stream)
235 bundle2.processbundle(self._repo, b)
235 bundle2.processbundle(self._repo, b)
236 raise
236 raise
237 except error.PushRaced as exc:
237 except error.PushRaced as exc:
238 raise error.ResponseError(_('push failed:'), str(exc))
238 raise error.ResponseError(_('push failed:'), str(exc))
239
239
240 def lock(self):
240 def lock(self):
241 return self._repo.lock()
241 return self._repo.lock()
242
242
243 def pushkey(self, namespace, key, old, new):
243 def pushkey(self, namespace, key, old, new):
244 return self._repo.pushkey(namespace, key, old, new)
244 return self._repo.pushkey(namespace, key, old, new)
245
245
246 def listkeys(self, namespace):
246 def listkeys(self, namespace):
247 return self._repo.listkeys(namespace)
247 return self._repo.listkeys(namespace)
248
248
249 def debugwireargs(self, one, two, three=None, four=None, five=None):
249 def debugwireargs(self, one, two, three=None, four=None, five=None):
250 '''used to test argument passing over the wire'''
250 '''used to test argument passing over the wire'''
251 return "%s %s %s %s %s" % (one, two, three, four, five)
251 return "%s %s %s %s %s" % (one, two, three, four, five)
252
252
253 class locallegacypeer(localpeer):
253 class locallegacypeer(localpeer):
254 '''peer extension which implements legacy methods too; used for tests with
254 '''peer extension which implements legacy methods too; used for tests with
255 restricted capabilities'''
255 restricted capabilities'''
256
256
257 def __init__(self, repo):
257 def __init__(self, repo):
258 localpeer.__init__(self, repo, caps=legacycaps)
258 localpeer.__init__(self, repo, caps=legacycaps)
259
259
260 def branches(self, nodes):
260 def branches(self, nodes):
261 return self._repo.branches(nodes)
261 return self._repo.branches(nodes)
262
262
263 def between(self, pairs):
263 def between(self, pairs):
264 return self._repo.between(pairs)
264 return self._repo.between(pairs)
265
265
266 def changegroup(self, basenodes, source):
266 def changegroup(self, basenodes, source):
267 return changegroup.changegroup(self._repo, basenodes, source)
267 return changegroup.changegroup(self._repo, basenodes, source)
268
268
269 def changegroupsubset(self, bases, heads, source):
269 def changegroupsubset(self, bases, heads, source):
270 return changegroup.changegroupsubset(self._repo, bases, heads, source)
270 return changegroup.changegroupsubset(self._repo, bases, heads, source)
271
271
272 # Increment the sub-version when the revlog v2 format changes to lock out old
272 # Increment the sub-version when the revlog v2 format changes to lock out old
273 # clients.
273 # clients.
274 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
274 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
275
275
276 class localrepository(object):
276 class localrepository(object):
277
277
278 supportedformats = {
278 supportedformats = {
279 'revlogv1',
279 'revlogv1',
280 'generaldelta',
280 'generaldelta',
281 'treemanifest',
281 'treemanifest',
282 'manifestv2',
282 'manifestv2',
283 REVLOGV2_REQUIREMENT,
283 REVLOGV2_REQUIREMENT,
284 }
284 }
285 _basesupported = supportedformats | {
285 _basesupported = supportedformats | {
286 'store',
286 'store',
287 'fncache',
287 'fncache',
288 'shared',
288 'shared',
289 'relshared',
289 'relshared',
290 'dotencode',
290 'dotencode',
291 }
291 }
292 openerreqs = {
292 openerreqs = {
293 'revlogv1',
293 'revlogv1',
294 'generaldelta',
294 'generaldelta',
295 'treemanifest',
295 'treemanifest',
296 'manifestv2',
296 'manifestv2',
297 }
297 }
298
298
299 # a list of (ui, featureset) functions.
299 # a list of (ui, featureset) functions.
300 # only functions defined in module of enabled extensions are invoked
300 # only functions defined in module of enabled extensions are invoked
301 featuresetupfuncs = set()
301 featuresetupfuncs = set()
302
302
303 # list of prefix for file which can be written without 'wlock'
303 # list of prefix for file which can be written without 'wlock'
304 # Extensions should extend this list when needed
304 # Extensions should extend this list when needed
305 _wlockfreeprefix = {
305 _wlockfreeprefix = {
306 # We migh consider requiring 'wlock' for the next
306 # We migh consider requiring 'wlock' for the next
307 # two, but pretty much all the existing code assume
307 # two, but pretty much all the existing code assume
308 # wlock is not needed so we keep them excluded for
308 # wlock is not needed so we keep them excluded for
309 # now.
309 # now.
310 'hgrc',
310 'hgrc',
311 'requires',
311 'requires',
312 # XXX cache is a complicatged business someone
312 # XXX cache is a complicatged business someone
313 # should investigate this in depth at some point
313 # should investigate this in depth at some point
314 'cache/',
314 'cache/',
315 # XXX shouldn't be dirstate covered by the wlock?
315 # XXX shouldn't be dirstate covered by the wlock?
316 'dirstate',
316 'dirstate',
317 # XXX bisect was still a bit too messy at the time
317 # XXX bisect was still a bit too messy at the time
318 # this changeset was introduced. Someone should fix
318 # this changeset was introduced. Someone should fix
319 # the remainig bit and drop this line
319 # the remainig bit and drop this line
320 'bisect.state',
320 'bisect.state',
321 }
321 }
322
322
323 def __init__(self, baseui, path, create=False):
323 def __init__(self, baseui, path, create=False):
324 self.requirements = set()
324 self.requirements = set()
325 self.filtername = None
325 self.filtername = None
326 # wvfs: rooted at the repository root, used to access the working copy
326 # wvfs: rooted at the repository root, used to access the working copy
327 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
327 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
328 # vfs: rooted at .hg, used to access repo files outside of .hg/store
328 # vfs: rooted at .hg, used to access repo files outside of .hg/store
329 self.vfs = None
329 self.vfs = None
330 # svfs: usually rooted at .hg/store, used to access repository history
330 # svfs: usually rooted at .hg/store, used to access repository history
331 # If this is a shared repository, this vfs may point to another
331 # If this is a shared repository, this vfs may point to another
332 # repository's .hg/store directory.
332 # repository's .hg/store directory.
333 self.svfs = None
333 self.svfs = None
334 self.root = self.wvfs.base
334 self.root = self.wvfs.base
335 self.path = self.wvfs.join(".hg")
335 self.path = self.wvfs.join(".hg")
336 self.origroot = path
336 self.origroot = path
337 # These auditor are not used by the vfs,
337 # These auditor are not used by the vfs,
338 # only used when writing this comment: basectx.match
338 # only used when writing this comment: basectx.match
339 self.auditor = pathutil.pathauditor(self.root, self._checknested)
339 self.auditor = pathutil.pathauditor(self.root, self._checknested)
340 self.nofsauditor = pathutil.pathauditor(self.root, self._checknested,
340 self.nofsauditor = pathutil.pathauditor(self.root, self._checknested,
341 realfs=False)
341 realfs=False)
342 self.baseui = baseui
342 self.baseui = baseui
343 self.ui = baseui.copy()
343 self.ui = baseui.copy()
344 self.ui.copy = baseui.copy # prevent copying repo configuration
344 self.ui.copy = baseui.copy # prevent copying repo configuration
345 self.vfs = vfsmod.vfs(self.path)
345 self.vfs = vfsmod.vfs(self.path)
346 if (self.ui.configbool('devel', 'all-warnings') or
346 if (self.ui.configbool('devel', 'all-warnings') or
347 self.ui.configbool('devel', 'check-locks')):
347 self.ui.configbool('devel', 'check-locks')):
348 self.vfs.audit = self._getvfsward(self.vfs.audit)
348 self.vfs.audit = self._getvfsward(self.vfs.audit)
349 # A list of callback to shape the phase if no data were found.
349 # A list of callback to shape the phase if no data were found.
350 # Callback are in the form: func(repo, roots) --> processed root.
350 # Callback are in the form: func(repo, roots) --> processed root.
351 # This list it to be filled by extension during repo setup
351 # This list it to be filled by extension during repo setup
352 self._phasedefaults = []
352 self._phasedefaults = []
353 try:
353 try:
354 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
354 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
355 self._loadextensions()
355 self._loadextensions()
356 except IOError:
356 except IOError:
357 pass
357 pass
358
358
359 if self.featuresetupfuncs:
359 if self.featuresetupfuncs:
360 self.supported = set(self._basesupported) # use private copy
360 self.supported = set(self._basesupported) # use private copy
361 extmods = set(m.__name__ for n, m
361 extmods = set(m.__name__ for n, m
362 in extensions.extensions(self.ui))
362 in extensions.extensions(self.ui))
363 for setupfunc in self.featuresetupfuncs:
363 for setupfunc in self.featuresetupfuncs:
364 if setupfunc.__module__ in extmods:
364 if setupfunc.__module__ in extmods:
365 setupfunc(self.ui, self.supported)
365 setupfunc(self.ui, self.supported)
366 else:
366 else:
367 self.supported = self._basesupported
367 self.supported = self._basesupported
368 color.setup(self.ui)
368 color.setup(self.ui)
369
369
370 # Add compression engines.
370 # Add compression engines.
371 for name in util.compengines:
371 for name in util.compengines:
372 engine = util.compengines[name]
372 engine = util.compengines[name]
373 if engine.revlogheader():
373 if engine.revlogheader():
374 self.supported.add('exp-compression-%s' % name)
374 self.supported.add('exp-compression-%s' % name)
375
375
376 if not self.vfs.isdir():
376 if not self.vfs.isdir():
377 if create:
377 if create:
378 self.requirements = newreporequirements(self)
378 self.requirements = newreporequirements(self)
379
379
380 if not self.wvfs.exists():
380 if not self.wvfs.exists():
381 self.wvfs.makedirs()
381 self.wvfs.makedirs()
382 self.vfs.makedir(notindexed=True)
382 self.vfs.makedir(notindexed=True)
383
383
384 if 'store' in self.requirements:
384 if 'store' in self.requirements:
385 self.vfs.mkdir("store")
385 self.vfs.mkdir("store")
386
386
387 # create an invalid changelog
387 # create an invalid changelog
388 self.vfs.append(
388 self.vfs.append(
389 "00changelog.i",
389 "00changelog.i",
390 '\0\0\0\2' # represents revlogv2
390 '\0\0\0\2' # represents revlogv2
391 ' dummy changelog to prevent using the old repo layout'
391 ' dummy changelog to prevent using the old repo layout'
392 )
392 )
393 else:
393 else:
394 raise error.RepoError(_("repository %s not found") % path)
394 raise error.RepoError(_("repository %s not found") % path)
395 elif create:
395 elif create:
396 raise error.RepoError(_("repository %s already exists") % path)
396 raise error.RepoError(_("repository %s already exists") % path)
397 else:
397 else:
398 try:
398 try:
399 self.requirements = scmutil.readrequires(
399 self.requirements = scmutil.readrequires(
400 self.vfs, self.supported)
400 self.vfs, self.supported)
401 except IOError as inst:
401 except IOError as inst:
402 if inst.errno != errno.ENOENT:
402 if inst.errno != errno.ENOENT:
403 raise
403 raise
404
404
405 self.sharedpath = self.path
405 self.sharedpath = self.path
406 try:
406 try:
407 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
407 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
408 if 'relshared' in self.requirements:
408 if 'relshared' in self.requirements:
409 sharedpath = self.vfs.join(sharedpath)
409 sharedpath = self.vfs.join(sharedpath)
410 vfs = vfsmod.vfs(sharedpath, realpath=True)
410 vfs = vfsmod.vfs(sharedpath, realpath=True)
411 s = vfs.base
411 s = vfs.base
412 if not vfs.exists():
412 if not vfs.exists():
413 raise error.RepoError(
413 raise error.RepoError(
414 _('.hg/sharedpath points to nonexistent directory %s') % s)
414 _('.hg/sharedpath points to nonexistent directory %s') % s)
415 self.sharedpath = s
415 self.sharedpath = s
416 except IOError as inst:
416 except IOError as inst:
417 if inst.errno != errno.ENOENT:
417 if inst.errno != errno.ENOENT:
418 raise
418 raise
419
419
420 self.store = store.store(
420 self.store = store.store(
421 self.requirements, self.sharedpath, vfsmod.vfs)
421 self.requirements, self.sharedpath, vfsmod.vfs)
422 self.spath = self.store.path
422 self.spath = self.store.path
423 self.svfs = self.store.vfs
423 self.svfs = self.store.vfs
424 self.sjoin = self.store.join
424 self.sjoin = self.store.join
425 self.vfs.createmode = self.store.createmode
425 self.vfs.createmode = self.store.createmode
426 self.cachevfs = vfsmod.vfs(self.vfs.join('cache'))
426 self.cachevfs = vfsmod.vfs(self.vfs.join('cache'))
427 self.cachevfs.createmode = self.store.createmode
427 self.cachevfs.createmode = self.store.createmode
428 if (self.ui.configbool('devel', 'all-warnings') or
428 if (self.ui.configbool('devel', 'all-warnings') or
429 self.ui.configbool('devel', 'check-locks')):
429 self.ui.configbool('devel', 'check-locks')):
430 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
430 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
431 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
431 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
432 else: # standard vfs
432 else: # standard vfs
433 self.svfs.audit = self._getsvfsward(self.svfs.audit)
433 self.svfs.audit = self._getsvfsward(self.svfs.audit)
434 self._applyopenerreqs()
434 self._applyopenerreqs()
435 if create:
435 if create:
436 self._writerequirements()
436 self._writerequirements()
437
437
438 self._dirstatevalidatewarned = False
438 self._dirstatevalidatewarned = False
439
439
440 self._branchcaches = {}
440 self._branchcaches = {}
441 self._revbranchcache = None
441 self._revbranchcache = None
442 self.filterpats = {}
442 self.filterpats = {}
443 self._datafilters = {}
443 self._datafilters = {}
444 self._transref = self._lockref = self._wlockref = None
444 self._transref = self._lockref = self._wlockref = None
445
445
446 # A cache for various files under .hg/ that tracks file changes,
446 # A cache for various files under .hg/ that tracks file changes,
447 # (used by the filecache decorator)
447 # (used by the filecache decorator)
448 #
448 #
449 # Maps a property name to its util.filecacheentry
449 # Maps a property name to its util.filecacheentry
450 self._filecache = {}
450 self._filecache = {}
451
451
452 # hold sets of revision to be filtered
452 # hold sets of revision to be filtered
453 # should be cleared when something might have changed the filter value:
453 # should be cleared when something might have changed the filter value:
454 # - new changesets,
454 # - new changesets,
455 # - phase change,
455 # - phase change,
456 # - new obsolescence marker,
456 # - new obsolescence marker,
457 # - working directory parent change,
457 # - working directory parent change,
458 # - bookmark changes
458 # - bookmark changes
459 self.filteredrevcache = {}
459 self.filteredrevcache = {}
460
460
461 # post-dirstate-status hooks
461 # post-dirstate-status hooks
462 self._postdsstatus = []
462 self._postdsstatus = []
463
463
464 # Cache of types representing filtered repos.
464 # Cache of types representing filtered repos.
465 self._filteredrepotypes = weakref.WeakKeyDictionary()
465 self._filteredrepotypes = weakref.WeakKeyDictionary()
466
466
467 # generic mapping between names and nodes
467 # generic mapping between names and nodes
468 self.names = namespaces.namespaces()
468 self.names = namespaces.namespaces()
469
469
470 # Key to signature value.
470 # Key to signature value.
471 self._sparsesignaturecache = {}
471 self._sparsesignaturecache = {}
472 # Signature to cached matcher instance.
472 # Signature to cached matcher instance.
473 self._sparsematchercache = {}
473 self._sparsematchercache = {}
474
474
475 def _getvfsward(self, origfunc):
475 def _getvfsward(self, origfunc):
476 """build a ward for self.vfs"""
476 """build a ward for self.vfs"""
477 rref = weakref.ref(self)
477 rref = weakref.ref(self)
478 def checkvfs(path, mode=None):
478 def checkvfs(path, mode=None):
479 ret = origfunc(path, mode=mode)
479 ret = origfunc(path, mode=mode)
480 repo = rref()
480 repo = rref()
481 if (repo is None
481 if (repo is None
482 or not util.safehasattr(repo, '_wlockref')
482 or not util.safehasattr(repo, '_wlockref')
483 or not util.safehasattr(repo, '_lockref')):
483 or not util.safehasattr(repo, '_lockref')):
484 return
484 return
485 if mode in (None, 'r', 'rb'):
485 if mode in (None, 'r', 'rb'):
486 return
486 return
487 if path.startswith(repo.path):
487 if path.startswith(repo.path):
488 # truncate name relative to the repository (.hg)
488 # truncate name relative to the repository (.hg)
489 path = path[len(repo.path) + 1:]
489 path = path[len(repo.path) + 1:]
490 if path.startswith('cache/'):
491 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
492 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
490 if path.startswith('journal.'):
493 if path.startswith('journal.'):
491 # journal is covered by 'lock'
494 # journal is covered by 'lock'
492 if repo._currentlock(repo._lockref) is None:
495 if repo._currentlock(repo._lockref) is None:
493 repo.ui.develwarn('write with no lock: "%s"' % path,
496 repo.ui.develwarn('write with no lock: "%s"' % path,
494 stacklevel=2, config='check-locks')
497 stacklevel=2, config='check-locks')
495 elif repo._currentlock(repo._wlockref) is None:
498 elif repo._currentlock(repo._wlockref) is None:
496 # rest of vfs files are covered by 'wlock'
499 # rest of vfs files are covered by 'wlock'
497 #
500 #
498 # exclude special files
501 # exclude special files
499 for prefix in self._wlockfreeprefix:
502 for prefix in self._wlockfreeprefix:
500 if path.startswith(prefix):
503 if path.startswith(prefix):
501 return
504 return
502 repo.ui.develwarn('write with no wlock: "%s"' % path,
505 repo.ui.develwarn('write with no wlock: "%s"' % path,
503 stacklevel=2, config='check-locks')
506 stacklevel=2, config='check-locks')
504 return ret
507 return ret
505 return checkvfs
508 return checkvfs
506
509
507 def _getsvfsward(self, origfunc):
510 def _getsvfsward(self, origfunc):
508 """build a ward for self.svfs"""
511 """build a ward for self.svfs"""
509 rref = weakref.ref(self)
512 rref = weakref.ref(self)
510 def checksvfs(path, mode=None):
513 def checksvfs(path, mode=None):
511 ret = origfunc(path, mode=mode)
514 ret = origfunc(path, mode=mode)
512 repo = rref()
515 repo = rref()
513 if repo is None or not util.safehasattr(repo, '_lockref'):
516 if repo is None or not util.safehasattr(repo, '_lockref'):
514 return
517 return
515 if mode in (None, 'r', 'rb'):
518 if mode in (None, 'r', 'rb'):
516 return
519 return
517 if path.startswith(repo.sharedpath):
520 if path.startswith(repo.sharedpath):
518 # truncate name relative to the repository (.hg)
521 # truncate name relative to the repository (.hg)
519 path = path[len(repo.sharedpath) + 1:]
522 path = path[len(repo.sharedpath) + 1:]
520 if repo._currentlock(repo._lockref) is None:
523 if repo._currentlock(repo._lockref) is None:
521 repo.ui.develwarn('write with no lock: "%s"' % path,
524 repo.ui.develwarn('write with no lock: "%s"' % path,
522 stacklevel=3)
525 stacklevel=3)
523 return ret
526 return ret
524 return checksvfs
527 return checksvfs
525
528
526 def close(self):
529 def close(self):
527 self._writecaches()
530 self._writecaches()
528
531
529 def _loadextensions(self):
532 def _loadextensions(self):
530 extensions.loadall(self.ui)
533 extensions.loadall(self.ui)
531
534
532 def _writecaches(self):
535 def _writecaches(self):
533 if self._revbranchcache:
536 if self._revbranchcache:
534 self._revbranchcache.write()
537 self._revbranchcache.write()
535
538
536 def _restrictcapabilities(self, caps):
539 def _restrictcapabilities(self, caps):
537 if self.ui.configbool('experimental', 'bundle2-advertise'):
540 if self.ui.configbool('experimental', 'bundle2-advertise'):
538 caps = set(caps)
541 caps = set(caps)
539 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
542 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
540 caps.add('bundle2=' + urlreq.quote(capsblob))
543 caps.add('bundle2=' + urlreq.quote(capsblob))
541 return caps
544 return caps
542
545
543 def _applyopenerreqs(self):
546 def _applyopenerreqs(self):
544 self.svfs.options = dict((r, 1) for r in self.requirements
547 self.svfs.options = dict((r, 1) for r in self.requirements
545 if r in self.openerreqs)
548 if r in self.openerreqs)
546 # experimental config: format.chunkcachesize
549 # experimental config: format.chunkcachesize
547 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
550 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
548 if chunkcachesize is not None:
551 if chunkcachesize is not None:
549 self.svfs.options['chunkcachesize'] = chunkcachesize
552 self.svfs.options['chunkcachesize'] = chunkcachesize
550 # experimental config: format.maxchainlen
553 # experimental config: format.maxchainlen
551 maxchainlen = self.ui.configint('format', 'maxchainlen')
554 maxchainlen = self.ui.configint('format', 'maxchainlen')
552 if maxchainlen is not None:
555 if maxchainlen is not None:
553 self.svfs.options['maxchainlen'] = maxchainlen
556 self.svfs.options['maxchainlen'] = maxchainlen
554 # experimental config: format.manifestcachesize
557 # experimental config: format.manifestcachesize
555 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
558 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
556 if manifestcachesize is not None:
559 if manifestcachesize is not None:
557 self.svfs.options['manifestcachesize'] = manifestcachesize
560 self.svfs.options['manifestcachesize'] = manifestcachesize
558 # experimental config: format.aggressivemergedeltas
561 # experimental config: format.aggressivemergedeltas
559 aggressivemergedeltas = self.ui.configbool('format',
562 aggressivemergedeltas = self.ui.configbool('format',
560 'aggressivemergedeltas')
563 'aggressivemergedeltas')
561 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
564 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
562 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
565 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
563 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan', -1)
566 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan', -1)
564 if 0 <= chainspan:
567 if 0 <= chainspan:
565 self.svfs.options['maxdeltachainspan'] = chainspan
568 self.svfs.options['maxdeltachainspan'] = chainspan
566
569
567 for r in self.requirements:
570 for r in self.requirements:
568 if r.startswith('exp-compression-'):
571 if r.startswith('exp-compression-'):
569 self.svfs.options['compengine'] = r[len('exp-compression-'):]
572 self.svfs.options['compengine'] = r[len('exp-compression-'):]
570
573
571 # TODO move "revlogv2" to openerreqs once finalized.
574 # TODO move "revlogv2" to openerreqs once finalized.
572 if REVLOGV2_REQUIREMENT in self.requirements:
575 if REVLOGV2_REQUIREMENT in self.requirements:
573 self.svfs.options['revlogv2'] = True
576 self.svfs.options['revlogv2'] = True
574
577
575 def _writerequirements(self):
578 def _writerequirements(self):
576 scmutil.writerequires(self.vfs, self.requirements)
579 scmutil.writerequires(self.vfs, self.requirements)
577
580
578 def _checknested(self, path):
581 def _checknested(self, path):
579 """Determine if path is a legal nested repository."""
582 """Determine if path is a legal nested repository."""
580 if not path.startswith(self.root):
583 if not path.startswith(self.root):
581 return False
584 return False
582 subpath = path[len(self.root) + 1:]
585 subpath = path[len(self.root) + 1:]
583 normsubpath = util.pconvert(subpath)
586 normsubpath = util.pconvert(subpath)
584
587
585 # XXX: Checking against the current working copy is wrong in
588 # XXX: Checking against the current working copy is wrong in
586 # the sense that it can reject things like
589 # the sense that it can reject things like
587 #
590 #
588 # $ hg cat -r 10 sub/x.txt
591 # $ hg cat -r 10 sub/x.txt
589 #
592 #
590 # if sub/ is no longer a subrepository in the working copy
593 # if sub/ is no longer a subrepository in the working copy
591 # parent revision.
594 # parent revision.
592 #
595 #
593 # However, it can of course also allow things that would have
596 # However, it can of course also allow things that would have
594 # been rejected before, such as the above cat command if sub/
597 # been rejected before, such as the above cat command if sub/
595 # is a subrepository now, but was a normal directory before.
598 # is a subrepository now, but was a normal directory before.
596 # The old path auditor would have rejected by mistake since it
599 # The old path auditor would have rejected by mistake since it
597 # panics when it sees sub/.hg/.
600 # panics when it sees sub/.hg/.
598 #
601 #
599 # All in all, checking against the working copy seems sensible
602 # All in all, checking against the working copy seems sensible
600 # since we want to prevent access to nested repositories on
603 # since we want to prevent access to nested repositories on
601 # the filesystem *now*.
604 # the filesystem *now*.
602 ctx = self[None]
605 ctx = self[None]
603 parts = util.splitpath(subpath)
606 parts = util.splitpath(subpath)
604 while parts:
607 while parts:
605 prefix = '/'.join(parts)
608 prefix = '/'.join(parts)
606 if prefix in ctx.substate:
609 if prefix in ctx.substate:
607 if prefix == normsubpath:
610 if prefix == normsubpath:
608 return True
611 return True
609 else:
612 else:
610 sub = ctx.sub(prefix)
613 sub = ctx.sub(prefix)
611 return sub.checknested(subpath[len(prefix) + 1:])
614 return sub.checknested(subpath[len(prefix) + 1:])
612 else:
615 else:
613 parts.pop()
616 parts.pop()
614 return False
617 return False
615
618
616 def peer(self):
619 def peer(self):
617 return localpeer(self) # not cached to avoid reference cycle
620 return localpeer(self) # not cached to avoid reference cycle
618
621
619 def unfiltered(self):
622 def unfiltered(self):
620 """Return unfiltered version of the repository
623 """Return unfiltered version of the repository
621
624
622 Intended to be overwritten by filtered repo."""
625 Intended to be overwritten by filtered repo."""
623 return self
626 return self
624
627
625 def filtered(self, name):
628 def filtered(self, name):
626 """Return a filtered version of a repository"""
629 """Return a filtered version of a repository"""
627 # Python <3.4 easily leaks types via __mro__. See
630 # Python <3.4 easily leaks types via __mro__. See
628 # https://bugs.python.org/issue17950. We cache dynamically
631 # https://bugs.python.org/issue17950. We cache dynamically
629 # created types so this method doesn't leak on every
632 # created types so this method doesn't leak on every
630 # invocation.
633 # invocation.
631
634
632 key = self.unfiltered().__class__
635 key = self.unfiltered().__class__
633 if key not in self._filteredrepotypes:
636 if key not in self._filteredrepotypes:
634 # Build a new type with the repoview mixin and the base
637 # Build a new type with the repoview mixin and the base
635 # class of this repo. Give it a name containing the
638 # class of this repo. Give it a name containing the
636 # filter name to aid debugging.
639 # filter name to aid debugging.
637 bases = (repoview.repoview, key)
640 bases = (repoview.repoview, key)
638 cls = type(r'%sfilteredrepo' % name, bases, {})
641 cls = type(r'%sfilteredrepo' % name, bases, {})
639 self._filteredrepotypes[key] = cls
642 self._filteredrepotypes[key] = cls
640
643
641 return self._filteredrepotypes[key](self, name)
644 return self._filteredrepotypes[key](self, name)
642
645
643 @repofilecache('bookmarks', 'bookmarks.current')
646 @repofilecache('bookmarks', 'bookmarks.current')
644 def _bookmarks(self):
647 def _bookmarks(self):
645 return bookmarks.bmstore(self)
648 return bookmarks.bmstore(self)
646
649
647 @property
650 @property
648 def _activebookmark(self):
651 def _activebookmark(self):
649 return self._bookmarks.active
652 return self._bookmarks.active
650
653
651 # _phaserevs and _phasesets depend on changelog. what we need is to
654 # _phaserevs and _phasesets depend on changelog. what we need is to
652 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
655 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
653 # can't be easily expressed in filecache mechanism.
656 # can't be easily expressed in filecache mechanism.
654 @storecache('phaseroots', '00changelog.i')
657 @storecache('phaseroots', '00changelog.i')
655 def _phasecache(self):
658 def _phasecache(self):
656 return phases.phasecache(self, self._phasedefaults)
659 return phases.phasecache(self, self._phasedefaults)
657
660
658 @storecache('obsstore')
661 @storecache('obsstore')
659 def obsstore(self):
662 def obsstore(self):
660 return obsolete.makestore(self.ui, self)
663 return obsolete.makestore(self.ui, self)
661
664
662 @storecache('00changelog.i')
665 @storecache('00changelog.i')
663 def changelog(self):
666 def changelog(self):
664 return changelog.changelog(self.svfs,
667 return changelog.changelog(self.svfs,
665 trypending=txnutil.mayhavepending(self.root))
668 trypending=txnutil.mayhavepending(self.root))
666
669
667 def _constructmanifest(self):
670 def _constructmanifest(self):
668 # This is a temporary function while we migrate from manifest to
671 # This is a temporary function while we migrate from manifest to
669 # manifestlog. It allows bundlerepo and unionrepo to intercept the
672 # manifestlog. It allows bundlerepo and unionrepo to intercept the
670 # manifest creation.
673 # manifest creation.
671 return manifest.manifestrevlog(self.svfs)
674 return manifest.manifestrevlog(self.svfs)
672
675
673 @storecache('00manifest.i')
676 @storecache('00manifest.i')
674 def manifestlog(self):
677 def manifestlog(self):
675 return manifest.manifestlog(self.svfs, self)
678 return manifest.manifestlog(self.svfs, self)
676
679
677 @repofilecache('dirstate')
680 @repofilecache('dirstate')
678 def dirstate(self):
681 def dirstate(self):
679 sparsematchfn = lambda: sparse.matcher(self)
682 sparsematchfn = lambda: sparse.matcher(self)
680
683
681 return dirstate.dirstate(self.vfs, self.ui, self.root,
684 return dirstate.dirstate(self.vfs, self.ui, self.root,
682 self._dirstatevalidate, sparsematchfn)
685 self._dirstatevalidate, sparsematchfn)
683
686
684 def _dirstatevalidate(self, node):
687 def _dirstatevalidate(self, node):
685 try:
688 try:
686 self.changelog.rev(node)
689 self.changelog.rev(node)
687 return node
690 return node
688 except error.LookupError:
691 except error.LookupError:
689 if not self._dirstatevalidatewarned:
692 if not self._dirstatevalidatewarned:
690 self._dirstatevalidatewarned = True
693 self._dirstatevalidatewarned = True
691 self.ui.warn(_("warning: ignoring unknown"
694 self.ui.warn(_("warning: ignoring unknown"
692 " working parent %s!\n") % short(node))
695 " working parent %s!\n") % short(node))
693 return nullid
696 return nullid
694
697
695 def __getitem__(self, changeid):
698 def __getitem__(self, changeid):
696 if changeid is None:
699 if changeid is None:
697 return context.workingctx(self)
700 return context.workingctx(self)
698 if isinstance(changeid, slice):
701 if isinstance(changeid, slice):
699 # wdirrev isn't contiguous so the slice shouldn't include it
702 # wdirrev isn't contiguous so the slice shouldn't include it
700 return [context.changectx(self, i)
703 return [context.changectx(self, i)
701 for i in xrange(*changeid.indices(len(self)))
704 for i in xrange(*changeid.indices(len(self)))
702 if i not in self.changelog.filteredrevs]
705 if i not in self.changelog.filteredrevs]
703 try:
706 try:
704 return context.changectx(self, changeid)
707 return context.changectx(self, changeid)
705 except error.WdirUnsupported:
708 except error.WdirUnsupported:
706 return context.workingctx(self)
709 return context.workingctx(self)
707
710
708 def __contains__(self, changeid):
711 def __contains__(self, changeid):
709 """True if the given changeid exists
712 """True if the given changeid exists
710
713
711 error.LookupError is raised if an ambiguous node specified.
714 error.LookupError is raised if an ambiguous node specified.
712 """
715 """
713 try:
716 try:
714 self[changeid]
717 self[changeid]
715 return True
718 return True
716 except error.RepoLookupError:
719 except error.RepoLookupError:
717 return False
720 return False
718
721
719 def __nonzero__(self):
722 def __nonzero__(self):
720 return True
723 return True
721
724
722 __bool__ = __nonzero__
725 __bool__ = __nonzero__
723
726
724 def __len__(self):
727 def __len__(self):
725 return len(self.changelog)
728 return len(self.changelog)
726
729
727 def __iter__(self):
730 def __iter__(self):
728 return iter(self.changelog)
731 return iter(self.changelog)
729
732
730 def revs(self, expr, *args):
733 def revs(self, expr, *args):
731 '''Find revisions matching a revset.
734 '''Find revisions matching a revset.
732
735
733 The revset is specified as a string ``expr`` that may contain
736 The revset is specified as a string ``expr`` that may contain
734 %-formatting to escape certain types. See ``revsetlang.formatspec``.
737 %-formatting to escape certain types. See ``revsetlang.formatspec``.
735
738
736 Revset aliases from the configuration are not expanded. To expand
739 Revset aliases from the configuration are not expanded. To expand
737 user aliases, consider calling ``scmutil.revrange()`` or
740 user aliases, consider calling ``scmutil.revrange()`` or
738 ``repo.anyrevs([expr], user=True)``.
741 ``repo.anyrevs([expr], user=True)``.
739
742
740 Returns a revset.abstractsmartset, which is a list-like interface
743 Returns a revset.abstractsmartset, which is a list-like interface
741 that contains integer revisions.
744 that contains integer revisions.
742 '''
745 '''
743 expr = revsetlang.formatspec(expr, *args)
746 expr = revsetlang.formatspec(expr, *args)
744 m = revset.match(None, expr)
747 m = revset.match(None, expr)
745 return m(self)
748 return m(self)
746
749
747 def set(self, expr, *args):
750 def set(self, expr, *args):
748 '''Find revisions matching a revset and emit changectx instances.
751 '''Find revisions matching a revset and emit changectx instances.
749
752
750 This is a convenience wrapper around ``revs()`` that iterates the
753 This is a convenience wrapper around ``revs()`` that iterates the
751 result and is a generator of changectx instances.
754 result and is a generator of changectx instances.
752
755
753 Revset aliases from the configuration are not expanded. To expand
756 Revset aliases from the configuration are not expanded. To expand
754 user aliases, consider calling ``scmutil.revrange()``.
757 user aliases, consider calling ``scmutil.revrange()``.
755 '''
758 '''
756 for r in self.revs(expr, *args):
759 for r in self.revs(expr, *args):
757 yield self[r]
760 yield self[r]
758
761
759 def anyrevs(self, specs, user=False, localalias=None):
762 def anyrevs(self, specs, user=False, localalias=None):
760 '''Find revisions matching one of the given revsets.
763 '''Find revisions matching one of the given revsets.
761
764
762 Revset aliases from the configuration are not expanded by default. To
765 Revset aliases from the configuration are not expanded by default. To
763 expand user aliases, specify ``user=True``. To provide some local
766 expand user aliases, specify ``user=True``. To provide some local
764 definitions overriding user aliases, set ``localalias`` to
767 definitions overriding user aliases, set ``localalias`` to
765 ``{name: definitionstring}``.
768 ``{name: definitionstring}``.
766 '''
769 '''
767 if user:
770 if user:
768 m = revset.matchany(self.ui, specs, repo=self,
771 m = revset.matchany(self.ui, specs, repo=self,
769 localalias=localalias)
772 localalias=localalias)
770 else:
773 else:
771 m = revset.matchany(None, specs, localalias=localalias)
774 m = revset.matchany(None, specs, localalias=localalias)
772 return m(self)
775 return m(self)
773
776
774 def url(self):
777 def url(self):
775 return 'file:' + self.root
778 return 'file:' + self.root
776
779
777 def hook(self, name, throw=False, **args):
780 def hook(self, name, throw=False, **args):
778 """Call a hook, passing this repo instance.
781 """Call a hook, passing this repo instance.
779
782
780 This a convenience method to aid invoking hooks. Extensions likely
783 This a convenience method to aid invoking hooks. Extensions likely
781 won't call this unless they have registered a custom hook or are
784 won't call this unless they have registered a custom hook or are
782 replacing code that is expected to call a hook.
785 replacing code that is expected to call a hook.
783 """
786 """
784 return hook.hook(self.ui, self, name, throw, **args)
787 return hook.hook(self.ui, self, name, throw, **args)
785
788
786 @filteredpropertycache
789 @filteredpropertycache
787 def _tagscache(self):
790 def _tagscache(self):
788 '''Returns a tagscache object that contains various tags related
791 '''Returns a tagscache object that contains various tags related
789 caches.'''
792 caches.'''
790
793
791 # This simplifies its cache management by having one decorated
794 # This simplifies its cache management by having one decorated
792 # function (this one) and the rest simply fetch things from it.
795 # function (this one) and the rest simply fetch things from it.
793 class tagscache(object):
796 class tagscache(object):
794 def __init__(self):
797 def __init__(self):
795 # These two define the set of tags for this repository. tags
798 # These two define the set of tags for this repository. tags
796 # maps tag name to node; tagtypes maps tag name to 'global' or
799 # maps tag name to node; tagtypes maps tag name to 'global' or
797 # 'local'. (Global tags are defined by .hgtags across all
800 # 'local'. (Global tags are defined by .hgtags across all
798 # heads, and local tags are defined in .hg/localtags.)
801 # heads, and local tags are defined in .hg/localtags.)
799 # They constitute the in-memory cache of tags.
802 # They constitute the in-memory cache of tags.
800 self.tags = self.tagtypes = None
803 self.tags = self.tagtypes = None
801
804
802 self.nodetagscache = self.tagslist = None
805 self.nodetagscache = self.tagslist = None
803
806
804 cache = tagscache()
807 cache = tagscache()
805 cache.tags, cache.tagtypes = self._findtags()
808 cache.tags, cache.tagtypes = self._findtags()
806
809
807 return cache
810 return cache
808
811
809 def tags(self):
812 def tags(self):
810 '''return a mapping of tag to node'''
813 '''return a mapping of tag to node'''
811 t = {}
814 t = {}
812 if self.changelog.filteredrevs:
815 if self.changelog.filteredrevs:
813 tags, tt = self._findtags()
816 tags, tt = self._findtags()
814 else:
817 else:
815 tags = self._tagscache.tags
818 tags = self._tagscache.tags
816 for k, v in tags.iteritems():
819 for k, v in tags.iteritems():
817 try:
820 try:
818 # ignore tags to unknown nodes
821 # ignore tags to unknown nodes
819 self.changelog.rev(v)
822 self.changelog.rev(v)
820 t[k] = v
823 t[k] = v
821 except (error.LookupError, ValueError):
824 except (error.LookupError, ValueError):
822 pass
825 pass
823 return t
826 return t
824
827
825 def _findtags(self):
828 def _findtags(self):
826 '''Do the hard work of finding tags. Return a pair of dicts
829 '''Do the hard work of finding tags. Return a pair of dicts
827 (tags, tagtypes) where tags maps tag name to node, and tagtypes
830 (tags, tagtypes) where tags maps tag name to node, and tagtypes
828 maps tag name to a string like \'global\' or \'local\'.
831 maps tag name to a string like \'global\' or \'local\'.
829 Subclasses or extensions are free to add their own tags, but
832 Subclasses or extensions are free to add their own tags, but
830 should be aware that the returned dicts will be retained for the
833 should be aware that the returned dicts will be retained for the
831 duration of the localrepo object.'''
834 duration of the localrepo object.'''
832
835
833 # XXX what tagtype should subclasses/extensions use? Currently
836 # XXX what tagtype should subclasses/extensions use? Currently
834 # mq and bookmarks add tags, but do not set the tagtype at all.
837 # mq and bookmarks add tags, but do not set the tagtype at all.
835 # Should each extension invent its own tag type? Should there
838 # Should each extension invent its own tag type? Should there
836 # be one tagtype for all such "virtual" tags? Or is the status
839 # be one tagtype for all such "virtual" tags? Or is the status
837 # quo fine?
840 # quo fine?
838
841
839
842
840 # map tag name to (node, hist)
843 # map tag name to (node, hist)
841 alltags = tagsmod.findglobaltags(self.ui, self)
844 alltags = tagsmod.findglobaltags(self.ui, self)
842 # map tag name to tag type
845 # map tag name to tag type
843 tagtypes = dict((tag, 'global') for tag in alltags)
846 tagtypes = dict((tag, 'global') for tag in alltags)
844
847
845 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
848 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
846
849
847 # Build the return dicts. Have to re-encode tag names because
850 # Build the return dicts. Have to re-encode tag names because
848 # the tags module always uses UTF-8 (in order not to lose info
851 # the tags module always uses UTF-8 (in order not to lose info
849 # writing to the cache), but the rest of Mercurial wants them in
852 # writing to the cache), but the rest of Mercurial wants them in
850 # local encoding.
853 # local encoding.
851 tags = {}
854 tags = {}
852 for (name, (node, hist)) in alltags.iteritems():
855 for (name, (node, hist)) in alltags.iteritems():
853 if node != nullid:
856 if node != nullid:
854 tags[encoding.tolocal(name)] = node
857 tags[encoding.tolocal(name)] = node
855 tags['tip'] = self.changelog.tip()
858 tags['tip'] = self.changelog.tip()
856 tagtypes = dict([(encoding.tolocal(name), value)
859 tagtypes = dict([(encoding.tolocal(name), value)
857 for (name, value) in tagtypes.iteritems()])
860 for (name, value) in tagtypes.iteritems()])
858 return (tags, tagtypes)
861 return (tags, tagtypes)
859
862
860 def tagtype(self, tagname):
863 def tagtype(self, tagname):
861 '''
864 '''
862 return the type of the given tag. result can be:
865 return the type of the given tag. result can be:
863
866
864 'local' : a local tag
867 'local' : a local tag
865 'global' : a global tag
868 'global' : a global tag
866 None : tag does not exist
869 None : tag does not exist
867 '''
870 '''
868
871
869 return self._tagscache.tagtypes.get(tagname)
872 return self._tagscache.tagtypes.get(tagname)
870
873
871 def tagslist(self):
874 def tagslist(self):
872 '''return a list of tags ordered by revision'''
875 '''return a list of tags ordered by revision'''
873 if not self._tagscache.tagslist:
876 if not self._tagscache.tagslist:
874 l = []
877 l = []
875 for t, n in self.tags().iteritems():
878 for t, n in self.tags().iteritems():
876 l.append((self.changelog.rev(n), t, n))
879 l.append((self.changelog.rev(n), t, n))
877 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
880 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
878
881
879 return self._tagscache.tagslist
882 return self._tagscache.tagslist
880
883
881 def nodetags(self, node):
884 def nodetags(self, node):
882 '''return the tags associated with a node'''
885 '''return the tags associated with a node'''
883 if not self._tagscache.nodetagscache:
886 if not self._tagscache.nodetagscache:
884 nodetagscache = {}
887 nodetagscache = {}
885 for t, n in self._tagscache.tags.iteritems():
888 for t, n in self._tagscache.tags.iteritems():
886 nodetagscache.setdefault(n, []).append(t)
889 nodetagscache.setdefault(n, []).append(t)
887 for tags in nodetagscache.itervalues():
890 for tags in nodetagscache.itervalues():
888 tags.sort()
891 tags.sort()
889 self._tagscache.nodetagscache = nodetagscache
892 self._tagscache.nodetagscache = nodetagscache
890 return self._tagscache.nodetagscache.get(node, [])
893 return self._tagscache.nodetagscache.get(node, [])
891
894
892 def nodebookmarks(self, node):
895 def nodebookmarks(self, node):
893 """return the list of bookmarks pointing to the specified node"""
896 """return the list of bookmarks pointing to the specified node"""
894 marks = []
897 marks = []
895 for bookmark, n in self._bookmarks.iteritems():
898 for bookmark, n in self._bookmarks.iteritems():
896 if n == node:
899 if n == node:
897 marks.append(bookmark)
900 marks.append(bookmark)
898 return sorted(marks)
901 return sorted(marks)
899
902
900 def branchmap(self):
903 def branchmap(self):
901 '''returns a dictionary {branch: [branchheads]} with branchheads
904 '''returns a dictionary {branch: [branchheads]} with branchheads
902 ordered by increasing revision number'''
905 ordered by increasing revision number'''
903 branchmap.updatecache(self)
906 branchmap.updatecache(self)
904 return self._branchcaches[self.filtername]
907 return self._branchcaches[self.filtername]
905
908
906 @unfilteredmethod
909 @unfilteredmethod
907 def revbranchcache(self):
910 def revbranchcache(self):
908 if not self._revbranchcache:
911 if not self._revbranchcache:
909 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
912 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
910 return self._revbranchcache
913 return self._revbranchcache
911
914
912 def branchtip(self, branch, ignoremissing=False):
915 def branchtip(self, branch, ignoremissing=False):
913 '''return the tip node for a given branch
916 '''return the tip node for a given branch
914
917
915 If ignoremissing is True, then this method will not raise an error.
918 If ignoremissing is True, then this method will not raise an error.
916 This is helpful for callers that only expect None for a missing branch
919 This is helpful for callers that only expect None for a missing branch
917 (e.g. namespace).
920 (e.g. namespace).
918
921
919 '''
922 '''
920 try:
923 try:
921 return self.branchmap().branchtip(branch)
924 return self.branchmap().branchtip(branch)
922 except KeyError:
925 except KeyError:
923 if not ignoremissing:
926 if not ignoremissing:
924 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
927 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
925 else:
928 else:
926 pass
929 pass
927
930
928 def lookup(self, key):
931 def lookup(self, key):
929 return self[key].node()
932 return self[key].node()
930
933
931 def lookupbranch(self, key, remote=None):
934 def lookupbranch(self, key, remote=None):
932 repo = remote or self
935 repo = remote or self
933 if key in repo.branchmap():
936 if key in repo.branchmap():
934 return key
937 return key
935
938
936 repo = (remote and remote.local()) and remote or self
939 repo = (remote and remote.local()) and remote or self
937 return repo[key].branch()
940 return repo[key].branch()
938
941
939 def known(self, nodes):
942 def known(self, nodes):
940 cl = self.changelog
943 cl = self.changelog
941 nm = cl.nodemap
944 nm = cl.nodemap
942 filtered = cl.filteredrevs
945 filtered = cl.filteredrevs
943 result = []
946 result = []
944 for n in nodes:
947 for n in nodes:
945 r = nm.get(n)
948 r = nm.get(n)
946 resp = not (r is None or r in filtered)
949 resp = not (r is None or r in filtered)
947 result.append(resp)
950 result.append(resp)
948 return result
951 return result
949
952
950 def local(self):
953 def local(self):
951 return self
954 return self
952
955
953 def publishing(self):
956 def publishing(self):
954 # it's safe (and desirable) to trust the publish flag unconditionally
957 # it's safe (and desirable) to trust the publish flag unconditionally
955 # so that we don't finalize changes shared between users via ssh or nfs
958 # so that we don't finalize changes shared between users via ssh or nfs
956 return self.ui.configbool('phases', 'publish', untrusted=True)
959 return self.ui.configbool('phases', 'publish', untrusted=True)
957
960
958 def cancopy(self):
961 def cancopy(self):
959 # so statichttprepo's override of local() works
962 # so statichttprepo's override of local() works
960 if not self.local():
963 if not self.local():
961 return False
964 return False
962 if not self.publishing():
965 if not self.publishing():
963 return True
966 return True
964 # if publishing we can't copy if there is filtered content
967 # if publishing we can't copy if there is filtered content
965 return not self.filtered('visible').changelog.filteredrevs
968 return not self.filtered('visible').changelog.filteredrevs
966
969
967 def shared(self):
970 def shared(self):
968 '''the type of shared repository (None if not shared)'''
971 '''the type of shared repository (None if not shared)'''
969 if self.sharedpath != self.path:
972 if self.sharedpath != self.path:
970 return 'store'
973 return 'store'
971 return None
974 return None
972
975
973 def wjoin(self, f, *insidef):
976 def wjoin(self, f, *insidef):
974 return self.vfs.reljoin(self.root, f, *insidef)
977 return self.vfs.reljoin(self.root, f, *insidef)
975
978
976 def file(self, f):
979 def file(self, f):
977 if f[0] == '/':
980 if f[0] == '/':
978 f = f[1:]
981 f = f[1:]
979 return filelog.filelog(self.svfs, f)
982 return filelog.filelog(self.svfs, f)
980
983
981 def changectx(self, changeid):
984 def changectx(self, changeid):
982 return self[changeid]
985 return self[changeid]
983
986
984 def setparents(self, p1, p2=nullid):
987 def setparents(self, p1, p2=nullid):
985 with self.dirstate.parentchange():
988 with self.dirstate.parentchange():
986 copies = self.dirstate.setparents(p1, p2)
989 copies = self.dirstate.setparents(p1, p2)
987 pctx = self[p1]
990 pctx = self[p1]
988 if copies:
991 if copies:
989 # Adjust copy records, the dirstate cannot do it, it
992 # Adjust copy records, the dirstate cannot do it, it
990 # requires access to parents manifests. Preserve them
993 # requires access to parents manifests. Preserve them
991 # only for entries added to first parent.
994 # only for entries added to first parent.
992 for f in copies:
995 for f in copies:
993 if f not in pctx and copies[f] in pctx:
996 if f not in pctx and copies[f] in pctx:
994 self.dirstate.copy(copies[f], f)
997 self.dirstate.copy(copies[f], f)
995 if p2 == nullid:
998 if p2 == nullid:
996 for f, s in sorted(self.dirstate.copies().items()):
999 for f, s in sorted(self.dirstate.copies().items()):
997 if f not in pctx and s not in pctx:
1000 if f not in pctx and s not in pctx:
998 self.dirstate.copy(None, f)
1001 self.dirstate.copy(None, f)
999
1002
1000 def filectx(self, path, changeid=None, fileid=None):
1003 def filectx(self, path, changeid=None, fileid=None):
1001 """changeid can be a changeset revision, node, or tag.
1004 """changeid can be a changeset revision, node, or tag.
1002 fileid can be a file revision or node."""
1005 fileid can be a file revision or node."""
1003 return context.filectx(self, path, changeid, fileid)
1006 return context.filectx(self, path, changeid, fileid)
1004
1007
1005 def getcwd(self):
1008 def getcwd(self):
1006 return self.dirstate.getcwd()
1009 return self.dirstate.getcwd()
1007
1010
1008 def pathto(self, f, cwd=None):
1011 def pathto(self, f, cwd=None):
1009 return self.dirstate.pathto(f, cwd)
1012 return self.dirstate.pathto(f, cwd)
1010
1013
1011 def _loadfilter(self, filter):
1014 def _loadfilter(self, filter):
1012 if filter not in self.filterpats:
1015 if filter not in self.filterpats:
1013 l = []
1016 l = []
1014 for pat, cmd in self.ui.configitems(filter):
1017 for pat, cmd in self.ui.configitems(filter):
1015 if cmd == '!':
1018 if cmd == '!':
1016 continue
1019 continue
1017 mf = matchmod.match(self.root, '', [pat])
1020 mf = matchmod.match(self.root, '', [pat])
1018 fn = None
1021 fn = None
1019 params = cmd
1022 params = cmd
1020 for name, filterfn in self._datafilters.iteritems():
1023 for name, filterfn in self._datafilters.iteritems():
1021 if cmd.startswith(name):
1024 if cmd.startswith(name):
1022 fn = filterfn
1025 fn = filterfn
1023 params = cmd[len(name):].lstrip()
1026 params = cmd[len(name):].lstrip()
1024 break
1027 break
1025 if not fn:
1028 if not fn:
1026 fn = lambda s, c, **kwargs: util.filter(s, c)
1029 fn = lambda s, c, **kwargs: util.filter(s, c)
1027 # Wrap old filters not supporting keyword arguments
1030 # Wrap old filters not supporting keyword arguments
1028 if not inspect.getargspec(fn)[2]:
1031 if not inspect.getargspec(fn)[2]:
1029 oldfn = fn
1032 oldfn = fn
1030 fn = lambda s, c, **kwargs: oldfn(s, c)
1033 fn = lambda s, c, **kwargs: oldfn(s, c)
1031 l.append((mf, fn, params))
1034 l.append((mf, fn, params))
1032 self.filterpats[filter] = l
1035 self.filterpats[filter] = l
1033 return self.filterpats[filter]
1036 return self.filterpats[filter]
1034
1037
1035 def _filter(self, filterpats, filename, data):
1038 def _filter(self, filterpats, filename, data):
1036 for mf, fn, cmd in filterpats:
1039 for mf, fn, cmd in filterpats:
1037 if mf(filename):
1040 if mf(filename):
1038 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1041 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1039 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1042 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1040 break
1043 break
1041
1044
1042 return data
1045 return data
1043
1046
1044 @unfilteredpropertycache
1047 @unfilteredpropertycache
1045 def _encodefilterpats(self):
1048 def _encodefilterpats(self):
1046 return self._loadfilter('encode')
1049 return self._loadfilter('encode')
1047
1050
1048 @unfilteredpropertycache
1051 @unfilteredpropertycache
1049 def _decodefilterpats(self):
1052 def _decodefilterpats(self):
1050 return self._loadfilter('decode')
1053 return self._loadfilter('decode')
1051
1054
1052 def adddatafilter(self, name, filter):
1055 def adddatafilter(self, name, filter):
1053 self._datafilters[name] = filter
1056 self._datafilters[name] = filter
1054
1057
1055 def wread(self, filename):
1058 def wread(self, filename):
1056 if self.wvfs.islink(filename):
1059 if self.wvfs.islink(filename):
1057 data = self.wvfs.readlink(filename)
1060 data = self.wvfs.readlink(filename)
1058 else:
1061 else:
1059 data = self.wvfs.read(filename)
1062 data = self.wvfs.read(filename)
1060 return self._filter(self._encodefilterpats, filename, data)
1063 return self._filter(self._encodefilterpats, filename, data)
1061
1064
1062 def wwrite(self, filename, data, flags, backgroundclose=False):
1065 def wwrite(self, filename, data, flags, backgroundclose=False):
1063 """write ``data`` into ``filename`` in the working directory
1066 """write ``data`` into ``filename`` in the working directory
1064
1067
1065 This returns length of written (maybe decoded) data.
1068 This returns length of written (maybe decoded) data.
1066 """
1069 """
1067 data = self._filter(self._decodefilterpats, filename, data)
1070 data = self._filter(self._decodefilterpats, filename, data)
1068 if 'l' in flags:
1071 if 'l' in flags:
1069 self.wvfs.symlink(data, filename)
1072 self.wvfs.symlink(data, filename)
1070 else:
1073 else:
1071 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1074 self.wvfs.write(filename, data, backgroundclose=backgroundclose)
1072 if 'x' in flags:
1075 if 'x' in flags:
1073 self.wvfs.setflags(filename, False, True)
1076 self.wvfs.setflags(filename, False, True)
1074 return len(data)
1077 return len(data)
1075
1078
1076 def wwritedata(self, filename, data):
1079 def wwritedata(self, filename, data):
1077 return self._filter(self._decodefilterpats, filename, data)
1080 return self._filter(self._decodefilterpats, filename, data)
1078
1081
1079 def currenttransaction(self):
1082 def currenttransaction(self):
1080 """return the current transaction or None if non exists"""
1083 """return the current transaction or None if non exists"""
1081 if self._transref:
1084 if self._transref:
1082 tr = self._transref()
1085 tr = self._transref()
1083 else:
1086 else:
1084 tr = None
1087 tr = None
1085
1088
1086 if tr and tr.running():
1089 if tr and tr.running():
1087 return tr
1090 return tr
1088 return None
1091 return None
1089
1092
1090 def transaction(self, desc, report=None):
1093 def transaction(self, desc, report=None):
1091 if (self.ui.configbool('devel', 'all-warnings')
1094 if (self.ui.configbool('devel', 'all-warnings')
1092 or self.ui.configbool('devel', 'check-locks')):
1095 or self.ui.configbool('devel', 'check-locks')):
1093 if self._currentlock(self._lockref) is None:
1096 if self._currentlock(self._lockref) is None:
1094 raise error.ProgrammingError('transaction requires locking')
1097 raise error.ProgrammingError('transaction requires locking')
1095 tr = self.currenttransaction()
1098 tr = self.currenttransaction()
1096 if tr is not None:
1099 if tr is not None:
1097 return tr.nest()
1100 return tr.nest()
1098
1101
1099 # abort here if the journal already exists
1102 # abort here if the journal already exists
1100 if self.svfs.exists("journal"):
1103 if self.svfs.exists("journal"):
1101 raise error.RepoError(
1104 raise error.RepoError(
1102 _("abandoned transaction found"),
1105 _("abandoned transaction found"),
1103 hint=_("run 'hg recover' to clean up transaction"))
1106 hint=_("run 'hg recover' to clean up transaction"))
1104
1107
1105 idbase = "%.40f#%f" % (random.random(), time.time())
1108 idbase = "%.40f#%f" % (random.random(), time.time())
1106 ha = hex(hashlib.sha1(idbase).digest())
1109 ha = hex(hashlib.sha1(idbase).digest())
1107 txnid = 'TXN:' + ha
1110 txnid = 'TXN:' + ha
1108 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1111 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1109
1112
1110 self._writejournal(desc)
1113 self._writejournal(desc)
1111 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1114 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1112 if report:
1115 if report:
1113 rp = report
1116 rp = report
1114 else:
1117 else:
1115 rp = self.ui.warn
1118 rp = self.ui.warn
1116 vfsmap = {'plain': self.vfs} # root of .hg/
1119 vfsmap = {'plain': self.vfs} # root of .hg/
1117 # we must avoid cyclic reference between repo and transaction.
1120 # we must avoid cyclic reference between repo and transaction.
1118 reporef = weakref.ref(self)
1121 reporef = weakref.ref(self)
1119 # Code to track tag movement
1122 # Code to track tag movement
1120 #
1123 #
1121 # Since tags are all handled as file content, it is actually quite hard
1124 # Since tags are all handled as file content, it is actually quite hard
1122 # to track these movement from a code perspective. So we fallback to a
1125 # to track these movement from a code perspective. So we fallback to a
1123 # tracking at the repository level. One could envision to track changes
1126 # tracking at the repository level. One could envision to track changes
1124 # to the '.hgtags' file through changegroup apply but that fails to
1127 # to the '.hgtags' file through changegroup apply but that fails to
1125 # cope with case where transaction expose new heads without changegroup
1128 # cope with case where transaction expose new heads without changegroup
1126 # being involved (eg: phase movement).
1129 # being involved (eg: phase movement).
1127 #
1130 #
1128 # For now, We gate the feature behind a flag since this likely comes
1131 # For now, We gate the feature behind a flag since this likely comes
1129 # with performance impacts. The current code run more often than needed
1132 # with performance impacts. The current code run more often than needed
1130 # and do not use caches as much as it could. The current focus is on
1133 # and do not use caches as much as it could. The current focus is on
1131 # the behavior of the feature so we disable it by default. The flag
1134 # the behavior of the feature so we disable it by default. The flag
1132 # will be removed when we are happy with the performance impact.
1135 # will be removed when we are happy with the performance impact.
1133 #
1136 #
1134 # Once this feature is no longer experimental move the following
1137 # Once this feature is no longer experimental move the following
1135 # documentation to the appropriate help section:
1138 # documentation to the appropriate help section:
1136 #
1139 #
1137 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1140 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1138 # tags (new or changed or deleted tags). In addition the details of
1141 # tags (new or changed or deleted tags). In addition the details of
1139 # these changes are made available in a file at:
1142 # these changes are made available in a file at:
1140 # ``REPOROOT/.hg/changes/tags.changes``.
1143 # ``REPOROOT/.hg/changes/tags.changes``.
1141 # Make sure you check for HG_TAG_MOVED before reading that file as it
1144 # Make sure you check for HG_TAG_MOVED before reading that file as it
1142 # might exist from a previous transaction even if no tag were touched
1145 # might exist from a previous transaction even if no tag were touched
1143 # in this one. Changes are recorded in a line base format::
1146 # in this one. Changes are recorded in a line base format::
1144 #
1147 #
1145 # <action> <hex-node> <tag-name>\n
1148 # <action> <hex-node> <tag-name>\n
1146 #
1149 #
1147 # Actions are defined as follow:
1150 # Actions are defined as follow:
1148 # "-R": tag is removed,
1151 # "-R": tag is removed,
1149 # "+A": tag is added,
1152 # "+A": tag is added,
1150 # "-M": tag is moved (old value),
1153 # "-M": tag is moved (old value),
1151 # "+M": tag is moved (new value),
1154 # "+M": tag is moved (new value),
1152 tracktags = lambda x: None
1155 tracktags = lambda x: None
1153 # experimental config: experimental.hook-track-tags
1156 # experimental config: experimental.hook-track-tags
1154 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1157 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1155 if desc != 'strip' and shouldtracktags:
1158 if desc != 'strip' and shouldtracktags:
1156 oldheads = self.changelog.headrevs()
1159 oldheads = self.changelog.headrevs()
1157 def tracktags(tr2):
1160 def tracktags(tr2):
1158 repo = reporef()
1161 repo = reporef()
1159 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1162 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1160 newheads = repo.changelog.headrevs()
1163 newheads = repo.changelog.headrevs()
1161 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1164 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1162 # notes: we compare lists here.
1165 # notes: we compare lists here.
1163 # As we do it only once buiding set would not be cheaper
1166 # As we do it only once buiding set would not be cheaper
1164 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1167 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1165 if changes:
1168 if changes:
1166 tr2.hookargs['tag_moved'] = '1'
1169 tr2.hookargs['tag_moved'] = '1'
1167 with repo.vfs('changes/tags.changes', 'w',
1170 with repo.vfs('changes/tags.changes', 'w',
1168 atomictemp=True) as changesfile:
1171 atomictemp=True) as changesfile:
1169 # note: we do not register the file to the transaction
1172 # note: we do not register the file to the transaction
1170 # because we needs it to still exist on the transaction
1173 # because we needs it to still exist on the transaction
1171 # is close (for txnclose hooks)
1174 # is close (for txnclose hooks)
1172 tagsmod.writediff(changesfile, changes)
1175 tagsmod.writediff(changesfile, changes)
1173 def validate(tr2):
1176 def validate(tr2):
1174 """will run pre-closing hooks"""
1177 """will run pre-closing hooks"""
1175 # XXX the transaction API is a bit lacking here so we take a hacky
1178 # XXX the transaction API is a bit lacking here so we take a hacky
1176 # path for now
1179 # path for now
1177 #
1180 #
1178 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1181 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1179 # dict is copied before these run. In addition we needs the data
1182 # dict is copied before these run. In addition we needs the data
1180 # available to in memory hooks too.
1183 # available to in memory hooks too.
1181 #
1184 #
1182 # Moreover, we also need to make sure this runs before txnclose
1185 # Moreover, we also need to make sure this runs before txnclose
1183 # hooks and there is no "pending" mechanism that would execute
1186 # hooks and there is no "pending" mechanism that would execute
1184 # logic only if hooks are about to run.
1187 # logic only if hooks are about to run.
1185 #
1188 #
1186 # Fixing this limitation of the transaction is also needed to track
1189 # Fixing this limitation of the transaction is also needed to track
1187 # other families of changes (bookmarks, phases, obsolescence).
1190 # other families of changes (bookmarks, phases, obsolescence).
1188 #
1191 #
1189 # This will have to be fixed before we remove the experimental
1192 # This will have to be fixed before we remove the experimental
1190 # gating.
1193 # gating.
1191 tracktags(tr2)
1194 tracktags(tr2)
1192 reporef().hook('pretxnclose', throw=True,
1195 reporef().hook('pretxnclose', throw=True,
1193 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1196 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1194 def releasefn(tr, success):
1197 def releasefn(tr, success):
1195 repo = reporef()
1198 repo = reporef()
1196 if success:
1199 if success:
1197 # this should be explicitly invoked here, because
1200 # this should be explicitly invoked here, because
1198 # in-memory changes aren't written out at closing
1201 # in-memory changes aren't written out at closing
1199 # transaction, if tr.addfilegenerator (via
1202 # transaction, if tr.addfilegenerator (via
1200 # dirstate.write or so) isn't invoked while
1203 # dirstate.write or so) isn't invoked while
1201 # transaction running
1204 # transaction running
1202 repo.dirstate.write(None)
1205 repo.dirstate.write(None)
1203 else:
1206 else:
1204 # discard all changes (including ones already written
1207 # discard all changes (including ones already written
1205 # out) in this transaction
1208 # out) in this transaction
1206 repo.dirstate.restorebackup(None, 'journal.dirstate')
1209 repo.dirstate.restorebackup(None, 'journal.dirstate')
1207
1210
1208 repo.invalidate(clearfilecache=True)
1211 repo.invalidate(clearfilecache=True)
1209
1212
1210 tr = transaction.transaction(rp, self.svfs, vfsmap,
1213 tr = transaction.transaction(rp, self.svfs, vfsmap,
1211 "journal",
1214 "journal",
1212 "undo",
1215 "undo",
1213 aftertrans(renames),
1216 aftertrans(renames),
1214 self.store.createmode,
1217 self.store.createmode,
1215 validator=validate,
1218 validator=validate,
1216 releasefn=releasefn,
1219 releasefn=releasefn,
1217 checkambigfiles=_cachedfiles)
1220 checkambigfiles=_cachedfiles)
1218 tr.changes['revs'] = set()
1221 tr.changes['revs'] = set()
1219 tr.changes['obsmarkers'] = set()
1222 tr.changes['obsmarkers'] = set()
1220 tr.changes['phases'] = {}
1223 tr.changes['phases'] = {}
1221 tr.changes['bookmarks'] = {}
1224 tr.changes['bookmarks'] = {}
1222
1225
1223 tr.hookargs['txnid'] = txnid
1226 tr.hookargs['txnid'] = txnid
1224 # note: writing the fncache only during finalize mean that the file is
1227 # note: writing the fncache only during finalize mean that the file is
1225 # outdated when running hooks. As fncache is used for streaming clone,
1228 # outdated when running hooks. As fncache is used for streaming clone,
1226 # this is not expected to break anything that happen during the hooks.
1229 # this is not expected to break anything that happen during the hooks.
1227 tr.addfinalize('flush-fncache', self.store.write)
1230 tr.addfinalize('flush-fncache', self.store.write)
1228 def txnclosehook(tr2):
1231 def txnclosehook(tr2):
1229 """To be run if transaction is successful, will schedule a hook run
1232 """To be run if transaction is successful, will schedule a hook run
1230 """
1233 """
1231 # Don't reference tr2 in hook() so we don't hold a reference.
1234 # Don't reference tr2 in hook() so we don't hold a reference.
1232 # This reduces memory consumption when there are multiple
1235 # This reduces memory consumption when there are multiple
1233 # transactions per lock. This can likely go away if issue5045
1236 # transactions per lock. This can likely go away if issue5045
1234 # fixes the function accumulation.
1237 # fixes the function accumulation.
1235 hookargs = tr2.hookargs
1238 hookargs = tr2.hookargs
1236
1239
1237 def hook():
1240 def hook():
1238 reporef().hook('txnclose', throw=False, txnname=desc,
1241 reporef().hook('txnclose', throw=False, txnname=desc,
1239 **pycompat.strkwargs(hookargs))
1242 **pycompat.strkwargs(hookargs))
1240 reporef()._afterlock(hook)
1243 reporef()._afterlock(hook)
1241 tr.addfinalize('txnclose-hook', txnclosehook)
1244 tr.addfinalize('txnclose-hook', txnclosehook)
1242 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1245 tr.addpostclose('warms-cache', self._buildcacheupdater(tr))
1243 def txnaborthook(tr2):
1246 def txnaborthook(tr2):
1244 """To be run if transaction is aborted
1247 """To be run if transaction is aborted
1245 """
1248 """
1246 reporef().hook('txnabort', throw=False, txnname=desc,
1249 reporef().hook('txnabort', throw=False, txnname=desc,
1247 **tr2.hookargs)
1250 **tr2.hookargs)
1248 tr.addabort('txnabort-hook', txnaborthook)
1251 tr.addabort('txnabort-hook', txnaborthook)
1249 # avoid eager cache invalidation. in-memory data should be identical
1252 # avoid eager cache invalidation. in-memory data should be identical
1250 # to stored data if transaction has no error.
1253 # to stored data if transaction has no error.
1251 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1254 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1252 self._transref = weakref.ref(tr)
1255 self._transref = weakref.ref(tr)
1253 return tr
1256 return tr
1254
1257
1255 def _journalfiles(self):
1258 def _journalfiles(self):
1256 return ((self.svfs, 'journal'),
1259 return ((self.svfs, 'journal'),
1257 (self.vfs, 'journal.dirstate'),
1260 (self.vfs, 'journal.dirstate'),
1258 (self.vfs, 'journal.branch'),
1261 (self.vfs, 'journal.branch'),
1259 (self.vfs, 'journal.desc'),
1262 (self.vfs, 'journal.desc'),
1260 (self.vfs, 'journal.bookmarks'),
1263 (self.vfs, 'journal.bookmarks'),
1261 (self.svfs, 'journal.phaseroots'))
1264 (self.svfs, 'journal.phaseroots'))
1262
1265
1263 def undofiles(self):
1266 def undofiles(self):
1264 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1267 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1265
1268
1266 @unfilteredmethod
1269 @unfilteredmethod
1267 def _writejournal(self, desc):
1270 def _writejournal(self, desc):
1268 self.dirstate.savebackup(None, 'journal.dirstate')
1271 self.dirstate.savebackup(None, 'journal.dirstate')
1269 self.vfs.write("journal.branch",
1272 self.vfs.write("journal.branch",
1270 encoding.fromlocal(self.dirstate.branch()))
1273 encoding.fromlocal(self.dirstate.branch()))
1271 self.vfs.write("journal.desc",
1274 self.vfs.write("journal.desc",
1272 "%d\n%s\n" % (len(self), desc))
1275 "%d\n%s\n" % (len(self), desc))
1273 self.vfs.write("journal.bookmarks",
1276 self.vfs.write("journal.bookmarks",
1274 self.vfs.tryread("bookmarks"))
1277 self.vfs.tryread("bookmarks"))
1275 self.svfs.write("journal.phaseroots",
1278 self.svfs.write("journal.phaseroots",
1276 self.svfs.tryread("phaseroots"))
1279 self.svfs.tryread("phaseroots"))
1277
1280
1278 def recover(self):
1281 def recover(self):
1279 with self.lock():
1282 with self.lock():
1280 if self.svfs.exists("journal"):
1283 if self.svfs.exists("journal"):
1281 self.ui.status(_("rolling back interrupted transaction\n"))
1284 self.ui.status(_("rolling back interrupted transaction\n"))
1282 vfsmap = {'': self.svfs,
1285 vfsmap = {'': self.svfs,
1283 'plain': self.vfs,}
1286 'plain': self.vfs,}
1284 transaction.rollback(self.svfs, vfsmap, "journal",
1287 transaction.rollback(self.svfs, vfsmap, "journal",
1285 self.ui.warn,
1288 self.ui.warn,
1286 checkambigfiles=_cachedfiles)
1289 checkambigfiles=_cachedfiles)
1287 self.invalidate()
1290 self.invalidate()
1288 return True
1291 return True
1289 else:
1292 else:
1290 self.ui.warn(_("no interrupted transaction available\n"))
1293 self.ui.warn(_("no interrupted transaction available\n"))
1291 return False
1294 return False
1292
1295
1293 def rollback(self, dryrun=False, force=False):
1296 def rollback(self, dryrun=False, force=False):
1294 wlock = lock = dsguard = None
1297 wlock = lock = dsguard = None
1295 try:
1298 try:
1296 wlock = self.wlock()
1299 wlock = self.wlock()
1297 lock = self.lock()
1300 lock = self.lock()
1298 if self.svfs.exists("undo"):
1301 if self.svfs.exists("undo"):
1299 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1302 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1300
1303
1301 return self._rollback(dryrun, force, dsguard)
1304 return self._rollback(dryrun, force, dsguard)
1302 else:
1305 else:
1303 self.ui.warn(_("no rollback information available\n"))
1306 self.ui.warn(_("no rollback information available\n"))
1304 return 1
1307 return 1
1305 finally:
1308 finally:
1306 release(dsguard, lock, wlock)
1309 release(dsguard, lock, wlock)
1307
1310
1308 @unfilteredmethod # Until we get smarter cache management
1311 @unfilteredmethod # Until we get smarter cache management
1309 def _rollback(self, dryrun, force, dsguard):
1312 def _rollback(self, dryrun, force, dsguard):
1310 ui = self.ui
1313 ui = self.ui
1311 try:
1314 try:
1312 args = self.vfs.read('undo.desc').splitlines()
1315 args = self.vfs.read('undo.desc').splitlines()
1313 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1316 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1314 if len(args) >= 3:
1317 if len(args) >= 3:
1315 detail = args[2]
1318 detail = args[2]
1316 oldtip = oldlen - 1
1319 oldtip = oldlen - 1
1317
1320
1318 if detail and ui.verbose:
1321 if detail and ui.verbose:
1319 msg = (_('repository tip rolled back to revision %d'
1322 msg = (_('repository tip rolled back to revision %d'
1320 ' (undo %s: %s)\n')
1323 ' (undo %s: %s)\n')
1321 % (oldtip, desc, detail))
1324 % (oldtip, desc, detail))
1322 else:
1325 else:
1323 msg = (_('repository tip rolled back to revision %d'
1326 msg = (_('repository tip rolled back to revision %d'
1324 ' (undo %s)\n')
1327 ' (undo %s)\n')
1325 % (oldtip, desc))
1328 % (oldtip, desc))
1326 except IOError:
1329 except IOError:
1327 msg = _('rolling back unknown transaction\n')
1330 msg = _('rolling back unknown transaction\n')
1328 desc = None
1331 desc = None
1329
1332
1330 if not force and self['.'] != self['tip'] and desc == 'commit':
1333 if not force and self['.'] != self['tip'] and desc == 'commit':
1331 raise error.Abort(
1334 raise error.Abort(
1332 _('rollback of last commit while not checked out '
1335 _('rollback of last commit while not checked out '
1333 'may lose data'), hint=_('use -f to force'))
1336 'may lose data'), hint=_('use -f to force'))
1334
1337
1335 ui.status(msg)
1338 ui.status(msg)
1336 if dryrun:
1339 if dryrun:
1337 return 0
1340 return 0
1338
1341
1339 parents = self.dirstate.parents()
1342 parents = self.dirstate.parents()
1340 self.destroying()
1343 self.destroying()
1341 vfsmap = {'plain': self.vfs, '': self.svfs}
1344 vfsmap = {'plain': self.vfs, '': self.svfs}
1342 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1345 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1343 checkambigfiles=_cachedfiles)
1346 checkambigfiles=_cachedfiles)
1344 if self.vfs.exists('undo.bookmarks'):
1347 if self.vfs.exists('undo.bookmarks'):
1345 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1348 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1346 if self.svfs.exists('undo.phaseroots'):
1349 if self.svfs.exists('undo.phaseroots'):
1347 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1350 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1348 self.invalidate()
1351 self.invalidate()
1349
1352
1350 parentgone = (parents[0] not in self.changelog.nodemap or
1353 parentgone = (parents[0] not in self.changelog.nodemap or
1351 parents[1] not in self.changelog.nodemap)
1354 parents[1] not in self.changelog.nodemap)
1352 if parentgone:
1355 if parentgone:
1353 # prevent dirstateguard from overwriting already restored one
1356 # prevent dirstateguard from overwriting already restored one
1354 dsguard.close()
1357 dsguard.close()
1355
1358
1356 self.dirstate.restorebackup(None, 'undo.dirstate')
1359 self.dirstate.restorebackup(None, 'undo.dirstate')
1357 try:
1360 try:
1358 branch = self.vfs.read('undo.branch')
1361 branch = self.vfs.read('undo.branch')
1359 self.dirstate.setbranch(encoding.tolocal(branch))
1362 self.dirstate.setbranch(encoding.tolocal(branch))
1360 except IOError:
1363 except IOError:
1361 ui.warn(_('named branch could not be reset: '
1364 ui.warn(_('named branch could not be reset: '
1362 'current branch is still \'%s\'\n')
1365 'current branch is still \'%s\'\n')
1363 % self.dirstate.branch())
1366 % self.dirstate.branch())
1364
1367
1365 parents = tuple([p.rev() for p in self[None].parents()])
1368 parents = tuple([p.rev() for p in self[None].parents()])
1366 if len(parents) > 1:
1369 if len(parents) > 1:
1367 ui.status(_('working directory now based on '
1370 ui.status(_('working directory now based on '
1368 'revisions %d and %d\n') % parents)
1371 'revisions %d and %d\n') % parents)
1369 else:
1372 else:
1370 ui.status(_('working directory now based on '
1373 ui.status(_('working directory now based on '
1371 'revision %d\n') % parents)
1374 'revision %d\n') % parents)
1372 mergemod.mergestate.clean(self, self['.'].node())
1375 mergemod.mergestate.clean(self, self['.'].node())
1373
1376
1374 # TODO: if we know which new heads may result from this rollback, pass
1377 # TODO: if we know which new heads may result from this rollback, pass
1375 # them to destroy(), which will prevent the branchhead cache from being
1378 # them to destroy(), which will prevent the branchhead cache from being
1376 # invalidated.
1379 # invalidated.
1377 self.destroyed()
1380 self.destroyed()
1378 return 0
1381 return 0
1379
1382
1380 def _buildcacheupdater(self, newtransaction):
1383 def _buildcacheupdater(self, newtransaction):
1381 """called during transaction to build the callback updating cache
1384 """called during transaction to build the callback updating cache
1382
1385
1383 Lives on the repository to help extension who might want to augment
1386 Lives on the repository to help extension who might want to augment
1384 this logic. For this purpose, the created transaction is passed to the
1387 this logic. For this purpose, the created transaction is passed to the
1385 method.
1388 method.
1386 """
1389 """
1387 # we must avoid cyclic reference between repo and transaction.
1390 # we must avoid cyclic reference between repo and transaction.
1388 reporef = weakref.ref(self)
1391 reporef = weakref.ref(self)
1389 def updater(tr):
1392 def updater(tr):
1390 repo = reporef()
1393 repo = reporef()
1391 repo.updatecaches(tr)
1394 repo.updatecaches(tr)
1392 return updater
1395 return updater
1393
1396
1394 @unfilteredmethod
1397 @unfilteredmethod
1395 def updatecaches(self, tr=None):
1398 def updatecaches(self, tr=None):
1396 """warm appropriate caches
1399 """warm appropriate caches
1397
1400
1398 If this function is called after a transaction closed. The transaction
1401 If this function is called after a transaction closed. The transaction
1399 will be available in the 'tr' argument. This can be used to selectively
1402 will be available in the 'tr' argument. This can be used to selectively
1400 update caches relevant to the changes in that transaction.
1403 update caches relevant to the changes in that transaction.
1401 """
1404 """
1402 if tr is not None and tr.hookargs.get('source') == 'strip':
1405 if tr is not None and tr.hookargs.get('source') == 'strip':
1403 # During strip, many caches are invalid but
1406 # During strip, many caches are invalid but
1404 # later call to `destroyed` will refresh them.
1407 # later call to `destroyed` will refresh them.
1405 return
1408 return
1406
1409
1407 if tr is None or tr.changes['revs']:
1410 if tr is None or tr.changes['revs']:
1408 # updating the unfiltered branchmap should refresh all the others,
1411 # updating the unfiltered branchmap should refresh all the others,
1409 self.ui.debug('updating the branch cache\n')
1412 self.ui.debug('updating the branch cache\n')
1410 branchmap.updatecache(self.filtered('served'))
1413 branchmap.updatecache(self.filtered('served'))
1411
1414
1412 def invalidatecaches(self):
1415 def invalidatecaches(self):
1413
1416
1414 if '_tagscache' in vars(self):
1417 if '_tagscache' in vars(self):
1415 # can't use delattr on proxy
1418 # can't use delattr on proxy
1416 del self.__dict__['_tagscache']
1419 del self.__dict__['_tagscache']
1417
1420
1418 self.unfiltered()._branchcaches.clear()
1421 self.unfiltered()._branchcaches.clear()
1419 self.invalidatevolatilesets()
1422 self.invalidatevolatilesets()
1420 self._sparsesignaturecache.clear()
1423 self._sparsesignaturecache.clear()
1421
1424
1422 def invalidatevolatilesets(self):
1425 def invalidatevolatilesets(self):
1423 self.filteredrevcache.clear()
1426 self.filteredrevcache.clear()
1424 obsolete.clearobscaches(self)
1427 obsolete.clearobscaches(self)
1425
1428
1426 def invalidatedirstate(self):
1429 def invalidatedirstate(self):
1427 '''Invalidates the dirstate, causing the next call to dirstate
1430 '''Invalidates the dirstate, causing the next call to dirstate
1428 to check if it was modified since the last time it was read,
1431 to check if it was modified since the last time it was read,
1429 rereading it if it has.
1432 rereading it if it has.
1430
1433
1431 This is different to dirstate.invalidate() that it doesn't always
1434 This is different to dirstate.invalidate() that it doesn't always
1432 rereads the dirstate. Use dirstate.invalidate() if you want to
1435 rereads the dirstate. Use dirstate.invalidate() if you want to
1433 explicitly read the dirstate again (i.e. restoring it to a previous
1436 explicitly read the dirstate again (i.e. restoring it to a previous
1434 known good state).'''
1437 known good state).'''
1435 if hasunfilteredcache(self, 'dirstate'):
1438 if hasunfilteredcache(self, 'dirstate'):
1436 for k in self.dirstate._filecache:
1439 for k in self.dirstate._filecache:
1437 try:
1440 try:
1438 delattr(self.dirstate, k)
1441 delattr(self.dirstate, k)
1439 except AttributeError:
1442 except AttributeError:
1440 pass
1443 pass
1441 delattr(self.unfiltered(), 'dirstate')
1444 delattr(self.unfiltered(), 'dirstate')
1442
1445
1443 def invalidate(self, clearfilecache=False):
1446 def invalidate(self, clearfilecache=False):
1444 '''Invalidates both store and non-store parts other than dirstate
1447 '''Invalidates both store and non-store parts other than dirstate
1445
1448
1446 If a transaction is running, invalidation of store is omitted,
1449 If a transaction is running, invalidation of store is omitted,
1447 because discarding in-memory changes might cause inconsistency
1450 because discarding in-memory changes might cause inconsistency
1448 (e.g. incomplete fncache causes unintentional failure, but
1451 (e.g. incomplete fncache causes unintentional failure, but
1449 redundant one doesn't).
1452 redundant one doesn't).
1450 '''
1453 '''
1451 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1454 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1452 for k in list(self._filecache.keys()):
1455 for k in list(self._filecache.keys()):
1453 # dirstate is invalidated separately in invalidatedirstate()
1456 # dirstate is invalidated separately in invalidatedirstate()
1454 if k == 'dirstate':
1457 if k == 'dirstate':
1455 continue
1458 continue
1456
1459
1457 if clearfilecache:
1460 if clearfilecache:
1458 del self._filecache[k]
1461 del self._filecache[k]
1459 try:
1462 try:
1460 delattr(unfiltered, k)
1463 delattr(unfiltered, k)
1461 except AttributeError:
1464 except AttributeError:
1462 pass
1465 pass
1463 self.invalidatecaches()
1466 self.invalidatecaches()
1464 if not self.currenttransaction():
1467 if not self.currenttransaction():
1465 # TODO: Changing contents of store outside transaction
1468 # TODO: Changing contents of store outside transaction
1466 # causes inconsistency. We should make in-memory store
1469 # causes inconsistency. We should make in-memory store
1467 # changes detectable, and abort if changed.
1470 # changes detectable, and abort if changed.
1468 self.store.invalidatecaches()
1471 self.store.invalidatecaches()
1469
1472
1470 def invalidateall(self):
1473 def invalidateall(self):
1471 '''Fully invalidates both store and non-store parts, causing the
1474 '''Fully invalidates both store and non-store parts, causing the
1472 subsequent operation to reread any outside changes.'''
1475 subsequent operation to reread any outside changes.'''
1473 # extension should hook this to invalidate its caches
1476 # extension should hook this to invalidate its caches
1474 self.invalidate()
1477 self.invalidate()
1475 self.invalidatedirstate()
1478 self.invalidatedirstate()
1476
1479
1477 @unfilteredmethod
1480 @unfilteredmethod
1478 def _refreshfilecachestats(self, tr):
1481 def _refreshfilecachestats(self, tr):
1479 """Reload stats of cached files so that they are flagged as valid"""
1482 """Reload stats of cached files so that they are flagged as valid"""
1480 for k, ce in self._filecache.items():
1483 for k, ce in self._filecache.items():
1481 if k == 'dirstate' or k not in self.__dict__:
1484 if k == 'dirstate' or k not in self.__dict__:
1482 continue
1485 continue
1483 ce.refresh()
1486 ce.refresh()
1484
1487
1485 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1488 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1486 inheritchecker=None, parentenvvar=None):
1489 inheritchecker=None, parentenvvar=None):
1487 parentlock = None
1490 parentlock = None
1488 # the contents of parentenvvar are used by the underlying lock to
1491 # the contents of parentenvvar are used by the underlying lock to
1489 # determine whether it can be inherited
1492 # determine whether it can be inherited
1490 if parentenvvar is not None:
1493 if parentenvvar is not None:
1491 parentlock = encoding.environ.get(parentenvvar)
1494 parentlock = encoding.environ.get(parentenvvar)
1492 try:
1495 try:
1493 l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
1496 l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
1494 acquirefn=acquirefn, desc=desc,
1497 acquirefn=acquirefn, desc=desc,
1495 inheritchecker=inheritchecker,
1498 inheritchecker=inheritchecker,
1496 parentlock=parentlock)
1499 parentlock=parentlock)
1497 except error.LockHeld as inst:
1500 except error.LockHeld as inst:
1498 if not wait:
1501 if not wait:
1499 raise
1502 raise
1500 # show more details for new-style locks
1503 # show more details for new-style locks
1501 if ':' in inst.locker:
1504 if ':' in inst.locker:
1502 host, pid = inst.locker.split(":", 1)
1505 host, pid = inst.locker.split(":", 1)
1503 self.ui.warn(
1506 self.ui.warn(
1504 _("waiting for lock on %s held by process %r "
1507 _("waiting for lock on %s held by process %r "
1505 "on host %r\n") % (desc, pid, host))
1508 "on host %r\n") % (desc, pid, host))
1506 else:
1509 else:
1507 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1510 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1508 (desc, inst.locker))
1511 (desc, inst.locker))
1509 # default to 600 seconds timeout
1512 # default to 600 seconds timeout
1510 l = lockmod.lock(vfs, lockname,
1513 l = lockmod.lock(vfs, lockname,
1511 int(self.ui.config("ui", "timeout")),
1514 int(self.ui.config("ui", "timeout")),
1512 releasefn=releasefn, acquirefn=acquirefn,
1515 releasefn=releasefn, acquirefn=acquirefn,
1513 desc=desc)
1516 desc=desc)
1514 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1517 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1515 return l
1518 return l
1516
1519
1517 def _afterlock(self, callback):
1520 def _afterlock(self, callback):
1518 """add a callback to be run when the repository is fully unlocked
1521 """add a callback to be run when the repository is fully unlocked
1519
1522
1520 The callback will be executed when the outermost lock is released
1523 The callback will be executed when the outermost lock is released
1521 (with wlock being higher level than 'lock')."""
1524 (with wlock being higher level than 'lock')."""
1522 for ref in (self._wlockref, self._lockref):
1525 for ref in (self._wlockref, self._lockref):
1523 l = ref and ref()
1526 l = ref and ref()
1524 if l and l.held:
1527 if l and l.held:
1525 l.postrelease.append(callback)
1528 l.postrelease.append(callback)
1526 break
1529 break
1527 else: # no lock have been found.
1530 else: # no lock have been found.
1528 callback()
1531 callback()
1529
1532
1530 def lock(self, wait=True):
1533 def lock(self, wait=True):
1531 '''Lock the repository store (.hg/store) and return a weak reference
1534 '''Lock the repository store (.hg/store) and return a weak reference
1532 to the lock. Use this before modifying the store (e.g. committing or
1535 to the lock. Use this before modifying the store (e.g. committing or
1533 stripping). If you are opening a transaction, get a lock as well.)
1536 stripping). If you are opening a transaction, get a lock as well.)
1534
1537
1535 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1538 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1536 'wlock' first to avoid a dead-lock hazard.'''
1539 'wlock' first to avoid a dead-lock hazard.'''
1537 l = self._currentlock(self._lockref)
1540 l = self._currentlock(self._lockref)
1538 if l is not None:
1541 if l is not None:
1539 l.lock()
1542 l.lock()
1540 return l
1543 return l
1541
1544
1542 l = self._lock(self.svfs, "lock", wait, None,
1545 l = self._lock(self.svfs, "lock", wait, None,
1543 self.invalidate, _('repository %s') % self.origroot)
1546 self.invalidate, _('repository %s') % self.origroot)
1544 self._lockref = weakref.ref(l)
1547 self._lockref = weakref.ref(l)
1545 return l
1548 return l
1546
1549
1547 def _wlockchecktransaction(self):
1550 def _wlockchecktransaction(self):
1548 if self.currenttransaction() is not None:
1551 if self.currenttransaction() is not None:
1549 raise error.LockInheritanceContractViolation(
1552 raise error.LockInheritanceContractViolation(
1550 'wlock cannot be inherited in the middle of a transaction')
1553 'wlock cannot be inherited in the middle of a transaction')
1551
1554
1552 def wlock(self, wait=True):
1555 def wlock(self, wait=True):
1553 '''Lock the non-store parts of the repository (everything under
1556 '''Lock the non-store parts of the repository (everything under
1554 .hg except .hg/store) and return a weak reference to the lock.
1557 .hg except .hg/store) and return a weak reference to the lock.
1555
1558
1556 Use this before modifying files in .hg.
1559 Use this before modifying files in .hg.
1557
1560
1558 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1561 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1559 'wlock' first to avoid a dead-lock hazard.'''
1562 'wlock' first to avoid a dead-lock hazard.'''
1560 l = self._wlockref and self._wlockref()
1563 l = self._wlockref and self._wlockref()
1561 if l is not None and l.held:
1564 if l is not None and l.held:
1562 l.lock()
1565 l.lock()
1563 return l
1566 return l
1564
1567
1565 # We do not need to check for non-waiting lock acquisition. Such
1568 # We do not need to check for non-waiting lock acquisition. Such
1566 # acquisition would not cause dead-lock as they would just fail.
1569 # acquisition would not cause dead-lock as they would just fail.
1567 if wait and (self.ui.configbool('devel', 'all-warnings')
1570 if wait and (self.ui.configbool('devel', 'all-warnings')
1568 or self.ui.configbool('devel', 'check-locks')):
1571 or self.ui.configbool('devel', 'check-locks')):
1569 if self._currentlock(self._lockref) is not None:
1572 if self._currentlock(self._lockref) is not None:
1570 self.ui.develwarn('"wlock" acquired after "lock"')
1573 self.ui.develwarn('"wlock" acquired after "lock"')
1571
1574
1572 def unlock():
1575 def unlock():
1573 if self.dirstate.pendingparentchange():
1576 if self.dirstate.pendingparentchange():
1574 self.dirstate.invalidate()
1577 self.dirstate.invalidate()
1575 else:
1578 else:
1576 self.dirstate.write(None)
1579 self.dirstate.write(None)
1577
1580
1578 self._filecache['dirstate'].refresh()
1581 self._filecache['dirstate'].refresh()
1579
1582
1580 l = self._lock(self.vfs, "wlock", wait, unlock,
1583 l = self._lock(self.vfs, "wlock", wait, unlock,
1581 self.invalidatedirstate, _('working directory of %s') %
1584 self.invalidatedirstate, _('working directory of %s') %
1582 self.origroot,
1585 self.origroot,
1583 inheritchecker=self._wlockchecktransaction,
1586 inheritchecker=self._wlockchecktransaction,
1584 parentenvvar='HG_WLOCK_LOCKER')
1587 parentenvvar='HG_WLOCK_LOCKER')
1585 self._wlockref = weakref.ref(l)
1588 self._wlockref = weakref.ref(l)
1586 return l
1589 return l
1587
1590
1588 def _currentlock(self, lockref):
1591 def _currentlock(self, lockref):
1589 """Returns the lock if it's held, or None if it's not."""
1592 """Returns the lock if it's held, or None if it's not."""
1590 if lockref is None:
1593 if lockref is None:
1591 return None
1594 return None
1592 l = lockref()
1595 l = lockref()
1593 if l is None or not l.held:
1596 if l is None or not l.held:
1594 return None
1597 return None
1595 return l
1598 return l
1596
1599
1597 def currentwlock(self):
1600 def currentwlock(self):
1598 """Returns the wlock if it's held, or None if it's not."""
1601 """Returns the wlock if it's held, or None if it's not."""
1599 return self._currentlock(self._wlockref)
1602 return self._currentlock(self._wlockref)
1600
1603
1601 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1604 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1602 """
1605 """
1603 commit an individual file as part of a larger transaction
1606 commit an individual file as part of a larger transaction
1604 """
1607 """
1605
1608
1606 fname = fctx.path()
1609 fname = fctx.path()
1607 fparent1 = manifest1.get(fname, nullid)
1610 fparent1 = manifest1.get(fname, nullid)
1608 fparent2 = manifest2.get(fname, nullid)
1611 fparent2 = manifest2.get(fname, nullid)
1609 if isinstance(fctx, context.filectx):
1612 if isinstance(fctx, context.filectx):
1610 node = fctx.filenode()
1613 node = fctx.filenode()
1611 if node in [fparent1, fparent2]:
1614 if node in [fparent1, fparent2]:
1612 self.ui.debug('reusing %s filelog entry\n' % fname)
1615 self.ui.debug('reusing %s filelog entry\n' % fname)
1613 if manifest1.flags(fname) != fctx.flags():
1616 if manifest1.flags(fname) != fctx.flags():
1614 changelist.append(fname)
1617 changelist.append(fname)
1615 return node
1618 return node
1616
1619
1617 flog = self.file(fname)
1620 flog = self.file(fname)
1618 meta = {}
1621 meta = {}
1619 copy = fctx.renamed()
1622 copy = fctx.renamed()
1620 if copy and copy[0] != fname:
1623 if copy and copy[0] != fname:
1621 # Mark the new revision of this file as a copy of another
1624 # Mark the new revision of this file as a copy of another
1622 # file. This copy data will effectively act as a parent
1625 # file. This copy data will effectively act as a parent
1623 # of this new revision. If this is a merge, the first
1626 # of this new revision. If this is a merge, the first
1624 # parent will be the nullid (meaning "look up the copy data")
1627 # parent will be the nullid (meaning "look up the copy data")
1625 # and the second one will be the other parent. For example:
1628 # and the second one will be the other parent. For example:
1626 #
1629 #
1627 # 0 --- 1 --- 3 rev1 changes file foo
1630 # 0 --- 1 --- 3 rev1 changes file foo
1628 # \ / rev2 renames foo to bar and changes it
1631 # \ / rev2 renames foo to bar and changes it
1629 # \- 2 -/ rev3 should have bar with all changes and
1632 # \- 2 -/ rev3 should have bar with all changes and
1630 # should record that bar descends from
1633 # should record that bar descends from
1631 # bar in rev2 and foo in rev1
1634 # bar in rev2 and foo in rev1
1632 #
1635 #
1633 # this allows this merge to succeed:
1636 # this allows this merge to succeed:
1634 #
1637 #
1635 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1638 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1636 # \ / merging rev3 and rev4 should use bar@rev2
1639 # \ / merging rev3 and rev4 should use bar@rev2
1637 # \- 2 --- 4 as the merge base
1640 # \- 2 --- 4 as the merge base
1638 #
1641 #
1639
1642
1640 cfname = copy[0]
1643 cfname = copy[0]
1641 crev = manifest1.get(cfname)
1644 crev = manifest1.get(cfname)
1642 newfparent = fparent2
1645 newfparent = fparent2
1643
1646
1644 if manifest2: # branch merge
1647 if manifest2: # branch merge
1645 if fparent2 == nullid or crev is None: # copied on remote side
1648 if fparent2 == nullid or crev is None: # copied on remote side
1646 if cfname in manifest2:
1649 if cfname in manifest2:
1647 crev = manifest2[cfname]
1650 crev = manifest2[cfname]
1648 newfparent = fparent1
1651 newfparent = fparent1
1649
1652
1650 # Here, we used to search backwards through history to try to find
1653 # Here, we used to search backwards through history to try to find
1651 # where the file copy came from if the source of a copy was not in
1654 # where the file copy came from if the source of a copy was not in
1652 # the parent directory. However, this doesn't actually make sense to
1655 # the parent directory. However, this doesn't actually make sense to
1653 # do (what does a copy from something not in your working copy even
1656 # do (what does a copy from something not in your working copy even
1654 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1657 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1655 # the user that copy information was dropped, so if they didn't
1658 # the user that copy information was dropped, so if they didn't
1656 # expect this outcome it can be fixed, but this is the correct
1659 # expect this outcome it can be fixed, but this is the correct
1657 # behavior in this circumstance.
1660 # behavior in this circumstance.
1658
1661
1659 if crev:
1662 if crev:
1660 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1663 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1661 meta["copy"] = cfname
1664 meta["copy"] = cfname
1662 meta["copyrev"] = hex(crev)
1665 meta["copyrev"] = hex(crev)
1663 fparent1, fparent2 = nullid, newfparent
1666 fparent1, fparent2 = nullid, newfparent
1664 else:
1667 else:
1665 self.ui.warn(_("warning: can't find ancestor for '%s' "
1668 self.ui.warn(_("warning: can't find ancestor for '%s' "
1666 "copied from '%s'!\n") % (fname, cfname))
1669 "copied from '%s'!\n") % (fname, cfname))
1667
1670
1668 elif fparent1 == nullid:
1671 elif fparent1 == nullid:
1669 fparent1, fparent2 = fparent2, nullid
1672 fparent1, fparent2 = fparent2, nullid
1670 elif fparent2 != nullid:
1673 elif fparent2 != nullid:
1671 # is one parent an ancestor of the other?
1674 # is one parent an ancestor of the other?
1672 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1675 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1673 if fparent1 in fparentancestors:
1676 if fparent1 in fparentancestors:
1674 fparent1, fparent2 = fparent2, nullid
1677 fparent1, fparent2 = fparent2, nullid
1675 elif fparent2 in fparentancestors:
1678 elif fparent2 in fparentancestors:
1676 fparent2 = nullid
1679 fparent2 = nullid
1677
1680
1678 # is the file changed?
1681 # is the file changed?
1679 text = fctx.data()
1682 text = fctx.data()
1680 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1683 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1681 changelist.append(fname)
1684 changelist.append(fname)
1682 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1685 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1683 # are just the flags changed during merge?
1686 # are just the flags changed during merge?
1684 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1687 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1685 changelist.append(fname)
1688 changelist.append(fname)
1686
1689
1687 return fparent1
1690 return fparent1
1688
1691
1689 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1692 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1690 """check for commit arguments that aren't committable"""
1693 """check for commit arguments that aren't committable"""
1691 if match.isexact() or match.prefix():
1694 if match.isexact() or match.prefix():
1692 matched = set(status.modified + status.added + status.removed)
1695 matched = set(status.modified + status.added + status.removed)
1693
1696
1694 for f in match.files():
1697 for f in match.files():
1695 f = self.dirstate.normalize(f)
1698 f = self.dirstate.normalize(f)
1696 if f == '.' or f in matched or f in wctx.substate:
1699 if f == '.' or f in matched or f in wctx.substate:
1697 continue
1700 continue
1698 if f in status.deleted:
1701 if f in status.deleted:
1699 fail(f, _('file not found!'))
1702 fail(f, _('file not found!'))
1700 if f in vdirs: # visited directory
1703 if f in vdirs: # visited directory
1701 d = f + '/'
1704 d = f + '/'
1702 for mf in matched:
1705 for mf in matched:
1703 if mf.startswith(d):
1706 if mf.startswith(d):
1704 break
1707 break
1705 else:
1708 else:
1706 fail(f, _("no match under directory!"))
1709 fail(f, _("no match under directory!"))
1707 elif f not in self.dirstate:
1710 elif f not in self.dirstate:
1708 fail(f, _("file not tracked!"))
1711 fail(f, _("file not tracked!"))
1709
1712
1710 @unfilteredmethod
1713 @unfilteredmethod
1711 def commit(self, text="", user=None, date=None, match=None, force=False,
1714 def commit(self, text="", user=None, date=None, match=None, force=False,
1712 editor=False, extra=None):
1715 editor=False, extra=None):
1713 """Add a new revision to current repository.
1716 """Add a new revision to current repository.
1714
1717
1715 Revision information is gathered from the working directory,
1718 Revision information is gathered from the working directory,
1716 match can be used to filter the committed files. If editor is
1719 match can be used to filter the committed files. If editor is
1717 supplied, it is called to get a commit message.
1720 supplied, it is called to get a commit message.
1718 """
1721 """
1719 if extra is None:
1722 if extra is None:
1720 extra = {}
1723 extra = {}
1721
1724
1722 def fail(f, msg):
1725 def fail(f, msg):
1723 raise error.Abort('%s: %s' % (f, msg))
1726 raise error.Abort('%s: %s' % (f, msg))
1724
1727
1725 if not match:
1728 if not match:
1726 match = matchmod.always(self.root, '')
1729 match = matchmod.always(self.root, '')
1727
1730
1728 if not force:
1731 if not force:
1729 vdirs = []
1732 vdirs = []
1730 match.explicitdir = vdirs.append
1733 match.explicitdir = vdirs.append
1731 match.bad = fail
1734 match.bad = fail
1732
1735
1733 wlock = lock = tr = None
1736 wlock = lock = tr = None
1734 try:
1737 try:
1735 wlock = self.wlock()
1738 wlock = self.wlock()
1736 lock = self.lock() # for recent changelog (see issue4368)
1739 lock = self.lock() # for recent changelog (see issue4368)
1737
1740
1738 wctx = self[None]
1741 wctx = self[None]
1739 merge = len(wctx.parents()) > 1
1742 merge = len(wctx.parents()) > 1
1740
1743
1741 if not force and merge and not match.always():
1744 if not force and merge and not match.always():
1742 raise error.Abort(_('cannot partially commit a merge '
1745 raise error.Abort(_('cannot partially commit a merge '
1743 '(do not specify files or patterns)'))
1746 '(do not specify files or patterns)'))
1744
1747
1745 status = self.status(match=match, clean=force)
1748 status = self.status(match=match, clean=force)
1746 if force:
1749 if force:
1747 status.modified.extend(status.clean) # mq may commit clean files
1750 status.modified.extend(status.clean) # mq may commit clean files
1748
1751
1749 # check subrepos
1752 # check subrepos
1750 subs = []
1753 subs = []
1751 commitsubs = set()
1754 commitsubs = set()
1752 newstate = wctx.substate.copy()
1755 newstate = wctx.substate.copy()
1753 # only manage subrepos and .hgsubstate if .hgsub is present
1756 # only manage subrepos and .hgsubstate if .hgsub is present
1754 if '.hgsub' in wctx:
1757 if '.hgsub' in wctx:
1755 # we'll decide whether to track this ourselves, thanks
1758 # we'll decide whether to track this ourselves, thanks
1756 for c in status.modified, status.added, status.removed:
1759 for c in status.modified, status.added, status.removed:
1757 if '.hgsubstate' in c:
1760 if '.hgsubstate' in c:
1758 c.remove('.hgsubstate')
1761 c.remove('.hgsubstate')
1759
1762
1760 # compare current state to last committed state
1763 # compare current state to last committed state
1761 # build new substate based on last committed state
1764 # build new substate based on last committed state
1762 oldstate = wctx.p1().substate
1765 oldstate = wctx.p1().substate
1763 for s in sorted(newstate.keys()):
1766 for s in sorted(newstate.keys()):
1764 if not match(s):
1767 if not match(s):
1765 # ignore working copy, use old state if present
1768 # ignore working copy, use old state if present
1766 if s in oldstate:
1769 if s in oldstate:
1767 newstate[s] = oldstate[s]
1770 newstate[s] = oldstate[s]
1768 continue
1771 continue
1769 if not force:
1772 if not force:
1770 raise error.Abort(
1773 raise error.Abort(
1771 _("commit with new subrepo %s excluded") % s)
1774 _("commit with new subrepo %s excluded") % s)
1772 dirtyreason = wctx.sub(s).dirtyreason(True)
1775 dirtyreason = wctx.sub(s).dirtyreason(True)
1773 if dirtyreason:
1776 if dirtyreason:
1774 if not self.ui.configbool('ui', 'commitsubrepos'):
1777 if not self.ui.configbool('ui', 'commitsubrepos'):
1775 raise error.Abort(dirtyreason,
1778 raise error.Abort(dirtyreason,
1776 hint=_("use --subrepos for recursive commit"))
1779 hint=_("use --subrepos for recursive commit"))
1777 subs.append(s)
1780 subs.append(s)
1778 commitsubs.add(s)
1781 commitsubs.add(s)
1779 else:
1782 else:
1780 bs = wctx.sub(s).basestate()
1783 bs = wctx.sub(s).basestate()
1781 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1784 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1782 if oldstate.get(s, (None, None, None))[1] != bs:
1785 if oldstate.get(s, (None, None, None))[1] != bs:
1783 subs.append(s)
1786 subs.append(s)
1784
1787
1785 # check for removed subrepos
1788 # check for removed subrepos
1786 for p in wctx.parents():
1789 for p in wctx.parents():
1787 r = [s for s in p.substate if s not in newstate]
1790 r = [s for s in p.substate if s not in newstate]
1788 subs += [s for s in r if match(s)]
1791 subs += [s for s in r if match(s)]
1789 if subs:
1792 if subs:
1790 if (not match('.hgsub') and
1793 if (not match('.hgsub') and
1791 '.hgsub' in (wctx.modified() + wctx.added())):
1794 '.hgsub' in (wctx.modified() + wctx.added())):
1792 raise error.Abort(
1795 raise error.Abort(
1793 _("can't commit subrepos without .hgsub"))
1796 _("can't commit subrepos without .hgsub"))
1794 status.modified.insert(0, '.hgsubstate')
1797 status.modified.insert(0, '.hgsubstate')
1795
1798
1796 elif '.hgsub' in status.removed:
1799 elif '.hgsub' in status.removed:
1797 # clean up .hgsubstate when .hgsub is removed
1800 # clean up .hgsubstate when .hgsub is removed
1798 if ('.hgsubstate' in wctx and
1801 if ('.hgsubstate' in wctx and
1799 '.hgsubstate' not in (status.modified + status.added +
1802 '.hgsubstate' not in (status.modified + status.added +
1800 status.removed)):
1803 status.removed)):
1801 status.removed.insert(0, '.hgsubstate')
1804 status.removed.insert(0, '.hgsubstate')
1802
1805
1803 # make sure all explicit patterns are matched
1806 # make sure all explicit patterns are matched
1804 if not force:
1807 if not force:
1805 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1808 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1806
1809
1807 cctx = context.workingcommitctx(self, status,
1810 cctx = context.workingcommitctx(self, status,
1808 text, user, date, extra)
1811 text, user, date, extra)
1809
1812
1810 # internal config: ui.allowemptycommit
1813 # internal config: ui.allowemptycommit
1811 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1814 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1812 or extra.get('close') or merge or cctx.files()
1815 or extra.get('close') or merge or cctx.files()
1813 or self.ui.configbool('ui', 'allowemptycommit'))
1816 or self.ui.configbool('ui', 'allowemptycommit'))
1814 if not allowemptycommit:
1817 if not allowemptycommit:
1815 return None
1818 return None
1816
1819
1817 if merge and cctx.deleted():
1820 if merge and cctx.deleted():
1818 raise error.Abort(_("cannot commit merge with missing files"))
1821 raise error.Abort(_("cannot commit merge with missing files"))
1819
1822
1820 ms = mergemod.mergestate.read(self)
1823 ms = mergemod.mergestate.read(self)
1821 mergeutil.checkunresolved(ms)
1824 mergeutil.checkunresolved(ms)
1822
1825
1823 if editor:
1826 if editor:
1824 cctx._text = editor(self, cctx, subs)
1827 cctx._text = editor(self, cctx, subs)
1825 edited = (text != cctx._text)
1828 edited = (text != cctx._text)
1826
1829
1827 # Save commit message in case this transaction gets rolled back
1830 # Save commit message in case this transaction gets rolled back
1828 # (e.g. by a pretxncommit hook). Leave the content alone on
1831 # (e.g. by a pretxncommit hook). Leave the content alone on
1829 # the assumption that the user will use the same editor again.
1832 # the assumption that the user will use the same editor again.
1830 msgfn = self.savecommitmessage(cctx._text)
1833 msgfn = self.savecommitmessage(cctx._text)
1831
1834
1832 # commit subs and write new state
1835 # commit subs and write new state
1833 if subs:
1836 if subs:
1834 for s in sorted(commitsubs):
1837 for s in sorted(commitsubs):
1835 sub = wctx.sub(s)
1838 sub = wctx.sub(s)
1836 self.ui.status(_('committing subrepository %s\n') %
1839 self.ui.status(_('committing subrepository %s\n') %
1837 subrepo.subrelpath(sub))
1840 subrepo.subrelpath(sub))
1838 sr = sub.commit(cctx._text, user, date)
1841 sr = sub.commit(cctx._text, user, date)
1839 newstate[s] = (newstate[s][0], sr)
1842 newstate[s] = (newstate[s][0], sr)
1840 subrepo.writestate(self, newstate)
1843 subrepo.writestate(self, newstate)
1841
1844
1842 p1, p2 = self.dirstate.parents()
1845 p1, p2 = self.dirstate.parents()
1843 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1846 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1844 try:
1847 try:
1845 self.hook("precommit", throw=True, parent1=hookp1,
1848 self.hook("precommit", throw=True, parent1=hookp1,
1846 parent2=hookp2)
1849 parent2=hookp2)
1847 tr = self.transaction('commit')
1850 tr = self.transaction('commit')
1848 ret = self.commitctx(cctx, True)
1851 ret = self.commitctx(cctx, True)
1849 except: # re-raises
1852 except: # re-raises
1850 if edited:
1853 if edited:
1851 self.ui.write(
1854 self.ui.write(
1852 _('note: commit message saved in %s\n') % msgfn)
1855 _('note: commit message saved in %s\n') % msgfn)
1853 raise
1856 raise
1854 # update bookmarks, dirstate and mergestate
1857 # update bookmarks, dirstate and mergestate
1855 bookmarks.update(self, [p1, p2], ret)
1858 bookmarks.update(self, [p1, p2], ret)
1856 cctx.markcommitted(ret)
1859 cctx.markcommitted(ret)
1857 ms.reset()
1860 ms.reset()
1858 tr.close()
1861 tr.close()
1859
1862
1860 finally:
1863 finally:
1861 lockmod.release(tr, lock, wlock)
1864 lockmod.release(tr, lock, wlock)
1862
1865
1863 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1866 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1864 # hack for command that use a temporary commit (eg: histedit)
1867 # hack for command that use a temporary commit (eg: histedit)
1865 # temporary commit got stripped before hook release
1868 # temporary commit got stripped before hook release
1866 if self.changelog.hasnode(ret):
1869 if self.changelog.hasnode(ret):
1867 self.hook("commit", node=node, parent1=parent1,
1870 self.hook("commit", node=node, parent1=parent1,
1868 parent2=parent2)
1871 parent2=parent2)
1869 self._afterlock(commithook)
1872 self._afterlock(commithook)
1870 return ret
1873 return ret
1871
1874
1872 @unfilteredmethod
1875 @unfilteredmethod
1873 def commitctx(self, ctx, error=False):
1876 def commitctx(self, ctx, error=False):
1874 """Add a new revision to current repository.
1877 """Add a new revision to current repository.
1875 Revision information is passed via the context argument.
1878 Revision information is passed via the context argument.
1876 """
1879 """
1877
1880
1878 tr = None
1881 tr = None
1879 p1, p2 = ctx.p1(), ctx.p2()
1882 p1, p2 = ctx.p1(), ctx.p2()
1880 user = ctx.user()
1883 user = ctx.user()
1881
1884
1882 lock = self.lock()
1885 lock = self.lock()
1883 try:
1886 try:
1884 tr = self.transaction("commit")
1887 tr = self.transaction("commit")
1885 trp = weakref.proxy(tr)
1888 trp = weakref.proxy(tr)
1886
1889
1887 if ctx.manifestnode():
1890 if ctx.manifestnode():
1888 # reuse an existing manifest revision
1891 # reuse an existing manifest revision
1889 mn = ctx.manifestnode()
1892 mn = ctx.manifestnode()
1890 files = ctx.files()
1893 files = ctx.files()
1891 elif ctx.files():
1894 elif ctx.files():
1892 m1ctx = p1.manifestctx()
1895 m1ctx = p1.manifestctx()
1893 m2ctx = p2.manifestctx()
1896 m2ctx = p2.manifestctx()
1894 mctx = m1ctx.copy()
1897 mctx = m1ctx.copy()
1895
1898
1896 m = mctx.read()
1899 m = mctx.read()
1897 m1 = m1ctx.read()
1900 m1 = m1ctx.read()
1898 m2 = m2ctx.read()
1901 m2 = m2ctx.read()
1899
1902
1900 # check in files
1903 # check in files
1901 added = []
1904 added = []
1902 changed = []
1905 changed = []
1903 removed = list(ctx.removed())
1906 removed = list(ctx.removed())
1904 linkrev = len(self)
1907 linkrev = len(self)
1905 self.ui.note(_("committing files:\n"))
1908 self.ui.note(_("committing files:\n"))
1906 for f in sorted(ctx.modified() + ctx.added()):
1909 for f in sorted(ctx.modified() + ctx.added()):
1907 self.ui.note(f + "\n")
1910 self.ui.note(f + "\n")
1908 try:
1911 try:
1909 fctx = ctx[f]
1912 fctx = ctx[f]
1910 if fctx is None:
1913 if fctx is None:
1911 removed.append(f)
1914 removed.append(f)
1912 else:
1915 else:
1913 added.append(f)
1916 added.append(f)
1914 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1917 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1915 trp, changed)
1918 trp, changed)
1916 m.setflag(f, fctx.flags())
1919 m.setflag(f, fctx.flags())
1917 except OSError as inst:
1920 except OSError as inst:
1918 self.ui.warn(_("trouble committing %s!\n") % f)
1921 self.ui.warn(_("trouble committing %s!\n") % f)
1919 raise
1922 raise
1920 except IOError as inst:
1923 except IOError as inst:
1921 errcode = getattr(inst, 'errno', errno.ENOENT)
1924 errcode = getattr(inst, 'errno', errno.ENOENT)
1922 if error or errcode and errcode != errno.ENOENT:
1925 if error or errcode and errcode != errno.ENOENT:
1923 self.ui.warn(_("trouble committing %s!\n") % f)
1926 self.ui.warn(_("trouble committing %s!\n") % f)
1924 raise
1927 raise
1925
1928
1926 # update manifest
1929 # update manifest
1927 self.ui.note(_("committing manifest\n"))
1930 self.ui.note(_("committing manifest\n"))
1928 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1931 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1929 drop = [f for f in removed if f in m]
1932 drop = [f for f in removed if f in m]
1930 for f in drop:
1933 for f in drop:
1931 del m[f]
1934 del m[f]
1932 mn = mctx.write(trp, linkrev,
1935 mn = mctx.write(trp, linkrev,
1933 p1.manifestnode(), p2.manifestnode(),
1936 p1.manifestnode(), p2.manifestnode(),
1934 added, drop)
1937 added, drop)
1935 files = changed + removed
1938 files = changed + removed
1936 else:
1939 else:
1937 mn = p1.manifestnode()
1940 mn = p1.manifestnode()
1938 files = []
1941 files = []
1939
1942
1940 # update changelog
1943 # update changelog
1941 self.ui.note(_("committing changelog\n"))
1944 self.ui.note(_("committing changelog\n"))
1942 self.changelog.delayupdate(tr)
1945 self.changelog.delayupdate(tr)
1943 n = self.changelog.add(mn, files, ctx.description(),
1946 n = self.changelog.add(mn, files, ctx.description(),
1944 trp, p1.node(), p2.node(),
1947 trp, p1.node(), p2.node(),
1945 user, ctx.date(), ctx.extra().copy())
1948 user, ctx.date(), ctx.extra().copy())
1946 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1949 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1947 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1950 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1948 parent2=xp2)
1951 parent2=xp2)
1949 # set the new commit is proper phase
1952 # set the new commit is proper phase
1950 targetphase = subrepo.newcommitphase(self.ui, ctx)
1953 targetphase = subrepo.newcommitphase(self.ui, ctx)
1951 if targetphase:
1954 if targetphase:
1952 # retract boundary do not alter parent changeset.
1955 # retract boundary do not alter parent changeset.
1953 # if a parent have higher the resulting phase will
1956 # if a parent have higher the resulting phase will
1954 # be compliant anyway
1957 # be compliant anyway
1955 #
1958 #
1956 # if minimal phase was 0 we don't need to retract anything
1959 # if minimal phase was 0 we don't need to retract anything
1957 phases.registernew(self, tr, targetphase, [n])
1960 phases.registernew(self, tr, targetphase, [n])
1958 tr.close()
1961 tr.close()
1959 return n
1962 return n
1960 finally:
1963 finally:
1961 if tr:
1964 if tr:
1962 tr.release()
1965 tr.release()
1963 lock.release()
1966 lock.release()
1964
1967
1965 @unfilteredmethod
1968 @unfilteredmethod
1966 def destroying(self):
1969 def destroying(self):
1967 '''Inform the repository that nodes are about to be destroyed.
1970 '''Inform the repository that nodes are about to be destroyed.
1968 Intended for use by strip and rollback, so there's a common
1971 Intended for use by strip and rollback, so there's a common
1969 place for anything that has to be done before destroying history.
1972 place for anything that has to be done before destroying history.
1970
1973
1971 This is mostly useful for saving state that is in memory and waiting
1974 This is mostly useful for saving state that is in memory and waiting
1972 to be flushed when the current lock is released. Because a call to
1975 to be flushed when the current lock is released. Because a call to
1973 destroyed is imminent, the repo will be invalidated causing those
1976 destroyed is imminent, the repo will be invalidated causing those
1974 changes to stay in memory (waiting for the next unlock), or vanish
1977 changes to stay in memory (waiting for the next unlock), or vanish
1975 completely.
1978 completely.
1976 '''
1979 '''
1977 # When using the same lock to commit and strip, the phasecache is left
1980 # When using the same lock to commit and strip, the phasecache is left
1978 # dirty after committing. Then when we strip, the repo is invalidated,
1981 # dirty after committing. Then when we strip, the repo is invalidated,
1979 # causing those changes to disappear.
1982 # causing those changes to disappear.
1980 if '_phasecache' in vars(self):
1983 if '_phasecache' in vars(self):
1981 self._phasecache.write()
1984 self._phasecache.write()
1982
1985
1983 @unfilteredmethod
1986 @unfilteredmethod
1984 def destroyed(self):
1987 def destroyed(self):
1985 '''Inform the repository that nodes have been destroyed.
1988 '''Inform the repository that nodes have been destroyed.
1986 Intended for use by strip and rollback, so there's a common
1989 Intended for use by strip and rollback, so there's a common
1987 place for anything that has to be done after destroying history.
1990 place for anything that has to be done after destroying history.
1988 '''
1991 '''
1989 # When one tries to:
1992 # When one tries to:
1990 # 1) destroy nodes thus calling this method (e.g. strip)
1993 # 1) destroy nodes thus calling this method (e.g. strip)
1991 # 2) use phasecache somewhere (e.g. commit)
1994 # 2) use phasecache somewhere (e.g. commit)
1992 #
1995 #
1993 # then 2) will fail because the phasecache contains nodes that were
1996 # then 2) will fail because the phasecache contains nodes that were
1994 # removed. We can either remove phasecache from the filecache,
1997 # removed. We can either remove phasecache from the filecache,
1995 # causing it to reload next time it is accessed, or simply filter
1998 # causing it to reload next time it is accessed, or simply filter
1996 # the removed nodes now and write the updated cache.
1999 # the removed nodes now and write the updated cache.
1997 self._phasecache.filterunknown(self)
2000 self._phasecache.filterunknown(self)
1998 self._phasecache.write()
2001 self._phasecache.write()
1999
2002
2000 # refresh all repository caches
2003 # refresh all repository caches
2001 self.updatecaches()
2004 self.updatecaches()
2002
2005
2003 # Ensure the persistent tag cache is updated. Doing it now
2006 # Ensure the persistent tag cache is updated. Doing it now
2004 # means that the tag cache only has to worry about destroyed
2007 # means that the tag cache only has to worry about destroyed
2005 # heads immediately after a strip/rollback. That in turn
2008 # heads immediately after a strip/rollback. That in turn
2006 # guarantees that "cachetip == currenttip" (comparing both rev
2009 # guarantees that "cachetip == currenttip" (comparing both rev
2007 # and node) always means no nodes have been added or destroyed.
2010 # and node) always means no nodes have been added or destroyed.
2008
2011
2009 # XXX this is suboptimal when qrefresh'ing: we strip the current
2012 # XXX this is suboptimal when qrefresh'ing: we strip the current
2010 # head, refresh the tag cache, then immediately add a new head.
2013 # head, refresh the tag cache, then immediately add a new head.
2011 # But I think doing it this way is necessary for the "instant
2014 # But I think doing it this way is necessary for the "instant
2012 # tag cache retrieval" case to work.
2015 # tag cache retrieval" case to work.
2013 self.invalidate()
2016 self.invalidate()
2014
2017
2015 def walk(self, match, node=None):
2018 def walk(self, match, node=None):
2016 '''
2019 '''
2017 walk recursively through the directory tree or a given
2020 walk recursively through the directory tree or a given
2018 changeset, finding all files matched by the match
2021 changeset, finding all files matched by the match
2019 function
2022 function
2020 '''
2023 '''
2021 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2024 self.ui.deprecwarn('use repo[node].walk instead of repo.walk', '4.3')
2022 return self[node].walk(match)
2025 return self[node].walk(match)
2023
2026
2024 def status(self, node1='.', node2=None, match=None,
2027 def status(self, node1='.', node2=None, match=None,
2025 ignored=False, clean=False, unknown=False,
2028 ignored=False, clean=False, unknown=False,
2026 listsubrepos=False):
2029 listsubrepos=False):
2027 '''a convenience method that calls node1.status(node2)'''
2030 '''a convenience method that calls node1.status(node2)'''
2028 return self[node1].status(node2, match, ignored, clean, unknown,
2031 return self[node1].status(node2, match, ignored, clean, unknown,
2029 listsubrepos)
2032 listsubrepos)
2030
2033
2031 def addpostdsstatus(self, ps):
2034 def addpostdsstatus(self, ps):
2032 """Add a callback to run within the wlock, at the point at which status
2035 """Add a callback to run within the wlock, at the point at which status
2033 fixups happen.
2036 fixups happen.
2034
2037
2035 On status completion, callback(wctx, status) will be called with the
2038 On status completion, callback(wctx, status) will be called with the
2036 wlock held, unless the dirstate has changed from underneath or the wlock
2039 wlock held, unless the dirstate has changed from underneath or the wlock
2037 couldn't be grabbed.
2040 couldn't be grabbed.
2038
2041
2039 Callbacks should not capture and use a cached copy of the dirstate --
2042 Callbacks should not capture and use a cached copy of the dirstate --
2040 it might change in the meanwhile. Instead, they should access the
2043 it might change in the meanwhile. Instead, they should access the
2041 dirstate via wctx.repo().dirstate.
2044 dirstate via wctx.repo().dirstate.
2042
2045
2043 This list is emptied out after each status run -- extensions should
2046 This list is emptied out after each status run -- extensions should
2044 make sure it adds to this list each time dirstate.status is called.
2047 make sure it adds to this list each time dirstate.status is called.
2045 Extensions should also make sure they don't call this for statuses
2048 Extensions should also make sure they don't call this for statuses
2046 that don't involve the dirstate.
2049 that don't involve the dirstate.
2047 """
2050 """
2048
2051
2049 # The list is located here for uniqueness reasons -- it is actually
2052 # The list is located here for uniqueness reasons -- it is actually
2050 # managed by the workingctx, but that isn't unique per-repo.
2053 # managed by the workingctx, but that isn't unique per-repo.
2051 self._postdsstatus.append(ps)
2054 self._postdsstatus.append(ps)
2052
2055
2053 def postdsstatus(self):
2056 def postdsstatus(self):
2054 """Used by workingctx to get the list of post-dirstate-status hooks."""
2057 """Used by workingctx to get the list of post-dirstate-status hooks."""
2055 return self._postdsstatus
2058 return self._postdsstatus
2056
2059
2057 def clearpostdsstatus(self):
2060 def clearpostdsstatus(self):
2058 """Used by workingctx to clear post-dirstate-status hooks."""
2061 """Used by workingctx to clear post-dirstate-status hooks."""
2059 del self._postdsstatus[:]
2062 del self._postdsstatus[:]
2060
2063
2061 def heads(self, start=None):
2064 def heads(self, start=None):
2062 if start is None:
2065 if start is None:
2063 cl = self.changelog
2066 cl = self.changelog
2064 headrevs = reversed(cl.headrevs())
2067 headrevs = reversed(cl.headrevs())
2065 return [cl.node(rev) for rev in headrevs]
2068 return [cl.node(rev) for rev in headrevs]
2066
2069
2067 heads = self.changelog.heads(start)
2070 heads = self.changelog.heads(start)
2068 # sort the output in rev descending order
2071 # sort the output in rev descending order
2069 return sorted(heads, key=self.changelog.rev, reverse=True)
2072 return sorted(heads, key=self.changelog.rev, reverse=True)
2070
2073
2071 def branchheads(self, branch=None, start=None, closed=False):
2074 def branchheads(self, branch=None, start=None, closed=False):
2072 '''return a (possibly filtered) list of heads for the given branch
2075 '''return a (possibly filtered) list of heads for the given branch
2073
2076
2074 Heads are returned in topological order, from newest to oldest.
2077 Heads are returned in topological order, from newest to oldest.
2075 If branch is None, use the dirstate branch.
2078 If branch is None, use the dirstate branch.
2076 If start is not None, return only heads reachable from start.
2079 If start is not None, return only heads reachable from start.
2077 If closed is True, return heads that are marked as closed as well.
2080 If closed is True, return heads that are marked as closed as well.
2078 '''
2081 '''
2079 if branch is None:
2082 if branch is None:
2080 branch = self[None].branch()
2083 branch = self[None].branch()
2081 branches = self.branchmap()
2084 branches = self.branchmap()
2082 if branch not in branches:
2085 if branch not in branches:
2083 return []
2086 return []
2084 # the cache returns heads ordered lowest to highest
2087 # the cache returns heads ordered lowest to highest
2085 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2088 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2086 if start is not None:
2089 if start is not None:
2087 # filter out the heads that cannot be reached from startrev
2090 # filter out the heads that cannot be reached from startrev
2088 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2091 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2089 bheads = [h for h in bheads if h in fbheads]
2092 bheads = [h for h in bheads if h in fbheads]
2090 return bheads
2093 return bheads
2091
2094
2092 def branches(self, nodes):
2095 def branches(self, nodes):
2093 if not nodes:
2096 if not nodes:
2094 nodes = [self.changelog.tip()]
2097 nodes = [self.changelog.tip()]
2095 b = []
2098 b = []
2096 for n in nodes:
2099 for n in nodes:
2097 t = n
2100 t = n
2098 while True:
2101 while True:
2099 p = self.changelog.parents(n)
2102 p = self.changelog.parents(n)
2100 if p[1] != nullid or p[0] == nullid:
2103 if p[1] != nullid or p[0] == nullid:
2101 b.append((t, n, p[0], p[1]))
2104 b.append((t, n, p[0], p[1]))
2102 break
2105 break
2103 n = p[0]
2106 n = p[0]
2104 return b
2107 return b
2105
2108
2106 def between(self, pairs):
2109 def between(self, pairs):
2107 r = []
2110 r = []
2108
2111
2109 for top, bottom in pairs:
2112 for top, bottom in pairs:
2110 n, l, i = top, [], 0
2113 n, l, i = top, [], 0
2111 f = 1
2114 f = 1
2112
2115
2113 while n != bottom and n != nullid:
2116 while n != bottom and n != nullid:
2114 p = self.changelog.parents(n)[0]
2117 p = self.changelog.parents(n)[0]
2115 if i == f:
2118 if i == f:
2116 l.append(n)
2119 l.append(n)
2117 f = f * 2
2120 f = f * 2
2118 n = p
2121 n = p
2119 i += 1
2122 i += 1
2120
2123
2121 r.append(l)
2124 r.append(l)
2122
2125
2123 return r
2126 return r
2124
2127
2125 def checkpush(self, pushop):
2128 def checkpush(self, pushop):
2126 """Extensions can override this function if additional checks have
2129 """Extensions can override this function if additional checks have
2127 to be performed before pushing, or call it if they override push
2130 to be performed before pushing, or call it if they override push
2128 command.
2131 command.
2129 """
2132 """
2130 pass
2133 pass
2131
2134
2132 @unfilteredpropertycache
2135 @unfilteredpropertycache
2133 def prepushoutgoinghooks(self):
2136 def prepushoutgoinghooks(self):
2134 """Return util.hooks consists of a pushop with repo, remote, outgoing
2137 """Return util.hooks consists of a pushop with repo, remote, outgoing
2135 methods, which are called before pushing changesets.
2138 methods, which are called before pushing changesets.
2136 """
2139 """
2137 return util.hooks()
2140 return util.hooks()
2138
2141
2139 def pushkey(self, namespace, key, old, new):
2142 def pushkey(self, namespace, key, old, new):
2140 try:
2143 try:
2141 tr = self.currenttransaction()
2144 tr = self.currenttransaction()
2142 hookargs = {}
2145 hookargs = {}
2143 if tr is not None:
2146 if tr is not None:
2144 hookargs.update(tr.hookargs)
2147 hookargs.update(tr.hookargs)
2145 hookargs['namespace'] = namespace
2148 hookargs['namespace'] = namespace
2146 hookargs['key'] = key
2149 hookargs['key'] = key
2147 hookargs['old'] = old
2150 hookargs['old'] = old
2148 hookargs['new'] = new
2151 hookargs['new'] = new
2149 self.hook('prepushkey', throw=True, **hookargs)
2152 self.hook('prepushkey', throw=True, **hookargs)
2150 except error.HookAbort as exc:
2153 except error.HookAbort as exc:
2151 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2154 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2152 if exc.hint:
2155 if exc.hint:
2153 self.ui.write_err(_("(%s)\n") % exc.hint)
2156 self.ui.write_err(_("(%s)\n") % exc.hint)
2154 return False
2157 return False
2155 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2158 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2156 ret = pushkey.push(self, namespace, key, old, new)
2159 ret = pushkey.push(self, namespace, key, old, new)
2157 def runhook():
2160 def runhook():
2158 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2161 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2159 ret=ret)
2162 ret=ret)
2160 self._afterlock(runhook)
2163 self._afterlock(runhook)
2161 return ret
2164 return ret
2162
2165
2163 def listkeys(self, namespace):
2166 def listkeys(self, namespace):
2164 self.hook('prelistkeys', throw=True, namespace=namespace)
2167 self.hook('prelistkeys', throw=True, namespace=namespace)
2165 self.ui.debug('listing keys for "%s"\n' % namespace)
2168 self.ui.debug('listing keys for "%s"\n' % namespace)
2166 values = pushkey.list(self, namespace)
2169 values = pushkey.list(self, namespace)
2167 self.hook('listkeys', namespace=namespace, values=values)
2170 self.hook('listkeys', namespace=namespace, values=values)
2168 return values
2171 return values
2169
2172
2170 def debugwireargs(self, one, two, three=None, four=None, five=None):
2173 def debugwireargs(self, one, two, three=None, four=None, five=None):
2171 '''used to test argument passing over the wire'''
2174 '''used to test argument passing over the wire'''
2172 return "%s %s %s %s %s" % (one, two, three, four, five)
2175 return "%s %s %s %s %s" % (one, two, three, four, five)
2173
2176
2174 def savecommitmessage(self, text):
2177 def savecommitmessage(self, text):
2175 fp = self.vfs('last-message.txt', 'wb')
2178 fp = self.vfs('last-message.txt', 'wb')
2176 try:
2179 try:
2177 fp.write(text)
2180 fp.write(text)
2178 finally:
2181 finally:
2179 fp.close()
2182 fp.close()
2180 return self.pathto(fp.name[len(self.root) + 1:])
2183 return self.pathto(fp.name[len(self.root) + 1:])
2181
2184
2182 # used to avoid circular references so destructors work
2185 # used to avoid circular references so destructors work
2183 def aftertrans(files):
2186 def aftertrans(files):
2184 renamefiles = [tuple(t) for t in files]
2187 renamefiles = [tuple(t) for t in files]
2185 def a():
2188 def a():
2186 for vfs, src, dest in renamefiles:
2189 for vfs, src, dest in renamefiles:
2187 # if src and dest refer to a same file, vfs.rename is a no-op,
2190 # if src and dest refer to a same file, vfs.rename is a no-op,
2188 # leaving both src and dest on disk. delete dest to make sure
2191 # leaving both src and dest on disk. delete dest to make sure
2189 # the rename couldn't be such a no-op.
2192 # the rename couldn't be such a no-op.
2190 vfs.tryunlink(dest)
2193 vfs.tryunlink(dest)
2191 try:
2194 try:
2192 vfs.rename(src, dest)
2195 vfs.rename(src, dest)
2193 except OSError: # journal file does not yet exist
2196 except OSError: # journal file does not yet exist
2194 pass
2197 pass
2195 return a
2198 return a
2196
2199
2197 def undoname(fn):
2200 def undoname(fn):
2198 base, name = os.path.split(fn)
2201 base, name = os.path.split(fn)
2199 assert name.startswith('journal')
2202 assert name.startswith('journal')
2200 return os.path.join(base, name.replace('journal', 'undo', 1))
2203 return os.path.join(base, name.replace('journal', 'undo', 1))
2201
2204
2202 def instance(ui, path, create):
2205 def instance(ui, path, create):
2203 return localrepository(ui, util.urllocalpath(path), create)
2206 return localrepository(ui, util.urllocalpath(path), create)
2204
2207
2205 def islocal(path):
2208 def islocal(path):
2206 return True
2209 return True
2207
2210
2208 def newreporequirements(repo):
2211 def newreporequirements(repo):
2209 """Determine the set of requirements for a new local repository.
2212 """Determine the set of requirements for a new local repository.
2210
2213
2211 Extensions can wrap this function to specify custom requirements for
2214 Extensions can wrap this function to specify custom requirements for
2212 new repositories.
2215 new repositories.
2213 """
2216 """
2214 ui = repo.ui
2217 ui = repo.ui
2215 requirements = {'revlogv1'}
2218 requirements = {'revlogv1'}
2216 if ui.configbool('format', 'usestore'):
2219 if ui.configbool('format', 'usestore'):
2217 requirements.add('store')
2220 requirements.add('store')
2218 if ui.configbool('format', 'usefncache'):
2221 if ui.configbool('format', 'usefncache'):
2219 requirements.add('fncache')
2222 requirements.add('fncache')
2220 if ui.configbool('format', 'dotencode'):
2223 if ui.configbool('format', 'dotencode'):
2221 requirements.add('dotencode')
2224 requirements.add('dotencode')
2222
2225
2223 compengine = ui.config('experimental', 'format.compression')
2226 compengine = ui.config('experimental', 'format.compression')
2224 if compengine not in util.compengines:
2227 if compengine not in util.compengines:
2225 raise error.Abort(_('compression engine %s defined by '
2228 raise error.Abort(_('compression engine %s defined by '
2226 'experimental.format.compression not available') %
2229 'experimental.format.compression not available') %
2227 compengine,
2230 compengine,
2228 hint=_('run "hg debuginstall" to list available '
2231 hint=_('run "hg debuginstall" to list available '
2229 'compression engines'))
2232 'compression engines'))
2230
2233
2231 # zlib is the historical default and doesn't need an explicit requirement.
2234 # zlib is the historical default and doesn't need an explicit requirement.
2232 if compengine != 'zlib':
2235 if compengine != 'zlib':
2233 requirements.add('exp-compression-%s' % compengine)
2236 requirements.add('exp-compression-%s' % compengine)
2234
2237
2235 if scmutil.gdinitconfig(ui):
2238 if scmutil.gdinitconfig(ui):
2236 requirements.add('generaldelta')
2239 requirements.add('generaldelta')
2237 if ui.configbool('experimental', 'treemanifest'):
2240 if ui.configbool('experimental', 'treemanifest'):
2238 requirements.add('treemanifest')
2241 requirements.add('treemanifest')
2239 if ui.configbool('experimental', 'manifestv2'):
2242 if ui.configbool('experimental', 'manifestv2'):
2240 requirements.add('manifestv2')
2243 requirements.add('manifestv2')
2241
2244
2242 revlogv2 = ui.config('experimental', 'revlogv2')
2245 revlogv2 = ui.config('experimental', 'revlogv2')
2243 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2246 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2244 requirements.remove('revlogv1')
2247 requirements.remove('revlogv1')
2245 # generaldelta is implied by revlogv2.
2248 # generaldelta is implied by revlogv2.
2246 requirements.discard('generaldelta')
2249 requirements.discard('generaldelta')
2247 requirements.add(REVLOGV2_REQUIREMENT)
2250 requirements.add(REVLOGV2_REQUIREMENT)
2248
2251
2249 return requirements
2252 return requirements
General Comments 0
You need to be logged in to leave comments. Login now