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