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