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