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