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