##// END OF EJS Templates
namespaces: remove weakref; always pass in repo...
Ryan McElroy -
r23561:3c2419e0 default
parent child Browse files
Show More
@@ -1,1689 +1,1689 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 return self.manifest().matches(match)
75 75
76 76 def _matchstatus(self, other, match):
77 77 """return match.always if match is none
78 78
79 79 This internal method provides a way for child objects to override the
80 80 match operator.
81 81 """
82 82 return match or matchmod.always(self._repo.root, self._repo.getcwd())
83 83
84 84 def _buildstatus(self, other, s, match, listignored, listclean,
85 85 listunknown):
86 86 """build a status with respect to another context"""
87 87 # Load earliest manifest first for caching reasons. More specifically,
88 88 # if you have revisions 1000 and 1001, 1001 is probably stored as a
89 89 # delta against 1000. Thus, if you read 1000 first, we'll reconstruct
90 90 # 1000 and cache it so that when you read 1001, we just need to apply a
91 91 # delta to what's in the cache. So that's one full reconstruction + one
92 92 # delta application.
93 93 if self.rev() is not None and self.rev() < other.rev():
94 94 self.manifest()
95 95 mf1 = other._manifestmatches(match, s)
96 96 mf2 = self._manifestmatches(match, s)
97 97
98 98 modified, added, clean = [], [], []
99 99 deleted, unknown, ignored = s.deleted, s.unknown, s.ignored
100 100 deletedset = set(deleted)
101 101 withflags = mf1.withflags() | mf2.withflags()
102 102 for fn, mf2node in mf2.iteritems():
103 103 if fn in mf1:
104 104 if (fn not in deletedset and
105 105 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
106 106 (mf1[fn] != mf2node and
107 107 (mf2node or self[fn].cmp(other[fn]))))):
108 108 modified.append(fn)
109 109 elif listclean:
110 110 clean.append(fn)
111 111 del mf1[fn]
112 112 elif fn not in deletedset:
113 113 added.append(fn)
114 114 removed = mf1.keys()
115 115 if removed:
116 116 # need to filter files if they are already reported as removed
117 117 unknown = [fn for fn in unknown if fn not in mf1]
118 118 ignored = [fn for fn in ignored if fn not in mf1]
119 119
120 120 return scmutil.status(modified, added, removed, deleted, unknown,
121 121 ignored, clean)
122 122
123 123 @propertycache
124 124 def substate(self):
125 125 return subrepo.state(self, self._repo.ui)
126 126
127 127 def subrev(self, subpath):
128 128 return self.substate[subpath][1]
129 129
130 130 def rev(self):
131 131 return self._rev
132 132 def node(self):
133 133 return self._node
134 134 def hex(self):
135 135 return hex(self.node())
136 136 def manifest(self):
137 137 return self._manifest
138 138 def phasestr(self):
139 139 return phases.phasenames[self.phase()]
140 140 def mutable(self):
141 141 return self.phase() > phases.public
142 142
143 143 def getfileset(self, expr):
144 144 return fileset.getfileset(self, expr)
145 145
146 146 def obsolete(self):
147 147 """True if the changeset is obsolete"""
148 148 return self.rev() in obsmod.getrevs(self._repo, 'obsolete')
149 149
150 150 def extinct(self):
151 151 """True if the changeset is extinct"""
152 152 return self.rev() in obsmod.getrevs(self._repo, 'extinct')
153 153
154 154 def unstable(self):
155 155 """True if the changeset is not obsolete but it's ancestor are"""
156 156 return self.rev() in obsmod.getrevs(self._repo, 'unstable')
157 157
158 158 def bumped(self):
159 159 """True if the changeset try to be a successor of a public changeset
160 160
161 161 Only non-public and non-obsolete changesets may be bumped.
162 162 """
163 163 return self.rev() in obsmod.getrevs(self._repo, 'bumped')
164 164
165 165 def divergent(self):
166 166 """Is a successors of a changeset with multiple possible successors set
167 167
168 168 Only non-public and non-obsolete changesets may be divergent.
169 169 """
170 170 return self.rev() in obsmod.getrevs(self._repo, 'divergent')
171 171
172 172 def troubled(self):
173 173 """True if the changeset is either unstable, bumped or divergent"""
174 174 return self.unstable() or self.bumped() or self.divergent()
175 175
176 176 def troubles(self):
177 177 """return the list of troubles affecting this changesets.
178 178
179 179 Troubles are returned as strings. possible values are:
180 180 - unstable,
181 181 - bumped,
182 182 - divergent.
183 183 """
184 184 troubles = []
185 185 if self.unstable():
186 186 troubles.append('unstable')
187 187 if self.bumped():
188 188 troubles.append('bumped')
189 189 if self.divergent():
190 190 troubles.append('divergent')
191 191 return troubles
192 192
193 193 def parents(self):
194 194 """return contexts for each parent changeset"""
195 195 return self._parents
196 196
197 197 def p1(self):
198 198 return self._parents[0]
199 199
200 200 def p2(self):
201 201 if len(self._parents) == 2:
202 202 return self._parents[1]
203 203 return changectx(self._repo, -1)
204 204
205 205 def _fileinfo(self, path):
206 206 if '_manifest' in self.__dict__:
207 207 try:
208 208 return self._manifest[path], self._manifest.flags(path)
209 209 except KeyError:
210 210 raise error.ManifestLookupError(self._node, path,
211 211 _('not found in manifest'))
212 212 if '_manifestdelta' in self.__dict__ or path in self.files():
213 213 if path in self._manifestdelta:
214 214 return (self._manifestdelta[path],
215 215 self._manifestdelta.flags(path))
216 216 node, flag = self._repo.manifest.find(self._changeset[0], path)
217 217 if not node:
218 218 raise error.ManifestLookupError(self._node, path,
219 219 _('not found in manifest'))
220 220
221 221 return node, flag
222 222
223 223 def filenode(self, path):
224 224 return self._fileinfo(path)[0]
225 225
226 226 def flags(self, path):
227 227 try:
228 228 return self._fileinfo(path)[1]
229 229 except error.LookupError:
230 230 return ''
231 231
232 232 def sub(self, path):
233 233 return subrepo.subrepo(self, path)
234 234
235 235 def match(self, pats=[], include=None, exclude=None, default='glob'):
236 236 r = self._repo
237 237 return matchmod.match(r.root, r.getcwd(), pats,
238 238 include, exclude, default,
239 239 auditor=r.auditor, ctx=self)
240 240
241 241 def diff(self, ctx2=None, match=None, **opts):
242 242 """Returns a diff generator for the given contexts and matcher"""
243 243 if ctx2 is None:
244 244 ctx2 = self.p1()
245 245 if ctx2 is not None:
246 246 ctx2 = self._repo[ctx2]
247 247 diffopts = patch.diffopts(self._repo.ui, opts)
248 248 return patch.diff(self._repo, ctx2, self, match=match, opts=diffopts)
249 249
250 250 @propertycache
251 251 def _dirs(self):
252 252 return scmutil.dirs(self._manifest)
253 253
254 254 def dirs(self):
255 255 return self._dirs
256 256
257 257 def dirty(self, missing=False, merge=True, branch=True):
258 258 return False
259 259
260 260 def status(self, other=None, match=None, listignored=False,
261 261 listclean=False, listunknown=False, listsubrepos=False):
262 262 """return status of files between two nodes or node and working
263 263 directory.
264 264
265 265 If other is None, compare this node with working directory.
266 266
267 267 returns (modified, added, removed, deleted, unknown, ignored, clean)
268 268 """
269 269
270 270 ctx1 = self
271 271 ctx2 = self._repo[other]
272 272
273 273 # This next code block is, admittedly, fragile logic that tests for
274 274 # reversing the contexts and wouldn't need to exist if it weren't for
275 275 # the fast (and common) code path of comparing the working directory
276 276 # with its first parent.
277 277 #
278 278 # What we're aiming for here is the ability to call:
279 279 #
280 280 # workingctx.status(parentctx)
281 281 #
282 282 # If we always built the manifest for each context and compared those,
283 283 # then we'd be done. But the special case of the above call means we
284 284 # just copy the manifest of the parent.
285 285 reversed = False
286 286 if (not isinstance(ctx1, changectx)
287 287 and isinstance(ctx2, changectx)):
288 288 reversed = True
289 289 ctx1, ctx2 = ctx2, ctx1
290 290
291 291 match = ctx2._matchstatus(ctx1, match)
292 292 r = scmutil.status([], [], [], [], [], [], [])
293 293 r = ctx2._buildstatus(ctx1, r, match, listignored, listclean,
294 294 listunknown)
295 295
296 296 if reversed:
297 297 # Reverse added and removed. Clear deleted, unknown and ignored as
298 298 # these make no sense to reverse.
299 299 r = scmutil.status(r.modified, r.removed, r.added, [], [], [],
300 300 r.clean)
301 301
302 302 if listsubrepos:
303 303 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
304 304 rev2 = ctx2.subrev(subpath)
305 305 try:
306 306 submatch = matchmod.narrowmatcher(subpath, match)
307 307 s = sub.status(rev2, match=submatch, ignored=listignored,
308 308 clean=listclean, unknown=listunknown,
309 309 listsubrepos=True)
310 310 for rfiles, sfiles in zip(r, s):
311 311 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
312 312 except error.LookupError:
313 313 self._repo.ui.status(_("skipping missing "
314 314 "subrepository: %s\n") % subpath)
315 315
316 316 for l in r:
317 317 l.sort()
318 318
319 319 return r
320 320
321 321
322 322 def makememctx(repo, parents, text, user, date, branch, files, store,
323 323 editor=None):
324 324 def getfilectx(repo, memctx, path):
325 325 data, mode, copied = store.getfile(path)
326 326 if data is None:
327 327 return None
328 328 islink, isexec = mode
329 329 return memfilectx(repo, path, data, islink=islink, isexec=isexec,
330 330 copied=copied, memctx=memctx)
331 331 extra = {}
332 332 if branch:
333 333 extra['branch'] = encoding.fromlocal(branch)
334 334 ctx = memctx(repo, parents, text, files, getfilectx, user,
335 335 date, extra, editor)
336 336 return ctx
337 337
338 338 class changectx(basectx):
339 339 """A changecontext object makes access to data related to a particular
340 340 changeset convenient. It represents a read-only context already present in
341 341 the repo."""
342 342 def __init__(self, repo, changeid=''):
343 343 """changeid is a revision number, node, or tag"""
344 344
345 345 # since basectx.__new__ already took care of copying the object, we
346 346 # don't need to do anything in __init__, so we just exit here
347 347 if isinstance(changeid, basectx):
348 348 return
349 349
350 350 if changeid == '':
351 351 changeid = '.'
352 352 self._repo = repo
353 353
354 354 try:
355 355 if isinstance(changeid, int):
356 356 self._node = repo.changelog.node(changeid)
357 357 self._rev = changeid
358 358 return
359 359 if isinstance(changeid, long):
360 360 changeid = str(changeid)
361 361 if changeid == '.':
362 362 self._node = repo.dirstate.p1()
363 363 self._rev = repo.changelog.rev(self._node)
364 364 return
365 365 if changeid == 'null':
366 366 self._node = nullid
367 367 self._rev = nullrev
368 368 return
369 369 if changeid == 'tip':
370 370 self._node = repo.changelog.tip()
371 371 self._rev = repo.changelog.rev(self._node)
372 372 return
373 373 if len(changeid) == 20:
374 374 try:
375 375 self._node = changeid
376 376 self._rev = repo.changelog.rev(changeid)
377 377 return
378 378 except error.FilteredRepoLookupError:
379 379 raise
380 380 except LookupError:
381 381 pass
382 382
383 383 try:
384 384 r = int(changeid)
385 385 if str(r) != changeid:
386 386 raise ValueError
387 387 l = len(repo.changelog)
388 388 if r < 0:
389 389 r += l
390 390 if r < 0 or r >= l:
391 391 raise ValueError
392 392 self._rev = r
393 393 self._node = repo.changelog.node(r)
394 394 return
395 395 except error.FilteredIndexError:
396 396 raise
397 397 except (ValueError, OverflowError, IndexError):
398 398 pass
399 399
400 400 if len(changeid) == 40:
401 401 try:
402 402 self._node = bin(changeid)
403 403 self._rev = repo.changelog.rev(self._node)
404 404 return
405 405 except error.FilteredLookupError:
406 406 raise
407 407 except (TypeError, LookupError):
408 408 pass
409 409
410 410 # lookup bookmarks through the name interface
411 411 try:
412 self._node = repo.names.singlenode(changeid)
412 self._node = repo.names.singlenode(repo, changeid)
413 413 self._rev = repo.changelog.rev(self._node)
414 414 return
415 415 except KeyError:
416 416 pass
417 417
418 418 if changeid in repo._tagscache.tags:
419 419 self._node = repo._tagscache.tags[changeid]
420 420 self._rev = repo.changelog.rev(self._node)
421 421 return
422 422 try:
423 423 self._node = repo.branchtip(changeid)
424 424 self._rev = repo.changelog.rev(self._node)
425 425 return
426 426 except error.FilteredRepoLookupError:
427 427 raise
428 428 except error.RepoLookupError:
429 429 pass
430 430
431 431 self._node = repo.unfiltered().changelog._partialmatch(changeid)
432 432 if self._node is not None:
433 433 self._rev = repo.changelog.rev(self._node)
434 434 return
435 435
436 436 # lookup failed
437 437 # check if it might have come from damaged dirstate
438 438 #
439 439 # XXX we could avoid the unfiltered if we had a recognizable
440 440 # exception for filtered changeset access
441 441 if changeid in repo.unfiltered().dirstate.parents():
442 442 msg = _("working directory has unknown parent '%s'!")
443 443 raise error.Abort(msg % short(changeid))
444 444 try:
445 445 if len(changeid) == 20:
446 446 changeid = hex(changeid)
447 447 except TypeError:
448 448 pass
449 449 except (error.FilteredIndexError, error.FilteredLookupError,
450 450 error.FilteredRepoLookupError):
451 451 if repo.filtername == 'visible':
452 452 msg = _("hidden revision '%s'") % changeid
453 453 hint = _('use --hidden to access hidden revisions')
454 454 raise error.FilteredRepoLookupError(msg, hint=hint)
455 455 msg = _("filtered revision '%s' (not in '%s' subset)")
456 456 msg %= (changeid, repo.filtername)
457 457 raise error.FilteredRepoLookupError(msg)
458 458 except IndexError:
459 459 pass
460 460 raise error.RepoLookupError(
461 461 _("unknown revision '%s'") % changeid)
462 462
463 463 def __hash__(self):
464 464 try:
465 465 return hash(self._rev)
466 466 except AttributeError:
467 467 return id(self)
468 468
469 469 def __nonzero__(self):
470 470 return self._rev != nullrev
471 471
472 472 @propertycache
473 473 def _changeset(self):
474 474 return self._repo.changelog.read(self.rev())
475 475
476 476 @propertycache
477 477 def _manifest(self):
478 478 return self._repo.manifest.read(self._changeset[0])
479 479
480 480 @propertycache
481 481 def _manifestdelta(self):
482 482 return self._repo.manifest.readdelta(self._changeset[0])
483 483
484 484 @propertycache
485 485 def _parents(self):
486 486 p = self._repo.changelog.parentrevs(self._rev)
487 487 if p[1] == nullrev:
488 488 p = p[:-1]
489 489 return [changectx(self._repo, x) for x in p]
490 490
491 491 def changeset(self):
492 492 return self._changeset
493 493 def manifestnode(self):
494 494 return self._changeset[0]
495 495
496 496 def user(self):
497 497 return self._changeset[1]
498 498 def date(self):
499 499 return self._changeset[2]
500 500 def files(self):
501 501 return self._changeset[3]
502 502 def description(self):
503 503 return self._changeset[4]
504 504 def branch(self):
505 505 return encoding.tolocal(self._changeset[5].get("branch"))
506 506 def closesbranch(self):
507 507 return 'close' in self._changeset[5]
508 508 def extra(self):
509 509 return self._changeset[5]
510 510 def tags(self):
511 511 return self._repo.nodetags(self._node)
512 512 def bookmarks(self):
513 513 return self._repo.nodebookmarks(self._node)
514 514 def phase(self):
515 515 return self._repo._phasecache.phase(self._repo, self._rev)
516 516 def hidden(self):
517 517 return self._rev in repoview.filterrevs(self._repo, 'visible')
518 518
519 519 def children(self):
520 520 """return contexts for each child changeset"""
521 521 c = self._repo.changelog.children(self._node)
522 522 return [changectx(self._repo, x) for x in c]
523 523
524 524 def ancestors(self):
525 525 for a in self._repo.changelog.ancestors([self._rev]):
526 526 yield changectx(self._repo, a)
527 527
528 528 def descendants(self):
529 529 for d in self._repo.changelog.descendants([self._rev]):
530 530 yield changectx(self._repo, d)
531 531
532 532 def filectx(self, path, fileid=None, filelog=None):
533 533 """get a file context from this changeset"""
534 534 if fileid is None:
535 535 fileid = self.filenode(path)
536 536 return filectx(self._repo, path, fileid=fileid,
537 537 changectx=self, filelog=filelog)
538 538
539 539 def ancestor(self, c2, warn=False):
540 540 """return the "best" ancestor context of self and c2
541 541
542 542 If there are multiple candidates, it will show a message and check
543 543 merge.preferancestor configuration before falling back to the
544 544 revlog ancestor."""
545 545 # deal with workingctxs
546 546 n2 = c2._node
547 547 if n2 is None:
548 548 n2 = c2._parents[0]._node
549 549 cahs = self._repo.changelog.commonancestorsheads(self._node, n2)
550 550 if not cahs:
551 551 anc = nullid
552 552 elif len(cahs) == 1:
553 553 anc = cahs[0]
554 554 else:
555 555 for r in self._repo.ui.configlist('merge', 'preferancestor'):
556 556 try:
557 557 ctx = changectx(self._repo, r)
558 558 except error.RepoLookupError:
559 559 continue
560 560 anc = ctx.node()
561 561 if anc in cahs:
562 562 break
563 563 else:
564 564 anc = self._repo.changelog.ancestor(self._node, n2)
565 565 if warn:
566 566 self._repo.ui.status(
567 567 (_("note: using %s as ancestor of %s and %s\n") %
568 568 (short(anc), short(self._node), short(n2))) +
569 569 ''.join(_(" alternatively, use --config "
570 570 "merge.preferancestor=%s\n") %
571 571 short(n) for n in sorted(cahs) if n != anc))
572 572 return changectx(self._repo, anc)
573 573
574 574 def descendant(self, other):
575 575 """True if other is descendant of this changeset"""
576 576 return self._repo.changelog.descendant(self._rev, other._rev)
577 577
578 578 def walk(self, match):
579 579 fset = set(match.files())
580 580 # for dirstate.walk, files=['.'] means "walk the whole tree".
581 581 # follow that here, too
582 582 fset.discard('.')
583 583
584 584 # avoid the entire walk if we're only looking for specific files
585 585 if fset and not match.anypats():
586 586 if util.all([fn in self for fn in fset]):
587 587 for fn in sorted(fset):
588 588 if match(fn):
589 589 yield fn
590 590 raise StopIteration
591 591
592 592 for fn in self:
593 593 if fn in fset:
594 594 # specified pattern is the exact name
595 595 fset.remove(fn)
596 596 if match(fn):
597 597 yield fn
598 598 for fn in sorted(fset):
599 599 if fn in self._dirs:
600 600 # specified pattern is a directory
601 601 continue
602 602 match.bad(fn, _('no such file in rev %s') % self)
603 603
604 604 def matches(self, match):
605 605 return self.walk(match)
606 606
607 607 class basefilectx(object):
608 608 """A filecontext object represents the common logic for its children:
609 609 filectx: read-only access to a filerevision that is already present
610 610 in the repo,
611 611 workingfilectx: a filecontext that represents files from the working
612 612 directory,
613 613 memfilectx: a filecontext that represents files in-memory."""
614 614 def __new__(cls, repo, path, *args, **kwargs):
615 615 return super(basefilectx, cls).__new__(cls)
616 616
617 617 @propertycache
618 618 def _filelog(self):
619 619 return self._repo.file(self._path)
620 620
621 621 @propertycache
622 622 def _changeid(self):
623 623 if '_changeid' in self.__dict__:
624 624 return self._changeid
625 625 elif '_changectx' in self.__dict__:
626 626 return self._changectx.rev()
627 627 else:
628 628 return self._filelog.linkrev(self._filerev)
629 629
630 630 @propertycache
631 631 def _filenode(self):
632 632 if '_fileid' in self.__dict__:
633 633 return self._filelog.lookup(self._fileid)
634 634 else:
635 635 return self._changectx.filenode(self._path)
636 636
637 637 @propertycache
638 638 def _filerev(self):
639 639 return self._filelog.rev(self._filenode)
640 640
641 641 @propertycache
642 642 def _repopath(self):
643 643 return self._path
644 644
645 645 def __nonzero__(self):
646 646 try:
647 647 self._filenode
648 648 return True
649 649 except error.LookupError:
650 650 # file is missing
651 651 return False
652 652
653 653 def __str__(self):
654 654 return "%s@%s" % (self.path(), self._changectx)
655 655
656 656 def __repr__(self):
657 657 return "<%s %s>" % (type(self).__name__, str(self))
658 658
659 659 def __hash__(self):
660 660 try:
661 661 return hash((self._path, self._filenode))
662 662 except AttributeError:
663 663 return id(self)
664 664
665 665 def __eq__(self, other):
666 666 try:
667 667 return (type(self) == type(other) and self._path == other._path
668 668 and self._filenode == other._filenode)
669 669 except AttributeError:
670 670 return False
671 671
672 672 def __ne__(self, other):
673 673 return not (self == other)
674 674
675 675 def filerev(self):
676 676 return self._filerev
677 677 def filenode(self):
678 678 return self._filenode
679 679 def flags(self):
680 680 return self._changectx.flags(self._path)
681 681 def filelog(self):
682 682 return self._filelog
683 683 def rev(self):
684 684 return self._changeid
685 685 def linkrev(self):
686 686 return self._filelog.linkrev(self._filerev)
687 687 def node(self):
688 688 return self._changectx.node()
689 689 def hex(self):
690 690 return self._changectx.hex()
691 691 def user(self):
692 692 return self._changectx.user()
693 693 def date(self):
694 694 return self._changectx.date()
695 695 def files(self):
696 696 return self._changectx.files()
697 697 def description(self):
698 698 return self._changectx.description()
699 699 def branch(self):
700 700 return self._changectx.branch()
701 701 def extra(self):
702 702 return self._changectx.extra()
703 703 def phase(self):
704 704 return self._changectx.phase()
705 705 def phasestr(self):
706 706 return self._changectx.phasestr()
707 707 def manifest(self):
708 708 return self._changectx.manifest()
709 709 def changectx(self):
710 710 return self._changectx
711 711
712 712 def path(self):
713 713 return self._path
714 714
715 715 def isbinary(self):
716 716 try:
717 717 return util.binary(self.data())
718 718 except IOError:
719 719 return False
720 720 def isexec(self):
721 721 return 'x' in self.flags()
722 722 def islink(self):
723 723 return 'l' in self.flags()
724 724
725 725 def cmp(self, fctx):
726 726 """compare with other file context
727 727
728 728 returns True if different than fctx.
729 729 """
730 730 if (fctx._filerev is None
731 731 and (self._repo._encodefilterpats
732 732 # if file data starts with '\1\n', empty metadata block is
733 733 # prepended, which adds 4 bytes to filelog.size().
734 734 or self.size() - 4 == fctx.size())
735 735 or self.size() == fctx.size()):
736 736 return self._filelog.cmp(self._filenode, fctx.data())
737 737
738 738 return True
739 739
740 740 def parents(self):
741 741 _path = self._path
742 742 fl = self._filelog
743 743 pl = [(_path, n, fl) for n in self._filelog.parents(self._filenode)]
744 744
745 745 r = self._filelog.renamed(self._filenode)
746 746 if r:
747 747 pl[0] = (r[0], r[1], None)
748 748
749 749 return [filectx(self._repo, p, fileid=n, filelog=l)
750 750 for p, n, l in pl if n != nullid]
751 751
752 752 def p1(self):
753 753 return self.parents()[0]
754 754
755 755 def p2(self):
756 756 p = self.parents()
757 757 if len(p) == 2:
758 758 return p[1]
759 759 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
760 760
761 761 def annotate(self, follow=False, linenumber=None, diffopts=None):
762 762 '''returns a list of tuples of (ctx, line) for each line
763 763 in the file, where ctx is the filectx of the node where
764 764 that line was last changed.
765 765 This returns tuples of ((ctx, linenumber), line) for each line,
766 766 if "linenumber" parameter is NOT "None".
767 767 In such tuples, linenumber means one at the first appearance
768 768 in the managed file.
769 769 To reduce annotation cost,
770 770 this returns fixed value(False is used) as linenumber,
771 771 if "linenumber" parameter is "False".'''
772 772
773 773 if linenumber is None:
774 774 def decorate(text, rev):
775 775 return ([rev] * len(text.splitlines()), text)
776 776 elif linenumber:
777 777 def decorate(text, rev):
778 778 size = len(text.splitlines())
779 779 return ([(rev, i) for i in xrange(1, size + 1)], text)
780 780 else:
781 781 def decorate(text, rev):
782 782 return ([(rev, False)] * len(text.splitlines()), text)
783 783
784 784 def pair(parent, child):
785 785 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
786 786 refine=True)
787 787 for (a1, a2, b1, b2), t in blocks:
788 788 # Changed blocks ('!') or blocks made only of blank lines ('~')
789 789 # belong to the child.
790 790 if t == '=':
791 791 child[0][b1:b2] = parent[0][a1:a2]
792 792 return child
793 793
794 794 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
795 795
796 796 def parents(f):
797 797 pl = f.parents()
798 798
799 799 # Don't return renamed parents if we aren't following.
800 800 if not follow:
801 801 pl = [p for p in pl if p.path() == f.path()]
802 802
803 803 # renamed filectx won't have a filelog yet, so set it
804 804 # from the cache to save time
805 805 for p in pl:
806 806 if not '_filelog' in p.__dict__:
807 807 p._filelog = getlog(p.path())
808 808
809 809 return pl
810 810
811 811 # use linkrev to find the first changeset where self appeared
812 812 if self.rev() != self.linkrev():
813 813 base = self.filectx(self.filenode())
814 814 else:
815 815 base = self
816 816
817 817 # This algorithm would prefer to be recursive, but Python is a
818 818 # bit recursion-hostile. Instead we do an iterative
819 819 # depth-first search.
820 820
821 821 visit = [base]
822 822 hist = {}
823 823 pcache = {}
824 824 needed = {base: 1}
825 825 while visit:
826 826 f = visit[-1]
827 827 pcached = f in pcache
828 828 if not pcached:
829 829 pcache[f] = parents(f)
830 830
831 831 ready = True
832 832 pl = pcache[f]
833 833 for p in pl:
834 834 if p not in hist:
835 835 ready = False
836 836 visit.append(p)
837 837 if not pcached:
838 838 needed[p] = needed.get(p, 0) + 1
839 839 if ready:
840 840 visit.pop()
841 841 reusable = f in hist
842 842 if reusable:
843 843 curr = hist[f]
844 844 else:
845 845 curr = decorate(f.data(), f)
846 846 for p in pl:
847 847 if not reusable:
848 848 curr = pair(hist[p], curr)
849 849 if needed[p] == 1:
850 850 del hist[p]
851 851 del needed[p]
852 852 else:
853 853 needed[p] -= 1
854 854
855 855 hist[f] = curr
856 856 pcache[f] = []
857 857
858 858 return zip(hist[base][0], hist[base][1].splitlines(True))
859 859
860 860 def ancestors(self, followfirst=False):
861 861 visit = {}
862 862 c = self
863 863 cut = followfirst and 1 or None
864 864 while True:
865 865 for parent in c.parents()[:cut]:
866 866 visit[(parent.rev(), parent.node())] = parent
867 867 if not visit:
868 868 break
869 869 c = visit.pop(max(visit))
870 870 yield c
871 871
872 872 class filectx(basefilectx):
873 873 """A filecontext object makes access to data related to a particular
874 874 filerevision convenient."""
875 875 def __init__(self, repo, path, changeid=None, fileid=None,
876 876 filelog=None, changectx=None):
877 877 """changeid can be a changeset revision, node, or tag.
878 878 fileid can be a file revision or node."""
879 879 self._repo = repo
880 880 self._path = path
881 881
882 882 assert (changeid is not None
883 883 or fileid is not None
884 884 or changectx is not None), \
885 885 ("bad args: changeid=%r, fileid=%r, changectx=%r"
886 886 % (changeid, fileid, changectx))
887 887
888 888 if filelog is not None:
889 889 self._filelog = filelog
890 890
891 891 if changeid is not None:
892 892 self._changeid = changeid
893 893 if changectx is not None:
894 894 self._changectx = changectx
895 895 if fileid is not None:
896 896 self._fileid = fileid
897 897
898 898 @propertycache
899 899 def _changectx(self):
900 900 try:
901 901 return changectx(self._repo, self._changeid)
902 902 except error.RepoLookupError:
903 903 # Linkrev may point to any revision in the repository. When the
904 904 # repository is filtered this may lead to `filectx` trying to build
905 905 # `changectx` for filtered revision. In such case we fallback to
906 906 # creating `changectx` on the unfiltered version of the reposition.
907 907 # This fallback should not be an issue because `changectx` from
908 908 # `filectx` are not used in complex operations that care about
909 909 # filtering.
910 910 #
911 911 # This fallback is a cheap and dirty fix that prevent several
912 912 # crashes. It does not ensure the behavior is correct. However the
913 913 # behavior was not correct before filtering either and "incorrect
914 914 # behavior" is seen as better as "crash"
915 915 #
916 916 # Linkrevs have several serious troubles with filtering that are
917 917 # complicated to solve. Proper handling of the issue here should be
918 918 # considered when solving linkrev issue are on the table.
919 919 return changectx(self._repo.unfiltered(), self._changeid)
920 920
921 921 def filectx(self, fileid):
922 922 '''opens an arbitrary revision of the file without
923 923 opening a new filelog'''
924 924 return filectx(self._repo, self._path, fileid=fileid,
925 925 filelog=self._filelog)
926 926
927 927 def data(self):
928 928 try:
929 929 return self._filelog.read(self._filenode)
930 930 except error.CensoredNodeError:
931 931 if self._repo.ui.config("censor", "policy", "abort") == "ignore":
932 932 return ""
933 933 raise util.Abort(_("censored node: %s") % short(self._filenode),
934 934 hint=_("set censor.policy to ignore errors"))
935 935
936 936 def size(self):
937 937 return self._filelog.size(self._filerev)
938 938
939 939 def renamed(self):
940 940 """check if file was actually renamed in this changeset revision
941 941
942 942 If rename logged in file revision, we report copy for changeset only
943 943 if file revisions linkrev points back to the changeset in question
944 944 or both changeset parents contain different file revisions.
945 945 """
946 946
947 947 renamed = self._filelog.renamed(self._filenode)
948 948 if not renamed:
949 949 return renamed
950 950
951 951 if self.rev() == self.linkrev():
952 952 return renamed
953 953
954 954 name = self.path()
955 955 fnode = self._filenode
956 956 for p in self._changectx.parents():
957 957 try:
958 958 if fnode == p.filenode(name):
959 959 return None
960 960 except error.LookupError:
961 961 pass
962 962 return renamed
963 963
964 964 def children(self):
965 965 # hard for renames
966 966 c = self._filelog.children(self._filenode)
967 967 return [filectx(self._repo, self._path, fileid=x,
968 968 filelog=self._filelog) for x in c]
969 969
970 970 class committablectx(basectx):
971 971 """A committablectx object provides common functionality for a context that
972 972 wants the ability to commit, e.g. workingctx or memctx."""
973 973 def __init__(self, repo, text="", user=None, date=None, extra=None,
974 974 changes=None):
975 975 self._repo = repo
976 976 self._rev = None
977 977 self._node = None
978 978 self._text = text
979 979 if date:
980 980 self._date = util.parsedate(date)
981 981 if user:
982 982 self._user = user
983 983 if changes:
984 984 self._status = changes
985 985
986 986 self._extra = {}
987 987 if extra:
988 988 self._extra = extra.copy()
989 989 if 'branch' not in self._extra:
990 990 try:
991 991 branch = encoding.fromlocal(self._repo.dirstate.branch())
992 992 except UnicodeDecodeError:
993 993 raise util.Abort(_('branch name not in UTF-8!'))
994 994 self._extra['branch'] = branch
995 995 if self._extra['branch'] == '':
996 996 self._extra['branch'] = 'default'
997 997
998 998 def __str__(self):
999 999 return str(self._parents[0]) + "+"
1000 1000
1001 1001 def __nonzero__(self):
1002 1002 return True
1003 1003
1004 1004 def _buildflagfunc(self):
1005 1005 # Create a fallback function for getting file flags when the
1006 1006 # filesystem doesn't support them
1007 1007
1008 1008 copiesget = self._repo.dirstate.copies().get
1009 1009
1010 1010 if len(self._parents) < 2:
1011 1011 # when we have one parent, it's easy: copy from parent
1012 1012 man = self._parents[0].manifest()
1013 1013 def func(f):
1014 1014 f = copiesget(f, f)
1015 1015 return man.flags(f)
1016 1016 else:
1017 1017 # merges are tricky: we try to reconstruct the unstored
1018 1018 # result from the merge (issue1802)
1019 1019 p1, p2 = self._parents
1020 1020 pa = p1.ancestor(p2)
1021 1021 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
1022 1022
1023 1023 def func(f):
1024 1024 f = copiesget(f, f) # may be wrong for merges with copies
1025 1025 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
1026 1026 if fl1 == fl2:
1027 1027 return fl1
1028 1028 if fl1 == fla:
1029 1029 return fl2
1030 1030 if fl2 == fla:
1031 1031 return fl1
1032 1032 return '' # punt for conflicts
1033 1033
1034 1034 return func
1035 1035
1036 1036 @propertycache
1037 1037 def _flagfunc(self):
1038 1038 return self._repo.dirstate.flagfunc(self._buildflagfunc)
1039 1039
1040 1040 @propertycache
1041 1041 def _manifest(self):
1042 1042 """generate a manifest corresponding to the values in self._status
1043 1043
1044 1044 This reuse the file nodeid from parent, but we append an extra letter
1045 1045 when modified. Modified files get an extra 'm' while added files get
1046 1046 an extra 'a'. This is used by manifests merge to see that files
1047 1047 are different and by update logic to avoid deleting newly added files.
1048 1048 """
1049 1049
1050 1050 man1 = self._parents[0].manifest()
1051 1051 man = man1.copy()
1052 1052 if len(self._parents) > 1:
1053 1053 man2 = self.p2().manifest()
1054 1054 def getman(f):
1055 1055 if f in man1:
1056 1056 return man1
1057 1057 return man2
1058 1058 else:
1059 1059 getman = lambda f: man1
1060 1060
1061 1061 copied = self._repo.dirstate.copies()
1062 1062 ff = self._flagfunc
1063 1063 for i, l in (("a", self._status.added), ("m", self._status.modified)):
1064 1064 for f in l:
1065 1065 orig = copied.get(f, f)
1066 1066 man[f] = getman(orig).get(orig, nullid) + i
1067 1067 try:
1068 1068 man.setflag(f, ff(f))
1069 1069 except OSError:
1070 1070 pass
1071 1071
1072 1072 for f in self._status.deleted + self._status.removed:
1073 1073 if f in man:
1074 1074 del man[f]
1075 1075
1076 1076 return man
1077 1077
1078 1078 @propertycache
1079 1079 def _status(self):
1080 1080 return self._repo.status()
1081 1081
1082 1082 @propertycache
1083 1083 def _user(self):
1084 1084 return self._repo.ui.username()
1085 1085
1086 1086 @propertycache
1087 1087 def _date(self):
1088 1088 return util.makedate()
1089 1089
1090 1090 def subrev(self, subpath):
1091 1091 return None
1092 1092
1093 1093 def user(self):
1094 1094 return self._user or self._repo.ui.username()
1095 1095 def date(self):
1096 1096 return self._date
1097 1097 def description(self):
1098 1098 return self._text
1099 1099 def files(self):
1100 1100 return sorted(self._status.modified + self._status.added +
1101 1101 self._status.removed)
1102 1102
1103 1103 def modified(self):
1104 1104 return self._status.modified
1105 1105 def added(self):
1106 1106 return self._status.added
1107 1107 def removed(self):
1108 1108 return self._status.removed
1109 1109 def deleted(self):
1110 1110 return self._status.deleted
1111 1111 def unknown(self):
1112 1112 return self._status.unknown
1113 1113 def ignored(self):
1114 1114 return self._status.ignored
1115 1115 def clean(self):
1116 1116 return self._status.clean
1117 1117 def branch(self):
1118 1118 return encoding.tolocal(self._extra['branch'])
1119 1119 def closesbranch(self):
1120 1120 return 'close' in self._extra
1121 1121 def extra(self):
1122 1122 return self._extra
1123 1123
1124 1124 def tags(self):
1125 1125 t = []
1126 1126 for p in self.parents():
1127 1127 t.extend(p.tags())
1128 1128 return t
1129 1129
1130 1130 def bookmarks(self):
1131 1131 b = []
1132 1132 for p in self.parents():
1133 1133 b.extend(p.bookmarks())
1134 1134 return b
1135 1135
1136 1136 def phase(self):
1137 1137 phase = phases.draft # default phase to draft
1138 1138 for p in self.parents():
1139 1139 phase = max(phase, p.phase())
1140 1140 return phase
1141 1141
1142 1142 def hidden(self):
1143 1143 return False
1144 1144
1145 1145 def children(self):
1146 1146 return []
1147 1147
1148 1148 def flags(self, path):
1149 1149 if '_manifest' in self.__dict__:
1150 1150 try:
1151 1151 return self._manifest.flags(path)
1152 1152 except KeyError:
1153 1153 return ''
1154 1154
1155 1155 try:
1156 1156 return self._flagfunc(path)
1157 1157 except OSError:
1158 1158 return ''
1159 1159
1160 1160 def ancestor(self, c2):
1161 1161 """return the "best" ancestor context of self and c2"""
1162 1162 return self._parents[0].ancestor(c2) # punt on two parents for now
1163 1163
1164 1164 def walk(self, match):
1165 1165 return sorted(self._repo.dirstate.walk(match, sorted(self.substate),
1166 1166 True, False))
1167 1167
1168 1168 def matches(self, match):
1169 1169 return sorted(self._repo.dirstate.matches(match))
1170 1170
1171 1171 def ancestors(self):
1172 1172 for a in self._repo.changelog.ancestors(
1173 1173 [p.rev() for p in self._parents]):
1174 1174 yield changectx(self._repo, a)
1175 1175
1176 1176 def markcommitted(self, node):
1177 1177 """Perform post-commit cleanup necessary after committing this ctx
1178 1178
1179 1179 Specifically, this updates backing stores this working context
1180 1180 wraps to reflect the fact that the changes reflected by this
1181 1181 workingctx have been committed. For example, it marks
1182 1182 modified and added files as normal in the dirstate.
1183 1183
1184 1184 """
1185 1185
1186 1186 self._repo.dirstate.beginparentchange()
1187 1187 for f in self.modified() + self.added():
1188 1188 self._repo.dirstate.normal(f)
1189 1189 for f in self.removed():
1190 1190 self._repo.dirstate.drop(f)
1191 1191 self._repo.dirstate.setparents(node)
1192 1192 self._repo.dirstate.endparentchange()
1193 1193
1194 1194 def dirs(self):
1195 1195 return self._repo.dirstate.dirs()
1196 1196
1197 1197 class workingctx(committablectx):
1198 1198 """A workingctx object makes access to data related to
1199 1199 the current working directory convenient.
1200 1200 date - any valid date string or (unixtime, offset), or None.
1201 1201 user - username string, or None.
1202 1202 extra - a dictionary of extra values, or None.
1203 1203 changes - a list of file lists as returned by localrepo.status()
1204 1204 or None to use the repository status.
1205 1205 """
1206 1206 def __init__(self, repo, text="", user=None, date=None, extra=None,
1207 1207 changes=None):
1208 1208 super(workingctx, self).__init__(repo, text, user, date, extra, changes)
1209 1209
1210 1210 def __iter__(self):
1211 1211 d = self._repo.dirstate
1212 1212 for f in d:
1213 1213 if d[f] != 'r':
1214 1214 yield f
1215 1215
1216 1216 def __contains__(self, key):
1217 1217 return self._repo.dirstate[key] not in "?r"
1218 1218
1219 1219 @propertycache
1220 1220 def _parents(self):
1221 1221 p = self._repo.dirstate.parents()
1222 1222 if p[1] == nullid:
1223 1223 p = p[:-1]
1224 1224 return [changectx(self._repo, x) for x in p]
1225 1225
1226 1226 def filectx(self, path, filelog=None):
1227 1227 """get a file context from the working directory"""
1228 1228 return workingfilectx(self._repo, path, workingctx=self,
1229 1229 filelog=filelog)
1230 1230
1231 1231 def dirty(self, missing=False, merge=True, branch=True):
1232 1232 "check whether a working directory is modified"
1233 1233 # check subrepos first
1234 1234 for s in sorted(self.substate):
1235 1235 if self.sub(s).dirty():
1236 1236 return True
1237 1237 # check current working dir
1238 1238 return ((merge and self.p2()) or
1239 1239 (branch and self.branch() != self.p1().branch()) or
1240 1240 self.modified() or self.added() or self.removed() or
1241 1241 (missing and self.deleted()))
1242 1242
1243 1243 def add(self, list, prefix=""):
1244 1244 join = lambda f: os.path.join(prefix, f)
1245 1245 wlock = self._repo.wlock()
1246 1246 ui, ds = self._repo.ui, self._repo.dirstate
1247 1247 try:
1248 1248 rejected = []
1249 1249 lstat = self._repo.wvfs.lstat
1250 1250 for f in list:
1251 1251 scmutil.checkportable(ui, join(f))
1252 1252 try:
1253 1253 st = lstat(f)
1254 1254 except OSError:
1255 1255 ui.warn(_("%s does not exist!\n") % join(f))
1256 1256 rejected.append(f)
1257 1257 continue
1258 1258 if st.st_size > 10000000:
1259 1259 ui.warn(_("%s: up to %d MB of RAM may be required "
1260 1260 "to manage this file\n"
1261 1261 "(use 'hg revert %s' to cancel the "
1262 1262 "pending addition)\n")
1263 1263 % (f, 3 * st.st_size // 1000000, join(f)))
1264 1264 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1265 1265 ui.warn(_("%s not added: only files and symlinks "
1266 1266 "supported currently\n") % join(f))
1267 1267 rejected.append(f)
1268 1268 elif ds[f] in 'amn':
1269 1269 ui.warn(_("%s already tracked!\n") % join(f))
1270 1270 elif ds[f] == 'r':
1271 1271 ds.normallookup(f)
1272 1272 else:
1273 1273 ds.add(f)
1274 1274 return rejected
1275 1275 finally:
1276 1276 wlock.release()
1277 1277
1278 1278 def forget(self, files, prefix=""):
1279 1279 join = lambda f: os.path.join(prefix, f)
1280 1280 wlock = self._repo.wlock()
1281 1281 try:
1282 1282 rejected = []
1283 1283 for f in files:
1284 1284 if f not in self._repo.dirstate:
1285 1285 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
1286 1286 rejected.append(f)
1287 1287 elif self._repo.dirstate[f] != 'a':
1288 1288 self._repo.dirstate.remove(f)
1289 1289 else:
1290 1290 self._repo.dirstate.drop(f)
1291 1291 return rejected
1292 1292 finally:
1293 1293 wlock.release()
1294 1294
1295 1295 def undelete(self, list):
1296 1296 pctxs = self.parents()
1297 1297 wlock = self._repo.wlock()
1298 1298 try:
1299 1299 for f in list:
1300 1300 if self._repo.dirstate[f] != 'r':
1301 1301 self._repo.ui.warn(_("%s not removed!\n") % f)
1302 1302 else:
1303 1303 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
1304 1304 t = fctx.data()
1305 1305 self._repo.wwrite(f, t, fctx.flags())
1306 1306 self._repo.dirstate.normal(f)
1307 1307 finally:
1308 1308 wlock.release()
1309 1309
1310 1310 def copy(self, source, dest):
1311 1311 try:
1312 1312 st = self._repo.wvfs.lstat(dest)
1313 1313 except OSError, err:
1314 1314 if err.errno != errno.ENOENT:
1315 1315 raise
1316 1316 self._repo.ui.warn(_("%s does not exist!\n") % dest)
1317 1317 return
1318 1318 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
1319 1319 self._repo.ui.warn(_("copy failed: %s is not a file or a "
1320 1320 "symbolic link\n") % dest)
1321 1321 else:
1322 1322 wlock = self._repo.wlock()
1323 1323 try:
1324 1324 if self._repo.dirstate[dest] in '?':
1325 1325 self._repo.dirstate.add(dest)
1326 1326 elif self._repo.dirstate[dest] in 'r':
1327 1327 self._repo.dirstate.normallookup(dest)
1328 1328 self._repo.dirstate.copy(source, dest)
1329 1329 finally:
1330 1330 wlock.release()
1331 1331
1332 1332 def _filtersuspectsymlink(self, files):
1333 1333 if not files or self._repo.dirstate._checklink:
1334 1334 return files
1335 1335
1336 1336 # Symlink placeholders may get non-symlink-like contents
1337 1337 # via user error or dereferencing by NFS or Samba servers,
1338 1338 # so we filter out any placeholders that don't look like a
1339 1339 # symlink
1340 1340 sane = []
1341 1341 for f in files:
1342 1342 if self.flags(f) == 'l':
1343 1343 d = self[f].data()
1344 1344 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1345 1345 self._repo.ui.debug('ignoring suspect symlink placeholder'
1346 1346 ' "%s"\n' % f)
1347 1347 continue
1348 1348 sane.append(f)
1349 1349 return sane
1350 1350
1351 1351 def _checklookup(self, files):
1352 1352 # check for any possibly clean files
1353 1353 if not files:
1354 1354 return [], []
1355 1355
1356 1356 modified = []
1357 1357 fixup = []
1358 1358 pctx = self._parents[0]
1359 1359 # do a full compare of any files that might have changed
1360 1360 for f in sorted(files):
1361 1361 if (f not in pctx or self.flags(f) != pctx.flags(f)
1362 1362 or pctx[f].cmp(self[f])):
1363 1363 modified.append(f)
1364 1364 else:
1365 1365 fixup.append(f)
1366 1366
1367 1367 # update dirstate for files that are actually clean
1368 1368 if fixup:
1369 1369 try:
1370 1370 # updating the dirstate is optional
1371 1371 # so we don't wait on the lock
1372 1372 # wlock can invalidate the dirstate, so cache normal _after_
1373 1373 # taking the lock
1374 1374 wlock = self._repo.wlock(False)
1375 1375 normal = self._repo.dirstate.normal
1376 1376 try:
1377 1377 for f in fixup:
1378 1378 normal(f)
1379 1379 finally:
1380 1380 wlock.release()
1381 1381 except error.LockError:
1382 1382 pass
1383 1383 return modified, fixup
1384 1384
1385 1385 def _manifestmatches(self, match, s):
1386 1386 """Slow path for workingctx
1387 1387
1388 1388 The fast path is when we compare the working directory to its parent
1389 1389 which means this function is comparing with a non-parent; therefore we
1390 1390 need to build a manifest and return what matches.
1391 1391 """
1392 1392 mf = self._repo['.']._manifestmatches(match, s)
1393 1393 for f in s.modified + s.added:
1394 1394 mf[f] = None
1395 1395 mf.setflag(f, self.flags(f))
1396 1396 for f in s.removed:
1397 1397 if f in mf:
1398 1398 del mf[f]
1399 1399 return mf
1400 1400
1401 1401 def _dirstatestatus(self, match=None, ignored=False, clean=False,
1402 1402 unknown=False):
1403 1403 '''Gets the status from the dirstate -- internal use only.'''
1404 1404 listignored, listclean, listunknown = ignored, clean, unknown
1405 1405 match = match or matchmod.always(self._repo.root, self._repo.getcwd())
1406 1406 subrepos = []
1407 1407 if '.hgsub' in self:
1408 1408 subrepos = sorted(self.substate)
1409 1409 cmp, s = self._repo.dirstate.status(match, subrepos, listignored,
1410 1410 listclean, listunknown)
1411 1411
1412 1412 # check for any possibly clean files
1413 1413 if cmp:
1414 1414 modified2, fixup = self._checklookup(cmp)
1415 1415 s.modified.extend(modified2)
1416 1416
1417 1417 # update dirstate for files that are actually clean
1418 1418 if fixup and listclean:
1419 1419 s.clean.extend(fixup)
1420 1420
1421 1421 return s
1422 1422
1423 1423 def _buildstatus(self, other, s, match, listignored, listclean,
1424 1424 listunknown):
1425 1425 """build a status with respect to another context
1426 1426
1427 1427 This includes logic for maintaining the fast path of status when
1428 1428 comparing the working directory against its parent, which is to skip
1429 1429 building a new manifest if self (working directory) is not comparing
1430 1430 against its parent (repo['.']).
1431 1431 """
1432 1432 s = self._dirstatestatus(match, listignored, listclean, listunknown)
1433 1433 # Filter out symlinks that, in the case of FAT32 and NTFS filesystems,
1434 1434 # might have accidentally ended up with the entire contents of the file
1435 1435 # they are supposed to be linking to.
1436 1436 s.modified[:] = self._filtersuspectsymlink(s.modified)
1437 1437 if other != self._repo['.']:
1438 1438 s = super(workingctx, self)._buildstatus(other, s, match,
1439 1439 listignored, listclean,
1440 1440 listunknown)
1441 1441 self._status = s
1442 1442 return s
1443 1443
1444 1444 def _matchstatus(self, other, match):
1445 1445 """override the match method with a filter for directory patterns
1446 1446
1447 1447 We use inheritance to customize the match.bad method only in cases of
1448 1448 workingctx since it belongs only to the working directory when
1449 1449 comparing against the parent changeset.
1450 1450
1451 1451 If we aren't comparing against the working directory's parent, then we
1452 1452 just use the default match object sent to us.
1453 1453 """
1454 1454 superself = super(workingctx, self)
1455 1455 match = superself._matchstatus(other, match)
1456 1456 if other != self._repo['.']:
1457 1457 def bad(f, msg):
1458 1458 # 'f' may be a directory pattern from 'match.files()',
1459 1459 # so 'f not in ctx1' is not enough
1460 1460 if f not in other and f not in other.dirs():
1461 1461 self._repo.ui.warn('%s: %s\n' %
1462 1462 (self._repo.dirstate.pathto(f), msg))
1463 1463 match.bad = bad
1464 1464 return match
1465 1465
1466 1466 class committablefilectx(basefilectx):
1467 1467 """A committablefilectx provides common functionality for a file context
1468 1468 that wants the ability to commit, e.g. workingfilectx or memfilectx."""
1469 1469 def __init__(self, repo, path, filelog=None, ctx=None):
1470 1470 self._repo = repo
1471 1471 self._path = path
1472 1472 self._changeid = None
1473 1473 self._filerev = self._filenode = None
1474 1474
1475 1475 if filelog is not None:
1476 1476 self._filelog = filelog
1477 1477 if ctx:
1478 1478 self._changectx = ctx
1479 1479
1480 1480 def __nonzero__(self):
1481 1481 return True
1482 1482
1483 1483 def parents(self):
1484 1484 '''return parent filectxs, following copies if necessary'''
1485 1485 def filenode(ctx, path):
1486 1486 return ctx._manifest.get(path, nullid)
1487 1487
1488 1488 path = self._path
1489 1489 fl = self._filelog
1490 1490 pcl = self._changectx._parents
1491 1491 renamed = self.renamed()
1492 1492
1493 1493 if renamed:
1494 1494 pl = [renamed + (None,)]
1495 1495 else:
1496 1496 pl = [(path, filenode(pcl[0], path), fl)]
1497 1497
1498 1498 for pc in pcl[1:]:
1499 1499 pl.append((path, filenode(pc, path), fl))
1500 1500
1501 1501 return [filectx(self._repo, p, fileid=n, filelog=l)
1502 1502 for p, n, l in pl if n != nullid]
1503 1503
1504 1504 def children(self):
1505 1505 return []
1506 1506
1507 1507 class workingfilectx(committablefilectx):
1508 1508 """A workingfilectx object makes access to data related to a particular
1509 1509 file in the working directory convenient."""
1510 1510 def __init__(self, repo, path, filelog=None, workingctx=None):
1511 1511 super(workingfilectx, self).__init__(repo, path, filelog, workingctx)
1512 1512
1513 1513 @propertycache
1514 1514 def _changectx(self):
1515 1515 return workingctx(self._repo)
1516 1516
1517 1517 def data(self):
1518 1518 return self._repo.wread(self._path)
1519 1519 def renamed(self):
1520 1520 rp = self._repo.dirstate.copied(self._path)
1521 1521 if not rp:
1522 1522 return None
1523 1523 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1524 1524
1525 1525 def size(self):
1526 1526 return self._repo.wvfs.lstat(self._path).st_size
1527 1527 def date(self):
1528 1528 t, tz = self._changectx.date()
1529 1529 try:
1530 1530 return (int(self._repo.wvfs.lstat(self._path).st_mtime), tz)
1531 1531 except OSError, err:
1532 1532 if err.errno != errno.ENOENT:
1533 1533 raise
1534 1534 return (t, tz)
1535 1535
1536 1536 def cmp(self, fctx):
1537 1537 """compare with other file context
1538 1538
1539 1539 returns True if different than fctx.
1540 1540 """
1541 1541 # fctx should be a filectx (not a workingfilectx)
1542 1542 # invert comparison to reuse the same code path
1543 1543 return fctx.cmp(self)
1544 1544
1545 1545 def remove(self, ignoremissing=False):
1546 1546 """wraps unlink for a repo's working directory"""
1547 1547 util.unlinkpath(self._repo.wjoin(self._path), ignoremissing)
1548 1548
1549 1549 def write(self, data, flags):
1550 1550 """wraps repo.wwrite"""
1551 1551 self._repo.wwrite(self._path, data, flags)
1552 1552
1553 1553 class memctx(committablectx):
1554 1554 """Use memctx to perform in-memory commits via localrepo.commitctx().
1555 1555
1556 1556 Revision information is supplied at initialization time while
1557 1557 related files data and is made available through a callback
1558 1558 mechanism. 'repo' is the current localrepo, 'parents' is a
1559 1559 sequence of two parent revisions identifiers (pass None for every
1560 1560 missing parent), 'text' is the commit message and 'files' lists
1561 1561 names of files touched by the revision (normalized and relative to
1562 1562 repository root).
1563 1563
1564 1564 filectxfn(repo, memctx, path) is a callable receiving the
1565 1565 repository, the current memctx object and the normalized path of
1566 1566 requested file, relative to repository root. It is fired by the
1567 1567 commit function for every file in 'files', but calls order is
1568 1568 undefined. If the file is available in the revision being
1569 1569 committed (updated or added), filectxfn returns a memfilectx
1570 1570 object. If the file was removed, filectxfn raises an
1571 1571 IOError. Moved files are represented by marking the source file
1572 1572 removed and the new file added with copy information (see
1573 1573 memfilectx).
1574 1574
1575 1575 user receives the committer name and defaults to current
1576 1576 repository username, date is the commit date in any format
1577 1577 supported by util.parsedate() and defaults to current date, extra
1578 1578 is a dictionary of metadata or is left empty.
1579 1579 """
1580 1580
1581 1581 # Mercurial <= 3.1 expects the filectxfn to raise IOError for missing files.
1582 1582 # Extensions that need to retain compatibility across Mercurial 3.1 can use
1583 1583 # this field to determine what to do in filectxfn.
1584 1584 _returnnoneformissingfiles = True
1585 1585
1586 1586 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1587 1587 date=None, extra=None, editor=False):
1588 1588 super(memctx, self).__init__(repo, text, user, date, extra)
1589 1589 self._rev = None
1590 1590 self._node = None
1591 1591 parents = [(p or nullid) for p in parents]
1592 1592 p1, p2 = parents
1593 1593 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1594 1594 files = sorted(set(files))
1595 1595 self._status = scmutil.status(files, [], [], [], [], [], [])
1596 1596 self._filectxfn = filectxfn
1597 1597 self.substate = {}
1598 1598
1599 1599 # if store is not callable, wrap it in a function
1600 1600 if not callable(filectxfn):
1601 1601 def getfilectx(repo, memctx, path):
1602 1602 fctx = filectxfn[path]
1603 1603 # this is weird but apparently we only keep track of one parent
1604 1604 # (why not only store that instead of a tuple?)
1605 1605 copied = fctx.renamed()
1606 1606 if copied:
1607 1607 copied = copied[0]
1608 1608 return memfilectx(repo, path, fctx.data(),
1609 1609 islink=fctx.islink(), isexec=fctx.isexec(),
1610 1610 copied=copied, memctx=memctx)
1611 1611 self._filectxfn = getfilectx
1612 1612
1613 1613 self._extra = extra and extra.copy() or {}
1614 1614 if self._extra.get('branch', '') == '':
1615 1615 self._extra['branch'] = 'default'
1616 1616
1617 1617 if editor:
1618 1618 self._text = editor(self._repo, self, [])
1619 1619 self._repo.savecommitmessage(self._text)
1620 1620
1621 1621 def filectx(self, path, filelog=None):
1622 1622 """get a file context from the working directory
1623 1623
1624 1624 Returns None if file doesn't exist and should be removed."""
1625 1625 return self._filectxfn(self._repo, self, path)
1626 1626
1627 1627 def commit(self):
1628 1628 """commit context to the repo"""
1629 1629 return self._repo.commitctx(self)
1630 1630
1631 1631 @propertycache
1632 1632 def _manifest(self):
1633 1633 """generate a manifest based on the return values of filectxfn"""
1634 1634
1635 1635 # keep this simple for now; just worry about p1
1636 1636 pctx = self._parents[0]
1637 1637 man = pctx.manifest().copy()
1638 1638
1639 1639 for f, fnode in man.iteritems():
1640 1640 p1node = nullid
1641 1641 p2node = nullid
1642 1642 p = pctx[f].parents() # if file isn't in pctx, check p2?
1643 1643 if len(p) > 0:
1644 1644 p1node = p[0].node()
1645 1645 if len(p) > 1:
1646 1646 p2node = p[1].node()
1647 1647 man[f] = revlog.hash(self[f].data(), p1node, p2node)
1648 1648
1649 1649 return man
1650 1650
1651 1651
1652 1652 class memfilectx(committablefilectx):
1653 1653 """memfilectx represents an in-memory file to commit.
1654 1654
1655 1655 See memctx and committablefilectx for more details.
1656 1656 """
1657 1657 def __init__(self, repo, path, data, islink=False,
1658 1658 isexec=False, copied=None, memctx=None):
1659 1659 """
1660 1660 path is the normalized file path relative to repository root.
1661 1661 data is the file content as a string.
1662 1662 islink is True if the file is a symbolic link.
1663 1663 isexec is True if the file is executable.
1664 1664 copied is the source file path if current file was copied in the
1665 1665 revision being committed, or None."""
1666 1666 super(memfilectx, self).__init__(repo, path, None, memctx)
1667 1667 self._data = data
1668 1668 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1669 1669 self._copied = None
1670 1670 if copied:
1671 1671 self._copied = (copied, nullid)
1672 1672
1673 1673 def data(self):
1674 1674 return self._data
1675 1675 def size(self):
1676 1676 return len(self.data())
1677 1677 def flags(self):
1678 1678 return self._flags
1679 1679 def renamed(self):
1680 1680 return self._copied
1681 1681
1682 1682 def remove(self, ignoremissing=False):
1683 1683 """wraps unlink for a repo's working directory"""
1684 1684 # need to figure out what to do here
1685 1685 del self._changectx[self._path]
1686 1686
1687 1687 def write(self, data, flags):
1688 1688 """wraps repo.wwrite"""
1689 1689 self._data = data
@@ -1,1827 +1,1827 b''
1 1 # localrepo.py - read/write repository class for mercurial
2 2 #
3 3 # Copyright 2005-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 from node import hex, nullid, short
8 8 from i18n import _
9 9 import urllib
10 10 import peer, changegroup, subrepo, pushkey, obsolete, repoview
11 11 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
12 12 import lock as lockmod
13 13 import transaction, store, encoding, exchange, bundle2
14 14 import scmutil, util, extensions, hook, error, revset
15 15 import match as matchmod
16 16 import merge as mergemod
17 17 import tags as tagsmod
18 18 from lock import release
19 19 import weakref, errno, os, time, inspect
20 20 import branchmap, pathutil
21 21 import namespaces
22 22 propertycache = util.propertycache
23 23 filecache = scmutil.filecache
24 24
25 25 class repofilecache(filecache):
26 26 """All filecache usage on repo are done for logic that should be unfiltered
27 27 """
28 28
29 29 def __get__(self, repo, type=None):
30 30 return super(repofilecache, self).__get__(repo.unfiltered(), type)
31 31 def __set__(self, repo, value):
32 32 return super(repofilecache, self).__set__(repo.unfiltered(), value)
33 33 def __delete__(self, repo):
34 34 return super(repofilecache, self).__delete__(repo.unfiltered())
35 35
36 36 class storecache(repofilecache):
37 37 """filecache for files in the store"""
38 38 def join(self, obj, fname):
39 39 return obj.sjoin(fname)
40 40
41 41 class unfilteredpropertycache(propertycache):
42 42 """propertycache that apply to unfiltered repo only"""
43 43
44 44 def __get__(self, repo, type=None):
45 45 unfi = repo.unfiltered()
46 46 if unfi is repo:
47 47 return super(unfilteredpropertycache, self).__get__(unfi)
48 48 return getattr(unfi, self.name)
49 49
50 50 class filteredpropertycache(propertycache):
51 51 """propertycache that must take filtering in account"""
52 52
53 53 def cachevalue(self, obj, value):
54 54 object.__setattr__(obj, self.name, value)
55 55
56 56
57 57 def hasunfilteredcache(repo, name):
58 58 """check if a repo has an unfilteredpropertycache value for <name>"""
59 59 return name in vars(repo.unfiltered())
60 60
61 61 def unfilteredmethod(orig):
62 62 """decorate method that always need to be run on unfiltered version"""
63 63 def wrapper(repo, *args, **kwargs):
64 64 return orig(repo.unfiltered(), *args, **kwargs)
65 65 return wrapper
66 66
67 67 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
68 68 'unbundle'))
69 69 legacycaps = moderncaps.union(set(['changegroupsubset']))
70 70
71 71 class localpeer(peer.peerrepository):
72 72 '''peer for a local repo; reflects only the most recent API'''
73 73
74 74 def __init__(self, repo, caps=moderncaps):
75 75 peer.peerrepository.__init__(self)
76 76 self._repo = repo.filtered('served')
77 77 self.ui = repo.ui
78 78 self._caps = repo._restrictcapabilities(caps)
79 79 self.requirements = repo.requirements
80 80 self.supportedformats = repo.supportedformats
81 81
82 82 def close(self):
83 83 self._repo.close()
84 84
85 85 def _capabilities(self):
86 86 return self._caps
87 87
88 88 def local(self):
89 89 return self._repo
90 90
91 91 def canpush(self):
92 92 return True
93 93
94 94 def url(self):
95 95 return self._repo.url()
96 96
97 97 def lookup(self, key):
98 98 return self._repo.lookup(key)
99 99
100 100 def branchmap(self):
101 101 return self._repo.branchmap()
102 102
103 103 def heads(self):
104 104 return self._repo.heads()
105 105
106 106 def known(self, nodes):
107 107 return self._repo.known(nodes)
108 108
109 109 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
110 110 format='HG10', **kwargs):
111 111 cg = exchange.getbundle(self._repo, source, heads=heads,
112 112 common=common, bundlecaps=bundlecaps, **kwargs)
113 113 if bundlecaps is not None and 'HG2Y' in bundlecaps:
114 114 # When requesting a bundle2, getbundle returns a stream to make the
115 115 # wire level function happier. We need to build a proper object
116 116 # from it in local peer.
117 117 cg = bundle2.unbundle20(self.ui, cg)
118 118 return cg
119 119
120 120 # TODO We might want to move the next two calls into legacypeer and add
121 121 # unbundle instead.
122 122
123 123 def unbundle(self, cg, heads, url):
124 124 """apply a bundle on a repo
125 125
126 126 This function handles the repo locking itself."""
127 127 try:
128 128 cg = exchange.readbundle(self.ui, cg, None)
129 129 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
130 130 if util.safehasattr(ret, 'getchunks'):
131 131 # This is a bundle20 object, turn it into an unbundler.
132 132 # This little dance should be dropped eventually when the API
133 133 # is finally improved.
134 134 stream = util.chunkbuffer(ret.getchunks())
135 135 ret = bundle2.unbundle20(self.ui, stream)
136 136 return ret
137 137 except error.PushRaced, exc:
138 138 raise error.ResponseError(_('push failed:'), str(exc))
139 139
140 140 def lock(self):
141 141 return self._repo.lock()
142 142
143 143 def addchangegroup(self, cg, source, url):
144 144 return changegroup.addchangegroup(self._repo, cg, source, url)
145 145
146 146 def pushkey(self, namespace, key, old, new):
147 147 return self._repo.pushkey(namespace, key, old, new)
148 148
149 149 def listkeys(self, namespace):
150 150 return self._repo.listkeys(namespace)
151 151
152 152 def debugwireargs(self, one, two, three=None, four=None, five=None):
153 153 '''used to test argument passing over the wire'''
154 154 return "%s %s %s %s %s" % (one, two, three, four, five)
155 155
156 156 class locallegacypeer(localpeer):
157 157 '''peer extension which implements legacy methods too; used for tests with
158 158 restricted capabilities'''
159 159
160 160 def __init__(self, repo):
161 161 localpeer.__init__(self, repo, caps=legacycaps)
162 162
163 163 def branches(self, nodes):
164 164 return self._repo.branches(nodes)
165 165
166 166 def between(self, pairs):
167 167 return self._repo.between(pairs)
168 168
169 169 def changegroup(self, basenodes, source):
170 170 return changegroup.changegroup(self._repo, basenodes, source)
171 171
172 172 def changegroupsubset(self, bases, heads, source):
173 173 return changegroup.changegroupsubset(self._repo, bases, heads, source)
174 174
175 175 class localrepository(object):
176 176
177 177 supportedformats = set(('revlogv1', 'generaldelta'))
178 178 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
179 179 'dotencode'))
180 180 openerreqs = set(('revlogv1', 'generaldelta'))
181 181 requirements = ['revlogv1']
182 182 filtername = None
183 183
184 184 # a list of (ui, featureset) functions.
185 185 # only functions defined in module of enabled extensions are invoked
186 186 featuresetupfuncs = set()
187 187
188 188 def _baserequirements(self, create):
189 189 return self.requirements[:]
190 190
191 191 def __init__(self, baseui, path=None, create=False):
192 192 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
193 193 self.wopener = self.wvfs
194 194 self.root = self.wvfs.base
195 195 self.path = self.wvfs.join(".hg")
196 196 self.origroot = path
197 197 self.auditor = pathutil.pathauditor(self.root, self._checknested)
198 198 self.vfs = scmutil.vfs(self.path)
199 199 self.opener = self.vfs
200 200 self.baseui = baseui
201 201 self.ui = baseui.copy()
202 202 self.ui.copy = baseui.copy # prevent copying repo configuration
203 203 # A list of callback to shape the phase if no data were found.
204 204 # Callback are in the form: func(repo, roots) --> processed root.
205 205 # This list it to be filled by extension during repo setup
206 206 self._phasedefaults = []
207 207 try:
208 208 self.ui.readconfig(self.join("hgrc"), self.root)
209 209 extensions.loadall(self.ui)
210 210 except IOError:
211 211 pass
212 212
213 213 if self.featuresetupfuncs:
214 214 self.supported = set(self._basesupported) # use private copy
215 215 extmods = set(m.__name__ for n, m
216 216 in extensions.extensions(self.ui))
217 217 for setupfunc in self.featuresetupfuncs:
218 218 if setupfunc.__module__ in extmods:
219 219 setupfunc(self.ui, self.supported)
220 220 else:
221 221 self.supported = self._basesupported
222 222
223 223 if not self.vfs.isdir():
224 224 if create:
225 225 if not self.wvfs.exists():
226 226 self.wvfs.makedirs()
227 227 self.vfs.makedir(notindexed=True)
228 228 requirements = self._baserequirements(create)
229 229 if self.ui.configbool('format', 'usestore', True):
230 230 self.vfs.mkdir("store")
231 231 requirements.append("store")
232 232 if self.ui.configbool('format', 'usefncache', True):
233 233 requirements.append("fncache")
234 234 if self.ui.configbool('format', 'dotencode', True):
235 235 requirements.append('dotencode')
236 236 # create an invalid changelog
237 237 self.vfs.append(
238 238 "00changelog.i",
239 239 '\0\0\0\2' # represents revlogv2
240 240 ' dummy changelog to prevent using the old repo layout'
241 241 )
242 242 if self.ui.configbool('format', 'generaldelta', False):
243 243 requirements.append("generaldelta")
244 244 requirements = set(requirements)
245 245 else:
246 246 raise error.RepoError(_("repository %s not found") % path)
247 247 elif create:
248 248 raise error.RepoError(_("repository %s already exists") % path)
249 249 else:
250 250 try:
251 251 requirements = scmutil.readrequires(self.vfs, self.supported)
252 252 except IOError, inst:
253 253 if inst.errno != errno.ENOENT:
254 254 raise
255 255 requirements = set()
256 256
257 257 self.sharedpath = self.path
258 258 try:
259 259 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
260 260 realpath=True)
261 261 s = vfs.base
262 262 if not vfs.exists():
263 263 raise error.RepoError(
264 264 _('.hg/sharedpath points to nonexistent directory %s') % s)
265 265 self.sharedpath = s
266 266 except IOError, inst:
267 267 if inst.errno != errno.ENOENT:
268 268 raise
269 269
270 270 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
271 271 self.spath = self.store.path
272 272 self.svfs = self.store.vfs
273 273 self.sopener = self.svfs
274 274 self.sjoin = self.store.join
275 275 self.vfs.createmode = self.store.createmode
276 276 self._applyrequirements(requirements)
277 277 if create:
278 278 self._writerequirements()
279 279
280 280
281 281 self._branchcaches = {}
282 282 self.filterpats = {}
283 283 self._datafilters = {}
284 284 self._transref = self._lockref = self._wlockref = None
285 285
286 286 # A cache for various files under .hg/ that tracks file changes,
287 287 # (used by the filecache decorator)
288 288 #
289 289 # Maps a property name to its util.filecacheentry
290 290 self._filecache = {}
291 291
292 292 # hold sets of revision to be filtered
293 293 # should be cleared when something might have changed the filter value:
294 294 # - new changesets,
295 295 # - phase change,
296 296 # - new obsolescence marker,
297 297 # - working directory parent change,
298 298 # - bookmark changes
299 299 self.filteredrevcache = {}
300 300
301 301 # generic mapping between names and nodes
302 self.names = namespaces.namespaces(self)
302 self.names = namespaces.namespaces()
303 303
304 304 def close(self):
305 305 pass
306 306
307 307 def _restrictcapabilities(self, caps):
308 308 # bundle2 is not ready for prime time, drop it unless explicitly
309 309 # required by the tests (or some brave tester)
310 310 if self.ui.configbool('experimental', 'bundle2-exp', False):
311 311 caps = set(caps)
312 312 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
313 313 caps.add('bundle2-exp=' + urllib.quote(capsblob))
314 314 return caps
315 315
316 316 def _applyrequirements(self, requirements):
317 317 self.requirements = requirements
318 318 self.sopener.options = dict((r, 1) for r in requirements
319 319 if r in self.openerreqs)
320 320 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
321 321 if chunkcachesize is not None:
322 322 self.sopener.options['chunkcachesize'] = chunkcachesize
323 323 maxchainlen = self.ui.configint('format', 'maxchainlen')
324 324 if maxchainlen is not None:
325 325 self.sopener.options['maxchainlen'] = maxchainlen
326 326
327 327 def _writerequirements(self):
328 328 reqfile = self.opener("requires", "w")
329 329 for r in sorted(self.requirements):
330 330 reqfile.write("%s\n" % r)
331 331 reqfile.close()
332 332
333 333 def _checknested(self, path):
334 334 """Determine if path is a legal nested repository."""
335 335 if not path.startswith(self.root):
336 336 return False
337 337 subpath = path[len(self.root) + 1:]
338 338 normsubpath = util.pconvert(subpath)
339 339
340 340 # XXX: Checking against the current working copy is wrong in
341 341 # the sense that it can reject things like
342 342 #
343 343 # $ hg cat -r 10 sub/x.txt
344 344 #
345 345 # if sub/ is no longer a subrepository in the working copy
346 346 # parent revision.
347 347 #
348 348 # However, it can of course also allow things that would have
349 349 # been rejected before, such as the above cat command if sub/
350 350 # is a subrepository now, but was a normal directory before.
351 351 # The old path auditor would have rejected by mistake since it
352 352 # panics when it sees sub/.hg/.
353 353 #
354 354 # All in all, checking against the working copy seems sensible
355 355 # since we want to prevent access to nested repositories on
356 356 # the filesystem *now*.
357 357 ctx = self[None]
358 358 parts = util.splitpath(subpath)
359 359 while parts:
360 360 prefix = '/'.join(parts)
361 361 if prefix in ctx.substate:
362 362 if prefix == normsubpath:
363 363 return True
364 364 else:
365 365 sub = ctx.sub(prefix)
366 366 return sub.checknested(subpath[len(prefix) + 1:])
367 367 else:
368 368 parts.pop()
369 369 return False
370 370
371 371 def peer(self):
372 372 return localpeer(self) # not cached to avoid reference cycle
373 373
374 374 def unfiltered(self):
375 375 """Return unfiltered version of the repository
376 376
377 377 Intended to be overwritten by filtered repo."""
378 378 return self
379 379
380 380 def filtered(self, name):
381 381 """Return a filtered version of a repository"""
382 382 # build a new class with the mixin and the current class
383 383 # (possibly subclass of the repo)
384 384 class proxycls(repoview.repoview, self.unfiltered().__class__):
385 385 pass
386 386 return proxycls(self, name)
387 387
388 388 @repofilecache('bookmarks')
389 389 def _bookmarks(self):
390 390 return bookmarks.bmstore(self)
391 391
392 392 @repofilecache('bookmarks.current')
393 393 def _bookmarkcurrent(self):
394 394 return bookmarks.readcurrent(self)
395 395
396 396 def bookmarkheads(self, bookmark):
397 397 name = bookmark.split('@', 1)[0]
398 398 heads = []
399 399 for mark, n in self._bookmarks.iteritems():
400 400 if mark.split('@', 1)[0] == name:
401 401 heads.append(n)
402 402 return heads
403 403
404 404 @storecache('phaseroots')
405 405 def _phasecache(self):
406 406 return phases.phasecache(self, self._phasedefaults)
407 407
408 408 @storecache('obsstore')
409 409 def obsstore(self):
410 410 # read default format for new obsstore.
411 411 defaultformat = self.ui.configint('format', 'obsstore-version', None)
412 412 # rely on obsstore class default when possible.
413 413 kwargs = {}
414 414 if defaultformat is not None:
415 415 kwargs['defaultformat'] = defaultformat
416 416 readonly = not obsolete.isenabled(self, obsolete.createmarkersopt)
417 417 store = obsolete.obsstore(self.sopener, readonly=readonly,
418 418 **kwargs)
419 419 if store and readonly:
420 420 # message is rare enough to not be translated
421 421 msg = 'obsolete feature not enabled but %i markers found!\n'
422 422 self.ui.warn(msg % len(list(store)))
423 423 return store
424 424
425 425 @storecache('00changelog.i')
426 426 def changelog(self):
427 427 c = changelog.changelog(self.sopener)
428 428 if 'HG_PENDING' in os.environ:
429 429 p = os.environ['HG_PENDING']
430 430 if p.startswith(self.root):
431 431 c.readpending('00changelog.i.a')
432 432 return c
433 433
434 434 @storecache('00manifest.i')
435 435 def manifest(self):
436 436 return manifest.manifest(self.sopener)
437 437
438 438 @repofilecache('dirstate')
439 439 def dirstate(self):
440 440 warned = [0]
441 441 def validate(node):
442 442 try:
443 443 self.changelog.rev(node)
444 444 return node
445 445 except error.LookupError:
446 446 if not warned[0]:
447 447 warned[0] = True
448 448 self.ui.warn(_("warning: ignoring unknown"
449 449 " working parent %s!\n") % short(node))
450 450 return nullid
451 451
452 452 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
453 453
454 454 def __getitem__(self, changeid):
455 455 if changeid is None:
456 456 return context.workingctx(self)
457 457 return context.changectx(self, changeid)
458 458
459 459 def __contains__(self, changeid):
460 460 try:
461 461 return bool(self.lookup(changeid))
462 462 except error.RepoLookupError:
463 463 return False
464 464
465 465 def __nonzero__(self):
466 466 return True
467 467
468 468 def __len__(self):
469 469 return len(self.changelog)
470 470
471 471 def __iter__(self):
472 472 return iter(self.changelog)
473 473
474 474 def revs(self, expr, *args):
475 475 '''Return a list of revisions matching the given revset'''
476 476 expr = revset.formatspec(expr, *args)
477 477 m = revset.match(None, expr)
478 478 return m(self, revset.spanset(self))
479 479
480 480 def set(self, expr, *args):
481 481 '''
482 482 Yield a context for each matching revision, after doing arg
483 483 replacement via revset.formatspec
484 484 '''
485 485 for r in self.revs(expr, *args):
486 486 yield self[r]
487 487
488 488 def url(self):
489 489 return 'file:' + self.root
490 490
491 491 def hook(self, name, throw=False, **args):
492 492 """Call a hook, passing this repo instance.
493 493
494 494 This a convenience method to aid invoking hooks. Extensions likely
495 495 won't call this unless they have registered a custom hook or are
496 496 replacing code that is expected to call a hook.
497 497 """
498 498 return hook.hook(self.ui, self, name, throw, **args)
499 499
500 500 @unfilteredmethod
501 501 def _tag(self, names, node, message, local, user, date, extra={},
502 502 editor=False):
503 503 if isinstance(names, str):
504 504 names = (names,)
505 505
506 506 branches = self.branchmap()
507 507 for name in names:
508 508 self.hook('pretag', throw=True, node=hex(node), tag=name,
509 509 local=local)
510 510 if name in branches:
511 511 self.ui.warn(_("warning: tag %s conflicts with existing"
512 512 " branch name\n") % name)
513 513
514 514 def writetags(fp, names, munge, prevtags):
515 515 fp.seek(0, 2)
516 516 if prevtags and prevtags[-1] != '\n':
517 517 fp.write('\n')
518 518 for name in names:
519 519 m = munge and munge(name) or name
520 520 if (self._tagscache.tagtypes and
521 521 name in self._tagscache.tagtypes):
522 522 old = self.tags().get(name, nullid)
523 523 fp.write('%s %s\n' % (hex(old), m))
524 524 fp.write('%s %s\n' % (hex(node), m))
525 525 fp.close()
526 526
527 527 prevtags = ''
528 528 if local:
529 529 try:
530 530 fp = self.opener('localtags', 'r+')
531 531 except IOError:
532 532 fp = self.opener('localtags', 'a')
533 533 else:
534 534 prevtags = fp.read()
535 535
536 536 # local tags are stored in the current charset
537 537 writetags(fp, names, None, prevtags)
538 538 for name in names:
539 539 self.hook('tag', node=hex(node), tag=name, local=local)
540 540 return
541 541
542 542 try:
543 543 fp = self.wfile('.hgtags', 'rb+')
544 544 except IOError, e:
545 545 if e.errno != errno.ENOENT:
546 546 raise
547 547 fp = self.wfile('.hgtags', 'ab')
548 548 else:
549 549 prevtags = fp.read()
550 550
551 551 # committed tags are stored in UTF-8
552 552 writetags(fp, names, encoding.fromlocal, prevtags)
553 553
554 554 fp.close()
555 555
556 556 self.invalidatecaches()
557 557
558 558 if '.hgtags' not in self.dirstate:
559 559 self[None].add(['.hgtags'])
560 560
561 561 m = matchmod.exact(self.root, '', ['.hgtags'])
562 562 tagnode = self.commit(message, user, date, extra=extra, match=m,
563 563 editor=editor)
564 564
565 565 for name in names:
566 566 self.hook('tag', node=hex(node), tag=name, local=local)
567 567
568 568 return tagnode
569 569
570 570 def tag(self, names, node, message, local, user, date, editor=False):
571 571 '''tag a revision with one or more symbolic names.
572 572
573 573 names is a list of strings or, when adding a single tag, names may be a
574 574 string.
575 575
576 576 if local is True, the tags are stored in a per-repository file.
577 577 otherwise, they are stored in the .hgtags file, and a new
578 578 changeset is committed with the change.
579 579
580 580 keyword arguments:
581 581
582 582 local: whether to store tags in non-version-controlled file
583 583 (default False)
584 584
585 585 message: commit message to use if committing
586 586
587 587 user: name of user to use if committing
588 588
589 589 date: date tuple to use if committing'''
590 590
591 591 if not local:
592 592 m = matchmod.exact(self.root, '', ['.hgtags'])
593 593 if util.any(self.status(match=m, unknown=True, ignored=True)):
594 594 raise util.Abort(_('working copy of .hgtags is changed'),
595 595 hint=_('please commit .hgtags manually'))
596 596
597 597 self.tags() # instantiate the cache
598 598 self._tag(names, node, message, local, user, date, editor=editor)
599 599
600 600 @filteredpropertycache
601 601 def _tagscache(self):
602 602 '''Returns a tagscache object that contains various tags related
603 603 caches.'''
604 604
605 605 # This simplifies its cache management by having one decorated
606 606 # function (this one) and the rest simply fetch things from it.
607 607 class tagscache(object):
608 608 def __init__(self):
609 609 # These two define the set of tags for this repository. tags
610 610 # maps tag name to node; tagtypes maps tag name to 'global' or
611 611 # 'local'. (Global tags are defined by .hgtags across all
612 612 # heads, and local tags are defined in .hg/localtags.)
613 613 # They constitute the in-memory cache of tags.
614 614 self.tags = self.tagtypes = None
615 615
616 616 self.nodetagscache = self.tagslist = None
617 617
618 618 cache = tagscache()
619 619 cache.tags, cache.tagtypes = self._findtags()
620 620
621 621 return cache
622 622
623 623 def tags(self):
624 624 '''return a mapping of tag to node'''
625 625 t = {}
626 626 if self.changelog.filteredrevs:
627 627 tags, tt = self._findtags()
628 628 else:
629 629 tags = self._tagscache.tags
630 630 for k, v in tags.iteritems():
631 631 try:
632 632 # ignore tags to unknown nodes
633 633 self.changelog.rev(v)
634 634 t[k] = v
635 635 except (error.LookupError, ValueError):
636 636 pass
637 637 return t
638 638
639 639 def _findtags(self):
640 640 '''Do the hard work of finding tags. Return a pair of dicts
641 641 (tags, tagtypes) where tags maps tag name to node, and tagtypes
642 642 maps tag name to a string like \'global\' or \'local\'.
643 643 Subclasses or extensions are free to add their own tags, but
644 644 should be aware that the returned dicts will be retained for the
645 645 duration of the localrepo object.'''
646 646
647 647 # XXX what tagtype should subclasses/extensions use? Currently
648 648 # mq and bookmarks add tags, but do not set the tagtype at all.
649 649 # Should each extension invent its own tag type? Should there
650 650 # be one tagtype for all such "virtual" tags? Or is the status
651 651 # quo fine?
652 652
653 653 alltags = {} # map tag name to (node, hist)
654 654 tagtypes = {}
655 655
656 656 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
657 657 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
658 658
659 659 # Build the return dicts. Have to re-encode tag names because
660 660 # the tags module always uses UTF-8 (in order not to lose info
661 661 # writing to the cache), but the rest of Mercurial wants them in
662 662 # local encoding.
663 663 tags = {}
664 664 for (name, (node, hist)) in alltags.iteritems():
665 665 if node != nullid:
666 666 tags[encoding.tolocal(name)] = node
667 667 tags['tip'] = self.changelog.tip()
668 668 tagtypes = dict([(encoding.tolocal(name), value)
669 669 for (name, value) in tagtypes.iteritems()])
670 670 return (tags, tagtypes)
671 671
672 672 def tagtype(self, tagname):
673 673 '''
674 674 return the type of the given tag. result can be:
675 675
676 676 'local' : a local tag
677 677 'global' : a global tag
678 678 None : tag does not exist
679 679 '''
680 680
681 681 return self._tagscache.tagtypes.get(tagname)
682 682
683 683 def tagslist(self):
684 684 '''return a list of tags ordered by revision'''
685 685 if not self._tagscache.tagslist:
686 686 l = []
687 687 for t, n in self.tags().iteritems():
688 688 l.append((self.changelog.rev(n), t, n))
689 689 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
690 690
691 691 return self._tagscache.tagslist
692 692
693 693 def nodetags(self, node):
694 694 '''return the tags associated with a node'''
695 695 if not self._tagscache.nodetagscache:
696 696 nodetagscache = {}
697 697 for t, n in self._tagscache.tags.iteritems():
698 698 nodetagscache.setdefault(n, []).append(t)
699 699 for tags in nodetagscache.itervalues():
700 700 tags.sort()
701 701 self._tagscache.nodetagscache = nodetagscache
702 702 return self._tagscache.nodetagscache.get(node, [])
703 703
704 704 def nodebookmarks(self, node):
705 705 marks = []
706 706 for bookmark, n in self._bookmarks.iteritems():
707 707 if n == node:
708 708 marks.append(bookmark)
709 709 return sorted(marks)
710 710
711 711 def branchmap(self):
712 712 '''returns a dictionary {branch: [branchheads]} with branchheads
713 713 ordered by increasing revision number'''
714 714 branchmap.updatecache(self)
715 715 return self._branchcaches[self.filtername]
716 716
717 717 def branchtip(self, branch):
718 718 '''return the tip node for a given branch'''
719 719 try:
720 720 return self.branchmap().branchtip(branch)
721 721 except KeyError:
722 722 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
723 723
724 724 def lookup(self, key):
725 725 return self[key].node()
726 726
727 727 def lookupbranch(self, key, remote=None):
728 728 repo = remote or self
729 729 if key in repo.branchmap():
730 730 return key
731 731
732 732 repo = (remote and remote.local()) and remote or self
733 733 return repo[key].branch()
734 734
735 735 def known(self, nodes):
736 736 nm = self.changelog.nodemap
737 737 pc = self._phasecache
738 738 result = []
739 739 for n in nodes:
740 740 r = nm.get(n)
741 741 resp = not (r is None or pc.phase(self, r) >= phases.secret)
742 742 result.append(resp)
743 743 return result
744 744
745 745 def local(self):
746 746 return self
747 747
748 748 def cancopy(self):
749 749 # so statichttprepo's override of local() works
750 750 if not self.local():
751 751 return False
752 752 if not self.ui.configbool('phases', 'publish', True):
753 753 return True
754 754 # if publishing we can't copy if there is filtered content
755 755 return not self.filtered('visible').changelog.filteredrevs
756 756
757 757 def join(self, f, *insidef):
758 758 return os.path.join(self.path, f, *insidef)
759 759
760 760 def wjoin(self, f, *insidef):
761 761 return os.path.join(self.root, f, *insidef)
762 762
763 763 def file(self, f):
764 764 if f[0] == '/':
765 765 f = f[1:]
766 766 return filelog.filelog(self.sopener, f)
767 767
768 768 def changectx(self, changeid):
769 769 return self[changeid]
770 770
771 771 def parents(self, changeid=None):
772 772 '''get list of changectxs for parents of changeid'''
773 773 return self[changeid].parents()
774 774
775 775 def setparents(self, p1, p2=nullid):
776 776 self.dirstate.beginparentchange()
777 777 copies = self.dirstate.setparents(p1, p2)
778 778 pctx = self[p1]
779 779 if copies:
780 780 # Adjust copy records, the dirstate cannot do it, it
781 781 # requires access to parents manifests. Preserve them
782 782 # only for entries added to first parent.
783 783 for f in copies:
784 784 if f not in pctx and copies[f] in pctx:
785 785 self.dirstate.copy(copies[f], f)
786 786 if p2 == nullid:
787 787 for f, s in sorted(self.dirstate.copies().items()):
788 788 if f not in pctx and s not in pctx:
789 789 self.dirstate.copy(None, f)
790 790 self.dirstate.endparentchange()
791 791
792 792 def filectx(self, path, changeid=None, fileid=None):
793 793 """changeid can be a changeset revision, node, or tag.
794 794 fileid can be a file revision or node."""
795 795 return context.filectx(self, path, changeid, fileid)
796 796
797 797 def getcwd(self):
798 798 return self.dirstate.getcwd()
799 799
800 800 def pathto(self, f, cwd=None):
801 801 return self.dirstate.pathto(f, cwd)
802 802
803 803 def wfile(self, f, mode='r'):
804 804 return self.wopener(f, mode)
805 805
806 806 def _link(self, f):
807 807 return self.wvfs.islink(f)
808 808
809 809 def _loadfilter(self, filter):
810 810 if filter not in self.filterpats:
811 811 l = []
812 812 for pat, cmd in self.ui.configitems(filter):
813 813 if cmd == '!':
814 814 continue
815 815 mf = matchmod.match(self.root, '', [pat])
816 816 fn = None
817 817 params = cmd
818 818 for name, filterfn in self._datafilters.iteritems():
819 819 if cmd.startswith(name):
820 820 fn = filterfn
821 821 params = cmd[len(name):].lstrip()
822 822 break
823 823 if not fn:
824 824 fn = lambda s, c, **kwargs: util.filter(s, c)
825 825 # Wrap old filters not supporting keyword arguments
826 826 if not inspect.getargspec(fn)[2]:
827 827 oldfn = fn
828 828 fn = lambda s, c, **kwargs: oldfn(s, c)
829 829 l.append((mf, fn, params))
830 830 self.filterpats[filter] = l
831 831 return self.filterpats[filter]
832 832
833 833 def _filter(self, filterpats, filename, data):
834 834 for mf, fn, cmd in filterpats:
835 835 if mf(filename):
836 836 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
837 837 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
838 838 break
839 839
840 840 return data
841 841
842 842 @unfilteredpropertycache
843 843 def _encodefilterpats(self):
844 844 return self._loadfilter('encode')
845 845
846 846 @unfilteredpropertycache
847 847 def _decodefilterpats(self):
848 848 return self._loadfilter('decode')
849 849
850 850 def adddatafilter(self, name, filter):
851 851 self._datafilters[name] = filter
852 852
853 853 def wread(self, filename):
854 854 if self._link(filename):
855 855 data = self.wvfs.readlink(filename)
856 856 else:
857 857 data = self.wopener.read(filename)
858 858 return self._filter(self._encodefilterpats, filename, data)
859 859
860 860 def wwrite(self, filename, data, flags):
861 861 data = self._filter(self._decodefilterpats, filename, data)
862 862 if 'l' in flags:
863 863 self.wopener.symlink(data, filename)
864 864 else:
865 865 self.wopener.write(filename, data)
866 866 if 'x' in flags:
867 867 self.wvfs.setflags(filename, False, True)
868 868
869 869 def wwritedata(self, filename, data):
870 870 return self._filter(self._decodefilterpats, filename, data)
871 871
872 872 def currenttransaction(self):
873 873 """return the current transaction or None if non exists"""
874 874 tr = self._transref and self._transref() or None
875 875 if tr and tr.running():
876 876 return tr
877 877 return None
878 878
879 879 def transaction(self, desc, report=None):
880 880 tr = self.currenttransaction()
881 881 if tr is not None:
882 882 return tr.nest()
883 883
884 884 # abort here if the journal already exists
885 885 if self.svfs.exists("journal"):
886 886 raise error.RepoError(
887 887 _("abandoned transaction found"),
888 888 hint=_("run 'hg recover' to clean up transaction"))
889 889
890 890 self._writejournal(desc)
891 891 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
892 892 rp = report and report or self.ui.warn
893 893 vfsmap = {'plain': self.opener} # root of .hg/
894 894 tr = transaction.transaction(rp, self.sopener, vfsmap,
895 895 "journal",
896 896 aftertrans(renames),
897 897 self.store.createmode)
898 898 # note: writing the fncache only during finalize mean that the file is
899 899 # outdated when running hooks. As fncache is used for streaming clone,
900 900 # this is not expected to break anything that happen during the hooks.
901 901 tr.addfinalize('flush-fncache', self.store.write)
902 902 self._transref = weakref.ref(tr)
903 903 return tr
904 904
905 905 def _journalfiles(self):
906 906 return ((self.svfs, 'journal'),
907 907 (self.vfs, 'journal.dirstate'),
908 908 (self.vfs, 'journal.branch'),
909 909 (self.vfs, 'journal.desc'),
910 910 (self.vfs, 'journal.bookmarks'),
911 911 (self.svfs, 'journal.phaseroots'))
912 912
913 913 def undofiles(self):
914 914 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
915 915
916 916 def _writejournal(self, desc):
917 917 self.opener.write("journal.dirstate",
918 918 self.opener.tryread("dirstate"))
919 919 self.opener.write("journal.branch",
920 920 encoding.fromlocal(self.dirstate.branch()))
921 921 self.opener.write("journal.desc",
922 922 "%d\n%s\n" % (len(self), desc))
923 923 self.opener.write("journal.bookmarks",
924 924 self.opener.tryread("bookmarks"))
925 925 self.sopener.write("journal.phaseroots",
926 926 self.sopener.tryread("phaseroots"))
927 927
928 928 def recover(self):
929 929 lock = self.lock()
930 930 try:
931 931 if self.svfs.exists("journal"):
932 932 self.ui.status(_("rolling back interrupted transaction\n"))
933 933 vfsmap = {'': self.sopener,
934 934 'plain': self.opener,}
935 935 transaction.rollback(self.sopener, vfsmap, "journal",
936 936 self.ui.warn)
937 937 self.invalidate()
938 938 return True
939 939 else:
940 940 self.ui.warn(_("no interrupted transaction available\n"))
941 941 return False
942 942 finally:
943 943 lock.release()
944 944
945 945 def rollback(self, dryrun=False, force=False):
946 946 wlock = lock = None
947 947 try:
948 948 wlock = self.wlock()
949 949 lock = self.lock()
950 950 if self.svfs.exists("undo"):
951 951 return self._rollback(dryrun, force)
952 952 else:
953 953 self.ui.warn(_("no rollback information available\n"))
954 954 return 1
955 955 finally:
956 956 release(lock, wlock)
957 957
958 958 @unfilteredmethod # Until we get smarter cache management
959 959 def _rollback(self, dryrun, force):
960 960 ui = self.ui
961 961 try:
962 962 args = self.opener.read('undo.desc').splitlines()
963 963 (oldlen, desc, detail) = (int(args[0]), args[1], None)
964 964 if len(args) >= 3:
965 965 detail = args[2]
966 966 oldtip = oldlen - 1
967 967
968 968 if detail and ui.verbose:
969 969 msg = (_('repository tip rolled back to revision %s'
970 970 ' (undo %s: %s)\n')
971 971 % (oldtip, desc, detail))
972 972 else:
973 973 msg = (_('repository tip rolled back to revision %s'
974 974 ' (undo %s)\n')
975 975 % (oldtip, desc))
976 976 except IOError:
977 977 msg = _('rolling back unknown transaction\n')
978 978 desc = None
979 979
980 980 if not force and self['.'] != self['tip'] and desc == 'commit':
981 981 raise util.Abort(
982 982 _('rollback of last commit while not checked out '
983 983 'may lose data'), hint=_('use -f to force'))
984 984
985 985 ui.status(msg)
986 986 if dryrun:
987 987 return 0
988 988
989 989 parents = self.dirstate.parents()
990 990 self.destroying()
991 991 vfsmap = {'plain': self.opener}
992 992 transaction.rollback(self.sopener, vfsmap, 'undo', ui.warn)
993 993 if self.vfs.exists('undo.bookmarks'):
994 994 self.vfs.rename('undo.bookmarks', 'bookmarks')
995 995 if self.svfs.exists('undo.phaseroots'):
996 996 self.svfs.rename('undo.phaseroots', 'phaseroots')
997 997 self.invalidate()
998 998
999 999 parentgone = (parents[0] not in self.changelog.nodemap or
1000 1000 parents[1] not in self.changelog.nodemap)
1001 1001 if parentgone:
1002 1002 self.vfs.rename('undo.dirstate', 'dirstate')
1003 1003 try:
1004 1004 branch = self.opener.read('undo.branch')
1005 1005 self.dirstate.setbranch(encoding.tolocal(branch))
1006 1006 except IOError:
1007 1007 ui.warn(_('named branch could not be reset: '
1008 1008 'current branch is still \'%s\'\n')
1009 1009 % self.dirstate.branch())
1010 1010
1011 1011 self.dirstate.invalidate()
1012 1012 parents = tuple([p.rev() for p in self.parents()])
1013 1013 if len(parents) > 1:
1014 1014 ui.status(_('working directory now based on '
1015 1015 'revisions %d and %d\n') % parents)
1016 1016 else:
1017 1017 ui.status(_('working directory now based on '
1018 1018 'revision %d\n') % parents)
1019 1019 # TODO: if we know which new heads may result from this rollback, pass
1020 1020 # them to destroy(), which will prevent the branchhead cache from being
1021 1021 # invalidated.
1022 1022 self.destroyed()
1023 1023 return 0
1024 1024
1025 1025 def invalidatecaches(self):
1026 1026
1027 1027 if '_tagscache' in vars(self):
1028 1028 # can't use delattr on proxy
1029 1029 del self.__dict__['_tagscache']
1030 1030
1031 1031 self.unfiltered()._branchcaches.clear()
1032 1032 self.invalidatevolatilesets()
1033 1033
1034 1034 def invalidatevolatilesets(self):
1035 1035 self.filteredrevcache.clear()
1036 1036 obsolete.clearobscaches(self)
1037 1037
1038 1038 def invalidatedirstate(self):
1039 1039 '''Invalidates the dirstate, causing the next call to dirstate
1040 1040 to check if it was modified since the last time it was read,
1041 1041 rereading it if it has.
1042 1042
1043 1043 This is different to dirstate.invalidate() that it doesn't always
1044 1044 rereads the dirstate. Use dirstate.invalidate() if you want to
1045 1045 explicitly read the dirstate again (i.e. restoring it to a previous
1046 1046 known good state).'''
1047 1047 if hasunfilteredcache(self, 'dirstate'):
1048 1048 for k in self.dirstate._filecache:
1049 1049 try:
1050 1050 delattr(self.dirstate, k)
1051 1051 except AttributeError:
1052 1052 pass
1053 1053 delattr(self.unfiltered(), 'dirstate')
1054 1054
1055 1055 def invalidate(self):
1056 1056 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1057 1057 for k in self._filecache:
1058 1058 # dirstate is invalidated separately in invalidatedirstate()
1059 1059 if k == 'dirstate':
1060 1060 continue
1061 1061
1062 1062 try:
1063 1063 delattr(unfiltered, k)
1064 1064 except AttributeError:
1065 1065 pass
1066 1066 self.invalidatecaches()
1067 1067 self.store.invalidatecaches()
1068 1068
1069 1069 def invalidateall(self):
1070 1070 '''Fully invalidates both store and non-store parts, causing the
1071 1071 subsequent operation to reread any outside changes.'''
1072 1072 # extension should hook this to invalidate its caches
1073 1073 self.invalidate()
1074 1074 self.invalidatedirstate()
1075 1075
1076 1076 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1077 1077 try:
1078 1078 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1079 1079 except error.LockHeld, inst:
1080 1080 if not wait:
1081 1081 raise
1082 1082 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1083 1083 (desc, inst.locker))
1084 1084 # default to 600 seconds timeout
1085 1085 l = lockmod.lock(vfs, lockname,
1086 1086 int(self.ui.config("ui", "timeout", "600")),
1087 1087 releasefn, desc=desc)
1088 1088 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1089 1089 if acquirefn:
1090 1090 acquirefn()
1091 1091 return l
1092 1092
1093 1093 def _afterlock(self, callback):
1094 1094 """add a callback to the current repository lock.
1095 1095
1096 1096 The callback will be executed on lock release."""
1097 1097 l = self._lockref and self._lockref()
1098 1098 if l:
1099 1099 l.postrelease.append(callback)
1100 1100 else:
1101 1101 callback()
1102 1102
1103 1103 def lock(self, wait=True):
1104 1104 '''Lock the repository store (.hg/store) and return a weak reference
1105 1105 to the lock. Use this before modifying the store (e.g. committing or
1106 1106 stripping). If you are opening a transaction, get a lock as well.)'''
1107 1107 l = self._lockref and self._lockref()
1108 1108 if l is not None and l.held:
1109 1109 l.lock()
1110 1110 return l
1111 1111
1112 1112 def unlock():
1113 1113 for k, ce in self._filecache.items():
1114 1114 if k == 'dirstate' or k not in self.__dict__:
1115 1115 continue
1116 1116 ce.refresh()
1117 1117
1118 1118 l = self._lock(self.svfs, "lock", wait, unlock,
1119 1119 self.invalidate, _('repository %s') % self.origroot)
1120 1120 self._lockref = weakref.ref(l)
1121 1121 return l
1122 1122
1123 1123 def wlock(self, wait=True):
1124 1124 '''Lock the non-store parts of the repository (everything under
1125 1125 .hg except .hg/store) and return a weak reference to the lock.
1126 1126 Use this before modifying files in .hg.'''
1127 1127 l = self._wlockref and self._wlockref()
1128 1128 if l is not None and l.held:
1129 1129 l.lock()
1130 1130 return l
1131 1131
1132 1132 def unlock():
1133 1133 if self.dirstate.pendingparentchange():
1134 1134 self.dirstate.invalidate()
1135 1135 else:
1136 1136 self.dirstate.write()
1137 1137
1138 1138 self._filecache['dirstate'].refresh()
1139 1139
1140 1140 l = self._lock(self.vfs, "wlock", wait, unlock,
1141 1141 self.invalidatedirstate, _('working directory of %s') %
1142 1142 self.origroot)
1143 1143 self._wlockref = weakref.ref(l)
1144 1144 return l
1145 1145
1146 1146 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1147 1147 """
1148 1148 commit an individual file as part of a larger transaction
1149 1149 """
1150 1150
1151 1151 fname = fctx.path()
1152 1152 text = fctx.data()
1153 1153 flog = self.file(fname)
1154 1154 fparent1 = manifest1.get(fname, nullid)
1155 1155 fparent2 = manifest2.get(fname, nullid)
1156 1156
1157 1157 meta = {}
1158 1158 copy = fctx.renamed()
1159 1159 if copy and copy[0] != fname:
1160 1160 # Mark the new revision of this file as a copy of another
1161 1161 # file. This copy data will effectively act as a parent
1162 1162 # of this new revision. If this is a merge, the first
1163 1163 # parent will be the nullid (meaning "look up the copy data")
1164 1164 # and the second one will be the other parent. For example:
1165 1165 #
1166 1166 # 0 --- 1 --- 3 rev1 changes file foo
1167 1167 # \ / rev2 renames foo to bar and changes it
1168 1168 # \- 2 -/ rev3 should have bar with all changes and
1169 1169 # should record that bar descends from
1170 1170 # bar in rev2 and foo in rev1
1171 1171 #
1172 1172 # this allows this merge to succeed:
1173 1173 #
1174 1174 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1175 1175 # \ / merging rev3 and rev4 should use bar@rev2
1176 1176 # \- 2 --- 4 as the merge base
1177 1177 #
1178 1178
1179 1179 cfname = copy[0]
1180 1180 crev = manifest1.get(cfname)
1181 1181 newfparent = fparent2
1182 1182
1183 1183 if manifest2: # branch merge
1184 1184 if fparent2 == nullid or crev is None: # copied on remote side
1185 1185 if cfname in manifest2:
1186 1186 crev = manifest2[cfname]
1187 1187 newfparent = fparent1
1188 1188
1189 1189 # find source in nearest ancestor if we've lost track
1190 1190 if not crev:
1191 1191 self.ui.debug(" %s: searching for copy revision for %s\n" %
1192 1192 (fname, cfname))
1193 1193 for ancestor in self[None].ancestors():
1194 1194 if cfname in ancestor:
1195 1195 crev = ancestor[cfname].filenode()
1196 1196 break
1197 1197
1198 1198 if crev:
1199 1199 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1200 1200 meta["copy"] = cfname
1201 1201 meta["copyrev"] = hex(crev)
1202 1202 fparent1, fparent2 = nullid, newfparent
1203 1203 else:
1204 1204 self.ui.warn(_("warning: can't find ancestor for '%s' "
1205 1205 "copied from '%s'!\n") % (fname, cfname))
1206 1206
1207 1207 elif fparent1 == nullid:
1208 1208 fparent1, fparent2 = fparent2, nullid
1209 1209 elif fparent2 != nullid:
1210 1210 # is one parent an ancestor of the other?
1211 1211 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1212 1212 if fparent1 in fparentancestors:
1213 1213 fparent1, fparent2 = fparent2, nullid
1214 1214 elif fparent2 in fparentancestors:
1215 1215 fparent2 = nullid
1216 1216
1217 1217 # is the file changed?
1218 1218 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1219 1219 changelist.append(fname)
1220 1220 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1221 1221 # are just the flags changed during merge?
1222 1222 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1223 1223 changelist.append(fname)
1224 1224
1225 1225 return fparent1
1226 1226
1227 1227 @unfilteredmethod
1228 1228 def commit(self, text="", user=None, date=None, match=None, force=False,
1229 1229 editor=False, extra={}):
1230 1230 """Add a new revision to current repository.
1231 1231
1232 1232 Revision information is gathered from the working directory,
1233 1233 match can be used to filter the committed files. If editor is
1234 1234 supplied, it is called to get a commit message.
1235 1235 """
1236 1236
1237 1237 def fail(f, msg):
1238 1238 raise util.Abort('%s: %s' % (f, msg))
1239 1239
1240 1240 if not match:
1241 1241 match = matchmod.always(self.root, '')
1242 1242
1243 1243 if not force:
1244 1244 vdirs = []
1245 1245 match.explicitdir = vdirs.append
1246 1246 match.bad = fail
1247 1247
1248 1248 wlock = self.wlock()
1249 1249 try:
1250 1250 wctx = self[None]
1251 1251 merge = len(wctx.parents()) > 1
1252 1252
1253 1253 if (not force and merge and match and
1254 1254 (match.files() or match.anypats())):
1255 1255 raise util.Abort(_('cannot partially commit a merge '
1256 1256 '(do not specify files or patterns)'))
1257 1257
1258 1258 status = self.status(match=match, clean=force)
1259 1259 if force:
1260 1260 status.modified.extend(status.clean) # mq may commit clean files
1261 1261
1262 1262 # check subrepos
1263 1263 subs = []
1264 1264 commitsubs = set()
1265 1265 newstate = wctx.substate.copy()
1266 1266 # only manage subrepos and .hgsubstate if .hgsub is present
1267 1267 if '.hgsub' in wctx:
1268 1268 # we'll decide whether to track this ourselves, thanks
1269 1269 for c in status.modified, status.added, status.removed:
1270 1270 if '.hgsubstate' in c:
1271 1271 c.remove('.hgsubstate')
1272 1272
1273 1273 # compare current state to last committed state
1274 1274 # build new substate based on last committed state
1275 1275 oldstate = wctx.p1().substate
1276 1276 for s in sorted(newstate.keys()):
1277 1277 if not match(s):
1278 1278 # ignore working copy, use old state if present
1279 1279 if s in oldstate:
1280 1280 newstate[s] = oldstate[s]
1281 1281 continue
1282 1282 if not force:
1283 1283 raise util.Abort(
1284 1284 _("commit with new subrepo %s excluded") % s)
1285 1285 if wctx.sub(s).dirty(True):
1286 1286 if not self.ui.configbool('ui', 'commitsubrepos'):
1287 1287 raise util.Abort(
1288 1288 _("uncommitted changes in subrepo %s") % s,
1289 1289 hint=_("use --subrepos for recursive commit"))
1290 1290 subs.append(s)
1291 1291 commitsubs.add(s)
1292 1292 else:
1293 1293 bs = wctx.sub(s).basestate()
1294 1294 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1295 1295 if oldstate.get(s, (None, None, None))[1] != bs:
1296 1296 subs.append(s)
1297 1297
1298 1298 # check for removed subrepos
1299 1299 for p in wctx.parents():
1300 1300 r = [s for s in p.substate if s not in newstate]
1301 1301 subs += [s for s in r if match(s)]
1302 1302 if subs:
1303 1303 if (not match('.hgsub') and
1304 1304 '.hgsub' in (wctx.modified() + wctx.added())):
1305 1305 raise util.Abort(
1306 1306 _("can't commit subrepos without .hgsub"))
1307 1307 status.modified.insert(0, '.hgsubstate')
1308 1308
1309 1309 elif '.hgsub' in status.removed:
1310 1310 # clean up .hgsubstate when .hgsub is removed
1311 1311 if ('.hgsubstate' in wctx and
1312 1312 '.hgsubstate' not in (status.modified + status.added +
1313 1313 status.removed)):
1314 1314 status.removed.insert(0, '.hgsubstate')
1315 1315
1316 1316 # make sure all explicit patterns are matched
1317 1317 if not force and match.files():
1318 1318 matched = set(status.modified + status.added + status.removed)
1319 1319
1320 1320 for f in match.files():
1321 1321 f = self.dirstate.normalize(f)
1322 1322 if f == '.' or f in matched or f in wctx.substate:
1323 1323 continue
1324 1324 if f in status.deleted:
1325 1325 fail(f, _('file not found!'))
1326 1326 if f in vdirs: # visited directory
1327 1327 d = f + '/'
1328 1328 for mf in matched:
1329 1329 if mf.startswith(d):
1330 1330 break
1331 1331 else:
1332 1332 fail(f, _("no match under directory!"))
1333 1333 elif f not in self.dirstate:
1334 1334 fail(f, _("file not tracked!"))
1335 1335
1336 1336 cctx = context.workingctx(self, text, user, date, extra, status)
1337 1337
1338 1338 if (not force and not extra.get("close") and not merge
1339 1339 and not cctx.files()
1340 1340 and wctx.branch() == wctx.p1().branch()):
1341 1341 return None
1342 1342
1343 1343 if merge and cctx.deleted():
1344 1344 raise util.Abort(_("cannot commit merge with missing files"))
1345 1345
1346 1346 ms = mergemod.mergestate(self)
1347 1347 for f in status.modified:
1348 1348 if f in ms and ms[f] == 'u':
1349 1349 raise util.Abort(_("unresolved merge conflicts "
1350 1350 "(see hg help resolve)"))
1351 1351
1352 1352 if editor:
1353 1353 cctx._text = editor(self, cctx, subs)
1354 1354 edited = (text != cctx._text)
1355 1355
1356 1356 # Save commit message in case this transaction gets rolled back
1357 1357 # (e.g. by a pretxncommit hook). Leave the content alone on
1358 1358 # the assumption that the user will use the same editor again.
1359 1359 msgfn = self.savecommitmessage(cctx._text)
1360 1360
1361 1361 # commit subs and write new state
1362 1362 if subs:
1363 1363 for s in sorted(commitsubs):
1364 1364 sub = wctx.sub(s)
1365 1365 self.ui.status(_('committing subrepository %s\n') %
1366 1366 subrepo.subrelpath(sub))
1367 1367 sr = sub.commit(cctx._text, user, date)
1368 1368 newstate[s] = (newstate[s][0], sr)
1369 1369 subrepo.writestate(self, newstate)
1370 1370
1371 1371 p1, p2 = self.dirstate.parents()
1372 1372 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1373 1373 try:
1374 1374 self.hook("precommit", throw=True, parent1=hookp1,
1375 1375 parent2=hookp2)
1376 1376 ret = self.commitctx(cctx, True)
1377 1377 except: # re-raises
1378 1378 if edited:
1379 1379 self.ui.write(
1380 1380 _('note: commit message saved in %s\n') % msgfn)
1381 1381 raise
1382 1382
1383 1383 # update bookmarks, dirstate and mergestate
1384 1384 bookmarks.update(self, [p1, p2], ret)
1385 1385 cctx.markcommitted(ret)
1386 1386 ms.reset()
1387 1387 finally:
1388 1388 wlock.release()
1389 1389
1390 1390 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1391 1391 # hack for command that use a temporary commit (eg: histedit)
1392 1392 # temporary commit got stripped before hook release
1393 1393 if node in self:
1394 1394 self.hook("commit", node=node, parent1=parent1,
1395 1395 parent2=parent2)
1396 1396 self._afterlock(commithook)
1397 1397 return ret
1398 1398
1399 1399 @unfilteredmethod
1400 1400 def commitctx(self, ctx, error=False):
1401 1401 """Add a new revision to current repository.
1402 1402 Revision information is passed via the context argument.
1403 1403 """
1404 1404
1405 1405 tr = None
1406 1406 p1, p2 = ctx.p1(), ctx.p2()
1407 1407 user = ctx.user()
1408 1408
1409 1409 lock = self.lock()
1410 1410 try:
1411 1411 tr = self.transaction("commit")
1412 1412 trp = weakref.proxy(tr)
1413 1413
1414 1414 if ctx.files():
1415 1415 m1 = p1.manifest()
1416 1416 m2 = p2.manifest()
1417 1417 m = m1.copy()
1418 1418
1419 1419 # check in files
1420 1420 added = []
1421 1421 changed = []
1422 1422 removed = list(ctx.removed())
1423 1423 linkrev = len(self)
1424 1424 for f in sorted(ctx.modified() + ctx.added()):
1425 1425 self.ui.note(f + "\n")
1426 1426 try:
1427 1427 fctx = ctx[f]
1428 1428 if fctx is None:
1429 1429 removed.append(f)
1430 1430 else:
1431 1431 added.append(f)
1432 1432 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1433 1433 trp, changed)
1434 1434 m.setflag(f, fctx.flags())
1435 1435 except OSError, inst:
1436 1436 self.ui.warn(_("trouble committing %s!\n") % f)
1437 1437 raise
1438 1438 except IOError, inst:
1439 1439 errcode = getattr(inst, 'errno', errno.ENOENT)
1440 1440 if error or errcode and errcode != errno.ENOENT:
1441 1441 self.ui.warn(_("trouble committing %s!\n") % f)
1442 1442 raise
1443 1443
1444 1444 # update manifest
1445 1445 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1446 1446 drop = [f for f in removed if f in m]
1447 1447 for f in drop:
1448 1448 del m[f]
1449 1449 mn = self.manifest.add(m, trp, linkrev,
1450 1450 p1.manifestnode(), p2.manifestnode(),
1451 1451 added, drop)
1452 1452 files = changed + removed
1453 1453 else:
1454 1454 mn = p1.manifestnode()
1455 1455 files = []
1456 1456
1457 1457 # update changelog
1458 1458 self.changelog.delayupdate(tr)
1459 1459 n = self.changelog.add(mn, files, ctx.description(),
1460 1460 trp, p1.node(), p2.node(),
1461 1461 user, ctx.date(), ctx.extra().copy())
1462 1462 p = lambda: tr.writepending() and self.root or ""
1463 1463 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1464 1464 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1465 1465 parent2=xp2, pending=p)
1466 1466 # set the new commit is proper phase
1467 1467 targetphase = subrepo.newcommitphase(self.ui, ctx)
1468 1468 if targetphase:
1469 1469 # retract boundary do not alter parent changeset.
1470 1470 # if a parent have higher the resulting phase will
1471 1471 # be compliant anyway
1472 1472 #
1473 1473 # if minimal phase was 0 we don't need to retract anything
1474 1474 phases.retractboundary(self, tr, targetphase, [n])
1475 1475 tr.close()
1476 1476 branchmap.updatecache(self.filtered('served'))
1477 1477 return n
1478 1478 finally:
1479 1479 if tr:
1480 1480 tr.release()
1481 1481 lock.release()
1482 1482
1483 1483 @unfilteredmethod
1484 1484 def destroying(self):
1485 1485 '''Inform the repository that nodes are about to be destroyed.
1486 1486 Intended for use by strip and rollback, so there's a common
1487 1487 place for anything that has to be done before destroying history.
1488 1488
1489 1489 This is mostly useful for saving state that is in memory and waiting
1490 1490 to be flushed when the current lock is released. Because a call to
1491 1491 destroyed is imminent, the repo will be invalidated causing those
1492 1492 changes to stay in memory (waiting for the next unlock), or vanish
1493 1493 completely.
1494 1494 '''
1495 1495 # When using the same lock to commit and strip, the phasecache is left
1496 1496 # dirty after committing. Then when we strip, the repo is invalidated,
1497 1497 # causing those changes to disappear.
1498 1498 if '_phasecache' in vars(self):
1499 1499 self._phasecache.write()
1500 1500
1501 1501 @unfilteredmethod
1502 1502 def destroyed(self):
1503 1503 '''Inform the repository that nodes have been destroyed.
1504 1504 Intended for use by strip and rollback, so there's a common
1505 1505 place for anything that has to be done after destroying history.
1506 1506 '''
1507 1507 # When one tries to:
1508 1508 # 1) destroy nodes thus calling this method (e.g. strip)
1509 1509 # 2) use phasecache somewhere (e.g. commit)
1510 1510 #
1511 1511 # then 2) will fail because the phasecache contains nodes that were
1512 1512 # removed. We can either remove phasecache from the filecache,
1513 1513 # causing it to reload next time it is accessed, or simply filter
1514 1514 # the removed nodes now and write the updated cache.
1515 1515 self._phasecache.filterunknown(self)
1516 1516 self._phasecache.write()
1517 1517
1518 1518 # update the 'served' branch cache to help read only server process
1519 1519 # Thanks to branchcache collaboration this is done from the nearest
1520 1520 # filtered subset and it is expected to be fast.
1521 1521 branchmap.updatecache(self.filtered('served'))
1522 1522
1523 1523 # Ensure the persistent tag cache is updated. Doing it now
1524 1524 # means that the tag cache only has to worry about destroyed
1525 1525 # heads immediately after a strip/rollback. That in turn
1526 1526 # guarantees that "cachetip == currenttip" (comparing both rev
1527 1527 # and node) always means no nodes have been added or destroyed.
1528 1528
1529 1529 # XXX this is suboptimal when qrefresh'ing: we strip the current
1530 1530 # head, refresh the tag cache, then immediately add a new head.
1531 1531 # But I think doing it this way is necessary for the "instant
1532 1532 # tag cache retrieval" case to work.
1533 1533 self.invalidate()
1534 1534
1535 1535 def walk(self, match, node=None):
1536 1536 '''
1537 1537 walk recursively through the directory tree or a given
1538 1538 changeset, finding all files matched by the match
1539 1539 function
1540 1540 '''
1541 1541 return self[node].walk(match)
1542 1542
1543 1543 def status(self, node1='.', node2=None, match=None,
1544 1544 ignored=False, clean=False, unknown=False,
1545 1545 listsubrepos=False):
1546 1546 '''a convenience method that calls node1.status(node2)'''
1547 1547 return self[node1].status(node2, match, ignored, clean, unknown,
1548 1548 listsubrepos)
1549 1549
1550 1550 def heads(self, start=None):
1551 1551 heads = self.changelog.heads(start)
1552 1552 # sort the output in rev descending order
1553 1553 return sorted(heads, key=self.changelog.rev, reverse=True)
1554 1554
1555 1555 def branchheads(self, branch=None, start=None, closed=False):
1556 1556 '''return a (possibly filtered) list of heads for the given branch
1557 1557
1558 1558 Heads are returned in topological order, from newest to oldest.
1559 1559 If branch is None, use the dirstate branch.
1560 1560 If start is not None, return only heads reachable from start.
1561 1561 If closed is True, return heads that are marked as closed as well.
1562 1562 '''
1563 1563 if branch is None:
1564 1564 branch = self[None].branch()
1565 1565 branches = self.branchmap()
1566 1566 if branch not in branches:
1567 1567 return []
1568 1568 # the cache returns heads ordered lowest to highest
1569 1569 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1570 1570 if start is not None:
1571 1571 # filter out the heads that cannot be reached from startrev
1572 1572 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1573 1573 bheads = [h for h in bheads if h in fbheads]
1574 1574 return bheads
1575 1575
1576 1576 def branches(self, nodes):
1577 1577 if not nodes:
1578 1578 nodes = [self.changelog.tip()]
1579 1579 b = []
1580 1580 for n in nodes:
1581 1581 t = n
1582 1582 while True:
1583 1583 p = self.changelog.parents(n)
1584 1584 if p[1] != nullid or p[0] == nullid:
1585 1585 b.append((t, n, p[0], p[1]))
1586 1586 break
1587 1587 n = p[0]
1588 1588 return b
1589 1589
1590 1590 def between(self, pairs):
1591 1591 r = []
1592 1592
1593 1593 for top, bottom in pairs:
1594 1594 n, l, i = top, [], 0
1595 1595 f = 1
1596 1596
1597 1597 while n != bottom and n != nullid:
1598 1598 p = self.changelog.parents(n)[0]
1599 1599 if i == f:
1600 1600 l.append(n)
1601 1601 f = f * 2
1602 1602 n = p
1603 1603 i += 1
1604 1604
1605 1605 r.append(l)
1606 1606
1607 1607 return r
1608 1608
1609 1609 def checkpush(self, pushop):
1610 1610 """Extensions can override this function if additional checks have
1611 1611 to be performed before pushing, or call it if they override push
1612 1612 command.
1613 1613 """
1614 1614 pass
1615 1615
1616 1616 @unfilteredpropertycache
1617 1617 def prepushoutgoinghooks(self):
1618 1618 """Return util.hooks consists of "(repo, remote, outgoing)"
1619 1619 functions, which are called before pushing changesets.
1620 1620 """
1621 1621 return util.hooks()
1622 1622
1623 1623 def stream_in(self, remote, requirements):
1624 1624 lock = self.lock()
1625 1625 try:
1626 1626 # Save remote branchmap. We will use it later
1627 1627 # to speed up branchcache creation
1628 1628 rbranchmap = None
1629 1629 if remote.capable("branchmap"):
1630 1630 rbranchmap = remote.branchmap()
1631 1631
1632 1632 fp = remote.stream_out()
1633 1633 l = fp.readline()
1634 1634 try:
1635 1635 resp = int(l)
1636 1636 except ValueError:
1637 1637 raise error.ResponseError(
1638 1638 _('unexpected response from remote server:'), l)
1639 1639 if resp == 1:
1640 1640 raise util.Abort(_('operation forbidden by server'))
1641 1641 elif resp == 2:
1642 1642 raise util.Abort(_('locking the remote repository failed'))
1643 1643 elif resp != 0:
1644 1644 raise util.Abort(_('the server sent an unknown error code'))
1645 1645 self.ui.status(_('streaming all changes\n'))
1646 1646 l = fp.readline()
1647 1647 try:
1648 1648 total_files, total_bytes = map(int, l.split(' ', 1))
1649 1649 except (ValueError, TypeError):
1650 1650 raise error.ResponseError(
1651 1651 _('unexpected response from remote server:'), l)
1652 1652 self.ui.status(_('%d files to transfer, %s of data\n') %
1653 1653 (total_files, util.bytecount(total_bytes)))
1654 1654 handled_bytes = 0
1655 1655 self.ui.progress(_('clone'), 0, total=total_bytes)
1656 1656 start = time.time()
1657 1657
1658 1658 tr = self.transaction(_('clone'))
1659 1659 try:
1660 1660 for i in xrange(total_files):
1661 1661 # XXX doesn't support '\n' or '\r' in filenames
1662 1662 l = fp.readline()
1663 1663 try:
1664 1664 name, size = l.split('\0', 1)
1665 1665 size = int(size)
1666 1666 except (ValueError, TypeError):
1667 1667 raise error.ResponseError(
1668 1668 _('unexpected response from remote server:'), l)
1669 1669 if self.ui.debugflag:
1670 1670 self.ui.debug('adding %s (%s)\n' %
1671 1671 (name, util.bytecount(size)))
1672 1672 # for backwards compat, name was partially encoded
1673 1673 ofp = self.sopener(store.decodedir(name), 'w')
1674 1674 for chunk in util.filechunkiter(fp, limit=size):
1675 1675 handled_bytes += len(chunk)
1676 1676 self.ui.progress(_('clone'), handled_bytes,
1677 1677 total=total_bytes)
1678 1678 ofp.write(chunk)
1679 1679 ofp.close()
1680 1680 tr.close()
1681 1681 finally:
1682 1682 tr.release()
1683 1683
1684 1684 # Writing straight to files circumvented the inmemory caches
1685 1685 self.invalidate()
1686 1686
1687 1687 elapsed = time.time() - start
1688 1688 if elapsed <= 0:
1689 1689 elapsed = 0.001
1690 1690 self.ui.progress(_('clone'), None)
1691 1691 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1692 1692 (util.bytecount(total_bytes), elapsed,
1693 1693 util.bytecount(total_bytes / elapsed)))
1694 1694
1695 1695 # new requirements = old non-format requirements +
1696 1696 # new format-related
1697 1697 # requirements from the streamed-in repository
1698 1698 requirements.update(set(self.requirements) - self.supportedformats)
1699 1699 self._applyrequirements(requirements)
1700 1700 self._writerequirements()
1701 1701
1702 1702 if rbranchmap:
1703 1703 rbheads = []
1704 1704 closed = []
1705 1705 for bheads in rbranchmap.itervalues():
1706 1706 rbheads.extend(bheads)
1707 1707 for h in bheads:
1708 1708 r = self.changelog.rev(h)
1709 1709 b, c = self.changelog.branchinfo(r)
1710 1710 if c:
1711 1711 closed.append(h)
1712 1712
1713 1713 if rbheads:
1714 1714 rtiprev = max((int(self.changelog.rev(node))
1715 1715 for node in rbheads))
1716 1716 cache = branchmap.branchcache(rbranchmap,
1717 1717 self[rtiprev].node(),
1718 1718 rtiprev,
1719 1719 closednodes=closed)
1720 1720 # Try to stick it as low as possible
1721 1721 # filter above served are unlikely to be fetch from a clone
1722 1722 for candidate in ('base', 'immutable', 'served'):
1723 1723 rview = self.filtered(candidate)
1724 1724 if cache.validfor(rview):
1725 1725 self._branchcaches[candidate] = cache
1726 1726 cache.write(rview)
1727 1727 break
1728 1728 self.invalidate()
1729 1729 return len(self.heads()) + 1
1730 1730 finally:
1731 1731 lock.release()
1732 1732
1733 1733 def clone(self, remote, heads=[], stream=None):
1734 1734 '''clone remote repository.
1735 1735
1736 1736 keyword arguments:
1737 1737 heads: list of revs to clone (forces use of pull)
1738 1738 stream: use streaming clone if possible'''
1739 1739
1740 1740 # now, all clients that can request uncompressed clones can
1741 1741 # read repo formats supported by all servers that can serve
1742 1742 # them.
1743 1743
1744 1744 # if revlog format changes, client will have to check version
1745 1745 # and format flags on "stream" capability, and use
1746 1746 # uncompressed only if compatible.
1747 1747
1748 1748 if stream is None:
1749 1749 # if the server explicitly prefers to stream (for fast LANs)
1750 1750 stream = remote.capable('stream-preferred')
1751 1751
1752 1752 if stream and not heads:
1753 1753 # 'stream' means remote revlog format is revlogv1 only
1754 1754 if remote.capable('stream'):
1755 1755 self.stream_in(remote, set(('revlogv1',)))
1756 1756 else:
1757 1757 # otherwise, 'streamreqs' contains the remote revlog format
1758 1758 streamreqs = remote.capable('streamreqs')
1759 1759 if streamreqs:
1760 1760 streamreqs = set(streamreqs.split(','))
1761 1761 # if we support it, stream in and adjust our requirements
1762 1762 if not streamreqs - self.supportedformats:
1763 1763 self.stream_in(remote, streamreqs)
1764 1764
1765 1765 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1766 1766 try:
1767 1767 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1768 1768 ret = exchange.pull(self, remote, heads).cgresult
1769 1769 finally:
1770 1770 self.ui.restoreconfig(quiet)
1771 1771 return ret
1772 1772
1773 1773 def pushkey(self, namespace, key, old, new):
1774 1774 try:
1775 1775 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1776 1776 old=old, new=new)
1777 1777 except error.HookAbort, exc:
1778 1778 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
1779 1779 if exc.hint:
1780 1780 self.ui.write_err(_("(%s)\n") % exc.hint)
1781 1781 return False
1782 1782 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1783 1783 ret = pushkey.push(self, namespace, key, old, new)
1784 1784 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1785 1785 ret=ret)
1786 1786 return ret
1787 1787
1788 1788 def listkeys(self, namespace):
1789 1789 self.hook('prelistkeys', throw=True, namespace=namespace)
1790 1790 self.ui.debug('listing keys for "%s"\n' % namespace)
1791 1791 values = pushkey.list(self, namespace)
1792 1792 self.hook('listkeys', namespace=namespace, values=values)
1793 1793 return values
1794 1794
1795 1795 def debugwireargs(self, one, two, three=None, four=None, five=None):
1796 1796 '''used to test argument passing over the wire'''
1797 1797 return "%s %s %s %s %s" % (one, two, three, four, five)
1798 1798
1799 1799 def savecommitmessage(self, text):
1800 1800 fp = self.opener('last-message.txt', 'wb')
1801 1801 try:
1802 1802 fp.write(text)
1803 1803 finally:
1804 1804 fp.close()
1805 1805 return self.pathto(fp.name[len(self.root) + 1:])
1806 1806
1807 1807 # used to avoid circular references so destructors work
1808 1808 def aftertrans(files):
1809 1809 renamefiles = [tuple(t) for t in files]
1810 1810 def a():
1811 1811 for vfs, src, dest in renamefiles:
1812 1812 try:
1813 1813 vfs.rename(src, dest)
1814 1814 except OSError: # journal file does not yet exist
1815 1815 pass
1816 1816 return a
1817 1817
1818 1818 def undoname(fn):
1819 1819 base, name = os.path.split(fn)
1820 1820 assert name.startswith('journal')
1821 1821 return os.path.join(base, name.replace('journal', 'undo', 1))
1822 1822
1823 1823 def instance(ui, path, create):
1824 1824 return localrepository(ui, util.urllocalpath(path), create)
1825 1825
1826 1826 def islocal(path):
1827 1827 return True
@@ -1,80 +1,74 b''
1 1 from i18n import _
2 2 from mercurial import util
3 import weakref
4 3
5 4 def tolist(val):
6 5 """
7 6 a convenience method to return an empty list instead of None
8 7 """
9 8 if val is None:
10 9 return []
11 10 else:
12 11 return [val]
13 12
14 13 class namespaces(object):
15 14 """
16 15 provides an interface to register a generic many-to-many mapping between
17 16 some (namespaced) names and nodes. The goal here is to control the
18 17 pollution of jamming things into tags or bookmarks (in extension-land) and
19 18 to simplify internal bits of mercurial: log output, tab completion, etc.
20 19
21 20 More precisely, we define a list of names (the namespace) and a mapping of
22 21 names to nodes. This name mapping returns a list of nodes.
23 22
24 23 Furthermore, each name mapping will be passed a name to lookup which might
25 24 not be in its domain. In this case, each method should return an empty list
26 25 and not raise an error.
27 26
28 27 We'll have a dictionary '_names' where each key is a namespace and
29 28 its value is a dictionary of functions:
30 29 'namemap': function that takes a name and returns a list of nodes
31 30 """
32 31
33 32 _names_version = 0
34 33
35 def __init__(self, repo):
34 def __init__(self):
36 35 self._names = util.sortdict()
37 self._repo = weakref.ref(repo)
38 36
39 37 # we need current mercurial named objects (bookmarks, tags, and
40 38 # branches) to be initialized somewhere, so that place is here
41 39 self.addnamespace("bookmarks",
42 40 lambda repo, name: tolist(repo._bookmarks.get(name)))
43 41
44 @property
45 def repo(self):
46 return self._repo()
47
48 42 def addnamespace(self, namespace, namemap, order=None):
49 43 """
50 44 register a namespace
51 45
52 46 namespace: the name to be registered (in plural form)
53 47 namemap: function that inputs a node, output name(s)
54 48 order: optional argument to specify the order of namespaces
55 49 (e.g. 'branches' should be listed before 'bookmarks')
56 50 """
57 51 val = {'namemap': namemap}
58 52 if order is not None:
59 53 self._names.insert(order, namespace, val)
60 54 else:
61 55 self._names[namespace] = val
62 56
63 def singlenode(self, name):
57 def singlenode(self, repo, name):
64 58 """
65 59 Return the 'best' node for the given name. Best means the first node
66 60 in the first nonempty list returned by a name-to-nodes mapping function
67 61 in the defined precedence order.
68 62
69 63 Raises a KeyError if there is no such node.
70 64 """
71 65 for ns, v in self._names.iteritems():
72 n = v['namemap'](self.repo, name)
66 n = v['namemap'](repo, name)
73 67 if n:
74 68 # return max revision number
75 69 if len(n) > 1:
76 cl = self.repo.changelog
70 cl = repo.changelog
77 71 maxrev = max(cl.rev(node) for node in n)
78 72 return cl.node(maxrev)
79 73 return n[0]
80 74 raise KeyError(_('no such name: %s') % name)
@@ -1,166 +1,166 b''
1 1 # statichttprepo.py - simple http repository class for mercurial
2 2 #
3 3 # This provides read-only repo access to repositories exported via static http
4 4 #
5 5 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
6 6 #
7 7 # This software may be used and distributed according to the terms of the
8 8 # GNU General Public License version 2 or any later version.
9 9
10 10 from i18n import _
11 11 import changelog, byterange, url, error, namespaces
12 12 import localrepo, manifest, util, scmutil, store
13 13 import urllib, urllib2, errno, os
14 14
15 15 class httprangereader(object):
16 16 def __init__(self, url, opener):
17 17 # we assume opener has HTTPRangeHandler
18 18 self.url = url
19 19 self.pos = 0
20 20 self.opener = opener
21 21 self.name = url
22 22 def seek(self, pos):
23 23 self.pos = pos
24 24 def read(self, bytes=None):
25 25 req = urllib2.Request(self.url)
26 26 end = ''
27 27 if bytes:
28 28 end = self.pos + bytes - 1
29 29 if self.pos or end:
30 30 req.add_header('Range', 'bytes=%d-%s' % (self.pos, end))
31 31
32 32 try:
33 33 f = self.opener.open(req)
34 34 data = f.read()
35 35 # Python 2.6+ defines a getcode() function, and 2.4 and
36 36 # 2.5 appear to always have an undocumented code attribute
37 37 # set. If we can't read either of those, fall back to 206
38 38 # and hope for the best.
39 39 code = getattr(f, 'getcode', lambda : getattr(f, 'code', 206))()
40 40 except urllib2.HTTPError, inst:
41 41 num = inst.code == 404 and errno.ENOENT or None
42 42 raise IOError(num, inst)
43 43 except urllib2.URLError, inst:
44 44 raise IOError(None, inst.reason[1])
45 45
46 46 if code == 200:
47 47 # HTTPRangeHandler does nothing if remote does not support
48 48 # Range headers and returns the full entity. Let's slice it.
49 49 if bytes:
50 50 data = data[self.pos:self.pos + bytes]
51 51 else:
52 52 data = data[self.pos:]
53 53 elif bytes:
54 54 data = data[:bytes]
55 55 self.pos += len(data)
56 56 return data
57 57 def readlines(self):
58 58 return self.read().splitlines(True)
59 59 def __iter__(self):
60 60 return iter(self.readlines())
61 61 def close(self):
62 62 pass
63 63
64 64 def build_opener(ui, authinfo):
65 65 # urllib cannot handle URLs with embedded user or passwd
66 66 urlopener = url.opener(ui, authinfo)
67 67 urlopener.add_handler(byterange.HTTPRangeHandler())
68 68
69 69 class statichttpvfs(scmutil.abstractvfs):
70 70 def __init__(self, base):
71 71 self.base = base
72 72
73 73 def __call__(self, path, mode='r', *args, **kw):
74 74 if mode not in ('r', 'rb'):
75 75 raise IOError('Permission denied')
76 76 f = "/".join((self.base, urllib.quote(path)))
77 77 return httprangereader(f, urlopener)
78 78
79 79 def join(self, path):
80 80 if path:
81 81 return os.path.join(self.base, path)
82 82 else:
83 83 return self.base
84 84
85 85 return statichttpvfs
86 86
87 87 class statichttppeer(localrepo.localpeer):
88 88 def local(self):
89 89 return None
90 90 def canpush(self):
91 91 return False
92 92
93 93 class statichttprepository(localrepo.localrepository):
94 94 supported = localrepo.localrepository._basesupported
95 95
96 96 def __init__(self, ui, path):
97 97 self._url = path
98 98 self.ui = ui
99 99
100 100 self.root = path
101 101 u = util.url(path.rstrip('/') + "/.hg")
102 102 self.path, authinfo = u.authinfo()
103 103
104 104 opener = build_opener(ui, authinfo)
105 105 self.opener = opener(self.path)
106 106 self.vfs = self.opener
107 107 self._phasedefaults = []
108 108
109 self.names = namespaces.namespaces(self)
109 self.names = namespaces.namespaces()
110 110
111 111 try:
112 112 requirements = scmutil.readrequires(self.opener, self.supported)
113 113 except IOError, inst:
114 114 if inst.errno != errno.ENOENT:
115 115 raise
116 116 requirements = set()
117 117
118 118 # check if it is a non-empty old-style repository
119 119 try:
120 120 fp = self.opener("00changelog.i")
121 121 fp.read(1)
122 122 fp.close()
123 123 except IOError, inst:
124 124 if inst.errno != errno.ENOENT:
125 125 raise
126 126 # we do not care about empty old-style repositories here
127 127 msg = _("'%s' does not appear to be an hg repository") % path
128 128 raise error.RepoError(msg)
129 129
130 130 # setup store
131 131 self.store = store.store(requirements, self.path, opener)
132 132 self.spath = self.store.path
133 133 self.sopener = self.store.opener
134 134 self.svfs = self.sopener
135 135 self.sjoin = self.store.join
136 136 self._filecache = {}
137 137 self.requirements = requirements
138 138
139 139 self.manifest = manifest.manifest(self.sopener)
140 140 self.changelog = changelog.changelog(self.sopener)
141 141 self._tags = None
142 142 self.nodetagscache = None
143 143 self._branchcaches = {}
144 144 self.encodepats = None
145 145 self.decodepats = None
146 146
147 147 def _restrictcapabilities(self, caps):
148 148 caps = super(statichttprepository, self)._restrictcapabilities(caps)
149 149 return caps.difference(["pushkey"])
150 150
151 151 def url(self):
152 152 return self._url
153 153
154 154 def local(self):
155 155 return False
156 156
157 157 def peer(self):
158 158 return statichttppeer(self)
159 159
160 160 def lock(self, wait=True):
161 161 raise util.Abort(_('cannot lock static-http repository'))
162 162
163 163 def instance(ui, path, create):
164 164 if create:
165 165 raise util.Abort(_('cannot create new static-http repository'))
166 166 return statichttprepository(ui, path[7:])
General Comments 0
You need to be logged in to leave comments. Login now