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