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