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