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