##// END OF EJS Templates
context: handle censored data in an on-disk file context based on config...
Mike Edgar -
r22932:d8179287 default
parent child Browse files
Show More
@@ -1,1710 +1,1717 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 node import nullid, nullrev, short, hex, bin
9 9 from i18n import _
10 10 import mdiff, error, util, scmutil, subrepo, patch, encoding, phases
11 11 import match as matchmod
12 12 import os, errno, stat
13 13 import obsolete as obsmod
14 14 import repoview
15 15 import fileset
16 16 import revlog
17 17
18 18 propertycache = util.propertycache
19 19
20 20 class basectx(object):
21 21 """A basectx object represents the common logic for its children:
22 22 changectx: read-only context that is already present in the repo,
23 23 workingctx: a context that represents the working directory and can
24 24 be committed,
25 25 memctx: a context that represents changes in-memory and can also
26 26 be committed."""
27 27 def __new__(cls, repo, changeid='', *args, **kwargs):
28 28 if isinstance(changeid, basectx):
29 29 return changeid
30 30
31 31 o = super(basectx, cls).__new__(cls)
32 32
33 33 o._repo = repo
34 34 o._rev = nullrev
35 35 o._node = nullid
36 36
37 37 return o
38 38
39 39 def __str__(self):
40 40 return short(self.node())
41 41
42 42 def __int__(self):
43 43 return self.rev()
44 44
45 45 def __repr__(self):
46 46 return "<%s %s>" % (type(self).__name__, str(self))
47 47
48 48 def __eq__(self, other):
49 49 try:
50 50 return type(self) == type(other) and self._rev == other._rev
51 51 except AttributeError:
52 52 return False
53 53
54 54 def __ne__(self, other):
55 55 return not (self == other)
56 56
57 57 def __contains__(self, key):
58 58 return key in self._manifest
59 59
60 60 def __getitem__(self, key):
61 61 return self.filectx(key)
62 62
63 63 def __iter__(self):
64 64 for f in sorted(self._manifest):
65 65 yield f
66 66
67 67 def _manifestmatches(self, match, s):
68 68 """generate a new manifest filtered by the match argument
69 69
70 70 This method is for internal use only and mainly exists to provide an
71 71 object oriented way for other contexts to customize the manifest
72 72 generation.
73 73 """
74 74 if match.always():
75 75 return self.manifest().copy()
76 76
77 77 files = match.files()
78 78 if (match.matchfn == match.exact or
79 79 (not match.anypats() and util.all(fn in self for fn in files))):
80 80 return self.manifest().intersectfiles(files)
81 81
82 82 mf = self.manifest().copy()
83 83 for fn in mf.keys():
84 84 if not match(fn):
85 85 del mf[fn]
86 86 return mf
87 87
88 88 def _matchstatus(self, other, s, match, listignored, listclean,
89 89 listunknown):
90 90 """return match.always if match is none
91 91
92 92 This internal method provides a way for child objects to override the
93 93 match operator.
94 94 """
95 95 return match or matchmod.always(self._repo.root, self._repo.getcwd())
96 96
97 97 def _prestatus(self, other, s, match, listignored, listclean, listunknown):
98 98 """provide a hook to allow child objects to preprocess status results
99 99
100 100 For example, this allows other contexts, such as workingctx, to query
101 101 the dirstate before comparing the manifests.
102 102 """
103 103 # load earliest manifest first for caching reasons
104 104 if self.rev() < other.rev():
105 105 self.manifest()
106 106 return s
107 107
108 108 def _poststatus(self, other, s, match, listignored, listclean, listunknown):
109 109 """provide a hook to allow child objects to postprocess status results
110 110
111 111 For example, this allows other contexts, such as workingctx, to filter
112 112 suspect symlinks in the case of FAT32 and NTFS filesytems.
113 113 """
114 114 return s
115 115
116 116 def _buildstatus(self, other, s, match, listignored, listclean,
117 117 listunknown):
118 118 """build a status with respect to another context"""
119 119 mf1 = other._manifestmatches(match, s)
120 120 mf2 = self._manifestmatches(match, s)
121 121
122 122 modified, added, clean = [], [], []
123 123 deleted, unknown, ignored = s[3], s[4], s[5]
124 124 withflags = mf1.withflags() | mf2.withflags()
125 125 for fn, mf2node in mf2.iteritems():
126 126 if fn in mf1:
127 127 if (fn not in deleted and
128 128 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
129 129 (mf1[fn] != mf2node and
130 130 (mf2node or self[fn].cmp(other[fn]))))):
131 131 modified.append(fn)
132 132 elif listclean:
133 133 clean.append(fn)
134 134 del mf1[fn]
135 135 elif fn not in deleted:
136 136 added.append(fn)
137 137 removed = mf1.keys()
138 138 if removed:
139 139 # need to filter files if they are already reported as removed
140 140 unknown = [fn for fn in unknown if fn not in mf1]
141 141 ignored = [fn for fn in ignored if fn not in mf1]
142 142
143 143 return [modified, added, removed, deleted, unknown, ignored, clean]
144 144
145 145 @propertycache
146 146 def substate(self):
147 147 return subrepo.state(self, self._repo.ui)
148 148
149 149 def subrev(self, subpath):
150 150 return self.substate[subpath][1]
151 151
152 152 def rev(self):
153 153 return self._rev
154 154 def node(self):
155 155 return self._node
156 156 def hex(self):
157 157 return hex(self.node())
158 158 def manifest(self):
159 159 return self._manifest
160 160 def phasestr(self):
161 161 return phases.phasenames[self.phase()]
162 162 def mutable(self):
163 163 return self.phase() > phases.public
164 164
165 165 def getfileset(self, expr):
166 166 return fileset.getfileset(self, expr)
167 167
168 168 def obsolete(self):
169 169 """True if the changeset is obsolete"""
170 170 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
171 171
172 172 def extinct(self):
173 173 """True if the changeset is extinct"""
174 174 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
175 175
176 176 def unstable(self):
177 177 """True if the changeset is not obsolete but it's ancestor are"""
178 178 return self.rev() in obsmod.getrevs(self._repo, 'unstable')
179 179
180 180 def bumped(self):
181 181 """True if the changeset try to be a successor of a public changeset
182 182
183 183 Only non-public and non-obsolete changesets may be bumped.
184 184 """
185 185 return self.rev() in obsmod.getrevs(self._repo, 'bumped')
186 186
187 187 def divergent(self):
188 188 """Is a successors of a changeset with multiple possible successors set
189 189
190 190 Only non-public and non-obsolete changesets may be divergent.
191 191 """
192 192 return self.rev() in obsmod.getrevs(self._repo, 'divergent')
193 193
194 194 def troubled(self):
195 195 """True if the changeset is either unstable, bumped or divergent"""
196 196 return self.unstable() or self.bumped() or self.divergent()
197 197
198 198 def troubles(self):
199 199 """return the list of troubles affecting this changesets.
200 200
201 201 Troubles are returned as strings. possible values are:
202 202 - unstable,
203 203 - bumped,
204 204 - divergent.
205 205 """
206 206 troubles = []
207 207 if self.unstable():
208 208 troubles.append('unstable')
209 209 if self.bumped():
210 210 troubles.append('bumped')
211 211 if self.divergent():
212 212 troubles.append('divergent')
213 213 return troubles
214 214
215 215 def parents(self):
216 216 """return contexts for each parent changeset"""
217 217 return self._parents
218 218
219 219 def p1(self):
220 220 return self._parents[0]
221 221
222 222 def p2(self):
223 223 if len(self._parents) == 2:
224 224 return self._parents[1]
225 225 return changectx(self._repo, -1)
226 226
227 227 def _fileinfo(self, path):
228 228 if '_manifest' in self.__dict__:
229 229 try:
230 230 return self._manifest[path], self._manifest.flags(path)
231 231 except KeyError:
232 232 raise error.ManifestLookupError(self._node, path,
233 233 _('not found in manifest'))
234 234 if '_manifestdelta' in self.__dict__ or path in self.files():
235 235 if path in self._manifestdelta:
236 236 return (self._manifestdelta[path],
237 237 self._manifestdelta.flags(path))
238 238 node, flag = self._repo.manifest.find(self._changeset[0], path)
239 239 if not node:
240 240 raise error.ManifestLookupError(self._node, path,
241 241 _('not found in manifest'))
242 242
243 243 return node, flag
244 244
245 245 def filenode(self, path):
246 246 return self._fileinfo(path)[0]
247 247
248 248 def flags(self, path):
249 249 try:
250 250 return self._fileinfo(path)[1]
251 251 except error.LookupError:
252 252 return ''
253 253
254 254 def sub(self, path):
255 255 return subrepo.subrepo(self, path)
256 256
257 257 def match(self, pats=[], include=None, exclude=None, default='glob'):
258 258 r = self._repo
259 259 return matchmod.match(r.root, r.getcwd(), pats,
260 260 include, exclude, default,
261 261 auditor=r.auditor, ctx=self)
262 262
263 263 def diff(self, ctx2=None, match=None, **opts):
264 264 """Returns a diff generator for the given contexts and matcher"""
265 265 if ctx2 is None:
266 266 ctx2 = self.p1()
267 267 if ctx2 is not None:
268 268 ctx2 = self._repo[ctx2]
269 269 diffopts = patch.diffopts(self._repo.ui, opts)
270 270 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
271 271
272 272 @propertycache
273 273 def _dirs(self):
274 274 return scmutil.dirs(self._manifest)
275 275
276 276 def dirs(self):
277 277 return self._dirs
278 278
279 279 def dirty(self, missing=False, merge=True, branch=True):
280 280 return False
281 281
282 282 def status(self, other=None, match=None, listignored=False,
283 283 listclean=False, listunknown=False, listsubrepos=False):
284 284 """return status of files between two nodes or node and working
285 285 directory.
286 286
287 287 If other is None, compare this node with working directory.
288 288
289 289 returns (modified, added, removed, deleted, unknown, ignored, clean)
290 290 """
291 291
292 292 ctx1 = self
293 293 ctx2 = self._repo[other]
294 294
295 295 # This next code block is, admittedly, fragile logic that tests for
296 296 # reversing the contexts and wouldn't need to exist if it weren't for
297 297 # the fast (and common) code path of comparing the working directory
298 298 # with its first parent.
299 299 #
300 300 # What we're aiming for here is the ability to call:
301 301 #
302 302 # workingctx.status(parentctx)
303 303 #
304 304 # If we always built the manifest for each context and compared those,
305 305 # then we'd be done. But the special case of the above call means we
306 306 # just copy the manifest of the parent.
307 307 reversed = False
308 308 if (not isinstance(ctx1, changectx)
309 309 and isinstance(ctx2, changectx)):
310 310 reversed = True
311 311 ctx1, ctx2 = ctx2, ctx1
312 312
313 313 r = [[], [], [], [], [], [], []]
314 314 match = ctx2._matchstatus(ctx1, r, match, listignored, listclean,
315 315 listunknown)
316 316 r = ctx2._prestatus(ctx1, r, match, listignored, listclean, listunknown)
317 317 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
318 318 listunknown)
319 319 r = ctx2._poststatus(ctx1, r, match, listignored, listclean,
320 320 listunknown)
321 321
322 322 if reversed:
323 323 # reverse added and removed
324 324 r[1], r[2] = r[2], r[1]
325 325
326 326 if listsubrepos:
327 327 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
328 328 rev2 = ctx2.subrev(subpath)
329 329 try:
330 330 submatch = matchmod.narrowmatcher(subpath, match)
331 331 s = sub.status(rev2, match=submatch, ignored=listignored,
332 332 clean=listclean, unknown=listunknown,
333 333 listsubrepos=True)
334 334 for rfiles, sfiles in zip(r, s):
335 335 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
336 336 except error.LookupError:
337 337 self._repo.ui.status(_("skipping missing "
338 338 "subrepository: %s\n") % subpath)
339 339
340 340 for l in r:
341 341 l.sort()
342 342
343 343 # we return a tuple to signify that this list isn't changing
344 344 return scmutil.status(*r)
345 345
346 346
347 347 def makememctx(repo, parents, text, user, date, branch, files, store,
348 348 editor=None):
349 349 def getfilectx(repo, memctx, path):
350 350 data, mode, copied = store.getfile(path)
351 351 if data is None:
352 352 return None
353 353 islink, isexec = mode
354 354 return memfilectx(repo, path, data, islink=islink, isexec=isexec,
355 355 copied=copied, memctx=memctx)
356 356 extra = {}
357 357 if branch:
358 358 extra['branch'] = encoding.fromlocal(branch)
359 359 ctx = memctx(repo, parents, text, files, getfilectx, user,
360 360 date, extra, editor)
361 361 return ctx
362 362
363 363 class changectx(basectx):
364 364 """A changecontext object makes access to data related to a particular
365 365 changeset convenient. It represents a read-only context already present in
366 366 the repo."""
367 367 def __init__(self, repo, changeid=''):
368 368 """changeid is a revision number, node, or tag"""
369 369
370 370 # since basectx.__new__ already took care of copying the object, we
371 371 # don't need to do anything in __init__, so we just exit here
372 372 if isinstance(changeid, basectx):
373 373 return
374 374
375 375 if changeid == '':
376 376 changeid = '.'
377 377 self._repo = repo
378 378
379 379 if isinstance(changeid, int):
380 380 try:
381 381 self._node = repo.changelog.node(changeid)
382 382 except IndexError:
383 383 raise error.RepoLookupError(
384 384 _("unknown revision '%s'") % changeid)
385 385 self._rev = changeid
386 386 return
387 387 if isinstance(changeid, long):
388 388 changeid = str(changeid)
389 389 if changeid == '.':
390 390 self._node = repo.dirstate.p1()
391 391 self._rev = repo.changelog.rev(self._node)
392 392 return
393 393 if changeid == 'null':
394 394 self._node = nullid
395 395 self._rev = nullrev
396 396 return
397 397 if changeid == 'tip':
398 398 self._node = repo.changelog.tip()
399 399 self._rev = repo.changelog.rev(self._node)
400 400 return
401 401 if len(changeid) == 20:
402 402 try:
403 403 self._node = changeid
404 404 self._rev = repo.changelog.rev(changeid)
405 405 return
406 406 except LookupError:
407 407 pass
408 408
409 409 try:
410 410 r = int(changeid)
411 411 if str(r) != changeid:
412 412 raise ValueError
413 413 l = len(repo.changelog)
414 414 if r < 0:
415 415 r += l
416 416 if r < 0 or r >= l:
417 417 raise ValueError
418 418 self._rev = r
419 419 self._node = repo.changelog.node(r)
420 420 return
421 421 except (ValueError, OverflowError, IndexError):
422 422 pass
423 423
424 424 if len(changeid) == 40:
425 425 try:
426 426 self._node = bin(changeid)
427 427 self._rev = repo.changelog.rev(self._node)
428 428 return
429 429 except (TypeError, LookupError):
430 430 pass
431 431
432 432 if changeid in repo._bookmarks:
433 433 self._node = repo._bookmarks[changeid]
434 434 self._rev = repo.changelog.rev(self._node)
435 435 return
436 436 if changeid in repo._tagscache.tags:
437 437 self._node = repo._tagscache.tags[changeid]
438 438 self._rev = repo.changelog.rev(self._node)
439 439 return
440 440 try:
441 441 self._node = repo.branchtip(changeid)
442 442 self._rev = repo.changelog.rev(self._node)
443 443 return
444 444 except error.RepoLookupError:
445 445 pass
446 446
447 447 self._node = repo.changelog._partialmatch(changeid)
448 448 if self._node is not None:
449 449 self._rev = repo.changelog.rev(self._node)
450 450 return
451 451
452 452 # lookup failed
453 453 # check if it might have come from damaged dirstate
454 454 #
455 455 # XXX we could avoid the unfiltered if we had a recognizable exception
456 456 # for filtered changeset access
457 457 if changeid in repo.unfiltered().dirstate.parents():
458 458 raise error.Abort(_("working directory has unknown parent '%s'!")
459 459 % short(changeid))
460 460 try:
461 461 if len(changeid) == 20:
462 462 changeid = hex(changeid)
463 463 except TypeError:
464 464 pass
465 465 raise error.RepoLookupError(
466 466 _("unknown revision '%s'") % changeid)
467 467
468 468 def __hash__(self):
469 469 try:
470 470 return hash(self._rev)
471 471 except AttributeError:
472 472 return id(self)
473 473
474 474 def __nonzero__(self):
475 475 return self._rev != nullrev
476 476
477 477 @propertycache
478 478 def _changeset(self):
479 479 return self._repo.changelog.read(self.rev())
480 480
481 481 @propertycache
482 482 def _manifest(self):
483 483 return self._repo.manifest.read(self._changeset[0])
484 484
485 485 @propertycache
486 486 def _manifestdelta(self):
487 487 return self._repo.manifest.readdelta(self._changeset[0])
488 488
489 489 @propertycache
490 490 def _parents(self):
491 491 p = self._repo.changelog.parentrevs(self._rev)
492 492 if p[1] == nullrev:
493 493 p = p[:-1]
494 494 return [changectx(self._repo, x) for x in p]
495 495
496 496 def changeset(self):
497 497 return self._changeset
498 498 def manifestnode(self):
499 499 return self._changeset[0]
500 500
501 501 def user(self):
502 502 return self._changeset[1]
503 503 def date(self):
504 504 return self._changeset[2]
505 505 def files(self):
506 506 return self._changeset[3]
507 507 def description(self):
508 508 return self._changeset[4]
509 509 def branch(self):
510 510 return encoding.tolocal(self._changeset[5].get("branch"))
511 511 def closesbranch(self):
512 512 return 'close' in self._changeset[5]
513 513 def extra(self):
514 514 return self._changeset[5]
515 515 def tags(self):
516 516 return self._repo.nodetags(self._node)
517 517 def bookmarks(self):
518 518 return self._repo.nodebookmarks(self._node)
519 519 def phase(self):
520 520 return self._repo._phasecache.phase(self._repo, self._rev)
521 521 def hidden(self):
522 522 return self._rev in repoview.filterrevs(self._repo, 'visible')
523 523
524 524 def children(self):
525 525 """return contexts for each child changeset"""
526 526 c = self._repo.changelog.children(self._node)
527 527 return [changectx(self._repo, x) for x in c]
528 528
529 529 def ancestors(self):
530 530 for a in self._repo.changelog.ancestors([self._rev]):
531 531 yield changectx(self._repo, a)
532 532
533 533 def descendants(self):
534 534 for d in self._repo.changelog.descendants([self._rev]):
535 535 yield changectx(self._repo, d)
536 536
537 537 def filectx(self, path, fileid=None, filelog=None):
538 538 """get a file context from this changeset"""
539 539 if fileid is None:
540 540 fileid = self.filenode(path)
541 541 return filectx(self._repo, path, fileid=fileid,
542 542 changectx=self, filelog=filelog)
543 543
544 544 def ancestor(self, c2, warn=False):
545 545 """return the "best" ancestor context of self and c2
546 546
547 547 If there are multiple candidates, it will show a message and check
548 548 merge.preferancestor configuration before falling back to the
549 549 revlog ancestor."""
550 550 # deal with workingctxs
551 551 n2 = c2._node
552 552 if n2 is None:
553 553 n2 = c2._parents[0]._node
554 554 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
555 555 if not cahs:
556 556 anc = nullid
557 557 elif len(cahs) == 1:
558 558 anc = cahs[0]
559 559 else:
560 560 for r in self._repo.ui.configlist('merge', 'preferancestor'):
561 561 try:
562 562 ctx = changectx(self._repo, r)
563 563 except error.RepoLookupError:
564 564 continue
565 565 anc = ctx.node()
566 566 if anc in cahs:
567 567 break
568 568 else:
569 569 anc = self._repo.changelog.ancestor(self._node, n2)
570 570 if warn:
571 571 self._repo.ui.status(
572 572 (_("note: using %s as ancestor of %s and %s\n") %
573 573 (short(anc), short(self._node), short(n2))) +
574 574 ''.join(_(" alternatively, use --config "
575 575 "merge.preferancestor=%s\n") %
576 576 short(n) for n in sorted(cahs) if n != anc))
577 577 return changectx(self._repo, anc)
578 578
579 579 def descendant(self, other):
580 580 """True if other is descendant of this changeset"""
581 581 return self._repo.changelog.descendant(self._rev, other._rev)
582 582
583 583 def walk(self, match):
584 584 fset = set(match.files())
585 585 # for dirstate.walk, files=['.'] means "walk the whole tree".
586 586 # follow that here, too
587 587 fset.discard('.')
588 588
589 589 # avoid the entire walk if we're only looking for specific files
590 590 if fset and not match.anypats():
591 591 if util.all([fn in self for fn in fset]):
592 592 for fn in sorted(fset):
593 593 if match(fn):
594 594 yield fn
595 595 raise StopIteration
596 596
597 597 for fn in self:
598 598 if fn in fset:
599 599 # specified pattern is the exact name
600 600 fset.remove(fn)
601 601 if match(fn):
602 602 yield fn
603 603 for fn in sorted(fset):
604 604 if fn in self._dirs:
605 605 # specified pattern is a directory
606 606 continue
607 607 match.bad(fn, _('no such file in rev %s') % self)
608 608
609 609 def matches(self, match):
610 610 return self.walk(match)
611 611
612 612 class basefilectx(object):
613 613 """A filecontext object represents the common logic for its children:
614 614 filectx: read-only access to a filerevision that is already present
615 615 in the repo,
616 616 workingfilectx: a filecontext that represents files from the working
617 617 directory,
618 618 memfilectx: a filecontext that represents files in-memory."""
619 619 def __new__(cls, repo, path, *args, **kwargs):
620 620 return super(basefilectx, cls).__new__(cls)
621 621
622 622 @propertycache
623 623 def _filelog(self):
624 624 return self._repo.file(self._path)
625 625
626 626 @propertycache
627 627 def _changeid(self):
628 628 if '_changeid' in self.__dict__:
629 629 return self._changeid
630 630 elif '_changectx' in self.__dict__:
631 631 return self._changectx.rev()
632 632 else:
633 633 return self._filelog.linkrev(self._filerev)
634 634
635 635 @propertycache
636 636 def _filenode(self):
637 637 if '_fileid' in self.__dict__:
638 638 return self._filelog.lookup(self._fileid)
639 639 else:
640 640 return self._changectx.filenode(self._path)
641 641
642 642 @propertycache
643 643 def _filerev(self):
644 644 return self._filelog.rev(self._filenode)
645 645
646 646 @propertycache
647 647 def _repopath(self):
648 648 return self._path
649 649
650 650 def __nonzero__(self):
651 651 try:
652 652 self._filenode
653 653 return True
654 654 except error.LookupError:
655 655 # file is missing
656 656 return False
657 657
658 658 def __str__(self):
659 659 return "%s@%s" % (self.path(), self._changectx)
660 660
661 661 def __repr__(self):
662 662 return "<%s %s>" % (type(self).__name__, str(self))
663 663
664 664 def __hash__(self):
665 665 try:
666 666 return hash((self._path, self._filenode))
667 667 except AttributeError:
668 668 return id(self)
669 669
670 670 def __eq__(self, other):
671 671 try:
672 672 return (type(self) == type(other) and self._path == other._path
673 673 and self._filenode == other._filenode)
674 674 except AttributeError:
675 675 return False
676 676
677 677 def __ne__(self, other):
678 678 return not (self == other)
679 679
680 680 def filerev(self):
681 681 return self._filerev
682 682 def filenode(self):
683 683 return self._filenode
684 684 def flags(self):
685 685 return self._changectx.flags(self._path)
686 686 def filelog(self):
687 687 return self._filelog
688 688 def rev(self):
689 689 return self._changeid
690 690 def linkrev(self):
691 691 return self._filelog.linkrev(self._filerev)
692 692 def node(self):
693 693 return self._changectx.node()
694 694 def hex(self):
695 695 return self._changectx.hex()
696 696 def user(self):
697 697 return self._changectx.user()
698 698 def date(self):
699 699 return self._changectx.date()
700 700 def files(self):
701 701 return self._changectx.files()
702 702 def description(self):
703 703 return self._changectx.description()
704 704 def branch(self):
705 705 return self._changectx.branch()
706 706 def extra(self):
707 707 return self._changectx.extra()
708 708 def phase(self):
709 709 return self._changectx.phase()
710 710 def phasestr(self):
711 711 return self._changectx.phasestr()
712 712 def manifest(self):
713 713 return self._changectx.manifest()
714 714 def changectx(self):
715 715 return self._changectx
716 716
717 717 def path(self):
718 718 return self._path
719 719
720 720 def isbinary(self):
721 721 try:
722 722 return util.binary(self.data())
723 723 except IOError:
724 724 return False
725 725 def isexec(self):
726 726 return 'x' in self.flags()
727 727 def islink(self):
728 728 return 'l' in self.flags()
729 729
730 730 def cmp(self, fctx):
731 731 """compare with other file context
732 732
733 733 returns True if different than fctx.
734 734 """
735 735 if (fctx._filerev is None
736 736 and (self._repo._encodefilterpats
737 737 # if file data starts with '\1\n', empty metadata block is
738 738 # prepended, which adds 4 bytes to filelog.size().
739 739 or self.size() - 4 == fctx.size())
740 740 or self.size() == fctx.size()):
741 741 return self._filelog.cmp(self._filenode, fctx.data())
742 742
743 743 return True
744 744
745 745 def parents(self):
746 746 _path = self._path
747 747 fl = self._filelog
748 748 pl = [(_path, n, fl) for n in self._filelog.parents(self._filenode)]
749 749
750 750 r = self._filelog.renamed(self._filenode)
751 751 if r:
752 752 pl[0] = (r[0], r[1], None)
753 753
754 754 return [filectx(self._repo, p, fileid=n, filelog=l)
755 755 for p, n, l in pl if n != nullid]
756 756
757 757 def p1(self):
758 758 return self.parents()[0]
759 759
760 760 def p2(self):
761 761 p = self.parents()
762 762 if len(p) == 2:
763 763 return p[1]
764 764 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
765 765
766 766 def annotate(self, follow=False, linenumber=None, diffopts=None):
767 767 '''returns a list of tuples of (ctx, line) for each line
768 768 in the file, where ctx is the filectx of the node where
769 769 that line was last changed.
770 770 This returns tuples of ((ctx, linenumber), line) for each line,
771 771 if "linenumber" parameter is NOT "None".
772 772 In such tuples, linenumber means one at the first appearance
773 773 in the managed file.
774 774 To reduce annotation cost,
775 775 this returns fixed value(False is used) as linenumber,
776 776 if "linenumber" parameter is "False".'''
777 777
778 778 if linenumber is None:
779 779 def decorate(text, rev):
780 780 return ([rev] * len(text.splitlines()), text)
781 781 elif linenumber:
782 782 def decorate(text, rev):
783 783 size = len(text.splitlines())
784 784 return ([(rev, i) for i in xrange(1, size + 1)], text)
785 785 else:
786 786 def decorate(text, rev):
787 787 return ([(rev, False)] * len(text.splitlines()), text)
788 788
789 789 def pair(parent, child):
790 790 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
791 791 refine=True)
792 792 for (a1, a2, b1, b2), t in blocks:
793 793 # Changed blocks ('!') or blocks made only of blank lines ('~')
794 794 # belong to the child.
795 795 if t == '=':
796 796 child[0][b1:b2] = parent[0][a1:a2]
797 797 return child
798 798
799 799 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
800 800
801 801 def parents(f):
802 802 pl = f.parents()
803 803
804 804 # Don't return renamed parents if we aren't following.
805 805 if not follow:
806 806 pl = [p for p in pl if p.path() == f.path()]
807 807
808 808 # renamed filectx won't have a filelog yet, so set it
809 809 # from the cache to save time
810 810 for p in pl:
811 811 if not '_filelog' in p.__dict__:
812 812 p._filelog = getlog(p.path())
813 813
814 814 return pl
815 815
816 816 # use linkrev to find the first changeset where self appeared
817 817 if self.rev() != self.linkrev():
818 818 base = self.filectx(self.filenode())
819 819 else:
820 820 base = self
821 821
822 822 # This algorithm would prefer to be recursive, but Python is a
823 823 # bit recursion-hostile. Instead we do an iterative
824 824 # depth-first search.
825 825
826 826 visit = [base]
827 827 hist = {}
828 828 pcache = {}
829 829 needed = {base: 1}
830 830 while visit:
831 831 f = visit[-1]
832 832 pcached = f in pcache
833 833 if not pcached:
834 834 pcache[f] = parents(f)
835 835
836 836 ready = True
837 837 pl = pcache[f]
838 838 for p in pl:
839 839 if p not in hist:
840 840 ready = False
841 841 visit.append(p)
842 842 if not pcached:
843 843 needed[p] = needed.get(p, 0) + 1
844 844 if ready:
845 845 visit.pop()
846 846 reusable = f in hist
847 847 if reusable:
848 848 curr = hist[f]
849 849 else:
850 850 curr = decorate(f.data(), f)
851 851 for p in pl:
852 852 if not reusable:
853 853 curr = pair(hist[p], curr)
854 854 if needed[p] == 1:
855 855 del hist[p]
856 856 del needed[p]
857 857 else:
858 858 needed[p] -= 1
859 859
860 860 hist[f] = curr
861 861 pcache[f] = []
862 862
863 863 return zip(hist[base][0], hist[base][1].splitlines(True))
864 864
865 865 def ancestors(self, followfirst=False):
866 866 visit = {}
867 867 c = self
868 868 cut = followfirst and 1 or None
869 869 while True:
870 870 for parent in c.parents()[:cut]:
871 871 visit[(parent.rev(), parent.node())] = parent
872 872 if not visit:
873 873 break
874 874 c = visit.pop(max(visit))
875 875 yield c
876 876
877 877 class filectx(basefilectx):
878 878 """A filecontext object makes access to data related to a particular
879 879 filerevision convenient."""
880 880 def __init__(self, repo, path, changeid=None, fileid=None,
881 881 filelog=None, changectx=None):
882 882 """changeid can be a changeset revision, node, or tag.
883 883 fileid can be a file revision or node."""
884 884 self._repo = repo
885 885 self._path = path
886 886
887 887 assert (changeid is not None
888 888 or fileid is not None
889 889 or changectx is not None), \
890 890 ("bad args: changeid=%r, fileid=%r, changectx=%r"
891 891 % (changeid, fileid, changectx))
892 892
893 893 if filelog is not None:
894 894 self._filelog = filelog
895 895
896 896 if changeid is not None:
897 897 self._changeid = changeid
898 898 if changectx is not None:
899 899 self._changectx = changectx
900 900 if fileid is not None:
901 901 self._fileid = fileid
902 902
903 903 @propertycache
904 904 def _changectx(self):
905 905 try:
906 906 return changectx(self._repo, self._changeid)
907 907 except error.RepoLookupError:
908 908 # Linkrev may point to any revision in the repository. When the
909 909 # repository is filtered this may lead to `filectx` trying to build
910 910 # `changectx` for filtered revision. In such case we fallback to
911 911 # creating `changectx` on the unfiltered version of the reposition.
912 912 # This fallback should not be an issue because `changectx` from
913 913 # `filectx` are not used in complex operations that care about
914 914 # filtering.
915 915 #
916 916 # This fallback is a cheap and dirty fix that prevent several
917 917 # crashes. It does not ensure the behavior is correct. However the
918 918 # behavior was not correct before filtering either and "incorrect
919 919 # behavior" is seen as better as "crash"
920 920 #
921 921 # Linkrevs have several serious troubles with filtering that are
922 922 # complicated to solve. Proper handling of the issue here should be
923 923 # considered when solving linkrev issue are on the table.
924 924 return changectx(self._repo.unfiltered(), self._changeid)
925 925
926 926 def filectx(self, fileid):
927 927 '''opens an arbitrary revision of the file without
928 928 opening a new filelog'''
929 929 return filectx(self._repo, self._path, fileid=fileid,
930 930 filelog=self._filelog)
931 931
932 932 def data(self):
933 return self._filelog.read(self._filenode)
933 try:
934 return self._filelog.read(self._filenode)
935 except error.CensoredNodeError:
936 if self._repo.ui.config("censor", "policy", "abort") == "ignore":
937 return ""
938 raise util.Abort(_("censored node: %s") % short(self._filenode),
939 hint="set censor.policy to ignore errors")
940
934 941 def size(self):
935 942 return self._filelog.size(self._filerev)
936 943
937 944 def renamed(self):
938 945 """check if file was actually renamed in this changeset revision
939 946
940 947 If rename logged in file revision, we report copy for changeset only
941 948 if file revisions linkrev points back to the changeset in question
942 949 or both changeset parents contain different file revisions.
943 950 """
944 951
945 952 renamed = self._filelog.renamed(self._filenode)
946 953 if not renamed:
947 954 return renamed
948 955
949 956 if self.rev() == self.linkrev():
950 957 return renamed
951 958
952 959 name = self.path()
953 960 fnode = self._filenode
954 961 for p in self._changectx.parents():
955 962 try:
956 963 if fnode == p.filenode(name):
957 964 return None
958 965 except error.LookupError:
959 966 pass
960 967 return renamed
961 968
962 969 def children(self):
963 970 # hard for renames
964 971 c = self._filelog.children(self._filenode)
965 972 return [filectx(self._repo, self._path, fileid=x,
966 973 filelog=self._filelog) for x in c]
967 974
968 975 class committablectx(basectx):
969 976 """A committablectx object provides common functionality for a context that
970 977 wants the ability to commit, e.g. workingctx or memctx."""
971 978 def __init__(self, repo, text="", user=None, date=None, extra=None,
972 979 changes=None):
973 980 self._repo = repo
974 981 self._rev = None
975 982 self._node = None
976 983 self._text = text
977 984 if date:
978 985 self._date = util.parsedate(date)
979 986 if user:
980 987 self._user = user
981 988 if changes:
982 989 self._status = changes
983 990
984 991 self._extra = {}
985 992 if extra:
986 993 self._extra = extra.copy()
987 994 if 'branch' not in self._extra:
988 995 try:
989 996 branch = encoding.fromlocal(self._repo.dirstate.branch())
990 997 except UnicodeDecodeError:
991 998 raise util.Abort(_('branch name not in UTF-8!'))
992 999 self._extra['branch'] = branch
993 1000 if self._extra['branch'] == '':
994 1001 self._extra['branch'] = 'default'
995 1002
996 1003 def __str__(self):
997 1004 return str(self._parents[0]) + "+"
998 1005
999 1006 def __nonzero__(self):
1000 1007 return True
1001 1008
1002 1009 def _buildflagfunc(self):
1003 1010 # Create a fallback function for getting file flags when the
1004 1011 # filesystem doesn't support them
1005 1012
1006 1013 copiesget = self._repo.dirstate.copies().get
1007 1014
1008 1015 if len(self._parents) < 2:
1009 1016 # when we have one parent, it's easy: copy from parent
1010 1017 man = self._parents[0].manifest()
1011 1018 def func(f):
1012 1019 f = copiesget(f, f)
1013 1020 return man.flags(f)
1014 1021 else:
1015 1022 # merges are tricky: we try to reconstruct the unstored
1016 1023 # result from the merge (issue1802)
1017 1024 p1, p2 = self._parents
1018 1025 pa = p1.ancestor(p2)
1019 1026 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1020 1027
1021 1028 def func(f):
1022 1029 f = copiesget(f, f) # may be wrong for merges with copies
1023 1030 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1024 1031 if fl1 == fl2:
1025 1032 return fl1
1026 1033 if fl1 == fla:
1027 1034 return fl2
1028 1035 if fl2 == fla:
1029 1036 return fl1
1030 1037 return '' # punt for conflicts
1031 1038
1032 1039 return func
1033 1040
1034 1041 @propertycache
1035 1042 def _flagfunc(self):
1036 1043 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1037 1044
1038 1045 @propertycache
1039 1046 def _manifest(self):
1040 1047 """generate a manifest corresponding to the values in self._status"""
1041 1048
1042 1049 man = self._parents[0].manifest().copy()
1043 1050 if len(self._parents) > 1:
1044 1051 man2 = self.p2().manifest()
1045 1052 def getman(f):
1046 1053 if f in man:
1047 1054 return man
1048 1055 return man2
1049 1056 else:
1050 1057 getman = lambda f: man
1051 1058
1052 1059 copied = self._repo.dirstate.copies()
1053 1060 ff = self._flagfunc
1054 1061 for i, l in (("a", self._status.added), ("m", self._status.modified)):
1055 1062 for f in l:
1056 1063 orig = copied.get(f, f)
1057 1064 man[f] = getman(orig).get(orig, nullid) + i
1058 1065 try:
1059 1066 man.set(f, ff(f))
1060 1067 except OSError:
1061 1068 pass
1062 1069
1063 1070 for f in self._status.deleted + self._status.removed:
1064 1071 if f in man:
1065 1072 del man[f]
1066 1073
1067 1074 return man
1068 1075
1069 1076 @propertycache
1070 1077 def _status(self):
1071 1078 return self._repo.status()
1072 1079
1073 1080 @propertycache
1074 1081 def _user(self):
1075 1082 return self._repo.ui.username()
1076 1083
1077 1084 @propertycache
1078 1085 def _date(self):
1079 1086 return util.makedate()
1080 1087
1081 1088 def subrev(self, subpath):
1082 1089 return None
1083 1090
1084 1091 def user(self):
1085 1092 return self._user or self._repo.ui.username()
1086 1093 def date(self):
1087 1094 return self._date
1088 1095 def description(self):
1089 1096 return self._text
1090 1097 def files(self):
1091 1098 return sorted(self._status.modified + self._status.added +
1092 1099 self._status.removed)
1093 1100
1094 1101 def modified(self):
1095 1102 return self._status.modified
1096 1103 def added(self):
1097 1104 return self._status.added
1098 1105 def removed(self):
1099 1106 return self._status.removed
1100 1107 def deleted(self):
1101 1108 return self._status.deleted
1102 1109 def unknown(self):
1103 1110 return self._status.unknown
1104 1111 def ignored(self):
1105 1112 return self._status.ignored
1106 1113 def clean(self):
1107 1114 return self._status.clean
1108 1115 def branch(self):
1109 1116 return encoding.tolocal(self._extra['branch'])
1110 1117 def closesbranch(self):
1111 1118 return 'close' in self._extra
1112 1119 def extra(self):
1113 1120 return self._extra
1114 1121
1115 1122 def tags(self):
1116 1123 t = []
1117 1124 for p in self.parents():
1118 1125 t.extend(p.tags())
1119 1126 return t
1120 1127
1121 1128 def bookmarks(self):
1122 1129 b = []
1123 1130 for p in self.parents():
1124 1131 b.extend(p.bookmarks())
1125 1132 return b
1126 1133
1127 1134 def phase(self):
1128 1135 phase = phases.draft # default phase to draft
1129 1136 for p in self.parents():
1130 1137 phase = max(phase, p.phase())
1131 1138 return phase
1132 1139
1133 1140 def hidden(self):
1134 1141 return False
1135 1142
1136 1143 def children(self):
1137 1144 return []
1138 1145
1139 1146 def flags(self, path):
1140 1147 if '_manifest' in self.__dict__:
1141 1148 try:
1142 1149 return self._manifest.flags(path)
1143 1150 except KeyError:
1144 1151 return ''
1145 1152
1146 1153 try:
1147 1154 return self._flagfunc(path)
1148 1155 except OSError:
1149 1156 return ''
1150 1157
1151 1158 def ancestor(self, c2):
1152 1159 """return the "best" ancestor context of self and c2"""
1153 1160 return self._parents[0].ancestor(c2) # punt on two parents for now
1154 1161
1155 1162 def walk(self, match):
1156 1163 return sorted(self._repo.dirstate.walk(match, sorted(self.substate),
1157 1164 True, False))
1158 1165
1159 1166 def matches(self, match):
1160 1167 return sorted(self._repo.dirstate.matches(match))
1161 1168
1162 1169 def ancestors(self):
1163 1170 for a in self._repo.changelog.ancestors(
1164 1171 [p.rev() for p in self._parents]):
1165 1172 yield changectx(self._repo, a)
1166 1173
1167 1174 def markcommitted(self, node):
1168 1175 """Perform post-commit cleanup necessary after committing this ctx
1169 1176
1170 1177 Specifically, this updates backing stores this working context
1171 1178 wraps to reflect the fact that the changes reflected by this
1172 1179 workingctx have been committed. For example, it marks
1173 1180 modified and added files as normal in the dirstate.
1174 1181
1175 1182 """
1176 1183
1177 1184 self._repo.dirstate.beginparentchange()
1178 1185 for f in self.modified() + self.added():
1179 1186 self._repo.dirstate.normal(f)
1180 1187 for f in self.removed():
1181 1188 self._repo.dirstate.drop(f)
1182 1189 self._repo.dirstate.setparents(node)
1183 1190 self._repo.dirstate.endparentchange()
1184 1191
1185 1192 def dirs(self):
1186 1193 return self._repo.dirstate.dirs()
1187 1194
1188 1195 class workingctx(committablectx):
1189 1196 """A workingctx object makes access to data related to
1190 1197 the current working directory convenient.
1191 1198 date - any valid date string or (unixtime, offset), or None.
1192 1199 user - username string, or None.
1193 1200 extra - a dictionary of extra values, or None.
1194 1201 changes - a list of file lists as returned by localrepo.status()
1195 1202 or None to use the repository status.
1196 1203 """
1197 1204 def __init__(self, repo, text="", user=None, date=None, extra=None,
1198 1205 changes=None):
1199 1206 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1200 1207
1201 1208 def __iter__(self):
1202 1209 d = self._repo.dirstate
1203 1210 for f in d:
1204 1211 if d[f] != 'r':
1205 1212 yield f
1206 1213
1207 1214 def __contains__(self, key):
1208 1215 return self._repo.dirstate[key] not in "?r"
1209 1216
1210 1217 @propertycache
1211 1218 def _parents(self):
1212 1219 p = self._repo.dirstate.parents()
1213 1220 if p[1] == nullid:
1214 1221 p = p[:-1]
1215 1222 return [changectx(self._repo, x) for x in p]
1216 1223
1217 1224 def filectx(self, path, filelog=None):
1218 1225 """get a file context from the working directory"""
1219 1226 return workingfilectx(self._repo, path, workingctx=self,
1220 1227 filelog=filelog)
1221 1228
1222 1229 def dirty(self, missing=False, merge=True, branch=True):
1223 1230 "check whether a working directory is modified"
1224 1231 # check subrepos first
1225 1232 for s in sorted(self.substate):
1226 1233 if self.sub(s).dirty():
1227 1234 return True
1228 1235 # check current working dir
1229 1236 return ((merge and self.p2()) or
1230 1237 (branch and self.branch() != self.p1().branch()) or
1231 1238 self.modified() or self.added() or self.removed() or
1232 1239 (missing and self.deleted()))
1233 1240
1234 1241 def add(self, list, prefix=""):
1235 1242 join = lambda f: os.path.join(prefix, f)
1236 1243 wlock = self._repo.wlock()
1237 1244 ui, ds = self._repo.ui, self._repo.dirstate
1238 1245 try:
1239 1246 rejected = []
1240 1247 lstat = self._repo.wvfs.lstat
1241 1248 for f in list:
1242 1249 scmutil.checkportable(ui, join(f))
1243 1250 try:
1244 1251 st = lstat(f)
1245 1252 except OSError:
1246 1253 ui.warn(_("%s does not exist!\n") % join(f))
1247 1254 rejected.append(f)
1248 1255 continue
1249 1256 if st.st_size > 10000000:
1250 1257 ui.warn(_("%s: up to %d MB of RAM may be required "
1251 1258 "to manage this file\n"
1252 1259 "(use 'hg revert %s' to cancel the "
1253 1260 "pending addition)\n")
1254 1261 % (f, 3 * st.st_size // 1000000, join(f)))
1255 1262 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1256 1263 ui.warn(_("%s not added: only files and symlinks "
1257 1264 "supported currently\n") % join(f))
1258 1265 rejected.append(f)
1259 1266 elif ds[f] in 'amn':
1260 1267 ui.warn(_("%s already tracked!\n") % join(f))
1261 1268 elif ds[f] == 'r':
1262 1269 ds.normallookup(f)
1263 1270 else:
1264 1271 ds.add(f)
1265 1272 return rejected
1266 1273 finally:
1267 1274 wlock.release()
1268 1275
1269 1276 def forget(self, files, prefix=""):
1270 1277 join = lambda f: os.path.join(prefix, f)
1271 1278 wlock = self._repo.wlock()
1272 1279 try:
1273 1280 rejected = []
1274 1281 for f in files:
1275 1282 if f not in self._repo.dirstate:
1276 1283 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1277 1284 rejected.append(f)
1278 1285 elif self._repo.dirstate[f] != 'a':
1279 1286 self._repo.dirstate.remove(f)
1280 1287 else:
1281 1288 self._repo.dirstate.drop(f)
1282 1289 return rejected
1283 1290 finally:
1284 1291 wlock.release()
1285 1292
1286 1293 def undelete(self, list):
1287 1294 pctxs = self.parents()
1288 1295 wlock = self._repo.wlock()
1289 1296 try:
1290 1297 for f in list:
1291 1298 if self._repo.dirstate[f] != 'r':
1292 1299 self._repo.ui.warn(_("%s not removed!\n") % f)
1293 1300 else:
1294 1301 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1295 1302 t = fctx.data()
1296 1303 self._repo.wwrite(f, t, fctx.flags())
1297 1304 self._repo.dirstate.normal(f)
1298 1305 finally:
1299 1306 wlock.release()
1300 1307
1301 1308 def copy(self, source, dest):
1302 1309 try:
1303 1310 st = self._repo.wvfs.lstat(dest)
1304 1311 except OSError, err:
1305 1312 if err.errno != errno.ENOENT:
1306 1313 raise
1307 1314 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1308 1315 return
1309 1316 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1310 1317 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1311 1318 "symbolic link\n") % dest)
1312 1319 else:
1313 1320 wlock = self._repo.wlock()
1314 1321 try:
1315 1322 if self._repo.dirstate[dest] in '?r':
1316 1323 self._repo.dirstate.add(dest)
1317 1324 self._repo.dirstate.copy(source, dest)
1318 1325 finally:
1319 1326 wlock.release()
1320 1327
1321 1328 def _filtersuspectsymlink(self, files):
1322 1329 if not files or self._repo.dirstate._checklink:
1323 1330 return files
1324 1331
1325 1332 # Symlink placeholders may get non-symlink-like contents
1326 1333 # via user error or dereferencing by NFS or Samba servers,
1327 1334 # so we filter out any placeholders that don't look like a
1328 1335 # symlink
1329 1336 sane = []
1330 1337 for f in files:
1331 1338 if self.flags(f) == 'l':
1332 1339 d = self[f].data()
1333 1340 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1334 1341 self._repo.ui.debug('ignoring suspect symlink placeholder'
1335 1342 ' "%s"\n' % f)
1336 1343 continue
1337 1344 sane.append(f)
1338 1345 return sane
1339 1346
1340 1347 def _checklookup(self, files):
1341 1348 # check for any possibly clean files
1342 1349 if not files:
1343 1350 return [], []
1344 1351
1345 1352 modified = []
1346 1353 fixup = []
1347 1354 pctx = self._parents[0]
1348 1355 # do a full compare of any files that might have changed
1349 1356 for f in sorted(files):
1350 1357 if (f not in pctx or self.flags(f) != pctx.flags(f)
1351 1358 or pctx[f].cmp(self[f])):
1352 1359 modified.append(f)
1353 1360 else:
1354 1361 fixup.append(f)
1355 1362
1356 1363 # update dirstate for files that are actually clean
1357 1364 if fixup:
1358 1365 try:
1359 1366 # updating the dirstate is optional
1360 1367 # so we don't wait on the lock
1361 1368 # wlock can invalidate the dirstate, so cache normal _after_
1362 1369 # taking the lock
1363 1370 wlock = self._repo.wlock(False)
1364 1371 normal = self._repo.dirstate.normal
1365 1372 try:
1366 1373 for f in fixup:
1367 1374 normal(f)
1368 1375 finally:
1369 1376 wlock.release()
1370 1377 except error.LockError:
1371 1378 pass
1372 1379 return modified, fixup
1373 1380
1374 1381 def _manifestmatches(self, match, s):
1375 1382 """Slow path for workingctx
1376 1383
1377 1384 The fast path is when we compare the working directory to its parent
1378 1385 which means this function is comparing with a non-parent; therefore we
1379 1386 need to build a manifest and return what matches.
1380 1387 """
1381 1388 mf = self._repo['.']._manifestmatches(match, s)
1382 1389 modified, added, removed = s[0:3]
1383 1390 for f in modified + added:
1384 1391 mf[f] = None
1385 1392 mf.set(f, self.flags(f))
1386 1393 for f in removed:
1387 1394 if f in mf:
1388 1395 del mf[f]
1389 1396 return mf
1390 1397
1391 1398 def _prestatus(self, other, s, match, listignored, listclean, listunknown):
1392 1399 """override the parent hook with a dirstate query
1393 1400
1394 1401 We use this prestatus hook to populate the status with information from
1395 1402 the dirstate.
1396 1403 """
1397 1404 # doesn't need to call super; if that changes, be aware that super
1398 1405 # calls self.manifest which would slow down the common case of calling
1399 1406 # status against a workingctx's parent
1400 1407 return self._dirstatestatus(match, listignored, listclean, listunknown)
1401 1408
1402 1409 def _poststatus(self, other, s, match, listignored, listclean, listunknown):
1403 1410 """override the parent hook with a filter for suspect symlinks
1404 1411
1405 1412 We use this poststatus hook to filter out symlinks that might have
1406 1413 accidentally ended up with the entire contents of the file they are
1407 1414 susposed to be linking to.
1408 1415 """
1409 1416 s[0] = self._filtersuspectsymlink(s[0])
1410 1417 self._status = scmutil.status(*s)
1411 1418 return s
1412 1419
1413 1420 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1414 1421 unknown=False):
1415 1422 '''Gets the status from the dirstate -- internal use only.'''
1416 1423 listignored, listclean, listunknown = ignored, clean, unknown
1417 1424 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1418 1425 subrepos = []
1419 1426 if '.hgsub' in self:
1420 1427 subrepos = sorted(self.substate)
1421 1428 cmp, s = self._repo.dirstate.status(match, subrepos, listignored,
1422 1429 listclean, listunknown)
1423 1430 modified, added, removed, deleted, unknown, ignored, clean = s
1424 1431
1425 1432 # check for any possibly clean files
1426 1433 if cmp:
1427 1434 modified2, fixup = self._checklookup(cmp)
1428 1435 modified += modified2
1429 1436
1430 1437 # update dirstate for files that are actually clean
1431 1438 if fixup and listclean:
1432 1439 clean += fixup
1433 1440
1434 1441 return [modified, added, removed, deleted, unknown, ignored, clean]
1435 1442
1436 1443 def _buildstatus(self, other, s, match, listignored, listclean,
1437 1444 listunknown):
1438 1445 """build a status with respect to another context
1439 1446
1440 1447 This includes logic for maintaining the fast path of status when
1441 1448 comparing the working directory against its parent, which is to skip
1442 1449 building a new manifest if self (working directory) is not comparing
1443 1450 against its parent (repo['.']).
1444 1451 """
1445 1452 if other != self._repo['.']:
1446 1453 s = super(workingctx, self)._buildstatus(other, s, match,
1447 1454 listignored, listclean,
1448 1455 listunknown)
1449 1456 return s
1450 1457
1451 1458 def _matchstatus(self, other, s, match, listignored, listclean,
1452 1459 listunknown):
1453 1460 """override the match method with a filter for directory patterns
1454 1461
1455 1462 We use inheritance to customize the match.bad method only in cases of
1456 1463 workingctx since it belongs only to the working directory when
1457 1464 comparing against the parent changeset.
1458 1465
1459 1466 If we aren't comparing against the working directory's parent, then we
1460 1467 just use the default match object sent to us.
1461 1468 """
1462 1469 superself = super(workingctx, self)
1463 1470 match = superself._matchstatus(other, s, match, listignored, listclean,
1464 1471 listunknown)
1465 1472 if other != self._repo['.']:
1466 1473 def bad(f, msg):
1467 1474 # 'f' may be a directory pattern from 'match.files()',
1468 1475 # so 'f not in ctx1' is not enough
1469 1476 if f not in other and f not in other.dirs():
1470 1477 self._repo.ui.warn('%s: %s\n' %
1471 1478 (self._repo.dirstate.pathto(f), msg))
1472 1479 match.bad = bad
1473 1480 return match
1474 1481
1475 1482 def status(self, other='.', match=None, listignored=False,
1476 1483 listclean=False, listunknown=False, listsubrepos=False):
1477 1484 # yet to be determined: what to do if 'other' is a 'workingctx' or a
1478 1485 # 'memctx'?
1479 1486 s = super(workingctx, self).status(other, match, listignored, listclean,
1480 1487 listunknown, listsubrepos)
1481 1488 # calling 'super' subtly reveresed the contexts, so we flip the results
1482 1489 # (s[1] is 'added' and s[2] is 'removed')
1483 1490 s = list(s)
1484 1491 s[1], s[2] = s[2], s[1]
1485 1492 return scmutil.status(*s)
1486 1493
1487 1494 class committablefilectx(basefilectx):
1488 1495 """A committablefilectx provides common functionality for a file context
1489 1496 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1490 1497 def __init__(self, repo, path, filelog=None, ctx=None):
1491 1498 self._repo = repo
1492 1499 self._path = path
1493 1500 self._changeid = None
1494 1501 self._filerev = self._filenode = None
1495 1502
1496 1503 if filelog is not None:
1497 1504 self._filelog = filelog
1498 1505 if ctx:
1499 1506 self._changectx = ctx
1500 1507
1501 1508 def __nonzero__(self):
1502 1509 return True
1503 1510
1504 1511 def parents(self):
1505 1512 '''return parent filectxs, following copies if necessary'''
1506 1513 def filenode(ctx, path):
1507 1514 return ctx._manifest.get(path, nullid)
1508 1515
1509 1516 path = self._path
1510 1517 fl = self._filelog
1511 1518 pcl = self._changectx._parents
1512 1519 renamed = self.renamed()
1513 1520
1514 1521 if renamed:
1515 1522 pl = [renamed + (None,)]
1516 1523 else:
1517 1524 pl = [(path, filenode(pcl[0], path), fl)]
1518 1525
1519 1526 for pc in pcl[1:]:
1520 1527 pl.append((path, filenode(pc, path), fl))
1521 1528
1522 1529 return [filectx(self._repo, p, fileid=n, filelog=l)
1523 1530 for p, n, l in pl if n != nullid]
1524 1531
1525 1532 def children(self):
1526 1533 return []
1527 1534
1528 1535 class workingfilectx(committablefilectx):
1529 1536 """A workingfilectx object makes access to data related to a particular
1530 1537 file in the working directory convenient."""
1531 1538 def __init__(self, repo, path, filelog=None, workingctx=None):
1532 1539 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1533 1540
1534 1541 @propertycache
1535 1542 def _changectx(self):
1536 1543 return workingctx(self._repo)
1537 1544
1538 1545 def data(self):
1539 1546 return self._repo.wread(self._path)
1540 1547 def renamed(self):
1541 1548 rp = self._repo.dirstate.copied(self._path)
1542 1549 if not rp:
1543 1550 return None
1544 1551 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1545 1552
1546 1553 def size(self):
1547 1554 return self._repo.wvfs.lstat(self._path).st_size
1548 1555 def date(self):
1549 1556 t, tz = self._changectx.date()
1550 1557 try:
1551 1558 return (int(self._repo.wvfs.lstat(self._path).st_mtime), tz)
1552 1559 except OSError, err:
1553 1560 if err.errno != errno.ENOENT:
1554 1561 raise
1555 1562 return (t, tz)
1556 1563
1557 1564 def cmp(self, fctx):
1558 1565 """compare with other file context
1559 1566
1560 1567 returns True if different than fctx.
1561 1568 """
1562 1569 # fctx should be a filectx (not a workingfilectx)
1563 1570 # invert comparison to reuse the same code path
1564 1571 return fctx.cmp(self)
1565 1572
1566 1573 def remove(self, ignoremissing=False):
1567 1574 """wraps unlink for a repo's working directory"""
1568 1575 util.unlinkpath(self._repo.wjoin(self._path), ignoremissing)
1569 1576
1570 1577 def write(self, data, flags):
1571 1578 """wraps repo.wwrite"""
1572 1579 self._repo.wwrite(self._path, data, flags)
1573 1580
1574 1581 class memctx(committablectx):
1575 1582 """Use memctx to perform in-memory commits via localrepo.commitctx().
1576 1583
1577 1584 Revision information is supplied at initialization time while
1578 1585 related files data and is made available through a callback
1579 1586 mechanism. 'repo' is the current localrepo, 'parents' is a
1580 1587 sequence of two parent revisions identifiers (pass None for every
1581 1588 missing parent), 'text' is the commit message and 'files' lists
1582 1589 names of files touched by the revision (normalized and relative to
1583 1590 repository root).
1584 1591
1585 1592 filectxfn(repo, memctx, path) is a callable receiving the
1586 1593 repository, the current memctx object and the normalized path of
1587 1594 requested file, relative to repository root. It is fired by the
1588 1595 commit function for every file in 'files', but calls order is
1589 1596 undefined. If the file is available in the revision being
1590 1597 committed (updated or added), filectxfn returns a memfilectx
1591 1598 object. If the file was removed, filectxfn raises an
1592 1599 IOError. Moved files are represented by marking the source file
1593 1600 removed and the new file added with copy information (see
1594 1601 memfilectx).
1595 1602
1596 1603 user receives the committer name and defaults to current
1597 1604 repository username, date is the commit date in any format
1598 1605 supported by util.parsedate() and defaults to current date, extra
1599 1606 is a dictionary of metadata or is left empty.
1600 1607 """
1601 1608
1602 1609 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
1603 1610 # Extensions that need to retain compatibility across Mercurial 3.1 can use
1604 1611 # this field to determine what to do in filectxfn.
1605 1612 _returnnoneformissingfiles = True
1606 1613
1607 1614 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1608 1615 date=None, extra=None, editor=False):
1609 1616 super(memctx, self).__init__(repo, text, user, date, extra)
1610 1617 self._rev = None
1611 1618 self._node = None
1612 1619 parents = [(p or nullid) for p in parents]
1613 1620 p1, p2 = parents
1614 1621 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1615 1622 files = sorted(set(files))
1616 1623 self._status = scmutil.status(files, [], [], [], [], [], [])
1617 1624 self._filectxfn = filectxfn
1618 1625 self.substate = {}
1619 1626
1620 1627 # if store is not callable, wrap it in a function
1621 1628 if not callable(filectxfn):
1622 1629 def getfilectx(repo, memctx, path):
1623 1630 fctx = filectxfn[path]
1624 1631 # this is weird but apparently we only keep track of one parent
1625 1632 # (why not only store that instead of a tuple?)
1626 1633 copied = fctx.renamed()
1627 1634 if copied:
1628 1635 copied = copied[0]
1629 1636 return memfilectx(repo, path, fctx.data(),
1630 1637 islink=fctx.islink(), isexec=fctx.isexec(),
1631 1638 copied=copied, memctx=memctx)
1632 1639 self._filectxfn = getfilectx
1633 1640
1634 1641 self._extra = extra and extra.copy() or {}
1635 1642 if self._extra.get('branch', '') == '':
1636 1643 self._extra['branch'] = 'default'
1637 1644
1638 1645 if editor:
1639 1646 self._text = editor(self._repo, self, [])
1640 1647 self._repo.savecommitmessage(self._text)
1641 1648
1642 1649 def filectx(self, path, filelog=None):
1643 1650 """get a file context from the working directory
1644 1651
1645 1652 Returns None if file doesn't exist and should be removed."""
1646 1653 return self._filectxfn(self._repo, self, path)
1647 1654
1648 1655 def commit(self):
1649 1656 """commit context to the repo"""
1650 1657 return self._repo.commitctx(self)
1651 1658
1652 1659 @propertycache
1653 1660 def _manifest(self):
1654 1661 """generate a manifest based on the return values of filectxfn"""
1655 1662
1656 1663 # keep this simple for now; just worry about p1
1657 1664 pctx = self._parents[0]
1658 1665 man = pctx.manifest().copy()
1659 1666
1660 1667 for f, fnode in man.iteritems():
1661 1668 p1node = nullid
1662 1669 p2node = nullid
1663 1670 p = pctx[f].parents() # if file isn't in pctx, check p2?
1664 1671 if len(p) > 0:
1665 1672 p1node = p[0].node()
1666 1673 if len(p) > 1:
1667 1674 p2node = p[1].node()
1668 1675 man[f] = revlog.hash(self[f].data(), p1node, p2node)
1669 1676
1670 1677 return man
1671 1678
1672 1679
1673 1680 class memfilectx(committablefilectx):
1674 1681 """memfilectx represents an in-memory file to commit.
1675 1682
1676 1683 See memctx and commitablefilectx for more details.
1677 1684 """
1678 1685 def __init__(self, repo, path, data, islink=False,
1679 1686 isexec=False, copied=None, memctx=None):
1680 1687 """
1681 1688 path is the normalized file path relative to repository root.
1682 1689 data is the file content as a string.
1683 1690 islink is True if the file is a symbolic link.
1684 1691 isexec is True if the file is executable.
1685 1692 copied is the source file path if current file was copied in the
1686 1693 revision being committed, or None."""
1687 1694 super(memfilectx, self).__init__(repo, path, None, memctx)
1688 1695 self._data = data
1689 1696 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1690 1697 self._copied = None
1691 1698 if copied:
1692 1699 self._copied = (copied, nullid)
1693 1700
1694 1701 def data(self):
1695 1702 return self._data
1696 1703 def size(self):
1697 1704 return len(self.data())
1698 1705 def flags(self):
1699 1706 return self._flags
1700 1707 def renamed(self):
1701 1708 return self._copied
1702 1709
1703 1710 def remove(self, ignoremissing=False):
1704 1711 """wraps unlink for a repo's working directory"""
1705 1712 # need to figure out what to do here
1706 1713 del self._changectx[self._path]
1707 1714
1708 1715 def write(self, data, flags):
1709 1716 """wraps repo.wwrite"""
1710 1717 self._data = data
General Comments 0
You need to be logged in to leave comments. Login now