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