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