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