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