##// END OF EJS Templates
status: fix post status invalidation...
marmoute -
r50951:1f369ca9 default
parent child Browse files
Show More
@@ -1,3153 +1,3155 b''
1 1 # context.py - changeset and file context objects for mercurial
2 2 #
3 3 # Copyright 2006, 2007 Olivia Mackall <olivia@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
9 9 import filecmp
10 10 import os
11 11 import stat
12 12
13 13 from .i18n import _
14 14 from .node import (
15 15 hex,
16 16 nullrev,
17 17 short,
18 18 )
19 19 from .pycompat import (
20 20 getattr,
21 21 )
22 22 from . import (
23 23 dagop,
24 24 encoding,
25 25 error,
26 26 fileset,
27 27 match as matchmod,
28 28 mergestate as mergestatemod,
29 29 metadata,
30 30 obsolete as obsmod,
31 31 patch,
32 32 pathutil,
33 33 phases,
34 34 repoview,
35 35 scmutil,
36 36 sparse,
37 37 subrepo,
38 38 subrepoutil,
39 39 util,
40 40 )
41 41 from .utils import (
42 42 dateutil,
43 43 stringutil,
44 44 )
45 45 from .dirstateutils import (
46 46 timestamp,
47 47 )
48 48
49 49 propertycache = util.propertycache
50 50
51 51
52 52 class basectx:
53 53 """A basectx object represents the common logic for its children:
54 54 changectx: read-only context that is already present in the repo,
55 55 workingctx: a context that represents the working directory and can
56 56 be committed,
57 57 memctx: a context that represents changes in-memory and can also
58 58 be committed."""
59 59
60 60 def __init__(self, repo):
61 61 self._repo = repo
62 62
63 63 def __bytes__(self):
64 64 return short(self.node())
65 65
66 66 __str__ = encoding.strmethod(__bytes__)
67 67
68 68 def __repr__(self):
69 69 return "<%s %s>" % (type(self).__name__, str(self))
70 70
71 71 def __eq__(self, other):
72 72 try:
73 73 return type(self) == type(other) and self._rev == other._rev
74 74 except AttributeError:
75 75 return False
76 76
77 77 def __ne__(self, other):
78 78 return not (self == other)
79 79
80 80 def __contains__(self, key):
81 81 return key in self._manifest
82 82
83 83 def __getitem__(self, key):
84 84 return self.filectx(key)
85 85
86 86 def __iter__(self):
87 87 return iter(self._manifest)
88 88
89 89 def _buildstatusmanifest(self, status):
90 90 """Builds a manifest that includes the given status results, if this is
91 91 a working copy context. For non-working copy contexts, it just returns
92 92 the normal manifest."""
93 93 return self.manifest()
94 94
95 95 def _matchstatus(self, other, match):
96 96 """This internal method provides a way for child objects to override the
97 97 match operator.
98 98 """
99 99 return match
100 100
101 101 def _buildstatus(
102 102 self, other, s, match, listignored, listclean, listunknown
103 103 ):
104 104 """build a status with respect to another context"""
105 105 # Load earliest manifest first for caching reasons. More specifically,
106 106 # if you have revisions 1000 and 1001, 1001 is probably stored as a
107 107 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
108 108 # 1000 and cache it so that when you read 1001, we just need to apply a
109 109 # delta to what's in the cache. So that's one full reconstruction + one
110 110 # delta application.
111 111 mf2 = None
112 112 if self.rev() is not None and self.rev() < other.rev():
113 113 mf2 = self._buildstatusmanifest(s)
114 114 mf1 = other._buildstatusmanifest(s)
115 115 if mf2 is None:
116 116 mf2 = self._buildstatusmanifest(s)
117 117
118 118 modified, added = [], []
119 119 removed = []
120 120 clean = []
121 121 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
122 122 deletedset = set(deleted)
123 123 d = mf1.diff(mf2, match=match, clean=listclean)
124 124 for fn, value in d.items():
125 125 if fn in deletedset:
126 126 continue
127 127 if value is None:
128 128 clean.append(fn)
129 129 continue
130 130 (node1, flag1), (node2, flag2) = value
131 131 if node1 is None:
132 132 added.append(fn)
133 133 elif node2 is None:
134 134 removed.append(fn)
135 135 elif flag1 != flag2:
136 136 modified.append(fn)
137 137 elif node2 not in self._repo.nodeconstants.wdirfilenodeids:
138 138 # When comparing files between two commits, we save time by
139 139 # not comparing the file contents when the nodeids differ.
140 140 # Note that this means we incorrectly report a reverted change
141 141 # to a file as a modification.
142 142 modified.append(fn)
143 143 elif self[fn].cmp(other[fn]):
144 144 modified.append(fn)
145 145 else:
146 146 clean.append(fn)
147 147
148 148 if removed:
149 149 # need to filter files if they are already reported as removed
150 150 unknown = [
151 151 fn
152 152 for fn in unknown
153 153 if fn not in mf1 and (not match or match(fn))
154 154 ]
155 155 ignored = [
156 156 fn
157 157 for fn in ignored
158 158 if fn not in mf1 and (not match or match(fn))
159 159 ]
160 160 # if they're deleted, don't report them as removed
161 161 removed = [fn for fn in removed if fn not in deletedset]
162 162
163 163 return scmutil.status(
164 164 modified, added, removed, deleted, unknown, ignored, clean
165 165 )
166 166
167 167 @propertycache
168 168 def substate(self):
169 169 return subrepoutil.state(self, self._repo.ui)
170 170
171 171 def subrev(self, subpath):
172 172 return self.substate[subpath][1]
173 173
174 174 def rev(self):
175 175 return self._rev
176 176
177 177 def node(self):
178 178 return self._node
179 179
180 180 def hex(self):
181 181 return hex(self.node())
182 182
183 183 def manifest(self):
184 184 return self._manifest
185 185
186 186 def manifestctx(self):
187 187 return self._manifestctx
188 188
189 189 def repo(self):
190 190 return self._repo
191 191
192 192 def phasestr(self):
193 193 return phases.phasenames[self.phase()]
194 194
195 195 def mutable(self):
196 196 return self.phase() > phases.public
197 197
198 198 def matchfileset(self, cwd, expr, badfn=None):
199 199 return fileset.match(self, cwd, expr, badfn=badfn)
200 200
201 201 def obsolete(self):
202 202 """True if the changeset is obsolete"""
203 203 return self.rev() in obsmod.getrevs(self._repo, b'obsolete')
204 204
205 205 def extinct(self):
206 206 """True if the changeset is extinct"""
207 207 return self.rev() in obsmod.getrevs(self._repo, b'extinct')
208 208
209 209 def orphan(self):
210 210 """True if the changeset is not obsolete, but its ancestor is"""
211 211 return self.rev() in obsmod.getrevs(self._repo, b'orphan')
212 212
213 213 def phasedivergent(self):
214 214 """True if the changeset tries to be a successor of a public changeset
215 215
216 216 Only non-public and non-obsolete changesets may be phase-divergent.
217 217 """
218 218 return self.rev() in obsmod.getrevs(self._repo, b'phasedivergent')
219 219
220 220 def contentdivergent(self):
221 221 """Is a successor of a changeset with multiple possible successor sets
222 222
223 223 Only non-public and non-obsolete changesets may be content-divergent.
224 224 """
225 225 return self.rev() in obsmod.getrevs(self._repo, b'contentdivergent')
226 226
227 227 def isunstable(self):
228 228 """True if the changeset is either orphan, phase-divergent or
229 229 content-divergent"""
230 230 return self.orphan() or self.phasedivergent() or self.contentdivergent()
231 231
232 232 def instabilities(self):
233 233 """return the list of instabilities affecting this changeset.
234 234
235 235 Instabilities are returned as strings. possible values are:
236 236 - orphan,
237 237 - phase-divergent,
238 238 - content-divergent.
239 239 """
240 240 instabilities = []
241 241 if self.orphan():
242 242 instabilities.append(b'orphan')
243 243 if self.phasedivergent():
244 244 instabilities.append(b'phase-divergent')
245 245 if self.contentdivergent():
246 246 instabilities.append(b'content-divergent')
247 247 return instabilities
248 248
249 249 def parents(self):
250 250 """return contexts for each parent changeset"""
251 251 return self._parents
252 252
253 253 def p1(self):
254 254 return self._parents[0]
255 255
256 256 def p2(self):
257 257 parents = self._parents
258 258 if len(parents) == 2:
259 259 return parents[1]
260 260 return self._repo[nullrev]
261 261
262 262 def _fileinfo(self, path):
263 263 if '_manifest' in self.__dict__:
264 264 try:
265 265 return self._manifest.find(path)
266 266 except KeyError:
267 267 raise error.ManifestLookupError(
268 268 self._node or b'None', path, _(b'not found in manifest')
269 269 )
270 270 if '_manifestdelta' in self.__dict__ or path in self.files():
271 271 if path in self._manifestdelta:
272 272 return (
273 273 self._manifestdelta[path],
274 274 self._manifestdelta.flags(path),
275 275 )
276 276 mfl = self._repo.manifestlog
277 277 try:
278 278 node, flag = mfl[self._changeset.manifest].find(path)
279 279 except KeyError:
280 280 raise error.ManifestLookupError(
281 281 self._node or b'None', path, _(b'not found in manifest')
282 282 )
283 283
284 284 return node, flag
285 285
286 286 def filenode(self, path):
287 287 return self._fileinfo(path)[0]
288 288
289 289 def flags(self, path):
290 290 try:
291 291 return self._fileinfo(path)[1]
292 292 except error.LookupError:
293 293 return b''
294 294
295 295 @propertycache
296 296 def _copies(self):
297 297 return metadata.computechangesetcopies(self)
298 298
299 299 def p1copies(self):
300 300 return self._copies[0]
301 301
302 302 def p2copies(self):
303 303 return self._copies[1]
304 304
305 305 def sub(self, path, allowcreate=True):
306 306 '''return a subrepo for the stored revision of path, never wdir()'''
307 307 return subrepo.subrepo(self, path, allowcreate=allowcreate)
308 308
309 309 def nullsub(self, path, pctx):
310 310 return subrepo.nullsubrepo(self, path, pctx)
311 311
312 312 def workingsub(self, path):
313 313 """return a subrepo for the stored revision, or wdir if this is a wdir
314 314 context.
315 315 """
316 316 return subrepo.subrepo(self, path, allowwdir=True)
317 317
318 318 def match(
319 319 self,
320 320 pats=None,
321 321 include=None,
322 322 exclude=None,
323 323 default=b'glob',
324 324 listsubrepos=False,
325 325 badfn=None,
326 326 cwd=None,
327 327 ):
328 328 r = self._repo
329 329 if not cwd:
330 330 cwd = r.getcwd()
331 331 return matchmod.match(
332 332 r.root,
333 333 cwd,
334 334 pats,
335 335 include,
336 336 exclude,
337 337 default,
338 338 auditor=r.nofsauditor,
339 339 ctx=self,
340 340 listsubrepos=listsubrepos,
341 341 badfn=badfn,
342 342 )
343 343
344 344 def diff(
345 345 self,
346 346 ctx2=None,
347 347 match=None,
348 348 changes=None,
349 349 opts=None,
350 350 losedatafn=None,
351 351 pathfn=None,
352 352 copy=None,
353 353 copysourcematch=None,
354 354 hunksfilterfn=None,
355 355 ):
356 356 """Returns a diff generator for the given contexts and matcher"""
357 357 if ctx2 is None:
358 358 ctx2 = self.p1()
359 359 if ctx2 is not None:
360 360 ctx2 = self._repo[ctx2]
361 361 return patch.diff(
362 362 self._repo,
363 363 ctx2,
364 364 self,
365 365 match=match,
366 366 changes=changes,
367 367 opts=opts,
368 368 losedatafn=losedatafn,
369 369 pathfn=pathfn,
370 370 copy=copy,
371 371 copysourcematch=copysourcematch,
372 372 hunksfilterfn=hunksfilterfn,
373 373 )
374 374
375 375 def dirs(self):
376 376 return self._manifest.dirs()
377 377
378 378 def hasdir(self, dir):
379 379 return self._manifest.hasdir(dir)
380 380
381 381 def status(
382 382 self,
383 383 other=None,
384 384 match=None,
385 385 listignored=False,
386 386 listclean=False,
387 387 listunknown=False,
388 388 listsubrepos=False,
389 389 ):
390 390 """return status of files between two nodes or node and working
391 391 directory.
392 392
393 393 If other is None, compare this node with working directory.
394 394
395 395 ctx1.status(ctx2) returns the status of change from ctx1 to ctx2
396 396
397 397 Returns a mercurial.scmutils.status object.
398 398
399 399 Data can be accessed using either tuple notation:
400 400
401 401 (modified, added, removed, deleted, unknown, ignored, clean)
402 402
403 403 or direct attribute access:
404 404
405 405 s.modified, s.added, ...
406 406 """
407 407
408 408 ctx1 = self
409 409 ctx2 = self._repo[other]
410 410
411 411 # This next code block is, admittedly, fragile logic that tests for
412 412 # reversing the contexts and wouldn't need to exist if it weren't for
413 413 # the fast (and common) code path of comparing the working directory
414 414 # with its first parent.
415 415 #
416 416 # What we're aiming for here is the ability to call:
417 417 #
418 418 # workingctx.status(parentctx)
419 419 #
420 420 # If we always built the manifest for each context and compared those,
421 421 # then we'd be done. But the special case of the above call means we
422 422 # just copy the manifest of the parent.
423 423 reversed = False
424 424 if not isinstance(ctx1, changectx) and isinstance(ctx2, changectx):
425 425 reversed = True
426 426 ctx1, ctx2 = ctx2, ctx1
427 427
428 428 match = self._repo.narrowmatch(match)
429 429 match = ctx2._matchstatus(ctx1, match)
430 430 r = scmutil.status([], [], [], [], [], [], [])
431 431 r = ctx2._buildstatus(
432 432 ctx1, r, match, listignored, listclean, listunknown
433 433 )
434 434
435 435 if reversed:
436 436 # Reverse added and removed. Clear deleted, unknown and ignored as
437 437 # these make no sense to reverse.
438 438 r = scmutil.status(
439 439 r.modified, r.removed, r.added, [], [], [], r.clean
440 440 )
441 441
442 442 if listsubrepos:
443 443 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
444 444 try:
445 445 rev2 = ctx2.subrev(subpath)
446 446 except KeyError:
447 447 # A subrepo that existed in node1 was deleted between
448 448 # node1 and node2 (inclusive). Thus, ctx2's substate
449 449 # won't contain that subpath. The best we can do ignore it.
450 450 rev2 = None
451 451 submatch = matchmod.subdirmatcher(subpath, match)
452 452 s = sub.status(
453 453 rev2,
454 454 match=submatch,
455 455 ignored=listignored,
456 456 clean=listclean,
457 457 unknown=listunknown,
458 458 listsubrepos=True,
459 459 )
460 460 for k in (
461 461 'modified',
462 462 'added',
463 463 'removed',
464 464 'deleted',
465 465 'unknown',
466 466 'ignored',
467 467 'clean',
468 468 ):
469 469 rfiles, sfiles = getattr(r, k), getattr(s, k)
470 470 rfiles.extend(b"%s/%s" % (subpath, f) for f in sfiles)
471 471
472 472 r.modified.sort()
473 473 r.added.sort()
474 474 r.removed.sort()
475 475 r.deleted.sort()
476 476 r.unknown.sort()
477 477 r.ignored.sort()
478 478 r.clean.sort()
479 479
480 480 return r
481 481
482 482 def mergestate(self, clean=False):
483 483 """Get a mergestate object for this context."""
484 484 raise NotImplementedError(
485 485 '%s does not implement mergestate()' % self.__class__
486 486 )
487 487
488 488 def isempty(self):
489 489 return not (
490 490 len(self.parents()) > 1
491 491 or self.branch() != self.p1().branch()
492 492 or self.closesbranch()
493 493 or self.files()
494 494 )
495 495
496 496
497 497 class changectx(basectx):
498 498 """A changecontext object makes access to data related to a particular
499 499 changeset convenient. It represents a read-only context already present in
500 500 the repo."""
501 501
502 502 def __init__(self, repo, rev, node, maybe_filtered=True):
503 503 super(changectx, self).__init__(repo)
504 504 self._rev = rev
505 505 self._node = node
506 506 # When maybe_filtered is True, the revision might be affected by
507 507 # changelog filtering and operation through the filtered changelog must be used.
508 508 #
509 509 # When maybe_filtered is False, the revision has already been checked
510 510 # against filtering and is not filtered. Operation through the
511 511 # unfiltered changelog might be used in some case.
512 512 self._maybe_filtered = maybe_filtered
513 513
514 514 def __hash__(self):
515 515 try:
516 516 return hash(self._rev)
517 517 except AttributeError:
518 518 return id(self)
519 519
520 520 def __nonzero__(self):
521 521 return self._rev != nullrev
522 522
523 523 __bool__ = __nonzero__
524 524
525 525 @propertycache
526 526 def _changeset(self):
527 527 if self._maybe_filtered:
528 528 repo = self._repo
529 529 else:
530 530 repo = self._repo.unfiltered()
531 531 return repo.changelog.changelogrevision(self.rev())
532 532
533 533 @propertycache
534 534 def _manifest(self):
535 535 return self._manifestctx.read()
536 536
537 537 @property
538 538 def _manifestctx(self):
539 539 return self._repo.manifestlog[self._changeset.manifest]
540 540
541 541 @propertycache
542 542 def _manifestdelta(self):
543 543 return self._manifestctx.readdelta()
544 544
545 545 @propertycache
546 546 def _parents(self):
547 547 repo = self._repo
548 548 if self._maybe_filtered:
549 549 cl = repo.changelog
550 550 else:
551 551 cl = repo.unfiltered().changelog
552 552
553 553 p1, p2 = cl.parentrevs(self._rev)
554 554 if p2 == nullrev:
555 555 return [changectx(repo, p1, cl.node(p1), maybe_filtered=False)]
556 556 return [
557 557 changectx(repo, p1, cl.node(p1), maybe_filtered=False),
558 558 changectx(repo, p2, cl.node(p2), maybe_filtered=False),
559 559 ]
560 560
561 561 def changeset(self):
562 562 c = self._changeset
563 563 return (
564 564 c.manifest,
565 565 c.user,
566 566 c.date,
567 567 c.files,
568 568 c.description,
569 569 c.extra,
570 570 )
571 571
572 572 def manifestnode(self):
573 573 return self._changeset.manifest
574 574
575 575 def user(self):
576 576 return self._changeset.user
577 577
578 578 def date(self):
579 579 return self._changeset.date
580 580
581 581 def files(self):
582 582 return self._changeset.files
583 583
584 584 def filesmodified(self):
585 585 modified = set(self.files())
586 586 modified.difference_update(self.filesadded())
587 587 modified.difference_update(self.filesremoved())
588 588 return sorted(modified)
589 589
590 590 def filesadded(self):
591 591 filesadded = self._changeset.filesadded
592 592 compute_on_none = True
593 593 if self._repo.filecopiesmode == b'changeset-sidedata':
594 594 compute_on_none = False
595 595 else:
596 596 source = self._repo.ui.config(b'experimental', b'copies.read-from')
597 597 if source == b'changeset-only':
598 598 compute_on_none = False
599 599 elif source != b'compatibility':
600 600 # filelog mode, ignore any changelog content
601 601 filesadded = None
602 602 if filesadded is None:
603 603 if compute_on_none:
604 604 filesadded = metadata.computechangesetfilesadded(self)
605 605 else:
606 606 filesadded = []
607 607 return filesadded
608 608
609 609 def filesremoved(self):
610 610 filesremoved = self._changeset.filesremoved
611 611 compute_on_none = True
612 612 if self._repo.filecopiesmode == b'changeset-sidedata':
613 613 compute_on_none = False
614 614 else:
615 615 source = self._repo.ui.config(b'experimental', b'copies.read-from')
616 616 if source == b'changeset-only':
617 617 compute_on_none = False
618 618 elif source != b'compatibility':
619 619 # filelog mode, ignore any changelog content
620 620 filesremoved = None
621 621 if filesremoved is None:
622 622 if compute_on_none:
623 623 filesremoved = metadata.computechangesetfilesremoved(self)
624 624 else:
625 625 filesremoved = []
626 626 return filesremoved
627 627
628 628 @propertycache
629 629 def _copies(self):
630 630 p1copies = self._changeset.p1copies
631 631 p2copies = self._changeset.p2copies
632 632 compute_on_none = True
633 633 if self._repo.filecopiesmode == b'changeset-sidedata':
634 634 compute_on_none = False
635 635 else:
636 636 source = self._repo.ui.config(b'experimental', b'copies.read-from')
637 637 # If config says to get copy metadata only from changeset, then
638 638 # return that, defaulting to {} if there was no copy metadata. In
639 639 # compatibility mode, we return copy data from the changeset if it
640 640 # was recorded there, and otherwise we fall back to getting it from
641 641 # the filelogs (below).
642 642 #
643 643 # If we are in compatiblity mode and there is not data in the
644 644 # changeset), we get the copy metadata from the filelogs.
645 645 #
646 646 # otherwise, when config said to read only from filelog, we get the
647 647 # copy metadata from the filelogs.
648 648 if source == b'changeset-only':
649 649 compute_on_none = False
650 650 elif source != b'compatibility':
651 651 # filelog mode, ignore any changelog content
652 652 p1copies = p2copies = None
653 653 if p1copies is None:
654 654 if compute_on_none:
655 655 p1copies, p2copies = super(changectx, self)._copies
656 656 else:
657 657 if p1copies is None:
658 658 p1copies = {}
659 659 if p2copies is None:
660 660 p2copies = {}
661 661 return p1copies, p2copies
662 662
663 663 def description(self):
664 664 return self._changeset.description
665 665
666 666 def branch(self):
667 667 return encoding.tolocal(self._changeset.extra.get(b"branch"))
668 668
669 669 def closesbranch(self):
670 670 return b'close' in self._changeset.extra
671 671
672 672 def extra(self):
673 673 """Return a dict of extra information."""
674 674 return self._changeset.extra
675 675
676 676 def tags(self):
677 677 """Return a list of byte tag names"""
678 678 return self._repo.nodetags(self._node)
679 679
680 680 def bookmarks(self):
681 681 """Return a list of byte bookmark names."""
682 682 return self._repo.nodebookmarks(self._node)
683 683
684 684 def fast_rank(self):
685 685 repo = self._repo
686 686 if self._maybe_filtered:
687 687 cl = repo.changelog
688 688 else:
689 689 cl = repo.unfiltered().changelog
690 690 return cl.fast_rank(self._rev)
691 691
692 692 def phase(self):
693 693 return self._repo._phasecache.phase(self._repo, self._rev)
694 694
695 695 def hidden(self):
696 696 return self._rev in repoview.filterrevs(self._repo, b'visible')
697 697
698 698 def isinmemory(self):
699 699 return False
700 700
701 701 def children(self):
702 702 """return list of changectx contexts for each child changeset.
703 703
704 704 This returns only the immediate child changesets. Use descendants() to
705 705 recursively walk children.
706 706 """
707 707 c = self._repo.changelog.children(self._node)
708 708 return [self._repo[x] for x in c]
709 709
710 710 def ancestors(self):
711 711 for a in self._repo.changelog.ancestors([self._rev]):
712 712 yield self._repo[a]
713 713
714 714 def descendants(self):
715 715 """Recursively yield all children of the changeset.
716 716
717 717 For just the immediate children, use children()
718 718 """
719 719 for d in self._repo.changelog.descendants([self._rev]):
720 720 yield self._repo[d]
721 721
722 722 def filectx(self, path, fileid=None, filelog=None):
723 723 """get a file context from this changeset"""
724 724 if fileid is None:
725 725 fileid = self.filenode(path)
726 726 return filectx(
727 727 self._repo, path, fileid=fileid, changectx=self, filelog=filelog
728 728 )
729 729
730 730 def ancestor(self, c2, warn=False):
731 731 """return the "best" ancestor context of self and c2
732 732
733 733 If there are multiple candidates, it will show a message and check
734 734 merge.preferancestor configuration before falling back to the
735 735 revlog ancestor."""
736 736 # deal with workingctxs
737 737 n2 = c2._node
738 738 if n2 is None:
739 739 n2 = c2._parents[0]._node
740 740 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
741 741 if not cahs:
742 742 anc = self._repo.nodeconstants.nullid
743 743 elif len(cahs) == 1:
744 744 anc = cahs[0]
745 745 else:
746 746 # experimental config: merge.preferancestor
747 747 for r in self._repo.ui.configlist(b'merge', b'preferancestor'):
748 748 try:
749 749 ctx = scmutil.revsymbol(self._repo, r)
750 750 except error.RepoLookupError:
751 751 continue
752 752 anc = ctx.node()
753 753 if anc in cahs:
754 754 break
755 755 else:
756 756 anc = self._repo.changelog.ancestor(self._node, n2)
757 757 if warn:
758 758 self._repo.ui.status(
759 759 (
760 760 _(b"note: using %s as ancestor of %s and %s\n")
761 761 % (short(anc), short(self._node), short(n2))
762 762 )
763 763 + b''.join(
764 764 _(
765 765 b" alternatively, use --config "
766 766 b"merge.preferancestor=%s\n"
767 767 )
768 768 % short(n)
769 769 for n in sorted(cahs)
770 770 if n != anc
771 771 )
772 772 )
773 773 return self._repo[anc]
774 774
775 775 def isancestorof(self, other):
776 776 """True if this changeset is an ancestor of other"""
777 777 return self._repo.changelog.isancestorrev(self._rev, other._rev)
778 778
779 779 def walk(self, match):
780 780 '''Generates matching file names.'''
781 781
782 782 # Wrap match.bad method to have message with nodeid
783 783 def bad(fn, msg):
784 784 # The manifest doesn't know about subrepos, so don't complain about
785 785 # paths into valid subrepos.
786 786 if any(fn == s or fn.startswith(s + b'/') for s in self.substate):
787 787 return
788 788 match.bad(fn, _(b'no such file in rev %s') % self)
789 789
790 790 m = matchmod.badmatch(self._repo.narrowmatch(match), bad)
791 791 return self._manifest.walk(m)
792 792
793 793 def matches(self, match):
794 794 return self.walk(match)
795 795
796 796
797 797 class basefilectx:
798 798 """A filecontext object represents the common logic for its children:
799 799 filectx: read-only access to a filerevision that is already present
800 800 in the repo,
801 801 workingfilectx: a filecontext that represents files from the working
802 802 directory,
803 803 memfilectx: a filecontext that represents files in-memory,
804 804 """
805 805
806 806 @propertycache
807 807 def _filelog(self):
808 808 return self._repo.file(self._path)
809 809
810 810 @propertycache
811 811 def _changeid(self):
812 812 if '_changectx' in self.__dict__:
813 813 return self._changectx.rev()
814 814 elif '_descendantrev' in self.__dict__:
815 815 # this file context was created from a revision with a known
816 816 # descendant, we can (lazily) correct for linkrev aliases
817 817 return self._adjustlinkrev(self._descendantrev)
818 818 else:
819 819 return self._filelog.linkrev(self._filerev)
820 820
821 821 @propertycache
822 822 def _filenode(self):
823 823 if '_fileid' in self.__dict__:
824 824 return self._filelog.lookup(self._fileid)
825 825 else:
826 826 return self._changectx.filenode(self._path)
827 827
828 828 @propertycache
829 829 def _filerev(self):
830 830 return self._filelog.rev(self._filenode)
831 831
832 832 @propertycache
833 833 def _repopath(self):
834 834 return self._path
835 835
836 836 def __nonzero__(self):
837 837 try:
838 838 self._filenode
839 839 return True
840 840 except error.LookupError:
841 841 # file is missing
842 842 return False
843 843
844 844 __bool__ = __nonzero__
845 845
846 846 def __bytes__(self):
847 847 try:
848 848 return b"%s@%s" % (self.path(), self._changectx)
849 849 except error.LookupError:
850 850 return b"%s@???" % self.path()
851 851
852 852 __str__ = encoding.strmethod(__bytes__)
853 853
854 854 def __repr__(self):
855 855 return "<%s %s>" % (type(self).__name__, str(self))
856 856
857 857 def __hash__(self):
858 858 try:
859 859 return hash((self._path, self._filenode))
860 860 except AttributeError:
861 861 return id(self)
862 862
863 863 def __eq__(self, other):
864 864 try:
865 865 return (
866 866 type(self) == type(other)
867 867 and self._path == other._path
868 868 and self._filenode == other._filenode
869 869 )
870 870 except AttributeError:
871 871 return False
872 872
873 873 def __ne__(self, other):
874 874 return not (self == other)
875 875
876 876 def filerev(self):
877 877 return self._filerev
878 878
879 879 def filenode(self):
880 880 return self._filenode
881 881
882 882 @propertycache
883 883 def _flags(self):
884 884 return self._changectx.flags(self._path)
885 885
886 886 def flags(self):
887 887 return self._flags
888 888
889 889 def filelog(self):
890 890 return self._filelog
891 891
892 892 def rev(self):
893 893 return self._changeid
894 894
895 895 def linkrev(self):
896 896 return self._filelog.linkrev(self._filerev)
897 897
898 898 def node(self):
899 899 return self._changectx.node()
900 900
901 901 def hex(self):
902 902 return self._changectx.hex()
903 903
904 904 def user(self):
905 905 return self._changectx.user()
906 906
907 907 def date(self):
908 908 return self._changectx.date()
909 909
910 910 def files(self):
911 911 return self._changectx.files()
912 912
913 913 def description(self):
914 914 return self._changectx.description()
915 915
916 916 def branch(self):
917 917 return self._changectx.branch()
918 918
919 919 def extra(self):
920 920 return self._changectx.extra()
921 921
922 922 def phase(self):
923 923 return self._changectx.phase()
924 924
925 925 def phasestr(self):
926 926 return self._changectx.phasestr()
927 927
928 928 def obsolete(self):
929 929 return self._changectx.obsolete()
930 930
931 931 def instabilities(self):
932 932 return self._changectx.instabilities()
933 933
934 934 def manifest(self):
935 935 return self._changectx.manifest()
936 936
937 937 def changectx(self):
938 938 return self._changectx
939 939
940 940 def renamed(self):
941 941 return self._copied
942 942
943 943 def copysource(self):
944 944 return self._copied and self._copied[0]
945 945
946 946 def repo(self):
947 947 return self._repo
948 948
949 949 def size(self):
950 950 return len(self.data())
951 951
952 952 def path(self):
953 953 return self._path
954 954
955 955 def isbinary(self):
956 956 try:
957 957 return stringutil.binary(self.data())
958 958 except IOError:
959 959 return False
960 960
961 961 def isexec(self):
962 962 return b'x' in self.flags()
963 963
964 964 def islink(self):
965 965 return b'l' in self.flags()
966 966
967 967 def isabsent(self):
968 968 """whether this filectx represents a file not in self._changectx
969 969
970 970 This is mainly for merge code to detect change/delete conflicts. This is
971 971 expected to be True for all subclasses of basectx."""
972 972 return False
973 973
974 974 _customcmp = False
975 975
976 976 def cmp(self, fctx):
977 977 """compare with other file context
978 978
979 979 returns True if different than fctx.
980 980 """
981 981 if fctx._customcmp:
982 982 return fctx.cmp(self)
983 983
984 984 if self._filenode is None:
985 985 raise error.ProgrammingError(
986 986 b'filectx.cmp() must be reimplemented if not backed by revlog'
987 987 )
988 988
989 989 if fctx._filenode is None:
990 990 if self._repo._encodefilterpats:
991 991 # can't rely on size() because wdir content may be decoded
992 992 return self._filelog.cmp(self._filenode, fctx.data())
993 993 # filelog.size() has two special cases:
994 994 # - censored metadata
995 995 # - copy/rename tracking
996 996 # The first is detected by peaking into the delta,
997 997 # the second is detected by abusing parent order
998 998 # in the revlog index as flag bit. This leaves files using
999 999 # the dummy encoding and non-standard meta attributes.
1000 1000 # The following check is a special case for the empty
1001 1001 # metadata block used if the raw file content starts with '\1\n'.
1002 1002 # Cases of arbitrary metadata flags are currently mishandled.
1003 1003 if self.size() - 4 == fctx.size():
1004 1004 # size() can match:
1005 1005 # if file data starts with '\1\n', empty metadata block is
1006 1006 # prepended, which adds 4 bytes to filelog.size().
1007 1007 return self._filelog.cmp(self._filenode, fctx.data())
1008 1008 if self.size() == fctx.size() or self.flags() == b'l':
1009 1009 # size() matches: need to compare content
1010 1010 # issue6456: Always compare symlinks because size can represent
1011 1011 # encrypted string for EXT-4 encryption(fscrypt).
1012 1012 return self._filelog.cmp(self._filenode, fctx.data())
1013 1013
1014 1014 # size() differs
1015 1015 return True
1016 1016
1017 1017 def _adjustlinkrev(self, srcrev, inclusive=False, stoprev=None):
1018 1018 """return the first ancestor of <srcrev> introducing <fnode>
1019 1019
1020 1020 If the linkrev of the file revision does not point to an ancestor of
1021 1021 srcrev, we'll walk down the ancestors until we find one introducing
1022 1022 this file revision.
1023 1023
1024 1024 :srcrev: the changeset revision we search ancestors from
1025 1025 :inclusive: if true, the src revision will also be checked
1026 1026 :stoprev: an optional revision to stop the walk at. If no introduction
1027 1027 of this file content could be found before this floor
1028 1028 revision, the function will returns "None" and stops its
1029 1029 iteration.
1030 1030 """
1031 1031 repo = self._repo
1032 1032 cl = repo.unfiltered().changelog
1033 1033 mfl = repo.manifestlog
1034 1034 # fetch the linkrev
1035 1035 lkr = self.linkrev()
1036 1036 if srcrev == lkr:
1037 1037 return lkr
1038 1038 # hack to reuse ancestor computation when searching for renames
1039 1039 memberanc = getattr(self, '_ancestrycontext', None)
1040 1040 iteranc = None
1041 1041 if srcrev is None:
1042 1042 # wctx case, used by workingfilectx during mergecopy
1043 1043 revs = [p.rev() for p in self._repo[None].parents()]
1044 1044 inclusive = True # we skipped the real (revless) source
1045 1045 else:
1046 1046 revs = [srcrev]
1047 1047 if memberanc is None:
1048 1048 memberanc = iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1049 1049 # check if this linkrev is an ancestor of srcrev
1050 1050 if lkr not in memberanc:
1051 1051 if iteranc is None:
1052 1052 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
1053 1053 fnode = self._filenode
1054 1054 path = self._path
1055 1055 for a in iteranc:
1056 1056 if stoprev is not None and a < stoprev:
1057 1057 return None
1058 1058 ac = cl.read(a) # get changeset data (we avoid object creation)
1059 1059 if path in ac[3]: # checking the 'files' field.
1060 1060 # The file has been touched, check if the content is
1061 1061 # similar to the one we search for.
1062 1062 if fnode == mfl[ac[0]].readfast().get(path):
1063 1063 return a
1064 1064 # In theory, we should never get out of that loop without a result.
1065 1065 # But if manifest uses a buggy file revision (not children of the
1066 1066 # one it replaces) we could. Such a buggy situation will likely
1067 1067 # result is crash somewhere else at to some point.
1068 1068 return lkr
1069 1069
1070 1070 def isintroducedafter(self, changelogrev):
1071 1071 """True if a filectx has been introduced after a given floor revision"""
1072 1072 if self.linkrev() >= changelogrev:
1073 1073 return True
1074 1074 introrev = self._introrev(stoprev=changelogrev)
1075 1075 if introrev is None:
1076 1076 return False
1077 1077 return introrev >= changelogrev
1078 1078
1079 1079 def introrev(self):
1080 1080 """return the rev of the changeset which introduced this file revision
1081 1081
1082 1082 This method is different from linkrev because it take into account the
1083 1083 changeset the filectx was created from. It ensures the returned
1084 1084 revision is one of its ancestors. This prevents bugs from
1085 1085 'linkrev-shadowing' when a file revision is used by multiple
1086 1086 changesets.
1087 1087 """
1088 1088 return self._introrev()
1089 1089
1090 1090 def _introrev(self, stoprev=None):
1091 1091 """
1092 1092 Same as `introrev` but, with an extra argument to limit changelog
1093 1093 iteration range in some internal usecase.
1094 1094
1095 1095 If `stoprev` is set, the `introrev` will not be searched past that
1096 1096 `stoprev` revision and "None" might be returned. This is useful to
1097 1097 limit the iteration range.
1098 1098 """
1099 1099 toprev = None
1100 1100 attrs = vars(self)
1101 1101 if '_changeid' in attrs:
1102 1102 # We have a cached value already
1103 1103 toprev = self._changeid
1104 1104 elif '_changectx' in attrs:
1105 1105 # We know which changelog entry we are coming from
1106 1106 toprev = self._changectx.rev()
1107 1107
1108 1108 if toprev is not None:
1109 1109 return self._adjustlinkrev(toprev, inclusive=True, stoprev=stoprev)
1110 1110 elif '_descendantrev' in attrs:
1111 1111 introrev = self._adjustlinkrev(self._descendantrev, stoprev=stoprev)
1112 1112 # be nice and cache the result of the computation
1113 1113 if introrev is not None:
1114 1114 self._changeid = introrev
1115 1115 return introrev
1116 1116 else:
1117 1117 return self.linkrev()
1118 1118
1119 1119 def introfilectx(self):
1120 1120 """Return filectx having identical contents, but pointing to the
1121 1121 changeset revision where this filectx was introduced"""
1122 1122 introrev = self.introrev()
1123 1123 if self.rev() == introrev:
1124 1124 return self
1125 1125 return self.filectx(self.filenode(), changeid=introrev)
1126 1126
1127 1127 def _parentfilectx(self, path, fileid, filelog):
1128 1128 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
1129 1129 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
1130 1130 if '_changeid' in vars(self) or '_changectx' in vars(self):
1131 1131 # If self is associated with a changeset (probably explicitly
1132 1132 # fed), ensure the created filectx is associated with a
1133 1133 # changeset that is an ancestor of self.changectx.
1134 1134 # This lets us later use _adjustlinkrev to get a correct link.
1135 1135 fctx._descendantrev = self.rev()
1136 1136 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1137 1137 elif '_descendantrev' in vars(self):
1138 1138 # Otherwise propagate _descendantrev if we have one associated.
1139 1139 fctx._descendantrev = self._descendantrev
1140 1140 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
1141 1141 return fctx
1142 1142
1143 1143 def parents(self):
1144 1144 _path = self._path
1145 1145 fl = self._filelog
1146 1146 parents = self._filelog.parents(self._filenode)
1147 1147 pl = [
1148 1148 (_path, node, fl)
1149 1149 for node in parents
1150 1150 if node != self._repo.nodeconstants.nullid
1151 1151 ]
1152 1152
1153 1153 r = fl.renamed(self._filenode)
1154 1154 if r:
1155 1155 # - In the simple rename case, both parent are nullid, pl is empty.
1156 1156 # - In case of merge, only one of the parent is null id and should
1157 1157 # be replaced with the rename information. This parent is -always-
1158 1158 # the first one.
1159 1159 #
1160 1160 # As null id have always been filtered out in the previous list
1161 1161 # comprehension, inserting to 0 will always result in "replacing
1162 1162 # first nullid parent with rename information.
1163 1163 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
1164 1164
1165 1165 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
1166 1166
1167 1167 def p1(self):
1168 1168 return self.parents()[0]
1169 1169
1170 1170 def p2(self):
1171 1171 p = self.parents()
1172 1172 if len(p) == 2:
1173 1173 return p[1]
1174 1174 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
1175 1175
1176 1176 def annotate(self, follow=False, skiprevs=None, diffopts=None):
1177 1177 """Returns a list of annotateline objects for each line in the file
1178 1178
1179 1179 - line.fctx is the filectx of the node where that line was last changed
1180 1180 - line.lineno is the line number at the first appearance in the managed
1181 1181 file
1182 1182 - line.text is the data on that line (including newline character)
1183 1183 """
1184 1184 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
1185 1185
1186 1186 def parents(f):
1187 1187 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
1188 1188 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
1189 1189 # from the topmost introrev (= srcrev) down to p.linkrev() if it
1190 1190 # isn't an ancestor of the srcrev.
1191 1191 f._changeid
1192 1192 pl = f.parents()
1193 1193
1194 1194 # Don't return renamed parents if we aren't following.
1195 1195 if not follow:
1196 1196 pl = [p for p in pl if p.path() == f.path()]
1197 1197
1198 1198 # renamed filectx won't have a filelog yet, so set it
1199 1199 # from the cache to save time
1200 1200 for p in pl:
1201 1201 if not '_filelog' in p.__dict__:
1202 1202 p._filelog = getlog(p.path())
1203 1203
1204 1204 return pl
1205 1205
1206 1206 # use linkrev to find the first changeset where self appeared
1207 1207 base = self.introfilectx()
1208 1208 if getattr(base, '_ancestrycontext', None) is None:
1209 1209 # it is safe to use an unfiltered repository here because we are
1210 1210 # walking ancestors only.
1211 1211 cl = self._repo.unfiltered().changelog
1212 1212 if base.rev() is None:
1213 1213 # wctx is not inclusive, but works because _ancestrycontext
1214 1214 # is used to test filelog revisions
1215 1215 ac = cl.ancestors(
1216 1216 [p.rev() for p in base.parents()], inclusive=True
1217 1217 )
1218 1218 else:
1219 1219 ac = cl.ancestors([base.rev()], inclusive=True)
1220 1220 base._ancestrycontext = ac
1221 1221
1222 1222 return dagop.annotate(
1223 1223 base, parents, skiprevs=skiprevs, diffopts=diffopts
1224 1224 )
1225 1225
1226 1226 def ancestors(self, followfirst=False):
1227 1227 visit = {}
1228 1228 c = self
1229 1229 if followfirst:
1230 1230 cut = 1
1231 1231 else:
1232 1232 cut = None
1233 1233
1234 1234 while True:
1235 1235 for parent in c.parents()[:cut]:
1236 1236 visit[(parent.linkrev(), parent.filenode())] = parent
1237 1237 if not visit:
1238 1238 break
1239 1239 c = visit.pop(max(visit))
1240 1240 yield c
1241 1241
1242 1242 def decodeddata(self):
1243 1243 """Returns `data()` after running repository decoding filters.
1244 1244
1245 1245 This is often equivalent to how the data would be expressed on disk.
1246 1246 """
1247 1247 return self._repo.wwritedata(self.path(), self.data())
1248 1248
1249 1249
1250 1250 class filectx(basefilectx):
1251 1251 """A filecontext object makes access to data related to a particular
1252 1252 filerevision convenient."""
1253 1253
1254 1254 def __init__(
1255 1255 self,
1256 1256 repo,
1257 1257 path,
1258 1258 changeid=None,
1259 1259 fileid=None,
1260 1260 filelog=None,
1261 1261 changectx=None,
1262 1262 ):
1263 1263 """changeid must be a revision number, if specified.
1264 1264 fileid can be a file revision or node."""
1265 1265 self._repo = repo
1266 1266 self._path = path
1267 1267
1268 1268 assert (
1269 1269 changeid is not None or fileid is not None or changectx is not None
1270 1270 ), b"bad args: changeid=%r, fileid=%r, changectx=%r" % (
1271 1271 changeid,
1272 1272 fileid,
1273 1273 changectx,
1274 1274 )
1275 1275
1276 1276 if filelog is not None:
1277 1277 self._filelog = filelog
1278 1278
1279 1279 if changeid is not None:
1280 1280 self._changeid = changeid
1281 1281 if changectx is not None:
1282 1282 self._changectx = changectx
1283 1283 if fileid is not None:
1284 1284 self._fileid = fileid
1285 1285
1286 1286 @propertycache
1287 1287 def _changectx(self):
1288 1288 try:
1289 1289 return self._repo[self._changeid]
1290 1290 except error.FilteredRepoLookupError:
1291 1291 # Linkrev may point to any revision in the repository. When the
1292 1292 # repository is filtered this may lead to `filectx` trying to build
1293 1293 # `changectx` for filtered revision. In such case we fallback to
1294 1294 # creating `changectx` on the unfiltered version of the reposition.
1295 1295 # This fallback should not be an issue because `changectx` from
1296 1296 # `filectx` are not used in complex operations that care about
1297 1297 # filtering.
1298 1298 #
1299 1299 # This fallback is a cheap and dirty fix that prevent several
1300 1300 # crashes. It does not ensure the behavior is correct. However the
1301 1301 # behavior was not correct before filtering either and "incorrect
1302 1302 # behavior" is seen as better as "crash"
1303 1303 #
1304 1304 # Linkrevs have several serious troubles with filtering that are
1305 1305 # complicated to solve. Proper handling of the issue here should be
1306 1306 # considered when solving linkrev issue are on the table.
1307 1307 return self._repo.unfiltered()[self._changeid]
1308 1308
1309 1309 def filectx(self, fileid, changeid=None):
1310 1310 """opens an arbitrary revision of the file without
1311 1311 opening a new filelog"""
1312 1312 return filectx(
1313 1313 self._repo,
1314 1314 self._path,
1315 1315 fileid=fileid,
1316 1316 filelog=self._filelog,
1317 1317 changeid=changeid,
1318 1318 )
1319 1319
1320 1320 def rawdata(self):
1321 1321 return self._filelog.rawdata(self._filenode)
1322 1322
1323 1323 def rawflags(self):
1324 1324 """low-level revlog flags"""
1325 1325 return self._filelog.flags(self._filerev)
1326 1326
1327 1327 def data(self):
1328 1328 try:
1329 1329 return self._filelog.read(self._filenode)
1330 1330 except error.CensoredNodeError:
1331 1331 if self._repo.ui.config(b"censor", b"policy") == b"ignore":
1332 1332 return b""
1333 1333 raise error.Abort(
1334 1334 _(b"censored node: %s") % short(self._filenode),
1335 1335 hint=_(b"set censor.policy to ignore errors"),
1336 1336 )
1337 1337
1338 1338 def size(self):
1339 1339 return self._filelog.size(self._filerev)
1340 1340
1341 1341 @propertycache
1342 1342 def _copied(self):
1343 1343 """check if file was actually renamed in this changeset revision
1344 1344
1345 1345 If rename logged in file revision, we report copy for changeset only
1346 1346 if file revisions linkrev points back to the changeset in question
1347 1347 or both changeset parents contain different file revisions.
1348 1348 """
1349 1349
1350 1350 renamed = self._filelog.renamed(self._filenode)
1351 1351 if not renamed:
1352 1352 return None
1353 1353
1354 1354 if self.rev() == self.linkrev():
1355 1355 return renamed
1356 1356
1357 1357 name = self.path()
1358 1358 fnode = self._filenode
1359 1359 for p in self._changectx.parents():
1360 1360 try:
1361 1361 if fnode == p.filenode(name):
1362 1362 return None
1363 1363 except error.LookupError:
1364 1364 pass
1365 1365 return renamed
1366 1366
1367 1367 def children(self):
1368 1368 # hard for renames
1369 1369 c = self._filelog.children(self._filenode)
1370 1370 return [
1371 1371 filectx(self._repo, self._path, fileid=x, filelog=self._filelog)
1372 1372 for x in c
1373 1373 ]
1374 1374
1375 1375
1376 1376 class committablectx(basectx):
1377 1377 """A committablectx object provides common functionality for a context that
1378 1378 wants the ability to commit, e.g. workingctx or memctx."""
1379 1379
1380 1380 def __init__(
1381 1381 self,
1382 1382 repo,
1383 1383 text=b"",
1384 1384 user=None,
1385 1385 date=None,
1386 1386 extra=None,
1387 1387 changes=None,
1388 1388 branch=None,
1389 1389 ):
1390 1390 super(committablectx, self).__init__(repo)
1391 1391 self._rev = None
1392 1392 self._node = None
1393 1393 self._text = text
1394 1394 if date:
1395 1395 self._date = dateutil.parsedate(date)
1396 1396 if user:
1397 1397 self._user = user
1398 1398 if changes:
1399 1399 self._status = changes
1400 1400
1401 1401 self._extra = {}
1402 1402 if extra:
1403 1403 self._extra = extra.copy()
1404 1404 if branch is not None:
1405 1405 self._extra[b'branch'] = encoding.fromlocal(branch)
1406 1406 if not self._extra.get(b'branch'):
1407 1407 self._extra[b'branch'] = b'default'
1408 1408
1409 1409 def __bytes__(self):
1410 1410 return bytes(self._parents[0]) + b"+"
1411 1411
1412 1412 def hex(self):
1413 1413 self._repo.nodeconstants.wdirhex
1414 1414
1415 1415 __str__ = encoding.strmethod(__bytes__)
1416 1416
1417 1417 def __nonzero__(self):
1418 1418 return True
1419 1419
1420 1420 __bool__ = __nonzero__
1421 1421
1422 1422 @propertycache
1423 1423 def _status(self):
1424 1424 return self._repo.status()
1425 1425
1426 1426 @propertycache
1427 1427 def _user(self):
1428 1428 return self._repo.ui.username()
1429 1429
1430 1430 @propertycache
1431 1431 def _date(self):
1432 1432 ui = self._repo.ui
1433 1433 date = ui.configdate(b'devel', b'default-date')
1434 1434 if date is None:
1435 1435 date = dateutil.makedate()
1436 1436 return date
1437 1437
1438 1438 def subrev(self, subpath):
1439 1439 return None
1440 1440
1441 1441 def manifestnode(self):
1442 1442 return None
1443 1443
1444 1444 def user(self):
1445 1445 return self._user or self._repo.ui.username()
1446 1446
1447 1447 def date(self):
1448 1448 return self._date
1449 1449
1450 1450 def description(self):
1451 1451 return self._text
1452 1452
1453 1453 def files(self):
1454 1454 return sorted(
1455 1455 self._status.modified + self._status.added + self._status.removed
1456 1456 )
1457 1457
1458 1458 def modified(self):
1459 1459 return self._status.modified
1460 1460
1461 1461 def added(self):
1462 1462 return self._status.added
1463 1463
1464 1464 def removed(self):
1465 1465 return self._status.removed
1466 1466
1467 1467 def deleted(self):
1468 1468 return self._status.deleted
1469 1469
1470 1470 filesmodified = modified
1471 1471 filesadded = added
1472 1472 filesremoved = removed
1473 1473
1474 1474 def branch(self):
1475 1475 return encoding.tolocal(self._extra[b'branch'])
1476 1476
1477 1477 def closesbranch(self):
1478 1478 return b'close' in self._extra
1479 1479
1480 1480 def extra(self):
1481 1481 return self._extra
1482 1482
1483 1483 def isinmemory(self):
1484 1484 return False
1485 1485
1486 1486 def tags(self):
1487 1487 return []
1488 1488
1489 1489 def bookmarks(self):
1490 1490 b = []
1491 1491 for p in self.parents():
1492 1492 b.extend(p.bookmarks())
1493 1493 return b
1494 1494
1495 1495 def phase(self):
1496 1496 phase = phases.newcommitphase(self._repo.ui)
1497 1497 for p in self.parents():
1498 1498 phase = max(phase, p.phase())
1499 1499 return phase
1500 1500
1501 1501 def hidden(self):
1502 1502 return False
1503 1503
1504 1504 def children(self):
1505 1505 return []
1506 1506
1507 1507 def flags(self, path):
1508 1508 if '_manifest' in self.__dict__:
1509 1509 try:
1510 1510 return self._manifest.flags(path)
1511 1511 except KeyError:
1512 1512 return b''
1513 1513
1514 1514 try:
1515 1515 return self._flagfunc(path)
1516 1516 except OSError:
1517 1517 return b''
1518 1518
1519 1519 def ancestor(self, c2):
1520 1520 """return the "best" ancestor context of self and c2"""
1521 1521 return self._parents[0].ancestor(c2) # punt on two parents for now
1522 1522
1523 1523 def ancestors(self):
1524 1524 for p in self._parents:
1525 1525 yield p
1526 1526 for a in self._repo.changelog.ancestors(
1527 1527 [p.rev() for p in self._parents]
1528 1528 ):
1529 1529 yield self._repo[a]
1530 1530
1531 1531 def markcommitted(self, node):
1532 1532 """Perform post-commit cleanup necessary after committing this ctx
1533 1533
1534 1534 Specifically, this updates backing stores this working context
1535 1535 wraps to reflect the fact that the changes reflected by this
1536 1536 workingctx have been committed. For example, it marks
1537 1537 modified and added files as normal in the dirstate.
1538 1538
1539 1539 """
1540 1540
1541 1541 def dirty(self, missing=False, merge=True, branch=True):
1542 1542 return False
1543 1543
1544 1544
1545 1545 class workingctx(committablectx):
1546 1546 """A workingctx object makes access to data related to
1547 1547 the current working directory convenient.
1548 1548 date - any valid date string or (unixtime, offset), or None.
1549 1549 user - username string, or None.
1550 1550 extra - a dictionary of extra values, or None.
1551 1551 changes - a list of file lists as returned by localrepo.status()
1552 1552 or None to use the repository status.
1553 1553 """
1554 1554
1555 1555 def __init__(
1556 1556 self, repo, text=b"", user=None, date=None, extra=None, changes=None
1557 1557 ):
1558 1558 branch = None
1559 1559 if not extra or b'branch' not in extra:
1560 1560 try:
1561 1561 branch = repo.dirstate.branch()
1562 1562 except UnicodeDecodeError:
1563 1563 raise error.Abort(_(b'branch name not in UTF-8!'))
1564 1564 super(workingctx, self).__init__(
1565 1565 repo, text, user, date, extra, changes, branch=branch
1566 1566 )
1567 1567
1568 1568 def __iter__(self):
1569 1569 d = self._repo.dirstate
1570 1570 for f in d:
1571 1571 if d.get_entry(f).tracked:
1572 1572 yield f
1573 1573
1574 1574 def __contains__(self, key):
1575 1575 return self._repo.dirstate.get_entry(key).tracked
1576 1576
1577 1577 def hex(self):
1578 1578 return self._repo.nodeconstants.wdirhex
1579 1579
1580 1580 @propertycache
1581 1581 def _parents(self):
1582 1582 p = self._repo.dirstate.parents()
1583 1583 if p[1] == self._repo.nodeconstants.nullid:
1584 1584 p = p[:-1]
1585 1585 # use unfiltered repo to delay/avoid loading obsmarkers
1586 1586 unfi = self._repo.unfiltered()
1587 1587 return [
1588 1588 changectx(
1589 1589 self._repo, unfi.changelog.rev(n), n, maybe_filtered=False
1590 1590 )
1591 1591 for n in p
1592 1592 ]
1593 1593
1594 1594 def setparents(self, p1node, p2node=None):
1595 1595 if p2node is None:
1596 1596 p2node = self._repo.nodeconstants.nullid
1597 1597 dirstate = self._repo.dirstate
1598 1598 with dirstate.changing_parents(self._repo):
1599 1599 copies = dirstate.setparents(p1node, p2node)
1600 1600 pctx = self._repo[p1node]
1601 1601 if copies:
1602 1602 # Adjust copy records, the dirstate cannot do it, it
1603 1603 # requires access to parents manifests. Preserve them
1604 1604 # only for entries added to first parent.
1605 1605 for f in copies:
1606 1606 if f not in pctx and copies[f] in pctx:
1607 1607 dirstate.copy(copies[f], f)
1608 1608 if p2node == self._repo.nodeconstants.nullid:
1609 1609 for f, s in sorted(dirstate.copies().items()):
1610 1610 if f not in pctx and s not in pctx:
1611 1611 dirstate.copy(None, f)
1612 1612
1613 1613 def _fileinfo(self, path):
1614 1614 # populate __dict__['_manifest'] as workingctx has no _manifestdelta
1615 1615 self._manifest
1616 1616 return super(workingctx, self)._fileinfo(path)
1617 1617
1618 1618 def _buildflagfunc(self):
1619 1619 # Create a fallback function for getting file flags when the
1620 1620 # filesystem doesn't support them
1621 1621
1622 1622 copiesget = self._repo.dirstate.copies().get
1623 1623 parents = self.parents()
1624 1624 if len(parents) < 2:
1625 1625 # when we have one parent, it's easy: copy from parent
1626 1626 man = parents[0].manifest()
1627 1627
1628 1628 def func(f):
1629 1629 f = copiesget(f, f)
1630 1630 return man.flags(f)
1631 1631
1632 1632 else:
1633 1633 # merges are tricky: we try to reconstruct the unstored
1634 1634 # result from the merge (issue1802)
1635 1635 p1, p2 = parents
1636 1636 pa = p1.ancestor(p2)
1637 1637 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1638 1638
1639 1639 def func(f):
1640 1640 f = copiesget(f, f) # may be wrong for merges with copies
1641 1641 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1642 1642 if fl1 == fl2:
1643 1643 return fl1
1644 1644 if fl1 == fla:
1645 1645 return fl2
1646 1646 if fl2 == fla:
1647 1647 return fl1
1648 1648 return b'' # punt for conflicts
1649 1649
1650 1650 return func
1651 1651
1652 1652 @propertycache
1653 1653 def _flagfunc(self):
1654 1654 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1655 1655
1656 1656 def flags(self, path):
1657 1657 try:
1658 1658 return self._flagfunc(path)
1659 1659 except OSError:
1660 1660 return b''
1661 1661
1662 1662 def filectx(self, path, filelog=None):
1663 1663 """get a file context from the working directory"""
1664 1664 return workingfilectx(
1665 1665 self._repo, path, workingctx=self, filelog=filelog
1666 1666 )
1667 1667
1668 1668 def dirty(self, missing=False, merge=True, branch=True):
1669 1669 """check whether a working directory is modified"""
1670 1670 # check subrepos first
1671 1671 for s in sorted(self.substate):
1672 1672 if self.sub(s).dirty(missing=missing):
1673 1673 return True
1674 1674 # check current working dir
1675 1675 return (
1676 1676 (merge and self.p2())
1677 1677 or (branch and self.branch() != self.p1().branch())
1678 1678 or self.modified()
1679 1679 or self.added()
1680 1680 or self.removed()
1681 1681 or (missing and self.deleted())
1682 1682 )
1683 1683
1684 1684 def add(self, list, prefix=b""):
1685 1685 with self._repo.wlock():
1686 1686 ui, ds = self._repo.ui, self._repo.dirstate
1687 1687 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1688 1688 rejected = []
1689 1689 lstat = self._repo.wvfs.lstat
1690 1690 for f in list:
1691 1691 # ds.pathto() returns an absolute file when this is invoked from
1692 1692 # the keyword extension. That gets flagged as non-portable on
1693 1693 # Windows, since it contains the drive letter and colon.
1694 1694 scmutil.checkportable(ui, os.path.join(prefix, f))
1695 1695 try:
1696 1696 st = lstat(f)
1697 1697 except OSError:
1698 1698 ui.warn(_(b"%s does not exist!\n") % uipath(f))
1699 1699 rejected.append(f)
1700 1700 continue
1701 1701 limit = ui.configbytes(b'ui', b'large-file-limit')
1702 1702 if limit != 0 and st.st_size > limit:
1703 1703 ui.warn(
1704 1704 _(
1705 1705 b"%s: up to %d MB of RAM may be required "
1706 1706 b"to manage this file\n"
1707 1707 b"(use 'hg revert %s' to cancel the "
1708 1708 b"pending addition)\n"
1709 1709 )
1710 1710 % (f, 3 * st.st_size // 1000000, uipath(f))
1711 1711 )
1712 1712 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1713 1713 ui.warn(
1714 1714 _(
1715 1715 b"%s not added: only files and symlinks "
1716 1716 b"supported currently\n"
1717 1717 )
1718 1718 % uipath(f)
1719 1719 )
1720 1720 rejected.append(f)
1721 1721 elif not ds.set_tracked(f):
1722 1722 ui.warn(_(b"%s already tracked!\n") % uipath(f))
1723 1723 return rejected
1724 1724
1725 1725 def forget(self, files, prefix=b""):
1726 1726 with self._repo.wlock():
1727 1727 ds = self._repo.dirstate
1728 1728 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1729 1729 rejected = []
1730 1730 for f in files:
1731 1731 if not ds.set_untracked(f):
1732 1732 self._repo.ui.warn(_(b"%s not tracked!\n") % uipath(f))
1733 1733 rejected.append(f)
1734 1734 return rejected
1735 1735
1736 1736 def copy(self, source, dest):
1737 1737 try:
1738 1738 st = self._repo.wvfs.lstat(dest)
1739 1739 except FileNotFoundError:
1740 1740 self._repo.ui.warn(
1741 1741 _(b"%s does not exist!\n") % self._repo.dirstate.pathto(dest)
1742 1742 )
1743 1743 return
1744 1744 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1745 1745 self._repo.ui.warn(
1746 1746 _(b"copy failed: %s is not a file or a symbolic link\n")
1747 1747 % self._repo.dirstate.pathto(dest)
1748 1748 )
1749 1749 else:
1750 1750 with self._repo.wlock():
1751 1751 ds = self._repo.dirstate
1752 1752 ds.set_tracked(dest)
1753 1753 ds.copy(source, dest)
1754 1754
1755 1755 def match(
1756 1756 self,
1757 1757 pats=None,
1758 1758 include=None,
1759 1759 exclude=None,
1760 1760 default=b'glob',
1761 1761 listsubrepos=False,
1762 1762 badfn=None,
1763 1763 cwd=None,
1764 1764 ):
1765 1765 r = self._repo
1766 1766 if not cwd:
1767 1767 cwd = r.getcwd()
1768 1768
1769 1769 # Only a case insensitive filesystem needs magic to translate user input
1770 1770 # to actual case in the filesystem.
1771 1771 icasefs = not util.fscasesensitive(r.root)
1772 1772 return matchmod.match(
1773 1773 r.root,
1774 1774 cwd,
1775 1775 pats,
1776 1776 include,
1777 1777 exclude,
1778 1778 default,
1779 1779 auditor=r.auditor,
1780 1780 ctx=self,
1781 1781 listsubrepos=listsubrepos,
1782 1782 badfn=badfn,
1783 1783 icasefs=icasefs,
1784 1784 )
1785 1785
1786 1786 def _filtersuspectsymlink(self, files):
1787 1787 if not files or self._repo.dirstate._checklink:
1788 1788 return files
1789 1789
1790 1790 # Symlink placeholders may get non-symlink-like contents
1791 1791 # via user error or dereferencing by NFS or Samba servers,
1792 1792 # so we filter out any placeholders that don't look like a
1793 1793 # symlink
1794 1794 sane = []
1795 1795 for f in files:
1796 1796 if self.flags(f) == b'l':
1797 1797 d = self[f].data()
1798 1798 if (
1799 1799 d == b''
1800 1800 or len(d) >= 1024
1801 1801 or b'\n' in d
1802 1802 or stringutil.binary(d)
1803 1803 ):
1804 1804 self._repo.ui.debug(
1805 1805 b'ignoring suspect symlink placeholder "%s"\n' % f
1806 1806 )
1807 1807 continue
1808 1808 sane.append(f)
1809 1809 return sane
1810 1810
1811 1811 def _checklookup(self, files, mtime_boundary):
1812 1812 # check for any possibly clean files
1813 1813 if not files:
1814 1814 return [], [], [], []
1815 1815
1816 1816 modified = []
1817 1817 deleted = []
1818 1818 clean = []
1819 1819 fixup = []
1820 1820 pctx = self._parents[0]
1821 1821 # do a full compare of any files that might have changed
1822 1822 for f in sorted(files):
1823 1823 try:
1824 1824 # This will return True for a file that got replaced by a
1825 1825 # directory in the interim, but fixing that is pretty hard.
1826 1826 if (
1827 1827 f not in pctx
1828 1828 or self.flags(f) != pctx.flags(f)
1829 1829 or pctx[f].cmp(self[f])
1830 1830 ):
1831 1831 modified.append(f)
1832 1832 elif mtime_boundary is None:
1833 1833 clean.append(f)
1834 1834 else:
1835 1835 s = self[f].lstat()
1836 1836 mode = s.st_mode
1837 1837 size = s.st_size
1838 1838 file_mtime = timestamp.reliable_mtime_of(s, mtime_boundary)
1839 1839 if file_mtime is not None:
1840 1840 cache_info = (mode, size, file_mtime)
1841 1841 fixup.append((f, cache_info))
1842 1842 else:
1843 1843 clean.append(f)
1844 1844 except (IOError, OSError):
1845 1845 # A file become inaccessible in between? Mark it as deleted,
1846 1846 # matching dirstate behavior (issue5584).
1847 1847 # The dirstate has more complex behavior around whether a
1848 1848 # missing file matches a directory, etc, but we don't need to
1849 1849 # bother with that: if f has made it to this point, we're sure
1850 1850 # it's in the dirstate.
1851 1851 deleted.append(f)
1852 1852
1853 1853 return modified, deleted, clean, fixup
1854 1854
1855 1855 def _poststatusfixup(self, status, fixup):
1856 1856 """update dirstate for files that are actually clean"""
1857 1857 poststatus = self._repo.postdsstatus()
1858 1858 if fixup or poststatus or self._repo.dirstate._dirty:
1859 1859 try:
1860 1860 oldid = self._repo.dirstate.identity()
1861 1861
1862 1862 # updating the dirstate is optional
1863 1863 # so we don't wait on the lock
1864 1864 # wlock can invalidate the dirstate, so cache normal _after_
1865 1865 # taking the lock
1866 1866 with self._repo.wlock(False):
1867 1867 dirstate = self._repo.dirstate
1868 1868 if dirstate.identity() == oldid:
1869 1869 if fixup:
1870 1870 if dirstate.is_changing_parents:
1871 1871 normal = lambda f, pfd: dirstate.update_file(
1872 1872 f, p1_tracked=True, wc_tracked=True
1873 1873 )
1874 1874 else:
1875 1875 normal = dirstate.set_clean
1876 1876 for f, pdf in fixup:
1877 1877 normal(f, pdf)
1878 1878 # write changes out explicitly, because nesting
1879 1879 # wlock at runtime may prevent 'wlock.release()'
1880 1880 # after this block from doing so for subsequent
1881 1881 # changing files
1882 1882 #
1883 1883 # (This is outside of the (if fixup) block because the
1884 1884 # status operation itself might have updated some cache
1885 1885 # information before.)
1886 1886 tr = self._repo.currenttransaction()
1887 1887 self._repo.dirstate.write(tr)
1888 1888
1889 1889 if poststatus:
1890 1890 for ps in poststatus:
1891 1891 ps(self, status)
1892 1892 else:
1893 1893 # in this case, writing changes out breaks
1894 1894 # consistency, because .hg/dirstate was
1895 1895 # already changed simultaneously after last
1896 1896 # caching (see also issue5584 for detail)
1897 1897 self._repo.ui.debug(
1898 1898 b'skip updating dirstate: identity mismatch\n'
1899 1899 )
1900 # throw away anything we have.
1901 dirstate.invalidate()
1900 1902 except error.LockError:
1901 1903 pass
1902 1904 finally:
1903 1905 # Even if the wlock couldn't be grabbed, clear out the list.
1904 1906 self._repo.clearpostdsstatus()
1905 1907
1906 1908 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1907 1909 '''Gets the status from the dirstate -- internal use only.'''
1908 1910 subrepos = []
1909 1911 if b'.hgsub' in self:
1910 1912 subrepos = sorted(self.substate)
1911 1913 cmp, s, mtime_boundary = self._repo.dirstate.status(
1912 1914 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1913 1915 )
1914 1916
1915 1917 # check for any possibly clean files
1916 1918 fixup = []
1917 1919 if cmp:
1918 1920 modified2, deleted2, clean_set, fixup = self._checklookup(
1919 1921 cmp, mtime_boundary
1920 1922 )
1921 1923 s.modified.extend(modified2)
1922 1924 s.deleted.extend(deleted2)
1923 1925
1924 1926 if clean_set and clean:
1925 1927 s.clean.extend(clean_set)
1926 1928 if fixup and clean:
1927 1929 s.clean.extend((f for f, _ in fixup))
1928 1930
1929 1931 self._poststatusfixup(s, fixup)
1930 1932
1931 1933 if match.always():
1932 1934 # cache for performance
1933 1935 if s.unknown or s.ignored or s.clean:
1934 1936 # "_status" is cached with list*=False in the normal route
1935 1937 self._status = scmutil.status(
1936 1938 s.modified, s.added, s.removed, s.deleted, [], [], []
1937 1939 )
1938 1940 else:
1939 1941 self._status = s
1940 1942
1941 1943 return s
1942 1944
1943 1945 @propertycache
1944 1946 def _copies(self):
1945 1947 p1copies = {}
1946 1948 p2copies = {}
1947 1949 parents = self._repo.dirstate.parents()
1948 1950 p1manifest = self._repo[parents[0]].manifest()
1949 1951 p2manifest = self._repo[parents[1]].manifest()
1950 1952 changedset = set(self.added()) | set(self.modified())
1951 1953 narrowmatch = self._repo.narrowmatch()
1952 1954 for dst, src in self._repo.dirstate.copies().items():
1953 1955 if dst not in changedset or not narrowmatch(dst):
1954 1956 continue
1955 1957 if src in p1manifest:
1956 1958 p1copies[dst] = src
1957 1959 elif src in p2manifest:
1958 1960 p2copies[dst] = src
1959 1961 return p1copies, p2copies
1960 1962
1961 1963 @propertycache
1962 1964 def _manifest(self):
1963 1965 """generate a manifest corresponding to the values in self._status
1964 1966
1965 1967 This reuse the file nodeid from parent, but we use special node
1966 1968 identifiers for added and modified files. This is used by manifests
1967 1969 merge to see that files are different and by update logic to avoid
1968 1970 deleting newly added files.
1969 1971 """
1970 1972 return self._buildstatusmanifest(self._status)
1971 1973
1972 1974 def _buildstatusmanifest(self, status):
1973 1975 """Builds a manifest that includes the given status results."""
1974 1976 parents = self.parents()
1975 1977
1976 1978 man = parents[0].manifest().copy()
1977 1979
1978 1980 ff = self._flagfunc
1979 1981 for i, l in (
1980 1982 (self._repo.nodeconstants.addednodeid, status.added),
1981 1983 (self._repo.nodeconstants.modifiednodeid, status.modified),
1982 1984 ):
1983 1985 for f in l:
1984 1986 man[f] = i
1985 1987 try:
1986 1988 man.setflag(f, ff(f))
1987 1989 except OSError:
1988 1990 pass
1989 1991
1990 1992 for f in status.deleted + status.removed:
1991 1993 if f in man:
1992 1994 del man[f]
1993 1995
1994 1996 return man
1995 1997
1996 1998 def _buildstatus(
1997 1999 self, other, s, match, listignored, listclean, listunknown
1998 2000 ):
1999 2001 """build a status with respect to another context
2000 2002
2001 2003 This includes logic for maintaining the fast path of status when
2002 2004 comparing the working directory against its parent, which is to skip
2003 2005 building a new manifest if self (working directory) is not comparing
2004 2006 against its parent (repo['.']).
2005 2007 """
2006 2008 s = self._dirstatestatus(match, listignored, listclean, listunknown)
2007 2009 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
2008 2010 # might have accidentally ended up with the entire contents of the file
2009 2011 # they are supposed to be linking to.
2010 2012 s.modified[:] = self._filtersuspectsymlink(s.modified)
2011 2013 if other != self._repo[b'.']:
2012 2014 s = super(workingctx, self)._buildstatus(
2013 2015 other, s, match, listignored, listclean, listunknown
2014 2016 )
2015 2017 return s
2016 2018
2017 2019 def _matchstatus(self, other, match):
2018 2020 """override the match method with a filter for directory patterns
2019 2021
2020 2022 We use inheritance to customize the match.bad method only in cases of
2021 2023 workingctx since it belongs only to the working directory when
2022 2024 comparing against the parent changeset.
2023 2025
2024 2026 If we aren't comparing against the working directory's parent, then we
2025 2027 just use the default match object sent to us.
2026 2028 """
2027 2029 if other != self._repo[b'.']:
2028 2030
2029 2031 def bad(f, msg):
2030 2032 # 'f' may be a directory pattern from 'match.files()',
2031 2033 # so 'f not in ctx1' is not enough
2032 2034 if f not in other and not other.hasdir(f):
2033 2035 self._repo.ui.warn(
2034 2036 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
2035 2037 )
2036 2038
2037 2039 match.bad = bad
2038 2040 return match
2039 2041
2040 2042 def walk(self, match):
2041 2043 '''Generates matching file names.'''
2042 2044 return sorted(
2043 2045 self._repo.dirstate.walk(
2044 2046 self._repo.narrowmatch(match),
2045 2047 subrepos=sorted(self.substate),
2046 2048 unknown=True,
2047 2049 ignored=False,
2048 2050 )
2049 2051 )
2050 2052
2051 2053 def matches(self, match):
2052 2054 match = self._repo.narrowmatch(match)
2053 2055 ds = self._repo.dirstate
2054 2056 return sorted(f for f in ds.matches(match) if ds.get_entry(f).tracked)
2055 2057
2056 2058 def markcommitted(self, node):
2057 2059 with self._repo.dirstate.changing_parents(self._repo):
2058 2060 for f in self.modified() + self.added():
2059 2061 self._repo.dirstate.update_file(
2060 2062 f, p1_tracked=True, wc_tracked=True
2061 2063 )
2062 2064 for f in self.removed():
2063 2065 self._repo.dirstate.update_file(
2064 2066 f, p1_tracked=False, wc_tracked=False
2065 2067 )
2066 2068 self._repo.dirstate.setparents(node)
2067 2069 self._repo._quick_access_changeid_invalidate()
2068 2070
2069 2071 sparse.aftercommit(self._repo, node)
2070 2072
2071 2073 # write changes out explicitly, because nesting wlock at
2072 2074 # runtime may prevent 'wlock.release()' in 'repo.commit()'
2073 2075 # from immediately doing so for subsequent changing files
2074 2076 self._repo.dirstate.write(self._repo.currenttransaction())
2075 2077
2076 2078 def mergestate(self, clean=False):
2077 2079 if clean:
2078 2080 return mergestatemod.mergestate.clean(self._repo)
2079 2081 return mergestatemod.mergestate.read(self._repo)
2080 2082
2081 2083
2082 2084 class committablefilectx(basefilectx):
2083 2085 """A committablefilectx provides common functionality for a file context
2084 2086 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
2085 2087
2086 2088 def __init__(self, repo, path, filelog=None, ctx=None):
2087 2089 self._repo = repo
2088 2090 self._path = path
2089 2091 self._changeid = None
2090 2092 self._filerev = self._filenode = None
2091 2093
2092 2094 if filelog is not None:
2093 2095 self._filelog = filelog
2094 2096 if ctx:
2095 2097 self._changectx = ctx
2096 2098
2097 2099 def __nonzero__(self):
2098 2100 return True
2099 2101
2100 2102 __bool__ = __nonzero__
2101 2103
2102 2104 def linkrev(self):
2103 2105 # linked to self._changectx no matter if file is modified or not
2104 2106 return self.rev()
2105 2107
2106 2108 def renamed(self):
2107 2109 path = self.copysource()
2108 2110 if not path:
2109 2111 return None
2110 2112 return (
2111 2113 path,
2112 2114 self._changectx._parents[0]._manifest.get(
2113 2115 path, self._repo.nodeconstants.nullid
2114 2116 ),
2115 2117 )
2116 2118
2117 2119 def parents(self):
2118 2120 '''return parent filectxs, following copies if necessary'''
2119 2121
2120 2122 def filenode(ctx, path):
2121 2123 return ctx._manifest.get(path, self._repo.nodeconstants.nullid)
2122 2124
2123 2125 path = self._path
2124 2126 fl = self._filelog
2125 2127 pcl = self._changectx._parents
2126 2128 renamed = self.renamed()
2127 2129
2128 2130 if renamed:
2129 2131 pl = [renamed + (None,)]
2130 2132 else:
2131 2133 pl = [(path, filenode(pcl[0], path), fl)]
2132 2134
2133 2135 for pc in pcl[1:]:
2134 2136 pl.append((path, filenode(pc, path), fl))
2135 2137
2136 2138 return [
2137 2139 self._parentfilectx(p, fileid=n, filelog=l)
2138 2140 for p, n, l in pl
2139 2141 if n != self._repo.nodeconstants.nullid
2140 2142 ]
2141 2143
2142 2144 def children(self):
2143 2145 return []
2144 2146
2145 2147
2146 2148 class workingfilectx(committablefilectx):
2147 2149 """A workingfilectx object makes access to data related to a particular
2148 2150 file in the working directory convenient."""
2149 2151
2150 2152 def __init__(self, repo, path, filelog=None, workingctx=None):
2151 2153 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2152 2154
2153 2155 @propertycache
2154 2156 def _changectx(self):
2155 2157 return workingctx(self._repo)
2156 2158
2157 2159 def data(self):
2158 2160 return self._repo.wread(self._path)
2159 2161
2160 2162 def copysource(self):
2161 2163 return self._repo.dirstate.copied(self._path)
2162 2164
2163 2165 def size(self):
2164 2166 return self._repo.wvfs.lstat(self._path).st_size
2165 2167
2166 2168 def lstat(self):
2167 2169 return self._repo.wvfs.lstat(self._path)
2168 2170
2169 2171 def date(self):
2170 2172 t, tz = self._changectx.date()
2171 2173 try:
2172 2174 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2173 2175 except FileNotFoundError:
2174 2176 return (t, tz)
2175 2177
2176 2178 def exists(self):
2177 2179 return self._repo.wvfs.exists(self._path)
2178 2180
2179 2181 def lexists(self):
2180 2182 return self._repo.wvfs.lexists(self._path)
2181 2183
2182 2184 def audit(self):
2183 2185 return self._repo.wvfs.audit(self._path)
2184 2186
2185 2187 def cmp(self, fctx):
2186 2188 """compare with other file context
2187 2189
2188 2190 returns True if different than fctx.
2189 2191 """
2190 2192 # fctx should be a filectx (not a workingfilectx)
2191 2193 # invert comparison to reuse the same code path
2192 2194 return fctx.cmp(self)
2193 2195
2194 2196 def remove(self, ignoremissing=False):
2195 2197 """wraps unlink for a repo's working directory"""
2196 2198 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2197 2199 self._repo.wvfs.unlinkpath(
2198 2200 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2199 2201 )
2200 2202
2201 2203 def write(self, data, flags, backgroundclose=False, **kwargs):
2202 2204 """wraps repo.wwrite"""
2203 2205 return self._repo.wwrite(
2204 2206 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2205 2207 )
2206 2208
2207 2209 def markcopied(self, src):
2208 2210 """marks this file a copy of `src`"""
2209 2211 self._repo.dirstate.copy(src, self._path)
2210 2212
2211 2213 def clearunknown(self):
2212 2214 """Removes conflicting items in the working directory so that
2213 2215 ``write()`` can be called successfully.
2214 2216 """
2215 2217 wvfs = self._repo.wvfs
2216 2218 f = self._path
2217 2219 wvfs.audit(f)
2218 2220 if self._repo.ui.configbool(
2219 2221 b'experimental', b'merge.checkpathconflicts'
2220 2222 ):
2221 2223 # remove files under the directory as they should already be
2222 2224 # warned and backed up
2223 2225 if wvfs.isdir(f) and not wvfs.islink(f):
2224 2226 wvfs.rmtree(f, forcibly=True)
2225 2227 for p in reversed(list(pathutil.finddirs(f))):
2226 2228 if wvfs.isfileorlink(p):
2227 2229 wvfs.unlink(p)
2228 2230 break
2229 2231 else:
2230 2232 # don't remove files if path conflicts are not processed
2231 2233 if wvfs.isdir(f) and not wvfs.islink(f):
2232 2234 wvfs.removedirs(f)
2233 2235
2234 2236 def setflags(self, l, x):
2235 2237 self._repo.wvfs.setflags(self._path, l, x)
2236 2238
2237 2239
2238 2240 class overlayworkingctx(committablectx):
2239 2241 """Wraps another mutable context with a write-back cache that can be
2240 2242 converted into a commit context.
2241 2243
2242 2244 self._cache[path] maps to a dict with keys: {
2243 2245 'exists': bool?
2244 2246 'date': date?
2245 2247 'data': str?
2246 2248 'flags': str?
2247 2249 'copied': str? (path or None)
2248 2250 }
2249 2251 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2250 2252 is `False`, the file was deleted.
2251 2253 """
2252 2254
2253 2255 def __init__(self, repo):
2254 2256 super(overlayworkingctx, self).__init__(repo)
2255 2257 self.clean()
2256 2258
2257 2259 def setbase(self, wrappedctx):
2258 2260 self._wrappedctx = wrappedctx
2259 2261 self._parents = [wrappedctx]
2260 2262 # Drop old manifest cache as it is now out of date.
2261 2263 # This is necessary when, e.g., rebasing several nodes with one
2262 2264 # ``overlayworkingctx`` (e.g. with --collapse).
2263 2265 util.clearcachedproperty(self, b'_manifest')
2264 2266
2265 2267 def setparents(self, p1node, p2node=None):
2266 2268 if p2node is None:
2267 2269 p2node = self._repo.nodeconstants.nullid
2268 2270 assert p1node == self._wrappedctx.node()
2269 2271 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2270 2272
2271 2273 def data(self, path):
2272 2274 if self.isdirty(path):
2273 2275 if self._cache[path][b'exists']:
2274 2276 if self._cache[path][b'data'] is not None:
2275 2277 return self._cache[path][b'data']
2276 2278 else:
2277 2279 # Must fallback here, too, because we only set flags.
2278 2280 return self._wrappedctx[path].data()
2279 2281 else:
2280 2282 raise error.ProgrammingError(
2281 2283 b"No such file or directory: %s" % path
2282 2284 )
2283 2285 else:
2284 2286 return self._wrappedctx[path].data()
2285 2287
2286 2288 @propertycache
2287 2289 def _manifest(self):
2288 2290 parents = self.parents()
2289 2291 man = parents[0].manifest().copy()
2290 2292
2291 2293 flag = self._flagfunc
2292 2294 for path in self.added():
2293 2295 man[path] = self._repo.nodeconstants.addednodeid
2294 2296 man.setflag(path, flag(path))
2295 2297 for path in self.modified():
2296 2298 man[path] = self._repo.nodeconstants.modifiednodeid
2297 2299 man.setflag(path, flag(path))
2298 2300 for path in self.removed():
2299 2301 del man[path]
2300 2302 return man
2301 2303
2302 2304 @propertycache
2303 2305 def _flagfunc(self):
2304 2306 def f(path):
2305 2307 return self._cache[path][b'flags']
2306 2308
2307 2309 return f
2308 2310
2309 2311 def files(self):
2310 2312 return sorted(self.added() + self.modified() + self.removed())
2311 2313
2312 2314 def modified(self):
2313 2315 return [
2314 2316 f
2315 2317 for f in self._cache.keys()
2316 2318 if self._cache[f][b'exists'] and self._existsinparent(f)
2317 2319 ]
2318 2320
2319 2321 def added(self):
2320 2322 return [
2321 2323 f
2322 2324 for f in self._cache.keys()
2323 2325 if self._cache[f][b'exists'] and not self._existsinparent(f)
2324 2326 ]
2325 2327
2326 2328 def removed(self):
2327 2329 return [
2328 2330 f
2329 2331 for f in self._cache.keys()
2330 2332 if not self._cache[f][b'exists'] and self._existsinparent(f)
2331 2333 ]
2332 2334
2333 2335 def p1copies(self):
2334 2336 copies = {}
2335 2337 narrowmatch = self._repo.narrowmatch()
2336 2338 for f in self._cache.keys():
2337 2339 if not narrowmatch(f):
2338 2340 continue
2339 2341 copies.pop(f, None) # delete if it exists
2340 2342 source = self._cache[f][b'copied']
2341 2343 if source:
2342 2344 copies[f] = source
2343 2345 return copies
2344 2346
2345 2347 def p2copies(self):
2346 2348 copies = {}
2347 2349 narrowmatch = self._repo.narrowmatch()
2348 2350 for f in self._cache.keys():
2349 2351 if not narrowmatch(f):
2350 2352 continue
2351 2353 copies.pop(f, None) # delete if it exists
2352 2354 source = self._cache[f][b'copied']
2353 2355 if source:
2354 2356 copies[f] = source
2355 2357 return copies
2356 2358
2357 2359 def isinmemory(self):
2358 2360 return True
2359 2361
2360 2362 def filedate(self, path):
2361 2363 if self.isdirty(path):
2362 2364 return self._cache[path][b'date']
2363 2365 else:
2364 2366 return self._wrappedctx[path].date()
2365 2367
2366 2368 def markcopied(self, path, origin):
2367 2369 self._markdirty(
2368 2370 path,
2369 2371 exists=True,
2370 2372 date=self.filedate(path),
2371 2373 flags=self.flags(path),
2372 2374 copied=origin,
2373 2375 )
2374 2376
2375 2377 def copydata(self, path):
2376 2378 if self.isdirty(path):
2377 2379 return self._cache[path][b'copied']
2378 2380 else:
2379 2381 return None
2380 2382
2381 2383 def flags(self, path):
2382 2384 if self.isdirty(path):
2383 2385 if self._cache[path][b'exists']:
2384 2386 return self._cache[path][b'flags']
2385 2387 else:
2386 2388 raise error.ProgrammingError(
2387 2389 b"No such file or directory: %s" % path
2388 2390 )
2389 2391 else:
2390 2392 return self._wrappedctx[path].flags()
2391 2393
2392 2394 def __contains__(self, key):
2393 2395 if key in self._cache:
2394 2396 return self._cache[key][b'exists']
2395 2397 return key in self.p1()
2396 2398
2397 2399 def _existsinparent(self, path):
2398 2400 try:
2399 2401 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2400 2402 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2401 2403 # with an ``exists()`` function.
2402 2404 self._wrappedctx[path]
2403 2405 return True
2404 2406 except error.ManifestLookupError:
2405 2407 return False
2406 2408
2407 2409 def _auditconflicts(self, path):
2408 2410 """Replicates conflict checks done by wvfs.write().
2409 2411
2410 2412 Since we never write to the filesystem and never call `applyupdates` in
2411 2413 IMM, we'll never check that a path is actually writable -- e.g., because
2412 2414 it adds `a/foo`, but `a` is actually a file in the other commit.
2413 2415 """
2414 2416
2415 2417 def fail(path, component):
2416 2418 # p1() is the base and we're receiving "writes" for p2()'s
2417 2419 # files.
2418 2420 if b'l' in self.p1()[component].flags():
2419 2421 raise error.Abort(
2420 2422 b"error: %s conflicts with symlink %s "
2421 2423 b"in %d." % (path, component, self.p1().rev())
2422 2424 )
2423 2425 else:
2424 2426 raise error.Abort(
2425 2427 b"error: '%s' conflicts with file '%s' in "
2426 2428 b"%d." % (path, component, self.p1().rev())
2427 2429 )
2428 2430
2429 2431 # Test that each new directory to be created to write this path from p2
2430 2432 # is not a file in p1.
2431 2433 components = path.split(b'/')
2432 2434 for i in range(len(components)):
2433 2435 component = b"/".join(components[0:i])
2434 2436 if component in self:
2435 2437 fail(path, component)
2436 2438
2437 2439 # Test the other direction -- that this path from p2 isn't a directory
2438 2440 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2439 2441 match = self.match([path], default=b'path')
2440 2442 mfiles = list(self.p1().manifest().walk(match))
2441 2443 if len(mfiles) > 0:
2442 2444 if len(mfiles) == 1 and mfiles[0] == path:
2443 2445 return
2444 2446 # omit the files which are deleted in current IMM wctx
2445 2447 mfiles = [m for m in mfiles if m in self]
2446 2448 if not mfiles:
2447 2449 return
2448 2450 raise error.Abort(
2449 2451 b"error: file '%s' cannot be written because "
2450 2452 b" '%s/' is a directory in %s (containing %d "
2451 2453 b"entries: %s)"
2452 2454 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2453 2455 )
2454 2456
2455 2457 def write(self, path, data, flags=b'', **kwargs):
2456 2458 if data is None:
2457 2459 raise error.ProgrammingError(b"data must be non-None")
2458 2460 self._auditconflicts(path)
2459 2461 self._markdirty(
2460 2462 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2461 2463 )
2462 2464
2463 2465 def setflags(self, path, l, x):
2464 2466 flag = b''
2465 2467 if l:
2466 2468 flag = b'l'
2467 2469 elif x:
2468 2470 flag = b'x'
2469 2471 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2470 2472
2471 2473 def remove(self, path):
2472 2474 self._markdirty(path, exists=False)
2473 2475
2474 2476 def exists(self, path):
2475 2477 """exists behaves like `lexists`, but needs to follow symlinks and
2476 2478 return False if they are broken.
2477 2479 """
2478 2480 if self.isdirty(path):
2479 2481 # If this path exists and is a symlink, "follow" it by calling
2480 2482 # exists on the destination path.
2481 2483 if (
2482 2484 self._cache[path][b'exists']
2483 2485 and b'l' in self._cache[path][b'flags']
2484 2486 ):
2485 2487 return self.exists(self._cache[path][b'data'].strip())
2486 2488 else:
2487 2489 return self._cache[path][b'exists']
2488 2490
2489 2491 return self._existsinparent(path)
2490 2492
2491 2493 def lexists(self, path):
2492 2494 """lexists returns True if the path exists"""
2493 2495 if self.isdirty(path):
2494 2496 return self._cache[path][b'exists']
2495 2497
2496 2498 return self._existsinparent(path)
2497 2499
2498 2500 def size(self, path):
2499 2501 if self.isdirty(path):
2500 2502 if self._cache[path][b'exists']:
2501 2503 return len(self._cache[path][b'data'])
2502 2504 else:
2503 2505 raise error.ProgrammingError(
2504 2506 b"No such file or directory: %s" % path
2505 2507 )
2506 2508 return self._wrappedctx[path].size()
2507 2509
2508 2510 def tomemctx(
2509 2511 self,
2510 2512 text,
2511 2513 branch=None,
2512 2514 extra=None,
2513 2515 date=None,
2514 2516 parents=None,
2515 2517 user=None,
2516 2518 editor=None,
2517 2519 ):
2518 2520 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2519 2521 committed.
2520 2522
2521 2523 ``text`` is the commit message.
2522 2524 ``parents`` (optional) are rev numbers.
2523 2525 """
2524 2526 # Default parents to the wrapped context if not passed.
2525 2527 if parents is None:
2526 2528 parents = self.parents()
2527 2529 if len(parents) == 1:
2528 2530 parents = (parents[0], None)
2529 2531
2530 2532 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2531 2533 if parents[1] is None:
2532 2534 parents = (self._repo[parents[0]], None)
2533 2535 else:
2534 2536 parents = (self._repo[parents[0]], self._repo[parents[1]])
2535 2537
2536 2538 files = self.files()
2537 2539
2538 2540 def getfile(repo, memctx, path):
2539 2541 if self._cache[path][b'exists']:
2540 2542 return memfilectx(
2541 2543 repo,
2542 2544 memctx,
2543 2545 path,
2544 2546 self._cache[path][b'data'],
2545 2547 b'l' in self._cache[path][b'flags'],
2546 2548 b'x' in self._cache[path][b'flags'],
2547 2549 self._cache[path][b'copied'],
2548 2550 )
2549 2551 else:
2550 2552 # Returning None, but including the path in `files`, is
2551 2553 # necessary for memctx to register a deletion.
2552 2554 return None
2553 2555
2554 2556 if branch is None:
2555 2557 branch = self._wrappedctx.branch()
2556 2558
2557 2559 return memctx(
2558 2560 self._repo,
2559 2561 parents,
2560 2562 text,
2561 2563 files,
2562 2564 getfile,
2563 2565 date=date,
2564 2566 extra=extra,
2565 2567 user=user,
2566 2568 branch=branch,
2567 2569 editor=editor,
2568 2570 )
2569 2571
2570 2572 def tomemctx_for_amend(self, precursor):
2571 2573 extra = precursor.extra().copy()
2572 2574 extra[b'amend_source'] = precursor.hex()
2573 2575 return self.tomemctx(
2574 2576 text=precursor.description(),
2575 2577 branch=precursor.branch(),
2576 2578 extra=extra,
2577 2579 date=precursor.date(),
2578 2580 user=precursor.user(),
2579 2581 )
2580 2582
2581 2583 def isdirty(self, path):
2582 2584 return path in self._cache
2583 2585
2584 2586 def clean(self):
2585 2587 self._mergestate = None
2586 2588 self._cache = {}
2587 2589
2588 2590 def _compact(self):
2589 2591 """Removes keys from the cache that are actually clean, by comparing
2590 2592 them with the underlying context.
2591 2593
2592 2594 This can occur during the merge process, e.g. by passing --tool :local
2593 2595 to resolve a conflict.
2594 2596 """
2595 2597 keys = []
2596 2598 # This won't be perfect, but can help performance significantly when
2597 2599 # using things like remotefilelog.
2598 2600 scmutil.prefetchfiles(
2599 2601 self.repo(),
2600 2602 [
2601 2603 (
2602 2604 self.p1().rev(),
2603 2605 scmutil.matchfiles(self.repo(), self._cache.keys()),
2604 2606 )
2605 2607 ],
2606 2608 )
2607 2609
2608 2610 for path in self._cache.keys():
2609 2611 cache = self._cache[path]
2610 2612 try:
2611 2613 underlying = self._wrappedctx[path]
2612 2614 if (
2613 2615 underlying.data() == cache[b'data']
2614 2616 and underlying.flags() == cache[b'flags']
2615 2617 ):
2616 2618 keys.append(path)
2617 2619 except error.ManifestLookupError:
2618 2620 # Path not in the underlying manifest (created).
2619 2621 continue
2620 2622
2621 2623 for path in keys:
2622 2624 del self._cache[path]
2623 2625 return keys
2624 2626
2625 2627 def _markdirty(
2626 2628 self, path, exists, data=None, date=None, flags=b'', copied=None
2627 2629 ):
2628 2630 # data not provided, let's see if we already have some; if not, let's
2629 2631 # grab it from our underlying context, so that we always have data if
2630 2632 # the file is marked as existing.
2631 2633 if exists and data is None:
2632 2634 oldentry = self._cache.get(path) or {}
2633 2635 data = oldentry.get(b'data')
2634 2636 if data is None:
2635 2637 data = self._wrappedctx[path].data()
2636 2638
2637 2639 self._cache[path] = {
2638 2640 b'exists': exists,
2639 2641 b'data': data,
2640 2642 b'date': date,
2641 2643 b'flags': flags,
2642 2644 b'copied': copied,
2643 2645 }
2644 2646 util.clearcachedproperty(self, b'_manifest')
2645 2647
2646 2648 def filectx(self, path, filelog=None):
2647 2649 return overlayworkingfilectx(
2648 2650 self._repo, path, parent=self, filelog=filelog
2649 2651 )
2650 2652
2651 2653 def mergestate(self, clean=False):
2652 2654 if clean or self._mergestate is None:
2653 2655 self._mergestate = mergestatemod.memmergestate(self._repo)
2654 2656 return self._mergestate
2655 2657
2656 2658
2657 2659 class overlayworkingfilectx(committablefilectx):
2658 2660 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2659 2661 cache, which can be flushed through later by calling ``flush()``."""
2660 2662
2661 2663 def __init__(self, repo, path, filelog=None, parent=None):
2662 2664 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2663 2665 self._repo = repo
2664 2666 self._parent = parent
2665 2667 self._path = path
2666 2668
2667 2669 def cmp(self, fctx):
2668 2670 return self.data() != fctx.data()
2669 2671
2670 2672 def changectx(self):
2671 2673 return self._parent
2672 2674
2673 2675 def data(self):
2674 2676 return self._parent.data(self._path)
2675 2677
2676 2678 def date(self):
2677 2679 return self._parent.filedate(self._path)
2678 2680
2679 2681 def exists(self):
2680 2682 return self.lexists()
2681 2683
2682 2684 def lexists(self):
2683 2685 return self._parent.exists(self._path)
2684 2686
2685 2687 def copysource(self):
2686 2688 return self._parent.copydata(self._path)
2687 2689
2688 2690 def size(self):
2689 2691 return self._parent.size(self._path)
2690 2692
2691 2693 def markcopied(self, origin):
2692 2694 self._parent.markcopied(self._path, origin)
2693 2695
2694 2696 def audit(self):
2695 2697 pass
2696 2698
2697 2699 def flags(self):
2698 2700 return self._parent.flags(self._path)
2699 2701
2700 2702 def setflags(self, islink, isexec):
2701 2703 return self._parent.setflags(self._path, islink, isexec)
2702 2704
2703 2705 def write(self, data, flags, backgroundclose=False, **kwargs):
2704 2706 return self._parent.write(self._path, data, flags, **kwargs)
2705 2707
2706 2708 def remove(self, ignoremissing=False):
2707 2709 return self._parent.remove(self._path)
2708 2710
2709 2711 def clearunknown(self):
2710 2712 pass
2711 2713
2712 2714
2713 2715 class workingcommitctx(workingctx):
2714 2716 """A workingcommitctx object makes access to data related to
2715 2717 the revision being committed convenient.
2716 2718
2717 2719 This hides changes in the working directory, if they aren't
2718 2720 committed in this context.
2719 2721 """
2720 2722
2721 2723 def __init__(
2722 2724 self, repo, changes, text=b"", user=None, date=None, extra=None
2723 2725 ):
2724 2726 super(workingcommitctx, self).__init__(
2725 2727 repo, text, user, date, extra, changes
2726 2728 )
2727 2729
2728 2730 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2729 2731 """Return matched files only in ``self._status``
2730 2732
2731 2733 Uncommitted files appear "clean" via this context, even if
2732 2734 they aren't actually so in the working directory.
2733 2735 """
2734 2736 if clean:
2735 2737 clean = [f for f in self._manifest if f not in self._changedset]
2736 2738 else:
2737 2739 clean = []
2738 2740 return scmutil.status(
2739 2741 [f for f in self._status.modified if match(f)],
2740 2742 [f for f in self._status.added if match(f)],
2741 2743 [f for f in self._status.removed if match(f)],
2742 2744 [],
2743 2745 [],
2744 2746 [],
2745 2747 clean,
2746 2748 )
2747 2749
2748 2750 @propertycache
2749 2751 def _changedset(self):
2750 2752 """Return the set of files changed in this context"""
2751 2753 changed = set(self._status.modified)
2752 2754 changed.update(self._status.added)
2753 2755 changed.update(self._status.removed)
2754 2756 return changed
2755 2757
2756 2758
2757 2759 def makecachingfilectxfn(func):
2758 2760 """Create a filectxfn that caches based on the path.
2759 2761
2760 2762 We can't use util.cachefunc because it uses all arguments as the cache
2761 2763 key and this creates a cycle since the arguments include the repo and
2762 2764 memctx.
2763 2765 """
2764 2766 cache = {}
2765 2767
2766 2768 def getfilectx(repo, memctx, path):
2767 2769 if path not in cache:
2768 2770 cache[path] = func(repo, memctx, path)
2769 2771 return cache[path]
2770 2772
2771 2773 return getfilectx
2772 2774
2773 2775
2774 2776 def memfilefromctx(ctx):
2775 2777 """Given a context return a memfilectx for ctx[path]
2776 2778
2777 2779 This is a convenience method for building a memctx based on another
2778 2780 context.
2779 2781 """
2780 2782
2781 2783 def getfilectx(repo, memctx, path):
2782 2784 fctx = ctx[path]
2783 2785 copysource = fctx.copysource()
2784 2786 return memfilectx(
2785 2787 repo,
2786 2788 memctx,
2787 2789 path,
2788 2790 fctx.data(),
2789 2791 islink=fctx.islink(),
2790 2792 isexec=fctx.isexec(),
2791 2793 copysource=copysource,
2792 2794 )
2793 2795
2794 2796 return getfilectx
2795 2797
2796 2798
2797 2799 def memfilefrompatch(patchstore):
2798 2800 """Given a patch (e.g. patchstore object) return a memfilectx
2799 2801
2800 2802 This is a convenience method for building a memctx based on a patchstore.
2801 2803 """
2802 2804
2803 2805 def getfilectx(repo, memctx, path):
2804 2806 data, mode, copysource = patchstore.getfile(path)
2805 2807 if data is None:
2806 2808 return None
2807 2809 islink, isexec = mode
2808 2810 return memfilectx(
2809 2811 repo,
2810 2812 memctx,
2811 2813 path,
2812 2814 data,
2813 2815 islink=islink,
2814 2816 isexec=isexec,
2815 2817 copysource=copysource,
2816 2818 )
2817 2819
2818 2820 return getfilectx
2819 2821
2820 2822
2821 2823 class memctx(committablectx):
2822 2824 """Use memctx to perform in-memory commits via localrepo.commitctx().
2823 2825
2824 2826 Revision information is supplied at initialization time while
2825 2827 related files data and is made available through a callback
2826 2828 mechanism. 'repo' is the current localrepo, 'parents' is a
2827 2829 sequence of two parent revisions identifiers (pass None for every
2828 2830 missing parent), 'text' is the commit message and 'files' lists
2829 2831 names of files touched by the revision (normalized and relative to
2830 2832 repository root).
2831 2833
2832 2834 filectxfn(repo, memctx, path) is a callable receiving the
2833 2835 repository, the current memctx object and the normalized path of
2834 2836 requested file, relative to repository root. It is fired by the
2835 2837 commit function for every file in 'files', but calls order is
2836 2838 undefined. If the file is available in the revision being
2837 2839 committed (updated or added), filectxfn returns a memfilectx
2838 2840 object. If the file was removed, filectxfn return None for recent
2839 2841 Mercurial. Moved files are represented by marking the source file
2840 2842 removed and the new file added with copy information (see
2841 2843 memfilectx).
2842 2844
2843 2845 user receives the committer name and defaults to current
2844 2846 repository username, date is the commit date in any format
2845 2847 supported by dateutil.parsedate() and defaults to current date, extra
2846 2848 is a dictionary of metadata or is left empty.
2847 2849 """
2848 2850
2849 2851 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2850 2852 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2851 2853 # this field to determine what to do in filectxfn.
2852 2854 _returnnoneformissingfiles = True
2853 2855
2854 2856 def __init__(
2855 2857 self,
2856 2858 repo,
2857 2859 parents,
2858 2860 text,
2859 2861 files,
2860 2862 filectxfn,
2861 2863 user=None,
2862 2864 date=None,
2863 2865 extra=None,
2864 2866 branch=None,
2865 2867 editor=None,
2866 2868 ):
2867 2869 super(memctx, self).__init__(
2868 2870 repo, text, user, date, extra, branch=branch
2869 2871 )
2870 2872 self._rev = None
2871 2873 self._node = None
2872 2874 parents = [(p or self._repo.nodeconstants.nullid) for p in parents]
2873 2875 p1, p2 = parents
2874 2876 self._parents = [self._repo[p] for p in (p1, p2)]
2875 2877 files = sorted(set(files))
2876 2878 self._files = files
2877 2879 self.substate = {}
2878 2880
2879 2881 if isinstance(filectxfn, patch.filestore):
2880 2882 filectxfn = memfilefrompatch(filectxfn)
2881 2883 elif not callable(filectxfn):
2882 2884 # if store is not callable, wrap it in a function
2883 2885 filectxfn = memfilefromctx(filectxfn)
2884 2886
2885 2887 # memoizing increases performance for e.g. vcs convert scenarios.
2886 2888 self._filectxfn = makecachingfilectxfn(filectxfn)
2887 2889
2888 2890 if editor:
2889 2891 self._text = editor(self._repo, self, [])
2890 2892 self._repo.savecommitmessage(self._text)
2891 2893
2892 2894 def filectx(self, path, filelog=None):
2893 2895 """get a file context from the working directory
2894 2896
2895 2897 Returns None if file doesn't exist and should be removed."""
2896 2898 return self._filectxfn(self._repo, self, path)
2897 2899
2898 2900 def commit(self):
2899 2901 """commit context to the repo"""
2900 2902 return self._repo.commitctx(self)
2901 2903
2902 2904 @propertycache
2903 2905 def _manifest(self):
2904 2906 """generate a manifest based on the return values of filectxfn"""
2905 2907
2906 2908 # keep this simple for now; just worry about p1
2907 2909 pctx = self._parents[0]
2908 2910 man = pctx.manifest().copy()
2909 2911
2910 2912 for f in self._status.modified:
2911 2913 man[f] = self._repo.nodeconstants.modifiednodeid
2912 2914
2913 2915 for f in self._status.added:
2914 2916 man[f] = self._repo.nodeconstants.addednodeid
2915 2917
2916 2918 for f in self._status.removed:
2917 2919 if f in man:
2918 2920 del man[f]
2919 2921
2920 2922 return man
2921 2923
2922 2924 @propertycache
2923 2925 def _status(self):
2924 2926 """Calculate exact status from ``files`` specified at construction"""
2925 2927 man1 = self.p1().manifest()
2926 2928 p2 = self._parents[1]
2927 2929 # "1 < len(self._parents)" can't be used for checking
2928 2930 # existence of the 2nd parent, because "memctx._parents" is
2929 2931 # explicitly initialized by the list, of which length is 2.
2930 2932 if p2.rev() != nullrev:
2931 2933 man2 = p2.manifest()
2932 2934 managing = lambda f: f in man1 or f in man2
2933 2935 else:
2934 2936 managing = lambda f: f in man1
2935 2937
2936 2938 modified, added, removed = [], [], []
2937 2939 for f in self._files:
2938 2940 if not managing(f):
2939 2941 added.append(f)
2940 2942 elif self[f]:
2941 2943 modified.append(f)
2942 2944 else:
2943 2945 removed.append(f)
2944 2946
2945 2947 return scmutil.status(modified, added, removed, [], [], [], [])
2946 2948
2947 2949 def parents(self):
2948 2950 if self._parents[1].rev() == nullrev:
2949 2951 return [self._parents[0]]
2950 2952 return self._parents
2951 2953
2952 2954
2953 2955 class memfilectx(committablefilectx):
2954 2956 """memfilectx represents an in-memory file to commit.
2955 2957
2956 2958 See memctx and committablefilectx for more details.
2957 2959 """
2958 2960
2959 2961 def __init__(
2960 2962 self,
2961 2963 repo,
2962 2964 changectx,
2963 2965 path,
2964 2966 data,
2965 2967 islink=False,
2966 2968 isexec=False,
2967 2969 copysource=None,
2968 2970 ):
2969 2971 """
2970 2972 path is the normalized file path relative to repository root.
2971 2973 data is the file content as a string.
2972 2974 islink is True if the file is a symbolic link.
2973 2975 isexec is True if the file is executable.
2974 2976 copied is the source file path if current file was copied in the
2975 2977 revision being committed, or None."""
2976 2978 super(memfilectx, self).__init__(repo, path, None, changectx)
2977 2979 self._data = data
2978 2980 if islink:
2979 2981 self._flags = b'l'
2980 2982 elif isexec:
2981 2983 self._flags = b'x'
2982 2984 else:
2983 2985 self._flags = b''
2984 2986 self._copysource = copysource
2985 2987
2986 2988 def copysource(self):
2987 2989 return self._copysource
2988 2990
2989 2991 def cmp(self, fctx):
2990 2992 return self.data() != fctx.data()
2991 2993
2992 2994 def data(self):
2993 2995 return self._data
2994 2996
2995 2997 def remove(self, ignoremissing=False):
2996 2998 """wraps unlink for a repo's working directory"""
2997 2999 # need to figure out what to do here
2998 3000 del self._changectx[self._path]
2999 3001
3000 3002 def write(self, data, flags, **kwargs):
3001 3003 """wraps repo.wwrite"""
3002 3004 self._data = data
3003 3005
3004 3006
3005 3007 class metadataonlyctx(committablectx):
3006 3008 """Like memctx but it's reusing the manifest of different commit.
3007 3009 Intended to be used by lightweight operations that are creating
3008 3010 metadata-only changes.
3009 3011
3010 3012 Revision information is supplied at initialization time. 'repo' is the
3011 3013 current localrepo, 'ctx' is original revision which manifest we're reuisng
3012 3014 'parents' is a sequence of two parent revisions identifiers (pass None for
3013 3015 every missing parent), 'text' is the commit.
3014 3016
3015 3017 user receives the committer name and defaults to current repository
3016 3018 username, date is the commit date in any format supported by
3017 3019 dateutil.parsedate() and defaults to current date, extra is a dictionary of
3018 3020 metadata or is left empty.
3019 3021 """
3020 3022
3021 3023 def __init__(
3022 3024 self,
3023 3025 repo,
3024 3026 originalctx,
3025 3027 parents=None,
3026 3028 text=None,
3027 3029 user=None,
3028 3030 date=None,
3029 3031 extra=None,
3030 3032 editor=None,
3031 3033 ):
3032 3034 if text is None:
3033 3035 text = originalctx.description()
3034 3036 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
3035 3037 self._rev = None
3036 3038 self._node = None
3037 3039 self._originalctx = originalctx
3038 3040 self._manifestnode = originalctx.manifestnode()
3039 3041 if parents is None:
3040 3042 parents = originalctx.parents()
3041 3043 else:
3042 3044 parents = [repo[p] for p in parents if p is not None]
3043 3045 parents = parents[:]
3044 3046 while len(parents) < 2:
3045 3047 parents.append(repo[nullrev])
3046 3048 p1, p2 = self._parents = parents
3047 3049
3048 3050 # sanity check to ensure that the reused manifest parents are
3049 3051 # manifests of our commit parents
3050 3052 mp1, mp2 = self.manifestctx().parents
3051 3053 if p1 != self._repo.nodeconstants.nullid and p1.manifestnode() != mp1:
3052 3054 raise RuntimeError(
3053 3055 r"can't reuse the manifest: its p1 "
3054 3056 r"doesn't match the new ctx p1"
3055 3057 )
3056 3058 if p2 != self._repo.nodeconstants.nullid and p2.manifestnode() != mp2:
3057 3059 raise RuntimeError(
3058 3060 r"can't reuse the manifest: "
3059 3061 r"its p2 doesn't match the new ctx p2"
3060 3062 )
3061 3063
3062 3064 self._files = originalctx.files()
3063 3065 self.substate = {}
3064 3066
3065 3067 if editor:
3066 3068 self._text = editor(self._repo, self, [])
3067 3069 self._repo.savecommitmessage(self._text)
3068 3070
3069 3071 def manifestnode(self):
3070 3072 return self._manifestnode
3071 3073
3072 3074 @property
3073 3075 def _manifestctx(self):
3074 3076 return self._repo.manifestlog[self._manifestnode]
3075 3077
3076 3078 def filectx(self, path, filelog=None):
3077 3079 return self._originalctx.filectx(path, filelog=filelog)
3078 3080
3079 3081 def commit(self):
3080 3082 """commit context to the repo"""
3081 3083 return self._repo.commitctx(self)
3082 3084
3083 3085 @property
3084 3086 def _manifest(self):
3085 3087 return self._originalctx.manifest()
3086 3088
3087 3089 @propertycache
3088 3090 def _status(self):
3089 3091 """Calculate exact status from ``files`` specified in the ``origctx``
3090 3092 and parents manifests.
3091 3093 """
3092 3094 man1 = self.p1().manifest()
3093 3095 p2 = self._parents[1]
3094 3096 # "1 < len(self._parents)" can't be used for checking
3095 3097 # existence of the 2nd parent, because "metadataonlyctx._parents" is
3096 3098 # explicitly initialized by the list, of which length is 2.
3097 3099 if p2.rev() != nullrev:
3098 3100 man2 = p2.manifest()
3099 3101 managing = lambda f: f in man1 or f in man2
3100 3102 else:
3101 3103 managing = lambda f: f in man1
3102 3104
3103 3105 modified, added, removed = [], [], []
3104 3106 for f in self._files:
3105 3107 if not managing(f):
3106 3108 added.append(f)
3107 3109 elif f in self:
3108 3110 modified.append(f)
3109 3111 else:
3110 3112 removed.append(f)
3111 3113
3112 3114 return scmutil.status(modified, added, removed, [], [], [], [])
3113 3115
3114 3116
3115 3117 class arbitraryfilectx:
3116 3118 """Allows you to use filectx-like functions on a file in an arbitrary
3117 3119 location on disk, possibly not in the working directory.
3118 3120 """
3119 3121
3120 3122 def __init__(self, path, repo=None):
3121 3123 # Repo is optional because contrib/simplemerge uses this class.
3122 3124 self._repo = repo
3123 3125 self._path = path
3124 3126
3125 3127 def cmp(self, fctx):
3126 3128 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3127 3129 # path if either side is a symlink.
3128 3130 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3129 3131 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3130 3132 # Add a fast-path for merge if both sides are disk-backed.
3131 3133 # Note that filecmp uses the opposite return values (True if same)
3132 3134 # from our cmp functions (True if different).
3133 3135 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3134 3136 return self.data() != fctx.data()
3135 3137
3136 3138 def path(self):
3137 3139 return self._path
3138 3140
3139 3141 def flags(self):
3140 3142 return b''
3141 3143
3142 3144 def data(self):
3143 3145 return util.readfile(self._path)
3144 3146
3145 3147 def decodeddata(self):
3146 3148 return util.readfile(self._path)
3147 3149
3148 3150 def remove(self):
3149 3151 util.unlink(self._path)
3150 3152
3151 3153 def write(self, data, flags, **kwargs):
3152 3154 assert not flags
3153 3155 util.writefile(self._path, data)
General Comments 0
You need to be logged in to leave comments. Login now