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