##// END OF EJS Templates
context: split `introrev` logic in a sub function...
Boris Feld -
r40731:9fa0d6dd default
parent child Browse files
Show More
@@ -1,2453 +1,2456 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 705 if (fctx._filenode is None
706 706 and (self._repo._encodefilterpats
707 707 # if file data starts with '\1\n', empty metadata block is
708 708 # prepended, which adds 4 bytes to filelog.size().
709 709 or self.size() - 4 == fctx.size())
710 710 or self.size() == fctx.size()):
711 711 return self._filelog.cmp(self._filenode, fctx.data())
712 712
713 713 return True
714 714
715 715 def _adjustlinkrev(self, srcrev, inclusive=False):
716 716 """return the first ancestor of <srcrev> introducing <fnode>
717 717
718 718 If the linkrev of the file revision does not point to an ancestor of
719 719 srcrev, we'll walk down the ancestors until we find one introducing
720 720 this file revision.
721 721
722 722 :srcrev: the changeset revision we search ancestors from
723 723 :inclusive: if true, the src revision will also be checked
724 724 """
725 725 repo = self._repo
726 726 cl = repo.unfiltered().changelog
727 727 mfl = repo.manifestlog
728 728 # fetch the linkrev
729 729 lkr = self.linkrev()
730 730 if srcrev == lkr:
731 731 return lkr
732 732 # hack to reuse ancestor computation when searching for renames
733 733 memberanc = getattr(self, '_ancestrycontext', None)
734 734 iteranc = None
735 735 if srcrev is None:
736 736 # wctx case, used by workingfilectx during mergecopy
737 737 revs = [p.rev() for p in self._repo[None].parents()]
738 738 inclusive = True # we skipped the real (revless) source
739 739 else:
740 740 revs = [srcrev]
741 741 if memberanc is None:
742 742 memberanc = iteranc = cl.ancestors(revs, lkr,
743 743 inclusive=inclusive)
744 744 # check if this linkrev is an ancestor of srcrev
745 745 if lkr not in memberanc:
746 746 if iteranc is None:
747 747 iteranc = cl.ancestors(revs, lkr, inclusive=inclusive)
748 748 fnode = self._filenode
749 749 path = self._path
750 750 for a in iteranc:
751 751 ac = cl.read(a) # get changeset data (we avoid object creation)
752 752 if path in ac[3]: # checking the 'files' field.
753 753 # The file has been touched, check if the content is
754 754 # similar to the one we search for.
755 755 if fnode == mfl[ac[0]].readfast().get(path):
756 756 return a
757 757 # In theory, we should never get out of that loop without a result.
758 758 # But if manifest uses a buggy file revision (not children of the
759 759 # one it replaces) we could. Such a buggy situation will likely
760 760 # result is crash somewhere else at to some point.
761 761 return lkr
762 762
763 763 def isintroducedafter(self, changelogrev):
764 764 """True if a filectx has been introduced after a given floor revision
765 765 """
766 766 return (self.linkrev() >= changelogrev
767 or self.introrev() >= changelogrev)
767 or self._introrev() >= changelogrev)
768 768
769 769 def introrev(self):
770 770 """return the rev of the changeset which introduced this file revision
771 771
772 772 This method is different from linkrev because it take into account the
773 773 changeset the filectx was created from. It ensures the returned
774 774 revision is one of its ancestors. This prevents bugs from
775 775 'linkrev-shadowing' when a file revision is used by multiple
776 776 changesets.
777 777 """
778 return self._introrev()
779
780 def _introrev(self):
778 781 toprev = None
779 782 attrs = vars(self)
780 783 if r'_changeid' in attrs:
781 784 # We have a cached value already
782 785 toprev = self._changeid
783 786 elif r'_changectx' in attrs:
784 787 # We know which changelog entry we are coming from
785 788 toprev = self._changectx.rev()
786 789
787 790 if toprev is not None:
788 791 return self._adjustlinkrev(toprev, inclusive=True)
789 792 elif r'_descendantrev' in attrs:
790 793 introrev = self._adjustlinkrev(self._descendantrev)
791 794 # be nice and cache the result of the computation
792 795 self._changeid = introrev
793 796 return introrev
794 797 else:
795 798 return self.linkrev()
796 799
797 800 def introfilectx(self):
798 801 """Return filectx having identical contents, but pointing to the
799 802 changeset revision where this filectx was introduced"""
800 803 introrev = self.introrev()
801 804 if self.rev() == introrev:
802 805 return self
803 806 return self.filectx(self.filenode(), changeid=introrev)
804 807
805 808 def _parentfilectx(self, path, fileid, filelog):
806 809 """create parent filectx keeping ancestry info for _adjustlinkrev()"""
807 810 fctx = filectx(self._repo, path, fileid=fileid, filelog=filelog)
808 811 if r'_changeid' in vars(self) or r'_changectx' in vars(self):
809 812 # If self is associated with a changeset (probably explicitly
810 813 # fed), ensure the created filectx is associated with a
811 814 # changeset that is an ancestor of self.changectx.
812 815 # This lets us later use _adjustlinkrev to get a correct link.
813 816 fctx._descendantrev = self.rev()
814 817 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
815 818 elif r'_descendantrev' in vars(self):
816 819 # Otherwise propagate _descendantrev if we have one associated.
817 820 fctx._descendantrev = self._descendantrev
818 821 fctx._ancestrycontext = getattr(self, '_ancestrycontext', None)
819 822 return fctx
820 823
821 824 def parents(self):
822 825 _path = self._path
823 826 fl = self._filelog
824 827 parents = self._filelog.parents(self._filenode)
825 828 pl = [(_path, node, fl) for node in parents if node != nullid]
826 829
827 830 r = fl.renamed(self._filenode)
828 831 if r:
829 832 # - In the simple rename case, both parent are nullid, pl is empty.
830 833 # - In case of merge, only one of the parent is null id and should
831 834 # be replaced with the rename information. This parent is -always-
832 835 # the first one.
833 836 #
834 837 # As null id have always been filtered out in the previous list
835 838 # comprehension, inserting to 0 will always result in "replacing
836 839 # first nullid parent with rename information.
837 840 pl.insert(0, (r[0], r[1], self._repo.file(r[0])))
838 841
839 842 return [self._parentfilectx(path, fnode, l) for path, fnode, l in pl]
840 843
841 844 def p1(self):
842 845 return self.parents()[0]
843 846
844 847 def p2(self):
845 848 p = self.parents()
846 849 if len(p) == 2:
847 850 return p[1]
848 851 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
849 852
850 853 def annotate(self, follow=False, skiprevs=None, diffopts=None):
851 854 """Returns a list of annotateline objects for each line in the file
852 855
853 856 - line.fctx is the filectx of the node where that line was last changed
854 857 - line.lineno is the line number at the first appearance in the managed
855 858 file
856 859 - line.text is the data on that line (including newline character)
857 860 """
858 861 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
859 862
860 863 def parents(f):
861 864 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
862 865 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
863 866 # from the topmost introrev (= srcrev) down to p.linkrev() if it
864 867 # isn't an ancestor of the srcrev.
865 868 f._changeid
866 869 pl = f.parents()
867 870
868 871 # Don't return renamed parents if we aren't following.
869 872 if not follow:
870 873 pl = [p for p in pl if p.path() == f.path()]
871 874
872 875 # renamed filectx won't have a filelog yet, so set it
873 876 # from the cache to save time
874 877 for p in pl:
875 878 if not r'_filelog' in p.__dict__:
876 879 p._filelog = getlog(p.path())
877 880
878 881 return pl
879 882
880 883 # use linkrev to find the first changeset where self appeared
881 884 base = self.introfilectx()
882 885 if getattr(base, '_ancestrycontext', None) is None:
883 886 cl = self._repo.changelog
884 887 if base.rev() is None:
885 888 # wctx is not inclusive, but works because _ancestrycontext
886 889 # is used to test filelog revisions
887 890 ac = cl.ancestors([p.rev() for p in base.parents()],
888 891 inclusive=True)
889 892 else:
890 893 ac = cl.ancestors([base.rev()], inclusive=True)
891 894 base._ancestrycontext = ac
892 895
893 896 return dagop.annotate(base, parents, skiprevs=skiprevs,
894 897 diffopts=diffopts)
895 898
896 899 def ancestors(self, followfirst=False):
897 900 visit = {}
898 901 c = self
899 902 if followfirst:
900 903 cut = 1
901 904 else:
902 905 cut = None
903 906
904 907 while True:
905 908 for parent in c.parents()[:cut]:
906 909 visit[(parent.linkrev(), parent.filenode())] = parent
907 910 if not visit:
908 911 break
909 912 c = visit.pop(max(visit))
910 913 yield c
911 914
912 915 def decodeddata(self):
913 916 """Returns `data()` after running repository decoding filters.
914 917
915 918 This is often equivalent to how the data would be expressed on disk.
916 919 """
917 920 return self._repo.wwritedata(self.path(), self.data())
918 921
919 922 class filectx(basefilectx):
920 923 """A filecontext object makes access to data related to a particular
921 924 filerevision convenient."""
922 925 def __init__(self, repo, path, changeid=None, fileid=None,
923 926 filelog=None, changectx=None):
924 927 """changeid must be a revision number, if specified.
925 928 fileid can be a file revision or node."""
926 929 self._repo = repo
927 930 self._path = path
928 931
929 932 assert (changeid is not None
930 933 or fileid is not None
931 934 or changectx is not None), \
932 935 ("bad args: changeid=%r, fileid=%r, changectx=%r"
933 936 % (changeid, fileid, changectx))
934 937
935 938 if filelog is not None:
936 939 self._filelog = filelog
937 940
938 941 if changeid is not None:
939 942 self._changeid = changeid
940 943 if changectx is not None:
941 944 self._changectx = changectx
942 945 if fileid is not None:
943 946 self._fileid = fileid
944 947
945 948 @propertycache
946 949 def _changectx(self):
947 950 try:
948 951 return self._repo[self._changeid]
949 952 except error.FilteredRepoLookupError:
950 953 # Linkrev may point to any revision in the repository. When the
951 954 # repository is filtered this may lead to `filectx` trying to build
952 955 # `changectx` for filtered revision. In such case we fallback to
953 956 # creating `changectx` on the unfiltered version of the reposition.
954 957 # This fallback should not be an issue because `changectx` from
955 958 # `filectx` are not used in complex operations that care about
956 959 # filtering.
957 960 #
958 961 # This fallback is a cheap and dirty fix that prevent several
959 962 # crashes. It does not ensure the behavior is correct. However the
960 963 # behavior was not correct before filtering either and "incorrect
961 964 # behavior" is seen as better as "crash"
962 965 #
963 966 # Linkrevs have several serious troubles with filtering that are
964 967 # complicated to solve. Proper handling of the issue here should be
965 968 # considered when solving linkrev issue are on the table.
966 969 return self._repo.unfiltered()[self._changeid]
967 970
968 971 def filectx(self, fileid, changeid=None):
969 972 '''opens an arbitrary revision of the file without
970 973 opening a new filelog'''
971 974 return filectx(self._repo, self._path, fileid=fileid,
972 975 filelog=self._filelog, changeid=changeid)
973 976
974 977 def rawdata(self):
975 978 return self._filelog.revision(self._filenode, raw=True)
976 979
977 980 def rawflags(self):
978 981 """low-level revlog flags"""
979 982 return self._filelog.flags(self._filerev)
980 983
981 984 def data(self):
982 985 try:
983 986 return self._filelog.read(self._filenode)
984 987 except error.CensoredNodeError:
985 988 if self._repo.ui.config("censor", "policy") == "ignore":
986 989 return ""
987 990 raise error.Abort(_("censored node: %s") % short(self._filenode),
988 991 hint=_("set censor.policy to ignore errors"))
989 992
990 993 def size(self):
991 994 return self._filelog.size(self._filerev)
992 995
993 996 @propertycache
994 997 def _copied(self):
995 998 """check if file was actually renamed in this changeset revision
996 999
997 1000 If rename logged in file revision, we report copy for changeset only
998 1001 if file revisions linkrev points back to the changeset in question
999 1002 or both changeset parents contain different file revisions.
1000 1003 """
1001 1004
1002 1005 renamed = self._filelog.renamed(self._filenode)
1003 1006 if not renamed:
1004 1007 return None
1005 1008
1006 1009 if self.rev() == self.linkrev():
1007 1010 return renamed
1008 1011
1009 1012 name = self.path()
1010 1013 fnode = self._filenode
1011 1014 for p in self._changectx.parents():
1012 1015 try:
1013 1016 if fnode == p.filenode(name):
1014 1017 return None
1015 1018 except error.LookupError:
1016 1019 pass
1017 1020 return renamed
1018 1021
1019 1022 def children(self):
1020 1023 # hard for renames
1021 1024 c = self._filelog.children(self._filenode)
1022 1025 return [filectx(self._repo, self._path, fileid=x,
1023 1026 filelog=self._filelog) for x in c]
1024 1027
1025 1028 class committablectx(basectx):
1026 1029 """A committablectx object provides common functionality for a context that
1027 1030 wants the ability to commit, e.g. workingctx or memctx."""
1028 1031 def __init__(self, repo, text="", user=None, date=None, extra=None,
1029 1032 changes=None):
1030 1033 super(committablectx, self).__init__(repo)
1031 1034 self._rev = None
1032 1035 self._node = None
1033 1036 self._text = text
1034 1037 if date:
1035 1038 self._date = dateutil.parsedate(date)
1036 1039 if user:
1037 1040 self._user = user
1038 1041 if changes:
1039 1042 self._status = changes
1040 1043
1041 1044 self._extra = {}
1042 1045 if extra:
1043 1046 self._extra = extra.copy()
1044 1047 if 'branch' not in self._extra:
1045 1048 try:
1046 1049 branch = encoding.fromlocal(self._repo.dirstate.branch())
1047 1050 except UnicodeDecodeError:
1048 1051 raise error.Abort(_('branch name not in UTF-8!'))
1049 1052 self._extra['branch'] = branch
1050 1053 if self._extra['branch'] == '':
1051 1054 self._extra['branch'] = 'default'
1052 1055
1053 1056 def __bytes__(self):
1054 1057 return bytes(self._parents[0]) + "+"
1055 1058
1056 1059 __str__ = encoding.strmethod(__bytes__)
1057 1060
1058 1061 def __nonzero__(self):
1059 1062 return True
1060 1063
1061 1064 __bool__ = __nonzero__
1062 1065
1063 1066 def _buildflagfunc(self):
1064 1067 # Create a fallback function for getting file flags when the
1065 1068 # filesystem doesn't support them
1066 1069
1067 1070 copiesget = self._repo.dirstate.copies().get
1068 1071 parents = self.parents()
1069 1072 if len(parents) < 2:
1070 1073 # when we have one parent, it's easy: copy from parent
1071 1074 man = parents[0].manifest()
1072 1075 def func(f):
1073 1076 f = copiesget(f, f)
1074 1077 return man.flags(f)
1075 1078 else:
1076 1079 # merges are tricky: we try to reconstruct the unstored
1077 1080 # result from the merge (issue1802)
1078 1081 p1, p2 = parents
1079 1082 pa = p1.ancestor(p2)
1080 1083 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1081 1084
1082 1085 def func(f):
1083 1086 f = copiesget(f, f) # may be wrong for merges with copies
1084 1087 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1085 1088 if fl1 == fl2:
1086 1089 return fl1
1087 1090 if fl1 == fla:
1088 1091 return fl2
1089 1092 if fl2 == fla:
1090 1093 return fl1
1091 1094 return '' # punt for conflicts
1092 1095
1093 1096 return func
1094 1097
1095 1098 @propertycache
1096 1099 def _flagfunc(self):
1097 1100 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1098 1101
1099 1102 @propertycache
1100 1103 def _status(self):
1101 1104 return self._repo.status()
1102 1105
1103 1106 @propertycache
1104 1107 def _user(self):
1105 1108 return self._repo.ui.username()
1106 1109
1107 1110 @propertycache
1108 1111 def _date(self):
1109 1112 ui = self._repo.ui
1110 1113 date = ui.configdate('devel', 'default-date')
1111 1114 if date is None:
1112 1115 date = dateutil.makedate()
1113 1116 return date
1114 1117
1115 1118 def subrev(self, subpath):
1116 1119 return None
1117 1120
1118 1121 def manifestnode(self):
1119 1122 return None
1120 1123 def user(self):
1121 1124 return self._user or self._repo.ui.username()
1122 1125 def date(self):
1123 1126 return self._date
1124 1127 def description(self):
1125 1128 return self._text
1126 1129 def files(self):
1127 1130 return sorted(self._status.modified + self._status.added +
1128 1131 self._status.removed)
1129 1132
1130 1133 def modified(self):
1131 1134 return self._status.modified
1132 1135 def added(self):
1133 1136 return self._status.added
1134 1137 def removed(self):
1135 1138 return self._status.removed
1136 1139 def deleted(self):
1137 1140 return self._status.deleted
1138 1141 def branch(self):
1139 1142 return encoding.tolocal(self._extra['branch'])
1140 1143 def closesbranch(self):
1141 1144 return 'close' in self._extra
1142 1145 def extra(self):
1143 1146 return self._extra
1144 1147
1145 1148 def isinmemory(self):
1146 1149 return False
1147 1150
1148 1151 def tags(self):
1149 1152 return []
1150 1153
1151 1154 def bookmarks(self):
1152 1155 b = []
1153 1156 for p in self.parents():
1154 1157 b.extend(p.bookmarks())
1155 1158 return b
1156 1159
1157 1160 def phase(self):
1158 1161 phase = phases.draft # default phase to draft
1159 1162 for p in self.parents():
1160 1163 phase = max(phase, p.phase())
1161 1164 return phase
1162 1165
1163 1166 def hidden(self):
1164 1167 return False
1165 1168
1166 1169 def children(self):
1167 1170 return []
1168 1171
1169 1172 def flags(self, path):
1170 1173 if r'_manifest' in self.__dict__:
1171 1174 try:
1172 1175 return self._manifest.flags(path)
1173 1176 except KeyError:
1174 1177 return ''
1175 1178
1176 1179 try:
1177 1180 return self._flagfunc(path)
1178 1181 except OSError:
1179 1182 return ''
1180 1183
1181 1184 def ancestor(self, c2):
1182 1185 """return the "best" ancestor context of self and c2"""
1183 1186 return self._parents[0].ancestor(c2) # punt on two parents for now
1184 1187
1185 1188 def walk(self, match):
1186 1189 '''Generates matching file names.'''
1187 1190 return sorted(self._repo.dirstate.walk(self._repo.narrowmatch(match),
1188 1191 subrepos=sorted(self.substate),
1189 1192 unknown=True, ignored=False))
1190 1193
1191 1194 def matches(self, match):
1192 1195 match = self._repo.narrowmatch(match)
1193 1196 ds = self._repo.dirstate
1194 1197 return sorted(f for f in ds.matches(match) if ds[f] != 'r')
1195 1198
1196 1199 def ancestors(self):
1197 1200 for p in self._parents:
1198 1201 yield p
1199 1202 for a in self._repo.changelog.ancestors(
1200 1203 [p.rev() for p in self._parents]):
1201 1204 yield self._repo[a]
1202 1205
1203 1206 def markcommitted(self, node):
1204 1207 """Perform post-commit cleanup necessary after committing this ctx
1205 1208
1206 1209 Specifically, this updates backing stores this working context
1207 1210 wraps to reflect the fact that the changes reflected by this
1208 1211 workingctx have been committed. For example, it marks
1209 1212 modified and added files as normal in the dirstate.
1210 1213
1211 1214 """
1212 1215
1213 1216 with self._repo.dirstate.parentchange():
1214 1217 for f in self.modified() + self.added():
1215 1218 self._repo.dirstate.normal(f)
1216 1219 for f in self.removed():
1217 1220 self._repo.dirstate.drop(f)
1218 1221 self._repo.dirstate.setparents(node)
1219 1222
1220 1223 # write changes out explicitly, because nesting wlock at
1221 1224 # runtime may prevent 'wlock.release()' in 'repo.commit()'
1222 1225 # from immediately doing so for subsequent changing files
1223 1226 self._repo.dirstate.write(self._repo.currenttransaction())
1224 1227
1225 1228 def dirty(self, missing=False, merge=True, branch=True):
1226 1229 return False
1227 1230
1228 1231 class workingctx(committablectx):
1229 1232 """A workingctx object makes access to data related to
1230 1233 the current working directory convenient.
1231 1234 date - any valid date string or (unixtime, offset), or None.
1232 1235 user - username string, or None.
1233 1236 extra - a dictionary of extra values, or None.
1234 1237 changes - a list of file lists as returned by localrepo.status()
1235 1238 or None to use the repository status.
1236 1239 """
1237 1240 def __init__(self, repo, text="", user=None, date=None, extra=None,
1238 1241 changes=None):
1239 1242 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1240 1243
1241 1244 def __iter__(self):
1242 1245 d = self._repo.dirstate
1243 1246 for f in d:
1244 1247 if d[f] != 'r':
1245 1248 yield f
1246 1249
1247 1250 def __contains__(self, key):
1248 1251 return self._repo.dirstate[key] not in "?r"
1249 1252
1250 1253 def hex(self):
1251 1254 return hex(wdirid)
1252 1255
1253 1256 @propertycache
1254 1257 def _parents(self):
1255 1258 p = self._repo.dirstate.parents()
1256 1259 if p[1] == nullid:
1257 1260 p = p[:-1]
1258 1261 # use unfiltered repo to delay/avoid loading obsmarkers
1259 1262 unfi = self._repo.unfiltered()
1260 1263 return [changectx(self._repo, unfi.changelog.rev(n), n) for n in p]
1261 1264
1262 1265 def _fileinfo(self, path):
1263 1266 # populate __dict__['_manifest'] as workingctx has no _manifestdelta
1264 1267 self._manifest
1265 1268 return super(workingctx, self)._fileinfo(path)
1266 1269
1267 1270 def filectx(self, path, filelog=None):
1268 1271 """get a file context from the working directory"""
1269 1272 return workingfilectx(self._repo, path, workingctx=self,
1270 1273 filelog=filelog)
1271 1274
1272 1275 def dirty(self, missing=False, merge=True, branch=True):
1273 1276 "check whether a working directory is modified"
1274 1277 # check subrepos first
1275 1278 for s in sorted(self.substate):
1276 1279 if self.sub(s).dirty(missing=missing):
1277 1280 return True
1278 1281 # check current working dir
1279 1282 return ((merge and self.p2()) or
1280 1283 (branch and self.branch() != self.p1().branch()) or
1281 1284 self.modified() or self.added() or self.removed() or
1282 1285 (missing and self.deleted()))
1283 1286
1284 1287 def add(self, list, prefix=""):
1285 1288 with self._repo.wlock():
1286 1289 ui, ds = self._repo.ui, self._repo.dirstate
1287 1290 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1288 1291 rejected = []
1289 1292 lstat = self._repo.wvfs.lstat
1290 1293 for f in list:
1291 1294 # ds.pathto() returns an absolute file when this is invoked from
1292 1295 # the keyword extension. That gets flagged as non-portable on
1293 1296 # Windows, since it contains the drive letter and colon.
1294 1297 scmutil.checkportable(ui, os.path.join(prefix, f))
1295 1298 try:
1296 1299 st = lstat(f)
1297 1300 except OSError:
1298 1301 ui.warn(_("%s does not exist!\n") % uipath(f))
1299 1302 rejected.append(f)
1300 1303 continue
1301 1304 limit = ui.configbytes('ui', 'large-file-limit')
1302 1305 if limit != 0 and st.st_size > limit:
1303 1306 ui.warn(_("%s: up to %d MB of RAM may be required "
1304 1307 "to manage this file\n"
1305 1308 "(use 'hg revert %s' to cancel the "
1306 1309 "pending addition)\n")
1307 1310 % (f, 3 * st.st_size // 1000000, uipath(f)))
1308 1311 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1309 1312 ui.warn(_("%s not added: only files and symlinks "
1310 1313 "supported currently\n") % uipath(f))
1311 1314 rejected.append(f)
1312 1315 elif ds[f] in 'amn':
1313 1316 ui.warn(_("%s already tracked!\n") % uipath(f))
1314 1317 elif ds[f] == 'r':
1315 1318 ds.normallookup(f)
1316 1319 else:
1317 1320 ds.add(f)
1318 1321 return rejected
1319 1322
1320 1323 def forget(self, files, prefix=""):
1321 1324 with self._repo.wlock():
1322 1325 ds = self._repo.dirstate
1323 1326 uipath = lambda f: ds.pathto(pathutil.join(prefix, f))
1324 1327 rejected = []
1325 1328 for f in files:
1326 1329 if f not in self._repo.dirstate:
1327 1330 self._repo.ui.warn(_("%s not tracked!\n") % uipath(f))
1328 1331 rejected.append(f)
1329 1332 elif self._repo.dirstate[f] != 'a':
1330 1333 self._repo.dirstate.remove(f)
1331 1334 else:
1332 1335 self._repo.dirstate.drop(f)
1333 1336 return rejected
1334 1337
1335 1338 def undelete(self, list):
1336 1339 pctxs = self.parents()
1337 1340 with self._repo.wlock():
1338 1341 ds = self._repo.dirstate
1339 1342 for f in list:
1340 1343 if self._repo.dirstate[f] != 'r':
1341 1344 self._repo.ui.warn(_("%s not removed!\n") % ds.pathto(f))
1342 1345 else:
1343 1346 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1344 1347 t = fctx.data()
1345 1348 self._repo.wwrite(f, t, fctx.flags())
1346 1349 self._repo.dirstate.normal(f)
1347 1350
1348 1351 def copy(self, source, dest):
1349 1352 try:
1350 1353 st = self._repo.wvfs.lstat(dest)
1351 1354 except OSError as err:
1352 1355 if err.errno != errno.ENOENT:
1353 1356 raise
1354 1357 self._repo.ui.warn(_("%s does not exist!\n")
1355 1358 % self._repo.dirstate.pathto(dest))
1356 1359 return
1357 1360 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1358 1361 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1359 1362 "symbolic link\n")
1360 1363 % self._repo.dirstate.pathto(dest))
1361 1364 else:
1362 1365 with self._repo.wlock():
1363 1366 if self._repo.dirstate[dest] in '?':
1364 1367 self._repo.dirstate.add(dest)
1365 1368 elif self._repo.dirstate[dest] in 'r':
1366 1369 self._repo.dirstate.normallookup(dest)
1367 1370 self._repo.dirstate.copy(source, dest)
1368 1371
1369 1372 def match(self, pats=None, include=None, exclude=None, default='glob',
1370 1373 listsubrepos=False, badfn=None):
1371 1374 r = self._repo
1372 1375
1373 1376 # Only a case insensitive filesystem needs magic to translate user input
1374 1377 # to actual case in the filesystem.
1375 1378 icasefs = not util.fscasesensitive(r.root)
1376 1379 return matchmod.match(r.root, r.getcwd(), pats, include, exclude,
1377 1380 default, auditor=r.auditor, ctx=self,
1378 1381 listsubrepos=listsubrepos, badfn=badfn,
1379 1382 icasefs=icasefs)
1380 1383
1381 1384 def _filtersuspectsymlink(self, files):
1382 1385 if not files or self._repo.dirstate._checklink:
1383 1386 return files
1384 1387
1385 1388 # Symlink placeholders may get non-symlink-like contents
1386 1389 # via user error or dereferencing by NFS or Samba servers,
1387 1390 # so we filter out any placeholders that don't look like a
1388 1391 # symlink
1389 1392 sane = []
1390 1393 for f in files:
1391 1394 if self.flags(f) == 'l':
1392 1395 d = self[f].data()
1393 1396 if (d == '' or len(d) >= 1024 or '\n' in d
1394 1397 or stringutil.binary(d)):
1395 1398 self._repo.ui.debug('ignoring suspect symlink placeholder'
1396 1399 ' "%s"\n' % f)
1397 1400 continue
1398 1401 sane.append(f)
1399 1402 return sane
1400 1403
1401 1404 def _checklookup(self, files):
1402 1405 # check for any possibly clean files
1403 1406 if not files:
1404 1407 return [], [], []
1405 1408
1406 1409 modified = []
1407 1410 deleted = []
1408 1411 fixup = []
1409 1412 pctx = self._parents[0]
1410 1413 # do a full compare of any files that might have changed
1411 1414 for f in sorted(files):
1412 1415 try:
1413 1416 # This will return True for a file that got replaced by a
1414 1417 # directory in the interim, but fixing that is pretty hard.
1415 1418 if (f not in pctx or self.flags(f) != pctx.flags(f)
1416 1419 or pctx[f].cmp(self[f])):
1417 1420 modified.append(f)
1418 1421 else:
1419 1422 fixup.append(f)
1420 1423 except (IOError, OSError):
1421 1424 # A file become inaccessible in between? Mark it as deleted,
1422 1425 # matching dirstate behavior (issue5584).
1423 1426 # The dirstate has more complex behavior around whether a
1424 1427 # missing file matches a directory, etc, but we don't need to
1425 1428 # bother with that: if f has made it to this point, we're sure
1426 1429 # it's in the dirstate.
1427 1430 deleted.append(f)
1428 1431
1429 1432 return modified, deleted, fixup
1430 1433
1431 1434 def _poststatusfixup(self, status, fixup):
1432 1435 """update dirstate for files that are actually clean"""
1433 1436 poststatus = self._repo.postdsstatus()
1434 1437 if fixup or poststatus:
1435 1438 try:
1436 1439 oldid = self._repo.dirstate.identity()
1437 1440
1438 1441 # updating the dirstate is optional
1439 1442 # so we don't wait on the lock
1440 1443 # wlock can invalidate the dirstate, so cache normal _after_
1441 1444 # taking the lock
1442 1445 with self._repo.wlock(False):
1443 1446 if self._repo.dirstate.identity() == oldid:
1444 1447 if fixup:
1445 1448 normal = self._repo.dirstate.normal
1446 1449 for f in fixup:
1447 1450 normal(f)
1448 1451 # write changes out explicitly, because nesting
1449 1452 # wlock at runtime may prevent 'wlock.release()'
1450 1453 # after this block from doing so for subsequent
1451 1454 # changing files
1452 1455 tr = self._repo.currenttransaction()
1453 1456 self._repo.dirstate.write(tr)
1454 1457
1455 1458 if poststatus:
1456 1459 for ps in poststatus:
1457 1460 ps(self, status)
1458 1461 else:
1459 1462 # in this case, writing changes out breaks
1460 1463 # consistency, because .hg/dirstate was
1461 1464 # already changed simultaneously after last
1462 1465 # caching (see also issue5584 for detail)
1463 1466 self._repo.ui.debug('skip updating dirstate: '
1464 1467 'identity mismatch\n')
1465 1468 except error.LockError:
1466 1469 pass
1467 1470 finally:
1468 1471 # Even if the wlock couldn't be grabbed, clear out the list.
1469 1472 self._repo.clearpostdsstatus()
1470 1473
1471 1474 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
1472 1475 '''Gets the status from the dirstate -- internal use only.'''
1473 1476 subrepos = []
1474 1477 if '.hgsub' in self:
1475 1478 subrepos = sorted(self.substate)
1476 1479 cmp, s = self._repo.dirstate.status(match, subrepos, ignored=ignored,
1477 1480 clean=clean, unknown=unknown)
1478 1481
1479 1482 # check for any possibly clean files
1480 1483 fixup = []
1481 1484 if cmp:
1482 1485 modified2, deleted2, fixup = self._checklookup(cmp)
1483 1486 s.modified.extend(modified2)
1484 1487 s.deleted.extend(deleted2)
1485 1488
1486 1489 if fixup and clean:
1487 1490 s.clean.extend(fixup)
1488 1491
1489 1492 self._poststatusfixup(s, fixup)
1490 1493
1491 1494 if match.always():
1492 1495 # cache for performance
1493 1496 if s.unknown or s.ignored or s.clean:
1494 1497 # "_status" is cached with list*=False in the normal route
1495 1498 self._status = scmutil.status(s.modified, s.added, s.removed,
1496 1499 s.deleted, [], [], [])
1497 1500 else:
1498 1501 self._status = s
1499 1502
1500 1503 return s
1501 1504
1502 1505 @propertycache
1503 1506 def _manifest(self):
1504 1507 """generate a manifest corresponding to the values in self._status
1505 1508
1506 1509 This reuse the file nodeid from parent, but we use special node
1507 1510 identifiers for added and modified files. This is used by manifests
1508 1511 merge to see that files are different and by update logic to avoid
1509 1512 deleting newly added files.
1510 1513 """
1511 1514 return self._buildstatusmanifest(self._status)
1512 1515
1513 1516 def _buildstatusmanifest(self, status):
1514 1517 """Builds a manifest that includes the given status results."""
1515 1518 parents = self.parents()
1516 1519
1517 1520 man = parents[0].manifest().copy()
1518 1521
1519 1522 ff = self._flagfunc
1520 1523 for i, l in ((addednodeid, status.added),
1521 1524 (modifiednodeid, status.modified)):
1522 1525 for f in l:
1523 1526 man[f] = i
1524 1527 try:
1525 1528 man.setflag(f, ff(f))
1526 1529 except OSError:
1527 1530 pass
1528 1531
1529 1532 for f in status.deleted + status.removed:
1530 1533 if f in man:
1531 1534 del man[f]
1532 1535
1533 1536 return man
1534 1537
1535 1538 def _buildstatus(self, other, s, match, listignored, listclean,
1536 1539 listunknown):
1537 1540 """build a status with respect to another context
1538 1541
1539 1542 This includes logic for maintaining the fast path of status when
1540 1543 comparing the working directory against its parent, which is to skip
1541 1544 building a new manifest if self (working directory) is not comparing
1542 1545 against its parent (repo['.']).
1543 1546 """
1544 1547 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1545 1548 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1546 1549 # might have accidentally ended up with the entire contents of the file
1547 1550 # they are supposed to be linking to.
1548 1551 s.modified[:] = self._filtersuspectsymlink(s.modified)
1549 1552 if other != self._repo['.']:
1550 1553 s = super(workingctx, self)._buildstatus(other, s, match,
1551 1554 listignored, listclean,
1552 1555 listunknown)
1553 1556 return s
1554 1557
1555 1558 def _matchstatus(self, other, match):
1556 1559 """override the match method with a filter for directory patterns
1557 1560
1558 1561 We use inheritance to customize the match.bad method only in cases of
1559 1562 workingctx since it belongs only to the working directory when
1560 1563 comparing against the parent changeset.
1561 1564
1562 1565 If we aren't comparing against the working directory's parent, then we
1563 1566 just use the default match object sent to us.
1564 1567 """
1565 1568 if other != self._repo['.']:
1566 1569 def bad(f, msg):
1567 1570 # 'f' may be a directory pattern from 'match.files()',
1568 1571 # so 'f not in ctx1' is not enough
1569 1572 if f not in other and not other.hasdir(f):
1570 1573 self._repo.ui.warn('%s: %s\n' %
1571 1574 (self._repo.dirstate.pathto(f), msg))
1572 1575 match.bad = bad
1573 1576 return match
1574 1577
1575 1578 def markcommitted(self, node):
1576 1579 super(workingctx, self).markcommitted(node)
1577 1580
1578 1581 sparse.aftercommit(self._repo, node)
1579 1582
1580 1583 class committablefilectx(basefilectx):
1581 1584 """A committablefilectx provides common functionality for a file context
1582 1585 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1583 1586 def __init__(self, repo, path, filelog=None, ctx=None):
1584 1587 self._repo = repo
1585 1588 self._path = path
1586 1589 self._changeid = None
1587 1590 self._filerev = self._filenode = None
1588 1591
1589 1592 if filelog is not None:
1590 1593 self._filelog = filelog
1591 1594 if ctx:
1592 1595 self._changectx = ctx
1593 1596
1594 1597 def __nonzero__(self):
1595 1598 return True
1596 1599
1597 1600 __bool__ = __nonzero__
1598 1601
1599 1602 def linkrev(self):
1600 1603 # linked to self._changectx no matter if file is modified or not
1601 1604 return self.rev()
1602 1605
1603 1606 def parents(self):
1604 1607 '''return parent filectxs, following copies if necessary'''
1605 1608 def filenode(ctx, path):
1606 1609 return ctx._manifest.get(path, nullid)
1607 1610
1608 1611 path = self._path
1609 1612 fl = self._filelog
1610 1613 pcl = self._changectx._parents
1611 1614 renamed = self.renamed()
1612 1615
1613 1616 if renamed:
1614 1617 pl = [renamed + (None,)]
1615 1618 else:
1616 1619 pl = [(path, filenode(pcl[0], path), fl)]
1617 1620
1618 1621 for pc in pcl[1:]:
1619 1622 pl.append((path, filenode(pc, path), fl))
1620 1623
1621 1624 return [self._parentfilectx(p, fileid=n, filelog=l)
1622 1625 for p, n, l in pl if n != nullid]
1623 1626
1624 1627 def children(self):
1625 1628 return []
1626 1629
1627 1630 class workingfilectx(committablefilectx):
1628 1631 """A workingfilectx object makes access to data related to a particular
1629 1632 file in the working directory convenient."""
1630 1633 def __init__(self, repo, path, filelog=None, workingctx=None):
1631 1634 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1632 1635
1633 1636 @propertycache
1634 1637 def _changectx(self):
1635 1638 return workingctx(self._repo)
1636 1639
1637 1640 def data(self):
1638 1641 return self._repo.wread(self._path)
1639 1642 def renamed(self):
1640 1643 rp = self._repo.dirstate.copied(self._path)
1641 1644 if not rp:
1642 1645 return None
1643 1646 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1644 1647
1645 1648 def size(self):
1646 1649 return self._repo.wvfs.lstat(self._path).st_size
1647 1650 def date(self):
1648 1651 t, tz = self._changectx.date()
1649 1652 try:
1650 1653 return (self._repo.wvfs.lstat(self._path)[stat.ST_MTIME], tz)
1651 1654 except OSError as err:
1652 1655 if err.errno != errno.ENOENT:
1653 1656 raise
1654 1657 return (t, tz)
1655 1658
1656 1659 def exists(self):
1657 1660 return self._repo.wvfs.exists(self._path)
1658 1661
1659 1662 def lexists(self):
1660 1663 return self._repo.wvfs.lexists(self._path)
1661 1664
1662 1665 def audit(self):
1663 1666 return self._repo.wvfs.audit(self._path)
1664 1667
1665 1668 def cmp(self, fctx):
1666 1669 """compare with other file context
1667 1670
1668 1671 returns True if different than fctx.
1669 1672 """
1670 1673 # fctx should be a filectx (not a workingfilectx)
1671 1674 # invert comparison to reuse the same code path
1672 1675 return fctx.cmp(self)
1673 1676
1674 1677 def remove(self, ignoremissing=False):
1675 1678 """wraps unlink for a repo's working directory"""
1676 1679 rmdir = self._repo.ui.configbool('experimental', 'removeemptydirs')
1677 1680 self._repo.wvfs.unlinkpath(self._path, ignoremissing=ignoremissing,
1678 1681 rmdir=rmdir)
1679 1682
1680 1683 def write(self, data, flags, backgroundclose=False, **kwargs):
1681 1684 """wraps repo.wwrite"""
1682 1685 self._repo.wwrite(self._path, data, flags,
1683 1686 backgroundclose=backgroundclose,
1684 1687 **kwargs)
1685 1688
1686 1689 def markcopied(self, src):
1687 1690 """marks this file a copy of `src`"""
1688 1691 if self._repo.dirstate[self._path] in "nma":
1689 1692 self._repo.dirstate.copy(src, self._path)
1690 1693
1691 1694 def clearunknown(self):
1692 1695 """Removes conflicting items in the working directory so that
1693 1696 ``write()`` can be called successfully.
1694 1697 """
1695 1698 wvfs = self._repo.wvfs
1696 1699 f = self._path
1697 1700 wvfs.audit(f)
1698 1701 if self._repo.ui.configbool('experimental', 'merge.checkpathconflicts'):
1699 1702 # remove files under the directory as they should already be
1700 1703 # warned and backed up
1701 1704 if wvfs.isdir(f) and not wvfs.islink(f):
1702 1705 wvfs.rmtree(f, forcibly=True)
1703 1706 for p in reversed(list(util.finddirs(f))):
1704 1707 if wvfs.isfileorlink(p):
1705 1708 wvfs.unlink(p)
1706 1709 break
1707 1710 else:
1708 1711 # don't remove files if path conflicts are not processed
1709 1712 if wvfs.isdir(f) and not wvfs.islink(f):
1710 1713 wvfs.removedirs(f)
1711 1714
1712 1715 def setflags(self, l, x):
1713 1716 self._repo.wvfs.setflags(self._path, l, x)
1714 1717
1715 1718 class overlayworkingctx(committablectx):
1716 1719 """Wraps another mutable context with a write-back cache that can be
1717 1720 converted into a commit context.
1718 1721
1719 1722 self._cache[path] maps to a dict with keys: {
1720 1723 'exists': bool?
1721 1724 'date': date?
1722 1725 'data': str?
1723 1726 'flags': str?
1724 1727 'copied': str? (path or None)
1725 1728 }
1726 1729 If `exists` is True, `flags` must be non-None and 'date' is non-None. If it
1727 1730 is `False`, the file was deleted.
1728 1731 """
1729 1732
1730 1733 def __init__(self, repo):
1731 1734 super(overlayworkingctx, self).__init__(repo)
1732 1735 self.clean()
1733 1736
1734 1737 def setbase(self, wrappedctx):
1735 1738 self._wrappedctx = wrappedctx
1736 1739 self._parents = [wrappedctx]
1737 1740 # Drop old manifest cache as it is now out of date.
1738 1741 # This is necessary when, e.g., rebasing several nodes with one
1739 1742 # ``overlayworkingctx`` (e.g. with --collapse).
1740 1743 util.clearcachedproperty(self, '_manifest')
1741 1744
1742 1745 def data(self, path):
1743 1746 if self.isdirty(path):
1744 1747 if self._cache[path]['exists']:
1745 1748 if self._cache[path]['data']:
1746 1749 return self._cache[path]['data']
1747 1750 else:
1748 1751 # Must fallback here, too, because we only set flags.
1749 1752 return self._wrappedctx[path].data()
1750 1753 else:
1751 1754 raise error.ProgrammingError("No such file or directory: %s" %
1752 1755 path)
1753 1756 else:
1754 1757 return self._wrappedctx[path].data()
1755 1758
1756 1759 @propertycache
1757 1760 def _manifest(self):
1758 1761 parents = self.parents()
1759 1762 man = parents[0].manifest().copy()
1760 1763
1761 1764 flag = self._flagfunc
1762 1765 for path in self.added():
1763 1766 man[path] = addednodeid
1764 1767 man.setflag(path, flag(path))
1765 1768 for path in self.modified():
1766 1769 man[path] = modifiednodeid
1767 1770 man.setflag(path, flag(path))
1768 1771 for path in self.removed():
1769 1772 del man[path]
1770 1773 return man
1771 1774
1772 1775 @propertycache
1773 1776 def _flagfunc(self):
1774 1777 def f(path):
1775 1778 return self._cache[path]['flags']
1776 1779 return f
1777 1780
1778 1781 def files(self):
1779 1782 return sorted(self.added() + self.modified() + self.removed())
1780 1783
1781 1784 def modified(self):
1782 1785 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
1783 1786 self._existsinparent(f)]
1784 1787
1785 1788 def added(self):
1786 1789 return [f for f in self._cache.keys() if self._cache[f]['exists'] and
1787 1790 not self._existsinparent(f)]
1788 1791
1789 1792 def removed(self):
1790 1793 return [f for f in self._cache.keys() if
1791 1794 not self._cache[f]['exists'] and self._existsinparent(f)]
1792 1795
1793 1796 def isinmemory(self):
1794 1797 return True
1795 1798
1796 1799 def filedate(self, path):
1797 1800 if self.isdirty(path):
1798 1801 return self._cache[path]['date']
1799 1802 else:
1800 1803 return self._wrappedctx[path].date()
1801 1804
1802 1805 def markcopied(self, path, origin):
1803 1806 if self.isdirty(path):
1804 1807 self._cache[path]['copied'] = origin
1805 1808 else:
1806 1809 raise error.ProgrammingError('markcopied() called on clean context')
1807 1810
1808 1811 def copydata(self, path):
1809 1812 if self.isdirty(path):
1810 1813 return self._cache[path]['copied']
1811 1814 else:
1812 1815 raise error.ProgrammingError('copydata() called on clean context')
1813 1816
1814 1817 def flags(self, path):
1815 1818 if self.isdirty(path):
1816 1819 if self._cache[path]['exists']:
1817 1820 return self._cache[path]['flags']
1818 1821 else:
1819 1822 raise error.ProgrammingError("No such file or directory: %s" %
1820 1823 self._path)
1821 1824 else:
1822 1825 return self._wrappedctx[path].flags()
1823 1826
1824 1827 def _existsinparent(self, path):
1825 1828 try:
1826 1829 # ``commitctx` raises a ``ManifestLookupError`` if a path does not
1827 1830 # exist, unlike ``workingctx``, which returns a ``workingfilectx``
1828 1831 # with an ``exists()`` function.
1829 1832 self._wrappedctx[path]
1830 1833 return True
1831 1834 except error.ManifestLookupError:
1832 1835 return False
1833 1836
1834 1837 def _auditconflicts(self, path):
1835 1838 """Replicates conflict checks done by wvfs.write().
1836 1839
1837 1840 Since we never write to the filesystem and never call `applyupdates` in
1838 1841 IMM, we'll never check that a path is actually writable -- e.g., because
1839 1842 it adds `a/foo`, but `a` is actually a file in the other commit.
1840 1843 """
1841 1844 def fail(path, component):
1842 1845 # p1() is the base and we're receiving "writes" for p2()'s
1843 1846 # files.
1844 1847 if 'l' in self.p1()[component].flags():
1845 1848 raise error.Abort("error: %s conflicts with symlink %s "
1846 1849 "in %s." % (path, component,
1847 1850 self.p1().rev()))
1848 1851 else:
1849 1852 raise error.Abort("error: '%s' conflicts with file '%s' in "
1850 1853 "%s." % (path, component,
1851 1854 self.p1().rev()))
1852 1855
1853 1856 # Test that each new directory to be created to write this path from p2
1854 1857 # is not a file in p1.
1855 1858 components = path.split('/')
1856 1859 for i in pycompat.xrange(len(components)):
1857 1860 component = "/".join(components[0:i])
1858 1861 if component in self.p1() and self._cache[component]['exists']:
1859 1862 fail(path, component)
1860 1863
1861 1864 # Test the other direction -- that this path from p2 isn't a directory
1862 1865 # in p1 (test that p1 doesn't any paths matching `path/*`).
1863 1866 match = matchmod.match('/', '', [path + '/'], default=b'relpath')
1864 1867 matches = self.p1().manifest().matches(match)
1865 1868 mfiles = matches.keys()
1866 1869 if len(mfiles) > 0:
1867 1870 if len(mfiles) == 1 and mfiles[0] == path:
1868 1871 return
1869 1872 # omit the files which are deleted in current IMM wctx
1870 1873 mfiles = [m for m in mfiles if self._cache[m]['exists']]
1871 1874 if not mfiles:
1872 1875 return
1873 1876 raise error.Abort("error: file '%s' cannot be written because "
1874 1877 " '%s/' is a folder in %s (containing %d "
1875 1878 "entries: %s)"
1876 1879 % (path, path, self.p1(), len(mfiles),
1877 1880 ', '.join(mfiles)))
1878 1881
1879 1882 def write(self, path, data, flags='', **kwargs):
1880 1883 if data is None:
1881 1884 raise error.ProgrammingError("data must be non-None")
1882 1885 self._auditconflicts(path)
1883 1886 self._markdirty(path, exists=True, data=data, date=dateutil.makedate(),
1884 1887 flags=flags)
1885 1888
1886 1889 def setflags(self, path, l, x):
1887 1890 flag = ''
1888 1891 if l:
1889 1892 flag = 'l'
1890 1893 elif x:
1891 1894 flag = 'x'
1892 1895 self._markdirty(path, exists=True, date=dateutil.makedate(),
1893 1896 flags=flag)
1894 1897
1895 1898 def remove(self, path):
1896 1899 self._markdirty(path, exists=False)
1897 1900
1898 1901 def exists(self, path):
1899 1902 """exists behaves like `lexists`, but needs to follow symlinks and
1900 1903 return False if they are broken.
1901 1904 """
1902 1905 if self.isdirty(path):
1903 1906 # If this path exists and is a symlink, "follow" it by calling
1904 1907 # exists on the destination path.
1905 1908 if (self._cache[path]['exists'] and
1906 1909 'l' in self._cache[path]['flags']):
1907 1910 return self.exists(self._cache[path]['data'].strip())
1908 1911 else:
1909 1912 return self._cache[path]['exists']
1910 1913
1911 1914 return self._existsinparent(path)
1912 1915
1913 1916 def lexists(self, path):
1914 1917 """lexists returns True if the path exists"""
1915 1918 if self.isdirty(path):
1916 1919 return self._cache[path]['exists']
1917 1920
1918 1921 return self._existsinparent(path)
1919 1922
1920 1923 def size(self, path):
1921 1924 if self.isdirty(path):
1922 1925 if self._cache[path]['exists']:
1923 1926 return len(self._cache[path]['data'])
1924 1927 else:
1925 1928 raise error.ProgrammingError("No such file or directory: %s" %
1926 1929 self._path)
1927 1930 return self._wrappedctx[path].size()
1928 1931
1929 1932 def tomemctx(self, text, branch=None, extra=None, date=None, parents=None,
1930 1933 user=None, editor=None):
1931 1934 """Converts this ``overlayworkingctx`` into a ``memctx`` ready to be
1932 1935 committed.
1933 1936
1934 1937 ``text`` is the commit message.
1935 1938 ``parents`` (optional) are rev numbers.
1936 1939 """
1937 1940 # Default parents to the wrapped contexts' if not passed.
1938 1941 if parents is None:
1939 1942 parents = self._wrappedctx.parents()
1940 1943 if len(parents) == 1:
1941 1944 parents = (parents[0], None)
1942 1945
1943 1946 # ``parents`` is passed as rev numbers; convert to ``commitctxs``.
1944 1947 if parents[1] is None:
1945 1948 parents = (self._repo[parents[0]], None)
1946 1949 else:
1947 1950 parents = (self._repo[parents[0]], self._repo[parents[1]])
1948 1951
1949 1952 files = self._cache.keys()
1950 1953 def getfile(repo, memctx, path):
1951 1954 if self._cache[path]['exists']:
1952 1955 return memfilectx(repo, memctx, path,
1953 1956 self._cache[path]['data'],
1954 1957 'l' in self._cache[path]['flags'],
1955 1958 'x' in self._cache[path]['flags'],
1956 1959 self._cache[path]['copied'])
1957 1960 else:
1958 1961 # Returning None, but including the path in `files`, is
1959 1962 # necessary for memctx to register a deletion.
1960 1963 return None
1961 1964 return memctx(self._repo, parents, text, files, getfile, date=date,
1962 1965 extra=extra, user=user, branch=branch, editor=editor)
1963 1966
1964 1967 def isdirty(self, path):
1965 1968 return path in self._cache
1966 1969
1967 1970 def isempty(self):
1968 1971 # We need to discard any keys that are actually clean before the empty
1969 1972 # commit check.
1970 1973 self._compact()
1971 1974 return len(self._cache) == 0
1972 1975
1973 1976 def clean(self):
1974 1977 self._cache = {}
1975 1978
1976 1979 def _compact(self):
1977 1980 """Removes keys from the cache that are actually clean, by comparing
1978 1981 them with the underlying context.
1979 1982
1980 1983 This can occur during the merge process, e.g. by passing --tool :local
1981 1984 to resolve a conflict.
1982 1985 """
1983 1986 keys = []
1984 1987 for path in self._cache.keys():
1985 1988 cache = self._cache[path]
1986 1989 try:
1987 1990 underlying = self._wrappedctx[path]
1988 1991 if (underlying.data() == cache['data'] and
1989 1992 underlying.flags() == cache['flags']):
1990 1993 keys.append(path)
1991 1994 except error.ManifestLookupError:
1992 1995 # Path not in the underlying manifest (created).
1993 1996 continue
1994 1997
1995 1998 for path in keys:
1996 1999 del self._cache[path]
1997 2000 return keys
1998 2001
1999 2002 def _markdirty(self, path, exists, data=None, date=None, flags=''):
2000 2003 # data not provided, let's see if we already have some; if not, let's
2001 2004 # grab it from our underlying context, so that we always have data if
2002 2005 # the file is marked as existing.
2003 2006 if exists and data is None:
2004 2007 oldentry = self._cache.get(path) or {}
2005 2008 data = oldentry.get('data') or self._wrappedctx[path].data()
2006 2009
2007 2010 self._cache[path] = {
2008 2011 'exists': exists,
2009 2012 'data': data,
2010 2013 'date': date,
2011 2014 'flags': flags,
2012 2015 'copied': None,
2013 2016 }
2014 2017
2015 2018 def filectx(self, path, filelog=None):
2016 2019 return overlayworkingfilectx(self._repo, path, parent=self,
2017 2020 filelog=filelog)
2018 2021
2019 2022 class overlayworkingfilectx(committablefilectx):
2020 2023 """Wrap a ``workingfilectx`` but intercepts all writes into an in-memory
2021 2024 cache, which can be flushed through later by calling ``flush()``."""
2022 2025
2023 2026 def __init__(self, repo, path, filelog=None, parent=None):
2024 2027 super(overlayworkingfilectx, self).__init__(repo, path, filelog,
2025 2028 parent)
2026 2029 self._repo = repo
2027 2030 self._parent = parent
2028 2031 self._path = path
2029 2032
2030 2033 def cmp(self, fctx):
2031 2034 return self.data() != fctx.data()
2032 2035
2033 2036 def changectx(self):
2034 2037 return self._parent
2035 2038
2036 2039 def data(self):
2037 2040 return self._parent.data(self._path)
2038 2041
2039 2042 def date(self):
2040 2043 return self._parent.filedate(self._path)
2041 2044
2042 2045 def exists(self):
2043 2046 return self.lexists()
2044 2047
2045 2048 def lexists(self):
2046 2049 return self._parent.exists(self._path)
2047 2050
2048 2051 def renamed(self):
2049 2052 path = self._parent.copydata(self._path)
2050 2053 if not path:
2051 2054 return None
2052 2055 return path, self._changectx._parents[0]._manifest.get(path, nullid)
2053 2056
2054 2057 def size(self):
2055 2058 return self._parent.size(self._path)
2056 2059
2057 2060 def markcopied(self, origin):
2058 2061 self._parent.markcopied(self._path, origin)
2059 2062
2060 2063 def audit(self):
2061 2064 pass
2062 2065
2063 2066 def flags(self):
2064 2067 return self._parent.flags(self._path)
2065 2068
2066 2069 def setflags(self, islink, isexec):
2067 2070 return self._parent.setflags(self._path, islink, isexec)
2068 2071
2069 2072 def write(self, data, flags, backgroundclose=False, **kwargs):
2070 2073 return self._parent.write(self._path, data, flags, **kwargs)
2071 2074
2072 2075 def remove(self, ignoremissing=False):
2073 2076 return self._parent.remove(self._path)
2074 2077
2075 2078 def clearunknown(self):
2076 2079 pass
2077 2080
2078 2081 class workingcommitctx(workingctx):
2079 2082 """A workingcommitctx object makes access to data related to
2080 2083 the revision being committed convenient.
2081 2084
2082 2085 This hides changes in the working directory, if they aren't
2083 2086 committed in this context.
2084 2087 """
2085 2088 def __init__(self, repo, changes,
2086 2089 text="", user=None, date=None, extra=None):
2087 2090 super(workingcommitctx, self).__init__(repo, text, user, date, extra,
2088 2091 changes)
2089 2092
2090 2093 def _dirstatestatus(self, match, ignored=False, clean=False, unknown=False):
2091 2094 """Return matched files only in ``self._status``
2092 2095
2093 2096 Uncommitted files appear "clean" via this context, even if
2094 2097 they aren't actually so in the working directory.
2095 2098 """
2096 2099 if clean:
2097 2100 clean = [f for f in self._manifest if f not in self._changedset]
2098 2101 else:
2099 2102 clean = []
2100 2103 return scmutil.status([f for f in self._status.modified if match(f)],
2101 2104 [f for f in self._status.added if match(f)],
2102 2105 [f for f in self._status.removed if match(f)],
2103 2106 [], [], [], clean)
2104 2107
2105 2108 @propertycache
2106 2109 def _changedset(self):
2107 2110 """Return the set of files changed in this context
2108 2111 """
2109 2112 changed = set(self._status.modified)
2110 2113 changed.update(self._status.added)
2111 2114 changed.update(self._status.removed)
2112 2115 return changed
2113 2116
2114 2117 def makecachingfilectxfn(func):
2115 2118 """Create a filectxfn that caches based on the path.
2116 2119
2117 2120 We can't use util.cachefunc because it uses all arguments as the cache
2118 2121 key and this creates a cycle since the arguments include the repo and
2119 2122 memctx.
2120 2123 """
2121 2124 cache = {}
2122 2125
2123 2126 def getfilectx(repo, memctx, path):
2124 2127 if path not in cache:
2125 2128 cache[path] = func(repo, memctx, path)
2126 2129 return cache[path]
2127 2130
2128 2131 return getfilectx
2129 2132
2130 2133 def memfilefromctx(ctx):
2131 2134 """Given a context return a memfilectx for ctx[path]
2132 2135
2133 2136 This is a convenience method for building a memctx based on another
2134 2137 context.
2135 2138 """
2136 2139 def getfilectx(repo, memctx, path):
2137 2140 fctx = ctx[path]
2138 2141 # this is weird but apparently we only keep track of one parent
2139 2142 # (why not only store that instead of a tuple?)
2140 2143 copied = fctx.renamed()
2141 2144 if copied:
2142 2145 copied = copied[0]
2143 2146 return memfilectx(repo, memctx, path, fctx.data(),
2144 2147 islink=fctx.islink(), isexec=fctx.isexec(),
2145 2148 copied=copied)
2146 2149
2147 2150 return getfilectx
2148 2151
2149 2152 def memfilefrompatch(patchstore):
2150 2153 """Given a patch (e.g. patchstore object) return a memfilectx
2151 2154
2152 2155 This is a convenience method for building a memctx based on a patchstore.
2153 2156 """
2154 2157 def getfilectx(repo, memctx, path):
2155 2158 data, mode, copied = patchstore.getfile(path)
2156 2159 if data is None:
2157 2160 return None
2158 2161 islink, isexec = mode
2159 2162 return memfilectx(repo, memctx, path, data, islink=islink,
2160 2163 isexec=isexec, copied=copied)
2161 2164
2162 2165 return getfilectx
2163 2166
2164 2167 class memctx(committablectx):
2165 2168 """Use memctx to perform in-memory commits via localrepo.commitctx().
2166 2169
2167 2170 Revision information is supplied at initialization time while
2168 2171 related files data and is made available through a callback
2169 2172 mechanism. 'repo' is the current localrepo, 'parents' is a
2170 2173 sequence of two parent revisions identifiers (pass None for every
2171 2174 missing parent), 'text' is the commit message and 'files' lists
2172 2175 names of files touched by the revision (normalized and relative to
2173 2176 repository root).
2174 2177
2175 2178 filectxfn(repo, memctx, path) is a callable receiving the
2176 2179 repository, the current memctx object and the normalized path of
2177 2180 requested file, relative to repository root. It is fired by the
2178 2181 commit function for every file in 'files', but calls order is
2179 2182 undefined. If the file is available in the revision being
2180 2183 committed (updated or added), filectxfn returns a memfilectx
2181 2184 object. If the file was removed, filectxfn return None for recent
2182 2185 Mercurial. Moved files are represented by marking the source file
2183 2186 removed and the new file added with copy information (see
2184 2187 memfilectx).
2185 2188
2186 2189 user receives the committer name and defaults to current
2187 2190 repository username, date is the commit date in any format
2188 2191 supported by dateutil.parsedate() and defaults to current date, extra
2189 2192 is a dictionary of metadata or is left empty.
2190 2193 """
2191 2194
2192 2195 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
2193 2196 # Extensions that need to retain compatibility across Mercurial 3.1 can use
2194 2197 # this field to determine what to do in filectxfn.
2195 2198 _returnnoneformissingfiles = True
2196 2199
2197 2200 def __init__(self, repo, parents, text, files, filectxfn, user=None,
2198 2201 date=None, extra=None, branch=None, editor=False):
2199 2202 super(memctx, self).__init__(repo, text, user, date, extra)
2200 2203 self._rev = None
2201 2204 self._node = None
2202 2205 parents = [(p or nullid) for p in parents]
2203 2206 p1, p2 = parents
2204 2207 self._parents = [self._repo[p] for p in (p1, p2)]
2205 2208 files = sorted(set(files))
2206 2209 self._files = files
2207 2210 if branch is not None:
2208 2211 self._extra['branch'] = encoding.fromlocal(branch)
2209 2212 self.substate = {}
2210 2213
2211 2214 if isinstance(filectxfn, patch.filestore):
2212 2215 filectxfn = memfilefrompatch(filectxfn)
2213 2216 elif not callable(filectxfn):
2214 2217 # if store is not callable, wrap it in a function
2215 2218 filectxfn = memfilefromctx(filectxfn)
2216 2219
2217 2220 # memoizing increases performance for e.g. vcs convert scenarios.
2218 2221 self._filectxfn = makecachingfilectxfn(filectxfn)
2219 2222
2220 2223 if editor:
2221 2224 self._text = editor(self._repo, self, [])
2222 2225 self._repo.savecommitmessage(self._text)
2223 2226
2224 2227 def filectx(self, path, filelog=None):
2225 2228 """get a file context from the working directory
2226 2229
2227 2230 Returns None if file doesn't exist and should be removed."""
2228 2231 return self._filectxfn(self._repo, self, path)
2229 2232
2230 2233 def commit(self):
2231 2234 """commit context to the repo"""
2232 2235 return self._repo.commitctx(self)
2233 2236
2234 2237 @propertycache
2235 2238 def _manifest(self):
2236 2239 """generate a manifest based on the return values of filectxfn"""
2237 2240
2238 2241 # keep this simple for now; just worry about p1
2239 2242 pctx = self._parents[0]
2240 2243 man = pctx.manifest().copy()
2241 2244
2242 2245 for f in self._status.modified:
2243 2246 man[f] = modifiednodeid
2244 2247
2245 2248 for f in self._status.added:
2246 2249 man[f] = addednodeid
2247 2250
2248 2251 for f in self._status.removed:
2249 2252 if f in man:
2250 2253 del man[f]
2251 2254
2252 2255 return man
2253 2256
2254 2257 @propertycache
2255 2258 def _status(self):
2256 2259 """Calculate exact status from ``files`` specified at construction
2257 2260 """
2258 2261 man1 = self.p1().manifest()
2259 2262 p2 = self._parents[1]
2260 2263 # "1 < len(self._parents)" can't be used for checking
2261 2264 # existence of the 2nd parent, because "memctx._parents" is
2262 2265 # explicitly initialized by the list, of which length is 2.
2263 2266 if p2.node() != nullid:
2264 2267 man2 = p2.manifest()
2265 2268 managing = lambda f: f in man1 or f in man2
2266 2269 else:
2267 2270 managing = lambda f: f in man1
2268 2271
2269 2272 modified, added, removed = [], [], []
2270 2273 for f in self._files:
2271 2274 if not managing(f):
2272 2275 added.append(f)
2273 2276 elif self[f]:
2274 2277 modified.append(f)
2275 2278 else:
2276 2279 removed.append(f)
2277 2280
2278 2281 return scmutil.status(modified, added, removed, [], [], [], [])
2279 2282
2280 2283 class memfilectx(committablefilectx):
2281 2284 """memfilectx represents an in-memory file to commit.
2282 2285
2283 2286 See memctx and committablefilectx for more details.
2284 2287 """
2285 2288 def __init__(self, repo, changectx, path, data, islink=False,
2286 2289 isexec=False, copied=None):
2287 2290 """
2288 2291 path is the normalized file path relative to repository root.
2289 2292 data is the file content as a string.
2290 2293 islink is True if the file is a symbolic link.
2291 2294 isexec is True if the file is executable.
2292 2295 copied is the source file path if current file was copied in the
2293 2296 revision being committed, or None."""
2294 2297 super(memfilectx, self).__init__(repo, path, None, changectx)
2295 2298 self._data = data
2296 2299 if islink:
2297 2300 self._flags = 'l'
2298 2301 elif isexec:
2299 2302 self._flags = 'x'
2300 2303 else:
2301 2304 self._flags = ''
2302 2305 self._copied = None
2303 2306 if copied:
2304 2307 self._copied = (copied, nullid)
2305 2308
2306 2309 def data(self):
2307 2310 return self._data
2308 2311
2309 2312 def remove(self, ignoremissing=False):
2310 2313 """wraps unlink for a repo's working directory"""
2311 2314 # need to figure out what to do here
2312 2315 del self._changectx[self._path]
2313 2316
2314 2317 def write(self, data, flags, **kwargs):
2315 2318 """wraps repo.wwrite"""
2316 2319 self._data = data
2317 2320
2318 2321
2319 2322 class metadataonlyctx(committablectx):
2320 2323 """Like memctx but it's reusing the manifest of different commit.
2321 2324 Intended to be used by lightweight operations that are creating
2322 2325 metadata-only changes.
2323 2326
2324 2327 Revision information is supplied at initialization time. 'repo' is the
2325 2328 current localrepo, 'ctx' is original revision which manifest we're reuisng
2326 2329 'parents' is a sequence of two parent revisions identifiers (pass None for
2327 2330 every missing parent), 'text' is the commit.
2328 2331
2329 2332 user receives the committer name and defaults to current repository
2330 2333 username, date is the commit date in any format supported by
2331 2334 dateutil.parsedate() and defaults to current date, extra is a dictionary of
2332 2335 metadata or is left empty.
2333 2336 """
2334 2337 def __init__(self, repo, originalctx, parents=None, text=None, user=None,
2335 2338 date=None, extra=None, editor=False):
2336 2339 if text is None:
2337 2340 text = originalctx.description()
2338 2341 super(metadataonlyctx, self).__init__(repo, text, user, date, extra)
2339 2342 self._rev = None
2340 2343 self._node = None
2341 2344 self._originalctx = originalctx
2342 2345 self._manifestnode = originalctx.manifestnode()
2343 2346 if parents is None:
2344 2347 parents = originalctx.parents()
2345 2348 else:
2346 2349 parents = [repo[p] for p in parents if p is not None]
2347 2350 parents = parents[:]
2348 2351 while len(parents) < 2:
2349 2352 parents.append(repo[nullid])
2350 2353 p1, p2 = self._parents = parents
2351 2354
2352 2355 # sanity check to ensure that the reused manifest parents are
2353 2356 # manifests of our commit parents
2354 2357 mp1, mp2 = self.manifestctx().parents
2355 2358 if p1 != nullid and p1.manifestnode() != mp1:
2356 2359 raise RuntimeError(r"can't reuse the manifest: its p1 "
2357 2360 r"doesn't match the new ctx p1")
2358 2361 if p2 != nullid and p2.manifestnode() != mp2:
2359 2362 raise RuntimeError(r"can't reuse the manifest: "
2360 2363 r"its p2 doesn't match the new ctx p2")
2361 2364
2362 2365 self._files = originalctx.files()
2363 2366 self.substate = {}
2364 2367
2365 2368 if editor:
2366 2369 self._text = editor(self._repo, self, [])
2367 2370 self._repo.savecommitmessage(self._text)
2368 2371
2369 2372 def manifestnode(self):
2370 2373 return self._manifestnode
2371 2374
2372 2375 @property
2373 2376 def _manifestctx(self):
2374 2377 return self._repo.manifestlog[self._manifestnode]
2375 2378
2376 2379 def filectx(self, path, filelog=None):
2377 2380 return self._originalctx.filectx(path, filelog=filelog)
2378 2381
2379 2382 def commit(self):
2380 2383 """commit context to the repo"""
2381 2384 return self._repo.commitctx(self)
2382 2385
2383 2386 @property
2384 2387 def _manifest(self):
2385 2388 return self._originalctx.manifest()
2386 2389
2387 2390 @propertycache
2388 2391 def _status(self):
2389 2392 """Calculate exact status from ``files`` specified in the ``origctx``
2390 2393 and parents manifests.
2391 2394 """
2392 2395 man1 = self.p1().manifest()
2393 2396 p2 = self._parents[1]
2394 2397 # "1 < len(self._parents)" can't be used for checking
2395 2398 # existence of the 2nd parent, because "metadataonlyctx._parents" is
2396 2399 # explicitly initialized by the list, of which length is 2.
2397 2400 if p2.node() != nullid:
2398 2401 man2 = p2.manifest()
2399 2402 managing = lambda f: f in man1 or f in man2
2400 2403 else:
2401 2404 managing = lambda f: f in man1
2402 2405
2403 2406 modified, added, removed = [], [], []
2404 2407 for f in self._files:
2405 2408 if not managing(f):
2406 2409 added.append(f)
2407 2410 elif f in self:
2408 2411 modified.append(f)
2409 2412 else:
2410 2413 removed.append(f)
2411 2414
2412 2415 return scmutil.status(modified, added, removed, [], [], [], [])
2413 2416
2414 2417 class arbitraryfilectx(object):
2415 2418 """Allows you to use filectx-like functions on a file in an arbitrary
2416 2419 location on disk, possibly not in the working directory.
2417 2420 """
2418 2421 def __init__(self, path, repo=None):
2419 2422 # Repo is optional because contrib/simplemerge uses this class.
2420 2423 self._repo = repo
2421 2424 self._path = path
2422 2425
2423 2426 def cmp(self, fctx):
2424 2427 # filecmp follows symlinks whereas `cmp` should not, so skip the fast
2425 2428 # path if either side is a symlink.
2426 2429 symlinks = ('l' in self.flags() or 'l' in fctx.flags())
2427 2430 if not symlinks and isinstance(fctx, workingfilectx) and self._repo:
2428 2431 # Add a fast-path for merge if both sides are disk-backed.
2429 2432 # Note that filecmp uses the opposite return values (True if same)
2430 2433 # from our cmp functions (True if different).
2431 2434 return not filecmp.cmp(self.path(), self._repo.wjoin(fctx.path()))
2432 2435 return self.data() != fctx.data()
2433 2436
2434 2437 def path(self):
2435 2438 return self._path
2436 2439
2437 2440 def flags(self):
2438 2441 return ''
2439 2442
2440 2443 def data(self):
2441 2444 return util.readfile(self._path)
2442 2445
2443 2446 def decodeddata(self):
2444 2447 with open(self._path, "rb") as f:
2445 2448 return f.read()
2446 2449
2447 2450 def remove(self):
2448 2451 util.unlink(self._path)
2449 2452
2450 2453 def write(self, data, flags, **kwargs):
2451 2454 assert not flags
2452 2455 with open(self._path, "wb") as f:
2453 2456 f.write(data)
General Comments 0
You need to be logged in to leave comments. Login now