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