##// END OF EJS Templates
localrepo: use vfs.reljoin rather than os.path.join in the localrepository class...
Angel Ezquerra -
r23714:e3a0e7e2 default
parent child Browse files
Show More
@@ -1,1840 +1,1840 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 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 if isinstance(changeid, slice):
458 458 return [context.changectx(self, i)
459 459 for i in xrange(*changeid.indices(len(self)))
460 460 if i not in self.changelog.filteredrevs]
461 461 return context.changectx(self, changeid)
462 462
463 463 def __contains__(self, changeid):
464 464 try:
465 465 return bool(self.lookup(changeid))
466 466 except error.RepoLookupError:
467 467 return False
468 468
469 469 def __nonzero__(self):
470 470 return True
471 471
472 472 def __len__(self):
473 473 return len(self.changelog)
474 474
475 475 def __iter__(self):
476 476 return iter(self.changelog)
477 477
478 478 def revs(self, expr, *args):
479 479 '''Return a list of revisions matching the given revset'''
480 480 expr = revset.formatspec(expr, *args)
481 481 m = revset.match(None, expr)
482 482 return m(self, revset.spanset(self))
483 483
484 484 def set(self, expr, *args):
485 485 '''
486 486 Yield a context for each matching revision, after doing arg
487 487 replacement via revset.formatspec
488 488 '''
489 489 for r in self.revs(expr, *args):
490 490 yield self[r]
491 491
492 492 def url(self):
493 493 return 'file:' + self.root
494 494
495 495 def hook(self, name, throw=False, **args):
496 496 """Call a hook, passing this repo instance.
497 497
498 498 This a convenience method to aid invoking hooks. Extensions likely
499 499 won't call this unless they have registered a custom hook or are
500 500 replacing code that is expected to call a hook.
501 501 """
502 502 return hook.hook(self.ui, self, name, throw, **args)
503 503
504 504 @unfilteredmethod
505 505 def _tag(self, names, node, message, local, user, date, extra={},
506 506 editor=False):
507 507 if isinstance(names, str):
508 508 names = (names,)
509 509
510 510 branches = self.branchmap()
511 511 for name in names:
512 512 self.hook('pretag', throw=True, node=hex(node), tag=name,
513 513 local=local)
514 514 if name in branches:
515 515 self.ui.warn(_("warning: tag %s conflicts with existing"
516 516 " branch name\n") % name)
517 517
518 518 def writetags(fp, names, munge, prevtags):
519 519 fp.seek(0, 2)
520 520 if prevtags and prevtags[-1] != '\n':
521 521 fp.write('\n')
522 522 for name in names:
523 523 m = munge and munge(name) or name
524 524 if (self._tagscache.tagtypes and
525 525 name in self._tagscache.tagtypes):
526 526 old = self.tags().get(name, nullid)
527 527 fp.write('%s %s\n' % (hex(old), m))
528 528 fp.write('%s %s\n' % (hex(node), m))
529 529 fp.close()
530 530
531 531 prevtags = ''
532 532 if local:
533 533 try:
534 534 fp = self.opener('localtags', 'r+')
535 535 except IOError:
536 536 fp = self.opener('localtags', 'a')
537 537 else:
538 538 prevtags = fp.read()
539 539
540 540 # local tags are stored in the current charset
541 541 writetags(fp, names, None, prevtags)
542 542 for name in names:
543 543 self.hook('tag', node=hex(node), tag=name, local=local)
544 544 return
545 545
546 546 try:
547 547 fp = self.wfile('.hgtags', 'rb+')
548 548 except IOError, e:
549 549 if e.errno != errno.ENOENT:
550 550 raise
551 551 fp = self.wfile('.hgtags', 'ab')
552 552 else:
553 553 prevtags = fp.read()
554 554
555 555 # committed tags are stored in UTF-8
556 556 writetags(fp, names, encoding.fromlocal, prevtags)
557 557
558 558 fp.close()
559 559
560 560 self.invalidatecaches()
561 561
562 562 if '.hgtags' not in self.dirstate:
563 563 self[None].add(['.hgtags'])
564 564
565 565 m = matchmod.exact(self.root, '', ['.hgtags'])
566 566 tagnode = self.commit(message, user, date, extra=extra, match=m,
567 567 editor=editor)
568 568
569 569 for name in names:
570 570 self.hook('tag', node=hex(node), tag=name, local=local)
571 571
572 572 return tagnode
573 573
574 574 def tag(self, names, node, message, local, user, date, editor=False):
575 575 '''tag a revision with one or more symbolic names.
576 576
577 577 names is a list of strings or, when adding a single tag, names may be a
578 578 string.
579 579
580 580 if local is True, the tags are stored in a per-repository file.
581 581 otherwise, they are stored in the .hgtags file, and a new
582 582 changeset is committed with the change.
583 583
584 584 keyword arguments:
585 585
586 586 local: whether to store tags in non-version-controlled file
587 587 (default False)
588 588
589 589 message: commit message to use if committing
590 590
591 591 user: name of user to use if committing
592 592
593 593 date: date tuple to use if committing'''
594 594
595 595 if not local:
596 596 m = matchmod.exact(self.root, '', ['.hgtags'])
597 597 if util.any(self.status(match=m, unknown=True, ignored=True)):
598 598 raise util.Abort(_('working copy of .hgtags is changed'),
599 599 hint=_('please commit .hgtags manually'))
600 600
601 601 self.tags() # instantiate the cache
602 602 self._tag(names, node, message, local, user, date, editor=editor)
603 603
604 604 @filteredpropertycache
605 605 def _tagscache(self):
606 606 '''Returns a tagscache object that contains various tags related
607 607 caches.'''
608 608
609 609 # This simplifies its cache management by having one decorated
610 610 # function (this one) and the rest simply fetch things from it.
611 611 class tagscache(object):
612 612 def __init__(self):
613 613 # These two define the set of tags for this repository. tags
614 614 # maps tag name to node; tagtypes maps tag name to 'global' or
615 615 # 'local'. (Global tags are defined by .hgtags across all
616 616 # heads, and local tags are defined in .hg/localtags.)
617 617 # They constitute the in-memory cache of tags.
618 618 self.tags = self.tagtypes = None
619 619
620 620 self.nodetagscache = self.tagslist = None
621 621
622 622 cache = tagscache()
623 623 cache.tags, cache.tagtypes = self._findtags()
624 624
625 625 return cache
626 626
627 627 def tags(self):
628 628 '''return a mapping of tag to node'''
629 629 t = {}
630 630 if self.changelog.filteredrevs:
631 631 tags, tt = self._findtags()
632 632 else:
633 633 tags = self._tagscache.tags
634 634 for k, v in tags.iteritems():
635 635 try:
636 636 # ignore tags to unknown nodes
637 637 self.changelog.rev(v)
638 638 t[k] = v
639 639 except (error.LookupError, ValueError):
640 640 pass
641 641 return t
642 642
643 643 def _findtags(self):
644 644 '''Do the hard work of finding tags. Return a pair of dicts
645 645 (tags, tagtypes) where tags maps tag name to node, and tagtypes
646 646 maps tag name to a string like \'global\' or \'local\'.
647 647 Subclasses or extensions are free to add their own tags, but
648 648 should be aware that the returned dicts will be retained for the
649 649 duration of the localrepo object.'''
650 650
651 651 # XXX what tagtype should subclasses/extensions use? Currently
652 652 # mq and bookmarks add tags, but do not set the tagtype at all.
653 653 # Should each extension invent its own tag type? Should there
654 654 # be one tagtype for all such "virtual" tags? Or is the status
655 655 # quo fine?
656 656
657 657 alltags = {} # map tag name to (node, hist)
658 658 tagtypes = {}
659 659
660 660 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
661 661 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
662 662
663 663 # Build the return dicts. Have to re-encode tag names because
664 664 # the tags module always uses UTF-8 (in order not to lose info
665 665 # writing to the cache), but the rest of Mercurial wants them in
666 666 # local encoding.
667 667 tags = {}
668 668 for (name, (node, hist)) in alltags.iteritems():
669 669 if node != nullid:
670 670 tags[encoding.tolocal(name)] = node
671 671 tags['tip'] = self.changelog.tip()
672 672 tagtypes = dict([(encoding.tolocal(name), value)
673 673 for (name, value) in tagtypes.iteritems()])
674 674 return (tags, tagtypes)
675 675
676 676 def tagtype(self, tagname):
677 677 '''
678 678 return the type of the given tag. result can be:
679 679
680 680 'local' : a local tag
681 681 'global' : a global tag
682 682 None : tag does not exist
683 683 '''
684 684
685 685 return self._tagscache.tagtypes.get(tagname)
686 686
687 687 def tagslist(self):
688 688 '''return a list of tags ordered by revision'''
689 689 if not self._tagscache.tagslist:
690 690 l = []
691 691 for t, n in self.tags().iteritems():
692 692 l.append((self.changelog.rev(n), t, n))
693 693 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
694 694
695 695 return self._tagscache.tagslist
696 696
697 697 def nodetags(self, node):
698 698 '''return the tags associated with a node'''
699 699 if not self._tagscache.nodetagscache:
700 700 nodetagscache = {}
701 701 for t, n in self._tagscache.tags.iteritems():
702 702 nodetagscache.setdefault(n, []).append(t)
703 703 for tags in nodetagscache.itervalues():
704 704 tags.sort()
705 705 self._tagscache.nodetagscache = nodetagscache
706 706 return self._tagscache.nodetagscache.get(node, [])
707 707
708 708 def nodebookmarks(self, node):
709 709 marks = []
710 710 for bookmark, n in self._bookmarks.iteritems():
711 711 if n == node:
712 712 marks.append(bookmark)
713 713 return sorted(marks)
714 714
715 715 def branchmap(self):
716 716 '''returns a dictionary {branch: [branchheads]} with branchheads
717 717 ordered by increasing revision number'''
718 718 branchmap.updatecache(self)
719 719 return self._branchcaches[self.filtername]
720 720
721 721 def branchtip(self, branch):
722 722 '''return the tip node for a given branch'''
723 723 try:
724 724 return self.branchmap().branchtip(branch)
725 725 except KeyError:
726 726 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
727 727
728 728 def lookup(self, key):
729 729 return self[key].node()
730 730
731 731 def lookupbranch(self, key, remote=None):
732 732 repo = remote or self
733 733 if key in repo.branchmap():
734 734 return key
735 735
736 736 repo = (remote and remote.local()) and remote or self
737 737 return repo[key].branch()
738 738
739 739 def known(self, nodes):
740 740 nm = self.changelog.nodemap
741 741 pc = self._phasecache
742 742 result = []
743 743 for n in nodes:
744 744 r = nm.get(n)
745 745 resp = not (r is None or pc.phase(self, r) >= phases.secret)
746 746 result.append(resp)
747 747 return result
748 748
749 749 def local(self):
750 750 return self
751 751
752 752 def cancopy(self):
753 753 # so statichttprepo's override of local() works
754 754 if not self.local():
755 755 return False
756 756 if not self.ui.configbool('phases', 'publish', True):
757 757 return True
758 758 # if publishing we can't copy if there is filtered content
759 759 return not self.filtered('visible').changelog.filteredrevs
760 760
761 761 def shared(self):
762 762 '''the type of shared repository (None if not shared)'''
763 763 if self.sharedpath != self.path:
764 764 return 'store'
765 765 return None
766 766
767 767 def join(self, f, *insidef):
768 768 return self.vfs.join(os.path.join(f, *insidef))
769 769
770 770 def wjoin(self, f, *insidef):
771 return os.path.join(self.root, f, *insidef)
771 return self.vfs.reljoin(self.root, f, *insidef)
772 772
773 773 def file(self, f):
774 774 if f[0] == '/':
775 775 f = f[1:]
776 776 return filelog.filelog(self.sopener, f)
777 777
778 778 def changectx(self, changeid):
779 779 return self[changeid]
780 780
781 781 def parents(self, changeid=None):
782 782 '''get list of changectxs for parents of changeid'''
783 783 return self[changeid].parents()
784 784
785 785 def setparents(self, p1, p2=nullid):
786 786 self.dirstate.beginparentchange()
787 787 copies = self.dirstate.setparents(p1, p2)
788 788 pctx = self[p1]
789 789 if copies:
790 790 # Adjust copy records, the dirstate cannot do it, it
791 791 # requires access to parents manifests. Preserve them
792 792 # only for entries added to first parent.
793 793 for f in copies:
794 794 if f not in pctx and copies[f] in pctx:
795 795 self.dirstate.copy(copies[f], f)
796 796 if p2 == nullid:
797 797 for f, s in sorted(self.dirstate.copies().items()):
798 798 if f not in pctx and s not in pctx:
799 799 self.dirstate.copy(None, f)
800 800 self.dirstate.endparentchange()
801 801
802 802 def filectx(self, path, changeid=None, fileid=None):
803 803 """changeid can be a changeset revision, node, or tag.
804 804 fileid can be a file revision or node."""
805 805 return context.filectx(self, path, changeid, fileid)
806 806
807 807 def getcwd(self):
808 808 return self.dirstate.getcwd()
809 809
810 810 def pathto(self, f, cwd=None):
811 811 return self.dirstate.pathto(f, cwd)
812 812
813 813 def wfile(self, f, mode='r'):
814 814 return self.wopener(f, mode)
815 815
816 816 def _link(self, f):
817 817 return self.wvfs.islink(f)
818 818
819 819 def _loadfilter(self, filter):
820 820 if filter not in self.filterpats:
821 821 l = []
822 822 for pat, cmd in self.ui.configitems(filter):
823 823 if cmd == '!':
824 824 continue
825 825 mf = matchmod.match(self.root, '', [pat])
826 826 fn = None
827 827 params = cmd
828 828 for name, filterfn in self._datafilters.iteritems():
829 829 if cmd.startswith(name):
830 830 fn = filterfn
831 831 params = cmd[len(name):].lstrip()
832 832 break
833 833 if not fn:
834 834 fn = lambda s, c, **kwargs: util.filter(s, c)
835 835 # Wrap old filters not supporting keyword arguments
836 836 if not inspect.getargspec(fn)[2]:
837 837 oldfn = fn
838 838 fn = lambda s, c, **kwargs: oldfn(s, c)
839 839 l.append((mf, fn, params))
840 840 self.filterpats[filter] = l
841 841 return self.filterpats[filter]
842 842
843 843 def _filter(self, filterpats, filename, data):
844 844 for mf, fn, cmd in filterpats:
845 845 if mf(filename):
846 846 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
847 847 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
848 848 break
849 849
850 850 return data
851 851
852 852 @unfilteredpropertycache
853 853 def _encodefilterpats(self):
854 854 return self._loadfilter('encode')
855 855
856 856 @unfilteredpropertycache
857 857 def _decodefilterpats(self):
858 858 return self._loadfilter('decode')
859 859
860 860 def adddatafilter(self, name, filter):
861 861 self._datafilters[name] = filter
862 862
863 863 def wread(self, filename):
864 864 if self._link(filename):
865 865 data = self.wvfs.readlink(filename)
866 866 else:
867 867 data = self.wopener.read(filename)
868 868 return self._filter(self._encodefilterpats, filename, data)
869 869
870 870 def wwrite(self, filename, data, flags):
871 871 data = self._filter(self._decodefilterpats, filename, data)
872 872 if 'l' in flags:
873 873 self.wopener.symlink(data, filename)
874 874 else:
875 875 self.wopener.write(filename, data)
876 876 if 'x' in flags:
877 877 self.wvfs.setflags(filename, False, True)
878 878
879 879 def wwritedata(self, filename, data):
880 880 return self._filter(self._decodefilterpats, filename, data)
881 881
882 882 def currenttransaction(self):
883 883 """return the current transaction or None if non exists"""
884 884 tr = self._transref and self._transref() or None
885 885 if tr and tr.running():
886 886 return tr
887 887 return None
888 888
889 889 def transaction(self, desc, report=None):
890 890 tr = self.currenttransaction()
891 891 if tr is not None:
892 892 return tr.nest()
893 893
894 894 # abort here if the journal already exists
895 895 if self.svfs.exists("journal"):
896 896 raise error.RepoError(
897 897 _("abandoned transaction found"),
898 898 hint=_("run 'hg recover' to clean up transaction"))
899 899
900 900 self._writejournal(desc)
901 901 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
902 902 rp = report and report or self.ui.warn
903 903 vfsmap = {'plain': self.opener} # root of .hg/
904 904 tr = transaction.transaction(rp, self.sopener, vfsmap,
905 905 "journal",
906 906 aftertrans(renames),
907 907 self.store.createmode)
908 908 # note: writing the fncache only during finalize mean that the file is
909 909 # outdated when running hooks. As fncache is used for streaming clone,
910 910 # this is not expected to break anything that happen during the hooks.
911 911 tr.addfinalize('flush-fncache', self.store.write)
912 912 self._transref = weakref.ref(tr)
913 913 return tr
914 914
915 915 def _journalfiles(self):
916 916 return ((self.svfs, 'journal'),
917 917 (self.vfs, 'journal.dirstate'),
918 918 (self.vfs, 'journal.branch'),
919 919 (self.vfs, 'journal.desc'),
920 920 (self.vfs, 'journal.bookmarks'),
921 921 (self.svfs, 'journal.phaseroots'))
922 922
923 923 def undofiles(self):
924 924 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
925 925
926 926 def _writejournal(self, desc):
927 927 self.opener.write("journal.dirstate",
928 928 self.opener.tryread("dirstate"))
929 929 self.opener.write("journal.branch",
930 930 encoding.fromlocal(self.dirstate.branch()))
931 931 self.opener.write("journal.desc",
932 932 "%d\n%s\n" % (len(self), desc))
933 933 self.opener.write("journal.bookmarks",
934 934 self.opener.tryread("bookmarks"))
935 935 self.sopener.write("journal.phaseroots",
936 936 self.sopener.tryread("phaseroots"))
937 937
938 938 def recover(self):
939 939 lock = self.lock()
940 940 try:
941 941 if self.svfs.exists("journal"):
942 942 self.ui.status(_("rolling back interrupted transaction\n"))
943 943 vfsmap = {'': self.sopener,
944 944 'plain': self.opener,}
945 945 transaction.rollback(self.sopener, vfsmap, "journal",
946 946 self.ui.warn)
947 947 self.invalidate()
948 948 return True
949 949 else:
950 950 self.ui.warn(_("no interrupted transaction available\n"))
951 951 return False
952 952 finally:
953 953 lock.release()
954 954
955 955 def rollback(self, dryrun=False, force=False):
956 956 wlock = lock = None
957 957 try:
958 958 wlock = self.wlock()
959 959 lock = self.lock()
960 960 if self.svfs.exists("undo"):
961 961 return self._rollback(dryrun, force)
962 962 else:
963 963 self.ui.warn(_("no rollback information available\n"))
964 964 return 1
965 965 finally:
966 966 release(lock, wlock)
967 967
968 968 @unfilteredmethod # Until we get smarter cache management
969 969 def _rollback(self, dryrun, force):
970 970 ui = self.ui
971 971 try:
972 972 args = self.opener.read('undo.desc').splitlines()
973 973 (oldlen, desc, detail) = (int(args[0]), args[1], None)
974 974 if len(args) >= 3:
975 975 detail = args[2]
976 976 oldtip = oldlen - 1
977 977
978 978 if detail and ui.verbose:
979 979 msg = (_('repository tip rolled back to revision %s'
980 980 ' (undo %s: %s)\n')
981 981 % (oldtip, desc, detail))
982 982 else:
983 983 msg = (_('repository tip rolled back to revision %s'
984 984 ' (undo %s)\n')
985 985 % (oldtip, desc))
986 986 except IOError:
987 987 msg = _('rolling back unknown transaction\n')
988 988 desc = None
989 989
990 990 if not force and self['.'] != self['tip'] and desc == 'commit':
991 991 raise util.Abort(
992 992 _('rollback of last commit while not checked out '
993 993 'may lose data'), hint=_('use -f to force'))
994 994
995 995 ui.status(msg)
996 996 if dryrun:
997 997 return 0
998 998
999 999 parents = self.dirstate.parents()
1000 1000 self.destroying()
1001 1001 vfsmap = {'plain': self.opener}
1002 1002 transaction.rollback(self.sopener, vfsmap, 'undo', ui.warn)
1003 1003 if self.vfs.exists('undo.bookmarks'):
1004 1004 self.vfs.rename('undo.bookmarks', 'bookmarks')
1005 1005 if self.svfs.exists('undo.phaseroots'):
1006 1006 self.svfs.rename('undo.phaseroots', 'phaseroots')
1007 1007 self.invalidate()
1008 1008
1009 1009 parentgone = (parents[0] not in self.changelog.nodemap or
1010 1010 parents[1] not in self.changelog.nodemap)
1011 1011 if parentgone:
1012 1012 self.vfs.rename('undo.dirstate', 'dirstate')
1013 1013 try:
1014 1014 branch = self.opener.read('undo.branch')
1015 1015 self.dirstate.setbranch(encoding.tolocal(branch))
1016 1016 except IOError:
1017 1017 ui.warn(_('named branch could not be reset: '
1018 1018 'current branch is still \'%s\'\n')
1019 1019 % self.dirstate.branch())
1020 1020
1021 1021 self.dirstate.invalidate()
1022 1022 parents = tuple([p.rev() for p in self.parents()])
1023 1023 if len(parents) > 1:
1024 1024 ui.status(_('working directory now based on '
1025 1025 'revisions %d and %d\n') % parents)
1026 1026 else:
1027 1027 ui.status(_('working directory now based on '
1028 1028 'revision %d\n') % parents)
1029 1029 # TODO: if we know which new heads may result from this rollback, pass
1030 1030 # them to destroy(), which will prevent the branchhead cache from being
1031 1031 # invalidated.
1032 1032 self.destroyed()
1033 1033 return 0
1034 1034
1035 1035 def invalidatecaches(self):
1036 1036
1037 1037 if '_tagscache' in vars(self):
1038 1038 # can't use delattr on proxy
1039 1039 del self.__dict__['_tagscache']
1040 1040
1041 1041 self.unfiltered()._branchcaches.clear()
1042 1042 self.invalidatevolatilesets()
1043 1043
1044 1044 def invalidatevolatilesets(self):
1045 1045 self.filteredrevcache.clear()
1046 1046 obsolete.clearobscaches(self)
1047 1047
1048 1048 def invalidatedirstate(self):
1049 1049 '''Invalidates the dirstate, causing the next call to dirstate
1050 1050 to check if it was modified since the last time it was read,
1051 1051 rereading it if it has.
1052 1052
1053 1053 This is different to dirstate.invalidate() that it doesn't always
1054 1054 rereads the dirstate. Use dirstate.invalidate() if you want to
1055 1055 explicitly read the dirstate again (i.e. restoring it to a previous
1056 1056 known good state).'''
1057 1057 if hasunfilteredcache(self, 'dirstate'):
1058 1058 for k in self.dirstate._filecache:
1059 1059 try:
1060 1060 delattr(self.dirstate, k)
1061 1061 except AttributeError:
1062 1062 pass
1063 1063 delattr(self.unfiltered(), 'dirstate')
1064 1064
1065 1065 def invalidate(self):
1066 1066 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1067 1067 for k in self._filecache:
1068 1068 # dirstate is invalidated separately in invalidatedirstate()
1069 1069 if k == 'dirstate':
1070 1070 continue
1071 1071
1072 1072 try:
1073 1073 delattr(unfiltered, k)
1074 1074 except AttributeError:
1075 1075 pass
1076 1076 self.invalidatecaches()
1077 1077 self.store.invalidatecaches()
1078 1078
1079 1079 def invalidateall(self):
1080 1080 '''Fully invalidates both store and non-store parts, causing the
1081 1081 subsequent operation to reread any outside changes.'''
1082 1082 # extension should hook this to invalidate its caches
1083 1083 self.invalidate()
1084 1084 self.invalidatedirstate()
1085 1085
1086 1086 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1087 1087 try:
1088 1088 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1089 1089 except error.LockHeld, inst:
1090 1090 if not wait:
1091 1091 raise
1092 1092 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1093 1093 (desc, inst.locker))
1094 1094 # default to 600 seconds timeout
1095 1095 l = lockmod.lock(vfs, lockname,
1096 1096 int(self.ui.config("ui", "timeout", "600")),
1097 1097 releasefn, desc=desc)
1098 1098 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1099 1099 if acquirefn:
1100 1100 acquirefn()
1101 1101 return l
1102 1102
1103 1103 def _afterlock(self, callback):
1104 1104 """add a callback to the current repository lock.
1105 1105
1106 1106 The callback will be executed on lock release."""
1107 1107 l = self._lockref and self._lockref()
1108 1108 if l:
1109 1109 l.postrelease.append(callback)
1110 1110 else:
1111 1111 callback()
1112 1112
1113 1113 def lock(self, wait=True):
1114 1114 '''Lock the repository store (.hg/store) and return a weak reference
1115 1115 to the lock. Use this before modifying the store (e.g. committing or
1116 1116 stripping). If you are opening a transaction, get a lock as well.)'''
1117 1117 l = self._lockref and self._lockref()
1118 1118 if l is not None and l.held:
1119 1119 l.lock()
1120 1120 return l
1121 1121
1122 1122 def unlock():
1123 1123 for k, ce in self._filecache.items():
1124 1124 if k == 'dirstate' or k not in self.__dict__:
1125 1125 continue
1126 1126 ce.refresh()
1127 1127
1128 1128 l = self._lock(self.svfs, "lock", wait, unlock,
1129 1129 self.invalidate, _('repository %s') % self.origroot)
1130 1130 self._lockref = weakref.ref(l)
1131 1131 return l
1132 1132
1133 1133 def wlock(self, wait=True):
1134 1134 '''Lock the non-store parts of the repository (everything under
1135 1135 .hg except .hg/store) and return a weak reference to the lock.
1136 1136 Use this before modifying files in .hg.'''
1137 1137 l = self._wlockref and self._wlockref()
1138 1138 if l is not None and l.held:
1139 1139 l.lock()
1140 1140 return l
1141 1141
1142 1142 def unlock():
1143 1143 if self.dirstate.pendingparentchange():
1144 1144 self.dirstate.invalidate()
1145 1145 else:
1146 1146 self.dirstate.write()
1147 1147
1148 1148 self._filecache['dirstate'].refresh()
1149 1149
1150 1150 l = self._lock(self.vfs, "wlock", wait, unlock,
1151 1151 self.invalidatedirstate, _('working directory of %s') %
1152 1152 self.origroot)
1153 1153 self._wlockref = weakref.ref(l)
1154 1154 return l
1155 1155
1156 1156 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1157 1157 """
1158 1158 commit an individual file as part of a larger transaction
1159 1159 """
1160 1160
1161 1161 fname = fctx.path()
1162 1162 text = fctx.data()
1163 1163 flog = self.file(fname)
1164 1164 fparent1 = manifest1.get(fname, nullid)
1165 1165 fparent2 = manifest2.get(fname, nullid)
1166 1166
1167 1167 meta = {}
1168 1168 copy = fctx.renamed()
1169 1169 if copy and copy[0] != fname:
1170 1170 # Mark the new revision of this file as a copy of another
1171 1171 # file. This copy data will effectively act as a parent
1172 1172 # of this new revision. If this is a merge, the first
1173 1173 # parent will be the nullid (meaning "look up the copy data")
1174 1174 # and the second one will be the other parent. For example:
1175 1175 #
1176 1176 # 0 --- 1 --- 3 rev1 changes file foo
1177 1177 # \ / rev2 renames foo to bar and changes it
1178 1178 # \- 2 -/ rev3 should have bar with all changes and
1179 1179 # should record that bar descends from
1180 1180 # bar in rev2 and foo in rev1
1181 1181 #
1182 1182 # this allows this merge to succeed:
1183 1183 #
1184 1184 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1185 1185 # \ / merging rev3 and rev4 should use bar@rev2
1186 1186 # \- 2 --- 4 as the merge base
1187 1187 #
1188 1188
1189 1189 cfname = copy[0]
1190 1190 crev = manifest1.get(cfname)
1191 1191 newfparent = fparent2
1192 1192
1193 1193 if manifest2: # branch merge
1194 1194 if fparent2 == nullid or crev is None: # copied on remote side
1195 1195 if cfname in manifest2:
1196 1196 crev = manifest2[cfname]
1197 1197 newfparent = fparent1
1198 1198
1199 1199 # find source in nearest ancestor if we've lost track
1200 1200 if not crev:
1201 1201 self.ui.debug(" %s: searching for copy revision for %s\n" %
1202 1202 (fname, cfname))
1203 1203 for ancestor in self[None].ancestors():
1204 1204 if cfname in ancestor:
1205 1205 crev = ancestor[cfname].filenode()
1206 1206 break
1207 1207
1208 1208 if crev:
1209 1209 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1210 1210 meta["copy"] = cfname
1211 1211 meta["copyrev"] = hex(crev)
1212 1212 fparent1, fparent2 = nullid, newfparent
1213 1213 else:
1214 1214 self.ui.warn(_("warning: can't find ancestor for '%s' "
1215 1215 "copied from '%s'!\n") % (fname, cfname))
1216 1216
1217 1217 elif fparent1 == nullid:
1218 1218 fparent1, fparent2 = fparent2, nullid
1219 1219 elif fparent2 != nullid:
1220 1220 # is one parent an ancestor of the other?
1221 1221 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1222 1222 if fparent1 in fparentancestors:
1223 1223 fparent1, fparent2 = fparent2, nullid
1224 1224 elif fparent2 in fparentancestors:
1225 1225 fparent2 = nullid
1226 1226
1227 1227 # is the file changed?
1228 1228 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1229 1229 changelist.append(fname)
1230 1230 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1231 1231 # are just the flags changed during merge?
1232 1232 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1233 1233 changelist.append(fname)
1234 1234
1235 1235 return fparent1
1236 1236
1237 1237 @unfilteredmethod
1238 1238 def commit(self, text="", user=None, date=None, match=None, force=False,
1239 1239 editor=False, extra={}):
1240 1240 """Add a new revision to current repository.
1241 1241
1242 1242 Revision information is gathered from the working directory,
1243 1243 match can be used to filter the committed files. If editor is
1244 1244 supplied, it is called to get a commit message.
1245 1245 """
1246 1246
1247 1247 def fail(f, msg):
1248 1248 raise util.Abort('%s: %s' % (f, msg))
1249 1249
1250 1250 if not match:
1251 1251 match = matchmod.always(self.root, '')
1252 1252
1253 1253 if not force:
1254 1254 vdirs = []
1255 1255 match.explicitdir = vdirs.append
1256 1256 match.bad = fail
1257 1257
1258 1258 wlock = self.wlock()
1259 1259 try:
1260 1260 wctx = self[None]
1261 1261 merge = len(wctx.parents()) > 1
1262 1262
1263 1263 if (not force and merge and match and
1264 1264 (match.files() or match.anypats())):
1265 1265 raise util.Abort(_('cannot partially commit a merge '
1266 1266 '(do not specify files or patterns)'))
1267 1267
1268 1268 status = self.status(match=match, clean=force)
1269 1269 if force:
1270 1270 status.modified.extend(status.clean) # mq may commit clean files
1271 1271
1272 1272 # check subrepos
1273 1273 subs = []
1274 1274 commitsubs = set()
1275 1275 newstate = wctx.substate.copy()
1276 1276 # only manage subrepos and .hgsubstate if .hgsub is present
1277 1277 if '.hgsub' in wctx:
1278 1278 # we'll decide whether to track this ourselves, thanks
1279 1279 for c in status.modified, status.added, status.removed:
1280 1280 if '.hgsubstate' in c:
1281 1281 c.remove('.hgsubstate')
1282 1282
1283 1283 # compare current state to last committed state
1284 1284 # build new substate based on last committed state
1285 1285 oldstate = wctx.p1().substate
1286 1286 for s in sorted(newstate.keys()):
1287 1287 if not match(s):
1288 1288 # ignore working copy, use old state if present
1289 1289 if s in oldstate:
1290 1290 newstate[s] = oldstate[s]
1291 1291 continue
1292 1292 if not force:
1293 1293 raise util.Abort(
1294 1294 _("commit with new subrepo %s excluded") % s)
1295 1295 if wctx.sub(s).dirty(True):
1296 1296 if not self.ui.configbool('ui', 'commitsubrepos'):
1297 1297 raise util.Abort(
1298 1298 _("uncommitted changes in subrepo %s") % s,
1299 1299 hint=_("use --subrepos for recursive commit"))
1300 1300 subs.append(s)
1301 1301 commitsubs.add(s)
1302 1302 else:
1303 1303 bs = wctx.sub(s).basestate()
1304 1304 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1305 1305 if oldstate.get(s, (None, None, None))[1] != bs:
1306 1306 subs.append(s)
1307 1307
1308 1308 # check for removed subrepos
1309 1309 for p in wctx.parents():
1310 1310 r = [s for s in p.substate if s not in newstate]
1311 1311 subs += [s for s in r if match(s)]
1312 1312 if subs:
1313 1313 if (not match('.hgsub') and
1314 1314 '.hgsub' in (wctx.modified() + wctx.added())):
1315 1315 raise util.Abort(
1316 1316 _("can't commit subrepos without .hgsub"))
1317 1317 status.modified.insert(0, '.hgsubstate')
1318 1318
1319 1319 elif '.hgsub' in status.removed:
1320 1320 # clean up .hgsubstate when .hgsub is removed
1321 1321 if ('.hgsubstate' in wctx and
1322 1322 '.hgsubstate' not in (status.modified + status.added +
1323 1323 status.removed)):
1324 1324 status.removed.insert(0, '.hgsubstate')
1325 1325
1326 1326 # make sure all explicit patterns are matched
1327 1327 if not force and match.files():
1328 1328 matched = set(status.modified + status.added + status.removed)
1329 1329
1330 1330 for f in match.files():
1331 1331 f = self.dirstate.normalize(f)
1332 1332 if f == '.' or f in matched or f in wctx.substate:
1333 1333 continue
1334 1334 if f in status.deleted:
1335 1335 fail(f, _('file not found!'))
1336 1336 if f in vdirs: # visited directory
1337 1337 d = f + '/'
1338 1338 for mf in matched:
1339 1339 if mf.startswith(d):
1340 1340 break
1341 1341 else:
1342 1342 fail(f, _("no match under directory!"))
1343 1343 elif f not in self.dirstate:
1344 1344 fail(f, _("file not tracked!"))
1345 1345
1346 1346 cctx = context.workingcommitctx(self, status,
1347 1347 text, user, date, extra)
1348 1348
1349 1349 if (not force and not extra.get("close") and not merge
1350 1350 and not cctx.files()
1351 1351 and wctx.branch() == wctx.p1().branch()):
1352 1352 return None
1353 1353
1354 1354 if merge and cctx.deleted():
1355 1355 raise util.Abort(_("cannot commit merge with missing files"))
1356 1356
1357 1357 ms = mergemod.mergestate(self)
1358 1358 for f in status.modified:
1359 1359 if f in ms and ms[f] == 'u':
1360 1360 raise util.Abort(_("unresolved merge conflicts "
1361 1361 "(see hg help resolve)"))
1362 1362
1363 1363 if editor:
1364 1364 cctx._text = editor(self, cctx, subs)
1365 1365 edited = (text != cctx._text)
1366 1366
1367 1367 # Save commit message in case this transaction gets rolled back
1368 1368 # (e.g. by a pretxncommit hook). Leave the content alone on
1369 1369 # the assumption that the user will use the same editor again.
1370 1370 msgfn = self.savecommitmessage(cctx._text)
1371 1371
1372 1372 # commit subs and write new state
1373 1373 if subs:
1374 1374 for s in sorted(commitsubs):
1375 1375 sub = wctx.sub(s)
1376 1376 self.ui.status(_('committing subrepository %s\n') %
1377 1377 subrepo.subrelpath(sub))
1378 1378 sr = sub.commit(cctx._text, user, date)
1379 1379 newstate[s] = (newstate[s][0], sr)
1380 1380 subrepo.writestate(self, newstate)
1381 1381
1382 1382 p1, p2 = self.dirstate.parents()
1383 1383 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1384 1384 try:
1385 1385 self.hook("precommit", throw=True, parent1=hookp1,
1386 1386 parent2=hookp2)
1387 1387 ret = self.commitctx(cctx, True)
1388 1388 except: # re-raises
1389 1389 if edited:
1390 1390 self.ui.write(
1391 1391 _('note: commit message saved in %s\n') % msgfn)
1392 1392 raise
1393 1393
1394 1394 # update bookmarks, dirstate and mergestate
1395 1395 bookmarks.update(self, [p1, p2], ret)
1396 1396 cctx.markcommitted(ret)
1397 1397 ms.reset()
1398 1398 finally:
1399 1399 wlock.release()
1400 1400
1401 1401 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1402 1402 # hack for command that use a temporary commit (eg: histedit)
1403 1403 # temporary commit got stripped before hook release
1404 1404 if node in self:
1405 1405 self.hook("commit", node=node, parent1=parent1,
1406 1406 parent2=parent2)
1407 1407 self._afterlock(commithook)
1408 1408 return ret
1409 1409
1410 1410 @unfilteredmethod
1411 1411 def commitctx(self, ctx, error=False):
1412 1412 """Add a new revision to current repository.
1413 1413 Revision information is passed via the context argument.
1414 1414 """
1415 1415
1416 1416 tr = None
1417 1417 p1, p2 = ctx.p1(), ctx.p2()
1418 1418 user = ctx.user()
1419 1419
1420 1420 lock = self.lock()
1421 1421 try:
1422 1422 tr = self.transaction("commit")
1423 1423 trp = weakref.proxy(tr)
1424 1424
1425 1425 if ctx.files():
1426 1426 m1 = p1.manifest()
1427 1427 m2 = p2.manifest()
1428 1428 m = m1.copy()
1429 1429
1430 1430 # check in files
1431 1431 added = []
1432 1432 changed = []
1433 1433 removed = list(ctx.removed())
1434 1434 linkrev = len(self)
1435 1435 for f in sorted(ctx.modified() + ctx.added()):
1436 1436 self.ui.note(f + "\n")
1437 1437 try:
1438 1438 fctx = ctx[f]
1439 1439 if fctx is None:
1440 1440 removed.append(f)
1441 1441 else:
1442 1442 added.append(f)
1443 1443 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1444 1444 trp, changed)
1445 1445 m.setflag(f, fctx.flags())
1446 1446 except OSError, inst:
1447 1447 self.ui.warn(_("trouble committing %s!\n") % f)
1448 1448 raise
1449 1449 except IOError, inst:
1450 1450 errcode = getattr(inst, 'errno', errno.ENOENT)
1451 1451 if error or errcode and errcode != errno.ENOENT:
1452 1452 self.ui.warn(_("trouble committing %s!\n") % f)
1453 1453 raise
1454 1454
1455 1455 # update manifest
1456 1456 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1457 1457 drop = [f for f in removed if f in m]
1458 1458 for f in drop:
1459 1459 del m[f]
1460 1460 mn = self.manifest.add(m, trp, linkrev,
1461 1461 p1.manifestnode(), p2.manifestnode(),
1462 1462 added, drop)
1463 1463 files = changed + removed
1464 1464 else:
1465 1465 mn = p1.manifestnode()
1466 1466 files = []
1467 1467
1468 1468 # update changelog
1469 1469 self.changelog.delayupdate(tr)
1470 1470 n = self.changelog.add(mn, files, ctx.description(),
1471 1471 trp, p1.node(), p2.node(),
1472 1472 user, ctx.date(), ctx.extra().copy())
1473 1473 p = lambda: tr.writepending() and self.root or ""
1474 1474 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1475 1475 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1476 1476 parent2=xp2, pending=p)
1477 1477 # set the new commit is proper phase
1478 1478 targetphase = subrepo.newcommitphase(self.ui, ctx)
1479 1479 if targetphase:
1480 1480 # retract boundary do not alter parent changeset.
1481 1481 # if a parent have higher the resulting phase will
1482 1482 # be compliant anyway
1483 1483 #
1484 1484 # if minimal phase was 0 we don't need to retract anything
1485 1485 phases.retractboundary(self, tr, targetphase, [n])
1486 1486 tr.close()
1487 1487 branchmap.updatecache(self.filtered('served'))
1488 1488 return n
1489 1489 finally:
1490 1490 if tr:
1491 1491 tr.release()
1492 1492 lock.release()
1493 1493
1494 1494 @unfilteredmethod
1495 1495 def destroying(self):
1496 1496 '''Inform the repository that nodes are about to be destroyed.
1497 1497 Intended for use by strip and rollback, so there's a common
1498 1498 place for anything that has to be done before destroying history.
1499 1499
1500 1500 This is mostly useful for saving state that is in memory and waiting
1501 1501 to be flushed when the current lock is released. Because a call to
1502 1502 destroyed is imminent, the repo will be invalidated causing those
1503 1503 changes to stay in memory (waiting for the next unlock), or vanish
1504 1504 completely.
1505 1505 '''
1506 1506 # When using the same lock to commit and strip, the phasecache is left
1507 1507 # dirty after committing. Then when we strip, the repo is invalidated,
1508 1508 # causing those changes to disappear.
1509 1509 if '_phasecache' in vars(self):
1510 1510 self._phasecache.write()
1511 1511
1512 1512 @unfilteredmethod
1513 1513 def destroyed(self):
1514 1514 '''Inform the repository that nodes have been destroyed.
1515 1515 Intended for use by strip and rollback, so there's a common
1516 1516 place for anything that has to be done after destroying history.
1517 1517 '''
1518 1518 # When one tries to:
1519 1519 # 1) destroy nodes thus calling this method (e.g. strip)
1520 1520 # 2) use phasecache somewhere (e.g. commit)
1521 1521 #
1522 1522 # then 2) will fail because the phasecache contains nodes that were
1523 1523 # removed. We can either remove phasecache from the filecache,
1524 1524 # causing it to reload next time it is accessed, or simply filter
1525 1525 # the removed nodes now and write the updated cache.
1526 1526 self._phasecache.filterunknown(self)
1527 1527 self._phasecache.write()
1528 1528
1529 1529 # update the 'served' branch cache to help read only server process
1530 1530 # Thanks to branchcache collaboration this is done from the nearest
1531 1531 # filtered subset and it is expected to be fast.
1532 1532 branchmap.updatecache(self.filtered('served'))
1533 1533
1534 1534 # Ensure the persistent tag cache is updated. Doing it now
1535 1535 # means that the tag cache only has to worry about destroyed
1536 1536 # heads immediately after a strip/rollback. That in turn
1537 1537 # guarantees that "cachetip == currenttip" (comparing both rev
1538 1538 # and node) always means no nodes have been added or destroyed.
1539 1539
1540 1540 # XXX this is suboptimal when qrefresh'ing: we strip the current
1541 1541 # head, refresh the tag cache, then immediately add a new head.
1542 1542 # But I think doing it this way is necessary for the "instant
1543 1543 # tag cache retrieval" case to work.
1544 1544 self.invalidate()
1545 1545
1546 1546 def walk(self, match, node=None):
1547 1547 '''
1548 1548 walk recursively through the directory tree or a given
1549 1549 changeset, finding all files matched by the match
1550 1550 function
1551 1551 '''
1552 1552 return self[node].walk(match)
1553 1553
1554 1554 def status(self, node1='.', node2=None, match=None,
1555 1555 ignored=False, clean=False, unknown=False,
1556 1556 listsubrepos=False):
1557 1557 '''a convenience method that calls node1.status(node2)'''
1558 1558 return self[node1].status(node2, match, ignored, clean, unknown,
1559 1559 listsubrepos)
1560 1560
1561 1561 def heads(self, start=None):
1562 1562 heads = self.changelog.heads(start)
1563 1563 # sort the output in rev descending order
1564 1564 return sorted(heads, key=self.changelog.rev, reverse=True)
1565 1565
1566 1566 def branchheads(self, branch=None, start=None, closed=False):
1567 1567 '''return a (possibly filtered) list of heads for the given branch
1568 1568
1569 1569 Heads are returned in topological order, from newest to oldest.
1570 1570 If branch is None, use the dirstate branch.
1571 1571 If start is not None, return only heads reachable from start.
1572 1572 If closed is True, return heads that are marked as closed as well.
1573 1573 '''
1574 1574 if branch is None:
1575 1575 branch = self[None].branch()
1576 1576 branches = self.branchmap()
1577 1577 if branch not in branches:
1578 1578 return []
1579 1579 # the cache returns heads ordered lowest to highest
1580 1580 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1581 1581 if start is not None:
1582 1582 # filter out the heads that cannot be reached from startrev
1583 1583 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1584 1584 bheads = [h for h in bheads if h in fbheads]
1585 1585 return bheads
1586 1586
1587 1587 def branches(self, nodes):
1588 1588 if not nodes:
1589 1589 nodes = [self.changelog.tip()]
1590 1590 b = []
1591 1591 for n in nodes:
1592 1592 t = n
1593 1593 while True:
1594 1594 p = self.changelog.parents(n)
1595 1595 if p[1] != nullid or p[0] == nullid:
1596 1596 b.append((t, n, p[0], p[1]))
1597 1597 break
1598 1598 n = p[0]
1599 1599 return b
1600 1600
1601 1601 def between(self, pairs):
1602 1602 r = []
1603 1603
1604 1604 for top, bottom in pairs:
1605 1605 n, l, i = top, [], 0
1606 1606 f = 1
1607 1607
1608 1608 while n != bottom and n != nullid:
1609 1609 p = self.changelog.parents(n)[0]
1610 1610 if i == f:
1611 1611 l.append(n)
1612 1612 f = f * 2
1613 1613 n = p
1614 1614 i += 1
1615 1615
1616 1616 r.append(l)
1617 1617
1618 1618 return r
1619 1619
1620 1620 def checkpush(self, pushop):
1621 1621 """Extensions can override this function if additional checks have
1622 1622 to be performed before pushing, or call it if they override push
1623 1623 command.
1624 1624 """
1625 1625 pass
1626 1626
1627 1627 @unfilteredpropertycache
1628 1628 def prepushoutgoinghooks(self):
1629 1629 """Return util.hooks consists of "(repo, remote, outgoing)"
1630 1630 functions, which are called before pushing changesets.
1631 1631 """
1632 1632 return util.hooks()
1633 1633
1634 1634 def stream_in(self, remote, requirements):
1635 1635 lock = self.lock()
1636 1636 try:
1637 1637 # Save remote branchmap. We will use it later
1638 1638 # to speed up branchcache creation
1639 1639 rbranchmap = None
1640 1640 if remote.capable("branchmap"):
1641 1641 rbranchmap = remote.branchmap()
1642 1642
1643 1643 fp = remote.stream_out()
1644 1644 l = fp.readline()
1645 1645 try:
1646 1646 resp = int(l)
1647 1647 except ValueError:
1648 1648 raise error.ResponseError(
1649 1649 _('unexpected response from remote server:'), l)
1650 1650 if resp == 1:
1651 1651 raise util.Abort(_('operation forbidden by server'))
1652 1652 elif resp == 2:
1653 1653 raise util.Abort(_('locking the remote repository failed'))
1654 1654 elif resp != 0:
1655 1655 raise util.Abort(_('the server sent an unknown error code'))
1656 1656 self.ui.status(_('streaming all changes\n'))
1657 1657 l = fp.readline()
1658 1658 try:
1659 1659 total_files, total_bytes = map(int, l.split(' ', 1))
1660 1660 except (ValueError, TypeError):
1661 1661 raise error.ResponseError(
1662 1662 _('unexpected response from remote server:'), l)
1663 1663 self.ui.status(_('%d files to transfer, %s of data\n') %
1664 1664 (total_files, util.bytecount(total_bytes)))
1665 1665 handled_bytes = 0
1666 1666 self.ui.progress(_('clone'), 0, total=total_bytes)
1667 1667 start = time.time()
1668 1668
1669 1669 tr = self.transaction(_('clone'))
1670 1670 try:
1671 1671 for i in xrange(total_files):
1672 1672 # XXX doesn't support '\n' or '\r' in filenames
1673 1673 l = fp.readline()
1674 1674 try:
1675 1675 name, size = l.split('\0', 1)
1676 1676 size = int(size)
1677 1677 except (ValueError, TypeError):
1678 1678 raise error.ResponseError(
1679 1679 _('unexpected response from remote server:'), l)
1680 1680 if self.ui.debugflag:
1681 1681 self.ui.debug('adding %s (%s)\n' %
1682 1682 (name, util.bytecount(size)))
1683 1683 # for backwards compat, name was partially encoded
1684 1684 ofp = self.sopener(store.decodedir(name), 'w')
1685 1685 for chunk in util.filechunkiter(fp, limit=size):
1686 1686 handled_bytes += len(chunk)
1687 1687 self.ui.progress(_('clone'), handled_bytes,
1688 1688 total=total_bytes)
1689 1689 ofp.write(chunk)
1690 1690 ofp.close()
1691 1691 tr.close()
1692 1692 finally:
1693 1693 tr.release()
1694 1694
1695 1695 # Writing straight to files circumvented the inmemory caches
1696 1696 self.invalidate()
1697 1697
1698 1698 elapsed = time.time() - start
1699 1699 if elapsed <= 0:
1700 1700 elapsed = 0.001
1701 1701 self.ui.progress(_('clone'), None)
1702 1702 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1703 1703 (util.bytecount(total_bytes), elapsed,
1704 1704 util.bytecount(total_bytes / elapsed)))
1705 1705
1706 1706 # new requirements = old non-format requirements +
1707 1707 # new format-related
1708 1708 # requirements from the streamed-in repository
1709 1709 requirements.update(set(self.requirements) - self.supportedformats)
1710 1710 self._applyrequirements(requirements)
1711 1711 self._writerequirements()
1712 1712
1713 1713 if rbranchmap:
1714 1714 rbheads = []
1715 1715 closed = []
1716 1716 for bheads in rbranchmap.itervalues():
1717 1717 rbheads.extend(bheads)
1718 1718 for h in bheads:
1719 1719 r = self.changelog.rev(h)
1720 1720 b, c = self.changelog.branchinfo(r)
1721 1721 if c:
1722 1722 closed.append(h)
1723 1723
1724 1724 if rbheads:
1725 1725 rtiprev = max((int(self.changelog.rev(node))
1726 1726 for node in rbheads))
1727 1727 cache = branchmap.branchcache(rbranchmap,
1728 1728 self[rtiprev].node(),
1729 1729 rtiprev,
1730 1730 closednodes=closed)
1731 1731 # Try to stick it as low as possible
1732 1732 # filter above served are unlikely to be fetch from a clone
1733 1733 for candidate in ('base', 'immutable', 'served'):
1734 1734 rview = self.filtered(candidate)
1735 1735 if cache.validfor(rview):
1736 1736 self._branchcaches[candidate] = cache
1737 1737 cache.write(rview)
1738 1738 break
1739 1739 self.invalidate()
1740 1740 return len(self.heads()) + 1
1741 1741 finally:
1742 1742 lock.release()
1743 1743
1744 1744 def clone(self, remote, heads=[], stream=None):
1745 1745 '''clone remote repository.
1746 1746
1747 1747 keyword arguments:
1748 1748 heads: list of revs to clone (forces use of pull)
1749 1749 stream: use streaming clone if possible'''
1750 1750
1751 1751 # now, all clients that can request uncompressed clones can
1752 1752 # read repo formats supported by all servers that can serve
1753 1753 # them.
1754 1754
1755 1755 # if revlog format changes, client will have to check version
1756 1756 # and format flags on "stream" capability, and use
1757 1757 # uncompressed only if compatible.
1758 1758
1759 1759 if stream is None:
1760 1760 # if the server explicitly prefers to stream (for fast LANs)
1761 1761 stream = remote.capable('stream-preferred')
1762 1762
1763 1763 if stream and not heads:
1764 1764 # 'stream' means remote revlog format is revlogv1 only
1765 1765 if remote.capable('stream'):
1766 1766 self.stream_in(remote, set(('revlogv1',)))
1767 1767 else:
1768 1768 # otherwise, 'streamreqs' contains the remote revlog format
1769 1769 streamreqs = remote.capable('streamreqs')
1770 1770 if streamreqs:
1771 1771 streamreqs = set(streamreqs.split(','))
1772 1772 # if we support it, stream in and adjust our requirements
1773 1773 if not streamreqs - self.supportedformats:
1774 1774 self.stream_in(remote, streamreqs)
1775 1775
1776 1776 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1777 1777 try:
1778 1778 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1779 1779 ret = exchange.pull(self, remote, heads).cgresult
1780 1780 finally:
1781 1781 self.ui.restoreconfig(quiet)
1782 1782 return ret
1783 1783
1784 1784 def pushkey(self, namespace, key, old, new):
1785 1785 try:
1786 1786 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
1787 1787 old=old, new=new)
1788 1788 except error.HookAbort, exc:
1789 1789 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
1790 1790 if exc.hint:
1791 1791 self.ui.write_err(_("(%s)\n") % exc.hint)
1792 1792 return False
1793 1793 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1794 1794 ret = pushkey.push(self, namespace, key, old, new)
1795 1795 def runhook():
1796 1796 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1797 1797 ret=ret)
1798 1798 self._afterlock(runhook)
1799 1799 return ret
1800 1800
1801 1801 def listkeys(self, namespace):
1802 1802 self.hook('prelistkeys', throw=True, namespace=namespace)
1803 1803 self.ui.debug('listing keys for "%s"\n' % namespace)
1804 1804 values = pushkey.list(self, namespace)
1805 1805 self.hook('listkeys', namespace=namespace, values=values)
1806 1806 return values
1807 1807
1808 1808 def debugwireargs(self, one, two, three=None, four=None, five=None):
1809 1809 '''used to test argument passing over the wire'''
1810 1810 return "%s %s %s %s %s" % (one, two, three, four, five)
1811 1811
1812 1812 def savecommitmessage(self, text):
1813 1813 fp = self.opener('last-message.txt', 'wb')
1814 1814 try:
1815 1815 fp.write(text)
1816 1816 finally:
1817 1817 fp.close()
1818 1818 return self.pathto(fp.name[len(self.root) + 1:])
1819 1819
1820 1820 # used to avoid circular references so destructors work
1821 1821 def aftertrans(files):
1822 1822 renamefiles = [tuple(t) for t in files]
1823 1823 def a():
1824 1824 for vfs, src, dest in renamefiles:
1825 1825 try:
1826 1826 vfs.rename(src, dest)
1827 1827 except OSError: # journal file does not yet exist
1828 1828 pass
1829 1829 return a
1830 1830
1831 1831 def undoname(fn):
1832 1832 base, name = os.path.split(fn)
1833 1833 assert name.startswith('journal')
1834 1834 return os.path.join(base, name.replace('journal', 'undo', 1))
1835 1835
1836 1836 def instance(ui, path, create):
1837 1837 return localrepository(ui, util.urllocalpath(path), create)
1838 1838
1839 1839 def islocal(path):
1840 1840 return True
General Comments 0
You need to be logged in to leave comments. Login now