##// END OF EJS Templates
persistent-node: check the value of the slow-path config...
marmoute -
r47027:2c9c8887 default
parent child Browse files
Show More
@@ -1,3619 +1,3634 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 functools
11 import functools
12 import os
12 import os
13 import random
13 import random
14 import sys
14 import sys
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 bin,
20 bin,
21 hex,
21 hex,
22 nullid,
22 nullid,
23 nullrev,
23 nullrev,
24 short,
24 short,
25 )
25 )
26 from .pycompat import (
26 from .pycompat import (
27 delattr,
27 delattr,
28 getattr,
28 getattr,
29 )
29 )
30 from . import (
30 from . import (
31 bookmarks,
31 bookmarks,
32 branchmap,
32 branchmap,
33 bundle2,
33 bundle2,
34 bundlecaches,
34 bundlecaches,
35 changegroup,
35 changegroup,
36 color,
36 color,
37 commit,
37 commit,
38 context,
38 context,
39 dirstate,
39 dirstate,
40 dirstateguard,
40 dirstateguard,
41 discovery,
41 discovery,
42 encoding,
42 encoding,
43 error,
43 error,
44 exchange,
44 exchange,
45 extensions,
45 extensions,
46 filelog,
46 filelog,
47 hook,
47 hook,
48 lock as lockmod,
48 lock as lockmod,
49 match as matchmod,
49 match as matchmod,
50 mergestate as mergestatemod,
50 mergestate as mergestatemod,
51 mergeutil,
51 mergeutil,
52 namespaces,
52 namespaces,
53 narrowspec,
53 narrowspec,
54 obsolete,
54 obsolete,
55 pathutil,
55 pathutil,
56 phases,
56 phases,
57 pushkey,
57 pushkey,
58 pycompat,
58 pycompat,
59 rcutil,
59 rcutil,
60 repoview,
60 repoview,
61 requirements as requirementsmod,
61 requirements as requirementsmod,
62 revset,
62 revset,
63 revsetlang,
63 revsetlang,
64 scmutil,
64 scmutil,
65 sparse,
65 sparse,
66 store as storemod,
66 store as storemod,
67 subrepoutil,
67 subrepoutil,
68 tags as tagsmod,
68 tags as tagsmod,
69 transaction,
69 transaction,
70 txnutil,
70 txnutil,
71 util,
71 util,
72 vfs as vfsmod,
72 vfs as vfsmod,
73 )
73 )
74
74
75 from .interfaces import (
75 from .interfaces import (
76 repository,
76 repository,
77 util as interfaceutil,
77 util as interfaceutil,
78 )
78 )
79
79
80 from .utils import (
80 from .utils import (
81 hashutil,
81 hashutil,
82 procutil,
82 procutil,
83 stringutil,
83 stringutil,
84 )
84 )
85
85
86 from .revlogutils import constants as revlogconst
86 from .revlogutils import constants as revlogconst
87
87
88 release = lockmod.release
88 release = lockmod.release
89 urlerr = util.urlerr
89 urlerr = util.urlerr
90 urlreq = util.urlreq
90 urlreq = util.urlreq
91
91
92 # set of (path, vfs-location) tuples. vfs-location is:
92 # set of (path, vfs-location) tuples. vfs-location is:
93 # - 'plain for vfs relative paths
93 # - 'plain for vfs relative paths
94 # - '' for svfs relative paths
94 # - '' for svfs relative paths
95 _cachedfiles = set()
95 _cachedfiles = set()
96
96
97
97
98 class _basefilecache(scmutil.filecache):
98 class _basefilecache(scmutil.filecache):
99 """All filecache usage on repo are done for logic that should be unfiltered"""
99 """All filecache usage on repo are done for logic that should be unfiltered"""
100
100
101 def __get__(self, repo, type=None):
101 def __get__(self, repo, type=None):
102 if repo is None:
102 if repo is None:
103 return self
103 return self
104 # proxy to unfiltered __dict__ since filtered repo has no entry
104 # proxy to unfiltered __dict__ since filtered repo has no entry
105 unfi = repo.unfiltered()
105 unfi = repo.unfiltered()
106 try:
106 try:
107 return unfi.__dict__[self.sname]
107 return unfi.__dict__[self.sname]
108 except KeyError:
108 except KeyError:
109 pass
109 pass
110 return super(_basefilecache, self).__get__(unfi, type)
110 return super(_basefilecache, self).__get__(unfi, type)
111
111
112 def set(self, repo, value):
112 def set(self, repo, value):
113 return super(_basefilecache, self).set(repo.unfiltered(), value)
113 return super(_basefilecache, self).set(repo.unfiltered(), value)
114
114
115
115
116 class repofilecache(_basefilecache):
116 class repofilecache(_basefilecache):
117 """filecache for files in .hg but outside of .hg/store"""
117 """filecache for files in .hg but outside of .hg/store"""
118
118
119 def __init__(self, *paths):
119 def __init__(self, *paths):
120 super(repofilecache, self).__init__(*paths)
120 super(repofilecache, self).__init__(*paths)
121 for path in paths:
121 for path in paths:
122 _cachedfiles.add((path, b'plain'))
122 _cachedfiles.add((path, b'plain'))
123
123
124 def join(self, obj, fname):
124 def join(self, obj, fname):
125 return obj.vfs.join(fname)
125 return obj.vfs.join(fname)
126
126
127
127
128 class storecache(_basefilecache):
128 class storecache(_basefilecache):
129 """filecache for files in the store"""
129 """filecache for files in the store"""
130
130
131 def __init__(self, *paths):
131 def __init__(self, *paths):
132 super(storecache, self).__init__(*paths)
132 super(storecache, self).__init__(*paths)
133 for path in paths:
133 for path in paths:
134 _cachedfiles.add((path, b''))
134 _cachedfiles.add((path, b''))
135
135
136 def join(self, obj, fname):
136 def join(self, obj, fname):
137 return obj.sjoin(fname)
137 return obj.sjoin(fname)
138
138
139
139
140 class mixedrepostorecache(_basefilecache):
140 class mixedrepostorecache(_basefilecache):
141 """filecache for a mix files in .hg/store and outside"""
141 """filecache for a mix files in .hg/store and outside"""
142
142
143 def __init__(self, *pathsandlocations):
143 def __init__(self, *pathsandlocations):
144 # scmutil.filecache only uses the path for passing back into our
144 # scmutil.filecache only uses the path for passing back into our
145 # join(), so we can safely pass a list of paths and locations
145 # join(), so we can safely pass a list of paths and locations
146 super(mixedrepostorecache, self).__init__(*pathsandlocations)
146 super(mixedrepostorecache, self).__init__(*pathsandlocations)
147 _cachedfiles.update(pathsandlocations)
147 _cachedfiles.update(pathsandlocations)
148
148
149 def join(self, obj, fnameandlocation):
149 def join(self, obj, fnameandlocation):
150 fname, location = fnameandlocation
150 fname, location = fnameandlocation
151 if location == b'plain':
151 if location == b'plain':
152 return obj.vfs.join(fname)
152 return obj.vfs.join(fname)
153 else:
153 else:
154 if location != b'':
154 if location != b'':
155 raise error.ProgrammingError(
155 raise error.ProgrammingError(
156 b'unexpected location: %s' % location
156 b'unexpected location: %s' % location
157 )
157 )
158 return obj.sjoin(fname)
158 return obj.sjoin(fname)
159
159
160
160
161 def isfilecached(repo, name):
161 def isfilecached(repo, name):
162 """check if a repo has already cached "name" filecache-ed property
162 """check if a repo has already cached "name" filecache-ed property
163
163
164 This returns (cachedobj-or-None, iscached) tuple.
164 This returns (cachedobj-or-None, iscached) tuple.
165 """
165 """
166 cacheentry = repo.unfiltered()._filecache.get(name, None)
166 cacheentry = repo.unfiltered()._filecache.get(name, None)
167 if not cacheentry:
167 if not cacheentry:
168 return None, False
168 return None, False
169 return cacheentry.obj, True
169 return cacheentry.obj, True
170
170
171
171
172 class unfilteredpropertycache(util.propertycache):
172 class unfilteredpropertycache(util.propertycache):
173 """propertycache that apply to unfiltered repo only"""
173 """propertycache that apply to unfiltered repo only"""
174
174
175 def __get__(self, repo, type=None):
175 def __get__(self, repo, type=None):
176 unfi = repo.unfiltered()
176 unfi = repo.unfiltered()
177 if unfi is repo:
177 if unfi is repo:
178 return super(unfilteredpropertycache, self).__get__(unfi)
178 return super(unfilteredpropertycache, self).__get__(unfi)
179 return getattr(unfi, self.name)
179 return getattr(unfi, self.name)
180
180
181
181
182 class filteredpropertycache(util.propertycache):
182 class filteredpropertycache(util.propertycache):
183 """propertycache that must take filtering in account"""
183 """propertycache that must take filtering in account"""
184
184
185 def cachevalue(self, obj, value):
185 def cachevalue(self, obj, value):
186 object.__setattr__(obj, self.name, value)
186 object.__setattr__(obj, self.name, value)
187
187
188
188
189 def hasunfilteredcache(repo, name):
189 def hasunfilteredcache(repo, name):
190 """check if a repo has an unfilteredpropertycache value for <name>"""
190 """check if a repo has an unfilteredpropertycache value for <name>"""
191 return name in vars(repo.unfiltered())
191 return name in vars(repo.unfiltered())
192
192
193
193
194 def unfilteredmethod(orig):
194 def unfilteredmethod(orig):
195 """decorate method that always need to be run on unfiltered version"""
195 """decorate method that always need to be run on unfiltered version"""
196
196
197 @functools.wraps(orig)
197 @functools.wraps(orig)
198 def wrapper(repo, *args, **kwargs):
198 def wrapper(repo, *args, **kwargs):
199 return orig(repo.unfiltered(), *args, **kwargs)
199 return orig(repo.unfiltered(), *args, **kwargs)
200
200
201 return wrapper
201 return wrapper
202
202
203
203
204 moderncaps = {
204 moderncaps = {
205 b'lookup',
205 b'lookup',
206 b'branchmap',
206 b'branchmap',
207 b'pushkey',
207 b'pushkey',
208 b'known',
208 b'known',
209 b'getbundle',
209 b'getbundle',
210 b'unbundle',
210 b'unbundle',
211 }
211 }
212 legacycaps = moderncaps.union({b'changegroupsubset'})
212 legacycaps = moderncaps.union({b'changegroupsubset'})
213
213
214
214
215 @interfaceutil.implementer(repository.ipeercommandexecutor)
215 @interfaceutil.implementer(repository.ipeercommandexecutor)
216 class localcommandexecutor(object):
216 class localcommandexecutor(object):
217 def __init__(self, peer):
217 def __init__(self, peer):
218 self._peer = peer
218 self._peer = peer
219 self._sent = False
219 self._sent = False
220 self._closed = False
220 self._closed = False
221
221
222 def __enter__(self):
222 def __enter__(self):
223 return self
223 return self
224
224
225 def __exit__(self, exctype, excvalue, exctb):
225 def __exit__(self, exctype, excvalue, exctb):
226 self.close()
226 self.close()
227
227
228 def callcommand(self, command, args):
228 def callcommand(self, command, args):
229 if self._sent:
229 if self._sent:
230 raise error.ProgrammingError(
230 raise error.ProgrammingError(
231 b'callcommand() cannot be used after sendcommands()'
231 b'callcommand() cannot be used after sendcommands()'
232 )
232 )
233
233
234 if self._closed:
234 if self._closed:
235 raise error.ProgrammingError(
235 raise error.ProgrammingError(
236 b'callcommand() cannot be used after close()'
236 b'callcommand() cannot be used after close()'
237 )
237 )
238
238
239 # We don't need to support anything fancy. Just call the named
239 # We don't need to support anything fancy. Just call the named
240 # method on the peer and return a resolved future.
240 # method on the peer and return a resolved future.
241 fn = getattr(self._peer, pycompat.sysstr(command))
241 fn = getattr(self._peer, pycompat.sysstr(command))
242
242
243 f = pycompat.futures.Future()
243 f = pycompat.futures.Future()
244
244
245 try:
245 try:
246 result = fn(**pycompat.strkwargs(args))
246 result = fn(**pycompat.strkwargs(args))
247 except Exception:
247 except Exception:
248 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
248 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
249 else:
249 else:
250 f.set_result(result)
250 f.set_result(result)
251
251
252 return f
252 return f
253
253
254 def sendcommands(self):
254 def sendcommands(self):
255 self._sent = True
255 self._sent = True
256
256
257 def close(self):
257 def close(self):
258 self._closed = True
258 self._closed = True
259
259
260
260
261 @interfaceutil.implementer(repository.ipeercommands)
261 @interfaceutil.implementer(repository.ipeercommands)
262 class localpeer(repository.peer):
262 class localpeer(repository.peer):
263 '''peer for a local repo; reflects only the most recent API'''
263 '''peer for a local repo; reflects only the most recent API'''
264
264
265 def __init__(self, repo, caps=None):
265 def __init__(self, repo, caps=None):
266 super(localpeer, self).__init__()
266 super(localpeer, self).__init__()
267
267
268 if caps is None:
268 if caps is None:
269 caps = moderncaps.copy()
269 caps = moderncaps.copy()
270 self._repo = repo.filtered(b'served')
270 self._repo = repo.filtered(b'served')
271 self.ui = repo.ui
271 self.ui = repo.ui
272 self._caps = repo._restrictcapabilities(caps)
272 self._caps = repo._restrictcapabilities(caps)
273
273
274 # Begin of _basepeer interface.
274 # Begin of _basepeer interface.
275
275
276 def url(self):
276 def url(self):
277 return self._repo.url()
277 return self._repo.url()
278
278
279 def local(self):
279 def local(self):
280 return self._repo
280 return self._repo
281
281
282 def peer(self):
282 def peer(self):
283 return self
283 return self
284
284
285 def canpush(self):
285 def canpush(self):
286 return True
286 return True
287
287
288 def close(self):
288 def close(self):
289 self._repo.close()
289 self._repo.close()
290
290
291 # End of _basepeer interface.
291 # End of _basepeer interface.
292
292
293 # Begin of _basewirecommands interface.
293 # Begin of _basewirecommands interface.
294
294
295 def branchmap(self):
295 def branchmap(self):
296 return self._repo.branchmap()
296 return self._repo.branchmap()
297
297
298 def capabilities(self):
298 def capabilities(self):
299 return self._caps
299 return self._caps
300
300
301 def clonebundles(self):
301 def clonebundles(self):
302 return self._repo.tryread(bundlecaches.CB_MANIFEST_FILE)
302 return self._repo.tryread(bundlecaches.CB_MANIFEST_FILE)
303
303
304 def debugwireargs(self, one, two, three=None, four=None, five=None):
304 def debugwireargs(self, one, two, three=None, four=None, five=None):
305 """Used to test argument passing over the wire"""
305 """Used to test argument passing over the wire"""
306 return b"%s %s %s %s %s" % (
306 return b"%s %s %s %s %s" % (
307 one,
307 one,
308 two,
308 two,
309 pycompat.bytestr(three),
309 pycompat.bytestr(three),
310 pycompat.bytestr(four),
310 pycompat.bytestr(four),
311 pycompat.bytestr(five),
311 pycompat.bytestr(five),
312 )
312 )
313
313
314 def getbundle(
314 def getbundle(
315 self, source, heads=None, common=None, bundlecaps=None, **kwargs
315 self, source, heads=None, common=None, bundlecaps=None, **kwargs
316 ):
316 ):
317 chunks = exchange.getbundlechunks(
317 chunks = exchange.getbundlechunks(
318 self._repo,
318 self._repo,
319 source,
319 source,
320 heads=heads,
320 heads=heads,
321 common=common,
321 common=common,
322 bundlecaps=bundlecaps,
322 bundlecaps=bundlecaps,
323 **kwargs
323 **kwargs
324 )[1]
324 )[1]
325 cb = util.chunkbuffer(chunks)
325 cb = util.chunkbuffer(chunks)
326
326
327 if exchange.bundle2requested(bundlecaps):
327 if exchange.bundle2requested(bundlecaps):
328 # When requesting a bundle2, getbundle returns a stream to make the
328 # When requesting a bundle2, getbundle returns a stream to make the
329 # wire level function happier. We need to build a proper object
329 # wire level function happier. We need to build a proper object
330 # from it in local peer.
330 # from it in local peer.
331 return bundle2.getunbundler(self.ui, cb)
331 return bundle2.getunbundler(self.ui, cb)
332 else:
332 else:
333 return changegroup.getunbundler(b'01', cb, None)
333 return changegroup.getunbundler(b'01', cb, None)
334
334
335 def heads(self):
335 def heads(self):
336 return self._repo.heads()
336 return self._repo.heads()
337
337
338 def known(self, nodes):
338 def known(self, nodes):
339 return self._repo.known(nodes)
339 return self._repo.known(nodes)
340
340
341 def listkeys(self, namespace):
341 def listkeys(self, namespace):
342 return self._repo.listkeys(namespace)
342 return self._repo.listkeys(namespace)
343
343
344 def lookup(self, key):
344 def lookup(self, key):
345 return self._repo.lookup(key)
345 return self._repo.lookup(key)
346
346
347 def pushkey(self, namespace, key, old, new):
347 def pushkey(self, namespace, key, old, new):
348 return self._repo.pushkey(namespace, key, old, new)
348 return self._repo.pushkey(namespace, key, old, new)
349
349
350 def stream_out(self):
350 def stream_out(self):
351 raise error.Abort(_(b'cannot perform stream clone against local peer'))
351 raise error.Abort(_(b'cannot perform stream clone against local peer'))
352
352
353 def unbundle(self, bundle, heads, url):
353 def unbundle(self, bundle, heads, url):
354 """apply a bundle on a repo
354 """apply a bundle on a repo
355
355
356 This function handles the repo locking itself."""
356 This function handles the repo locking itself."""
357 try:
357 try:
358 try:
358 try:
359 bundle = exchange.readbundle(self.ui, bundle, None)
359 bundle = exchange.readbundle(self.ui, bundle, None)
360 ret = exchange.unbundle(self._repo, bundle, heads, b'push', url)
360 ret = exchange.unbundle(self._repo, bundle, heads, b'push', url)
361 if util.safehasattr(ret, b'getchunks'):
361 if util.safehasattr(ret, b'getchunks'):
362 # This is a bundle20 object, turn it into an unbundler.
362 # This is a bundle20 object, turn it into an unbundler.
363 # This little dance should be dropped eventually when the
363 # This little dance should be dropped eventually when the
364 # API is finally improved.
364 # API is finally improved.
365 stream = util.chunkbuffer(ret.getchunks())
365 stream = util.chunkbuffer(ret.getchunks())
366 ret = bundle2.getunbundler(self.ui, stream)
366 ret = bundle2.getunbundler(self.ui, stream)
367 return ret
367 return ret
368 except Exception as exc:
368 except Exception as exc:
369 # If the exception contains output salvaged from a bundle2
369 # If the exception contains output salvaged from a bundle2
370 # reply, we need to make sure it is printed before continuing
370 # reply, we need to make sure it is printed before continuing
371 # to fail. So we build a bundle2 with such output and consume
371 # to fail. So we build a bundle2 with such output and consume
372 # it directly.
372 # it directly.
373 #
373 #
374 # This is not very elegant but allows a "simple" solution for
374 # This is not very elegant but allows a "simple" solution for
375 # issue4594
375 # issue4594
376 output = getattr(exc, '_bundle2salvagedoutput', ())
376 output = getattr(exc, '_bundle2salvagedoutput', ())
377 if output:
377 if output:
378 bundler = bundle2.bundle20(self._repo.ui)
378 bundler = bundle2.bundle20(self._repo.ui)
379 for out in output:
379 for out in output:
380 bundler.addpart(out)
380 bundler.addpart(out)
381 stream = util.chunkbuffer(bundler.getchunks())
381 stream = util.chunkbuffer(bundler.getchunks())
382 b = bundle2.getunbundler(self.ui, stream)
382 b = bundle2.getunbundler(self.ui, stream)
383 bundle2.processbundle(self._repo, b)
383 bundle2.processbundle(self._repo, b)
384 raise
384 raise
385 except error.PushRaced as exc:
385 except error.PushRaced as exc:
386 raise error.ResponseError(
386 raise error.ResponseError(
387 _(b'push failed:'), stringutil.forcebytestr(exc)
387 _(b'push failed:'), stringutil.forcebytestr(exc)
388 )
388 )
389
389
390 # End of _basewirecommands interface.
390 # End of _basewirecommands interface.
391
391
392 # Begin of peer interface.
392 # Begin of peer interface.
393
393
394 def commandexecutor(self):
394 def commandexecutor(self):
395 return localcommandexecutor(self)
395 return localcommandexecutor(self)
396
396
397 # End of peer interface.
397 # End of peer interface.
398
398
399
399
400 @interfaceutil.implementer(repository.ipeerlegacycommands)
400 @interfaceutil.implementer(repository.ipeerlegacycommands)
401 class locallegacypeer(localpeer):
401 class locallegacypeer(localpeer):
402 """peer extension which implements legacy methods too; used for tests with
402 """peer extension which implements legacy methods too; used for tests with
403 restricted capabilities"""
403 restricted capabilities"""
404
404
405 def __init__(self, repo):
405 def __init__(self, repo):
406 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
406 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
407
407
408 # Begin of baselegacywirecommands interface.
408 # Begin of baselegacywirecommands interface.
409
409
410 def between(self, pairs):
410 def between(self, pairs):
411 return self._repo.between(pairs)
411 return self._repo.between(pairs)
412
412
413 def branches(self, nodes):
413 def branches(self, nodes):
414 return self._repo.branches(nodes)
414 return self._repo.branches(nodes)
415
415
416 def changegroup(self, nodes, source):
416 def changegroup(self, nodes, source):
417 outgoing = discovery.outgoing(
417 outgoing = discovery.outgoing(
418 self._repo, missingroots=nodes, ancestorsof=self._repo.heads()
418 self._repo, missingroots=nodes, ancestorsof=self._repo.heads()
419 )
419 )
420 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
420 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
421
421
422 def changegroupsubset(self, bases, heads, source):
422 def changegroupsubset(self, bases, heads, source):
423 outgoing = discovery.outgoing(
423 outgoing = discovery.outgoing(
424 self._repo, missingroots=bases, ancestorsof=heads
424 self._repo, missingroots=bases, ancestorsof=heads
425 )
425 )
426 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
426 return changegroup.makechangegroup(self._repo, outgoing, b'01', source)
427
427
428 # End of baselegacywirecommands interface.
428 # End of baselegacywirecommands interface.
429
429
430
430
431 # Functions receiving (ui, features) that extensions can register to impact
431 # Functions receiving (ui, features) that extensions can register to impact
432 # the ability to load repositories with custom requirements. Only
432 # the ability to load repositories with custom requirements. Only
433 # functions defined in loaded extensions are called.
433 # functions defined in loaded extensions are called.
434 #
434 #
435 # The function receives a set of requirement strings that the repository
435 # The function receives a set of requirement strings that the repository
436 # is capable of opening. Functions will typically add elements to the
436 # is capable of opening. Functions will typically add elements to the
437 # set to reflect that the extension knows how to handle that requirements.
437 # set to reflect that the extension knows how to handle that requirements.
438 featuresetupfuncs = set()
438 featuresetupfuncs = set()
439
439
440
440
441 def _getsharedvfs(hgvfs, requirements):
441 def _getsharedvfs(hgvfs, requirements):
442 """returns the vfs object pointing to root of shared source
442 """returns the vfs object pointing to root of shared source
443 repo for a shared repository
443 repo for a shared repository
444
444
445 hgvfs is vfs pointing at .hg/ of current repo (shared one)
445 hgvfs is vfs pointing at .hg/ of current repo (shared one)
446 requirements is a set of requirements of current repo (shared one)
446 requirements is a set of requirements of current repo (shared one)
447 """
447 """
448 # The ``shared`` or ``relshared`` requirements indicate the
448 # The ``shared`` or ``relshared`` requirements indicate the
449 # store lives in the path contained in the ``.hg/sharedpath`` file.
449 # store lives in the path contained in the ``.hg/sharedpath`` file.
450 # This is an absolute path for ``shared`` and relative to
450 # This is an absolute path for ``shared`` and relative to
451 # ``.hg/`` for ``relshared``.
451 # ``.hg/`` for ``relshared``.
452 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
452 sharedpath = hgvfs.read(b'sharedpath').rstrip(b'\n')
453 if requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements:
453 if requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements:
454 sharedpath = hgvfs.join(sharedpath)
454 sharedpath = hgvfs.join(sharedpath)
455
455
456 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
456 sharedvfs = vfsmod.vfs(sharedpath, realpath=True)
457
457
458 if not sharedvfs.exists():
458 if not sharedvfs.exists():
459 raise error.RepoError(
459 raise error.RepoError(
460 _(b'.hg/sharedpath points to nonexistent directory %s')
460 _(b'.hg/sharedpath points to nonexistent directory %s')
461 % sharedvfs.base
461 % sharedvfs.base
462 )
462 )
463 return sharedvfs
463 return sharedvfs
464
464
465
465
466 def _readrequires(vfs, allowmissing):
466 def _readrequires(vfs, allowmissing):
467 """reads the require file present at root of this vfs
467 """reads the require file present at root of this vfs
468 and return a set of requirements
468 and return a set of requirements
469
469
470 If allowmissing is True, we suppress ENOENT if raised"""
470 If allowmissing is True, we suppress ENOENT if raised"""
471 # requires file contains a newline-delimited list of
471 # requires file contains a newline-delimited list of
472 # features/capabilities the opener (us) must have in order to use
472 # features/capabilities the opener (us) must have in order to use
473 # the repository. This file was introduced in Mercurial 0.9.2,
473 # the repository. This file was introduced in Mercurial 0.9.2,
474 # which means very old repositories may not have one. We assume
474 # which means very old repositories may not have one. We assume
475 # a missing file translates to no requirements.
475 # a missing file translates to no requirements.
476 try:
476 try:
477 requirements = set(vfs.read(b'requires').splitlines())
477 requirements = set(vfs.read(b'requires').splitlines())
478 except IOError as e:
478 except IOError as e:
479 if not (allowmissing and e.errno == errno.ENOENT):
479 if not (allowmissing and e.errno == errno.ENOENT):
480 raise
480 raise
481 requirements = set()
481 requirements = set()
482 return requirements
482 return requirements
483
483
484
484
485 def makelocalrepository(baseui, path, intents=None):
485 def makelocalrepository(baseui, path, intents=None):
486 """Create a local repository object.
486 """Create a local repository object.
487
487
488 Given arguments needed to construct a local repository, this function
488 Given arguments needed to construct a local repository, this function
489 performs various early repository loading functionality (such as
489 performs various early repository loading functionality (such as
490 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
490 reading the ``.hg/requires`` and ``.hg/hgrc`` files), validates that
491 the repository can be opened, derives a type suitable for representing
491 the repository can be opened, derives a type suitable for representing
492 that repository, and returns an instance of it.
492 that repository, and returns an instance of it.
493
493
494 The returned object conforms to the ``repository.completelocalrepository``
494 The returned object conforms to the ``repository.completelocalrepository``
495 interface.
495 interface.
496
496
497 The repository type is derived by calling a series of factory functions
497 The repository type is derived by calling a series of factory functions
498 for each aspect/interface of the final repository. These are defined by
498 for each aspect/interface of the final repository. These are defined by
499 ``REPO_INTERFACES``.
499 ``REPO_INTERFACES``.
500
500
501 Each factory function is called to produce a type implementing a specific
501 Each factory function is called to produce a type implementing a specific
502 interface. The cumulative list of returned types will be combined into a
502 interface. The cumulative list of returned types will be combined into a
503 new type and that type will be instantiated to represent the local
503 new type and that type will be instantiated to represent the local
504 repository.
504 repository.
505
505
506 The factory functions each receive various state that may be consulted
506 The factory functions each receive various state that may be consulted
507 as part of deriving a type.
507 as part of deriving a type.
508
508
509 Extensions should wrap these factory functions to customize repository type
509 Extensions should wrap these factory functions to customize repository type
510 creation. Note that an extension's wrapped function may be called even if
510 creation. Note that an extension's wrapped function may be called even if
511 that extension is not loaded for the repo being constructed. Extensions
511 that extension is not loaded for the repo being constructed. Extensions
512 should check if their ``__name__`` appears in the
512 should check if their ``__name__`` appears in the
513 ``extensionmodulenames`` set passed to the factory function and no-op if
513 ``extensionmodulenames`` set passed to the factory function and no-op if
514 not.
514 not.
515 """
515 """
516 ui = baseui.copy()
516 ui = baseui.copy()
517 # Prevent copying repo configuration.
517 # Prevent copying repo configuration.
518 ui.copy = baseui.copy
518 ui.copy = baseui.copy
519
519
520 # Working directory VFS rooted at repository root.
520 # Working directory VFS rooted at repository root.
521 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
521 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
522
522
523 # Main VFS for .hg/ directory.
523 # Main VFS for .hg/ directory.
524 hgpath = wdirvfs.join(b'.hg')
524 hgpath = wdirvfs.join(b'.hg')
525 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
525 hgvfs = vfsmod.vfs(hgpath, cacheaudited=True)
526 # Whether this repository is shared one or not
526 # Whether this repository is shared one or not
527 shared = False
527 shared = False
528 # If this repository is shared, vfs pointing to shared repo
528 # If this repository is shared, vfs pointing to shared repo
529 sharedvfs = None
529 sharedvfs = None
530
530
531 # The .hg/ path should exist and should be a directory. All other
531 # The .hg/ path should exist and should be a directory. All other
532 # cases are errors.
532 # cases are errors.
533 if not hgvfs.isdir():
533 if not hgvfs.isdir():
534 try:
534 try:
535 hgvfs.stat()
535 hgvfs.stat()
536 except OSError as e:
536 except OSError as e:
537 if e.errno != errno.ENOENT:
537 if e.errno != errno.ENOENT:
538 raise
538 raise
539 except ValueError as e:
539 except ValueError as e:
540 # Can be raised on Python 3.8 when path is invalid.
540 # Can be raised on Python 3.8 when path is invalid.
541 raise error.Abort(
541 raise error.Abort(
542 _(b'invalid path %s: %s') % (path, pycompat.bytestr(e))
542 _(b'invalid path %s: %s') % (path, pycompat.bytestr(e))
543 )
543 )
544
544
545 raise error.RepoError(_(b'repository %s not found') % path)
545 raise error.RepoError(_(b'repository %s not found') % path)
546
546
547 requirements = _readrequires(hgvfs, True)
547 requirements = _readrequires(hgvfs, True)
548 shared = (
548 shared = (
549 requirementsmod.SHARED_REQUIREMENT in requirements
549 requirementsmod.SHARED_REQUIREMENT in requirements
550 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
550 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
551 )
551 )
552 storevfs = None
552 storevfs = None
553 if shared:
553 if shared:
554 # This is a shared repo
554 # This is a shared repo
555 sharedvfs = _getsharedvfs(hgvfs, requirements)
555 sharedvfs = _getsharedvfs(hgvfs, requirements)
556 storevfs = vfsmod.vfs(sharedvfs.join(b'store'))
556 storevfs = vfsmod.vfs(sharedvfs.join(b'store'))
557 else:
557 else:
558 storevfs = vfsmod.vfs(hgvfs.join(b'store'))
558 storevfs = vfsmod.vfs(hgvfs.join(b'store'))
559
559
560 # if .hg/requires contains the sharesafe requirement, it means
560 # if .hg/requires contains the sharesafe requirement, it means
561 # there exists a `.hg/store/requires` too and we should read it
561 # there exists a `.hg/store/requires` too and we should read it
562 # NOTE: presence of SHARESAFE_REQUIREMENT imply that store requirement
562 # NOTE: presence of SHARESAFE_REQUIREMENT imply that store requirement
563 # is present. We never write SHARESAFE_REQUIREMENT for a repo if store
563 # is present. We never write SHARESAFE_REQUIREMENT for a repo if store
564 # is not present, refer checkrequirementscompat() for that
564 # is not present, refer checkrequirementscompat() for that
565 #
565 #
566 # However, if SHARESAFE_REQUIREMENT is not present, it means that the
566 # However, if SHARESAFE_REQUIREMENT is not present, it means that the
567 # repository was shared the old way. We check the share source .hg/requires
567 # repository was shared the old way. We check the share source .hg/requires
568 # for SHARESAFE_REQUIREMENT to detect whether the current repository needs
568 # for SHARESAFE_REQUIREMENT to detect whether the current repository needs
569 # to be reshared
569 # to be reshared
570 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
570 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
571
571
572 if (
572 if (
573 shared
573 shared
574 and requirementsmod.SHARESAFE_REQUIREMENT
574 and requirementsmod.SHARESAFE_REQUIREMENT
575 not in _readrequires(sharedvfs, True)
575 not in _readrequires(sharedvfs, True)
576 ):
576 ):
577 if ui.configbool(
577 if ui.configbool(
578 b'experimental', b'sharesafe-auto-downgrade-shares'
578 b'experimental', b'sharesafe-auto-downgrade-shares'
579 ):
579 ):
580 # prevent cyclic import localrepo -> upgrade -> localrepo
580 # prevent cyclic import localrepo -> upgrade -> localrepo
581 from . import upgrade
581 from . import upgrade
582
582
583 upgrade.downgrade_share_to_non_safe(
583 upgrade.downgrade_share_to_non_safe(
584 ui,
584 ui,
585 hgvfs,
585 hgvfs,
586 sharedvfs,
586 sharedvfs,
587 requirements,
587 requirements,
588 )
588 )
589 else:
589 else:
590 raise error.Abort(
590 raise error.Abort(
591 _(
591 _(
592 b"share source does not support exp-sharesafe requirement"
592 b"share source does not support exp-sharesafe requirement"
593 )
593 )
594 )
594 )
595 else:
595 else:
596 requirements |= _readrequires(storevfs, False)
596 requirements |= _readrequires(storevfs, False)
597 elif shared:
597 elif shared:
598 sourcerequires = _readrequires(sharedvfs, False)
598 sourcerequires = _readrequires(sharedvfs, False)
599 if requirementsmod.SHARESAFE_REQUIREMENT in sourcerequires:
599 if requirementsmod.SHARESAFE_REQUIREMENT in sourcerequires:
600 if ui.configbool(b'experimental', b'sharesafe-auto-upgrade-shares'):
600 if ui.configbool(b'experimental', b'sharesafe-auto-upgrade-shares'):
601 # prevent cyclic import localrepo -> upgrade -> localrepo
601 # prevent cyclic import localrepo -> upgrade -> localrepo
602 from . import upgrade
602 from . import upgrade
603
603
604 upgrade.upgrade_share_to_safe(
604 upgrade.upgrade_share_to_safe(
605 ui,
605 ui,
606 hgvfs,
606 hgvfs,
607 storevfs,
607 storevfs,
608 requirements,
608 requirements,
609 )
609 )
610 elif ui.configbool(
610 elif ui.configbool(
611 b'experimental', b'sharesafe-warn-outdated-shares'
611 b'experimental', b'sharesafe-warn-outdated-shares'
612 ):
612 ):
613 ui.warn(
613 ui.warn(
614 _(
614 _(
615 b'warning: source repository supports share-safe functionality.'
615 b'warning: source repository supports share-safe functionality.'
616 b' Reshare to upgrade.\n'
616 b' Reshare to upgrade.\n'
617 )
617 )
618 )
618 )
619
619
620 # The .hg/hgrc file may load extensions or contain config options
620 # The .hg/hgrc file may load extensions or contain config options
621 # that influence repository construction. Attempt to load it and
621 # that influence repository construction. Attempt to load it and
622 # process any new extensions that it may have pulled in.
622 # process any new extensions that it may have pulled in.
623 if loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs):
623 if loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs):
624 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
624 afterhgrcload(ui, wdirvfs, hgvfs, requirements)
625 extensions.loadall(ui)
625 extensions.loadall(ui)
626 extensions.populateui(ui)
626 extensions.populateui(ui)
627
627
628 # Set of module names of extensions loaded for this repository.
628 # Set of module names of extensions loaded for this repository.
629 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
629 extensionmodulenames = {m.__name__ for n, m in extensions.extensions(ui)}
630
630
631 supportedrequirements = gathersupportedrequirements(ui)
631 supportedrequirements = gathersupportedrequirements(ui)
632
632
633 # We first validate the requirements are known.
633 # We first validate the requirements are known.
634 ensurerequirementsrecognized(requirements, supportedrequirements)
634 ensurerequirementsrecognized(requirements, supportedrequirements)
635
635
636 # Then we validate that the known set is reasonable to use together.
636 # Then we validate that the known set is reasonable to use together.
637 ensurerequirementscompatible(ui, requirements)
637 ensurerequirementscompatible(ui, requirements)
638
638
639 # TODO there are unhandled edge cases related to opening repositories with
639 # TODO there are unhandled edge cases related to opening repositories with
640 # shared storage. If storage is shared, we should also test for requirements
640 # shared storage. If storage is shared, we should also test for requirements
641 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
641 # compatibility in the pointed-to repo. This entails loading the .hg/hgrc in
642 # that repo, as that repo may load extensions needed to open it. This is a
642 # that repo, as that repo may load extensions needed to open it. This is a
643 # bit complicated because we don't want the other hgrc to overwrite settings
643 # bit complicated because we don't want the other hgrc to overwrite settings
644 # in this hgrc.
644 # in this hgrc.
645 #
645 #
646 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
646 # This bug is somewhat mitigated by the fact that we copy the .hg/requires
647 # file when sharing repos. But if a requirement is added after the share is
647 # file when sharing repos. But if a requirement is added after the share is
648 # performed, thereby introducing a new requirement for the opener, we may
648 # performed, thereby introducing a new requirement for the opener, we may
649 # will not see that and could encounter a run-time error interacting with
649 # will not see that and could encounter a run-time error interacting with
650 # that shared store since it has an unknown-to-us requirement.
650 # that shared store since it has an unknown-to-us requirement.
651
651
652 # At this point, we know we should be capable of opening the repository.
652 # At this point, we know we should be capable of opening the repository.
653 # Now get on with doing that.
653 # Now get on with doing that.
654
654
655 features = set()
655 features = set()
656
656
657 # The "store" part of the repository holds versioned data. How it is
657 # The "store" part of the repository holds versioned data. How it is
658 # accessed is determined by various requirements. If `shared` or
658 # accessed is determined by various requirements. If `shared` or
659 # `relshared` requirements are present, this indicates current repository
659 # `relshared` requirements are present, this indicates current repository
660 # is a share and store exists in path mentioned in `.hg/sharedpath`
660 # is a share and store exists in path mentioned in `.hg/sharedpath`
661 if shared:
661 if shared:
662 storebasepath = sharedvfs.base
662 storebasepath = sharedvfs.base
663 cachepath = sharedvfs.join(b'cache')
663 cachepath = sharedvfs.join(b'cache')
664 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
664 features.add(repository.REPO_FEATURE_SHARED_STORAGE)
665 else:
665 else:
666 storebasepath = hgvfs.base
666 storebasepath = hgvfs.base
667 cachepath = hgvfs.join(b'cache')
667 cachepath = hgvfs.join(b'cache')
668 wcachepath = hgvfs.join(b'wcache')
668 wcachepath = hgvfs.join(b'wcache')
669
669
670 # The store has changed over time and the exact layout is dictated by
670 # The store has changed over time and the exact layout is dictated by
671 # requirements. The store interface abstracts differences across all
671 # requirements. The store interface abstracts differences across all
672 # of them.
672 # of them.
673 store = makestore(
673 store = makestore(
674 requirements,
674 requirements,
675 storebasepath,
675 storebasepath,
676 lambda base: vfsmod.vfs(base, cacheaudited=True),
676 lambda base: vfsmod.vfs(base, cacheaudited=True),
677 )
677 )
678 hgvfs.createmode = store.createmode
678 hgvfs.createmode = store.createmode
679
679
680 storevfs = store.vfs
680 storevfs = store.vfs
681 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
681 storevfs.options = resolvestorevfsoptions(ui, requirements, features)
682
682
683 # The cache vfs is used to manage cache files.
683 # The cache vfs is used to manage cache files.
684 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
684 cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
685 cachevfs.createmode = store.createmode
685 cachevfs.createmode = store.createmode
686 # The cache vfs is used to manage cache files related to the working copy
686 # The cache vfs is used to manage cache files related to the working copy
687 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
687 wcachevfs = vfsmod.vfs(wcachepath, cacheaudited=True)
688 wcachevfs.createmode = store.createmode
688 wcachevfs.createmode = store.createmode
689
689
690 # Now resolve the type for the repository object. We do this by repeatedly
690 # Now resolve the type for the repository object. We do this by repeatedly
691 # calling a factory function to produces types for specific aspects of the
691 # calling a factory function to produces types for specific aspects of the
692 # repo's operation. The aggregate returned types are used as base classes
692 # repo's operation. The aggregate returned types are used as base classes
693 # for a dynamically-derived type, which will represent our new repository.
693 # for a dynamically-derived type, which will represent our new repository.
694
694
695 bases = []
695 bases = []
696 extrastate = {}
696 extrastate = {}
697
697
698 for iface, fn in REPO_INTERFACES:
698 for iface, fn in REPO_INTERFACES:
699 # We pass all potentially useful state to give extensions tons of
699 # We pass all potentially useful state to give extensions tons of
700 # flexibility.
700 # flexibility.
701 typ = fn()(
701 typ = fn()(
702 ui=ui,
702 ui=ui,
703 intents=intents,
703 intents=intents,
704 requirements=requirements,
704 requirements=requirements,
705 features=features,
705 features=features,
706 wdirvfs=wdirvfs,
706 wdirvfs=wdirvfs,
707 hgvfs=hgvfs,
707 hgvfs=hgvfs,
708 store=store,
708 store=store,
709 storevfs=storevfs,
709 storevfs=storevfs,
710 storeoptions=storevfs.options,
710 storeoptions=storevfs.options,
711 cachevfs=cachevfs,
711 cachevfs=cachevfs,
712 wcachevfs=wcachevfs,
712 wcachevfs=wcachevfs,
713 extensionmodulenames=extensionmodulenames,
713 extensionmodulenames=extensionmodulenames,
714 extrastate=extrastate,
714 extrastate=extrastate,
715 baseclasses=bases,
715 baseclasses=bases,
716 )
716 )
717
717
718 if not isinstance(typ, type):
718 if not isinstance(typ, type):
719 raise error.ProgrammingError(
719 raise error.ProgrammingError(
720 b'unable to construct type for %s' % iface
720 b'unable to construct type for %s' % iface
721 )
721 )
722
722
723 bases.append(typ)
723 bases.append(typ)
724
724
725 # type() allows you to use characters in type names that wouldn't be
725 # type() allows you to use characters in type names that wouldn't be
726 # recognized as Python symbols in source code. We abuse that to add
726 # recognized as Python symbols in source code. We abuse that to add
727 # rich information about our constructed repo.
727 # rich information about our constructed repo.
728 name = pycompat.sysstr(
728 name = pycompat.sysstr(
729 b'derivedrepo:%s<%s>' % (wdirvfs.base, b','.join(sorted(requirements)))
729 b'derivedrepo:%s<%s>' % (wdirvfs.base, b','.join(sorted(requirements)))
730 )
730 )
731
731
732 cls = type(name, tuple(bases), {})
732 cls = type(name, tuple(bases), {})
733
733
734 return cls(
734 return cls(
735 baseui=baseui,
735 baseui=baseui,
736 ui=ui,
736 ui=ui,
737 origroot=path,
737 origroot=path,
738 wdirvfs=wdirvfs,
738 wdirvfs=wdirvfs,
739 hgvfs=hgvfs,
739 hgvfs=hgvfs,
740 requirements=requirements,
740 requirements=requirements,
741 supportedrequirements=supportedrequirements,
741 supportedrequirements=supportedrequirements,
742 sharedpath=storebasepath,
742 sharedpath=storebasepath,
743 store=store,
743 store=store,
744 cachevfs=cachevfs,
744 cachevfs=cachevfs,
745 wcachevfs=wcachevfs,
745 wcachevfs=wcachevfs,
746 features=features,
746 features=features,
747 intents=intents,
747 intents=intents,
748 )
748 )
749
749
750
750
751 def loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs=None):
751 def loadhgrc(ui, wdirvfs, hgvfs, requirements, sharedvfs=None):
752 """Load hgrc files/content into a ui instance.
752 """Load hgrc files/content into a ui instance.
753
753
754 This is called during repository opening to load any additional
754 This is called during repository opening to load any additional
755 config files or settings relevant to the current repository.
755 config files or settings relevant to the current repository.
756
756
757 Returns a bool indicating whether any additional configs were loaded.
757 Returns a bool indicating whether any additional configs were loaded.
758
758
759 Extensions should monkeypatch this function to modify how per-repo
759 Extensions should monkeypatch this function to modify how per-repo
760 configs are loaded. For example, an extension may wish to pull in
760 configs are loaded. For example, an extension may wish to pull in
761 configs from alternate files or sources.
761 configs from alternate files or sources.
762
762
763 sharedvfs is vfs object pointing to source repo if the current one is a
763 sharedvfs is vfs object pointing to source repo if the current one is a
764 shared one
764 shared one
765 """
765 """
766 if not rcutil.use_repo_hgrc():
766 if not rcutil.use_repo_hgrc():
767 return False
767 return False
768
768
769 ret = False
769 ret = False
770 # first load config from shared source if we has to
770 # first load config from shared source if we has to
771 if requirementsmod.SHARESAFE_REQUIREMENT in requirements and sharedvfs:
771 if requirementsmod.SHARESAFE_REQUIREMENT in requirements and sharedvfs:
772 try:
772 try:
773 ui.readconfig(sharedvfs.join(b'hgrc'), root=sharedvfs.base)
773 ui.readconfig(sharedvfs.join(b'hgrc'), root=sharedvfs.base)
774 ret = True
774 ret = True
775 except IOError:
775 except IOError:
776 pass
776 pass
777
777
778 try:
778 try:
779 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
779 ui.readconfig(hgvfs.join(b'hgrc'), root=wdirvfs.base)
780 ret = True
780 ret = True
781 except IOError:
781 except IOError:
782 pass
782 pass
783
783
784 try:
784 try:
785 ui.readconfig(hgvfs.join(b'hgrc-not-shared'), root=wdirvfs.base)
785 ui.readconfig(hgvfs.join(b'hgrc-not-shared'), root=wdirvfs.base)
786 ret = True
786 ret = True
787 except IOError:
787 except IOError:
788 pass
788 pass
789
789
790 return ret
790 return ret
791
791
792
792
793 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
793 def afterhgrcload(ui, wdirvfs, hgvfs, requirements):
794 """Perform additional actions after .hg/hgrc is loaded.
794 """Perform additional actions after .hg/hgrc is loaded.
795
795
796 This function is called during repository loading immediately after
796 This function is called during repository loading immediately after
797 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
797 the .hg/hgrc file is loaded and before per-repo extensions are loaded.
798
798
799 The function can be used to validate configs, automatically add
799 The function can be used to validate configs, automatically add
800 options (including extensions) based on requirements, etc.
800 options (including extensions) based on requirements, etc.
801 """
801 """
802
802
803 # Map of requirements to list of extensions to load automatically when
803 # Map of requirements to list of extensions to load automatically when
804 # requirement is present.
804 # requirement is present.
805 autoextensions = {
805 autoextensions = {
806 b'git': [b'git'],
806 b'git': [b'git'],
807 b'largefiles': [b'largefiles'],
807 b'largefiles': [b'largefiles'],
808 b'lfs': [b'lfs'],
808 b'lfs': [b'lfs'],
809 }
809 }
810
810
811 for requirement, names in sorted(autoextensions.items()):
811 for requirement, names in sorted(autoextensions.items()):
812 if requirement not in requirements:
812 if requirement not in requirements:
813 continue
813 continue
814
814
815 for name in names:
815 for name in names:
816 if not ui.hasconfig(b'extensions', name):
816 if not ui.hasconfig(b'extensions', name):
817 ui.setconfig(b'extensions', name, b'', source=b'autoload')
817 ui.setconfig(b'extensions', name, b'', source=b'autoload')
818
818
819
819
820 def gathersupportedrequirements(ui):
820 def gathersupportedrequirements(ui):
821 """Determine the complete set of recognized requirements."""
821 """Determine the complete set of recognized requirements."""
822 # Start with all requirements supported by this file.
822 # Start with all requirements supported by this file.
823 supported = set(localrepository._basesupported)
823 supported = set(localrepository._basesupported)
824
824
825 # Execute ``featuresetupfuncs`` entries if they belong to an extension
825 # Execute ``featuresetupfuncs`` entries if they belong to an extension
826 # relevant to this ui instance.
826 # relevant to this ui instance.
827 modules = {m.__name__ for n, m in extensions.extensions(ui)}
827 modules = {m.__name__ for n, m in extensions.extensions(ui)}
828
828
829 for fn in featuresetupfuncs:
829 for fn in featuresetupfuncs:
830 if fn.__module__ in modules:
830 if fn.__module__ in modules:
831 fn(ui, supported)
831 fn(ui, supported)
832
832
833 # Add derived requirements from registered compression engines.
833 # Add derived requirements from registered compression engines.
834 for name in util.compengines:
834 for name in util.compengines:
835 engine = util.compengines[name]
835 engine = util.compengines[name]
836 if engine.available() and engine.revlogheader():
836 if engine.available() and engine.revlogheader():
837 supported.add(b'exp-compression-%s' % name)
837 supported.add(b'exp-compression-%s' % name)
838 if engine.name() == b'zstd':
838 if engine.name() == b'zstd':
839 supported.add(b'revlog-compression-zstd')
839 supported.add(b'revlog-compression-zstd')
840
840
841 return supported
841 return supported
842
842
843
843
844 def ensurerequirementsrecognized(requirements, supported):
844 def ensurerequirementsrecognized(requirements, supported):
845 """Validate that a set of local requirements is recognized.
845 """Validate that a set of local requirements is recognized.
846
846
847 Receives a set of requirements. Raises an ``error.RepoError`` if there
847 Receives a set of requirements. Raises an ``error.RepoError`` if there
848 exists any requirement in that set that currently loaded code doesn't
848 exists any requirement in that set that currently loaded code doesn't
849 recognize.
849 recognize.
850
850
851 Returns a set of supported requirements.
851 Returns a set of supported requirements.
852 """
852 """
853 missing = set()
853 missing = set()
854
854
855 for requirement in requirements:
855 for requirement in requirements:
856 if requirement in supported:
856 if requirement in supported:
857 continue
857 continue
858
858
859 if not requirement or not requirement[0:1].isalnum():
859 if not requirement or not requirement[0:1].isalnum():
860 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
860 raise error.RequirementError(_(b'.hg/requires file is corrupt'))
861
861
862 missing.add(requirement)
862 missing.add(requirement)
863
863
864 if missing:
864 if missing:
865 raise error.RequirementError(
865 raise error.RequirementError(
866 _(b'repository requires features unknown to this Mercurial: %s')
866 _(b'repository requires features unknown to this Mercurial: %s')
867 % b' '.join(sorted(missing)),
867 % b' '.join(sorted(missing)),
868 hint=_(
868 hint=_(
869 b'see https://mercurial-scm.org/wiki/MissingRequirement '
869 b'see https://mercurial-scm.org/wiki/MissingRequirement '
870 b'for more information'
870 b'for more information'
871 ),
871 ),
872 )
872 )
873
873
874
874
875 def ensurerequirementscompatible(ui, requirements):
875 def ensurerequirementscompatible(ui, requirements):
876 """Validates that a set of recognized requirements is mutually compatible.
876 """Validates that a set of recognized requirements is mutually compatible.
877
877
878 Some requirements may not be compatible with others or require
878 Some requirements may not be compatible with others or require
879 config options that aren't enabled. This function is called during
879 config options that aren't enabled. This function is called during
880 repository opening to ensure that the set of requirements needed
880 repository opening to ensure that the set of requirements needed
881 to open a repository is sane and compatible with config options.
881 to open a repository is sane and compatible with config options.
882
882
883 Extensions can monkeypatch this function to perform additional
883 Extensions can monkeypatch this function to perform additional
884 checking.
884 checking.
885
885
886 ``error.RepoError`` should be raised on failure.
886 ``error.RepoError`` should be raised on failure.
887 """
887 """
888 if (
888 if (
889 requirementsmod.SPARSE_REQUIREMENT in requirements
889 requirementsmod.SPARSE_REQUIREMENT in requirements
890 and not sparse.enabled
890 and not sparse.enabled
891 ):
891 ):
892 raise error.RepoError(
892 raise error.RepoError(
893 _(
893 _(
894 b'repository is using sparse feature but '
894 b'repository is using sparse feature but '
895 b'sparse is not enabled; enable the '
895 b'sparse is not enabled; enable the '
896 b'"sparse" extensions to access'
896 b'"sparse" extensions to access'
897 )
897 )
898 )
898 )
899
899
900
900
901 def makestore(requirements, path, vfstype):
901 def makestore(requirements, path, vfstype):
902 """Construct a storage object for a repository."""
902 """Construct a storage object for a repository."""
903 if b'store' in requirements:
903 if b'store' in requirements:
904 if b'fncache' in requirements:
904 if b'fncache' in requirements:
905 return storemod.fncachestore(
905 return storemod.fncachestore(
906 path, vfstype, b'dotencode' in requirements
906 path, vfstype, b'dotencode' in requirements
907 )
907 )
908
908
909 return storemod.encodedstore(path, vfstype)
909 return storemod.encodedstore(path, vfstype)
910
910
911 return storemod.basicstore(path, vfstype)
911 return storemod.basicstore(path, vfstype)
912
912
913
913
914 def resolvestorevfsoptions(ui, requirements, features):
914 def resolvestorevfsoptions(ui, requirements, features):
915 """Resolve the options to pass to the store vfs opener.
915 """Resolve the options to pass to the store vfs opener.
916
916
917 The returned dict is used to influence behavior of the storage layer.
917 The returned dict is used to influence behavior of the storage layer.
918 """
918 """
919 options = {}
919 options = {}
920
920
921 if requirementsmod.TREEMANIFEST_REQUIREMENT in requirements:
921 if requirementsmod.TREEMANIFEST_REQUIREMENT in requirements:
922 options[b'treemanifest'] = True
922 options[b'treemanifest'] = True
923
923
924 # experimental config: format.manifestcachesize
924 # experimental config: format.manifestcachesize
925 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
925 manifestcachesize = ui.configint(b'format', b'manifestcachesize')
926 if manifestcachesize is not None:
926 if manifestcachesize is not None:
927 options[b'manifestcachesize'] = manifestcachesize
927 options[b'manifestcachesize'] = manifestcachesize
928
928
929 # In the absence of another requirement superseding a revlog-related
929 # In the absence of another requirement superseding a revlog-related
930 # requirement, we have to assume the repo is using revlog version 0.
930 # requirement, we have to assume the repo is using revlog version 0.
931 # This revlog format is super old and we don't bother trying to parse
931 # This revlog format is super old and we don't bother trying to parse
932 # opener options for it because those options wouldn't do anything
932 # opener options for it because those options wouldn't do anything
933 # meaningful on such old repos.
933 # meaningful on such old repos.
934 if (
934 if (
935 b'revlogv1' in requirements
935 b'revlogv1' in requirements
936 or requirementsmod.REVLOGV2_REQUIREMENT in requirements
936 or requirementsmod.REVLOGV2_REQUIREMENT in requirements
937 ):
937 ):
938 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
938 options.update(resolverevlogstorevfsoptions(ui, requirements, features))
939 else: # explicitly mark repo as using revlogv0
939 else: # explicitly mark repo as using revlogv0
940 options[b'revlogv0'] = True
940 options[b'revlogv0'] = True
941
941
942 if requirementsmod.COPIESSDC_REQUIREMENT in requirements:
942 if requirementsmod.COPIESSDC_REQUIREMENT in requirements:
943 options[b'copies-storage'] = b'changeset-sidedata'
943 options[b'copies-storage'] = b'changeset-sidedata'
944 else:
944 else:
945 writecopiesto = ui.config(b'experimental', b'copies.write-to')
945 writecopiesto = ui.config(b'experimental', b'copies.write-to')
946 copiesextramode = (b'changeset-only', b'compatibility')
946 copiesextramode = (b'changeset-only', b'compatibility')
947 if writecopiesto in copiesextramode:
947 if writecopiesto in copiesextramode:
948 options[b'copies-storage'] = b'extra'
948 options[b'copies-storage'] = b'extra'
949
949
950 return options
950 return options
951
951
952
952
953 def resolverevlogstorevfsoptions(ui, requirements, features):
953 def resolverevlogstorevfsoptions(ui, requirements, features):
954 """Resolve opener options specific to revlogs."""
954 """Resolve opener options specific to revlogs."""
955
955
956 options = {}
956 options = {}
957 options[b'flagprocessors'] = {}
957 options[b'flagprocessors'] = {}
958
958
959 if b'revlogv1' in requirements:
959 if b'revlogv1' in requirements:
960 options[b'revlogv1'] = True
960 options[b'revlogv1'] = True
961 if requirementsmod.REVLOGV2_REQUIREMENT in requirements:
961 if requirementsmod.REVLOGV2_REQUIREMENT in requirements:
962 options[b'revlogv2'] = True
962 options[b'revlogv2'] = True
963
963
964 if b'generaldelta' in requirements:
964 if b'generaldelta' in requirements:
965 options[b'generaldelta'] = True
965 options[b'generaldelta'] = True
966
966
967 # experimental config: format.chunkcachesize
967 # experimental config: format.chunkcachesize
968 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
968 chunkcachesize = ui.configint(b'format', b'chunkcachesize')
969 if chunkcachesize is not None:
969 if chunkcachesize is not None:
970 options[b'chunkcachesize'] = chunkcachesize
970 options[b'chunkcachesize'] = chunkcachesize
971
971
972 deltabothparents = ui.configbool(
972 deltabothparents = ui.configbool(
973 b'storage', b'revlog.optimize-delta-parent-choice'
973 b'storage', b'revlog.optimize-delta-parent-choice'
974 )
974 )
975 options[b'deltabothparents'] = deltabothparents
975 options[b'deltabothparents'] = deltabothparents
976
976
977 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
977 lazydelta = ui.configbool(b'storage', b'revlog.reuse-external-delta')
978 lazydeltabase = False
978 lazydeltabase = False
979 if lazydelta:
979 if lazydelta:
980 lazydeltabase = ui.configbool(
980 lazydeltabase = ui.configbool(
981 b'storage', b'revlog.reuse-external-delta-parent'
981 b'storage', b'revlog.reuse-external-delta-parent'
982 )
982 )
983 if lazydeltabase is None:
983 if lazydeltabase is None:
984 lazydeltabase = not scmutil.gddeltaconfig(ui)
984 lazydeltabase = not scmutil.gddeltaconfig(ui)
985 options[b'lazydelta'] = lazydelta
985 options[b'lazydelta'] = lazydelta
986 options[b'lazydeltabase'] = lazydeltabase
986 options[b'lazydeltabase'] = lazydeltabase
987
987
988 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
988 chainspan = ui.configbytes(b'experimental', b'maxdeltachainspan')
989 if 0 <= chainspan:
989 if 0 <= chainspan:
990 options[b'maxdeltachainspan'] = chainspan
990 options[b'maxdeltachainspan'] = chainspan
991
991
992 mmapindexthreshold = ui.configbytes(b'experimental', b'mmapindexthreshold')
992 mmapindexthreshold = ui.configbytes(b'experimental', b'mmapindexthreshold')
993 if mmapindexthreshold is not None:
993 if mmapindexthreshold is not None:
994 options[b'mmapindexthreshold'] = mmapindexthreshold
994 options[b'mmapindexthreshold'] = mmapindexthreshold
995
995
996 withsparseread = ui.configbool(b'experimental', b'sparse-read')
996 withsparseread = ui.configbool(b'experimental', b'sparse-read')
997 srdensitythres = float(
997 srdensitythres = float(
998 ui.config(b'experimental', b'sparse-read.density-threshold')
998 ui.config(b'experimental', b'sparse-read.density-threshold')
999 )
999 )
1000 srmingapsize = ui.configbytes(b'experimental', b'sparse-read.min-gap-size')
1000 srmingapsize = ui.configbytes(b'experimental', b'sparse-read.min-gap-size')
1001 options[b'with-sparse-read'] = withsparseread
1001 options[b'with-sparse-read'] = withsparseread
1002 options[b'sparse-read-density-threshold'] = srdensitythres
1002 options[b'sparse-read-density-threshold'] = srdensitythres
1003 options[b'sparse-read-min-gap-size'] = srmingapsize
1003 options[b'sparse-read-min-gap-size'] = srmingapsize
1004
1004
1005 sparserevlog = requirementsmod.SPARSEREVLOG_REQUIREMENT in requirements
1005 sparserevlog = requirementsmod.SPARSEREVLOG_REQUIREMENT in requirements
1006 options[b'sparse-revlog'] = sparserevlog
1006 options[b'sparse-revlog'] = sparserevlog
1007 if sparserevlog:
1007 if sparserevlog:
1008 options[b'generaldelta'] = True
1008 options[b'generaldelta'] = True
1009
1009
1010 sidedata = requirementsmod.SIDEDATA_REQUIREMENT in requirements
1010 sidedata = requirementsmod.SIDEDATA_REQUIREMENT in requirements
1011 options[b'side-data'] = sidedata
1011 options[b'side-data'] = sidedata
1012
1012
1013 maxchainlen = None
1013 maxchainlen = None
1014 if sparserevlog:
1014 if sparserevlog:
1015 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
1015 maxchainlen = revlogconst.SPARSE_REVLOG_MAX_CHAIN_LENGTH
1016 # experimental config: format.maxchainlen
1016 # experimental config: format.maxchainlen
1017 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
1017 maxchainlen = ui.configint(b'format', b'maxchainlen', maxchainlen)
1018 if maxchainlen is not None:
1018 if maxchainlen is not None:
1019 options[b'maxchainlen'] = maxchainlen
1019 options[b'maxchainlen'] = maxchainlen
1020
1020
1021 for r in requirements:
1021 for r in requirements:
1022 # we allow multiple compression engine requirement to co-exist because
1022 # we allow multiple compression engine requirement to co-exist because
1023 # strickly speaking, revlog seems to support mixed compression style.
1023 # strickly speaking, revlog seems to support mixed compression style.
1024 #
1024 #
1025 # The compression used for new entries will be "the last one"
1025 # The compression used for new entries will be "the last one"
1026 prefix = r.startswith
1026 prefix = r.startswith
1027 if prefix(b'revlog-compression-') or prefix(b'exp-compression-'):
1027 if prefix(b'revlog-compression-') or prefix(b'exp-compression-'):
1028 options[b'compengine'] = r.split(b'-', 2)[2]
1028 options[b'compengine'] = r.split(b'-', 2)[2]
1029
1029
1030 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
1030 options[b'zlib.level'] = ui.configint(b'storage', b'revlog.zlib.level')
1031 if options[b'zlib.level'] is not None:
1031 if options[b'zlib.level'] is not None:
1032 if not (0 <= options[b'zlib.level'] <= 9):
1032 if not (0 <= options[b'zlib.level'] <= 9):
1033 msg = _(b'invalid value for `storage.revlog.zlib.level` config: %d')
1033 msg = _(b'invalid value for `storage.revlog.zlib.level` config: %d')
1034 raise error.Abort(msg % options[b'zlib.level'])
1034 raise error.Abort(msg % options[b'zlib.level'])
1035 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
1035 options[b'zstd.level'] = ui.configint(b'storage', b'revlog.zstd.level')
1036 if options[b'zstd.level'] is not None:
1036 if options[b'zstd.level'] is not None:
1037 if not (0 <= options[b'zstd.level'] <= 22):
1037 if not (0 <= options[b'zstd.level'] <= 22):
1038 msg = _(b'invalid value for `storage.revlog.zstd.level` config: %d')
1038 msg = _(b'invalid value for `storage.revlog.zstd.level` config: %d')
1039 raise error.Abort(msg % options[b'zstd.level'])
1039 raise error.Abort(msg % options[b'zstd.level'])
1040
1040
1041 if requirementsmod.NARROW_REQUIREMENT in requirements:
1041 if requirementsmod.NARROW_REQUIREMENT in requirements:
1042 options[b'enableellipsis'] = True
1042 options[b'enableellipsis'] = True
1043
1043
1044 if ui.configbool(b'experimental', b'rust.index'):
1044 if ui.configbool(b'experimental', b'rust.index'):
1045 options[b'rust.index'] = True
1045 options[b'rust.index'] = True
1046 if requirementsmod.NODEMAP_REQUIREMENT in requirements:
1046 if requirementsmod.NODEMAP_REQUIREMENT in requirements:
1047 slow_path = ui.config(
1048 b'storage', b'revlog.persistent-nodemap.slow-path'
1049 )
1050 if slow_path not in (b'allow'):
1051 default = ui.config_default(
1052 b'storage', b'revlog.persistent-nodemap.slow-path'
1053 )
1054 msg = _(
1055 b'unknown value for config '
1056 b'"storage.revlog.persistent-nodemap.slow-path": "%s"\n'
1057 )
1058 ui.warn(msg % slow_path)
1059 if not ui.quiet:
1060 ui.warn(_(b'falling back to default value: %s\n') % default)
1061 slow_path = default
1047 options[b'persistent-nodemap'] = True
1062 options[b'persistent-nodemap'] = True
1048 if ui.configbool(b'storage', b'revlog.persistent-nodemap.mmap'):
1063 if ui.configbool(b'storage', b'revlog.persistent-nodemap.mmap'):
1049 options[b'persistent-nodemap.mmap'] = True
1064 options[b'persistent-nodemap.mmap'] = True
1050 epnm = ui.config(b'storage', b'revlog.nodemap.mode')
1065 epnm = ui.config(b'storage', b'revlog.nodemap.mode')
1051 options[b'persistent-nodemap.mode'] = epnm
1066 options[b'persistent-nodemap.mode'] = epnm
1052 if ui.configbool(b'devel', b'persistent-nodemap'):
1067 if ui.configbool(b'devel', b'persistent-nodemap'):
1053 options[b'devel-force-nodemap'] = True
1068 options[b'devel-force-nodemap'] = True
1054
1069
1055 return options
1070 return options
1056
1071
1057
1072
1058 def makemain(**kwargs):
1073 def makemain(**kwargs):
1059 """Produce a type conforming to ``ilocalrepositorymain``."""
1074 """Produce a type conforming to ``ilocalrepositorymain``."""
1060 return localrepository
1075 return localrepository
1061
1076
1062
1077
1063 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1078 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1064 class revlogfilestorage(object):
1079 class revlogfilestorage(object):
1065 """File storage when using revlogs."""
1080 """File storage when using revlogs."""
1066
1081
1067 def file(self, path):
1082 def file(self, path):
1068 if path[0] == b'/':
1083 if path[0] == b'/':
1069 path = path[1:]
1084 path = path[1:]
1070
1085
1071 return filelog.filelog(self.svfs, path)
1086 return filelog.filelog(self.svfs, path)
1072
1087
1073
1088
1074 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1089 @interfaceutil.implementer(repository.ilocalrepositoryfilestorage)
1075 class revlognarrowfilestorage(object):
1090 class revlognarrowfilestorage(object):
1076 """File storage when using revlogs and narrow files."""
1091 """File storage when using revlogs and narrow files."""
1077
1092
1078 def file(self, path):
1093 def file(self, path):
1079 if path[0] == b'/':
1094 if path[0] == b'/':
1080 path = path[1:]
1095 path = path[1:]
1081
1096
1082 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
1097 return filelog.narrowfilelog(self.svfs, path, self._storenarrowmatch)
1083
1098
1084
1099
1085 def makefilestorage(requirements, features, **kwargs):
1100 def makefilestorage(requirements, features, **kwargs):
1086 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
1101 """Produce a type conforming to ``ilocalrepositoryfilestorage``."""
1087 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
1102 features.add(repository.REPO_FEATURE_REVLOG_FILE_STORAGE)
1088 features.add(repository.REPO_FEATURE_STREAM_CLONE)
1103 features.add(repository.REPO_FEATURE_STREAM_CLONE)
1089
1104
1090 if requirementsmod.NARROW_REQUIREMENT in requirements:
1105 if requirementsmod.NARROW_REQUIREMENT in requirements:
1091 return revlognarrowfilestorage
1106 return revlognarrowfilestorage
1092 else:
1107 else:
1093 return revlogfilestorage
1108 return revlogfilestorage
1094
1109
1095
1110
1096 # List of repository interfaces and factory functions for them. Each
1111 # List of repository interfaces and factory functions for them. Each
1097 # will be called in order during ``makelocalrepository()`` to iteratively
1112 # will be called in order during ``makelocalrepository()`` to iteratively
1098 # derive the final type for a local repository instance. We capture the
1113 # derive the final type for a local repository instance. We capture the
1099 # function as a lambda so we don't hold a reference and the module-level
1114 # function as a lambda so we don't hold a reference and the module-level
1100 # functions can be wrapped.
1115 # functions can be wrapped.
1101 REPO_INTERFACES = [
1116 REPO_INTERFACES = [
1102 (repository.ilocalrepositorymain, lambda: makemain),
1117 (repository.ilocalrepositorymain, lambda: makemain),
1103 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
1118 (repository.ilocalrepositoryfilestorage, lambda: makefilestorage),
1104 ]
1119 ]
1105
1120
1106
1121
1107 @interfaceutil.implementer(repository.ilocalrepositorymain)
1122 @interfaceutil.implementer(repository.ilocalrepositorymain)
1108 class localrepository(object):
1123 class localrepository(object):
1109 """Main class for representing local repositories.
1124 """Main class for representing local repositories.
1110
1125
1111 All local repositories are instances of this class.
1126 All local repositories are instances of this class.
1112
1127
1113 Constructed on its own, instances of this class are not usable as
1128 Constructed on its own, instances of this class are not usable as
1114 repository objects. To obtain a usable repository object, call
1129 repository objects. To obtain a usable repository object, call
1115 ``hg.repository()``, ``localrepo.instance()``, or
1130 ``hg.repository()``, ``localrepo.instance()``, or
1116 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
1131 ``localrepo.makelocalrepository()``. The latter is the lowest-level.
1117 ``instance()`` adds support for creating new repositories.
1132 ``instance()`` adds support for creating new repositories.
1118 ``hg.repository()`` adds more extension integration, including calling
1133 ``hg.repository()`` adds more extension integration, including calling
1119 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
1134 ``reposetup()``. Generally speaking, ``hg.repository()`` should be
1120 used.
1135 used.
1121 """
1136 """
1122
1137
1123 # obsolete experimental requirements:
1138 # obsolete experimental requirements:
1124 # - manifestv2: An experimental new manifest format that allowed
1139 # - manifestv2: An experimental new manifest format that allowed
1125 # for stem compression of long paths. Experiment ended up not
1140 # for stem compression of long paths. Experiment ended up not
1126 # being successful (repository sizes went up due to worse delta
1141 # being successful (repository sizes went up due to worse delta
1127 # chains), and the code was deleted in 4.6.
1142 # chains), and the code was deleted in 4.6.
1128 supportedformats = {
1143 supportedformats = {
1129 b'revlogv1',
1144 b'revlogv1',
1130 b'generaldelta',
1145 b'generaldelta',
1131 requirementsmod.TREEMANIFEST_REQUIREMENT,
1146 requirementsmod.TREEMANIFEST_REQUIREMENT,
1132 requirementsmod.COPIESSDC_REQUIREMENT,
1147 requirementsmod.COPIESSDC_REQUIREMENT,
1133 requirementsmod.REVLOGV2_REQUIREMENT,
1148 requirementsmod.REVLOGV2_REQUIREMENT,
1134 requirementsmod.SIDEDATA_REQUIREMENT,
1149 requirementsmod.SIDEDATA_REQUIREMENT,
1135 requirementsmod.SPARSEREVLOG_REQUIREMENT,
1150 requirementsmod.SPARSEREVLOG_REQUIREMENT,
1136 requirementsmod.NODEMAP_REQUIREMENT,
1151 requirementsmod.NODEMAP_REQUIREMENT,
1137 bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT,
1152 bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT,
1138 requirementsmod.SHARESAFE_REQUIREMENT,
1153 requirementsmod.SHARESAFE_REQUIREMENT,
1139 }
1154 }
1140 _basesupported = supportedformats | {
1155 _basesupported = supportedformats | {
1141 b'store',
1156 b'store',
1142 b'fncache',
1157 b'fncache',
1143 requirementsmod.SHARED_REQUIREMENT,
1158 requirementsmod.SHARED_REQUIREMENT,
1144 requirementsmod.RELATIVE_SHARED_REQUIREMENT,
1159 requirementsmod.RELATIVE_SHARED_REQUIREMENT,
1145 b'dotencode',
1160 b'dotencode',
1146 requirementsmod.SPARSE_REQUIREMENT,
1161 requirementsmod.SPARSE_REQUIREMENT,
1147 requirementsmod.INTERNAL_PHASE_REQUIREMENT,
1162 requirementsmod.INTERNAL_PHASE_REQUIREMENT,
1148 }
1163 }
1149
1164
1150 # list of prefix for file which can be written without 'wlock'
1165 # list of prefix for file which can be written without 'wlock'
1151 # Extensions should extend this list when needed
1166 # Extensions should extend this list when needed
1152 _wlockfreeprefix = {
1167 _wlockfreeprefix = {
1153 # We migh consider requiring 'wlock' for the next
1168 # We migh consider requiring 'wlock' for the next
1154 # two, but pretty much all the existing code assume
1169 # two, but pretty much all the existing code assume
1155 # wlock is not needed so we keep them excluded for
1170 # wlock is not needed so we keep them excluded for
1156 # now.
1171 # now.
1157 b'hgrc',
1172 b'hgrc',
1158 b'requires',
1173 b'requires',
1159 # XXX cache is a complicatged business someone
1174 # XXX cache is a complicatged business someone
1160 # should investigate this in depth at some point
1175 # should investigate this in depth at some point
1161 b'cache/',
1176 b'cache/',
1162 # XXX shouldn't be dirstate covered by the wlock?
1177 # XXX shouldn't be dirstate covered by the wlock?
1163 b'dirstate',
1178 b'dirstate',
1164 # XXX bisect was still a bit too messy at the time
1179 # XXX bisect was still a bit too messy at the time
1165 # this changeset was introduced. Someone should fix
1180 # this changeset was introduced. Someone should fix
1166 # the remainig bit and drop this line
1181 # the remainig bit and drop this line
1167 b'bisect.state',
1182 b'bisect.state',
1168 }
1183 }
1169
1184
1170 def __init__(
1185 def __init__(
1171 self,
1186 self,
1172 baseui,
1187 baseui,
1173 ui,
1188 ui,
1174 origroot,
1189 origroot,
1175 wdirvfs,
1190 wdirvfs,
1176 hgvfs,
1191 hgvfs,
1177 requirements,
1192 requirements,
1178 supportedrequirements,
1193 supportedrequirements,
1179 sharedpath,
1194 sharedpath,
1180 store,
1195 store,
1181 cachevfs,
1196 cachevfs,
1182 wcachevfs,
1197 wcachevfs,
1183 features,
1198 features,
1184 intents=None,
1199 intents=None,
1185 ):
1200 ):
1186 """Create a new local repository instance.
1201 """Create a new local repository instance.
1187
1202
1188 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
1203 Most callers should use ``hg.repository()``, ``localrepo.instance()``,
1189 or ``localrepo.makelocalrepository()`` for obtaining a new repository
1204 or ``localrepo.makelocalrepository()`` for obtaining a new repository
1190 object.
1205 object.
1191
1206
1192 Arguments:
1207 Arguments:
1193
1208
1194 baseui
1209 baseui
1195 ``ui.ui`` instance that ``ui`` argument was based off of.
1210 ``ui.ui`` instance that ``ui`` argument was based off of.
1196
1211
1197 ui
1212 ui
1198 ``ui.ui`` instance for use by the repository.
1213 ``ui.ui`` instance for use by the repository.
1199
1214
1200 origroot
1215 origroot
1201 ``bytes`` path to working directory root of this repository.
1216 ``bytes`` path to working directory root of this repository.
1202
1217
1203 wdirvfs
1218 wdirvfs
1204 ``vfs.vfs`` rooted at the working directory.
1219 ``vfs.vfs`` rooted at the working directory.
1205
1220
1206 hgvfs
1221 hgvfs
1207 ``vfs.vfs`` rooted at .hg/
1222 ``vfs.vfs`` rooted at .hg/
1208
1223
1209 requirements
1224 requirements
1210 ``set`` of bytestrings representing repository opening requirements.
1225 ``set`` of bytestrings representing repository opening requirements.
1211
1226
1212 supportedrequirements
1227 supportedrequirements
1213 ``set`` of bytestrings representing repository requirements that we
1228 ``set`` of bytestrings representing repository requirements that we
1214 know how to open. May be a supetset of ``requirements``.
1229 know how to open. May be a supetset of ``requirements``.
1215
1230
1216 sharedpath
1231 sharedpath
1217 ``bytes`` Defining path to storage base directory. Points to a
1232 ``bytes`` Defining path to storage base directory. Points to a
1218 ``.hg/`` directory somewhere.
1233 ``.hg/`` directory somewhere.
1219
1234
1220 store
1235 store
1221 ``store.basicstore`` (or derived) instance providing access to
1236 ``store.basicstore`` (or derived) instance providing access to
1222 versioned storage.
1237 versioned storage.
1223
1238
1224 cachevfs
1239 cachevfs
1225 ``vfs.vfs`` used for cache files.
1240 ``vfs.vfs`` used for cache files.
1226
1241
1227 wcachevfs
1242 wcachevfs
1228 ``vfs.vfs`` used for cache files related to the working copy.
1243 ``vfs.vfs`` used for cache files related to the working copy.
1229
1244
1230 features
1245 features
1231 ``set`` of bytestrings defining features/capabilities of this
1246 ``set`` of bytestrings defining features/capabilities of this
1232 instance.
1247 instance.
1233
1248
1234 intents
1249 intents
1235 ``set`` of system strings indicating what this repo will be used
1250 ``set`` of system strings indicating what this repo will be used
1236 for.
1251 for.
1237 """
1252 """
1238 self.baseui = baseui
1253 self.baseui = baseui
1239 self.ui = ui
1254 self.ui = ui
1240 self.origroot = origroot
1255 self.origroot = origroot
1241 # vfs rooted at working directory.
1256 # vfs rooted at working directory.
1242 self.wvfs = wdirvfs
1257 self.wvfs = wdirvfs
1243 self.root = wdirvfs.base
1258 self.root = wdirvfs.base
1244 # vfs rooted at .hg/. Used to access most non-store paths.
1259 # vfs rooted at .hg/. Used to access most non-store paths.
1245 self.vfs = hgvfs
1260 self.vfs = hgvfs
1246 self.path = hgvfs.base
1261 self.path = hgvfs.base
1247 self.requirements = requirements
1262 self.requirements = requirements
1248 self.supported = supportedrequirements
1263 self.supported = supportedrequirements
1249 self.sharedpath = sharedpath
1264 self.sharedpath = sharedpath
1250 self.store = store
1265 self.store = store
1251 self.cachevfs = cachevfs
1266 self.cachevfs = cachevfs
1252 self.wcachevfs = wcachevfs
1267 self.wcachevfs = wcachevfs
1253 self.features = features
1268 self.features = features
1254
1269
1255 self.filtername = None
1270 self.filtername = None
1256
1271
1257 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1272 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1258 b'devel', b'check-locks'
1273 b'devel', b'check-locks'
1259 ):
1274 ):
1260 self.vfs.audit = self._getvfsward(self.vfs.audit)
1275 self.vfs.audit = self._getvfsward(self.vfs.audit)
1261 # A list of callback to shape the phase if no data were found.
1276 # A list of callback to shape the phase if no data were found.
1262 # Callback are in the form: func(repo, roots) --> processed root.
1277 # Callback are in the form: func(repo, roots) --> processed root.
1263 # This list it to be filled by extension during repo setup
1278 # This list it to be filled by extension during repo setup
1264 self._phasedefaults = []
1279 self._phasedefaults = []
1265
1280
1266 color.setup(self.ui)
1281 color.setup(self.ui)
1267
1282
1268 self.spath = self.store.path
1283 self.spath = self.store.path
1269 self.svfs = self.store.vfs
1284 self.svfs = self.store.vfs
1270 self.sjoin = self.store.join
1285 self.sjoin = self.store.join
1271 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1286 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
1272 b'devel', b'check-locks'
1287 b'devel', b'check-locks'
1273 ):
1288 ):
1274 if util.safehasattr(self.svfs, b'vfs'): # this is filtervfs
1289 if util.safehasattr(self.svfs, b'vfs'): # this is filtervfs
1275 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1290 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
1276 else: # standard vfs
1291 else: # standard vfs
1277 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1292 self.svfs.audit = self._getsvfsward(self.svfs.audit)
1278
1293
1279 self._dirstatevalidatewarned = False
1294 self._dirstatevalidatewarned = False
1280
1295
1281 self._branchcaches = branchmap.BranchMapCache()
1296 self._branchcaches = branchmap.BranchMapCache()
1282 self._revbranchcache = None
1297 self._revbranchcache = None
1283 self._filterpats = {}
1298 self._filterpats = {}
1284 self._datafilters = {}
1299 self._datafilters = {}
1285 self._transref = self._lockref = self._wlockref = None
1300 self._transref = self._lockref = self._wlockref = None
1286
1301
1287 # A cache for various files under .hg/ that tracks file changes,
1302 # A cache for various files under .hg/ that tracks file changes,
1288 # (used by the filecache decorator)
1303 # (used by the filecache decorator)
1289 #
1304 #
1290 # Maps a property name to its util.filecacheentry
1305 # Maps a property name to its util.filecacheentry
1291 self._filecache = {}
1306 self._filecache = {}
1292
1307
1293 # hold sets of revision to be filtered
1308 # hold sets of revision to be filtered
1294 # should be cleared when something might have changed the filter value:
1309 # should be cleared when something might have changed the filter value:
1295 # - new changesets,
1310 # - new changesets,
1296 # - phase change,
1311 # - phase change,
1297 # - new obsolescence marker,
1312 # - new obsolescence marker,
1298 # - working directory parent change,
1313 # - working directory parent change,
1299 # - bookmark changes
1314 # - bookmark changes
1300 self.filteredrevcache = {}
1315 self.filteredrevcache = {}
1301
1316
1302 # post-dirstate-status hooks
1317 # post-dirstate-status hooks
1303 self._postdsstatus = []
1318 self._postdsstatus = []
1304
1319
1305 # generic mapping between names and nodes
1320 # generic mapping between names and nodes
1306 self.names = namespaces.namespaces()
1321 self.names = namespaces.namespaces()
1307
1322
1308 # Key to signature value.
1323 # Key to signature value.
1309 self._sparsesignaturecache = {}
1324 self._sparsesignaturecache = {}
1310 # Signature to cached matcher instance.
1325 # Signature to cached matcher instance.
1311 self._sparsematchercache = {}
1326 self._sparsematchercache = {}
1312
1327
1313 self._extrafilterid = repoview.extrafilter(ui)
1328 self._extrafilterid = repoview.extrafilter(ui)
1314
1329
1315 self.filecopiesmode = None
1330 self.filecopiesmode = None
1316 if requirementsmod.COPIESSDC_REQUIREMENT in self.requirements:
1331 if requirementsmod.COPIESSDC_REQUIREMENT in self.requirements:
1317 self.filecopiesmode = b'changeset-sidedata'
1332 self.filecopiesmode = b'changeset-sidedata'
1318
1333
1319 def _getvfsward(self, origfunc):
1334 def _getvfsward(self, origfunc):
1320 """build a ward for self.vfs"""
1335 """build a ward for self.vfs"""
1321 rref = weakref.ref(self)
1336 rref = weakref.ref(self)
1322
1337
1323 def checkvfs(path, mode=None):
1338 def checkvfs(path, mode=None):
1324 ret = origfunc(path, mode=mode)
1339 ret = origfunc(path, mode=mode)
1325 repo = rref()
1340 repo = rref()
1326 if (
1341 if (
1327 repo is None
1342 repo is None
1328 or not util.safehasattr(repo, b'_wlockref')
1343 or not util.safehasattr(repo, b'_wlockref')
1329 or not util.safehasattr(repo, b'_lockref')
1344 or not util.safehasattr(repo, b'_lockref')
1330 ):
1345 ):
1331 return
1346 return
1332 if mode in (None, b'r', b'rb'):
1347 if mode in (None, b'r', b'rb'):
1333 return
1348 return
1334 if path.startswith(repo.path):
1349 if path.startswith(repo.path):
1335 # truncate name relative to the repository (.hg)
1350 # truncate name relative to the repository (.hg)
1336 path = path[len(repo.path) + 1 :]
1351 path = path[len(repo.path) + 1 :]
1337 if path.startswith(b'cache/'):
1352 if path.startswith(b'cache/'):
1338 msg = b'accessing cache with vfs instead of cachevfs: "%s"'
1353 msg = b'accessing cache with vfs instead of cachevfs: "%s"'
1339 repo.ui.develwarn(msg % path, stacklevel=3, config=b"cache-vfs")
1354 repo.ui.develwarn(msg % path, stacklevel=3, config=b"cache-vfs")
1340 # path prefixes covered by 'lock'
1355 # path prefixes covered by 'lock'
1341 vfs_path_prefixes = (
1356 vfs_path_prefixes = (
1342 b'journal.',
1357 b'journal.',
1343 b'undo.',
1358 b'undo.',
1344 b'strip-backup/',
1359 b'strip-backup/',
1345 b'cache/',
1360 b'cache/',
1346 )
1361 )
1347 if any(path.startswith(prefix) for prefix in vfs_path_prefixes):
1362 if any(path.startswith(prefix) for prefix in vfs_path_prefixes):
1348 if repo._currentlock(repo._lockref) is None:
1363 if repo._currentlock(repo._lockref) is None:
1349 repo.ui.develwarn(
1364 repo.ui.develwarn(
1350 b'write with no lock: "%s"' % path,
1365 b'write with no lock: "%s"' % path,
1351 stacklevel=3,
1366 stacklevel=3,
1352 config=b'check-locks',
1367 config=b'check-locks',
1353 )
1368 )
1354 elif repo._currentlock(repo._wlockref) is None:
1369 elif repo._currentlock(repo._wlockref) is None:
1355 # rest of vfs files are covered by 'wlock'
1370 # rest of vfs files are covered by 'wlock'
1356 #
1371 #
1357 # exclude special files
1372 # exclude special files
1358 for prefix in self._wlockfreeprefix:
1373 for prefix in self._wlockfreeprefix:
1359 if path.startswith(prefix):
1374 if path.startswith(prefix):
1360 return
1375 return
1361 repo.ui.develwarn(
1376 repo.ui.develwarn(
1362 b'write with no wlock: "%s"' % path,
1377 b'write with no wlock: "%s"' % path,
1363 stacklevel=3,
1378 stacklevel=3,
1364 config=b'check-locks',
1379 config=b'check-locks',
1365 )
1380 )
1366 return ret
1381 return ret
1367
1382
1368 return checkvfs
1383 return checkvfs
1369
1384
1370 def _getsvfsward(self, origfunc):
1385 def _getsvfsward(self, origfunc):
1371 """build a ward for self.svfs"""
1386 """build a ward for self.svfs"""
1372 rref = weakref.ref(self)
1387 rref = weakref.ref(self)
1373
1388
1374 def checksvfs(path, mode=None):
1389 def checksvfs(path, mode=None):
1375 ret = origfunc(path, mode=mode)
1390 ret = origfunc(path, mode=mode)
1376 repo = rref()
1391 repo = rref()
1377 if repo is None or not util.safehasattr(repo, b'_lockref'):
1392 if repo is None or not util.safehasattr(repo, b'_lockref'):
1378 return
1393 return
1379 if mode in (None, b'r', b'rb'):
1394 if mode in (None, b'r', b'rb'):
1380 return
1395 return
1381 if path.startswith(repo.sharedpath):
1396 if path.startswith(repo.sharedpath):
1382 # truncate name relative to the repository (.hg)
1397 # truncate name relative to the repository (.hg)
1383 path = path[len(repo.sharedpath) + 1 :]
1398 path = path[len(repo.sharedpath) + 1 :]
1384 if repo._currentlock(repo._lockref) is None:
1399 if repo._currentlock(repo._lockref) is None:
1385 repo.ui.develwarn(
1400 repo.ui.develwarn(
1386 b'write with no lock: "%s"' % path, stacklevel=4
1401 b'write with no lock: "%s"' % path, stacklevel=4
1387 )
1402 )
1388 return ret
1403 return ret
1389
1404
1390 return checksvfs
1405 return checksvfs
1391
1406
1392 def close(self):
1407 def close(self):
1393 self._writecaches()
1408 self._writecaches()
1394
1409
1395 def _writecaches(self):
1410 def _writecaches(self):
1396 if self._revbranchcache:
1411 if self._revbranchcache:
1397 self._revbranchcache.write()
1412 self._revbranchcache.write()
1398
1413
1399 def _restrictcapabilities(self, caps):
1414 def _restrictcapabilities(self, caps):
1400 if self.ui.configbool(b'experimental', b'bundle2-advertise'):
1415 if self.ui.configbool(b'experimental', b'bundle2-advertise'):
1401 caps = set(caps)
1416 caps = set(caps)
1402 capsblob = bundle2.encodecaps(
1417 capsblob = bundle2.encodecaps(
1403 bundle2.getrepocaps(self, role=b'client')
1418 bundle2.getrepocaps(self, role=b'client')
1404 )
1419 )
1405 caps.add(b'bundle2=' + urlreq.quote(capsblob))
1420 caps.add(b'bundle2=' + urlreq.quote(capsblob))
1406 return caps
1421 return caps
1407
1422
1408 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1423 # Don't cache auditor/nofsauditor, or you'll end up with reference cycle:
1409 # self -> auditor -> self._checknested -> self
1424 # self -> auditor -> self._checknested -> self
1410
1425
1411 @property
1426 @property
1412 def auditor(self):
1427 def auditor(self):
1413 # This is only used by context.workingctx.match in order to
1428 # This is only used by context.workingctx.match in order to
1414 # detect files in subrepos.
1429 # detect files in subrepos.
1415 return pathutil.pathauditor(self.root, callback=self._checknested)
1430 return pathutil.pathauditor(self.root, callback=self._checknested)
1416
1431
1417 @property
1432 @property
1418 def nofsauditor(self):
1433 def nofsauditor(self):
1419 # This is only used by context.basectx.match in order to detect
1434 # This is only used by context.basectx.match in order to detect
1420 # files in subrepos.
1435 # files in subrepos.
1421 return pathutil.pathauditor(
1436 return pathutil.pathauditor(
1422 self.root, callback=self._checknested, realfs=False, cached=True
1437 self.root, callback=self._checknested, realfs=False, cached=True
1423 )
1438 )
1424
1439
1425 def _checknested(self, path):
1440 def _checknested(self, path):
1426 """Determine if path is a legal nested repository."""
1441 """Determine if path is a legal nested repository."""
1427 if not path.startswith(self.root):
1442 if not path.startswith(self.root):
1428 return False
1443 return False
1429 subpath = path[len(self.root) + 1 :]
1444 subpath = path[len(self.root) + 1 :]
1430 normsubpath = util.pconvert(subpath)
1445 normsubpath = util.pconvert(subpath)
1431
1446
1432 # XXX: Checking against the current working copy is wrong in
1447 # XXX: Checking against the current working copy is wrong in
1433 # the sense that it can reject things like
1448 # the sense that it can reject things like
1434 #
1449 #
1435 # $ hg cat -r 10 sub/x.txt
1450 # $ hg cat -r 10 sub/x.txt
1436 #
1451 #
1437 # if sub/ is no longer a subrepository in the working copy
1452 # if sub/ is no longer a subrepository in the working copy
1438 # parent revision.
1453 # parent revision.
1439 #
1454 #
1440 # However, it can of course also allow things that would have
1455 # However, it can of course also allow things that would have
1441 # been rejected before, such as the above cat command if sub/
1456 # been rejected before, such as the above cat command if sub/
1442 # is a subrepository now, but was a normal directory before.
1457 # is a subrepository now, but was a normal directory before.
1443 # The old path auditor would have rejected by mistake since it
1458 # The old path auditor would have rejected by mistake since it
1444 # panics when it sees sub/.hg/.
1459 # panics when it sees sub/.hg/.
1445 #
1460 #
1446 # All in all, checking against the working copy seems sensible
1461 # All in all, checking against the working copy seems sensible
1447 # since we want to prevent access to nested repositories on
1462 # since we want to prevent access to nested repositories on
1448 # the filesystem *now*.
1463 # the filesystem *now*.
1449 ctx = self[None]
1464 ctx = self[None]
1450 parts = util.splitpath(subpath)
1465 parts = util.splitpath(subpath)
1451 while parts:
1466 while parts:
1452 prefix = b'/'.join(parts)
1467 prefix = b'/'.join(parts)
1453 if prefix in ctx.substate:
1468 if prefix in ctx.substate:
1454 if prefix == normsubpath:
1469 if prefix == normsubpath:
1455 return True
1470 return True
1456 else:
1471 else:
1457 sub = ctx.sub(prefix)
1472 sub = ctx.sub(prefix)
1458 return sub.checknested(subpath[len(prefix) + 1 :])
1473 return sub.checknested(subpath[len(prefix) + 1 :])
1459 else:
1474 else:
1460 parts.pop()
1475 parts.pop()
1461 return False
1476 return False
1462
1477
1463 def peer(self):
1478 def peer(self):
1464 return localpeer(self) # not cached to avoid reference cycle
1479 return localpeer(self) # not cached to avoid reference cycle
1465
1480
1466 def unfiltered(self):
1481 def unfiltered(self):
1467 """Return unfiltered version of the repository
1482 """Return unfiltered version of the repository
1468
1483
1469 Intended to be overwritten by filtered repo."""
1484 Intended to be overwritten by filtered repo."""
1470 return self
1485 return self
1471
1486
1472 def filtered(self, name, visibilityexceptions=None):
1487 def filtered(self, name, visibilityexceptions=None):
1473 """Return a filtered version of a repository
1488 """Return a filtered version of a repository
1474
1489
1475 The `name` parameter is the identifier of the requested view. This
1490 The `name` parameter is the identifier of the requested view. This
1476 will return a repoview object set "exactly" to the specified view.
1491 will return a repoview object set "exactly" to the specified view.
1477
1492
1478 This function does not apply recursive filtering to a repository. For
1493 This function does not apply recursive filtering to a repository. For
1479 example calling `repo.filtered("served")` will return a repoview using
1494 example calling `repo.filtered("served")` will return a repoview using
1480 the "served" view, regardless of the initial view used by `repo`.
1495 the "served" view, regardless of the initial view used by `repo`.
1481
1496
1482 In other word, there is always only one level of `repoview` "filtering".
1497 In other word, there is always only one level of `repoview` "filtering".
1483 """
1498 """
1484 if self._extrafilterid is not None and b'%' not in name:
1499 if self._extrafilterid is not None and b'%' not in name:
1485 name = name + b'%' + self._extrafilterid
1500 name = name + b'%' + self._extrafilterid
1486
1501
1487 cls = repoview.newtype(self.unfiltered().__class__)
1502 cls = repoview.newtype(self.unfiltered().__class__)
1488 return cls(self, name, visibilityexceptions)
1503 return cls(self, name, visibilityexceptions)
1489
1504
1490 @mixedrepostorecache(
1505 @mixedrepostorecache(
1491 (b'bookmarks', b'plain'),
1506 (b'bookmarks', b'plain'),
1492 (b'bookmarks.current', b'plain'),
1507 (b'bookmarks.current', b'plain'),
1493 (b'bookmarks', b''),
1508 (b'bookmarks', b''),
1494 (b'00changelog.i', b''),
1509 (b'00changelog.i', b''),
1495 )
1510 )
1496 def _bookmarks(self):
1511 def _bookmarks(self):
1497 # Since the multiple files involved in the transaction cannot be
1512 # Since the multiple files involved in the transaction cannot be
1498 # written atomically (with current repository format), there is a race
1513 # written atomically (with current repository format), there is a race
1499 # condition here.
1514 # condition here.
1500 #
1515 #
1501 # 1) changelog content A is read
1516 # 1) changelog content A is read
1502 # 2) outside transaction update changelog to content B
1517 # 2) outside transaction update changelog to content B
1503 # 3) outside transaction update bookmark file referring to content B
1518 # 3) outside transaction update bookmark file referring to content B
1504 # 4) bookmarks file content is read and filtered against changelog-A
1519 # 4) bookmarks file content is read and filtered against changelog-A
1505 #
1520 #
1506 # When this happens, bookmarks against nodes missing from A are dropped.
1521 # When this happens, bookmarks against nodes missing from A are dropped.
1507 #
1522 #
1508 # Having this happening during read is not great, but it become worse
1523 # Having this happening during read is not great, but it become worse
1509 # when this happen during write because the bookmarks to the "unknown"
1524 # when this happen during write because the bookmarks to the "unknown"
1510 # nodes will be dropped for good. However, writes happen within locks.
1525 # nodes will be dropped for good. However, writes happen within locks.
1511 # This locking makes it possible to have a race free consistent read.
1526 # This locking makes it possible to have a race free consistent read.
1512 # For this purpose data read from disc before locking are
1527 # For this purpose data read from disc before locking are
1513 # "invalidated" right after the locks are taken. This invalidations are
1528 # "invalidated" right after the locks are taken. This invalidations are
1514 # "light", the `filecache` mechanism keep the data in memory and will
1529 # "light", the `filecache` mechanism keep the data in memory and will
1515 # reuse them if the underlying files did not changed. Not parsing the
1530 # reuse them if the underlying files did not changed. Not parsing the
1516 # same data multiple times helps performances.
1531 # same data multiple times helps performances.
1517 #
1532 #
1518 # Unfortunately in the case describe above, the files tracked by the
1533 # Unfortunately in the case describe above, the files tracked by the
1519 # bookmarks file cache might not have changed, but the in-memory
1534 # bookmarks file cache might not have changed, but the in-memory
1520 # content is still "wrong" because we used an older changelog content
1535 # content is still "wrong" because we used an older changelog content
1521 # to process the on-disk data. So after locking, the changelog would be
1536 # to process the on-disk data. So after locking, the changelog would be
1522 # refreshed but `_bookmarks` would be preserved.
1537 # refreshed but `_bookmarks` would be preserved.
1523 # Adding `00changelog.i` to the list of tracked file is not
1538 # Adding `00changelog.i` to the list of tracked file is not
1524 # enough, because at the time we build the content for `_bookmarks` in
1539 # enough, because at the time we build the content for `_bookmarks` in
1525 # (4), the changelog file has already diverged from the content used
1540 # (4), the changelog file has already diverged from the content used
1526 # for loading `changelog` in (1)
1541 # for loading `changelog` in (1)
1527 #
1542 #
1528 # To prevent the issue, we force the changelog to be explicitly
1543 # To prevent the issue, we force the changelog to be explicitly
1529 # reloaded while computing `_bookmarks`. The data race can still happen
1544 # reloaded while computing `_bookmarks`. The data race can still happen
1530 # without the lock (with a narrower window), but it would no longer go
1545 # without the lock (with a narrower window), but it would no longer go
1531 # undetected during the lock time refresh.
1546 # undetected during the lock time refresh.
1532 #
1547 #
1533 # The new schedule is as follow
1548 # The new schedule is as follow
1534 #
1549 #
1535 # 1) filecache logic detect that `_bookmarks` needs to be computed
1550 # 1) filecache logic detect that `_bookmarks` needs to be computed
1536 # 2) cachestat for `bookmarks` and `changelog` are captured (for book)
1551 # 2) cachestat for `bookmarks` and `changelog` are captured (for book)
1537 # 3) We force `changelog` filecache to be tested
1552 # 3) We force `changelog` filecache to be tested
1538 # 4) cachestat for `changelog` are captured (for changelog)
1553 # 4) cachestat for `changelog` are captured (for changelog)
1539 # 5) `_bookmarks` is computed and cached
1554 # 5) `_bookmarks` is computed and cached
1540 #
1555 #
1541 # The step in (3) ensure we have a changelog at least as recent as the
1556 # The step in (3) ensure we have a changelog at least as recent as the
1542 # cache stat computed in (1). As a result at locking time:
1557 # cache stat computed in (1). As a result at locking time:
1543 # * if the changelog did not changed since (1) -> we can reuse the data
1558 # * if the changelog did not changed since (1) -> we can reuse the data
1544 # * otherwise -> the bookmarks get refreshed.
1559 # * otherwise -> the bookmarks get refreshed.
1545 self._refreshchangelog()
1560 self._refreshchangelog()
1546 return bookmarks.bmstore(self)
1561 return bookmarks.bmstore(self)
1547
1562
1548 def _refreshchangelog(self):
1563 def _refreshchangelog(self):
1549 """make sure the in memory changelog match the on-disk one"""
1564 """make sure the in memory changelog match the on-disk one"""
1550 if 'changelog' in vars(self) and self.currenttransaction() is None:
1565 if 'changelog' in vars(self) and self.currenttransaction() is None:
1551 del self.changelog
1566 del self.changelog
1552
1567
1553 @property
1568 @property
1554 def _activebookmark(self):
1569 def _activebookmark(self):
1555 return self._bookmarks.active
1570 return self._bookmarks.active
1556
1571
1557 # _phasesets depend on changelog. what we need is to call
1572 # _phasesets depend on changelog. what we need is to call
1558 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1573 # _phasecache.invalidate() if '00changelog.i' was changed, but it
1559 # can't be easily expressed in filecache mechanism.
1574 # can't be easily expressed in filecache mechanism.
1560 @storecache(b'phaseroots', b'00changelog.i')
1575 @storecache(b'phaseroots', b'00changelog.i')
1561 def _phasecache(self):
1576 def _phasecache(self):
1562 return phases.phasecache(self, self._phasedefaults)
1577 return phases.phasecache(self, self._phasedefaults)
1563
1578
1564 @storecache(b'obsstore')
1579 @storecache(b'obsstore')
1565 def obsstore(self):
1580 def obsstore(self):
1566 return obsolete.makestore(self.ui, self)
1581 return obsolete.makestore(self.ui, self)
1567
1582
1568 @storecache(b'00changelog.i')
1583 @storecache(b'00changelog.i')
1569 def changelog(self):
1584 def changelog(self):
1570 # load dirstate before changelog to avoid race see issue6303
1585 # load dirstate before changelog to avoid race see issue6303
1571 self.dirstate.prefetch_parents()
1586 self.dirstate.prefetch_parents()
1572 return self.store.changelog(txnutil.mayhavepending(self.root))
1587 return self.store.changelog(txnutil.mayhavepending(self.root))
1573
1588
1574 @storecache(b'00manifest.i')
1589 @storecache(b'00manifest.i')
1575 def manifestlog(self):
1590 def manifestlog(self):
1576 return self.store.manifestlog(self, self._storenarrowmatch)
1591 return self.store.manifestlog(self, self._storenarrowmatch)
1577
1592
1578 @repofilecache(b'dirstate')
1593 @repofilecache(b'dirstate')
1579 def dirstate(self):
1594 def dirstate(self):
1580 return self._makedirstate()
1595 return self._makedirstate()
1581
1596
1582 def _makedirstate(self):
1597 def _makedirstate(self):
1583 """Extension point for wrapping the dirstate per-repo."""
1598 """Extension point for wrapping the dirstate per-repo."""
1584 sparsematchfn = lambda: sparse.matcher(self)
1599 sparsematchfn = lambda: sparse.matcher(self)
1585
1600
1586 return dirstate.dirstate(
1601 return dirstate.dirstate(
1587 self.vfs, self.ui, self.root, self._dirstatevalidate, sparsematchfn
1602 self.vfs, self.ui, self.root, self._dirstatevalidate, sparsematchfn
1588 )
1603 )
1589
1604
1590 def _dirstatevalidate(self, node):
1605 def _dirstatevalidate(self, node):
1591 try:
1606 try:
1592 self.changelog.rev(node)
1607 self.changelog.rev(node)
1593 return node
1608 return node
1594 except error.LookupError:
1609 except error.LookupError:
1595 if not self._dirstatevalidatewarned:
1610 if not self._dirstatevalidatewarned:
1596 self._dirstatevalidatewarned = True
1611 self._dirstatevalidatewarned = True
1597 self.ui.warn(
1612 self.ui.warn(
1598 _(b"warning: ignoring unknown working parent %s!\n")
1613 _(b"warning: ignoring unknown working parent %s!\n")
1599 % short(node)
1614 % short(node)
1600 )
1615 )
1601 return nullid
1616 return nullid
1602
1617
1603 @storecache(narrowspec.FILENAME)
1618 @storecache(narrowspec.FILENAME)
1604 def narrowpats(self):
1619 def narrowpats(self):
1605 """matcher patterns for this repository's narrowspec
1620 """matcher patterns for this repository's narrowspec
1606
1621
1607 A tuple of (includes, excludes).
1622 A tuple of (includes, excludes).
1608 """
1623 """
1609 return narrowspec.load(self)
1624 return narrowspec.load(self)
1610
1625
1611 @storecache(narrowspec.FILENAME)
1626 @storecache(narrowspec.FILENAME)
1612 def _storenarrowmatch(self):
1627 def _storenarrowmatch(self):
1613 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1628 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1614 return matchmod.always()
1629 return matchmod.always()
1615 include, exclude = self.narrowpats
1630 include, exclude = self.narrowpats
1616 return narrowspec.match(self.root, include=include, exclude=exclude)
1631 return narrowspec.match(self.root, include=include, exclude=exclude)
1617
1632
1618 @storecache(narrowspec.FILENAME)
1633 @storecache(narrowspec.FILENAME)
1619 def _narrowmatch(self):
1634 def _narrowmatch(self):
1620 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1635 if requirementsmod.NARROW_REQUIREMENT not in self.requirements:
1621 return matchmod.always()
1636 return matchmod.always()
1622 narrowspec.checkworkingcopynarrowspec(self)
1637 narrowspec.checkworkingcopynarrowspec(self)
1623 include, exclude = self.narrowpats
1638 include, exclude = self.narrowpats
1624 return narrowspec.match(self.root, include=include, exclude=exclude)
1639 return narrowspec.match(self.root, include=include, exclude=exclude)
1625
1640
1626 def narrowmatch(self, match=None, includeexact=False):
1641 def narrowmatch(self, match=None, includeexact=False):
1627 """matcher corresponding the the repo's narrowspec
1642 """matcher corresponding the the repo's narrowspec
1628
1643
1629 If `match` is given, then that will be intersected with the narrow
1644 If `match` is given, then that will be intersected with the narrow
1630 matcher.
1645 matcher.
1631
1646
1632 If `includeexact` is True, then any exact matches from `match` will
1647 If `includeexact` is True, then any exact matches from `match` will
1633 be included even if they're outside the narrowspec.
1648 be included even if they're outside the narrowspec.
1634 """
1649 """
1635 if match:
1650 if match:
1636 if includeexact and not self._narrowmatch.always():
1651 if includeexact and not self._narrowmatch.always():
1637 # do not exclude explicitly-specified paths so that they can
1652 # do not exclude explicitly-specified paths so that they can
1638 # be warned later on
1653 # be warned later on
1639 em = matchmod.exact(match.files())
1654 em = matchmod.exact(match.files())
1640 nm = matchmod.unionmatcher([self._narrowmatch, em])
1655 nm = matchmod.unionmatcher([self._narrowmatch, em])
1641 return matchmod.intersectmatchers(match, nm)
1656 return matchmod.intersectmatchers(match, nm)
1642 return matchmod.intersectmatchers(match, self._narrowmatch)
1657 return matchmod.intersectmatchers(match, self._narrowmatch)
1643 return self._narrowmatch
1658 return self._narrowmatch
1644
1659
1645 def setnarrowpats(self, newincludes, newexcludes):
1660 def setnarrowpats(self, newincludes, newexcludes):
1646 narrowspec.save(self, newincludes, newexcludes)
1661 narrowspec.save(self, newincludes, newexcludes)
1647 self.invalidate(clearfilecache=True)
1662 self.invalidate(clearfilecache=True)
1648
1663
1649 @unfilteredpropertycache
1664 @unfilteredpropertycache
1650 def _quick_access_changeid_null(self):
1665 def _quick_access_changeid_null(self):
1651 return {
1666 return {
1652 b'null': (nullrev, nullid),
1667 b'null': (nullrev, nullid),
1653 nullrev: (nullrev, nullid),
1668 nullrev: (nullrev, nullid),
1654 nullid: (nullrev, nullid),
1669 nullid: (nullrev, nullid),
1655 }
1670 }
1656
1671
1657 @unfilteredpropertycache
1672 @unfilteredpropertycache
1658 def _quick_access_changeid_wc(self):
1673 def _quick_access_changeid_wc(self):
1659 # also fast path access to the working copy parents
1674 # also fast path access to the working copy parents
1660 # however, only do it for filter that ensure wc is visible.
1675 # however, only do it for filter that ensure wc is visible.
1661 quick = self._quick_access_changeid_null.copy()
1676 quick = self._quick_access_changeid_null.copy()
1662 cl = self.unfiltered().changelog
1677 cl = self.unfiltered().changelog
1663 for node in self.dirstate.parents():
1678 for node in self.dirstate.parents():
1664 if node == nullid:
1679 if node == nullid:
1665 continue
1680 continue
1666 rev = cl.index.get_rev(node)
1681 rev = cl.index.get_rev(node)
1667 if rev is None:
1682 if rev is None:
1668 # unknown working copy parent case:
1683 # unknown working copy parent case:
1669 #
1684 #
1670 # skip the fast path and let higher code deal with it
1685 # skip the fast path and let higher code deal with it
1671 continue
1686 continue
1672 pair = (rev, node)
1687 pair = (rev, node)
1673 quick[rev] = pair
1688 quick[rev] = pair
1674 quick[node] = pair
1689 quick[node] = pair
1675 # also add the parents of the parents
1690 # also add the parents of the parents
1676 for r in cl.parentrevs(rev):
1691 for r in cl.parentrevs(rev):
1677 if r == nullrev:
1692 if r == nullrev:
1678 continue
1693 continue
1679 n = cl.node(r)
1694 n = cl.node(r)
1680 pair = (r, n)
1695 pair = (r, n)
1681 quick[r] = pair
1696 quick[r] = pair
1682 quick[n] = pair
1697 quick[n] = pair
1683 p1node = self.dirstate.p1()
1698 p1node = self.dirstate.p1()
1684 if p1node != nullid:
1699 if p1node != nullid:
1685 quick[b'.'] = quick[p1node]
1700 quick[b'.'] = quick[p1node]
1686 return quick
1701 return quick
1687
1702
1688 @unfilteredmethod
1703 @unfilteredmethod
1689 def _quick_access_changeid_invalidate(self):
1704 def _quick_access_changeid_invalidate(self):
1690 if '_quick_access_changeid_wc' in vars(self):
1705 if '_quick_access_changeid_wc' in vars(self):
1691 del self.__dict__['_quick_access_changeid_wc']
1706 del self.__dict__['_quick_access_changeid_wc']
1692
1707
1693 @property
1708 @property
1694 def _quick_access_changeid(self):
1709 def _quick_access_changeid(self):
1695 """an helper dictionnary for __getitem__ calls
1710 """an helper dictionnary for __getitem__ calls
1696
1711
1697 This contains a list of symbol we can recognise right away without
1712 This contains a list of symbol we can recognise right away without
1698 further processing.
1713 further processing.
1699 """
1714 """
1700 if self.filtername in repoview.filter_has_wc:
1715 if self.filtername in repoview.filter_has_wc:
1701 return self._quick_access_changeid_wc
1716 return self._quick_access_changeid_wc
1702 return self._quick_access_changeid_null
1717 return self._quick_access_changeid_null
1703
1718
1704 def __getitem__(self, changeid):
1719 def __getitem__(self, changeid):
1705 # dealing with special cases
1720 # dealing with special cases
1706 if changeid is None:
1721 if changeid is None:
1707 return context.workingctx(self)
1722 return context.workingctx(self)
1708 if isinstance(changeid, context.basectx):
1723 if isinstance(changeid, context.basectx):
1709 return changeid
1724 return changeid
1710
1725
1711 # dealing with multiple revisions
1726 # dealing with multiple revisions
1712 if isinstance(changeid, slice):
1727 if isinstance(changeid, slice):
1713 # wdirrev isn't contiguous so the slice shouldn't include it
1728 # wdirrev isn't contiguous so the slice shouldn't include it
1714 return [
1729 return [
1715 self[i]
1730 self[i]
1716 for i in pycompat.xrange(*changeid.indices(len(self)))
1731 for i in pycompat.xrange(*changeid.indices(len(self)))
1717 if i not in self.changelog.filteredrevs
1732 if i not in self.changelog.filteredrevs
1718 ]
1733 ]
1719
1734
1720 # dealing with some special values
1735 # dealing with some special values
1721 quick_access = self._quick_access_changeid.get(changeid)
1736 quick_access = self._quick_access_changeid.get(changeid)
1722 if quick_access is not None:
1737 if quick_access is not None:
1723 rev, node = quick_access
1738 rev, node = quick_access
1724 return context.changectx(self, rev, node, maybe_filtered=False)
1739 return context.changectx(self, rev, node, maybe_filtered=False)
1725 if changeid == b'tip':
1740 if changeid == b'tip':
1726 node = self.changelog.tip()
1741 node = self.changelog.tip()
1727 rev = self.changelog.rev(node)
1742 rev = self.changelog.rev(node)
1728 return context.changectx(self, rev, node)
1743 return context.changectx(self, rev, node)
1729
1744
1730 # dealing with arbitrary values
1745 # dealing with arbitrary values
1731 try:
1746 try:
1732 if isinstance(changeid, int):
1747 if isinstance(changeid, int):
1733 node = self.changelog.node(changeid)
1748 node = self.changelog.node(changeid)
1734 rev = changeid
1749 rev = changeid
1735 elif changeid == b'.':
1750 elif changeid == b'.':
1736 # this is a hack to delay/avoid loading obsmarkers
1751 # this is a hack to delay/avoid loading obsmarkers
1737 # when we know that '.' won't be hidden
1752 # when we know that '.' won't be hidden
1738 node = self.dirstate.p1()
1753 node = self.dirstate.p1()
1739 rev = self.unfiltered().changelog.rev(node)
1754 rev = self.unfiltered().changelog.rev(node)
1740 elif len(changeid) == 20:
1755 elif len(changeid) == 20:
1741 try:
1756 try:
1742 node = changeid
1757 node = changeid
1743 rev = self.changelog.rev(changeid)
1758 rev = self.changelog.rev(changeid)
1744 except error.FilteredLookupError:
1759 except error.FilteredLookupError:
1745 changeid = hex(changeid) # for the error message
1760 changeid = hex(changeid) # for the error message
1746 raise
1761 raise
1747 except LookupError:
1762 except LookupError:
1748 # check if it might have come from damaged dirstate
1763 # check if it might have come from damaged dirstate
1749 #
1764 #
1750 # XXX we could avoid the unfiltered if we had a recognizable
1765 # XXX we could avoid the unfiltered if we had a recognizable
1751 # exception for filtered changeset access
1766 # exception for filtered changeset access
1752 if (
1767 if (
1753 self.local()
1768 self.local()
1754 and changeid in self.unfiltered().dirstate.parents()
1769 and changeid in self.unfiltered().dirstate.parents()
1755 ):
1770 ):
1756 msg = _(b"working directory has unknown parent '%s'!")
1771 msg = _(b"working directory has unknown parent '%s'!")
1757 raise error.Abort(msg % short(changeid))
1772 raise error.Abort(msg % short(changeid))
1758 changeid = hex(changeid) # for the error message
1773 changeid = hex(changeid) # for the error message
1759 raise
1774 raise
1760
1775
1761 elif len(changeid) == 40:
1776 elif len(changeid) == 40:
1762 node = bin(changeid)
1777 node = bin(changeid)
1763 rev = self.changelog.rev(node)
1778 rev = self.changelog.rev(node)
1764 else:
1779 else:
1765 raise error.ProgrammingError(
1780 raise error.ProgrammingError(
1766 b"unsupported changeid '%s' of type %s"
1781 b"unsupported changeid '%s' of type %s"
1767 % (changeid, pycompat.bytestr(type(changeid)))
1782 % (changeid, pycompat.bytestr(type(changeid)))
1768 )
1783 )
1769
1784
1770 return context.changectx(self, rev, node)
1785 return context.changectx(self, rev, node)
1771
1786
1772 except (error.FilteredIndexError, error.FilteredLookupError):
1787 except (error.FilteredIndexError, error.FilteredLookupError):
1773 raise error.FilteredRepoLookupError(
1788 raise error.FilteredRepoLookupError(
1774 _(b"filtered revision '%s'") % pycompat.bytestr(changeid)
1789 _(b"filtered revision '%s'") % pycompat.bytestr(changeid)
1775 )
1790 )
1776 except (IndexError, LookupError):
1791 except (IndexError, LookupError):
1777 raise error.RepoLookupError(
1792 raise error.RepoLookupError(
1778 _(b"unknown revision '%s'") % pycompat.bytestr(changeid)
1793 _(b"unknown revision '%s'") % pycompat.bytestr(changeid)
1779 )
1794 )
1780 except error.WdirUnsupported:
1795 except error.WdirUnsupported:
1781 return context.workingctx(self)
1796 return context.workingctx(self)
1782
1797
1783 def __contains__(self, changeid):
1798 def __contains__(self, changeid):
1784 """True if the given changeid exists"""
1799 """True if the given changeid exists"""
1785 try:
1800 try:
1786 self[changeid]
1801 self[changeid]
1787 return True
1802 return True
1788 except error.RepoLookupError:
1803 except error.RepoLookupError:
1789 return False
1804 return False
1790
1805
1791 def __nonzero__(self):
1806 def __nonzero__(self):
1792 return True
1807 return True
1793
1808
1794 __bool__ = __nonzero__
1809 __bool__ = __nonzero__
1795
1810
1796 def __len__(self):
1811 def __len__(self):
1797 # no need to pay the cost of repoview.changelog
1812 # no need to pay the cost of repoview.changelog
1798 unfi = self.unfiltered()
1813 unfi = self.unfiltered()
1799 return len(unfi.changelog)
1814 return len(unfi.changelog)
1800
1815
1801 def __iter__(self):
1816 def __iter__(self):
1802 return iter(self.changelog)
1817 return iter(self.changelog)
1803
1818
1804 def revs(self, expr, *args):
1819 def revs(self, expr, *args):
1805 """Find revisions matching a revset.
1820 """Find revisions matching a revset.
1806
1821
1807 The revset is specified as a string ``expr`` that may contain
1822 The revset is specified as a string ``expr`` that may contain
1808 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1823 %-formatting to escape certain types. See ``revsetlang.formatspec``.
1809
1824
1810 Revset aliases from the configuration are not expanded. To expand
1825 Revset aliases from the configuration are not expanded. To expand
1811 user aliases, consider calling ``scmutil.revrange()`` or
1826 user aliases, consider calling ``scmutil.revrange()`` or
1812 ``repo.anyrevs([expr], user=True)``.
1827 ``repo.anyrevs([expr], user=True)``.
1813
1828
1814 Returns a smartset.abstractsmartset, which is a list-like interface
1829 Returns a smartset.abstractsmartset, which is a list-like interface
1815 that contains integer revisions.
1830 that contains integer revisions.
1816 """
1831 """
1817 tree = revsetlang.spectree(expr, *args)
1832 tree = revsetlang.spectree(expr, *args)
1818 return revset.makematcher(tree)(self)
1833 return revset.makematcher(tree)(self)
1819
1834
1820 def set(self, expr, *args):
1835 def set(self, expr, *args):
1821 """Find revisions matching a revset and emit changectx instances.
1836 """Find revisions matching a revset and emit changectx instances.
1822
1837
1823 This is a convenience wrapper around ``revs()`` that iterates the
1838 This is a convenience wrapper around ``revs()`` that iterates the
1824 result and is a generator of changectx instances.
1839 result and is a generator of changectx instances.
1825
1840
1826 Revset aliases from the configuration are not expanded. To expand
1841 Revset aliases from the configuration are not expanded. To expand
1827 user aliases, consider calling ``scmutil.revrange()``.
1842 user aliases, consider calling ``scmutil.revrange()``.
1828 """
1843 """
1829 for r in self.revs(expr, *args):
1844 for r in self.revs(expr, *args):
1830 yield self[r]
1845 yield self[r]
1831
1846
1832 def anyrevs(self, specs, user=False, localalias=None):
1847 def anyrevs(self, specs, user=False, localalias=None):
1833 """Find revisions matching one of the given revsets.
1848 """Find revisions matching one of the given revsets.
1834
1849
1835 Revset aliases from the configuration are not expanded by default. To
1850 Revset aliases from the configuration are not expanded by default. To
1836 expand user aliases, specify ``user=True``. To provide some local
1851 expand user aliases, specify ``user=True``. To provide some local
1837 definitions overriding user aliases, set ``localalias`` to
1852 definitions overriding user aliases, set ``localalias`` to
1838 ``{name: definitionstring}``.
1853 ``{name: definitionstring}``.
1839 """
1854 """
1840 if specs == [b'null']:
1855 if specs == [b'null']:
1841 return revset.baseset([nullrev])
1856 return revset.baseset([nullrev])
1842 if specs == [b'.']:
1857 if specs == [b'.']:
1843 quick_data = self._quick_access_changeid.get(b'.')
1858 quick_data = self._quick_access_changeid.get(b'.')
1844 if quick_data is not None:
1859 if quick_data is not None:
1845 return revset.baseset([quick_data[0]])
1860 return revset.baseset([quick_data[0]])
1846 if user:
1861 if user:
1847 m = revset.matchany(
1862 m = revset.matchany(
1848 self.ui,
1863 self.ui,
1849 specs,
1864 specs,
1850 lookup=revset.lookupfn(self),
1865 lookup=revset.lookupfn(self),
1851 localalias=localalias,
1866 localalias=localalias,
1852 )
1867 )
1853 else:
1868 else:
1854 m = revset.matchany(None, specs, localalias=localalias)
1869 m = revset.matchany(None, specs, localalias=localalias)
1855 return m(self)
1870 return m(self)
1856
1871
1857 def url(self):
1872 def url(self):
1858 return b'file:' + self.root
1873 return b'file:' + self.root
1859
1874
1860 def hook(self, name, throw=False, **args):
1875 def hook(self, name, throw=False, **args):
1861 """Call a hook, passing this repo instance.
1876 """Call a hook, passing this repo instance.
1862
1877
1863 This a convenience method to aid invoking hooks. Extensions likely
1878 This a convenience method to aid invoking hooks. Extensions likely
1864 won't call this unless they have registered a custom hook or are
1879 won't call this unless they have registered a custom hook or are
1865 replacing code that is expected to call a hook.
1880 replacing code that is expected to call a hook.
1866 """
1881 """
1867 return hook.hook(self.ui, self, name, throw, **args)
1882 return hook.hook(self.ui, self, name, throw, **args)
1868
1883
1869 @filteredpropertycache
1884 @filteredpropertycache
1870 def _tagscache(self):
1885 def _tagscache(self):
1871 """Returns a tagscache object that contains various tags related
1886 """Returns a tagscache object that contains various tags related
1872 caches."""
1887 caches."""
1873
1888
1874 # This simplifies its cache management by having one decorated
1889 # This simplifies its cache management by having one decorated
1875 # function (this one) and the rest simply fetch things from it.
1890 # function (this one) and the rest simply fetch things from it.
1876 class tagscache(object):
1891 class tagscache(object):
1877 def __init__(self):
1892 def __init__(self):
1878 # These two define the set of tags for this repository. tags
1893 # These two define the set of tags for this repository. tags
1879 # maps tag name to node; tagtypes maps tag name to 'global' or
1894 # maps tag name to node; tagtypes maps tag name to 'global' or
1880 # 'local'. (Global tags are defined by .hgtags across all
1895 # 'local'. (Global tags are defined by .hgtags across all
1881 # heads, and local tags are defined in .hg/localtags.)
1896 # heads, and local tags are defined in .hg/localtags.)
1882 # They constitute the in-memory cache of tags.
1897 # They constitute the in-memory cache of tags.
1883 self.tags = self.tagtypes = None
1898 self.tags = self.tagtypes = None
1884
1899
1885 self.nodetagscache = self.tagslist = None
1900 self.nodetagscache = self.tagslist = None
1886
1901
1887 cache = tagscache()
1902 cache = tagscache()
1888 cache.tags, cache.tagtypes = self._findtags()
1903 cache.tags, cache.tagtypes = self._findtags()
1889
1904
1890 return cache
1905 return cache
1891
1906
1892 def tags(self):
1907 def tags(self):
1893 '''return a mapping of tag to node'''
1908 '''return a mapping of tag to node'''
1894 t = {}
1909 t = {}
1895 if self.changelog.filteredrevs:
1910 if self.changelog.filteredrevs:
1896 tags, tt = self._findtags()
1911 tags, tt = self._findtags()
1897 else:
1912 else:
1898 tags = self._tagscache.tags
1913 tags = self._tagscache.tags
1899 rev = self.changelog.rev
1914 rev = self.changelog.rev
1900 for k, v in pycompat.iteritems(tags):
1915 for k, v in pycompat.iteritems(tags):
1901 try:
1916 try:
1902 # ignore tags to unknown nodes
1917 # ignore tags to unknown nodes
1903 rev(v)
1918 rev(v)
1904 t[k] = v
1919 t[k] = v
1905 except (error.LookupError, ValueError):
1920 except (error.LookupError, ValueError):
1906 pass
1921 pass
1907 return t
1922 return t
1908
1923
1909 def _findtags(self):
1924 def _findtags(self):
1910 """Do the hard work of finding tags. Return a pair of dicts
1925 """Do the hard work of finding tags. Return a pair of dicts
1911 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1926 (tags, tagtypes) where tags maps tag name to node, and tagtypes
1912 maps tag name to a string like \'global\' or \'local\'.
1927 maps tag name to a string like \'global\' or \'local\'.
1913 Subclasses or extensions are free to add their own tags, but
1928 Subclasses or extensions are free to add their own tags, but
1914 should be aware that the returned dicts will be retained for the
1929 should be aware that the returned dicts will be retained for the
1915 duration of the localrepo object."""
1930 duration of the localrepo object."""
1916
1931
1917 # XXX what tagtype should subclasses/extensions use? Currently
1932 # XXX what tagtype should subclasses/extensions use? Currently
1918 # mq and bookmarks add tags, but do not set the tagtype at all.
1933 # mq and bookmarks add tags, but do not set the tagtype at all.
1919 # Should each extension invent its own tag type? Should there
1934 # Should each extension invent its own tag type? Should there
1920 # be one tagtype for all such "virtual" tags? Or is the status
1935 # be one tagtype for all such "virtual" tags? Or is the status
1921 # quo fine?
1936 # quo fine?
1922
1937
1923 # map tag name to (node, hist)
1938 # map tag name to (node, hist)
1924 alltags = tagsmod.findglobaltags(self.ui, self)
1939 alltags = tagsmod.findglobaltags(self.ui, self)
1925 # map tag name to tag type
1940 # map tag name to tag type
1926 tagtypes = {tag: b'global' for tag in alltags}
1941 tagtypes = {tag: b'global' for tag in alltags}
1927
1942
1928 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1943 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1929
1944
1930 # Build the return dicts. Have to re-encode tag names because
1945 # Build the return dicts. Have to re-encode tag names because
1931 # the tags module always uses UTF-8 (in order not to lose info
1946 # the tags module always uses UTF-8 (in order not to lose info
1932 # writing to the cache), but the rest of Mercurial wants them in
1947 # writing to the cache), but the rest of Mercurial wants them in
1933 # local encoding.
1948 # local encoding.
1934 tags = {}
1949 tags = {}
1935 for (name, (node, hist)) in pycompat.iteritems(alltags):
1950 for (name, (node, hist)) in pycompat.iteritems(alltags):
1936 if node != nullid:
1951 if node != nullid:
1937 tags[encoding.tolocal(name)] = node
1952 tags[encoding.tolocal(name)] = node
1938 tags[b'tip'] = self.changelog.tip()
1953 tags[b'tip'] = self.changelog.tip()
1939 tagtypes = {
1954 tagtypes = {
1940 encoding.tolocal(name): value
1955 encoding.tolocal(name): value
1941 for (name, value) in pycompat.iteritems(tagtypes)
1956 for (name, value) in pycompat.iteritems(tagtypes)
1942 }
1957 }
1943 return (tags, tagtypes)
1958 return (tags, tagtypes)
1944
1959
1945 def tagtype(self, tagname):
1960 def tagtype(self, tagname):
1946 """
1961 """
1947 return the type of the given tag. result can be:
1962 return the type of the given tag. result can be:
1948
1963
1949 'local' : a local tag
1964 'local' : a local tag
1950 'global' : a global tag
1965 'global' : a global tag
1951 None : tag does not exist
1966 None : tag does not exist
1952 """
1967 """
1953
1968
1954 return self._tagscache.tagtypes.get(tagname)
1969 return self._tagscache.tagtypes.get(tagname)
1955
1970
1956 def tagslist(self):
1971 def tagslist(self):
1957 '''return a list of tags ordered by revision'''
1972 '''return a list of tags ordered by revision'''
1958 if not self._tagscache.tagslist:
1973 if not self._tagscache.tagslist:
1959 l = []
1974 l = []
1960 for t, n in pycompat.iteritems(self.tags()):
1975 for t, n in pycompat.iteritems(self.tags()):
1961 l.append((self.changelog.rev(n), t, n))
1976 l.append((self.changelog.rev(n), t, n))
1962 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1977 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1963
1978
1964 return self._tagscache.tagslist
1979 return self._tagscache.tagslist
1965
1980
1966 def nodetags(self, node):
1981 def nodetags(self, node):
1967 '''return the tags associated with a node'''
1982 '''return the tags associated with a node'''
1968 if not self._tagscache.nodetagscache:
1983 if not self._tagscache.nodetagscache:
1969 nodetagscache = {}
1984 nodetagscache = {}
1970 for t, n in pycompat.iteritems(self._tagscache.tags):
1985 for t, n in pycompat.iteritems(self._tagscache.tags):
1971 nodetagscache.setdefault(n, []).append(t)
1986 nodetagscache.setdefault(n, []).append(t)
1972 for tags in pycompat.itervalues(nodetagscache):
1987 for tags in pycompat.itervalues(nodetagscache):
1973 tags.sort()
1988 tags.sort()
1974 self._tagscache.nodetagscache = nodetagscache
1989 self._tagscache.nodetagscache = nodetagscache
1975 return self._tagscache.nodetagscache.get(node, [])
1990 return self._tagscache.nodetagscache.get(node, [])
1976
1991
1977 def nodebookmarks(self, node):
1992 def nodebookmarks(self, node):
1978 """return the list of bookmarks pointing to the specified node"""
1993 """return the list of bookmarks pointing to the specified node"""
1979 return self._bookmarks.names(node)
1994 return self._bookmarks.names(node)
1980
1995
1981 def branchmap(self):
1996 def branchmap(self):
1982 """returns a dictionary {branch: [branchheads]} with branchheads
1997 """returns a dictionary {branch: [branchheads]} with branchheads
1983 ordered by increasing revision number"""
1998 ordered by increasing revision number"""
1984 return self._branchcaches[self]
1999 return self._branchcaches[self]
1985
2000
1986 @unfilteredmethod
2001 @unfilteredmethod
1987 def revbranchcache(self):
2002 def revbranchcache(self):
1988 if not self._revbranchcache:
2003 if not self._revbranchcache:
1989 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
2004 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1990 return self._revbranchcache
2005 return self._revbranchcache
1991
2006
1992 def branchtip(self, branch, ignoremissing=False):
2007 def branchtip(self, branch, ignoremissing=False):
1993 """return the tip node for a given branch
2008 """return the tip node for a given branch
1994
2009
1995 If ignoremissing is True, then this method will not raise an error.
2010 If ignoremissing is True, then this method will not raise an error.
1996 This is helpful for callers that only expect None for a missing branch
2011 This is helpful for callers that only expect None for a missing branch
1997 (e.g. namespace).
2012 (e.g. namespace).
1998
2013
1999 """
2014 """
2000 try:
2015 try:
2001 return self.branchmap().branchtip(branch)
2016 return self.branchmap().branchtip(branch)
2002 except KeyError:
2017 except KeyError:
2003 if not ignoremissing:
2018 if not ignoremissing:
2004 raise error.RepoLookupError(_(b"unknown branch '%s'") % branch)
2019 raise error.RepoLookupError(_(b"unknown branch '%s'") % branch)
2005 else:
2020 else:
2006 pass
2021 pass
2007
2022
2008 def lookup(self, key):
2023 def lookup(self, key):
2009 node = scmutil.revsymbol(self, key).node()
2024 node = scmutil.revsymbol(self, key).node()
2010 if node is None:
2025 if node is None:
2011 raise error.RepoLookupError(_(b"unknown revision '%s'") % key)
2026 raise error.RepoLookupError(_(b"unknown revision '%s'") % key)
2012 return node
2027 return node
2013
2028
2014 def lookupbranch(self, key):
2029 def lookupbranch(self, key):
2015 if self.branchmap().hasbranch(key):
2030 if self.branchmap().hasbranch(key):
2016 return key
2031 return key
2017
2032
2018 return scmutil.revsymbol(self, key).branch()
2033 return scmutil.revsymbol(self, key).branch()
2019
2034
2020 def known(self, nodes):
2035 def known(self, nodes):
2021 cl = self.changelog
2036 cl = self.changelog
2022 get_rev = cl.index.get_rev
2037 get_rev = cl.index.get_rev
2023 filtered = cl.filteredrevs
2038 filtered = cl.filteredrevs
2024 result = []
2039 result = []
2025 for n in nodes:
2040 for n in nodes:
2026 r = get_rev(n)
2041 r = get_rev(n)
2027 resp = not (r is None or r in filtered)
2042 resp = not (r is None or r in filtered)
2028 result.append(resp)
2043 result.append(resp)
2029 return result
2044 return result
2030
2045
2031 def local(self):
2046 def local(self):
2032 return self
2047 return self
2033
2048
2034 def publishing(self):
2049 def publishing(self):
2035 # it's safe (and desirable) to trust the publish flag unconditionally
2050 # it's safe (and desirable) to trust the publish flag unconditionally
2036 # so that we don't finalize changes shared between users via ssh or nfs
2051 # so that we don't finalize changes shared between users via ssh or nfs
2037 return self.ui.configbool(b'phases', b'publish', untrusted=True)
2052 return self.ui.configbool(b'phases', b'publish', untrusted=True)
2038
2053
2039 def cancopy(self):
2054 def cancopy(self):
2040 # so statichttprepo's override of local() works
2055 # so statichttprepo's override of local() works
2041 if not self.local():
2056 if not self.local():
2042 return False
2057 return False
2043 if not self.publishing():
2058 if not self.publishing():
2044 return True
2059 return True
2045 # if publishing we can't copy if there is filtered content
2060 # if publishing we can't copy if there is filtered content
2046 return not self.filtered(b'visible').changelog.filteredrevs
2061 return not self.filtered(b'visible').changelog.filteredrevs
2047
2062
2048 def shared(self):
2063 def shared(self):
2049 '''the type of shared repository (None if not shared)'''
2064 '''the type of shared repository (None if not shared)'''
2050 if self.sharedpath != self.path:
2065 if self.sharedpath != self.path:
2051 return b'store'
2066 return b'store'
2052 return None
2067 return None
2053
2068
2054 def wjoin(self, f, *insidef):
2069 def wjoin(self, f, *insidef):
2055 return self.vfs.reljoin(self.root, f, *insidef)
2070 return self.vfs.reljoin(self.root, f, *insidef)
2056
2071
2057 def setparents(self, p1, p2=nullid):
2072 def setparents(self, p1, p2=nullid):
2058 self[None].setparents(p1, p2)
2073 self[None].setparents(p1, p2)
2059 self._quick_access_changeid_invalidate()
2074 self._quick_access_changeid_invalidate()
2060
2075
2061 def filectx(self, path, changeid=None, fileid=None, changectx=None):
2076 def filectx(self, path, changeid=None, fileid=None, changectx=None):
2062 """changeid must be a changeset revision, if specified.
2077 """changeid must be a changeset revision, if specified.
2063 fileid can be a file revision or node."""
2078 fileid can be a file revision or node."""
2064 return context.filectx(
2079 return context.filectx(
2065 self, path, changeid, fileid, changectx=changectx
2080 self, path, changeid, fileid, changectx=changectx
2066 )
2081 )
2067
2082
2068 def getcwd(self):
2083 def getcwd(self):
2069 return self.dirstate.getcwd()
2084 return self.dirstate.getcwd()
2070
2085
2071 def pathto(self, f, cwd=None):
2086 def pathto(self, f, cwd=None):
2072 return self.dirstate.pathto(f, cwd)
2087 return self.dirstate.pathto(f, cwd)
2073
2088
2074 def _loadfilter(self, filter):
2089 def _loadfilter(self, filter):
2075 if filter not in self._filterpats:
2090 if filter not in self._filterpats:
2076 l = []
2091 l = []
2077 for pat, cmd in self.ui.configitems(filter):
2092 for pat, cmd in self.ui.configitems(filter):
2078 if cmd == b'!':
2093 if cmd == b'!':
2079 continue
2094 continue
2080 mf = matchmod.match(self.root, b'', [pat])
2095 mf = matchmod.match(self.root, b'', [pat])
2081 fn = None
2096 fn = None
2082 params = cmd
2097 params = cmd
2083 for name, filterfn in pycompat.iteritems(self._datafilters):
2098 for name, filterfn in pycompat.iteritems(self._datafilters):
2084 if cmd.startswith(name):
2099 if cmd.startswith(name):
2085 fn = filterfn
2100 fn = filterfn
2086 params = cmd[len(name) :].lstrip()
2101 params = cmd[len(name) :].lstrip()
2087 break
2102 break
2088 if not fn:
2103 if not fn:
2089 fn = lambda s, c, **kwargs: procutil.filter(s, c)
2104 fn = lambda s, c, **kwargs: procutil.filter(s, c)
2090 fn.__name__ = 'commandfilter'
2105 fn.__name__ = 'commandfilter'
2091 # Wrap old filters not supporting keyword arguments
2106 # Wrap old filters not supporting keyword arguments
2092 if not pycompat.getargspec(fn)[2]:
2107 if not pycompat.getargspec(fn)[2]:
2093 oldfn = fn
2108 oldfn = fn
2094 fn = lambda s, c, oldfn=oldfn, **kwargs: oldfn(s, c)
2109 fn = lambda s, c, oldfn=oldfn, **kwargs: oldfn(s, c)
2095 fn.__name__ = 'compat-' + oldfn.__name__
2110 fn.__name__ = 'compat-' + oldfn.__name__
2096 l.append((mf, fn, params))
2111 l.append((mf, fn, params))
2097 self._filterpats[filter] = l
2112 self._filterpats[filter] = l
2098 return self._filterpats[filter]
2113 return self._filterpats[filter]
2099
2114
2100 def _filter(self, filterpats, filename, data):
2115 def _filter(self, filterpats, filename, data):
2101 for mf, fn, cmd in filterpats:
2116 for mf, fn, cmd in filterpats:
2102 if mf(filename):
2117 if mf(filename):
2103 self.ui.debug(
2118 self.ui.debug(
2104 b"filtering %s through %s\n"
2119 b"filtering %s through %s\n"
2105 % (filename, cmd or pycompat.sysbytes(fn.__name__))
2120 % (filename, cmd or pycompat.sysbytes(fn.__name__))
2106 )
2121 )
2107 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
2122 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
2108 break
2123 break
2109
2124
2110 return data
2125 return data
2111
2126
2112 @unfilteredpropertycache
2127 @unfilteredpropertycache
2113 def _encodefilterpats(self):
2128 def _encodefilterpats(self):
2114 return self._loadfilter(b'encode')
2129 return self._loadfilter(b'encode')
2115
2130
2116 @unfilteredpropertycache
2131 @unfilteredpropertycache
2117 def _decodefilterpats(self):
2132 def _decodefilterpats(self):
2118 return self._loadfilter(b'decode')
2133 return self._loadfilter(b'decode')
2119
2134
2120 def adddatafilter(self, name, filter):
2135 def adddatafilter(self, name, filter):
2121 self._datafilters[name] = filter
2136 self._datafilters[name] = filter
2122
2137
2123 def wread(self, filename):
2138 def wread(self, filename):
2124 if self.wvfs.islink(filename):
2139 if self.wvfs.islink(filename):
2125 data = self.wvfs.readlink(filename)
2140 data = self.wvfs.readlink(filename)
2126 else:
2141 else:
2127 data = self.wvfs.read(filename)
2142 data = self.wvfs.read(filename)
2128 return self._filter(self._encodefilterpats, filename, data)
2143 return self._filter(self._encodefilterpats, filename, data)
2129
2144
2130 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
2145 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
2131 """write ``data`` into ``filename`` in the working directory
2146 """write ``data`` into ``filename`` in the working directory
2132
2147
2133 This returns length of written (maybe decoded) data.
2148 This returns length of written (maybe decoded) data.
2134 """
2149 """
2135 data = self._filter(self._decodefilterpats, filename, data)
2150 data = self._filter(self._decodefilterpats, filename, data)
2136 if b'l' in flags:
2151 if b'l' in flags:
2137 self.wvfs.symlink(data, filename)
2152 self.wvfs.symlink(data, filename)
2138 else:
2153 else:
2139 self.wvfs.write(
2154 self.wvfs.write(
2140 filename, data, backgroundclose=backgroundclose, **kwargs
2155 filename, data, backgroundclose=backgroundclose, **kwargs
2141 )
2156 )
2142 if b'x' in flags:
2157 if b'x' in flags:
2143 self.wvfs.setflags(filename, False, True)
2158 self.wvfs.setflags(filename, False, True)
2144 else:
2159 else:
2145 self.wvfs.setflags(filename, False, False)
2160 self.wvfs.setflags(filename, False, False)
2146 return len(data)
2161 return len(data)
2147
2162
2148 def wwritedata(self, filename, data):
2163 def wwritedata(self, filename, data):
2149 return self._filter(self._decodefilterpats, filename, data)
2164 return self._filter(self._decodefilterpats, filename, data)
2150
2165
2151 def currenttransaction(self):
2166 def currenttransaction(self):
2152 """return the current transaction or None if non exists"""
2167 """return the current transaction or None if non exists"""
2153 if self._transref:
2168 if self._transref:
2154 tr = self._transref()
2169 tr = self._transref()
2155 else:
2170 else:
2156 tr = None
2171 tr = None
2157
2172
2158 if tr and tr.running():
2173 if tr and tr.running():
2159 return tr
2174 return tr
2160 return None
2175 return None
2161
2176
2162 def transaction(self, desc, report=None):
2177 def transaction(self, desc, report=None):
2163 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
2178 if self.ui.configbool(b'devel', b'all-warnings') or self.ui.configbool(
2164 b'devel', b'check-locks'
2179 b'devel', b'check-locks'
2165 ):
2180 ):
2166 if self._currentlock(self._lockref) is None:
2181 if self._currentlock(self._lockref) is None:
2167 raise error.ProgrammingError(b'transaction requires locking')
2182 raise error.ProgrammingError(b'transaction requires locking')
2168 tr = self.currenttransaction()
2183 tr = self.currenttransaction()
2169 if tr is not None:
2184 if tr is not None:
2170 return tr.nest(name=desc)
2185 return tr.nest(name=desc)
2171
2186
2172 # abort here if the journal already exists
2187 # abort here if the journal already exists
2173 if self.svfs.exists(b"journal"):
2188 if self.svfs.exists(b"journal"):
2174 raise error.RepoError(
2189 raise error.RepoError(
2175 _(b"abandoned transaction found"),
2190 _(b"abandoned transaction found"),
2176 hint=_(b"run 'hg recover' to clean up transaction"),
2191 hint=_(b"run 'hg recover' to clean up transaction"),
2177 )
2192 )
2178
2193
2179 idbase = b"%.40f#%f" % (random.random(), time.time())
2194 idbase = b"%.40f#%f" % (random.random(), time.time())
2180 ha = hex(hashutil.sha1(idbase).digest())
2195 ha = hex(hashutil.sha1(idbase).digest())
2181 txnid = b'TXN:' + ha
2196 txnid = b'TXN:' + ha
2182 self.hook(b'pretxnopen', throw=True, txnname=desc, txnid=txnid)
2197 self.hook(b'pretxnopen', throw=True, txnname=desc, txnid=txnid)
2183
2198
2184 self._writejournal(desc)
2199 self._writejournal(desc)
2185 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
2200 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
2186 if report:
2201 if report:
2187 rp = report
2202 rp = report
2188 else:
2203 else:
2189 rp = self.ui.warn
2204 rp = self.ui.warn
2190 vfsmap = {b'plain': self.vfs, b'store': self.svfs} # root of .hg/
2205 vfsmap = {b'plain': self.vfs, b'store': self.svfs} # root of .hg/
2191 # we must avoid cyclic reference between repo and transaction.
2206 # we must avoid cyclic reference between repo and transaction.
2192 reporef = weakref.ref(self)
2207 reporef = weakref.ref(self)
2193 # Code to track tag movement
2208 # Code to track tag movement
2194 #
2209 #
2195 # Since tags are all handled as file content, it is actually quite hard
2210 # Since tags are all handled as file content, it is actually quite hard
2196 # to track these movement from a code perspective. So we fallback to a
2211 # to track these movement from a code perspective. So we fallback to a
2197 # tracking at the repository level. One could envision to track changes
2212 # tracking at the repository level. One could envision to track changes
2198 # to the '.hgtags' file through changegroup apply but that fails to
2213 # to the '.hgtags' file through changegroup apply but that fails to
2199 # cope with case where transaction expose new heads without changegroup
2214 # cope with case where transaction expose new heads without changegroup
2200 # being involved (eg: phase movement).
2215 # being involved (eg: phase movement).
2201 #
2216 #
2202 # For now, We gate the feature behind a flag since this likely comes
2217 # For now, We gate the feature behind a flag since this likely comes
2203 # with performance impacts. The current code run more often than needed
2218 # with performance impacts. The current code run more often than needed
2204 # and do not use caches as much as it could. The current focus is on
2219 # and do not use caches as much as it could. The current focus is on
2205 # the behavior of the feature so we disable it by default. The flag
2220 # the behavior of the feature so we disable it by default. The flag
2206 # will be removed when we are happy with the performance impact.
2221 # will be removed when we are happy with the performance impact.
2207 #
2222 #
2208 # Once this feature is no longer experimental move the following
2223 # Once this feature is no longer experimental move the following
2209 # documentation to the appropriate help section:
2224 # documentation to the appropriate help section:
2210 #
2225 #
2211 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
2226 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
2212 # tags (new or changed or deleted tags). In addition the details of
2227 # tags (new or changed or deleted tags). In addition the details of
2213 # these changes are made available in a file at:
2228 # these changes are made available in a file at:
2214 # ``REPOROOT/.hg/changes/tags.changes``.
2229 # ``REPOROOT/.hg/changes/tags.changes``.
2215 # Make sure you check for HG_TAG_MOVED before reading that file as it
2230 # Make sure you check for HG_TAG_MOVED before reading that file as it
2216 # might exist from a previous transaction even if no tag were touched
2231 # might exist from a previous transaction even if no tag were touched
2217 # in this one. Changes are recorded in a line base format::
2232 # in this one. Changes are recorded in a line base format::
2218 #
2233 #
2219 # <action> <hex-node> <tag-name>\n
2234 # <action> <hex-node> <tag-name>\n
2220 #
2235 #
2221 # Actions are defined as follow:
2236 # Actions are defined as follow:
2222 # "-R": tag is removed,
2237 # "-R": tag is removed,
2223 # "+A": tag is added,
2238 # "+A": tag is added,
2224 # "-M": tag is moved (old value),
2239 # "-M": tag is moved (old value),
2225 # "+M": tag is moved (new value),
2240 # "+M": tag is moved (new value),
2226 tracktags = lambda x: None
2241 tracktags = lambda x: None
2227 # experimental config: experimental.hook-track-tags
2242 # experimental config: experimental.hook-track-tags
2228 shouldtracktags = self.ui.configbool(
2243 shouldtracktags = self.ui.configbool(
2229 b'experimental', b'hook-track-tags'
2244 b'experimental', b'hook-track-tags'
2230 )
2245 )
2231 if desc != b'strip' and shouldtracktags:
2246 if desc != b'strip' and shouldtracktags:
2232 oldheads = self.changelog.headrevs()
2247 oldheads = self.changelog.headrevs()
2233
2248
2234 def tracktags(tr2):
2249 def tracktags(tr2):
2235 repo = reporef()
2250 repo = reporef()
2236 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
2251 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
2237 newheads = repo.changelog.headrevs()
2252 newheads = repo.changelog.headrevs()
2238 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
2253 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
2239 # notes: we compare lists here.
2254 # notes: we compare lists here.
2240 # As we do it only once buiding set would not be cheaper
2255 # As we do it only once buiding set would not be cheaper
2241 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
2256 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
2242 if changes:
2257 if changes:
2243 tr2.hookargs[b'tag_moved'] = b'1'
2258 tr2.hookargs[b'tag_moved'] = b'1'
2244 with repo.vfs(
2259 with repo.vfs(
2245 b'changes/tags.changes', b'w', atomictemp=True
2260 b'changes/tags.changes', b'w', atomictemp=True
2246 ) as changesfile:
2261 ) as changesfile:
2247 # note: we do not register the file to the transaction
2262 # note: we do not register the file to the transaction
2248 # because we needs it to still exist on the transaction
2263 # because we needs it to still exist on the transaction
2249 # is close (for txnclose hooks)
2264 # is close (for txnclose hooks)
2250 tagsmod.writediff(changesfile, changes)
2265 tagsmod.writediff(changesfile, changes)
2251
2266
2252 def validate(tr2):
2267 def validate(tr2):
2253 """will run pre-closing hooks"""
2268 """will run pre-closing hooks"""
2254 # XXX the transaction API is a bit lacking here so we take a hacky
2269 # XXX the transaction API is a bit lacking here so we take a hacky
2255 # path for now
2270 # path for now
2256 #
2271 #
2257 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
2272 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
2258 # dict is copied before these run. In addition we needs the data
2273 # dict is copied before these run. In addition we needs the data
2259 # available to in memory hooks too.
2274 # available to in memory hooks too.
2260 #
2275 #
2261 # Moreover, we also need to make sure this runs before txnclose
2276 # Moreover, we also need to make sure this runs before txnclose
2262 # hooks and there is no "pending" mechanism that would execute
2277 # hooks and there is no "pending" mechanism that would execute
2263 # logic only if hooks are about to run.
2278 # logic only if hooks are about to run.
2264 #
2279 #
2265 # Fixing this limitation of the transaction is also needed to track
2280 # Fixing this limitation of the transaction is also needed to track
2266 # other families of changes (bookmarks, phases, obsolescence).
2281 # other families of changes (bookmarks, phases, obsolescence).
2267 #
2282 #
2268 # This will have to be fixed before we remove the experimental
2283 # This will have to be fixed before we remove the experimental
2269 # gating.
2284 # gating.
2270 tracktags(tr2)
2285 tracktags(tr2)
2271 repo = reporef()
2286 repo = reporef()
2272
2287
2273 singleheadopt = (b'experimental', b'single-head-per-branch')
2288 singleheadopt = (b'experimental', b'single-head-per-branch')
2274 singlehead = repo.ui.configbool(*singleheadopt)
2289 singlehead = repo.ui.configbool(*singleheadopt)
2275 if singlehead:
2290 if singlehead:
2276 singleheadsub = repo.ui.configsuboptions(*singleheadopt)[1]
2291 singleheadsub = repo.ui.configsuboptions(*singleheadopt)[1]
2277 accountclosed = singleheadsub.get(
2292 accountclosed = singleheadsub.get(
2278 b"account-closed-heads", False
2293 b"account-closed-heads", False
2279 )
2294 )
2280 if singleheadsub.get(b"public-changes-only", False):
2295 if singleheadsub.get(b"public-changes-only", False):
2281 filtername = b"immutable"
2296 filtername = b"immutable"
2282 else:
2297 else:
2283 filtername = b"visible"
2298 filtername = b"visible"
2284 scmutil.enforcesinglehead(
2299 scmutil.enforcesinglehead(
2285 repo, tr2, desc, accountclosed, filtername
2300 repo, tr2, desc, accountclosed, filtername
2286 )
2301 )
2287 if hook.hashook(repo.ui, b'pretxnclose-bookmark'):
2302 if hook.hashook(repo.ui, b'pretxnclose-bookmark'):
2288 for name, (old, new) in sorted(
2303 for name, (old, new) in sorted(
2289 tr.changes[b'bookmarks'].items()
2304 tr.changes[b'bookmarks'].items()
2290 ):
2305 ):
2291 args = tr.hookargs.copy()
2306 args = tr.hookargs.copy()
2292 args.update(bookmarks.preparehookargs(name, old, new))
2307 args.update(bookmarks.preparehookargs(name, old, new))
2293 repo.hook(
2308 repo.hook(
2294 b'pretxnclose-bookmark',
2309 b'pretxnclose-bookmark',
2295 throw=True,
2310 throw=True,
2296 **pycompat.strkwargs(args)
2311 **pycompat.strkwargs(args)
2297 )
2312 )
2298 if hook.hashook(repo.ui, b'pretxnclose-phase'):
2313 if hook.hashook(repo.ui, b'pretxnclose-phase'):
2299 cl = repo.unfiltered().changelog
2314 cl = repo.unfiltered().changelog
2300 for revs, (old, new) in tr.changes[b'phases']:
2315 for revs, (old, new) in tr.changes[b'phases']:
2301 for rev in revs:
2316 for rev in revs:
2302 args = tr.hookargs.copy()
2317 args = tr.hookargs.copy()
2303 node = hex(cl.node(rev))
2318 node = hex(cl.node(rev))
2304 args.update(phases.preparehookargs(node, old, new))
2319 args.update(phases.preparehookargs(node, old, new))
2305 repo.hook(
2320 repo.hook(
2306 b'pretxnclose-phase',
2321 b'pretxnclose-phase',
2307 throw=True,
2322 throw=True,
2308 **pycompat.strkwargs(args)
2323 **pycompat.strkwargs(args)
2309 )
2324 )
2310
2325
2311 repo.hook(
2326 repo.hook(
2312 b'pretxnclose', throw=True, **pycompat.strkwargs(tr.hookargs)
2327 b'pretxnclose', throw=True, **pycompat.strkwargs(tr.hookargs)
2313 )
2328 )
2314
2329
2315 def releasefn(tr, success):
2330 def releasefn(tr, success):
2316 repo = reporef()
2331 repo = reporef()
2317 if repo is None:
2332 if repo is None:
2318 # If the repo has been GC'd (and this release function is being
2333 # If the repo has been GC'd (and this release function is being
2319 # called from transaction.__del__), there's not much we can do,
2334 # called from transaction.__del__), there's not much we can do,
2320 # so just leave the unfinished transaction there and let the
2335 # so just leave the unfinished transaction there and let the
2321 # user run `hg recover`.
2336 # user run `hg recover`.
2322 return
2337 return
2323 if success:
2338 if success:
2324 # this should be explicitly invoked here, because
2339 # this should be explicitly invoked here, because
2325 # in-memory changes aren't written out at closing
2340 # in-memory changes aren't written out at closing
2326 # transaction, if tr.addfilegenerator (via
2341 # transaction, if tr.addfilegenerator (via
2327 # dirstate.write or so) isn't invoked while
2342 # dirstate.write or so) isn't invoked while
2328 # transaction running
2343 # transaction running
2329 repo.dirstate.write(None)
2344 repo.dirstate.write(None)
2330 else:
2345 else:
2331 # discard all changes (including ones already written
2346 # discard all changes (including ones already written
2332 # out) in this transaction
2347 # out) in this transaction
2333 narrowspec.restorebackup(self, b'journal.narrowspec')
2348 narrowspec.restorebackup(self, b'journal.narrowspec')
2334 narrowspec.restorewcbackup(self, b'journal.narrowspec.dirstate')
2349 narrowspec.restorewcbackup(self, b'journal.narrowspec.dirstate')
2335 repo.dirstate.restorebackup(None, b'journal.dirstate')
2350 repo.dirstate.restorebackup(None, b'journal.dirstate')
2336
2351
2337 repo.invalidate(clearfilecache=True)
2352 repo.invalidate(clearfilecache=True)
2338
2353
2339 tr = transaction.transaction(
2354 tr = transaction.transaction(
2340 rp,
2355 rp,
2341 self.svfs,
2356 self.svfs,
2342 vfsmap,
2357 vfsmap,
2343 b"journal",
2358 b"journal",
2344 b"undo",
2359 b"undo",
2345 aftertrans(renames),
2360 aftertrans(renames),
2346 self.store.createmode,
2361 self.store.createmode,
2347 validator=validate,
2362 validator=validate,
2348 releasefn=releasefn,
2363 releasefn=releasefn,
2349 checkambigfiles=_cachedfiles,
2364 checkambigfiles=_cachedfiles,
2350 name=desc,
2365 name=desc,
2351 )
2366 )
2352 tr.changes[b'origrepolen'] = len(self)
2367 tr.changes[b'origrepolen'] = len(self)
2353 tr.changes[b'obsmarkers'] = set()
2368 tr.changes[b'obsmarkers'] = set()
2354 tr.changes[b'phases'] = []
2369 tr.changes[b'phases'] = []
2355 tr.changes[b'bookmarks'] = {}
2370 tr.changes[b'bookmarks'] = {}
2356
2371
2357 tr.hookargs[b'txnid'] = txnid
2372 tr.hookargs[b'txnid'] = txnid
2358 tr.hookargs[b'txnname'] = desc
2373 tr.hookargs[b'txnname'] = desc
2359 tr.hookargs[b'changes'] = tr.changes
2374 tr.hookargs[b'changes'] = tr.changes
2360 # note: writing the fncache only during finalize mean that the file is
2375 # note: writing the fncache only during finalize mean that the file is
2361 # outdated when running hooks. As fncache is used for streaming clone,
2376 # outdated when running hooks. As fncache is used for streaming clone,
2362 # this is not expected to break anything that happen during the hooks.
2377 # this is not expected to break anything that happen during the hooks.
2363 tr.addfinalize(b'flush-fncache', self.store.write)
2378 tr.addfinalize(b'flush-fncache', self.store.write)
2364
2379
2365 def txnclosehook(tr2):
2380 def txnclosehook(tr2):
2366 """To be run if transaction is successful, will schedule a hook run"""
2381 """To be run if transaction is successful, will schedule a hook run"""
2367 # Don't reference tr2 in hook() so we don't hold a reference.
2382 # Don't reference tr2 in hook() so we don't hold a reference.
2368 # This reduces memory consumption when there are multiple
2383 # This reduces memory consumption when there are multiple
2369 # transactions per lock. This can likely go away if issue5045
2384 # transactions per lock. This can likely go away if issue5045
2370 # fixes the function accumulation.
2385 # fixes the function accumulation.
2371 hookargs = tr2.hookargs
2386 hookargs = tr2.hookargs
2372
2387
2373 def hookfunc(unused_success):
2388 def hookfunc(unused_success):
2374 repo = reporef()
2389 repo = reporef()
2375 if hook.hashook(repo.ui, b'txnclose-bookmark'):
2390 if hook.hashook(repo.ui, b'txnclose-bookmark'):
2376 bmchanges = sorted(tr.changes[b'bookmarks'].items())
2391 bmchanges = sorted(tr.changes[b'bookmarks'].items())
2377 for name, (old, new) in bmchanges:
2392 for name, (old, new) in bmchanges:
2378 args = tr.hookargs.copy()
2393 args = tr.hookargs.copy()
2379 args.update(bookmarks.preparehookargs(name, old, new))
2394 args.update(bookmarks.preparehookargs(name, old, new))
2380 repo.hook(
2395 repo.hook(
2381 b'txnclose-bookmark',
2396 b'txnclose-bookmark',
2382 throw=False,
2397 throw=False,
2383 **pycompat.strkwargs(args)
2398 **pycompat.strkwargs(args)
2384 )
2399 )
2385
2400
2386 if hook.hashook(repo.ui, b'txnclose-phase'):
2401 if hook.hashook(repo.ui, b'txnclose-phase'):
2387 cl = repo.unfiltered().changelog
2402 cl = repo.unfiltered().changelog
2388 phasemv = sorted(
2403 phasemv = sorted(
2389 tr.changes[b'phases'], key=lambda r: r[0][0]
2404 tr.changes[b'phases'], key=lambda r: r[0][0]
2390 )
2405 )
2391 for revs, (old, new) in phasemv:
2406 for revs, (old, new) in phasemv:
2392 for rev in revs:
2407 for rev in revs:
2393 args = tr.hookargs.copy()
2408 args = tr.hookargs.copy()
2394 node = hex(cl.node(rev))
2409 node = hex(cl.node(rev))
2395 args.update(phases.preparehookargs(node, old, new))
2410 args.update(phases.preparehookargs(node, old, new))
2396 repo.hook(
2411 repo.hook(
2397 b'txnclose-phase',
2412 b'txnclose-phase',
2398 throw=False,
2413 throw=False,
2399 **pycompat.strkwargs(args)
2414 **pycompat.strkwargs(args)
2400 )
2415 )
2401
2416
2402 repo.hook(
2417 repo.hook(
2403 b'txnclose', throw=False, **pycompat.strkwargs(hookargs)
2418 b'txnclose', throw=False, **pycompat.strkwargs(hookargs)
2404 )
2419 )
2405
2420
2406 reporef()._afterlock(hookfunc)
2421 reporef()._afterlock(hookfunc)
2407
2422
2408 tr.addfinalize(b'txnclose-hook', txnclosehook)
2423 tr.addfinalize(b'txnclose-hook', txnclosehook)
2409 # Include a leading "-" to make it happen before the transaction summary
2424 # Include a leading "-" to make it happen before the transaction summary
2410 # reports registered via scmutil.registersummarycallback() whose names
2425 # reports registered via scmutil.registersummarycallback() whose names
2411 # are 00-txnreport etc. That way, the caches will be warm when the
2426 # are 00-txnreport etc. That way, the caches will be warm when the
2412 # callbacks run.
2427 # callbacks run.
2413 tr.addpostclose(b'-warm-cache', self._buildcacheupdater(tr))
2428 tr.addpostclose(b'-warm-cache', self._buildcacheupdater(tr))
2414
2429
2415 def txnaborthook(tr2):
2430 def txnaborthook(tr2):
2416 """To be run if transaction is aborted"""
2431 """To be run if transaction is aborted"""
2417 reporef().hook(
2432 reporef().hook(
2418 b'txnabort', throw=False, **pycompat.strkwargs(tr2.hookargs)
2433 b'txnabort', throw=False, **pycompat.strkwargs(tr2.hookargs)
2419 )
2434 )
2420
2435
2421 tr.addabort(b'txnabort-hook', txnaborthook)
2436 tr.addabort(b'txnabort-hook', txnaborthook)
2422 # avoid eager cache invalidation. in-memory data should be identical
2437 # avoid eager cache invalidation. in-memory data should be identical
2423 # to stored data if transaction has no error.
2438 # to stored data if transaction has no error.
2424 tr.addpostclose(b'refresh-filecachestats', self._refreshfilecachestats)
2439 tr.addpostclose(b'refresh-filecachestats', self._refreshfilecachestats)
2425 self._transref = weakref.ref(tr)
2440 self._transref = weakref.ref(tr)
2426 scmutil.registersummarycallback(self, tr, desc)
2441 scmutil.registersummarycallback(self, tr, desc)
2427 return tr
2442 return tr
2428
2443
2429 def _journalfiles(self):
2444 def _journalfiles(self):
2430 return (
2445 return (
2431 (self.svfs, b'journal'),
2446 (self.svfs, b'journal'),
2432 (self.svfs, b'journal.narrowspec'),
2447 (self.svfs, b'journal.narrowspec'),
2433 (self.vfs, b'journal.narrowspec.dirstate'),
2448 (self.vfs, b'journal.narrowspec.dirstate'),
2434 (self.vfs, b'journal.dirstate'),
2449 (self.vfs, b'journal.dirstate'),
2435 (self.vfs, b'journal.branch'),
2450 (self.vfs, b'journal.branch'),
2436 (self.vfs, b'journal.desc'),
2451 (self.vfs, b'journal.desc'),
2437 (bookmarks.bookmarksvfs(self), b'journal.bookmarks'),
2452 (bookmarks.bookmarksvfs(self), b'journal.bookmarks'),
2438 (self.svfs, b'journal.phaseroots'),
2453 (self.svfs, b'journal.phaseroots'),
2439 )
2454 )
2440
2455
2441 def undofiles(self):
2456 def undofiles(self):
2442 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
2457 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
2443
2458
2444 @unfilteredmethod
2459 @unfilteredmethod
2445 def _writejournal(self, desc):
2460 def _writejournal(self, desc):
2446 self.dirstate.savebackup(None, b'journal.dirstate')
2461 self.dirstate.savebackup(None, b'journal.dirstate')
2447 narrowspec.savewcbackup(self, b'journal.narrowspec.dirstate')
2462 narrowspec.savewcbackup(self, b'journal.narrowspec.dirstate')
2448 narrowspec.savebackup(self, b'journal.narrowspec')
2463 narrowspec.savebackup(self, b'journal.narrowspec')
2449 self.vfs.write(
2464 self.vfs.write(
2450 b"journal.branch", encoding.fromlocal(self.dirstate.branch())
2465 b"journal.branch", encoding.fromlocal(self.dirstate.branch())
2451 )
2466 )
2452 self.vfs.write(b"journal.desc", b"%d\n%s\n" % (len(self), desc))
2467 self.vfs.write(b"journal.desc", b"%d\n%s\n" % (len(self), desc))
2453 bookmarksvfs = bookmarks.bookmarksvfs(self)
2468 bookmarksvfs = bookmarks.bookmarksvfs(self)
2454 bookmarksvfs.write(
2469 bookmarksvfs.write(
2455 b"journal.bookmarks", bookmarksvfs.tryread(b"bookmarks")
2470 b"journal.bookmarks", bookmarksvfs.tryread(b"bookmarks")
2456 )
2471 )
2457 self.svfs.write(b"journal.phaseroots", self.svfs.tryread(b"phaseroots"))
2472 self.svfs.write(b"journal.phaseroots", self.svfs.tryread(b"phaseroots"))
2458
2473
2459 def recover(self):
2474 def recover(self):
2460 with self.lock():
2475 with self.lock():
2461 if self.svfs.exists(b"journal"):
2476 if self.svfs.exists(b"journal"):
2462 self.ui.status(_(b"rolling back interrupted transaction\n"))
2477 self.ui.status(_(b"rolling back interrupted transaction\n"))
2463 vfsmap = {
2478 vfsmap = {
2464 b'': self.svfs,
2479 b'': self.svfs,
2465 b'plain': self.vfs,
2480 b'plain': self.vfs,
2466 }
2481 }
2467 transaction.rollback(
2482 transaction.rollback(
2468 self.svfs,
2483 self.svfs,
2469 vfsmap,
2484 vfsmap,
2470 b"journal",
2485 b"journal",
2471 self.ui.warn,
2486 self.ui.warn,
2472 checkambigfiles=_cachedfiles,
2487 checkambigfiles=_cachedfiles,
2473 )
2488 )
2474 self.invalidate()
2489 self.invalidate()
2475 return True
2490 return True
2476 else:
2491 else:
2477 self.ui.warn(_(b"no interrupted transaction available\n"))
2492 self.ui.warn(_(b"no interrupted transaction available\n"))
2478 return False
2493 return False
2479
2494
2480 def rollback(self, dryrun=False, force=False):
2495 def rollback(self, dryrun=False, force=False):
2481 wlock = lock = dsguard = None
2496 wlock = lock = dsguard = None
2482 try:
2497 try:
2483 wlock = self.wlock()
2498 wlock = self.wlock()
2484 lock = self.lock()
2499 lock = self.lock()
2485 if self.svfs.exists(b"undo"):
2500 if self.svfs.exists(b"undo"):
2486 dsguard = dirstateguard.dirstateguard(self, b'rollback')
2501 dsguard = dirstateguard.dirstateguard(self, b'rollback')
2487
2502
2488 return self._rollback(dryrun, force, dsguard)
2503 return self._rollback(dryrun, force, dsguard)
2489 else:
2504 else:
2490 self.ui.warn(_(b"no rollback information available\n"))
2505 self.ui.warn(_(b"no rollback information available\n"))
2491 return 1
2506 return 1
2492 finally:
2507 finally:
2493 release(dsguard, lock, wlock)
2508 release(dsguard, lock, wlock)
2494
2509
2495 @unfilteredmethod # Until we get smarter cache management
2510 @unfilteredmethod # Until we get smarter cache management
2496 def _rollback(self, dryrun, force, dsguard):
2511 def _rollback(self, dryrun, force, dsguard):
2497 ui = self.ui
2512 ui = self.ui
2498 try:
2513 try:
2499 args = self.vfs.read(b'undo.desc').splitlines()
2514 args = self.vfs.read(b'undo.desc').splitlines()
2500 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2515 (oldlen, desc, detail) = (int(args[0]), args[1], None)
2501 if len(args) >= 3:
2516 if len(args) >= 3:
2502 detail = args[2]
2517 detail = args[2]
2503 oldtip = oldlen - 1
2518 oldtip = oldlen - 1
2504
2519
2505 if detail and ui.verbose:
2520 if detail and ui.verbose:
2506 msg = _(
2521 msg = _(
2507 b'repository tip rolled back to revision %d'
2522 b'repository tip rolled back to revision %d'
2508 b' (undo %s: %s)\n'
2523 b' (undo %s: %s)\n'
2509 ) % (oldtip, desc, detail)
2524 ) % (oldtip, desc, detail)
2510 else:
2525 else:
2511 msg = _(
2526 msg = _(
2512 b'repository tip rolled back to revision %d (undo %s)\n'
2527 b'repository tip rolled back to revision %d (undo %s)\n'
2513 ) % (oldtip, desc)
2528 ) % (oldtip, desc)
2514 except IOError:
2529 except IOError:
2515 msg = _(b'rolling back unknown transaction\n')
2530 msg = _(b'rolling back unknown transaction\n')
2516 desc = None
2531 desc = None
2517
2532
2518 if not force and self[b'.'] != self[b'tip'] and desc == b'commit':
2533 if not force and self[b'.'] != self[b'tip'] and desc == b'commit':
2519 raise error.Abort(
2534 raise error.Abort(
2520 _(
2535 _(
2521 b'rollback of last commit while not checked out '
2536 b'rollback of last commit while not checked out '
2522 b'may lose data'
2537 b'may lose data'
2523 ),
2538 ),
2524 hint=_(b'use -f to force'),
2539 hint=_(b'use -f to force'),
2525 )
2540 )
2526
2541
2527 ui.status(msg)
2542 ui.status(msg)
2528 if dryrun:
2543 if dryrun:
2529 return 0
2544 return 0
2530
2545
2531 parents = self.dirstate.parents()
2546 parents = self.dirstate.parents()
2532 self.destroying()
2547 self.destroying()
2533 vfsmap = {b'plain': self.vfs, b'': self.svfs}
2548 vfsmap = {b'plain': self.vfs, b'': self.svfs}
2534 transaction.rollback(
2549 transaction.rollback(
2535 self.svfs, vfsmap, b'undo', ui.warn, checkambigfiles=_cachedfiles
2550 self.svfs, vfsmap, b'undo', ui.warn, checkambigfiles=_cachedfiles
2536 )
2551 )
2537 bookmarksvfs = bookmarks.bookmarksvfs(self)
2552 bookmarksvfs = bookmarks.bookmarksvfs(self)
2538 if bookmarksvfs.exists(b'undo.bookmarks'):
2553 if bookmarksvfs.exists(b'undo.bookmarks'):
2539 bookmarksvfs.rename(
2554 bookmarksvfs.rename(
2540 b'undo.bookmarks', b'bookmarks', checkambig=True
2555 b'undo.bookmarks', b'bookmarks', checkambig=True
2541 )
2556 )
2542 if self.svfs.exists(b'undo.phaseroots'):
2557 if self.svfs.exists(b'undo.phaseroots'):
2543 self.svfs.rename(b'undo.phaseroots', b'phaseroots', checkambig=True)
2558 self.svfs.rename(b'undo.phaseroots', b'phaseroots', checkambig=True)
2544 self.invalidate()
2559 self.invalidate()
2545
2560
2546 has_node = self.changelog.index.has_node
2561 has_node = self.changelog.index.has_node
2547 parentgone = any(not has_node(p) for p in parents)
2562 parentgone = any(not has_node(p) for p in parents)
2548 if parentgone:
2563 if parentgone:
2549 # prevent dirstateguard from overwriting already restored one
2564 # prevent dirstateguard from overwriting already restored one
2550 dsguard.close()
2565 dsguard.close()
2551
2566
2552 narrowspec.restorebackup(self, b'undo.narrowspec')
2567 narrowspec.restorebackup(self, b'undo.narrowspec')
2553 narrowspec.restorewcbackup(self, b'undo.narrowspec.dirstate')
2568 narrowspec.restorewcbackup(self, b'undo.narrowspec.dirstate')
2554 self.dirstate.restorebackup(None, b'undo.dirstate')
2569 self.dirstate.restorebackup(None, b'undo.dirstate')
2555 try:
2570 try:
2556 branch = self.vfs.read(b'undo.branch')
2571 branch = self.vfs.read(b'undo.branch')
2557 self.dirstate.setbranch(encoding.tolocal(branch))
2572 self.dirstate.setbranch(encoding.tolocal(branch))
2558 except IOError:
2573 except IOError:
2559 ui.warn(
2574 ui.warn(
2560 _(
2575 _(
2561 b'named branch could not be reset: '
2576 b'named branch could not be reset: '
2562 b'current branch is still \'%s\'\n'
2577 b'current branch is still \'%s\'\n'
2563 )
2578 )
2564 % self.dirstate.branch()
2579 % self.dirstate.branch()
2565 )
2580 )
2566
2581
2567 parents = tuple([p.rev() for p in self[None].parents()])
2582 parents = tuple([p.rev() for p in self[None].parents()])
2568 if len(parents) > 1:
2583 if len(parents) > 1:
2569 ui.status(
2584 ui.status(
2570 _(
2585 _(
2571 b'working directory now based on '
2586 b'working directory now based on '
2572 b'revisions %d and %d\n'
2587 b'revisions %d and %d\n'
2573 )
2588 )
2574 % parents
2589 % parents
2575 )
2590 )
2576 else:
2591 else:
2577 ui.status(
2592 ui.status(
2578 _(b'working directory now based on revision %d\n') % parents
2593 _(b'working directory now based on revision %d\n') % parents
2579 )
2594 )
2580 mergestatemod.mergestate.clean(self)
2595 mergestatemod.mergestate.clean(self)
2581
2596
2582 # TODO: if we know which new heads may result from this rollback, pass
2597 # TODO: if we know which new heads may result from this rollback, pass
2583 # them to destroy(), which will prevent the branchhead cache from being
2598 # them to destroy(), which will prevent the branchhead cache from being
2584 # invalidated.
2599 # invalidated.
2585 self.destroyed()
2600 self.destroyed()
2586 return 0
2601 return 0
2587
2602
2588 def _buildcacheupdater(self, newtransaction):
2603 def _buildcacheupdater(self, newtransaction):
2589 """called during transaction to build the callback updating cache
2604 """called during transaction to build the callback updating cache
2590
2605
2591 Lives on the repository to help extension who might want to augment
2606 Lives on the repository to help extension who might want to augment
2592 this logic. For this purpose, the created transaction is passed to the
2607 this logic. For this purpose, the created transaction is passed to the
2593 method.
2608 method.
2594 """
2609 """
2595 # we must avoid cyclic reference between repo and transaction.
2610 # we must avoid cyclic reference between repo and transaction.
2596 reporef = weakref.ref(self)
2611 reporef = weakref.ref(self)
2597
2612
2598 def updater(tr):
2613 def updater(tr):
2599 repo = reporef()
2614 repo = reporef()
2600 repo.updatecaches(tr)
2615 repo.updatecaches(tr)
2601
2616
2602 return updater
2617 return updater
2603
2618
2604 @unfilteredmethod
2619 @unfilteredmethod
2605 def updatecaches(self, tr=None, full=False):
2620 def updatecaches(self, tr=None, full=False):
2606 """warm appropriate caches
2621 """warm appropriate caches
2607
2622
2608 If this function is called after a transaction closed. The transaction
2623 If this function is called after a transaction closed. The transaction
2609 will be available in the 'tr' argument. This can be used to selectively
2624 will be available in the 'tr' argument. This can be used to selectively
2610 update caches relevant to the changes in that transaction.
2625 update caches relevant to the changes in that transaction.
2611
2626
2612 If 'full' is set, make sure all caches the function knows about have
2627 If 'full' is set, make sure all caches the function knows about have
2613 up-to-date data. Even the ones usually loaded more lazily.
2628 up-to-date data. Even the ones usually loaded more lazily.
2614 """
2629 """
2615 if tr is not None and tr.hookargs.get(b'source') == b'strip':
2630 if tr is not None and tr.hookargs.get(b'source') == b'strip':
2616 # During strip, many caches are invalid but
2631 # During strip, many caches are invalid but
2617 # later call to `destroyed` will refresh them.
2632 # later call to `destroyed` will refresh them.
2618 return
2633 return
2619
2634
2620 if tr is None or tr.changes[b'origrepolen'] < len(self):
2635 if tr is None or tr.changes[b'origrepolen'] < len(self):
2621 # accessing the 'served' branchmap should refresh all the others,
2636 # accessing the 'served' branchmap should refresh all the others,
2622 self.ui.debug(b'updating the branch cache\n')
2637 self.ui.debug(b'updating the branch cache\n')
2623 self.filtered(b'served').branchmap()
2638 self.filtered(b'served').branchmap()
2624 self.filtered(b'served.hidden').branchmap()
2639 self.filtered(b'served.hidden').branchmap()
2625
2640
2626 if full:
2641 if full:
2627 unfi = self.unfiltered()
2642 unfi = self.unfiltered()
2628
2643
2629 self.changelog.update_caches(transaction=tr)
2644 self.changelog.update_caches(transaction=tr)
2630 self.manifestlog.update_caches(transaction=tr)
2645 self.manifestlog.update_caches(transaction=tr)
2631
2646
2632 rbc = unfi.revbranchcache()
2647 rbc = unfi.revbranchcache()
2633 for r in unfi.changelog:
2648 for r in unfi.changelog:
2634 rbc.branchinfo(r)
2649 rbc.branchinfo(r)
2635 rbc.write()
2650 rbc.write()
2636
2651
2637 # ensure the working copy parents are in the manifestfulltextcache
2652 # ensure the working copy parents are in the manifestfulltextcache
2638 for ctx in self[b'.'].parents():
2653 for ctx in self[b'.'].parents():
2639 ctx.manifest() # accessing the manifest is enough
2654 ctx.manifest() # accessing the manifest is enough
2640
2655
2641 # accessing fnode cache warms the cache
2656 # accessing fnode cache warms the cache
2642 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2657 tagsmod.fnoderevs(self.ui, unfi, unfi.changelog.revs())
2643 # accessing tags warm the cache
2658 # accessing tags warm the cache
2644 self.tags()
2659 self.tags()
2645 self.filtered(b'served').tags()
2660 self.filtered(b'served').tags()
2646
2661
2647 # The `full` arg is documented as updating even the lazily-loaded
2662 # The `full` arg is documented as updating even the lazily-loaded
2648 # caches immediately, so we're forcing a write to cause these caches
2663 # caches immediately, so we're forcing a write to cause these caches
2649 # to be warmed up even if they haven't explicitly been requested
2664 # to be warmed up even if they haven't explicitly been requested
2650 # yet (if they've never been used by hg, they won't ever have been
2665 # yet (if they've never been used by hg, they won't ever have been
2651 # written, even if they're a subset of another kind of cache that
2666 # written, even if they're a subset of another kind of cache that
2652 # *has* been used).
2667 # *has* been used).
2653 for filt in repoview.filtertable.keys():
2668 for filt in repoview.filtertable.keys():
2654 filtered = self.filtered(filt)
2669 filtered = self.filtered(filt)
2655 filtered.branchmap().write(filtered)
2670 filtered.branchmap().write(filtered)
2656
2671
2657 def invalidatecaches(self):
2672 def invalidatecaches(self):
2658
2673
2659 if '_tagscache' in vars(self):
2674 if '_tagscache' in vars(self):
2660 # can't use delattr on proxy
2675 # can't use delattr on proxy
2661 del self.__dict__['_tagscache']
2676 del self.__dict__['_tagscache']
2662
2677
2663 self._branchcaches.clear()
2678 self._branchcaches.clear()
2664 self.invalidatevolatilesets()
2679 self.invalidatevolatilesets()
2665 self._sparsesignaturecache.clear()
2680 self._sparsesignaturecache.clear()
2666
2681
2667 def invalidatevolatilesets(self):
2682 def invalidatevolatilesets(self):
2668 self.filteredrevcache.clear()
2683 self.filteredrevcache.clear()
2669 obsolete.clearobscaches(self)
2684 obsolete.clearobscaches(self)
2670 self._quick_access_changeid_invalidate()
2685 self._quick_access_changeid_invalidate()
2671
2686
2672 def invalidatedirstate(self):
2687 def invalidatedirstate(self):
2673 """Invalidates the dirstate, causing the next call to dirstate
2688 """Invalidates the dirstate, causing the next call to dirstate
2674 to check if it was modified since the last time it was read,
2689 to check if it was modified since the last time it was read,
2675 rereading it if it has.
2690 rereading it if it has.
2676
2691
2677 This is different to dirstate.invalidate() that it doesn't always
2692 This is different to dirstate.invalidate() that it doesn't always
2678 rereads the dirstate. Use dirstate.invalidate() if you want to
2693 rereads the dirstate. Use dirstate.invalidate() if you want to
2679 explicitly read the dirstate again (i.e. restoring it to a previous
2694 explicitly read the dirstate again (i.e. restoring it to a previous
2680 known good state)."""
2695 known good state)."""
2681 if hasunfilteredcache(self, 'dirstate'):
2696 if hasunfilteredcache(self, 'dirstate'):
2682 for k in self.dirstate._filecache:
2697 for k in self.dirstate._filecache:
2683 try:
2698 try:
2684 delattr(self.dirstate, k)
2699 delattr(self.dirstate, k)
2685 except AttributeError:
2700 except AttributeError:
2686 pass
2701 pass
2687 delattr(self.unfiltered(), 'dirstate')
2702 delattr(self.unfiltered(), 'dirstate')
2688
2703
2689 def invalidate(self, clearfilecache=False):
2704 def invalidate(self, clearfilecache=False):
2690 """Invalidates both store and non-store parts other than dirstate
2705 """Invalidates both store and non-store parts other than dirstate
2691
2706
2692 If a transaction is running, invalidation of store is omitted,
2707 If a transaction is running, invalidation of store is omitted,
2693 because discarding in-memory changes might cause inconsistency
2708 because discarding in-memory changes might cause inconsistency
2694 (e.g. incomplete fncache causes unintentional failure, but
2709 (e.g. incomplete fncache causes unintentional failure, but
2695 redundant one doesn't).
2710 redundant one doesn't).
2696 """
2711 """
2697 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2712 unfiltered = self.unfiltered() # all file caches are stored unfiltered
2698 for k in list(self._filecache.keys()):
2713 for k in list(self._filecache.keys()):
2699 # dirstate is invalidated separately in invalidatedirstate()
2714 # dirstate is invalidated separately in invalidatedirstate()
2700 if k == b'dirstate':
2715 if k == b'dirstate':
2701 continue
2716 continue
2702 if (
2717 if (
2703 k == b'changelog'
2718 k == b'changelog'
2704 and self.currenttransaction()
2719 and self.currenttransaction()
2705 and self.changelog._delayed
2720 and self.changelog._delayed
2706 ):
2721 ):
2707 # The changelog object may store unwritten revisions. We don't
2722 # The changelog object may store unwritten revisions. We don't
2708 # want to lose them.
2723 # want to lose them.
2709 # TODO: Solve the problem instead of working around it.
2724 # TODO: Solve the problem instead of working around it.
2710 continue
2725 continue
2711
2726
2712 if clearfilecache:
2727 if clearfilecache:
2713 del self._filecache[k]
2728 del self._filecache[k]
2714 try:
2729 try:
2715 delattr(unfiltered, k)
2730 delattr(unfiltered, k)
2716 except AttributeError:
2731 except AttributeError:
2717 pass
2732 pass
2718 self.invalidatecaches()
2733 self.invalidatecaches()
2719 if not self.currenttransaction():
2734 if not self.currenttransaction():
2720 # TODO: Changing contents of store outside transaction
2735 # TODO: Changing contents of store outside transaction
2721 # causes inconsistency. We should make in-memory store
2736 # causes inconsistency. We should make in-memory store
2722 # changes detectable, and abort if changed.
2737 # changes detectable, and abort if changed.
2723 self.store.invalidatecaches()
2738 self.store.invalidatecaches()
2724
2739
2725 def invalidateall(self):
2740 def invalidateall(self):
2726 """Fully invalidates both store and non-store parts, causing the
2741 """Fully invalidates both store and non-store parts, causing the
2727 subsequent operation to reread any outside changes."""
2742 subsequent operation to reread any outside changes."""
2728 # extension should hook this to invalidate its caches
2743 # extension should hook this to invalidate its caches
2729 self.invalidate()
2744 self.invalidate()
2730 self.invalidatedirstate()
2745 self.invalidatedirstate()
2731
2746
2732 @unfilteredmethod
2747 @unfilteredmethod
2733 def _refreshfilecachestats(self, tr):
2748 def _refreshfilecachestats(self, tr):
2734 """Reload stats of cached files so that they are flagged as valid"""
2749 """Reload stats of cached files so that they are flagged as valid"""
2735 for k, ce in self._filecache.items():
2750 for k, ce in self._filecache.items():
2736 k = pycompat.sysstr(k)
2751 k = pycompat.sysstr(k)
2737 if k == 'dirstate' or k not in self.__dict__:
2752 if k == 'dirstate' or k not in self.__dict__:
2738 continue
2753 continue
2739 ce.refresh()
2754 ce.refresh()
2740
2755
2741 def _lock(
2756 def _lock(
2742 self,
2757 self,
2743 vfs,
2758 vfs,
2744 lockname,
2759 lockname,
2745 wait,
2760 wait,
2746 releasefn,
2761 releasefn,
2747 acquirefn,
2762 acquirefn,
2748 desc,
2763 desc,
2749 ):
2764 ):
2750 timeout = 0
2765 timeout = 0
2751 warntimeout = 0
2766 warntimeout = 0
2752 if wait:
2767 if wait:
2753 timeout = self.ui.configint(b"ui", b"timeout")
2768 timeout = self.ui.configint(b"ui", b"timeout")
2754 warntimeout = self.ui.configint(b"ui", b"timeout.warn")
2769 warntimeout = self.ui.configint(b"ui", b"timeout.warn")
2755 # internal config: ui.signal-safe-lock
2770 # internal config: ui.signal-safe-lock
2756 signalsafe = self.ui.configbool(b'ui', b'signal-safe-lock')
2771 signalsafe = self.ui.configbool(b'ui', b'signal-safe-lock')
2757
2772
2758 l = lockmod.trylock(
2773 l = lockmod.trylock(
2759 self.ui,
2774 self.ui,
2760 vfs,
2775 vfs,
2761 lockname,
2776 lockname,
2762 timeout,
2777 timeout,
2763 warntimeout,
2778 warntimeout,
2764 releasefn=releasefn,
2779 releasefn=releasefn,
2765 acquirefn=acquirefn,
2780 acquirefn=acquirefn,
2766 desc=desc,
2781 desc=desc,
2767 signalsafe=signalsafe,
2782 signalsafe=signalsafe,
2768 )
2783 )
2769 return l
2784 return l
2770
2785
2771 def _afterlock(self, callback):
2786 def _afterlock(self, callback):
2772 """add a callback to be run when the repository is fully unlocked
2787 """add a callback to be run when the repository is fully unlocked
2773
2788
2774 The callback will be executed when the outermost lock is released
2789 The callback will be executed when the outermost lock is released
2775 (with wlock being higher level than 'lock')."""
2790 (with wlock being higher level than 'lock')."""
2776 for ref in (self._wlockref, self._lockref):
2791 for ref in (self._wlockref, self._lockref):
2777 l = ref and ref()
2792 l = ref and ref()
2778 if l and l.held:
2793 if l and l.held:
2779 l.postrelease.append(callback)
2794 l.postrelease.append(callback)
2780 break
2795 break
2781 else: # no lock have been found.
2796 else: # no lock have been found.
2782 callback(True)
2797 callback(True)
2783
2798
2784 def lock(self, wait=True):
2799 def lock(self, wait=True):
2785 """Lock the repository store (.hg/store) and return a weak reference
2800 """Lock the repository store (.hg/store) and return a weak reference
2786 to the lock. Use this before modifying the store (e.g. committing or
2801 to the lock. Use this before modifying the store (e.g. committing or
2787 stripping). If you are opening a transaction, get a lock as well.)
2802 stripping). If you are opening a transaction, get a lock as well.)
2788
2803
2789 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2804 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2790 'wlock' first to avoid a dead-lock hazard."""
2805 'wlock' first to avoid a dead-lock hazard."""
2791 l = self._currentlock(self._lockref)
2806 l = self._currentlock(self._lockref)
2792 if l is not None:
2807 if l is not None:
2793 l.lock()
2808 l.lock()
2794 return l
2809 return l
2795
2810
2796 l = self._lock(
2811 l = self._lock(
2797 vfs=self.svfs,
2812 vfs=self.svfs,
2798 lockname=b"lock",
2813 lockname=b"lock",
2799 wait=wait,
2814 wait=wait,
2800 releasefn=None,
2815 releasefn=None,
2801 acquirefn=self.invalidate,
2816 acquirefn=self.invalidate,
2802 desc=_(b'repository %s') % self.origroot,
2817 desc=_(b'repository %s') % self.origroot,
2803 )
2818 )
2804 self._lockref = weakref.ref(l)
2819 self._lockref = weakref.ref(l)
2805 return l
2820 return l
2806
2821
2807 def wlock(self, wait=True):
2822 def wlock(self, wait=True):
2808 """Lock the non-store parts of the repository (everything under
2823 """Lock the non-store parts of the repository (everything under
2809 .hg except .hg/store) and return a weak reference to the lock.
2824 .hg except .hg/store) and return a weak reference to the lock.
2810
2825
2811 Use this before modifying files in .hg.
2826 Use this before modifying files in .hg.
2812
2827
2813 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2828 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
2814 'wlock' first to avoid a dead-lock hazard."""
2829 'wlock' first to avoid a dead-lock hazard."""
2815 l = self._wlockref and self._wlockref()
2830 l = self._wlockref and self._wlockref()
2816 if l is not None and l.held:
2831 if l is not None and l.held:
2817 l.lock()
2832 l.lock()
2818 return l
2833 return l
2819
2834
2820 # We do not need to check for non-waiting lock acquisition. Such
2835 # We do not need to check for non-waiting lock acquisition. Such
2821 # acquisition would not cause dead-lock as they would just fail.
2836 # acquisition would not cause dead-lock as they would just fail.
2822 if wait and (
2837 if wait and (
2823 self.ui.configbool(b'devel', b'all-warnings')
2838 self.ui.configbool(b'devel', b'all-warnings')
2824 or self.ui.configbool(b'devel', b'check-locks')
2839 or self.ui.configbool(b'devel', b'check-locks')
2825 ):
2840 ):
2826 if self._currentlock(self._lockref) is not None:
2841 if self._currentlock(self._lockref) is not None:
2827 self.ui.develwarn(b'"wlock" acquired after "lock"')
2842 self.ui.develwarn(b'"wlock" acquired after "lock"')
2828
2843
2829 def unlock():
2844 def unlock():
2830 if self.dirstate.pendingparentchange():
2845 if self.dirstate.pendingparentchange():
2831 self.dirstate.invalidate()
2846 self.dirstate.invalidate()
2832 else:
2847 else:
2833 self.dirstate.write(None)
2848 self.dirstate.write(None)
2834
2849
2835 self._filecache[b'dirstate'].refresh()
2850 self._filecache[b'dirstate'].refresh()
2836
2851
2837 l = self._lock(
2852 l = self._lock(
2838 self.vfs,
2853 self.vfs,
2839 b"wlock",
2854 b"wlock",
2840 wait,
2855 wait,
2841 unlock,
2856 unlock,
2842 self.invalidatedirstate,
2857 self.invalidatedirstate,
2843 _(b'working directory of %s') % self.origroot,
2858 _(b'working directory of %s') % self.origroot,
2844 )
2859 )
2845 self._wlockref = weakref.ref(l)
2860 self._wlockref = weakref.ref(l)
2846 return l
2861 return l
2847
2862
2848 def _currentlock(self, lockref):
2863 def _currentlock(self, lockref):
2849 """Returns the lock if it's held, or None if it's not."""
2864 """Returns the lock if it's held, or None if it's not."""
2850 if lockref is None:
2865 if lockref is None:
2851 return None
2866 return None
2852 l = lockref()
2867 l = lockref()
2853 if l is None or not l.held:
2868 if l is None or not l.held:
2854 return None
2869 return None
2855 return l
2870 return l
2856
2871
2857 def currentwlock(self):
2872 def currentwlock(self):
2858 """Returns the wlock if it's held, or None if it's not."""
2873 """Returns the wlock if it's held, or None if it's not."""
2859 return self._currentlock(self._wlockref)
2874 return self._currentlock(self._wlockref)
2860
2875
2861 def checkcommitpatterns(self, wctx, match, status, fail):
2876 def checkcommitpatterns(self, wctx, match, status, fail):
2862 """check for commit arguments that aren't committable"""
2877 """check for commit arguments that aren't committable"""
2863 if match.isexact() or match.prefix():
2878 if match.isexact() or match.prefix():
2864 matched = set(status.modified + status.added + status.removed)
2879 matched = set(status.modified + status.added + status.removed)
2865
2880
2866 for f in match.files():
2881 for f in match.files():
2867 f = self.dirstate.normalize(f)
2882 f = self.dirstate.normalize(f)
2868 if f == b'.' or f in matched or f in wctx.substate:
2883 if f == b'.' or f in matched or f in wctx.substate:
2869 continue
2884 continue
2870 if f in status.deleted:
2885 if f in status.deleted:
2871 fail(f, _(b'file not found!'))
2886 fail(f, _(b'file not found!'))
2872 # Is it a directory that exists or used to exist?
2887 # Is it a directory that exists or used to exist?
2873 if self.wvfs.isdir(f) or wctx.p1().hasdir(f):
2888 if self.wvfs.isdir(f) or wctx.p1().hasdir(f):
2874 d = f + b'/'
2889 d = f + b'/'
2875 for mf in matched:
2890 for mf in matched:
2876 if mf.startswith(d):
2891 if mf.startswith(d):
2877 break
2892 break
2878 else:
2893 else:
2879 fail(f, _(b"no match under directory!"))
2894 fail(f, _(b"no match under directory!"))
2880 elif f not in self.dirstate:
2895 elif f not in self.dirstate:
2881 fail(f, _(b"file not tracked!"))
2896 fail(f, _(b"file not tracked!"))
2882
2897
2883 @unfilteredmethod
2898 @unfilteredmethod
2884 def commit(
2899 def commit(
2885 self,
2900 self,
2886 text=b"",
2901 text=b"",
2887 user=None,
2902 user=None,
2888 date=None,
2903 date=None,
2889 match=None,
2904 match=None,
2890 force=False,
2905 force=False,
2891 editor=None,
2906 editor=None,
2892 extra=None,
2907 extra=None,
2893 ):
2908 ):
2894 """Add a new revision to current repository.
2909 """Add a new revision to current repository.
2895
2910
2896 Revision information is gathered from the working directory,
2911 Revision information is gathered from the working directory,
2897 match can be used to filter the committed files. If editor is
2912 match can be used to filter the committed files. If editor is
2898 supplied, it is called to get a commit message.
2913 supplied, it is called to get a commit message.
2899 """
2914 """
2900 if extra is None:
2915 if extra is None:
2901 extra = {}
2916 extra = {}
2902
2917
2903 def fail(f, msg):
2918 def fail(f, msg):
2904 raise error.InputError(b'%s: %s' % (f, msg))
2919 raise error.InputError(b'%s: %s' % (f, msg))
2905
2920
2906 if not match:
2921 if not match:
2907 match = matchmod.always()
2922 match = matchmod.always()
2908
2923
2909 if not force:
2924 if not force:
2910 match.bad = fail
2925 match.bad = fail
2911
2926
2912 # lock() for recent changelog (see issue4368)
2927 # lock() for recent changelog (see issue4368)
2913 with self.wlock(), self.lock():
2928 with self.wlock(), self.lock():
2914 wctx = self[None]
2929 wctx = self[None]
2915 merge = len(wctx.parents()) > 1
2930 merge = len(wctx.parents()) > 1
2916
2931
2917 if not force and merge and not match.always():
2932 if not force and merge and not match.always():
2918 raise error.Abort(
2933 raise error.Abort(
2919 _(
2934 _(
2920 b'cannot partially commit a merge '
2935 b'cannot partially commit a merge '
2921 b'(do not specify files or patterns)'
2936 b'(do not specify files or patterns)'
2922 )
2937 )
2923 )
2938 )
2924
2939
2925 status = self.status(match=match, clean=force)
2940 status = self.status(match=match, clean=force)
2926 if force:
2941 if force:
2927 status.modified.extend(
2942 status.modified.extend(
2928 status.clean
2943 status.clean
2929 ) # mq may commit clean files
2944 ) # mq may commit clean files
2930
2945
2931 # check subrepos
2946 # check subrepos
2932 subs, commitsubs, newstate = subrepoutil.precommit(
2947 subs, commitsubs, newstate = subrepoutil.precommit(
2933 self.ui, wctx, status, match, force=force
2948 self.ui, wctx, status, match, force=force
2934 )
2949 )
2935
2950
2936 # make sure all explicit patterns are matched
2951 # make sure all explicit patterns are matched
2937 if not force:
2952 if not force:
2938 self.checkcommitpatterns(wctx, match, status, fail)
2953 self.checkcommitpatterns(wctx, match, status, fail)
2939
2954
2940 cctx = context.workingcommitctx(
2955 cctx = context.workingcommitctx(
2941 self, status, text, user, date, extra
2956 self, status, text, user, date, extra
2942 )
2957 )
2943
2958
2944 ms = mergestatemod.mergestate.read(self)
2959 ms = mergestatemod.mergestate.read(self)
2945 mergeutil.checkunresolved(ms)
2960 mergeutil.checkunresolved(ms)
2946
2961
2947 # internal config: ui.allowemptycommit
2962 # internal config: ui.allowemptycommit
2948 if cctx.isempty() and not self.ui.configbool(
2963 if cctx.isempty() and not self.ui.configbool(
2949 b'ui', b'allowemptycommit'
2964 b'ui', b'allowemptycommit'
2950 ):
2965 ):
2951 self.ui.debug(b'nothing to commit, clearing merge state\n')
2966 self.ui.debug(b'nothing to commit, clearing merge state\n')
2952 ms.reset()
2967 ms.reset()
2953 return None
2968 return None
2954
2969
2955 if merge and cctx.deleted():
2970 if merge and cctx.deleted():
2956 raise error.Abort(_(b"cannot commit merge with missing files"))
2971 raise error.Abort(_(b"cannot commit merge with missing files"))
2957
2972
2958 if editor:
2973 if editor:
2959 cctx._text = editor(self, cctx, subs)
2974 cctx._text = editor(self, cctx, subs)
2960 edited = text != cctx._text
2975 edited = text != cctx._text
2961
2976
2962 # Save commit message in case this transaction gets rolled back
2977 # Save commit message in case this transaction gets rolled back
2963 # (e.g. by a pretxncommit hook). Leave the content alone on
2978 # (e.g. by a pretxncommit hook). Leave the content alone on
2964 # the assumption that the user will use the same editor again.
2979 # the assumption that the user will use the same editor again.
2965 msgfn = self.savecommitmessage(cctx._text)
2980 msgfn = self.savecommitmessage(cctx._text)
2966
2981
2967 # commit subs and write new state
2982 # commit subs and write new state
2968 if subs:
2983 if subs:
2969 uipathfn = scmutil.getuipathfn(self)
2984 uipathfn = scmutil.getuipathfn(self)
2970 for s in sorted(commitsubs):
2985 for s in sorted(commitsubs):
2971 sub = wctx.sub(s)
2986 sub = wctx.sub(s)
2972 self.ui.status(
2987 self.ui.status(
2973 _(b'committing subrepository %s\n')
2988 _(b'committing subrepository %s\n')
2974 % uipathfn(subrepoutil.subrelpath(sub))
2989 % uipathfn(subrepoutil.subrelpath(sub))
2975 )
2990 )
2976 sr = sub.commit(cctx._text, user, date)
2991 sr = sub.commit(cctx._text, user, date)
2977 newstate[s] = (newstate[s][0], sr)
2992 newstate[s] = (newstate[s][0], sr)
2978 subrepoutil.writestate(self, newstate)
2993 subrepoutil.writestate(self, newstate)
2979
2994
2980 p1, p2 = self.dirstate.parents()
2995 p1, p2 = self.dirstate.parents()
2981 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or b'')
2996 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or b'')
2982 try:
2997 try:
2983 self.hook(
2998 self.hook(
2984 b"precommit", throw=True, parent1=hookp1, parent2=hookp2
2999 b"precommit", throw=True, parent1=hookp1, parent2=hookp2
2985 )
3000 )
2986 with self.transaction(b'commit'):
3001 with self.transaction(b'commit'):
2987 ret = self.commitctx(cctx, True)
3002 ret = self.commitctx(cctx, True)
2988 # update bookmarks, dirstate and mergestate
3003 # update bookmarks, dirstate and mergestate
2989 bookmarks.update(self, [p1, p2], ret)
3004 bookmarks.update(self, [p1, p2], ret)
2990 cctx.markcommitted(ret)
3005 cctx.markcommitted(ret)
2991 ms.reset()
3006 ms.reset()
2992 except: # re-raises
3007 except: # re-raises
2993 if edited:
3008 if edited:
2994 self.ui.write(
3009 self.ui.write(
2995 _(b'note: commit message saved in %s\n') % msgfn
3010 _(b'note: commit message saved in %s\n') % msgfn
2996 )
3011 )
2997 self.ui.write(
3012 self.ui.write(
2998 _(
3013 _(
2999 b"note: use 'hg commit --logfile "
3014 b"note: use 'hg commit --logfile "
3000 b".hg/last-message.txt --edit' to reuse it\n"
3015 b".hg/last-message.txt --edit' to reuse it\n"
3001 )
3016 )
3002 )
3017 )
3003 raise
3018 raise
3004
3019
3005 def commithook(unused_success):
3020 def commithook(unused_success):
3006 # hack for command that use a temporary commit (eg: histedit)
3021 # hack for command that use a temporary commit (eg: histedit)
3007 # temporary commit got stripped before hook release
3022 # temporary commit got stripped before hook release
3008 if self.changelog.hasnode(ret):
3023 if self.changelog.hasnode(ret):
3009 self.hook(
3024 self.hook(
3010 b"commit", node=hex(ret), parent1=hookp1, parent2=hookp2
3025 b"commit", node=hex(ret), parent1=hookp1, parent2=hookp2
3011 )
3026 )
3012
3027
3013 self._afterlock(commithook)
3028 self._afterlock(commithook)
3014 return ret
3029 return ret
3015
3030
3016 @unfilteredmethod
3031 @unfilteredmethod
3017 def commitctx(self, ctx, error=False, origctx=None):
3032 def commitctx(self, ctx, error=False, origctx=None):
3018 return commit.commitctx(self, ctx, error=error, origctx=origctx)
3033 return commit.commitctx(self, ctx, error=error, origctx=origctx)
3019
3034
3020 @unfilteredmethod
3035 @unfilteredmethod
3021 def destroying(self):
3036 def destroying(self):
3022 """Inform the repository that nodes are about to be destroyed.
3037 """Inform the repository that nodes are about to be destroyed.
3023 Intended for use by strip and rollback, so there's a common
3038 Intended for use by strip and rollback, so there's a common
3024 place for anything that has to be done before destroying history.
3039 place for anything that has to be done before destroying history.
3025
3040
3026 This is mostly useful for saving state that is in memory and waiting
3041 This is mostly useful for saving state that is in memory and waiting
3027 to be flushed when the current lock is released. Because a call to
3042 to be flushed when the current lock is released. Because a call to
3028 destroyed is imminent, the repo will be invalidated causing those
3043 destroyed is imminent, the repo will be invalidated causing those
3029 changes to stay in memory (waiting for the next unlock), or vanish
3044 changes to stay in memory (waiting for the next unlock), or vanish
3030 completely.
3045 completely.
3031 """
3046 """
3032 # When using the same lock to commit and strip, the phasecache is left
3047 # When using the same lock to commit and strip, the phasecache is left
3033 # dirty after committing. Then when we strip, the repo is invalidated,
3048 # dirty after committing. Then when we strip, the repo is invalidated,
3034 # causing those changes to disappear.
3049 # causing those changes to disappear.
3035 if '_phasecache' in vars(self):
3050 if '_phasecache' in vars(self):
3036 self._phasecache.write()
3051 self._phasecache.write()
3037
3052
3038 @unfilteredmethod
3053 @unfilteredmethod
3039 def destroyed(self):
3054 def destroyed(self):
3040 """Inform the repository that nodes have been destroyed.
3055 """Inform the repository that nodes have been destroyed.
3041 Intended for use by strip and rollback, so there's a common
3056 Intended for use by strip and rollback, so there's a common
3042 place for anything that has to be done after destroying history.
3057 place for anything that has to be done after destroying history.
3043 """
3058 """
3044 # When one tries to:
3059 # When one tries to:
3045 # 1) destroy nodes thus calling this method (e.g. strip)
3060 # 1) destroy nodes thus calling this method (e.g. strip)
3046 # 2) use phasecache somewhere (e.g. commit)
3061 # 2) use phasecache somewhere (e.g. commit)
3047 #
3062 #
3048 # then 2) will fail because the phasecache contains nodes that were
3063 # then 2) will fail because the phasecache contains nodes that were
3049 # removed. We can either remove phasecache from the filecache,
3064 # removed. We can either remove phasecache from the filecache,
3050 # causing it to reload next time it is accessed, or simply filter
3065 # causing it to reload next time it is accessed, or simply filter
3051 # the removed nodes now and write the updated cache.
3066 # the removed nodes now and write the updated cache.
3052 self._phasecache.filterunknown(self)
3067 self._phasecache.filterunknown(self)
3053 self._phasecache.write()
3068 self._phasecache.write()
3054
3069
3055 # refresh all repository caches
3070 # refresh all repository caches
3056 self.updatecaches()
3071 self.updatecaches()
3057
3072
3058 # Ensure the persistent tag cache is updated. Doing it now
3073 # Ensure the persistent tag cache is updated. Doing it now
3059 # means that the tag cache only has to worry about destroyed
3074 # means that the tag cache only has to worry about destroyed
3060 # heads immediately after a strip/rollback. That in turn
3075 # heads immediately after a strip/rollback. That in turn
3061 # guarantees that "cachetip == currenttip" (comparing both rev
3076 # guarantees that "cachetip == currenttip" (comparing both rev
3062 # and node) always means no nodes have been added or destroyed.
3077 # and node) always means no nodes have been added or destroyed.
3063
3078
3064 # XXX this is suboptimal when qrefresh'ing: we strip the current
3079 # XXX this is suboptimal when qrefresh'ing: we strip the current
3065 # head, refresh the tag cache, then immediately add a new head.
3080 # head, refresh the tag cache, then immediately add a new head.
3066 # But I think doing it this way is necessary for the "instant
3081 # But I think doing it this way is necessary for the "instant
3067 # tag cache retrieval" case to work.
3082 # tag cache retrieval" case to work.
3068 self.invalidate()
3083 self.invalidate()
3069
3084
3070 def status(
3085 def status(
3071 self,
3086 self,
3072 node1=b'.',
3087 node1=b'.',
3073 node2=None,
3088 node2=None,
3074 match=None,
3089 match=None,
3075 ignored=False,
3090 ignored=False,
3076 clean=False,
3091 clean=False,
3077 unknown=False,
3092 unknown=False,
3078 listsubrepos=False,
3093 listsubrepos=False,
3079 ):
3094 ):
3080 '''a convenience method that calls node1.status(node2)'''
3095 '''a convenience method that calls node1.status(node2)'''
3081 return self[node1].status(
3096 return self[node1].status(
3082 node2, match, ignored, clean, unknown, listsubrepos
3097 node2, match, ignored, clean, unknown, listsubrepos
3083 )
3098 )
3084
3099
3085 def addpostdsstatus(self, ps):
3100 def addpostdsstatus(self, ps):
3086 """Add a callback to run within the wlock, at the point at which status
3101 """Add a callback to run within the wlock, at the point at which status
3087 fixups happen.
3102 fixups happen.
3088
3103
3089 On status completion, callback(wctx, status) will be called with the
3104 On status completion, callback(wctx, status) will be called with the
3090 wlock held, unless the dirstate has changed from underneath or the wlock
3105 wlock held, unless the dirstate has changed from underneath or the wlock
3091 couldn't be grabbed.
3106 couldn't be grabbed.
3092
3107
3093 Callbacks should not capture and use a cached copy of the dirstate --
3108 Callbacks should not capture and use a cached copy of the dirstate --
3094 it might change in the meanwhile. Instead, they should access the
3109 it might change in the meanwhile. Instead, they should access the
3095 dirstate via wctx.repo().dirstate.
3110 dirstate via wctx.repo().dirstate.
3096
3111
3097 This list is emptied out after each status run -- extensions should
3112 This list is emptied out after each status run -- extensions should
3098 make sure it adds to this list each time dirstate.status is called.
3113 make sure it adds to this list each time dirstate.status is called.
3099 Extensions should also make sure they don't call this for statuses
3114 Extensions should also make sure they don't call this for statuses
3100 that don't involve the dirstate.
3115 that don't involve the dirstate.
3101 """
3116 """
3102
3117
3103 # The list is located here for uniqueness reasons -- it is actually
3118 # The list is located here for uniqueness reasons -- it is actually
3104 # managed by the workingctx, but that isn't unique per-repo.
3119 # managed by the workingctx, but that isn't unique per-repo.
3105 self._postdsstatus.append(ps)
3120 self._postdsstatus.append(ps)
3106
3121
3107 def postdsstatus(self):
3122 def postdsstatus(self):
3108 """Used by workingctx to get the list of post-dirstate-status hooks."""
3123 """Used by workingctx to get the list of post-dirstate-status hooks."""
3109 return self._postdsstatus
3124 return self._postdsstatus
3110
3125
3111 def clearpostdsstatus(self):
3126 def clearpostdsstatus(self):
3112 """Used by workingctx to clear post-dirstate-status hooks."""
3127 """Used by workingctx to clear post-dirstate-status hooks."""
3113 del self._postdsstatus[:]
3128 del self._postdsstatus[:]
3114
3129
3115 def heads(self, start=None):
3130 def heads(self, start=None):
3116 if start is None:
3131 if start is None:
3117 cl = self.changelog
3132 cl = self.changelog
3118 headrevs = reversed(cl.headrevs())
3133 headrevs = reversed(cl.headrevs())
3119 return [cl.node(rev) for rev in headrevs]
3134 return [cl.node(rev) for rev in headrevs]
3120
3135
3121 heads = self.changelog.heads(start)
3136 heads = self.changelog.heads(start)
3122 # sort the output in rev descending order
3137 # sort the output in rev descending order
3123 return sorted(heads, key=self.changelog.rev, reverse=True)
3138 return sorted(heads, key=self.changelog.rev, reverse=True)
3124
3139
3125 def branchheads(self, branch=None, start=None, closed=False):
3140 def branchheads(self, branch=None, start=None, closed=False):
3126 """return a (possibly filtered) list of heads for the given branch
3141 """return a (possibly filtered) list of heads for the given branch
3127
3142
3128 Heads are returned in topological order, from newest to oldest.
3143 Heads are returned in topological order, from newest to oldest.
3129 If branch is None, use the dirstate branch.
3144 If branch is None, use the dirstate branch.
3130 If start is not None, return only heads reachable from start.
3145 If start is not None, return only heads reachable from start.
3131 If closed is True, return heads that are marked as closed as well.
3146 If closed is True, return heads that are marked as closed as well.
3132 """
3147 """
3133 if branch is None:
3148 if branch is None:
3134 branch = self[None].branch()
3149 branch = self[None].branch()
3135 branches = self.branchmap()
3150 branches = self.branchmap()
3136 if not branches.hasbranch(branch):
3151 if not branches.hasbranch(branch):
3137 return []
3152 return []
3138 # the cache returns heads ordered lowest to highest
3153 # the cache returns heads ordered lowest to highest
3139 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
3154 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
3140 if start is not None:
3155 if start is not None:
3141 # filter out the heads that cannot be reached from startrev
3156 # filter out the heads that cannot be reached from startrev
3142 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
3157 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
3143 bheads = [h for h in bheads if h in fbheads]
3158 bheads = [h for h in bheads if h in fbheads]
3144 return bheads
3159 return bheads
3145
3160
3146 def branches(self, nodes):
3161 def branches(self, nodes):
3147 if not nodes:
3162 if not nodes:
3148 nodes = [self.changelog.tip()]
3163 nodes = [self.changelog.tip()]
3149 b = []
3164 b = []
3150 for n in nodes:
3165 for n in nodes:
3151 t = n
3166 t = n
3152 while True:
3167 while True:
3153 p = self.changelog.parents(n)
3168 p = self.changelog.parents(n)
3154 if p[1] != nullid or p[0] == nullid:
3169 if p[1] != nullid or p[0] == nullid:
3155 b.append((t, n, p[0], p[1]))
3170 b.append((t, n, p[0], p[1]))
3156 break
3171 break
3157 n = p[0]
3172 n = p[0]
3158 return b
3173 return b
3159
3174
3160 def between(self, pairs):
3175 def between(self, pairs):
3161 r = []
3176 r = []
3162
3177
3163 for top, bottom in pairs:
3178 for top, bottom in pairs:
3164 n, l, i = top, [], 0
3179 n, l, i = top, [], 0
3165 f = 1
3180 f = 1
3166
3181
3167 while n != bottom and n != nullid:
3182 while n != bottom and n != nullid:
3168 p = self.changelog.parents(n)[0]
3183 p = self.changelog.parents(n)[0]
3169 if i == f:
3184 if i == f:
3170 l.append(n)
3185 l.append(n)
3171 f = f * 2
3186 f = f * 2
3172 n = p
3187 n = p
3173 i += 1
3188 i += 1
3174
3189
3175 r.append(l)
3190 r.append(l)
3176
3191
3177 return r
3192 return r
3178
3193
3179 def checkpush(self, pushop):
3194 def checkpush(self, pushop):
3180 """Extensions can override this function if additional checks have
3195 """Extensions can override this function if additional checks have
3181 to be performed before pushing, or call it if they override push
3196 to be performed before pushing, or call it if they override push
3182 command.
3197 command.
3183 """
3198 """
3184
3199
3185 @unfilteredpropertycache
3200 @unfilteredpropertycache
3186 def prepushoutgoinghooks(self):
3201 def prepushoutgoinghooks(self):
3187 """Return util.hooks consists of a pushop with repo, remote, outgoing
3202 """Return util.hooks consists of a pushop with repo, remote, outgoing
3188 methods, which are called before pushing changesets.
3203 methods, which are called before pushing changesets.
3189 """
3204 """
3190 return util.hooks()
3205 return util.hooks()
3191
3206
3192 def pushkey(self, namespace, key, old, new):
3207 def pushkey(self, namespace, key, old, new):
3193 try:
3208 try:
3194 tr = self.currenttransaction()
3209 tr = self.currenttransaction()
3195 hookargs = {}
3210 hookargs = {}
3196 if tr is not None:
3211 if tr is not None:
3197 hookargs.update(tr.hookargs)
3212 hookargs.update(tr.hookargs)
3198 hookargs = pycompat.strkwargs(hookargs)
3213 hookargs = pycompat.strkwargs(hookargs)
3199 hookargs['namespace'] = namespace
3214 hookargs['namespace'] = namespace
3200 hookargs['key'] = key
3215 hookargs['key'] = key
3201 hookargs['old'] = old
3216 hookargs['old'] = old
3202 hookargs['new'] = new
3217 hookargs['new'] = new
3203 self.hook(b'prepushkey', throw=True, **hookargs)
3218 self.hook(b'prepushkey', throw=True, **hookargs)
3204 except error.HookAbort as exc:
3219 except error.HookAbort as exc:
3205 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
3220 self.ui.write_err(_(b"pushkey-abort: %s\n") % exc)
3206 if exc.hint:
3221 if exc.hint:
3207 self.ui.write_err(_(b"(%s)\n") % exc.hint)
3222 self.ui.write_err(_(b"(%s)\n") % exc.hint)
3208 return False
3223 return False
3209 self.ui.debug(b'pushing key for "%s:%s"\n' % (namespace, key))
3224 self.ui.debug(b'pushing key for "%s:%s"\n' % (namespace, key))
3210 ret = pushkey.push(self, namespace, key, old, new)
3225 ret = pushkey.push(self, namespace, key, old, new)
3211
3226
3212 def runhook(unused_success):
3227 def runhook(unused_success):
3213 self.hook(
3228 self.hook(
3214 b'pushkey',
3229 b'pushkey',
3215 namespace=namespace,
3230 namespace=namespace,
3216 key=key,
3231 key=key,
3217 old=old,
3232 old=old,
3218 new=new,
3233 new=new,
3219 ret=ret,
3234 ret=ret,
3220 )
3235 )
3221
3236
3222 self._afterlock(runhook)
3237 self._afterlock(runhook)
3223 return ret
3238 return ret
3224
3239
3225 def listkeys(self, namespace):
3240 def listkeys(self, namespace):
3226 self.hook(b'prelistkeys', throw=True, namespace=namespace)
3241 self.hook(b'prelistkeys', throw=True, namespace=namespace)
3227 self.ui.debug(b'listing keys for "%s"\n' % namespace)
3242 self.ui.debug(b'listing keys for "%s"\n' % namespace)
3228 values = pushkey.list(self, namespace)
3243 values = pushkey.list(self, namespace)
3229 self.hook(b'listkeys', namespace=namespace, values=values)
3244 self.hook(b'listkeys', namespace=namespace, values=values)
3230 return values
3245 return values
3231
3246
3232 def debugwireargs(self, one, two, three=None, four=None, five=None):
3247 def debugwireargs(self, one, two, three=None, four=None, five=None):
3233 '''used to test argument passing over the wire'''
3248 '''used to test argument passing over the wire'''
3234 return b"%s %s %s %s %s" % (
3249 return b"%s %s %s %s %s" % (
3235 one,
3250 one,
3236 two,
3251 two,
3237 pycompat.bytestr(three),
3252 pycompat.bytestr(three),
3238 pycompat.bytestr(four),
3253 pycompat.bytestr(four),
3239 pycompat.bytestr(five),
3254 pycompat.bytestr(five),
3240 )
3255 )
3241
3256
3242 def savecommitmessage(self, text):
3257 def savecommitmessage(self, text):
3243 fp = self.vfs(b'last-message.txt', b'wb')
3258 fp = self.vfs(b'last-message.txt', b'wb')
3244 try:
3259 try:
3245 fp.write(text)
3260 fp.write(text)
3246 finally:
3261 finally:
3247 fp.close()
3262 fp.close()
3248 return self.pathto(fp.name[len(self.root) + 1 :])
3263 return self.pathto(fp.name[len(self.root) + 1 :])
3249
3264
3250
3265
3251 # used to avoid circular references so destructors work
3266 # used to avoid circular references so destructors work
3252 def aftertrans(files):
3267 def aftertrans(files):
3253 renamefiles = [tuple(t) for t in files]
3268 renamefiles = [tuple(t) for t in files]
3254
3269
3255 def a():
3270 def a():
3256 for vfs, src, dest in renamefiles:
3271 for vfs, src, dest in renamefiles:
3257 # if src and dest refer to a same file, vfs.rename is a no-op,
3272 # if src and dest refer to a same file, vfs.rename is a no-op,
3258 # leaving both src and dest on disk. delete dest to make sure
3273 # leaving both src and dest on disk. delete dest to make sure
3259 # the rename couldn't be such a no-op.
3274 # the rename couldn't be such a no-op.
3260 vfs.tryunlink(dest)
3275 vfs.tryunlink(dest)
3261 try:
3276 try:
3262 vfs.rename(src, dest)
3277 vfs.rename(src, dest)
3263 except OSError: # journal file does not yet exist
3278 except OSError: # journal file does not yet exist
3264 pass
3279 pass
3265
3280
3266 return a
3281 return a
3267
3282
3268
3283
3269 def undoname(fn):
3284 def undoname(fn):
3270 base, name = os.path.split(fn)
3285 base, name = os.path.split(fn)
3271 assert name.startswith(b'journal')
3286 assert name.startswith(b'journal')
3272 return os.path.join(base, name.replace(b'journal', b'undo', 1))
3287 return os.path.join(base, name.replace(b'journal', b'undo', 1))
3273
3288
3274
3289
3275 def instance(ui, path, create, intents=None, createopts=None):
3290 def instance(ui, path, create, intents=None, createopts=None):
3276 localpath = util.urllocalpath(path)
3291 localpath = util.urllocalpath(path)
3277 if create:
3292 if create:
3278 createrepository(ui, localpath, createopts=createopts)
3293 createrepository(ui, localpath, createopts=createopts)
3279
3294
3280 return makelocalrepository(ui, localpath, intents=intents)
3295 return makelocalrepository(ui, localpath, intents=intents)
3281
3296
3282
3297
3283 def islocal(path):
3298 def islocal(path):
3284 return True
3299 return True
3285
3300
3286
3301
3287 def defaultcreateopts(ui, createopts=None):
3302 def defaultcreateopts(ui, createopts=None):
3288 """Populate the default creation options for a repository.
3303 """Populate the default creation options for a repository.
3289
3304
3290 A dictionary of explicitly requested creation options can be passed
3305 A dictionary of explicitly requested creation options can be passed
3291 in. Missing keys will be populated.
3306 in. Missing keys will be populated.
3292 """
3307 """
3293 createopts = dict(createopts or {})
3308 createopts = dict(createopts or {})
3294
3309
3295 if b'backend' not in createopts:
3310 if b'backend' not in createopts:
3296 # experimental config: storage.new-repo-backend
3311 # experimental config: storage.new-repo-backend
3297 createopts[b'backend'] = ui.config(b'storage', b'new-repo-backend')
3312 createopts[b'backend'] = ui.config(b'storage', b'new-repo-backend')
3298
3313
3299 return createopts
3314 return createopts
3300
3315
3301
3316
3302 def newreporequirements(ui, createopts):
3317 def newreporequirements(ui, createopts):
3303 """Determine the set of requirements for a new local repository.
3318 """Determine the set of requirements for a new local repository.
3304
3319
3305 Extensions can wrap this function to specify custom requirements for
3320 Extensions can wrap this function to specify custom requirements for
3306 new repositories.
3321 new repositories.
3307 """
3322 """
3308 # If the repo is being created from a shared repository, we copy
3323 # If the repo is being created from a shared repository, we copy
3309 # its requirements.
3324 # its requirements.
3310 if b'sharedrepo' in createopts:
3325 if b'sharedrepo' in createopts:
3311 requirements = set(createopts[b'sharedrepo'].requirements)
3326 requirements = set(createopts[b'sharedrepo'].requirements)
3312 if createopts.get(b'sharedrelative'):
3327 if createopts.get(b'sharedrelative'):
3313 requirements.add(requirementsmod.RELATIVE_SHARED_REQUIREMENT)
3328 requirements.add(requirementsmod.RELATIVE_SHARED_REQUIREMENT)
3314 else:
3329 else:
3315 requirements.add(requirementsmod.SHARED_REQUIREMENT)
3330 requirements.add(requirementsmod.SHARED_REQUIREMENT)
3316
3331
3317 return requirements
3332 return requirements
3318
3333
3319 if b'backend' not in createopts:
3334 if b'backend' not in createopts:
3320 raise error.ProgrammingError(
3335 raise error.ProgrammingError(
3321 b'backend key not present in createopts; '
3336 b'backend key not present in createopts; '
3322 b'was defaultcreateopts() called?'
3337 b'was defaultcreateopts() called?'
3323 )
3338 )
3324
3339
3325 if createopts[b'backend'] != b'revlogv1':
3340 if createopts[b'backend'] != b'revlogv1':
3326 raise error.Abort(
3341 raise error.Abort(
3327 _(
3342 _(
3328 b'unable to determine repository requirements for '
3343 b'unable to determine repository requirements for '
3329 b'storage backend: %s'
3344 b'storage backend: %s'
3330 )
3345 )
3331 % createopts[b'backend']
3346 % createopts[b'backend']
3332 )
3347 )
3333
3348
3334 requirements = {b'revlogv1'}
3349 requirements = {b'revlogv1'}
3335 if ui.configbool(b'format', b'usestore'):
3350 if ui.configbool(b'format', b'usestore'):
3336 requirements.add(b'store')
3351 requirements.add(b'store')
3337 if ui.configbool(b'format', b'usefncache'):
3352 if ui.configbool(b'format', b'usefncache'):
3338 requirements.add(b'fncache')
3353 requirements.add(b'fncache')
3339 if ui.configbool(b'format', b'dotencode'):
3354 if ui.configbool(b'format', b'dotencode'):
3340 requirements.add(b'dotencode')
3355 requirements.add(b'dotencode')
3341
3356
3342 compengines = ui.configlist(b'format', b'revlog-compression')
3357 compengines = ui.configlist(b'format', b'revlog-compression')
3343 for compengine in compengines:
3358 for compengine in compengines:
3344 if compengine in util.compengines:
3359 if compengine in util.compengines:
3345 break
3360 break
3346 else:
3361 else:
3347 raise error.Abort(
3362 raise error.Abort(
3348 _(
3363 _(
3349 b'compression engines %s defined by '
3364 b'compression engines %s defined by '
3350 b'format.revlog-compression not available'
3365 b'format.revlog-compression not available'
3351 )
3366 )
3352 % b', '.join(b'"%s"' % e for e in compengines),
3367 % b', '.join(b'"%s"' % e for e in compengines),
3353 hint=_(
3368 hint=_(
3354 b'run "hg debuginstall" to list available '
3369 b'run "hg debuginstall" to list available '
3355 b'compression engines'
3370 b'compression engines'
3356 ),
3371 ),
3357 )
3372 )
3358
3373
3359 # zlib is the historical default and doesn't need an explicit requirement.
3374 # zlib is the historical default and doesn't need an explicit requirement.
3360 if compengine == b'zstd':
3375 if compengine == b'zstd':
3361 requirements.add(b'revlog-compression-zstd')
3376 requirements.add(b'revlog-compression-zstd')
3362 elif compengine != b'zlib':
3377 elif compengine != b'zlib':
3363 requirements.add(b'exp-compression-%s' % compengine)
3378 requirements.add(b'exp-compression-%s' % compengine)
3364
3379
3365 if scmutil.gdinitconfig(ui):
3380 if scmutil.gdinitconfig(ui):
3366 requirements.add(b'generaldelta')
3381 requirements.add(b'generaldelta')
3367 if ui.configbool(b'format', b'sparse-revlog'):
3382 if ui.configbool(b'format', b'sparse-revlog'):
3368 requirements.add(requirementsmod.SPARSEREVLOG_REQUIREMENT)
3383 requirements.add(requirementsmod.SPARSEREVLOG_REQUIREMENT)
3369
3384
3370 # experimental config: format.exp-use-side-data
3385 # experimental config: format.exp-use-side-data
3371 if ui.configbool(b'format', b'exp-use-side-data'):
3386 if ui.configbool(b'format', b'exp-use-side-data'):
3372 requirements.add(requirementsmod.SIDEDATA_REQUIREMENT)
3387 requirements.add(requirementsmod.SIDEDATA_REQUIREMENT)
3373 # experimental config: format.exp-use-copies-side-data-changeset
3388 # experimental config: format.exp-use-copies-side-data-changeset
3374 if ui.configbool(b'format', b'exp-use-copies-side-data-changeset'):
3389 if ui.configbool(b'format', b'exp-use-copies-side-data-changeset'):
3375 requirements.add(requirementsmod.SIDEDATA_REQUIREMENT)
3390 requirements.add(requirementsmod.SIDEDATA_REQUIREMENT)
3376 requirements.add(requirementsmod.COPIESSDC_REQUIREMENT)
3391 requirements.add(requirementsmod.COPIESSDC_REQUIREMENT)
3377 if ui.configbool(b'experimental', b'treemanifest'):
3392 if ui.configbool(b'experimental', b'treemanifest'):
3378 requirements.add(requirementsmod.TREEMANIFEST_REQUIREMENT)
3393 requirements.add(requirementsmod.TREEMANIFEST_REQUIREMENT)
3379
3394
3380 revlogv2 = ui.config(b'experimental', b'revlogv2')
3395 revlogv2 = ui.config(b'experimental', b'revlogv2')
3381 if revlogv2 == b'enable-unstable-format-and-corrupt-my-data':
3396 if revlogv2 == b'enable-unstable-format-and-corrupt-my-data':
3382 requirements.remove(b'revlogv1')
3397 requirements.remove(b'revlogv1')
3383 # generaldelta is implied by revlogv2.
3398 # generaldelta is implied by revlogv2.
3384 requirements.discard(b'generaldelta')
3399 requirements.discard(b'generaldelta')
3385 requirements.add(requirementsmod.REVLOGV2_REQUIREMENT)
3400 requirements.add(requirementsmod.REVLOGV2_REQUIREMENT)
3386 # experimental config: format.internal-phase
3401 # experimental config: format.internal-phase
3387 if ui.configbool(b'format', b'internal-phase'):
3402 if ui.configbool(b'format', b'internal-phase'):
3388 requirements.add(requirementsmod.INTERNAL_PHASE_REQUIREMENT)
3403 requirements.add(requirementsmod.INTERNAL_PHASE_REQUIREMENT)
3389
3404
3390 if createopts.get(b'narrowfiles'):
3405 if createopts.get(b'narrowfiles'):
3391 requirements.add(requirementsmod.NARROW_REQUIREMENT)
3406 requirements.add(requirementsmod.NARROW_REQUIREMENT)
3392
3407
3393 if createopts.get(b'lfs'):
3408 if createopts.get(b'lfs'):
3394 requirements.add(b'lfs')
3409 requirements.add(b'lfs')
3395
3410
3396 if ui.configbool(b'format', b'bookmarks-in-store'):
3411 if ui.configbool(b'format', b'bookmarks-in-store'):
3397 requirements.add(bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT)
3412 requirements.add(bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT)
3398
3413
3399 if ui.configbool(b'format', b'use-persistent-nodemap'):
3414 if ui.configbool(b'format', b'use-persistent-nodemap'):
3400 requirements.add(requirementsmod.NODEMAP_REQUIREMENT)
3415 requirements.add(requirementsmod.NODEMAP_REQUIREMENT)
3401
3416
3402 # if share-safe is enabled, let's create the new repository with the new
3417 # if share-safe is enabled, let's create the new repository with the new
3403 # requirement
3418 # requirement
3404 if ui.configbool(b'format', b'exp-share-safe'):
3419 if ui.configbool(b'format', b'exp-share-safe'):
3405 requirements.add(requirementsmod.SHARESAFE_REQUIREMENT)
3420 requirements.add(requirementsmod.SHARESAFE_REQUIREMENT)
3406
3421
3407 return requirements
3422 return requirements
3408
3423
3409
3424
3410 def checkrequirementscompat(ui, requirements):
3425 def checkrequirementscompat(ui, requirements):
3411 """Checks compatibility of repository requirements enabled and disabled.
3426 """Checks compatibility of repository requirements enabled and disabled.
3412
3427
3413 Returns a set of requirements which needs to be dropped because dependend
3428 Returns a set of requirements which needs to be dropped because dependend
3414 requirements are not enabled. Also warns users about it"""
3429 requirements are not enabled. Also warns users about it"""
3415
3430
3416 dropped = set()
3431 dropped = set()
3417
3432
3418 if b'store' not in requirements:
3433 if b'store' not in requirements:
3419 if bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT in requirements:
3434 if bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT in requirements:
3420 ui.warn(
3435 ui.warn(
3421 _(
3436 _(
3422 b'ignoring enabled \'format.bookmarks-in-store\' config '
3437 b'ignoring enabled \'format.bookmarks-in-store\' config '
3423 b'beacuse it is incompatible with disabled '
3438 b'beacuse it is incompatible with disabled '
3424 b'\'format.usestore\' config\n'
3439 b'\'format.usestore\' config\n'
3425 )
3440 )
3426 )
3441 )
3427 dropped.add(bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT)
3442 dropped.add(bookmarks.BOOKMARKS_IN_STORE_REQUIREMENT)
3428
3443
3429 if (
3444 if (
3430 requirementsmod.SHARED_REQUIREMENT in requirements
3445 requirementsmod.SHARED_REQUIREMENT in requirements
3431 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
3446 or requirementsmod.RELATIVE_SHARED_REQUIREMENT in requirements
3432 ):
3447 ):
3433 raise error.Abort(
3448 raise error.Abort(
3434 _(
3449 _(
3435 b"cannot create shared repository as source was created"
3450 b"cannot create shared repository as source was created"
3436 b" with 'format.usestore' config disabled"
3451 b" with 'format.usestore' config disabled"
3437 )
3452 )
3438 )
3453 )
3439
3454
3440 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
3455 if requirementsmod.SHARESAFE_REQUIREMENT in requirements:
3441 ui.warn(
3456 ui.warn(
3442 _(
3457 _(
3443 b"ignoring enabled 'format.exp-share-safe' config because "
3458 b"ignoring enabled 'format.exp-share-safe' config because "
3444 b"it is incompatible with disabled 'format.usestore'"
3459 b"it is incompatible with disabled 'format.usestore'"
3445 b" config\n"
3460 b" config\n"
3446 )
3461 )
3447 )
3462 )
3448 dropped.add(requirementsmod.SHARESAFE_REQUIREMENT)
3463 dropped.add(requirementsmod.SHARESAFE_REQUIREMENT)
3449
3464
3450 return dropped
3465 return dropped
3451
3466
3452
3467
3453 def filterknowncreateopts(ui, createopts):
3468 def filterknowncreateopts(ui, createopts):
3454 """Filters a dict of repo creation options against options that are known.
3469 """Filters a dict of repo creation options against options that are known.
3455
3470
3456 Receives a dict of repo creation options and returns a dict of those
3471 Receives a dict of repo creation options and returns a dict of those
3457 options that we don't know how to handle.
3472 options that we don't know how to handle.
3458
3473
3459 This function is called as part of repository creation. If the
3474 This function is called as part of repository creation. If the
3460 returned dict contains any items, repository creation will not
3475 returned dict contains any items, repository creation will not
3461 be allowed, as it means there was a request to create a repository
3476 be allowed, as it means there was a request to create a repository
3462 with options not recognized by loaded code.
3477 with options not recognized by loaded code.
3463
3478
3464 Extensions can wrap this function to filter out creation options
3479 Extensions can wrap this function to filter out creation options
3465 they know how to handle.
3480 they know how to handle.
3466 """
3481 """
3467 known = {
3482 known = {
3468 b'backend',
3483 b'backend',
3469 b'lfs',
3484 b'lfs',
3470 b'narrowfiles',
3485 b'narrowfiles',
3471 b'sharedrepo',
3486 b'sharedrepo',
3472 b'sharedrelative',
3487 b'sharedrelative',
3473 b'shareditems',
3488 b'shareditems',
3474 b'shallowfilestore',
3489 b'shallowfilestore',
3475 }
3490 }
3476
3491
3477 return {k: v for k, v in createopts.items() if k not in known}
3492 return {k: v for k, v in createopts.items() if k not in known}
3478
3493
3479
3494
3480 def createrepository(ui, path, createopts=None):
3495 def createrepository(ui, path, createopts=None):
3481 """Create a new repository in a vfs.
3496 """Create a new repository in a vfs.
3482
3497
3483 ``path`` path to the new repo's working directory.
3498 ``path`` path to the new repo's working directory.
3484 ``createopts`` options for the new repository.
3499 ``createopts`` options for the new repository.
3485
3500
3486 The following keys for ``createopts`` are recognized:
3501 The following keys for ``createopts`` are recognized:
3487
3502
3488 backend
3503 backend
3489 The storage backend to use.
3504 The storage backend to use.
3490 lfs
3505 lfs
3491 Repository will be created with ``lfs`` requirement. The lfs extension
3506 Repository will be created with ``lfs`` requirement. The lfs extension
3492 will automatically be loaded when the repository is accessed.
3507 will automatically be loaded when the repository is accessed.
3493 narrowfiles
3508 narrowfiles
3494 Set up repository to support narrow file storage.
3509 Set up repository to support narrow file storage.
3495 sharedrepo
3510 sharedrepo
3496 Repository object from which storage should be shared.
3511 Repository object from which storage should be shared.
3497 sharedrelative
3512 sharedrelative
3498 Boolean indicating if the path to the shared repo should be
3513 Boolean indicating if the path to the shared repo should be
3499 stored as relative. By default, the pointer to the "parent" repo
3514 stored as relative. By default, the pointer to the "parent" repo
3500 is stored as an absolute path.
3515 is stored as an absolute path.
3501 shareditems
3516 shareditems
3502 Set of items to share to the new repository (in addition to storage).
3517 Set of items to share to the new repository (in addition to storage).
3503 shallowfilestore
3518 shallowfilestore
3504 Indicates that storage for files should be shallow (not all ancestor
3519 Indicates that storage for files should be shallow (not all ancestor
3505 revisions are known).
3520 revisions are known).
3506 """
3521 """
3507 createopts = defaultcreateopts(ui, createopts=createopts)
3522 createopts = defaultcreateopts(ui, createopts=createopts)
3508
3523
3509 unknownopts = filterknowncreateopts(ui, createopts)
3524 unknownopts = filterknowncreateopts(ui, createopts)
3510
3525
3511 if not isinstance(unknownopts, dict):
3526 if not isinstance(unknownopts, dict):
3512 raise error.ProgrammingError(
3527 raise error.ProgrammingError(
3513 b'filterknowncreateopts() did not return a dict'
3528 b'filterknowncreateopts() did not return a dict'
3514 )
3529 )
3515
3530
3516 if unknownopts:
3531 if unknownopts:
3517 raise error.Abort(
3532 raise error.Abort(
3518 _(
3533 _(
3519 b'unable to create repository because of unknown '
3534 b'unable to create repository because of unknown '
3520 b'creation option: %s'
3535 b'creation option: %s'
3521 )
3536 )
3522 % b', '.join(sorted(unknownopts)),
3537 % b', '.join(sorted(unknownopts)),
3523 hint=_(b'is a required extension not loaded?'),
3538 hint=_(b'is a required extension not loaded?'),
3524 )
3539 )
3525
3540
3526 requirements = newreporequirements(ui, createopts=createopts)
3541 requirements = newreporequirements(ui, createopts=createopts)
3527 requirements -= checkrequirementscompat(ui, requirements)
3542 requirements -= checkrequirementscompat(ui, requirements)
3528
3543
3529 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3544 wdirvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
3530
3545
3531 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3546 hgvfs = vfsmod.vfs(wdirvfs.join(b'.hg'))
3532 if hgvfs.exists():
3547 if hgvfs.exists():
3533 raise error.RepoError(_(b'repository %s already exists') % path)
3548 raise error.RepoError(_(b'repository %s already exists') % path)
3534
3549
3535 if b'sharedrepo' in createopts:
3550 if b'sharedrepo' in createopts:
3536 sharedpath = createopts[b'sharedrepo'].sharedpath
3551 sharedpath = createopts[b'sharedrepo'].sharedpath
3537
3552
3538 if createopts.get(b'sharedrelative'):
3553 if createopts.get(b'sharedrelative'):
3539 try:
3554 try:
3540 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3555 sharedpath = os.path.relpath(sharedpath, hgvfs.base)
3541 except (IOError, ValueError) as e:
3556 except (IOError, ValueError) as e:
3542 # ValueError is raised on Windows if the drive letters differ
3557 # ValueError is raised on Windows if the drive letters differ
3543 # on each path.
3558 # on each path.
3544 raise error.Abort(
3559 raise error.Abort(
3545 _(b'cannot calculate relative path'),
3560 _(b'cannot calculate relative path'),
3546 hint=stringutil.forcebytestr(e),
3561 hint=stringutil.forcebytestr(e),
3547 )
3562 )
3548
3563
3549 if not wdirvfs.exists():
3564 if not wdirvfs.exists():
3550 wdirvfs.makedirs()
3565 wdirvfs.makedirs()
3551
3566
3552 hgvfs.makedir(notindexed=True)
3567 hgvfs.makedir(notindexed=True)
3553 if b'sharedrepo' not in createopts:
3568 if b'sharedrepo' not in createopts:
3554 hgvfs.mkdir(b'cache')
3569 hgvfs.mkdir(b'cache')
3555 hgvfs.mkdir(b'wcache')
3570 hgvfs.mkdir(b'wcache')
3556
3571
3557 if b'store' in requirements and b'sharedrepo' not in createopts:
3572 if b'store' in requirements and b'sharedrepo' not in createopts:
3558 hgvfs.mkdir(b'store')
3573 hgvfs.mkdir(b'store')
3559
3574
3560 # We create an invalid changelog outside the store so very old
3575 # We create an invalid changelog outside the store so very old
3561 # Mercurial versions (which didn't know about the requirements
3576 # Mercurial versions (which didn't know about the requirements
3562 # file) encounter an error on reading the changelog. This
3577 # file) encounter an error on reading the changelog. This
3563 # effectively locks out old clients and prevents them from
3578 # effectively locks out old clients and prevents them from
3564 # mucking with a repo in an unknown format.
3579 # mucking with a repo in an unknown format.
3565 #
3580 #
3566 # The revlog header has version 2, which won't be recognized by
3581 # The revlog header has version 2, which won't be recognized by
3567 # such old clients.
3582 # such old clients.
3568 hgvfs.append(
3583 hgvfs.append(
3569 b'00changelog.i',
3584 b'00changelog.i',
3570 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3585 b'\0\0\0\2 dummy changelog to prevent using the old repo '
3571 b'layout',
3586 b'layout',
3572 )
3587 )
3573
3588
3574 # Filter the requirements into working copy and store ones
3589 # Filter the requirements into working copy and store ones
3575 wcreq, storereq = scmutil.filterrequirements(requirements)
3590 wcreq, storereq = scmutil.filterrequirements(requirements)
3576 # write working copy ones
3591 # write working copy ones
3577 scmutil.writerequires(hgvfs, wcreq)
3592 scmutil.writerequires(hgvfs, wcreq)
3578 # If there are store requirements and the current repository
3593 # If there are store requirements and the current repository
3579 # is not a shared one, write stored requirements
3594 # is not a shared one, write stored requirements
3580 # For new shared repository, we don't need to write the store
3595 # For new shared repository, we don't need to write the store
3581 # requirements as they are already present in store requires
3596 # requirements as they are already present in store requires
3582 if storereq and b'sharedrepo' not in createopts:
3597 if storereq and b'sharedrepo' not in createopts:
3583 storevfs = vfsmod.vfs(hgvfs.join(b'store'), cacheaudited=True)
3598 storevfs = vfsmod.vfs(hgvfs.join(b'store'), cacheaudited=True)
3584 scmutil.writerequires(storevfs, storereq)
3599 scmutil.writerequires(storevfs, storereq)
3585
3600
3586 # Write out file telling readers where to find the shared store.
3601 # Write out file telling readers where to find the shared store.
3587 if b'sharedrepo' in createopts:
3602 if b'sharedrepo' in createopts:
3588 hgvfs.write(b'sharedpath', sharedpath)
3603 hgvfs.write(b'sharedpath', sharedpath)
3589
3604
3590 if createopts.get(b'shareditems'):
3605 if createopts.get(b'shareditems'):
3591 shared = b'\n'.join(sorted(createopts[b'shareditems'])) + b'\n'
3606 shared = b'\n'.join(sorted(createopts[b'shareditems'])) + b'\n'
3592 hgvfs.write(b'shared', shared)
3607 hgvfs.write(b'shared', shared)
3593
3608
3594
3609
3595 def poisonrepository(repo):
3610 def poisonrepository(repo):
3596 """Poison a repository instance so it can no longer be used."""
3611 """Poison a repository instance so it can no longer be used."""
3597 # Perform any cleanup on the instance.
3612 # Perform any cleanup on the instance.
3598 repo.close()
3613 repo.close()
3599
3614
3600 # Our strategy is to replace the type of the object with one that
3615 # Our strategy is to replace the type of the object with one that
3601 # has all attribute lookups result in error.
3616 # has all attribute lookups result in error.
3602 #
3617 #
3603 # But we have to allow the close() method because some constructors
3618 # But we have to allow the close() method because some constructors
3604 # of repos call close() on repo references.
3619 # of repos call close() on repo references.
3605 class poisonedrepository(object):
3620 class poisonedrepository(object):
3606 def __getattribute__(self, item):
3621 def __getattribute__(self, item):
3607 if item == 'close':
3622 if item == 'close':
3608 return object.__getattribute__(self, item)
3623 return object.__getattribute__(self, item)
3609
3624
3610 raise error.ProgrammingError(
3625 raise error.ProgrammingError(
3611 b'repo instances should not be used after unshare'
3626 b'repo instances should not be used after unshare'
3612 )
3627 )
3613
3628
3614 def close(self):
3629 def close(self):
3615 pass
3630 pass
3616
3631
3617 # We may have a repoview, which intercepts __setattr__. So be sure
3632 # We may have a repoview, which intercepts __setattr__. So be sure
3618 # we operate at the lowest level possible.
3633 # we operate at the lowest level possible.
3619 object.__setattr__(repo, '__class__', poisonedrepository)
3634 object.__setattr__(repo, '__class__', poisonedrepository)
@@ -1,628 +1,637 b''
1 ===================================
1 ===================================
2 Test the persistent on-disk nodemap
2 Test the persistent on-disk nodemap
3 ===================================
3 ===================================
4
4
5 $ cat << EOF >> $HGRCPATH
5 $ cat << EOF >> $HGRCPATH
6 > [format]
6 > [format]
7 > use-persistent-nodemap=yes
7 > use-persistent-nodemap=yes
8 > [devel]
8 > [devel]
9 > persistent-nodemap=yes
9 > persistent-nodemap=yes
10 > EOF
10 > EOF
11 $ hg init test-repo
11 $ hg init test-repo
12 $ cd test-repo
12 $ cd test-repo
13 $ hg debugformat
13 $ hg debugformat
14 format-variant repo
14 format-variant repo
15 fncache: yes
15 fncache: yes
16 dotencode: yes
16 dotencode: yes
17 generaldelta: yes
17 generaldelta: yes
18 exp-sharesafe: no
18 exp-sharesafe: no
19 sparserevlog: yes
19 sparserevlog: yes
20 sidedata: no
20 sidedata: no
21 persistent-nodemap: yes
21 persistent-nodemap: yes
22 copies-sdc: no
22 copies-sdc: no
23 plain-cl-delta: yes
23 plain-cl-delta: yes
24 compression: zlib
24 compression: zlib
25 compression-level: default
25 compression-level: default
26 $ hg debugbuilddag .+5000 --new-file --config "storage.revlog.nodemap.mode=warn"
26 $ hg debugbuilddag .+5000 --new-file --config "storage.revlog.nodemap.mode=warn"
27 persistent nodemap in strict mode without efficient method (no-rust no-pure !)
27 persistent nodemap in strict mode without efficient method (no-rust no-pure !)
28 persistent nodemap in strict mode without efficient method (no-rust no-pure !)
28 persistent nodemap in strict mode without efficient method (no-rust no-pure !)
29 $ hg debugnodemap --metadata
29 $ hg debugnodemap --metadata
30 uid: ???????????????? (glob)
30 uid: ???????????????? (glob)
31 tip-rev: 5000
31 tip-rev: 5000
32 tip-node: 6b02b8c7b96654c25e86ba69eda198d7e6ad8b3c
32 tip-node: 6b02b8c7b96654c25e86ba69eda198d7e6ad8b3c
33 data-length: 121088
33 data-length: 121088
34 data-unused: 0
34 data-unused: 0
35 data-unused: 0.000%
35 data-unused: 0.000%
36 $ f --size .hg/store/00changelog.n
36 $ f --size .hg/store/00changelog.n
37 .hg/store/00changelog.n: size=70
37 .hg/store/00changelog.n: size=70
38
38
39 Simple lookup works
39 Simple lookup works
40
40
41 $ ANYNODE=`hg log --template '{node|short}\n' --rev tip`
41 $ ANYNODE=`hg log --template '{node|short}\n' --rev tip`
42 $ hg log -r "$ANYNODE" --template '{rev}\n'
42 $ hg log -r "$ANYNODE" --template '{rev}\n'
43 5000
43 5000
44
44
45
45
46 #if rust
46 #if rust
47
47
48 $ f --sha256 .hg/store/00changelog-*.nd
48 $ f --sha256 .hg/store/00changelog-*.nd
49 .hg/store/00changelog-????????????????.nd: sha256=2e029d3200bd1a986b32784fc2ef1a3bd60dc331f025718bcf5ff44d93f026fd (glob)
49 .hg/store/00changelog-????????????????.nd: sha256=2e029d3200bd1a986b32784fc2ef1a3bd60dc331f025718bcf5ff44d93f026fd (glob)
50
50
51 $ f --sha256 .hg/store/00manifest-*.nd
51 $ f --sha256 .hg/store/00manifest-*.nd
52 .hg/store/00manifest-????????????????.nd: sha256=97117b1c064ea2f86664a124589e47db0e254e8d34739b5c5cc5bf31c9da2b51 (glob)
52 .hg/store/00manifest-????????????????.nd: sha256=97117b1c064ea2f86664a124589e47db0e254e8d34739b5c5cc5bf31c9da2b51 (glob)
53 $ hg debugnodemap --dump-new | f --sha256 --size
53 $ hg debugnodemap --dump-new | f --sha256 --size
54 size=121088, sha256=2e029d3200bd1a986b32784fc2ef1a3bd60dc331f025718bcf5ff44d93f026fd
54 size=121088, sha256=2e029d3200bd1a986b32784fc2ef1a3bd60dc331f025718bcf5ff44d93f026fd
55 $ hg debugnodemap --dump-disk | f --sha256 --bytes=256 --hexdump --size
55 $ hg debugnodemap --dump-disk | f --sha256 --bytes=256 --hexdump --size
56 size=121088, sha256=2e029d3200bd1a986b32784fc2ef1a3bd60dc331f025718bcf5ff44d93f026fd
56 size=121088, sha256=2e029d3200bd1a986b32784fc2ef1a3bd60dc331f025718bcf5ff44d93f026fd
57 0000: 00 00 00 91 00 00 00 20 00 00 00 bb 00 00 00 e7 |....... ........|
57 0000: 00 00 00 91 00 00 00 20 00 00 00 bb 00 00 00 e7 |....... ........|
58 0010: 00 00 00 66 00 00 00 a1 00 00 01 13 00 00 01 22 |...f..........."|
58 0010: 00 00 00 66 00 00 00 a1 00 00 01 13 00 00 01 22 |...f..........."|
59 0020: 00 00 00 23 00 00 00 fc 00 00 00 ba 00 00 00 5e |...#...........^|
59 0020: 00 00 00 23 00 00 00 fc 00 00 00 ba 00 00 00 5e |...#...........^|
60 0030: 00 00 00 df 00 00 01 4e 00 00 01 65 00 00 00 ab |.......N...e....|
60 0030: 00 00 00 df 00 00 01 4e 00 00 01 65 00 00 00 ab |.......N...e....|
61 0040: 00 00 00 a9 00 00 00 95 00 00 00 73 00 00 00 38 |...........s...8|
61 0040: 00 00 00 a9 00 00 00 95 00 00 00 73 00 00 00 38 |...........s...8|
62 0050: 00 00 00 cc 00 00 00 92 00 00 00 90 00 00 00 69 |...............i|
62 0050: 00 00 00 cc 00 00 00 92 00 00 00 90 00 00 00 69 |...............i|
63 0060: 00 00 00 ec 00 00 00 8d 00 00 01 4f 00 00 00 12 |...........O....|
63 0060: 00 00 00 ec 00 00 00 8d 00 00 01 4f 00 00 00 12 |...........O....|
64 0070: 00 00 02 0c 00 00 00 77 00 00 00 9c 00 00 00 8f |.......w........|
64 0070: 00 00 02 0c 00 00 00 77 00 00 00 9c 00 00 00 8f |.......w........|
65 0080: 00 00 00 d5 00 00 00 6b 00 00 00 48 00 00 00 b3 |.......k...H....|
65 0080: 00 00 00 d5 00 00 00 6b 00 00 00 48 00 00 00 b3 |.......k...H....|
66 0090: 00 00 00 e5 00 00 00 b5 00 00 00 8e 00 00 00 ad |................|
66 0090: 00 00 00 e5 00 00 00 b5 00 00 00 8e 00 00 00 ad |................|
67 00a0: 00 00 00 7b 00 00 00 7c 00 00 00 0b 00 00 00 2b |...{...|.......+|
67 00a0: 00 00 00 7b 00 00 00 7c 00 00 00 0b 00 00 00 2b |...{...|.......+|
68 00b0: 00 00 00 c6 00 00 00 1e 00 00 01 08 00 00 00 11 |................|
68 00b0: 00 00 00 c6 00 00 00 1e 00 00 01 08 00 00 00 11 |................|
69 00c0: 00 00 01 30 00 00 00 26 00 00 01 9c 00 00 00 35 |...0...&.......5|
69 00c0: 00 00 01 30 00 00 00 26 00 00 01 9c 00 00 00 35 |...0...&.......5|
70 00d0: 00 00 00 b8 00 00 01 31 00 00 00 2c 00 00 00 55 |.......1...,...U|
70 00d0: 00 00 00 b8 00 00 01 31 00 00 00 2c 00 00 00 55 |.......1...,...U|
71 00e0: 00 00 00 8a 00 00 00 9a 00 00 00 0c 00 00 01 1e |................|
71 00e0: 00 00 00 8a 00 00 00 9a 00 00 00 0c 00 00 01 1e |................|
72 00f0: 00 00 00 a4 00 00 00 83 00 00 00 c9 00 00 00 8c |................|
72 00f0: 00 00 00 a4 00 00 00 83 00 00 00 c9 00 00 00 8c |................|
73
73
74
74
75 #else
75 #else
76
76
77 $ f --sha256 .hg/store/00changelog-*.nd
77 $ f --sha256 .hg/store/00changelog-*.nd
78 .hg/store/00changelog-????????????????.nd: sha256=f544f5462ff46097432caf6d764091f6d8c46d6121be315ead8576d548c9dd79 (glob)
78 .hg/store/00changelog-????????????????.nd: sha256=f544f5462ff46097432caf6d764091f6d8c46d6121be315ead8576d548c9dd79 (glob)
79 $ hg debugnodemap --dump-new | f --sha256 --size
79 $ hg debugnodemap --dump-new | f --sha256 --size
80 size=121088, sha256=f544f5462ff46097432caf6d764091f6d8c46d6121be315ead8576d548c9dd79
80 size=121088, sha256=f544f5462ff46097432caf6d764091f6d8c46d6121be315ead8576d548c9dd79
81 $ hg debugnodemap --dump-disk | f --sha256 --bytes=256 --hexdump --size
81 $ hg debugnodemap --dump-disk | f --sha256 --bytes=256 --hexdump --size
82 size=121088, sha256=f544f5462ff46097432caf6d764091f6d8c46d6121be315ead8576d548c9dd79
82 size=121088, sha256=f544f5462ff46097432caf6d764091f6d8c46d6121be315ead8576d548c9dd79
83 0000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
83 0000: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
84 0010: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
84 0010: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
85 0020: ff ff ff ff ff ff f5 06 ff ff ff ff ff ff f3 e7 |................|
85 0020: ff ff ff ff ff ff f5 06 ff ff ff ff ff ff f3 e7 |................|
86 0030: ff ff ef ca ff ff ff ff ff ff ff ff ff ff ff ff |................|
86 0030: ff ff ef ca ff ff ff ff ff ff ff ff ff ff ff ff |................|
87 0040: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
87 0040: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
88 0050: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ed 08 |................|
88 0050: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ed 08 |................|
89 0060: ff ff ed 66 ff ff ff ff ff ff ff ff ff ff ff ff |...f............|
89 0060: ff ff ed 66 ff ff ff ff ff ff ff ff ff ff ff ff |...f............|
90 0070: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
90 0070: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
91 0080: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
91 0080: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
92 0090: ff ff ff ff ff ff ff ff ff ff ff ff ff ff f6 ed |................|
92 0090: ff ff ff ff ff ff ff ff ff ff ff ff ff ff f6 ed |................|
93 00a0: ff ff ff ff ff ff fe 61 ff ff ff ff ff ff ff ff |.......a........|
93 00a0: ff ff ff ff ff ff fe 61 ff ff ff ff ff ff ff ff |.......a........|
94 00b0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
94 00b0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
95 00c0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
95 00c0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
96 00d0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
96 00d0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff |................|
97 00e0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff f1 02 |................|
97 00e0: ff ff ff ff ff ff ff ff ff ff ff ff ff ff f1 02 |................|
98 00f0: ff ff ff ff ff ff ed 1b ff ff ff ff ff ff ff ff |................|
98 00f0: ff ff ff ff ff ff ed 1b ff ff ff ff ff ff ff ff |................|
99
99
100 #endif
100 #endif
101
101
102 $ hg debugnodemap --check
102 $ hg debugnodemap --check
103 revision in index: 5001
103 revision in index: 5001
104 revision in nodemap: 5001
104 revision in nodemap: 5001
105
105
106 add a new commit
106 add a new commit
107
107
108 $ hg up
108 $ hg up
109 5001 files updated, 0 files merged, 0 files removed, 0 files unresolved
109 5001 files updated, 0 files merged, 0 files removed, 0 files unresolved
110 $ echo foo > foo
110 $ echo foo > foo
111 $ hg add foo
111 $ hg add foo
112
112
113
114 Check slow-path config value handling
115 -------------------------------------
116
117 $ hg id --config "storage.revlog.persistent-nodemap.slow-path=invalid-value"
118 unknown value for config "storage.revlog.persistent-nodemap.slow-path": "invalid-value"
119 falling back to default value: allow
120 6b02b8c7b966+ tip
121
113 #if no-pure no-rust
122 #if no-pure no-rust
114
123
115 $ hg ci -m 'foo' --config "storage.revlog.nodemap.mode=strict"
124 $ hg ci -m 'foo' --config "storage.revlog.nodemap.mode=strict"
116 transaction abort!
125 transaction abort!
117 rollback completed
126 rollback completed
118 abort: persistent nodemap in strict mode without efficient method
127 abort: persistent nodemap in strict mode without efficient method
119 [255]
128 [255]
120
129
121 #endif
130 #endif
122
131
123 $ hg ci -m 'foo'
132 $ hg ci -m 'foo'
124
133
125 #if no-pure no-rust
134 #if no-pure no-rust
126 $ hg debugnodemap --metadata
135 $ hg debugnodemap --metadata
127 uid: ???????????????? (glob)
136 uid: ???????????????? (glob)
128 tip-rev: 5001
137 tip-rev: 5001
129 tip-node: 16395c3cf7e231394735e6b1717823ada303fb0c
138 tip-node: 16395c3cf7e231394735e6b1717823ada303fb0c
130 data-length: 121088
139 data-length: 121088
131 data-unused: 0
140 data-unused: 0
132 data-unused: 0.000%
141 data-unused: 0.000%
133 #else
142 #else
134 $ hg debugnodemap --metadata
143 $ hg debugnodemap --metadata
135 uid: ???????????????? (glob)
144 uid: ???????????????? (glob)
136 tip-rev: 5001
145 tip-rev: 5001
137 tip-node: 16395c3cf7e231394735e6b1717823ada303fb0c
146 tip-node: 16395c3cf7e231394735e6b1717823ada303fb0c
138 data-length: 121344
147 data-length: 121344
139 data-unused: 256
148 data-unused: 256
140 data-unused: 0.211%
149 data-unused: 0.211%
141 #endif
150 #endif
142
151
143 $ f --size .hg/store/00changelog.n
152 $ f --size .hg/store/00changelog.n
144 .hg/store/00changelog.n: size=70
153 .hg/store/00changelog.n: size=70
145
154
146 (The pure code use the debug code that perform incremental update, the C code reencode from scratch)
155 (The pure code use the debug code that perform incremental update, the C code reencode from scratch)
147
156
148 #if pure
157 #if pure
149 $ f --sha256 .hg/store/00changelog-*.nd --size
158 $ f --sha256 .hg/store/00changelog-*.nd --size
150 .hg/store/00changelog-????????????????.nd: size=121344, sha256=cce54c5da5bde3ad72a4938673ed4064c86231b9c64376b082b163fdb20f8f66 (glob)
159 .hg/store/00changelog-????????????????.nd: size=121344, sha256=cce54c5da5bde3ad72a4938673ed4064c86231b9c64376b082b163fdb20f8f66 (glob)
151 #endif
160 #endif
152
161
153 #if rust
162 #if rust
154 $ f --sha256 .hg/store/00changelog-*.nd --size
163 $ f --sha256 .hg/store/00changelog-*.nd --size
155 .hg/store/00changelog-????????????????.nd: size=121344, sha256=952b042fcf614ceb37b542b1b723e04f18f83efe99bee4e0f5ccd232ef470e58 (glob)
164 .hg/store/00changelog-????????????????.nd: size=121344, sha256=952b042fcf614ceb37b542b1b723e04f18f83efe99bee4e0f5ccd232ef470e58 (glob)
156 #endif
165 #endif
157
166
158 #if no-pure no-rust
167 #if no-pure no-rust
159 $ f --sha256 .hg/store/00changelog-*.nd --size
168 $ f --sha256 .hg/store/00changelog-*.nd --size
160 .hg/store/00changelog-????????????????.nd: size=121088, sha256=df7c06a035b96cb28c7287d349d603baef43240be7736fe34eea419a49702e17 (glob)
169 .hg/store/00changelog-????????????????.nd: size=121088, sha256=df7c06a035b96cb28c7287d349d603baef43240be7736fe34eea419a49702e17 (glob)
161 #endif
170 #endif
162
171
163 $ hg debugnodemap --check
172 $ hg debugnodemap --check
164 revision in index: 5002
173 revision in index: 5002
165 revision in nodemap: 5002
174 revision in nodemap: 5002
166
175
167 Test code path without mmap
176 Test code path without mmap
168 ---------------------------
177 ---------------------------
169
178
170 $ echo bar > bar
179 $ echo bar > bar
171 $ hg add bar
180 $ hg add bar
172 $ hg ci -m 'bar' --config storage.revlog.persistent-nodemap.mmap=no
181 $ hg ci -m 'bar' --config storage.revlog.persistent-nodemap.mmap=no
173
182
174 $ hg debugnodemap --check --config storage.revlog.persistent-nodemap.mmap=yes
183 $ hg debugnodemap --check --config storage.revlog.persistent-nodemap.mmap=yes
175 revision in index: 5003
184 revision in index: 5003
176 revision in nodemap: 5003
185 revision in nodemap: 5003
177 $ hg debugnodemap --check --config storage.revlog.persistent-nodemap.mmap=no
186 $ hg debugnodemap --check --config storage.revlog.persistent-nodemap.mmap=no
178 revision in index: 5003
187 revision in index: 5003
179 revision in nodemap: 5003
188 revision in nodemap: 5003
180
189
181
190
182 #if pure
191 #if pure
183 $ hg debugnodemap --metadata
192 $ hg debugnodemap --metadata
184 uid: ???????????????? (glob)
193 uid: ???????????????? (glob)
185 tip-rev: 5002
194 tip-rev: 5002
186 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
195 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
187 data-length: 121600
196 data-length: 121600
188 data-unused: 512
197 data-unused: 512
189 data-unused: 0.421%
198 data-unused: 0.421%
190 $ f --sha256 .hg/store/00changelog-*.nd --size
199 $ f --sha256 .hg/store/00changelog-*.nd --size
191 .hg/store/00changelog-????????????????.nd: size=121600, sha256=def52503d049ccb823974af313a98a935319ba61f40f3aa06a8be4d35c215054 (glob)
200 .hg/store/00changelog-????????????????.nd: size=121600, sha256=def52503d049ccb823974af313a98a935319ba61f40f3aa06a8be4d35c215054 (glob)
192 #endif
201 #endif
193 #if rust
202 #if rust
194 $ hg debugnodemap --metadata
203 $ hg debugnodemap --metadata
195 uid: ???????????????? (glob)
204 uid: ???????????????? (glob)
196 tip-rev: 5002
205 tip-rev: 5002
197 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
206 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
198 data-length: 121600
207 data-length: 121600
199 data-unused: 512
208 data-unused: 512
200 data-unused: 0.421%
209 data-unused: 0.421%
201 $ f --sha256 .hg/store/00changelog-*.nd --size
210 $ f --sha256 .hg/store/00changelog-*.nd --size
202 .hg/store/00changelog-????????????????.nd: size=121600, sha256=dacf5b5f1d4585fee7527d0e67cad5b1ba0930e6a0928f650f779aefb04ce3fb (glob)
211 .hg/store/00changelog-????????????????.nd: size=121600, sha256=dacf5b5f1d4585fee7527d0e67cad5b1ba0930e6a0928f650f779aefb04ce3fb (glob)
203 #endif
212 #endif
204 #if no-pure no-rust
213 #if no-pure no-rust
205 $ hg debugnodemap --metadata
214 $ hg debugnodemap --metadata
206 uid: ???????????????? (glob)
215 uid: ???????????????? (glob)
207 tip-rev: 5002
216 tip-rev: 5002
208 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
217 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
209 data-length: 121088
218 data-length: 121088
210 data-unused: 0
219 data-unused: 0
211 data-unused: 0.000%
220 data-unused: 0.000%
212 $ f --sha256 .hg/store/00changelog-*.nd --size
221 $ f --sha256 .hg/store/00changelog-*.nd --size
213 .hg/store/00changelog-????????????????.nd: size=121088, sha256=59fcede3e3cc587755916ceed29e3c33748cd1aa7d2f91828ac83e7979d935e8 (glob)
222 .hg/store/00changelog-????????????????.nd: size=121088, sha256=59fcede3e3cc587755916ceed29e3c33748cd1aa7d2f91828ac83e7979d935e8 (glob)
214 #endif
223 #endif
215
224
216 Test force warming the cache
225 Test force warming the cache
217
226
218 $ rm .hg/store/00changelog.n
227 $ rm .hg/store/00changelog.n
219 $ hg debugnodemap --metadata
228 $ hg debugnodemap --metadata
220 $ hg debugupdatecache
229 $ hg debugupdatecache
221 #if pure
230 #if pure
222 $ hg debugnodemap --metadata
231 $ hg debugnodemap --metadata
223 uid: ???????????????? (glob)
232 uid: ???????????????? (glob)
224 tip-rev: 5002
233 tip-rev: 5002
225 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
234 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
226 data-length: 121088
235 data-length: 121088
227 data-unused: 0
236 data-unused: 0
228 data-unused: 0.000%
237 data-unused: 0.000%
229 #else
238 #else
230 $ hg debugnodemap --metadata
239 $ hg debugnodemap --metadata
231 uid: ???????????????? (glob)
240 uid: ???????????????? (glob)
232 tip-rev: 5002
241 tip-rev: 5002
233 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
242 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
234 data-length: 121088
243 data-length: 121088
235 data-unused: 0
244 data-unused: 0
236 data-unused: 0.000%
245 data-unused: 0.000%
237 #endif
246 #endif
238
247
239 Check out of sync nodemap
248 Check out of sync nodemap
240 =========================
249 =========================
241
250
242 First copy old data on the side.
251 First copy old data on the side.
243
252
244 $ mkdir ../tmp-copies
253 $ mkdir ../tmp-copies
245 $ cp .hg/store/00changelog-????????????????.nd .hg/store/00changelog.n ../tmp-copies
254 $ cp .hg/store/00changelog-????????????????.nd .hg/store/00changelog.n ../tmp-copies
246
255
247 Nodemap lagging behind
256 Nodemap lagging behind
248 ----------------------
257 ----------------------
249
258
250 make a new commit
259 make a new commit
251
260
252 $ echo bar2 > bar
261 $ echo bar2 > bar
253 $ hg ci -m 'bar2'
262 $ hg ci -m 'bar2'
254 $ NODE=`hg log -r tip -T '{node}\n'`
263 $ NODE=`hg log -r tip -T '{node}\n'`
255 $ hg log -r "$NODE" -T '{rev}\n'
264 $ hg log -r "$NODE" -T '{rev}\n'
256 5003
265 5003
257
266
258 If the nodemap is lagging behind, it can catch up fine
267 If the nodemap is lagging behind, it can catch up fine
259
268
260 $ hg debugnodemap --metadata
269 $ hg debugnodemap --metadata
261 uid: ???????????????? (glob)
270 uid: ???????????????? (glob)
262 tip-rev: 5003
271 tip-rev: 5003
263 tip-node: c9329770f979ade2d16912267c38ba5f82fd37b3
272 tip-node: c9329770f979ade2d16912267c38ba5f82fd37b3
264 data-length: 121344 (pure !)
273 data-length: 121344 (pure !)
265 data-length: 121344 (rust !)
274 data-length: 121344 (rust !)
266 data-length: 121152 (no-rust no-pure !)
275 data-length: 121152 (no-rust no-pure !)
267 data-unused: 192 (pure !)
276 data-unused: 192 (pure !)
268 data-unused: 192 (rust !)
277 data-unused: 192 (rust !)
269 data-unused: 0 (no-rust no-pure !)
278 data-unused: 0 (no-rust no-pure !)
270 data-unused: 0.158% (pure !)
279 data-unused: 0.158% (pure !)
271 data-unused: 0.158% (rust !)
280 data-unused: 0.158% (rust !)
272 data-unused: 0.000% (no-rust no-pure !)
281 data-unused: 0.000% (no-rust no-pure !)
273 $ cp -f ../tmp-copies/* .hg/store/
282 $ cp -f ../tmp-copies/* .hg/store/
274 $ hg debugnodemap --metadata
283 $ hg debugnodemap --metadata
275 uid: ???????????????? (glob)
284 uid: ???????????????? (glob)
276 tip-rev: 5002
285 tip-rev: 5002
277 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
286 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
278 data-length: 121088
287 data-length: 121088
279 data-unused: 0
288 data-unused: 0
280 data-unused: 0.000%
289 data-unused: 0.000%
281 $ hg log -r "$NODE" -T '{rev}\n'
290 $ hg log -r "$NODE" -T '{rev}\n'
282 5003
291 5003
283
292
284 changelog altered
293 changelog altered
285 -----------------
294 -----------------
286
295
287 If the nodemap is not gated behind a requirements, an unaware client can alter
296 If the nodemap is not gated behind a requirements, an unaware client can alter
288 the repository so the revlog used to generate the nodemap is not longer
297 the repository so the revlog used to generate the nodemap is not longer
289 compatible with the persistent nodemap. We need to detect that.
298 compatible with the persistent nodemap. We need to detect that.
290
299
291 $ hg up "$NODE~5"
300 $ hg up "$NODE~5"
292 0 files updated, 0 files merged, 4 files removed, 0 files unresolved
301 0 files updated, 0 files merged, 4 files removed, 0 files unresolved
293 $ echo bar > babar
302 $ echo bar > babar
294 $ hg add babar
303 $ hg add babar
295 $ hg ci -m 'babar'
304 $ hg ci -m 'babar'
296 created new head
305 created new head
297 $ OTHERNODE=`hg log -r tip -T '{node}\n'`
306 $ OTHERNODE=`hg log -r tip -T '{node}\n'`
298 $ hg log -r "$OTHERNODE" -T '{rev}\n'
307 $ hg log -r "$OTHERNODE" -T '{rev}\n'
299 5004
308 5004
300
309
301 $ hg --config extensions.strip= strip --rev "$NODE~1" --no-backup
310 $ hg --config extensions.strip= strip --rev "$NODE~1" --no-backup
302
311
303 the nodemap should detect the changelog have been tampered with and recover.
312 the nodemap should detect the changelog have been tampered with and recover.
304
313
305 $ hg debugnodemap --metadata
314 $ hg debugnodemap --metadata
306 uid: ???????????????? (glob)
315 uid: ???????????????? (glob)
307 tip-rev: 5002
316 tip-rev: 5002
308 tip-node: b355ef8adce0949b8bdf6afc72ca853740d65944
317 tip-node: b355ef8adce0949b8bdf6afc72ca853740d65944
309 data-length: 121536 (pure !)
318 data-length: 121536 (pure !)
310 data-length: 121088 (rust !)
319 data-length: 121088 (rust !)
311 data-length: 121088 (no-pure no-rust !)
320 data-length: 121088 (no-pure no-rust !)
312 data-unused: 448 (pure !)
321 data-unused: 448 (pure !)
313 data-unused: 0 (rust !)
322 data-unused: 0 (rust !)
314 data-unused: 0 (no-pure no-rust !)
323 data-unused: 0 (no-pure no-rust !)
315 data-unused: 0.000% (rust !)
324 data-unused: 0.000% (rust !)
316 data-unused: 0.369% (pure !)
325 data-unused: 0.369% (pure !)
317 data-unused: 0.000% (no-pure no-rust !)
326 data-unused: 0.000% (no-pure no-rust !)
318
327
319 $ cp -f ../tmp-copies/* .hg/store/
328 $ cp -f ../tmp-copies/* .hg/store/
320 $ hg debugnodemap --metadata
329 $ hg debugnodemap --metadata
321 uid: ???????????????? (glob)
330 uid: ???????????????? (glob)
322 tip-rev: 5002
331 tip-rev: 5002
323 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
332 tip-node: 880b18d239dfa9f632413a2071bfdbcc4806a4fd
324 data-length: 121088
333 data-length: 121088
325 data-unused: 0
334 data-unused: 0
326 data-unused: 0.000%
335 data-unused: 0.000%
327 $ hg log -r "$OTHERNODE" -T '{rev}\n'
336 $ hg log -r "$OTHERNODE" -T '{rev}\n'
328 5002
337 5002
329
338
330 Check transaction related property
339 Check transaction related property
331 ==================================
340 ==================================
332
341
333 An up to date nodemap should be available to shell hooks,
342 An up to date nodemap should be available to shell hooks,
334
343
335 $ echo dsljfl > a
344 $ echo dsljfl > a
336 $ hg add a
345 $ hg add a
337 $ hg ci -m a
346 $ hg ci -m a
338 $ hg debugnodemap --metadata
347 $ hg debugnodemap --metadata
339 uid: ???????????????? (glob)
348 uid: ???????????????? (glob)
340 tip-rev: 5003
349 tip-rev: 5003
341 tip-node: a52c5079765b5865d97b993b303a18740113bbb2
350 tip-node: a52c5079765b5865d97b993b303a18740113bbb2
342 data-length: 121088
351 data-length: 121088
343 data-unused: 0
352 data-unused: 0
344 data-unused: 0.000%
353 data-unused: 0.000%
345 $ echo babar2 > babar
354 $ echo babar2 > babar
346 $ hg ci -m 'babar2' --config "hooks.pretxnclose.nodemap-test=hg debugnodemap --metadata"
355 $ hg ci -m 'babar2' --config "hooks.pretxnclose.nodemap-test=hg debugnodemap --metadata"
347 uid: ???????????????? (glob)
356 uid: ???????????????? (glob)
348 tip-rev: 5004
357 tip-rev: 5004
349 tip-node: 2f5fb1c06a16834c5679d672e90da7c5f3b1a984
358 tip-node: 2f5fb1c06a16834c5679d672e90da7c5f3b1a984
350 data-length: 121280 (pure !)
359 data-length: 121280 (pure !)
351 data-length: 121280 (rust !)
360 data-length: 121280 (rust !)
352 data-length: 121088 (no-pure no-rust !)
361 data-length: 121088 (no-pure no-rust !)
353 data-unused: 192 (pure !)
362 data-unused: 192 (pure !)
354 data-unused: 192 (rust !)
363 data-unused: 192 (rust !)
355 data-unused: 0 (no-pure no-rust !)
364 data-unused: 0 (no-pure no-rust !)
356 data-unused: 0.158% (pure !)
365 data-unused: 0.158% (pure !)
357 data-unused: 0.158% (rust !)
366 data-unused: 0.158% (rust !)
358 data-unused: 0.000% (no-pure no-rust !)
367 data-unused: 0.000% (no-pure no-rust !)
359 $ hg debugnodemap --metadata
368 $ hg debugnodemap --metadata
360 uid: ???????????????? (glob)
369 uid: ???????????????? (glob)
361 tip-rev: 5004
370 tip-rev: 5004
362 tip-node: 2f5fb1c06a16834c5679d672e90da7c5f3b1a984
371 tip-node: 2f5fb1c06a16834c5679d672e90da7c5f3b1a984
363 data-length: 121280 (pure !)
372 data-length: 121280 (pure !)
364 data-length: 121280 (rust !)
373 data-length: 121280 (rust !)
365 data-length: 121088 (no-pure no-rust !)
374 data-length: 121088 (no-pure no-rust !)
366 data-unused: 192 (pure !)
375 data-unused: 192 (pure !)
367 data-unused: 192 (rust !)
376 data-unused: 192 (rust !)
368 data-unused: 0 (no-pure no-rust !)
377 data-unused: 0 (no-pure no-rust !)
369 data-unused: 0.158% (pure !)
378 data-unused: 0.158% (pure !)
370 data-unused: 0.158% (rust !)
379 data-unused: 0.158% (rust !)
371 data-unused: 0.000% (no-pure no-rust !)
380 data-unused: 0.000% (no-pure no-rust !)
372
381
373 Another process does not see the pending nodemap content during run.
382 Another process does not see the pending nodemap content during run.
374
383
375 $ PATH=$RUNTESTDIR/testlib/:$PATH
384 $ PATH=$RUNTESTDIR/testlib/:$PATH
376 $ echo qpoasp > a
385 $ echo qpoasp > a
377 $ hg ci -m a2 \
386 $ hg ci -m a2 \
378 > --config "hooks.pretxnclose=wait-on-file 20 sync-repo-read sync-txn-pending" \
387 > --config "hooks.pretxnclose=wait-on-file 20 sync-repo-read sync-txn-pending" \
379 > --config "hooks.txnclose=touch sync-txn-close" > output.txt 2>&1 &
388 > --config "hooks.txnclose=touch sync-txn-close" > output.txt 2>&1 &
380
389
381 (read the repository while the commit transaction is pending)
390 (read the repository while the commit transaction is pending)
382
391
383 $ wait-on-file 20 sync-txn-pending && \
392 $ wait-on-file 20 sync-txn-pending && \
384 > hg debugnodemap --metadata && \
393 > hg debugnodemap --metadata && \
385 > wait-on-file 20 sync-txn-close sync-repo-read
394 > wait-on-file 20 sync-txn-close sync-repo-read
386 uid: ???????????????? (glob)
395 uid: ???????????????? (glob)
387 tip-rev: 5004
396 tip-rev: 5004
388 tip-node: 2f5fb1c06a16834c5679d672e90da7c5f3b1a984
397 tip-node: 2f5fb1c06a16834c5679d672e90da7c5f3b1a984
389 data-length: 121280 (pure !)
398 data-length: 121280 (pure !)
390 data-length: 121280 (rust !)
399 data-length: 121280 (rust !)
391 data-length: 121088 (no-pure no-rust !)
400 data-length: 121088 (no-pure no-rust !)
392 data-unused: 192 (pure !)
401 data-unused: 192 (pure !)
393 data-unused: 192 (rust !)
402 data-unused: 192 (rust !)
394 data-unused: 0 (no-pure no-rust !)
403 data-unused: 0 (no-pure no-rust !)
395 data-unused: 0.158% (pure !)
404 data-unused: 0.158% (pure !)
396 data-unused: 0.158% (rust !)
405 data-unused: 0.158% (rust !)
397 data-unused: 0.000% (no-pure no-rust !)
406 data-unused: 0.000% (no-pure no-rust !)
398 $ hg debugnodemap --metadata
407 $ hg debugnodemap --metadata
399 uid: ???????????????? (glob)
408 uid: ???????????????? (glob)
400 tip-rev: 5005
409 tip-rev: 5005
401 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
410 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
402 data-length: 121536 (pure !)
411 data-length: 121536 (pure !)
403 data-length: 121536 (rust !)
412 data-length: 121536 (rust !)
404 data-length: 121088 (no-pure no-rust !)
413 data-length: 121088 (no-pure no-rust !)
405 data-unused: 448 (pure !)
414 data-unused: 448 (pure !)
406 data-unused: 448 (rust !)
415 data-unused: 448 (rust !)
407 data-unused: 0 (no-pure no-rust !)
416 data-unused: 0 (no-pure no-rust !)
408 data-unused: 0.369% (pure !)
417 data-unused: 0.369% (pure !)
409 data-unused: 0.369% (rust !)
418 data-unused: 0.369% (rust !)
410 data-unused: 0.000% (no-pure no-rust !)
419 data-unused: 0.000% (no-pure no-rust !)
411
420
412 $ cat output.txt
421 $ cat output.txt
413
422
414 Check that a failing transaction will properly revert the data
423 Check that a failing transaction will properly revert the data
415
424
416 $ echo plakfe > a
425 $ echo plakfe > a
417 $ f --size --sha256 .hg/store/00changelog-*.nd
426 $ f --size --sha256 .hg/store/00changelog-*.nd
418 .hg/store/00changelog-????????????????.nd: size=121536, sha256=bb414468d225cf52d69132e1237afba34d4346ee2eb81b505027e6197b107f03 (glob) (pure !)
427 .hg/store/00changelog-????????????????.nd: size=121536, sha256=bb414468d225cf52d69132e1237afba34d4346ee2eb81b505027e6197b107f03 (glob) (pure !)
419 .hg/store/00changelog-????????????????.nd: size=121536, sha256=909ac727bc4d1c0fda5f7bff3c620c98bd4a2967c143405a1503439e33b377da (glob) (rust !)
428 .hg/store/00changelog-????????????????.nd: size=121536, sha256=909ac727bc4d1c0fda5f7bff3c620c98bd4a2967c143405a1503439e33b377da (glob) (rust !)
420 .hg/store/00changelog-????????????????.nd: size=121088, sha256=342d36d30d86dde67d3cb6c002606c4a75bcad665595d941493845066d9c8ee0 (glob) (no-pure no-rust !)
429 .hg/store/00changelog-????????????????.nd: size=121088, sha256=342d36d30d86dde67d3cb6c002606c4a75bcad665595d941493845066d9c8ee0 (glob) (no-pure no-rust !)
421 $ hg ci -m a3 --config "extensions.abort=$RUNTESTDIR/testlib/crash_transaction_late.py"
430 $ hg ci -m a3 --config "extensions.abort=$RUNTESTDIR/testlib/crash_transaction_late.py"
422 transaction abort!
431 transaction abort!
423 rollback completed
432 rollback completed
424 abort: This is a late abort
433 abort: This is a late abort
425 [255]
434 [255]
426 $ hg debugnodemap --metadata
435 $ hg debugnodemap --metadata
427 uid: ???????????????? (glob)
436 uid: ???????????????? (glob)
428 tip-rev: 5005
437 tip-rev: 5005
429 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
438 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
430 data-length: 121536 (pure !)
439 data-length: 121536 (pure !)
431 data-length: 121536 (rust !)
440 data-length: 121536 (rust !)
432 data-length: 121088 (no-pure no-rust !)
441 data-length: 121088 (no-pure no-rust !)
433 data-unused: 448 (pure !)
442 data-unused: 448 (pure !)
434 data-unused: 448 (rust !)
443 data-unused: 448 (rust !)
435 data-unused: 0 (no-pure no-rust !)
444 data-unused: 0 (no-pure no-rust !)
436 data-unused: 0.369% (pure !)
445 data-unused: 0.369% (pure !)
437 data-unused: 0.369% (rust !)
446 data-unused: 0.369% (rust !)
438 data-unused: 0.000% (no-pure no-rust !)
447 data-unused: 0.000% (no-pure no-rust !)
439 $ f --size --sha256 .hg/store/00changelog-*.nd
448 $ f --size --sha256 .hg/store/00changelog-*.nd
440 .hg/store/00changelog-????????????????.nd: size=121536, sha256=bb414468d225cf52d69132e1237afba34d4346ee2eb81b505027e6197b107f03 (glob) (pure !)
449 .hg/store/00changelog-????????????????.nd: size=121536, sha256=bb414468d225cf52d69132e1237afba34d4346ee2eb81b505027e6197b107f03 (glob) (pure !)
441 .hg/store/00changelog-????????????????.nd: size=121536, sha256=909ac727bc4d1c0fda5f7bff3c620c98bd4a2967c143405a1503439e33b377da (glob) (rust !)
450 .hg/store/00changelog-????????????????.nd: size=121536, sha256=909ac727bc4d1c0fda5f7bff3c620c98bd4a2967c143405a1503439e33b377da (glob) (rust !)
442 .hg/store/00changelog-????????????????.nd: size=121088, sha256=342d36d30d86dde67d3cb6c002606c4a75bcad665595d941493845066d9c8ee0 (glob) (no-pure no-rust !)
451 .hg/store/00changelog-????????????????.nd: size=121088, sha256=342d36d30d86dde67d3cb6c002606c4a75bcad665595d941493845066d9c8ee0 (glob) (no-pure no-rust !)
443
452
444 Check that removing content does not confuse the nodemap
453 Check that removing content does not confuse the nodemap
445 --------------------------------------------------------
454 --------------------------------------------------------
446
455
447 removing data with rollback
456 removing data with rollback
448
457
449 $ echo aso > a
458 $ echo aso > a
450 $ hg ci -m a4
459 $ hg ci -m a4
451 $ hg rollback
460 $ hg rollback
452 repository tip rolled back to revision 5005 (undo commit)
461 repository tip rolled back to revision 5005 (undo commit)
453 working directory now based on revision 5005
462 working directory now based on revision 5005
454 $ hg id -r .
463 $ hg id -r .
455 90d5d3ba2fc4 tip
464 90d5d3ba2fc4 tip
456
465
457 roming data with strip
466 roming data with strip
458
467
459 $ echo aso > a
468 $ echo aso > a
460 $ hg ci -m a4
469 $ hg ci -m a4
461 $ hg --config extensions.strip= strip -r . --no-backup
470 $ hg --config extensions.strip= strip -r . --no-backup
462 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
471 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
463 $ hg id -r . --traceback
472 $ hg id -r . --traceback
464 90d5d3ba2fc4 tip
473 90d5d3ba2fc4 tip
465
474
466 Test upgrade / downgrade
475 Test upgrade / downgrade
467 ========================
476 ========================
468
477
469 downgrading
478 downgrading
470
479
471 $ cat << EOF >> .hg/hgrc
480 $ cat << EOF >> .hg/hgrc
472 > [format]
481 > [format]
473 > use-persistent-nodemap=no
482 > use-persistent-nodemap=no
474 > EOF
483 > EOF
475 $ hg debugformat -v
484 $ hg debugformat -v
476 format-variant repo config default
485 format-variant repo config default
477 fncache: yes yes yes
486 fncache: yes yes yes
478 dotencode: yes yes yes
487 dotencode: yes yes yes
479 generaldelta: yes yes yes
488 generaldelta: yes yes yes
480 exp-sharesafe: no no no
489 exp-sharesafe: no no no
481 sparserevlog: yes yes yes
490 sparserevlog: yes yes yes
482 sidedata: no no no
491 sidedata: no no no
483 persistent-nodemap: yes no no
492 persistent-nodemap: yes no no
484 copies-sdc: no no no
493 copies-sdc: no no no
485 plain-cl-delta: yes yes yes
494 plain-cl-delta: yes yes yes
486 compression: zlib zlib zlib
495 compression: zlib zlib zlib
487 compression-level: default default default
496 compression-level: default default default
488 $ hg debugupgraderepo --run --no-backup --quiet
497 $ hg debugupgraderepo --run --no-backup --quiet
489 upgrade will perform the following actions:
498 upgrade will perform the following actions:
490
499
491 requirements
500 requirements
492 preserved: dotencode, fncache, generaldelta, revlogv1, sparserevlog, store
501 preserved: dotencode, fncache, generaldelta, revlogv1, sparserevlog, store
493 removed: persistent-nodemap
502 removed: persistent-nodemap
494
503
495 processed revlogs:
504 processed revlogs:
496 - all-filelogs
505 - all-filelogs
497 - changelog
506 - changelog
498 - manifest
507 - manifest
499
508
500 $ ls -1 .hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
509 $ ls -1 .hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
501 [1]
510 [1]
502 $ hg debugnodemap --metadata
511 $ hg debugnodemap --metadata
503
512
504
513
505 upgrading
514 upgrading
506
515
507 $ cat << EOF >> .hg/hgrc
516 $ cat << EOF >> .hg/hgrc
508 > [format]
517 > [format]
509 > use-persistent-nodemap=yes
518 > use-persistent-nodemap=yes
510 > EOF
519 > EOF
511 $ hg debugformat -v
520 $ hg debugformat -v
512 format-variant repo config default
521 format-variant repo config default
513 fncache: yes yes yes
522 fncache: yes yes yes
514 dotencode: yes yes yes
523 dotencode: yes yes yes
515 generaldelta: yes yes yes
524 generaldelta: yes yes yes
516 exp-sharesafe: no no no
525 exp-sharesafe: no no no
517 sparserevlog: yes yes yes
526 sparserevlog: yes yes yes
518 sidedata: no no no
527 sidedata: no no no
519 persistent-nodemap: no yes no
528 persistent-nodemap: no yes no
520 copies-sdc: no no no
529 copies-sdc: no no no
521 plain-cl-delta: yes yes yes
530 plain-cl-delta: yes yes yes
522 compression: zlib zlib zlib
531 compression: zlib zlib zlib
523 compression-level: default default default
532 compression-level: default default default
524 $ hg debugupgraderepo --run --no-backup --quiet
533 $ hg debugupgraderepo --run --no-backup --quiet
525 upgrade will perform the following actions:
534 upgrade will perform the following actions:
526
535
527 requirements
536 requirements
528 preserved: dotencode, fncache, generaldelta, revlogv1, sparserevlog, store
537 preserved: dotencode, fncache, generaldelta, revlogv1, sparserevlog, store
529 added: persistent-nodemap
538 added: persistent-nodemap
530
539
531 processed revlogs:
540 processed revlogs:
532 - all-filelogs
541 - all-filelogs
533 - changelog
542 - changelog
534 - manifest
543 - manifest
535
544
536 $ ls -1 .hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
545 $ ls -1 .hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
537 00changelog-*.nd (glob)
546 00changelog-*.nd (glob)
538 00changelog.n
547 00changelog.n
539 00manifest-*.nd (glob)
548 00manifest-*.nd (glob)
540 00manifest.n
549 00manifest.n
541
550
542 $ hg debugnodemap --metadata
551 $ hg debugnodemap --metadata
543 uid: * (glob)
552 uid: * (glob)
544 tip-rev: 5005
553 tip-rev: 5005
545 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
554 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
546 data-length: 121088
555 data-length: 121088
547 data-unused: 0
556 data-unused: 0
548 data-unused: 0.000%
557 data-unused: 0.000%
549
558
550 Running unrelated upgrade
559 Running unrelated upgrade
551
560
552 $ hg debugupgraderepo --run --no-backup --quiet --optimize re-delta-all
561 $ hg debugupgraderepo --run --no-backup --quiet --optimize re-delta-all
553 upgrade will perform the following actions:
562 upgrade will perform the following actions:
554
563
555 requirements
564 requirements
556 preserved: dotencode, fncache, generaldelta, persistent-nodemap, revlogv1, sparserevlog, store
565 preserved: dotencode, fncache, generaldelta, persistent-nodemap, revlogv1, sparserevlog, store
557
566
558 optimisations: re-delta-all
567 optimisations: re-delta-all
559
568
560 processed revlogs:
569 processed revlogs:
561 - all-filelogs
570 - all-filelogs
562 - changelog
571 - changelog
563 - manifest
572 - manifest
564
573
565 $ ls -1 .hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
574 $ ls -1 .hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
566 00changelog-*.nd (glob)
575 00changelog-*.nd (glob)
567 00changelog.n
576 00changelog.n
568 00manifest-*.nd (glob)
577 00manifest-*.nd (glob)
569 00manifest.n
578 00manifest.n
570
579
571 $ hg debugnodemap --metadata
580 $ hg debugnodemap --metadata
572 uid: * (glob)
581 uid: * (glob)
573 tip-rev: 5005
582 tip-rev: 5005
574 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
583 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
575 data-length: 121088
584 data-length: 121088
576 data-unused: 0
585 data-unused: 0
577 data-unused: 0.000%
586 data-unused: 0.000%
578
587
579 Persistent nodemap and local/streaming clone
588 Persistent nodemap and local/streaming clone
580 ============================================
589 ============================================
581
590
582 $ cd ..
591 $ cd ..
583
592
584 standard clone
593 standard clone
585 --------------
594 --------------
586
595
587 The persistent nodemap should exist after a streaming clone
596 The persistent nodemap should exist after a streaming clone
588
597
589 $ hg clone --pull --quiet -U test-repo standard-clone
598 $ hg clone --pull --quiet -U test-repo standard-clone
590 $ ls -1 standard-clone/.hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
599 $ ls -1 standard-clone/.hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
591 00changelog-*.nd (glob)
600 00changelog-*.nd (glob)
592 00changelog.n
601 00changelog.n
593 00manifest-*.nd (glob)
602 00manifest-*.nd (glob)
594 00manifest.n
603 00manifest.n
595 $ hg -R standard-clone debugnodemap --metadata
604 $ hg -R standard-clone debugnodemap --metadata
596 uid: * (glob)
605 uid: * (glob)
597 tip-rev: 5005
606 tip-rev: 5005
598 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
607 tip-node: 90d5d3ba2fc47db50f712570487cb261a68c8ffe
599 data-length: 121088
608 data-length: 121088
600 data-unused: 0
609 data-unused: 0
601 data-unused: 0.000%
610 data-unused: 0.000%
602
611
603
612
604 local clone
613 local clone
605 ------------
614 ------------
606
615
607 The persistent nodemap should exist after a streaming clone
616 The persistent nodemap should exist after a streaming clone
608
617
609 $ hg clone -U test-repo local-clone
618 $ hg clone -U test-repo local-clone
610 $ ls -1 local-clone/.hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
619 $ ls -1 local-clone/.hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
611 [1]
620 [1]
612 $ hg -R local-clone debugnodemap --metadata
621 $ hg -R local-clone debugnodemap --metadata
613
622
614 stream clone
623 stream clone
615 ------------
624 ------------
616
625
617 The persistent nodemap should exist after a streaming clone
626 The persistent nodemap should exist after a streaming clone
618
627
619 $ hg clone -U --stream --config ui.ssh="\"$PYTHON\" \"$TESTDIR/dummyssh\"" ssh://user@dummy/test-repo stream-clone --debug | egrep '00(changelog|manifest)'
628 $ hg clone -U --stream --config ui.ssh="\"$PYTHON\" \"$TESTDIR/dummyssh\"" ssh://user@dummy/test-repo stream-clone --debug | egrep '00(changelog|manifest)'
620 adding [s] 00manifest.n (70 bytes)
629 adding [s] 00manifest.n (70 bytes)
621 adding [s] 00manifest.i (313 KB)
630 adding [s] 00manifest.i (313 KB)
622 adding [s] 00manifest.d (452 KB)
631 adding [s] 00manifest.d (452 KB)
623 adding [s] 00changelog.n (70 bytes)
632 adding [s] 00changelog.n (70 bytes)
624 adding [s] 00changelog.i (313 KB)
633 adding [s] 00changelog.i (313 KB)
625 adding [s] 00changelog.d (360 KB)
634 adding [s] 00changelog.d (360 KB)
626 $ ls -1 stream-clone/.hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
635 $ ls -1 stream-clone/.hg/store/ | egrep '00(changelog|manifest)(\.n|-.*\.nd)'
627 [1]
636 [1]
628 $ hg -R stream-clone debugnodemap --metadata
637 $ hg -R stream-clone debugnodemap --metadata
General Comments 0
You need to be logged in to leave comments. Login now