##// END OF EJS Templates
status: pre-indent the dirstate status code...
marmoute -
r51028:21b6ce3a default
parent child Browse files
Show More
@@ -1,3144 +1,3145 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 dirstate = self._repo.dirstate
1858 1858 poststatus = self._repo.postdsstatus()
1859 1859 if fixup:
1860 1860 if dirstate.is_changing_parents:
1861 1861 normal = lambda f, pfd: dirstate.update_file(
1862 1862 f,
1863 1863 p1_tracked=True,
1864 1864 wc_tracked=True,
1865 1865 )
1866 1866 else:
1867 1867 normal = dirstate.set_clean
1868 1868 for f, pdf in fixup:
1869 1869 normal(f, pdf)
1870 1870 if poststatus or self._repo.dirstate._dirty:
1871 1871 try:
1872 1872 # updating the dirstate is optional
1873 1873 # so we don't wait on the lock
1874 1874 # wlock can invalidate the dirstate, so cache normal _after_
1875 1875 # taking the lock
1876 1876 pre_dirty = dirstate._dirty
1877 1877 with self._repo.wlock(False):
1878 1878 assert self._repo.dirstate is dirstate
1879 1879 post_dirty = dirstate._dirty
1880 1880 if post_dirty:
1881 1881 tr = self._repo.currenttransaction()
1882 1882 dirstate.write(tr)
1883 1883 elif pre_dirty:
1884 1884 # the wlock grabbing detected that dirtate changes
1885 1885 # needed to be dropped
1886 1886 m = b'skip updating dirstate: identity mismatch\n'
1887 1887 self._repo.ui.debug(m)
1888 1888 if poststatus:
1889 1889 for ps in poststatus:
1890 1890 ps(self, status)
1891 1891 except error.LockError:
1892 1892 dirstate.invalidate()
1893 1893 finally:
1894 1894 # Even if the wlock couldn't be grabbed, clear out the list.
1895 1895 self._repo.clearpostdsstatus()
1896 1896
1897 1897 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1898 1898 '''Gets the status from the dirstate -- internal use only.'''
1899 1899 subrepos = []
1900 1900 if b'.hgsub' in self:
1901 1901 subrepos = sorted(self.substate)
1902 if True:
1902 1903 cmp, s, mtime_boundary = self._repo.dirstate.status(
1903 1904 match, subrepos, ignored=ignored, clean=clean, unknown=unknown
1904 1905 )
1905 1906
1906 1907 # check for any possibly clean files
1907 1908 fixup = []
1908 1909 if cmp:
1909 1910 modified2, deleted2, clean_set, fixup = self._checklookup(
1910 1911 cmp, mtime_boundary
1911 1912 )
1912 1913 s.modified.extend(modified2)
1913 1914 s.deleted.extend(deleted2)
1914 1915
1915 1916 if clean_set and clean:
1916 1917 s.clean.extend(clean_set)
1917 1918 if fixup and clean:
1918 1919 s.clean.extend((f for f, _ in fixup))
1919 1920
1920 1921 self._poststatusfixup(s, fixup)
1921 1922
1922 1923 if match.always():
1923 1924 # cache for performance
1924 1925 if s.unknown or s.ignored or s.clean:
1925 1926 # "_status" is cached with list*=False in the normal route
1926 1927 self._status = scmutil.status(
1927 1928 s.modified, s.added, s.removed, s.deleted, [], [], []
1928 1929 )
1929 1930 else:
1930 1931 self._status = s
1931 1932
1932 1933 return s
1933 1934
1934 1935 @propertycache
1935 1936 def _copies(self):
1936 1937 p1copies = {}
1937 1938 p2copies = {}
1938 1939 parents = self._repo.dirstate.parents()
1939 1940 p1manifest = self._repo[parents[0]].manifest()
1940 1941 p2manifest = self._repo[parents[1]].manifest()
1941 1942 changedset = set(self.added()) | set(self.modified())
1942 1943 narrowmatch = self._repo.narrowmatch()
1943 1944 for dst, src in self._repo.dirstate.copies().items():
1944 1945 if dst not in changedset or not narrowmatch(dst):
1945 1946 continue
1946 1947 if src in p1manifest:
1947 1948 p1copies[dst] = src
1948 1949 elif src in p2manifest:
1949 1950 p2copies[dst] = src
1950 1951 return p1copies, p2copies
1951 1952
1952 1953 @propertycache
1953 1954 def _manifest(self):
1954 1955 """generate a manifest corresponding to the values in self._status
1955 1956
1956 1957 This reuse the file nodeid from parent, but we use special node
1957 1958 identifiers for added and modified files. This is used by manifests
1958 1959 merge to see that files are different and by update logic to avoid
1959 1960 deleting newly added files.
1960 1961 """
1961 1962 return self._buildstatusmanifest(self._status)
1962 1963
1963 1964 def _buildstatusmanifest(self, status):
1964 1965 """Builds a manifest that includes the given status results."""
1965 1966 parents = self.parents()
1966 1967
1967 1968 man = parents[0].manifest().copy()
1968 1969
1969 1970 ff = self._flagfunc
1970 1971 for i, l in (
1971 1972 (self._repo.nodeconstants.addednodeid, status.added),
1972 1973 (self._repo.nodeconstants.modifiednodeid, status.modified),
1973 1974 ):
1974 1975 for f in l:
1975 1976 man[f] = i
1976 1977 try:
1977 1978 man.setflag(f, ff(f))
1978 1979 except OSError:
1979 1980 pass
1980 1981
1981 1982 for f in status.deleted + status.removed:
1982 1983 if f in man:
1983 1984 del man[f]
1984 1985
1985 1986 return man
1986 1987
1987 1988 def _buildstatus(
1988 1989 self, other, s, match, listignored, listclean, listunknown
1989 1990 ):
1990 1991 """build a status with respect to another context
1991 1992
1992 1993 This includes logic for maintaining the fast path of status when
1993 1994 comparing the working directory against its parent, which is to skip
1994 1995 building a new manifest if self (working directory) is not comparing
1995 1996 against its parent (repo['.']).
1996 1997 """
1997 1998 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1998 1999 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1999 2000 # might have accidentally ended up with the entire contents of the file
2000 2001 # they are supposed to be linking to.
2001 2002 s.modified[:] = self._filtersuspectsymlink(s.modified)
2002 2003 if other != self._repo[b'.']:
2003 2004 s = super(workingctx, self)._buildstatus(
2004 2005 other, s, match, listignored, listclean, listunknown
2005 2006 )
2006 2007 return s
2007 2008
2008 2009 def _matchstatus(self, other, match):
2009 2010 """override the match method with a filter for directory patterns
2010 2011
2011 2012 We use inheritance to customize the match.bad method only in cases of
2012 2013 workingctx since it belongs only to the working directory when
2013 2014 comparing against the parent changeset.
2014 2015
2015 2016 If we aren't comparing against the working directory's parent, then we
2016 2017 just use the default match object sent to us.
2017 2018 """
2018 2019 if other != self._repo[b'.']:
2019 2020
2020 2021 def bad(f, msg):
2021 2022 # 'f' may be a directory pattern from 'match.files()',
2022 2023 # so 'f not in ctx1' is not enough
2023 2024 if f not in other and not other.hasdir(f):
2024 2025 self._repo.ui.warn(
2025 2026 b'%s: %s\n' % (self._repo.dirstate.pathto(f), msg)
2026 2027 )
2027 2028
2028 2029 match.bad = bad
2029 2030 return match
2030 2031
2031 2032 def walk(self, match):
2032 2033 '''Generates matching file names.'''
2033 2034 return sorted(
2034 2035 self._repo.dirstate.walk(
2035 2036 self._repo.narrowmatch(match),
2036 2037 subrepos=sorted(self.substate),
2037 2038 unknown=True,
2038 2039 ignored=False,
2039 2040 )
2040 2041 )
2041 2042
2042 2043 def matches(self, match):
2043 2044 match = self._repo.narrowmatch(match)
2044 2045 ds = self._repo.dirstate
2045 2046 return sorted(f for f in ds.matches(match) if ds.get_entry(f).tracked)
2046 2047
2047 2048 def markcommitted(self, node):
2048 2049 with self._repo.dirstate.changing_parents(self._repo):
2049 2050 for f in self.modified() + self.added():
2050 2051 self._repo.dirstate.update_file(
2051 2052 f, p1_tracked=True, wc_tracked=True
2052 2053 )
2053 2054 for f in self.removed():
2054 2055 self._repo.dirstate.update_file(
2055 2056 f, p1_tracked=False, wc_tracked=False
2056 2057 )
2057 2058 self._repo.dirstate.setparents(node)
2058 2059 self._repo._quick_access_changeid_invalidate()
2059 2060
2060 2061 sparse.aftercommit(self._repo, node)
2061 2062
2062 2063 # write changes out explicitly, because nesting wlock at
2063 2064 # runtime may prevent 'wlock.release()' in 'repo.commit()'
2064 2065 # from immediately doing so for subsequent changing files
2065 2066 self._repo.dirstate.write(self._repo.currenttransaction())
2066 2067
2067 2068 def mergestate(self, clean=False):
2068 2069 if clean:
2069 2070 return mergestatemod.mergestate.clean(self._repo)
2070 2071 return mergestatemod.mergestate.read(self._repo)
2071 2072
2072 2073
2073 2074 class committablefilectx(basefilectx):
2074 2075 """A committablefilectx provides common functionality for a file context
2075 2076 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
2076 2077
2077 2078 def __init__(self, repo, path, filelog=None, ctx=None):
2078 2079 self._repo = repo
2079 2080 self._path = path
2080 2081 self._changeid = None
2081 2082 self._filerev = self._filenode = None
2082 2083
2083 2084 if filelog is not None:
2084 2085 self._filelog = filelog
2085 2086 if ctx:
2086 2087 self._changectx = ctx
2087 2088
2088 2089 def __nonzero__(self):
2089 2090 return True
2090 2091
2091 2092 __bool__ = __nonzero__
2092 2093
2093 2094 def linkrev(self):
2094 2095 # linked to self._changectx no matter if file is modified or not
2095 2096 return self.rev()
2096 2097
2097 2098 def renamed(self):
2098 2099 path = self.copysource()
2099 2100 if not path:
2100 2101 return None
2101 2102 return (
2102 2103 path,
2103 2104 self._changectx._parents[0]._manifest.get(
2104 2105 path, self._repo.nodeconstants.nullid
2105 2106 ),
2106 2107 )
2107 2108
2108 2109 def parents(self):
2109 2110 '''return parent filectxs, following copies if necessary'''
2110 2111
2111 2112 def filenode(ctx, path):
2112 2113 return ctx._manifest.get(path, self._repo.nodeconstants.nullid)
2113 2114
2114 2115 path = self._path
2115 2116 fl = self._filelog
2116 2117 pcl = self._changectx._parents
2117 2118 renamed = self.renamed()
2118 2119
2119 2120 if renamed:
2120 2121 pl = [renamed + (None,)]
2121 2122 else:
2122 2123 pl = [(path, filenode(pcl[0], path), fl)]
2123 2124
2124 2125 for pc in pcl[1:]:
2125 2126 pl.append((path, filenode(pc, path), fl))
2126 2127
2127 2128 return [
2128 2129 self._parentfilectx(p, fileid=n, filelog=l)
2129 2130 for p, n, l in pl
2130 2131 if n != self._repo.nodeconstants.nullid
2131 2132 ]
2132 2133
2133 2134 def children(self):
2134 2135 return []
2135 2136
2136 2137
2137 2138 class workingfilectx(committablefilectx):
2138 2139 """A workingfilectx object makes access to data related to a particular
2139 2140 file in the working directory convenient."""
2140 2141
2141 2142 def __init__(self, repo, path, filelog=None, workingctx=None):
2142 2143 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
2143 2144
2144 2145 @propertycache
2145 2146 def _changectx(self):
2146 2147 return workingctx(self._repo)
2147 2148
2148 2149 def data(self):
2149 2150 return self._repo.wread(self._path)
2150 2151
2151 2152 def copysource(self):
2152 2153 return self._repo.dirstate.copied(self._path)
2153 2154
2154 2155 def size(self):
2155 2156 return self._repo.wvfs.lstat(self._path).st_size
2156 2157
2157 2158 def lstat(self):
2158 2159 return self._repo.wvfs.lstat(self._path)
2159 2160
2160 2161 def date(self):
2161 2162 t, tz = self._changectx.date()
2162 2163 try:
2163 2164 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
2164 2165 except FileNotFoundError:
2165 2166 return (t, tz)
2166 2167
2167 2168 def exists(self):
2168 2169 return self._repo.wvfs.exists(self._path)
2169 2170
2170 2171 def lexists(self):
2171 2172 return self._repo.wvfs.lexists(self._path)
2172 2173
2173 2174 def audit(self):
2174 2175 return self._repo.wvfs.audit(self._path)
2175 2176
2176 2177 def cmp(self, fctx):
2177 2178 """compare with other file context
2178 2179
2179 2180 returns True if different than fctx.
2180 2181 """
2181 2182 # fctx should be a filectx (not a workingfilectx)
2182 2183 # invert comparison to reuse the same code path
2183 2184 return fctx.cmp(self)
2184 2185
2185 2186 def remove(self, ignoremissing=False):
2186 2187 """wraps unlink for a repo's working directory"""
2187 2188 rmdir = self._repo.ui.configbool(b'experimental', b'removeemptydirs')
2188 2189 self._repo.wvfs.unlinkpath(
2189 2190 self._path, ignoremissing=ignoremissing, rmdir=rmdir
2190 2191 )
2191 2192
2192 2193 def write(self, data, flags, backgroundclose=False, **kwargs):
2193 2194 """wraps repo.wwrite"""
2194 2195 return self._repo.wwrite(
2195 2196 self._path, data, flags, backgroundclose=backgroundclose, **kwargs
2196 2197 )
2197 2198
2198 2199 def markcopied(self, src):
2199 2200 """marks this file a copy of `src`"""
2200 2201 self._repo.dirstate.copy(src, self._path)
2201 2202
2202 2203 def clearunknown(self):
2203 2204 """Removes conflicting items in the working directory so that
2204 2205 ``write()`` can be called successfully.
2205 2206 """
2206 2207 wvfs = self._repo.wvfs
2207 2208 f = self._path
2208 2209 wvfs.audit(f)
2209 2210 if self._repo.ui.configbool(
2210 2211 b'experimental', b'merge.checkpathconflicts'
2211 2212 ):
2212 2213 # remove files under the directory as they should already be
2213 2214 # warned and backed up
2214 2215 if wvfs.isdir(f) and not wvfs.islink(f):
2215 2216 wvfs.rmtree(f, forcibly=True)
2216 2217 for p in reversed(list(pathutil.finddirs(f))):
2217 2218 if wvfs.isfileorlink(p):
2218 2219 wvfs.unlink(p)
2219 2220 break
2220 2221 else:
2221 2222 # don't remove files if path conflicts are not processed
2222 2223 if wvfs.isdir(f) and not wvfs.islink(f):
2223 2224 wvfs.removedirs(f)
2224 2225
2225 2226 def setflags(self, l, x):
2226 2227 self._repo.wvfs.setflags(self._path, l, x)
2227 2228
2228 2229
2229 2230 class overlayworkingctx(committablectx):
2230 2231 """Wraps another mutable context with a write-back cache that can be
2231 2232 converted into a commit context.
2232 2233
2233 2234 self._cache[path] maps to a dict with keys: {
2234 2235 'exists': bool?
2235 2236 'date': date?
2236 2237 'data': str?
2237 2238 'flags': str?
2238 2239 'copied': str? (path or None)
2239 2240 }
2240 2241 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
2241 2242 is `False`, the file was deleted.
2242 2243 """
2243 2244
2244 2245 def __init__(self, repo):
2245 2246 super(overlayworkingctx, self).__init__(repo)
2246 2247 self.clean()
2247 2248
2248 2249 def setbase(self, wrappedctx):
2249 2250 self._wrappedctx = wrappedctx
2250 2251 self._parents = [wrappedctx]
2251 2252 # Drop old manifest cache as it is now out of date.
2252 2253 # This is necessary when, e.g., rebasing several nodes with one
2253 2254 # ``overlayworkingctx`` (e.g. with --collapse).
2254 2255 util.clearcachedproperty(self, b'_manifest')
2255 2256
2256 2257 def setparents(self, p1node, p2node=None):
2257 2258 if p2node is None:
2258 2259 p2node = self._repo.nodeconstants.nullid
2259 2260 assert p1node == self._wrappedctx.node()
2260 2261 self._parents = [self._wrappedctx, self._repo.unfiltered()[p2node]]
2261 2262
2262 2263 def data(self, path):
2263 2264 if self.isdirty(path):
2264 2265 if self._cache[path][b'exists']:
2265 2266 if self._cache[path][b'data'] is not None:
2266 2267 return self._cache[path][b'data']
2267 2268 else:
2268 2269 # Must fallback here, too, because we only set flags.
2269 2270 return self._wrappedctx[path].data()
2270 2271 else:
2271 2272 raise error.ProgrammingError(
2272 2273 b"No such file or directory: %s" % path
2273 2274 )
2274 2275 else:
2275 2276 return self._wrappedctx[path].data()
2276 2277
2277 2278 @propertycache
2278 2279 def _manifest(self):
2279 2280 parents = self.parents()
2280 2281 man = parents[0].manifest().copy()
2281 2282
2282 2283 flag = self._flagfunc
2283 2284 for path in self.added():
2284 2285 man[path] = self._repo.nodeconstants.addednodeid
2285 2286 man.setflag(path, flag(path))
2286 2287 for path in self.modified():
2287 2288 man[path] = self._repo.nodeconstants.modifiednodeid
2288 2289 man.setflag(path, flag(path))
2289 2290 for path in self.removed():
2290 2291 del man[path]
2291 2292 return man
2292 2293
2293 2294 @propertycache
2294 2295 def _flagfunc(self):
2295 2296 def f(path):
2296 2297 return self._cache[path][b'flags']
2297 2298
2298 2299 return f
2299 2300
2300 2301 def files(self):
2301 2302 return sorted(self.added() + self.modified() + self.removed())
2302 2303
2303 2304 def modified(self):
2304 2305 return [
2305 2306 f
2306 2307 for f in self._cache.keys()
2307 2308 if self._cache[f][b'exists'] and self._existsinparent(f)
2308 2309 ]
2309 2310
2310 2311 def added(self):
2311 2312 return [
2312 2313 f
2313 2314 for f in self._cache.keys()
2314 2315 if self._cache[f][b'exists'] and not self._existsinparent(f)
2315 2316 ]
2316 2317
2317 2318 def removed(self):
2318 2319 return [
2319 2320 f
2320 2321 for f in self._cache.keys()
2321 2322 if not self._cache[f][b'exists'] and self._existsinparent(f)
2322 2323 ]
2323 2324
2324 2325 def p1copies(self):
2325 2326 copies = {}
2326 2327 narrowmatch = self._repo.narrowmatch()
2327 2328 for f in self._cache.keys():
2328 2329 if not narrowmatch(f):
2329 2330 continue
2330 2331 copies.pop(f, None) # delete if it exists
2331 2332 source = self._cache[f][b'copied']
2332 2333 if source:
2333 2334 copies[f] = source
2334 2335 return copies
2335 2336
2336 2337 def p2copies(self):
2337 2338 copies = {}
2338 2339 narrowmatch = self._repo.narrowmatch()
2339 2340 for f in self._cache.keys():
2340 2341 if not narrowmatch(f):
2341 2342 continue
2342 2343 copies.pop(f, None) # delete if it exists
2343 2344 source = self._cache[f][b'copied']
2344 2345 if source:
2345 2346 copies[f] = source
2346 2347 return copies
2347 2348
2348 2349 def isinmemory(self):
2349 2350 return True
2350 2351
2351 2352 def filedate(self, path):
2352 2353 if self.isdirty(path):
2353 2354 return self._cache[path][b'date']
2354 2355 else:
2355 2356 return self._wrappedctx[path].date()
2356 2357
2357 2358 def markcopied(self, path, origin):
2358 2359 self._markdirty(
2359 2360 path,
2360 2361 exists=True,
2361 2362 date=self.filedate(path),
2362 2363 flags=self.flags(path),
2363 2364 copied=origin,
2364 2365 )
2365 2366
2366 2367 def copydata(self, path):
2367 2368 if self.isdirty(path):
2368 2369 return self._cache[path][b'copied']
2369 2370 else:
2370 2371 return None
2371 2372
2372 2373 def flags(self, path):
2373 2374 if self.isdirty(path):
2374 2375 if self._cache[path][b'exists']:
2375 2376 return self._cache[path][b'flags']
2376 2377 else:
2377 2378 raise error.ProgrammingError(
2378 2379 b"No such file or directory: %s" % path
2379 2380 )
2380 2381 else:
2381 2382 return self._wrappedctx[path].flags()
2382 2383
2383 2384 def __contains__(self, key):
2384 2385 if key in self._cache:
2385 2386 return self._cache[key][b'exists']
2386 2387 return key in self.p1()
2387 2388
2388 2389 def _existsinparent(self, path):
2389 2390 try:
2390 2391 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
2391 2392 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
2392 2393 # with an ``exists()`` function.
2393 2394 self._wrappedctx[path]
2394 2395 return True
2395 2396 except error.ManifestLookupError:
2396 2397 return False
2397 2398
2398 2399 def _auditconflicts(self, path):
2399 2400 """Replicates conflict checks done by wvfs.write().
2400 2401
2401 2402 Since we never write to the filesystem and never call `applyupdates` in
2402 2403 IMM, we'll never check that a path is actually writable -- e.g., because
2403 2404 it adds `a/foo`, but `a` is actually a file in the other commit.
2404 2405 """
2405 2406
2406 2407 def fail(path, component):
2407 2408 # p1() is the base and we're receiving "writes" for p2()'s
2408 2409 # files.
2409 2410 if b'l' in self.p1()[component].flags():
2410 2411 raise error.Abort(
2411 2412 b"error: %s conflicts with symlink %s "
2412 2413 b"in %d." % (path, component, self.p1().rev())
2413 2414 )
2414 2415 else:
2415 2416 raise error.Abort(
2416 2417 b"error: '%s' conflicts with file '%s' in "
2417 2418 b"%d." % (path, component, self.p1().rev())
2418 2419 )
2419 2420
2420 2421 # Test that each new directory to be created to write this path from p2
2421 2422 # is not a file in p1.
2422 2423 components = path.split(b'/')
2423 2424 for i in range(len(components)):
2424 2425 component = b"/".join(components[0:i])
2425 2426 if component in self:
2426 2427 fail(path, component)
2427 2428
2428 2429 # Test the other direction -- that this path from p2 isn't a directory
2429 2430 # in p1 (test that p1 doesn't have any paths matching `path/*`).
2430 2431 match = self.match([path], default=b'path')
2431 2432 mfiles = list(self.p1().manifest().walk(match))
2432 2433 if len(mfiles) > 0:
2433 2434 if len(mfiles) == 1 and mfiles[0] == path:
2434 2435 return
2435 2436 # omit the files which are deleted in current IMM wctx
2436 2437 mfiles = [m for m in mfiles if m in self]
2437 2438 if not mfiles:
2438 2439 return
2439 2440 raise error.Abort(
2440 2441 b"error: file '%s' cannot be written because "
2441 2442 b" '%s/' is a directory in %s (containing %d "
2442 2443 b"entries: %s)"
2443 2444 % (path, path, self.p1(), len(mfiles), b', '.join(mfiles))
2444 2445 )
2445 2446
2446 2447 def write(self, path, data, flags=b'', **kwargs):
2447 2448 if data is None:
2448 2449 raise error.ProgrammingError(b"data must be non-None")
2449 2450 self._auditconflicts(path)
2450 2451 self._markdirty(
2451 2452 path, exists=True, data=data, date=dateutil.makedate(), flags=flags
2452 2453 )
2453 2454
2454 2455 def setflags(self, path, l, x):
2455 2456 flag = b''
2456 2457 if l:
2457 2458 flag = b'l'
2458 2459 elif x:
2459 2460 flag = b'x'
2460 2461 self._markdirty(path, exists=True, date=dateutil.makedate(), flags=flag)
2461 2462
2462 2463 def remove(self, path):
2463 2464 self._markdirty(path, exists=False)
2464 2465
2465 2466 def exists(self, path):
2466 2467 """exists behaves like `lexists`, but needs to follow symlinks and
2467 2468 return False if they are broken.
2468 2469 """
2469 2470 if self.isdirty(path):
2470 2471 # If this path exists and is a symlink, "follow" it by calling
2471 2472 # exists on the destination path.
2472 2473 if (
2473 2474 self._cache[path][b'exists']
2474 2475 and b'l' in self._cache[path][b'flags']
2475 2476 ):
2476 2477 return self.exists(self._cache[path][b'data'].strip())
2477 2478 else:
2478 2479 return self._cache[path][b'exists']
2479 2480
2480 2481 return self._existsinparent(path)
2481 2482
2482 2483 def lexists(self, path):
2483 2484 """lexists returns True if the path exists"""
2484 2485 if self.isdirty(path):
2485 2486 return self._cache[path][b'exists']
2486 2487
2487 2488 return self._existsinparent(path)
2488 2489
2489 2490 def size(self, path):
2490 2491 if self.isdirty(path):
2491 2492 if self._cache[path][b'exists']:
2492 2493 return len(self._cache[path][b'data'])
2493 2494 else:
2494 2495 raise error.ProgrammingError(
2495 2496 b"No such file or directory: %s" % path
2496 2497 )
2497 2498 return self._wrappedctx[path].size()
2498 2499
2499 2500 def tomemctx(
2500 2501 self,
2501 2502 text,
2502 2503 branch=None,
2503 2504 extra=None,
2504 2505 date=None,
2505 2506 parents=None,
2506 2507 user=None,
2507 2508 editor=None,
2508 2509 ):
2509 2510 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
2510 2511 committed.
2511 2512
2512 2513 ``text`` is the commit message.
2513 2514 ``parents`` (optional) are rev numbers.
2514 2515 """
2515 2516 # Default parents to the wrapped context if not passed.
2516 2517 if parents is None:
2517 2518 parents = self.parents()
2518 2519 if len(parents) == 1:
2519 2520 parents = (parents[0], None)
2520 2521
2521 2522 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
2522 2523 if parents[1] is None:
2523 2524 parents = (self._repo[parents[0]], None)
2524 2525 else:
2525 2526 parents = (self._repo[parents[0]], self._repo[parents[1]])
2526 2527
2527 2528 files = self.files()
2528 2529
2529 2530 def getfile(repo, memctx, path):
2530 2531 if self._cache[path][b'exists']:
2531 2532 return memfilectx(
2532 2533 repo,
2533 2534 memctx,
2534 2535 path,
2535 2536 self._cache[path][b'data'],
2536 2537 b'l' in self._cache[path][b'flags'],
2537 2538 b'x' in self._cache[path][b'flags'],
2538 2539 self._cache[path][b'copied'],
2539 2540 )
2540 2541 else:
2541 2542 # Returning None, but including the path in `files`, is
2542 2543 # necessary for memctx to register a deletion.
2543 2544 return None
2544 2545
2545 2546 if branch is None:
2546 2547 branch = self._wrappedctx.branch()
2547 2548
2548 2549 return memctx(
2549 2550 self._repo,
2550 2551 parents,
2551 2552 text,
2552 2553 files,
2553 2554 getfile,
2554 2555 date=date,
2555 2556 extra=extra,
2556 2557 user=user,
2557 2558 branch=branch,
2558 2559 editor=editor,
2559 2560 )
2560 2561
2561 2562 def tomemctx_for_amend(self, precursor):
2562 2563 extra = precursor.extra().copy()
2563 2564 extra[b'amend_source'] = precursor.hex()
2564 2565 return self.tomemctx(
2565 2566 text=precursor.description(),
2566 2567 branch=precursor.branch(),
2567 2568 extra=extra,
2568 2569 date=precursor.date(),
2569 2570 user=precursor.user(),
2570 2571 )
2571 2572
2572 2573 def isdirty(self, path):
2573 2574 return path in self._cache
2574 2575
2575 2576 def clean(self):
2576 2577 self._mergestate = None
2577 2578 self._cache = {}
2578 2579
2579 2580 def _compact(self):
2580 2581 """Removes keys from the cache that are actually clean, by comparing
2581 2582 them with the underlying context.
2582 2583
2583 2584 This can occur during the merge process, e.g. by passing --tool :local
2584 2585 to resolve a conflict.
2585 2586 """
2586 2587 keys = []
2587 2588 # This won't be perfect, but can help performance significantly when
2588 2589 # using things like remotefilelog.
2589 2590 scmutil.prefetchfiles(
2590 2591 self.repo(),
2591 2592 [
2592 2593 (
2593 2594 self.p1().rev(),
2594 2595 scmutil.matchfiles(self.repo(), self._cache.keys()),
2595 2596 )
2596 2597 ],
2597 2598 )
2598 2599
2599 2600 for path in self._cache.keys():
2600 2601 cache = self._cache[path]
2601 2602 try:
2602 2603 underlying = self._wrappedctx[path]
2603 2604 if (
2604 2605 underlying.data() == cache[b'data']
2605 2606 and underlying.flags() == cache[b'flags']
2606 2607 ):
2607 2608 keys.append(path)
2608 2609 except error.ManifestLookupError:
2609 2610 # Path not in the underlying manifest (created).
2610 2611 continue
2611 2612
2612 2613 for path in keys:
2613 2614 del self._cache[path]
2614 2615 return keys
2615 2616
2616 2617 def _markdirty(
2617 2618 self, path, exists, data=None, date=None, flags=b'', copied=None
2618 2619 ):
2619 2620 # data not provided, let's see if we already have some; if not, let's
2620 2621 # grab it from our underlying context, so that we always have data if
2621 2622 # the file is marked as existing.
2622 2623 if exists and data is None:
2623 2624 oldentry = self._cache.get(path) or {}
2624 2625 data = oldentry.get(b'data')
2625 2626 if data is None:
2626 2627 data = self._wrappedctx[path].data()
2627 2628
2628 2629 self._cache[path] = {
2629 2630 b'exists': exists,
2630 2631 b'data': data,
2631 2632 b'date': date,
2632 2633 b'flags': flags,
2633 2634 b'copied': copied,
2634 2635 }
2635 2636 util.clearcachedproperty(self, b'_manifest')
2636 2637
2637 2638 def filectx(self, path, filelog=None):
2638 2639 return overlayworkingfilectx(
2639 2640 self._repo, path, parent=self, filelog=filelog
2640 2641 )
2641 2642
2642 2643 def mergestate(self, clean=False):
2643 2644 if clean or self._mergestate is None:
2644 2645 self._mergestate = mergestatemod.memmergestate(self._repo)
2645 2646 return self._mergestate
2646 2647
2647 2648
2648 2649 class overlayworkingfilectx(committablefilectx):
2649 2650 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2650 2651 cache, which can be flushed through later by calling ``flush()``."""
2651 2652
2652 2653 def __init__(self, repo, path, filelog=None, parent=None):
2653 2654 super(overlayworkingfilectx, self).__init__(repo, path, filelog, parent)
2654 2655 self._repo = repo
2655 2656 self._parent = parent
2656 2657 self._path = path
2657 2658
2658 2659 def cmp(self, fctx):
2659 2660 return self.data() != fctx.data()
2660 2661
2661 2662 def changectx(self):
2662 2663 return self._parent
2663 2664
2664 2665 def data(self):
2665 2666 return self._parent.data(self._path)
2666 2667
2667 2668 def date(self):
2668 2669 return self._parent.filedate(self._path)
2669 2670
2670 2671 def exists(self):
2671 2672 return self.lexists()
2672 2673
2673 2674 def lexists(self):
2674 2675 return self._parent.exists(self._path)
2675 2676
2676 2677 def copysource(self):
2677 2678 return self._parent.copydata(self._path)
2678 2679
2679 2680 def size(self):
2680 2681 return self._parent.size(self._path)
2681 2682
2682 2683 def markcopied(self, origin):
2683 2684 self._parent.markcopied(self._path, origin)
2684 2685
2685 2686 def audit(self):
2686 2687 pass
2687 2688
2688 2689 def flags(self):
2689 2690 return self._parent.flags(self._path)
2690 2691
2691 2692 def setflags(self, islink, isexec):
2692 2693 return self._parent.setflags(self._path, islink, isexec)
2693 2694
2694 2695 def write(self, data, flags, backgroundclose=False, **kwargs):
2695 2696 return self._parent.write(self._path, data, flags, **kwargs)
2696 2697
2697 2698 def remove(self, ignoremissing=False):
2698 2699 return self._parent.remove(self._path)
2699 2700
2700 2701 def clearunknown(self):
2701 2702 pass
2702 2703
2703 2704
2704 2705 class workingcommitctx(workingctx):
2705 2706 """A workingcommitctx object makes access to data related to
2706 2707 the revision being committed convenient.
2707 2708
2708 2709 This hides changes in the working directory, if they aren't
2709 2710 committed in this context.
2710 2711 """
2711 2712
2712 2713 def __init__(
2713 2714 self, repo, changes, text=b"", user=None, date=None, extra=None
2714 2715 ):
2715 2716 super(workingcommitctx, self).__init__(
2716 2717 repo, text, user, date, extra, changes
2717 2718 )
2718 2719
2719 2720 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2720 2721 """Return matched files only in ``self._status``
2721 2722
2722 2723 Uncommitted files appear "clean" via this context, even if
2723 2724 they aren't actually so in the working directory.
2724 2725 """
2725 2726 if clean:
2726 2727 clean = [f for f in self._manifest if f not in self._changedset]
2727 2728 else:
2728 2729 clean = []
2729 2730 return scmutil.status(
2730 2731 [f for f in self._status.modified if match(f)],
2731 2732 [f for f in self._status.added if match(f)],
2732 2733 [f for f in self._status.removed if match(f)],
2733 2734 [],
2734 2735 [],
2735 2736 [],
2736 2737 clean,
2737 2738 )
2738 2739
2739 2740 @propertycache
2740 2741 def _changedset(self):
2741 2742 """Return the set of files changed in this context"""
2742 2743 changed = set(self._status.modified)
2743 2744 changed.update(self._status.added)
2744 2745 changed.update(self._status.removed)
2745 2746 return changed
2746 2747
2747 2748
2748 2749 def makecachingfilectxfn(func):
2749 2750 """Create a filectxfn that caches based on the path.
2750 2751
2751 2752 We can't use util.cachefunc because it uses all arguments as the cache
2752 2753 key and this creates a cycle since the arguments include the repo and
2753 2754 memctx.
2754 2755 """
2755 2756 cache = {}
2756 2757
2757 2758 def getfilectx(repo, memctx, path):
2758 2759 if path not in cache:
2759 2760 cache[path] = func(repo, memctx, path)
2760 2761 return cache[path]
2761 2762
2762 2763 return getfilectx
2763 2764
2764 2765
2765 2766 def memfilefromctx(ctx):
2766 2767 """Given a context return a memfilectx for ctx[path]
2767 2768
2768 2769 This is a convenience method for building a memctx based on another
2769 2770 context.
2770 2771 """
2771 2772
2772 2773 def getfilectx(repo, memctx, path):
2773 2774 fctx = ctx[path]
2774 2775 copysource = fctx.copysource()
2775 2776 return memfilectx(
2776 2777 repo,
2777 2778 memctx,
2778 2779 path,
2779 2780 fctx.data(),
2780 2781 islink=fctx.islink(),
2781 2782 isexec=fctx.isexec(),
2782 2783 copysource=copysource,
2783 2784 )
2784 2785
2785 2786 return getfilectx
2786 2787
2787 2788
2788 2789 def memfilefrompatch(patchstore):
2789 2790 """Given a patch (e.g. patchstore object) return a memfilectx
2790 2791
2791 2792 This is a convenience method for building a memctx based on a patchstore.
2792 2793 """
2793 2794
2794 2795 def getfilectx(repo, memctx, path):
2795 2796 data, mode, copysource = patchstore.getfile(path)
2796 2797 if data is None:
2797 2798 return None
2798 2799 islink, isexec = mode
2799 2800 return memfilectx(
2800 2801 repo,
2801 2802 memctx,
2802 2803 path,
2803 2804 data,
2804 2805 islink=islink,
2805 2806 isexec=isexec,
2806 2807 copysource=copysource,
2807 2808 )
2808 2809
2809 2810 return getfilectx
2810 2811
2811 2812
2812 2813 class memctx(committablectx):
2813 2814 """Use memctx to perform in-memory commits via localrepo.commitctx().
2814 2815
2815 2816 Revision information is supplied at initialization time while
2816 2817 related files data and is made available through a callback
2817 2818 mechanism. 'repo' is the current localrepo, 'parents' is a
2818 2819 sequence of two parent revisions identifiers (pass None for every
2819 2820 missing parent), 'text' is the commit message and 'files' lists
2820 2821 names of files touched by the revision (normalized and relative to
2821 2822 repository root).
2822 2823
2823 2824 filectxfn(repo, memctx, path) is a callable receiving the
2824 2825 repository, the current memctx object and the normalized path of
2825 2826 requested file, relative to repository root. It is fired by the
2826 2827 commit function for every file in 'files', but calls order is
2827 2828 undefined. If the file is available in the revision being
2828 2829 committed (updated or added), filectxfn returns a memfilectx
2829 2830 object. If the file was removed, filectxfn return None for recent
2830 2831 Mercurial. Moved files are represented by marking the source file
2831 2832 removed and the new file added with copy information (see
2832 2833 memfilectx).
2833 2834
2834 2835 user receives the committer name and defaults to current
2835 2836 repository username, date is the commit date in any format
2836 2837 supported by dateutil.parsedate() and defaults to current date, extra
2837 2838 is a dictionary of metadata or is left empty.
2838 2839 """
2839 2840
2840 2841 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2841 2842 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2842 2843 # this field to determine what to do in filectxfn.
2843 2844 _returnnoneformissingfiles = True
2844 2845
2845 2846 def __init__(
2846 2847 self,
2847 2848 repo,
2848 2849 parents,
2849 2850 text,
2850 2851 files,
2851 2852 filectxfn,
2852 2853 user=None,
2853 2854 date=None,
2854 2855 extra=None,
2855 2856 branch=None,
2856 2857 editor=None,
2857 2858 ):
2858 2859 super(memctx, self).__init__(
2859 2860 repo, text, user, date, extra, branch=branch
2860 2861 )
2861 2862 self._rev = None
2862 2863 self._node = None
2863 2864 parents = [(p or self._repo.nodeconstants.nullid) for p in parents]
2864 2865 p1, p2 = parents
2865 2866 self._parents = [self._repo[p] for p in (p1, p2)]
2866 2867 files = sorted(set(files))
2867 2868 self._files = files
2868 2869 self.substate = {}
2869 2870
2870 2871 if isinstance(filectxfn, patch.filestore):
2871 2872 filectxfn = memfilefrompatch(filectxfn)
2872 2873 elif not callable(filectxfn):
2873 2874 # if store is not callable, wrap it in a function
2874 2875 filectxfn = memfilefromctx(filectxfn)
2875 2876
2876 2877 # memoizing increases performance for e.g. vcs convert scenarios.
2877 2878 self._filectxfn = makecachingfilectxfn(filectxfn)
2878 2879
2879 2880 if editor:
2880 2881 self._text = editor(self._repo, self, [])
2881 2882 self._repo.savecommitmessage(self._text)
2882 2883
2883 2884 def filectx(self, path, filelog=None):
2884 2885 """get a file context from the working directory
2885 2886
2886 2887 Returns None if file doesn't exist and should be removed."""
2887 2888 return self._filectxfn(self._repo, self, path)
2888 2889
2889 2890 def commit(self):
2890 2891 """commit context to the repo"""
2891 2892 return self._repo.commitctx(self)
2892 2893
2893 2894 @propertycache
2894 2895 def _manifest(self):
2895 2896 """generate a manifest based on the return values of filectxfn"""
2896 2897
2897 2898 # keep this simple for now; just worry about p1
2898 2899 pctx = self._parents[0]
2899 2900 man = pctx.manifest().copy()
2900 2901
2901 2902 for f in self._status.modified:
2902 2903 man[f] = self._repo.nodeconstants.modifiednodeid
2903 2904
2904 2905 for f in self._status.added:
2905 2906 man[f] = self._repo.nodeconstants.addednodeid
2906 2907
2907 2908 for f in self._status.removed:
2908 2909 if f in man:
2909 2910 del man[f]
2910 2911
2911 2912 return man
2912 2913
2913 2914 @propertycache
2914 2915 def _status(self):
2915 2916 """Calculate exact status from ``files`` specified at construction"""
2916 2917 man1 = self.p1().manifest()
2917 2918 p2 = self._parents[1]
2918 2919 # "1 < len(self._parents)" can't be used for checking
2919 2920 # existence of the 2nd parent, because "memctx._parents" is
2920 2921 # explicitly initialized by the list, of which length is 2.
2921 2922 if p2.rev() != nullrev:
2922 2923 man2 = p2.manifest()
2923 2924 managing = lambda f: f in man1 or f in man2
2924 2925 else:
2925 2926 managing = lambda f: f in man1
2926 2927
2927 2928 modified, added, removed = [], [], []
2928 2929 for f in self._files:
2929 2930 if not managing(f):
2930 2931 added.append(f)
2931 2932 elif self[f]:
2932 2933 modified.append(f)
2933 2934 else:
2934 2935 removed.append(f)
2935 2936
2936 2937 return scmutil.status(modified, added, removed, [], [], [], [])
2937 2938
2938 2939 def parents(self):
2939 2940 if self._parents[1].rev() == nullrev:
2940 2941 return [self._parents[0]]
2941 2942 return self._parents
2942 2943
2943 2944
2944 2945 class memfilectx(committablefilectx):
2945 2946 """memfilectx represents an in-memory file to commit.
2946 2947
2947 2948 See memctx and committablefilectx for more details.
2948 2949 """
2949 2950
2950 2951 def __init__(
2951 2952 self,
2952 2953 repo,
2953 2954 changectx,
2954 2955 path,
2955 2956 data,
2956 2957 islink=False,
2957 2958 isexec=False,
2958 2959 copysource=None,
2959 2960 ):
2960 2961 """
2961 2962 path is the normalized file path relative to repository root.
2962 2963 data is the file content as a string.
2963 2964 islink is True if the file is a symbolic link.
2964 2965 isexec is True if the file is executable.
2965 2966 copied is the source file path if current file was copied in the
2966 2967 revision being committed, or None."""
2967 2968 super(memfilectx, self).__init__(repo, path, None, changectx)
2968 2969 self._data = data
2969 2970 if islink:
2970 2971 self._flags = b'l'
2971 2972 elif isexec:
2972 2973 self._flags = b'x'
2973 2974 else:
2974 2975 self._flags = b''
2975 2976 self._copysource = copysource
2976 2977
2977 2978 def copysource(self):
2978 2979 return self._copysource
2979 2980
2980 2981 def cmp(self, fctx):
2981 2982 return self.data() != fctx.data()
2982 2983
2983 2984 def data(self):
2984 2985 return self._data
2985 2986
2986 2987 def remove(self, ignoremissing=False):
2987 2988 """wraps unlink for a repo's working directory"""
2988 2989 # need to figure out what to do here
2989 2990 del self._changectx[self._path]
2990 2991
2991 2992 def write(self, data, flags, **kwargs):
2992 2993 """wraps repo.wwrite"""
2993 2994 self._data = data
2994 2995
2995 2996
2996 2997 class metadataonlyctx(committablectx):
2997 2998 """Like memctx but it's reusing the manifest of different commit.
2998 2999 Intended to be used by lightweight operations that are creating
2999 3000 metadata-only changes.
3000 3001
3001 3002 Revision information is supplied at initialization time. 'repo' is the
3002 3003 current localrepo, 'ctx' is original revision which manifest we're reuisng
3003 3004 'parents' is a sequence of two parent revisions identifiers (pass None for
3004 3005 every missing parent), 'text' is the commit.
3005 3006
3006 3007 user receives the committer name and defaults to current repository
3007 3008 username, date is the commit date in any format supported by
3008 3009 dateutil.parsedate() and defaults to current date, extra is a dictionary of
3009 3010 metadata or is left empty.
3010 3011 """
3011 3012
3012 3013 def __init__(
3013 3014 self,
3014 3015 repo,
3015 3016 originalctx,
3016 3017 parents=None,
3017 3018 text=None,
3018 3019 user=None,
3019 3020 date=None,
3020 3021 extra=None,
3021 3022 editor=None,
3022 3023 ):
3023 3024 if text is None:
3024 3025 text = originalctx.description()
3025 3026 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
3026 3027 self._rev = None
3027 3028 self._node = None
3028 3029 self._originalctx = originalctx
3029 3030 self._manifestnode = originalctx.manifestnode()
3030 3031 if parents is None:
3031 3032 parents = originalctx.parents()
3032 3033 else:
3033 3034 parents = [repo[p] for p in parents if p is not None]
3034 3035 parents = parents[:]
3035 3036 while len(parents) < 2:
3036 3037 parents.append(repo[nullrev])
3037 3038 p1, p2 = self._parents = parents
3038 3039
3039 3040 # sanity check to ensure that the reused manifest parents are
3040 3041 # manifests of our commit parents
3041 3042 mp1, mp2 = self.manifestctx().parents
3042 3043 if p1 != self._repo.nodeconstants.nullid and p1.manifestnode() != mp1:
3043 3044 raise RuntimeError(
3044 3045 r"can't reuse the manifest: its p1 "
3045 3046 r"doesn't match the new ctx p1"
3046 3047 )
3047 3048 if p2 != self._repo.nodeconstants.nullid and p2.manifestnode() != mp2:
3048 3049 raise RuntimeError(
3049 3050 r"can't reuse the manifest: "
3050 3051 r"its p2 doesn't match the new ctx p2"
3051 3052 )
3052 3053
3053 3054 self._files = originalctx.files()
3054 3055 self.substate = {}
3055 3056
3056 3057 if editor:
3057 3058 self._text = editor(self._repo, self, [])
3058 3059 self._repo.savecommitmessage(self._text)
3059 3060
3060 3061 def manifestnode(self):
3061 3062 return self._manifestnode
3062 3063
3063 3064 @property
3064 3065 def _manifestctx(self):
3065 3066 return self._repo.manifestlog[self._manifestnode]
3066 3067
3067 3068 def filectx(self, path, filelog=None):
3068 3069 return self._originalctx.filectx(path, filelog=filelog)
3069 3070
3070 3071 def commit(self):
3071 3072 """commit context to the repo"""
3072 3073 return self._repo.commitctx(self)
3073 3074
3074 3075 @property
3075 3076 def _manifest(self):
3076 3077 return self._originalctx.manifest()
3077 3078
3078 3079 @propertycache
3079 3080 def _status(self):
3080 3081 """Calculate exact status from ``files`` specified in the ``origctx``
3081 3082 and parents manifests.
3082 3083 """
3083 3084 man1 = self.p1().manifest()
3084 3085 p2 = self._parents[1]
3085 3086 # "1 < len(self._parents)" can't be used for checking
3086 3087 # existence of the 2nd parent, because "metadataonlyctx._parents" is
3087 3088 # explicitly initialized by the list, of which length is 2.
3088 3089 if p2.rev() != nullrev:
3089 3090 man2 = p2.manifest()
3090 3091 managing = lambda f: f in man1 or f in man2
3091 3092 else:
3092 3093 managing = lambda f: f in man1
3093 3094
3094 3095 modified, added, removed = [], [], []
3095 3096 for f in self._files:
3096 3097 if not managing(f):
3097 3098 added.append(f)
3098 3099 elif f in self:
3099 3100 modified.append(f)
3100 3101 else:
3101 3102 removed.append(f)
3102 3103
3103 3104 return scmutil.status(modified, added, removed, [], [], [], [])
3104 3105
3105 3106
3106 3107 class arbitraryfilectx:
3107 3108 """Allows you to use filectx-like functions on a file in an arbitrary
3108 3109 location on disk, possibly not in the working directory.
3109 3110 """
3110 3111
3111 3112 def __init__(self, path, repo=None):
3112 3113 # Repo is optional because contrib/simplemerge uses this class.
3113 3114 self._repo = repo
3114 3115 self._path = path
3115 3116
3116 3117 def cmp(self, fctx):
3117 3118 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
3118 3119 # path if either side is a symlink.
3119 3120 symlinks = b'l' in self.flags() or b'l' in fctx.flags()
3120 3121 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
3121 3122 # Add a fast-path for merge if both sides are disk-backed.
3122 3123 # Note that filecmp uses the opposite return values (True if same)
3123 3124 # from our cmp functions (True if different).
3124 3125 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
3125 3126 return self.data() != fctx.data()
3126 3127
3127 3128 def path(self):
3128 3129 return self._path
3129 3130
3130 3131 def flags(self):
3131 3132 return b''
3132 3133
3133 3134 def data(self):
3134 3135 return util.readfile(self._path)
3135 3136
3136 3137 def decodeddata(self):
3137 3138 return util.readfile(self._path)
3138 3139
3139 3140 def remove(self):
3140 3141 util.unlink(self._path)
3141 3142
3142 3143 def write(self, data, flags, **kwargs):
3143 3144 assert not flags
3144 3145 util.writefile(self._path, data)
General Comments 0
You need to be logged in to leave comments. Login now