##// END OF EJS Templates
localrepo: prevent wlock from being inherited when a transaction is running...
Siddharth Agarwal -
r26499:e72b62b1 default
parent child Browse files
Show More
@@ -1,1886 +1,1894
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, wdirrev, 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, random
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 **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 'HG20' 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.getunbundler(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 try:
129 129 cg = exchange.readbundle(self.ui, cg, None)
130 130 ret = exchange.unbundle(self._repo, cg, heads, 'push', url)
131 131 if util.safehasattr(ret, 'getchunks'):
132 132 # This is a bundle20 object, turn it into an unbundler.
133 133 # This little dance should be dropped eventually when the
134 134 # API is finally improved.
135 135 stream = util.chunkbuffer(ret.getchunks())
136 136 ret = bundle2.getunbundler(self.ui, stream)
137 137 return ret
138 138 except Exception as exc:
139 139 # If the exception contains output salvaged from a bundle2
140 140 # reply, we need to make sure it is printed before continuing
141 141 # to fail. So we build a bundle2 with such output and consume
142 142 # it directly.
143 143 #
144 144 # This is not very elegant but allows a "simple" solution for
145 145 # issue4594
146 146 output = getattr(exc, '_bundle2salvagedoutput', ())
147 147 if output:
148 148 bundler = bundle2.bundle20(self._repo.ui)
149 149 for out in output:
150 150 bundler.addpart(out)
151 151 stream = util.chunkbuffer(bundler.getchunks())
152 152 b = bundle2.getunbundler(self.ui, stream)
153 153 bundle2.processbundle(self._repo, b)
154 154 raise
155 155 except error.PushRaced as exc:
156 156 raise error.ResponseError(_('push failed:'), str(exc))
157 157
158 158 def lock(self):
159 159 return self._repo.lock()
160 160
161 161 def addchangegroup(self, cg, source, url):
162 162 return changegroup.addchangegroup(self._repo, cg, source, url)
163 163
164 164 def pushkey(self, namespace, key, old, new):
165 165 return self._repo.pushkey(namespace, key, old, new)
166 166
167 167 def listkeys(self, namespace):
168 168 return self._repo.listkeys(namespace)
169 169
170 170 def debugwireargs(self, one, two, three=None, four=None, five=None):
171 171 '''used to test argument passing over the wire'''
172 172 return "%s %s %s %s %s" % (one, two, three, four, five)
173 173
174 174 class locallegacypeer(localpeer):
175 175 '''peer extension which implements legacy methods too; used for tests with
176 176 restricted capabilities'''
177 177
178 178 def __init__(self, repo):
179 179 localpeer.__init__(self, repo, caps=legacycaps)
180 180
181 181 def branches(self, nodes):
182 182 return self._repo.branches(nodes)
183 183
184 184 def between(self, pairs):
185 185 return self._repo.between(pairs)
186 186
187 187 def changegroup(self, basenodes, source):
188 188 return changegroup.changegroup(self._repo, basenodes, source)
189 189
190 190 def changegroupsubset(self, bases, heads, source):
191 191 return changegroup.changegroupsubset(self._repo, bases, heads, source)
192 192
193 193 class localrepository(object):
194 194
195 195 supportedformats = set(('revlogv1', 'generaldelta', 'treemanifest',
196 196 'manifestv2'))
197 197 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
198 198 'dotencode'))
199 199 openerreqs = set(('revlogv1', 'generaldelta', 'treemanifest', 'manifestv2'))
200 200 filtername = None
201 201
202 202 # a list of (ui, featureset) functions.
203 203 # only functions defined in module of enabled extensions are invoked
204 204 featuresetupfuncs = set()
205 205
206 206 def _baserequirements(self, create):
207 207 return ['revlogv1']
208 208
209 209 def __init__(self, baseui, path=None, create=False):
210 210 self.requirements = set()
211 211 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
212 212 self.wopener = self.wvfs
213 213 self.root = self.wvfs.base
214 214 self.path = self.wvfs.join(".hg")
215 215 self.origroot = path
216 216 self.auditor = pathutil.pathauditor(self.root, self._checknested)
217 217 self.vfs = scmutil.vfs(self.path)
218 218 self.opener = self.vfs
219 219 self.baseui = baseui
220 220 self.ui = baseui.copy()
221 221 self.ui.copy = baseui.copy # prevent copying repo configuration
222 222 # A list of callback to shape the phase if no data were found.
223 223 # Callback are in the form: func(repo, roots) --> processed root.
224 224 # This list it to be filled by extension during repo setup
225 225 self._phasedefaults = []
226 226 try:
227 227 self.ui.readconfig(self.join("hgrc"), self.root)
228 228 extensions.loadall(self.ui)
229 229 except IOError:
230 230 pass
231 231
232 232 if self.featuresetupfuncs:
233 233 self.supported = set(self._basesupported) # use private copy
234 234 extmods = set(m.__name__ for n, m
235 235 in extensions.extensions(self.ui))
236 236 for setupfunc in self.featuresetupfuncs:
237 237 if setupfunc.__module__ in extmods:
238 238 setupfunc(self.ui, self.supported)
239 239 else:
240 240 self.supported = self._basesupported
241 241
242 242 if not self.vfs.isdir():
243 243 if create:
244 244 if not self.wvfs.exists():
245 245 self.wvfs.makedirs()
246 246 self.vfs.makedir(notindexed=True)
247 247 self.requirements.update(self._baserequirements(create))
248 248 if self.ui.configbool('format', 'usestore', True):
249 249 self.vfs.mkdir("store")
250 250 self.requirements.add("store")
251 251 if self.ui.configbool('format', 'usefncache', True):
252 252 self.requirements.add("fncache")
253 253 if self.ui.configbool('format', 'dotencode', True):
254 254 self.requirements.add('dotencode')
255 255 # create an invalid changelog
256 256 self.vfs.append(
257 257 "00changelog.i",
258 258 '\0\0\0\2' # represents revlogv2
259 259 ' dummy changelog to prevent using the old repo layout'
260 260 )
261 261 # experimental config: format.generaldelta
262 262 if self.ui.configbool('format', 'generaldelta', False):
263 263 self.requirements.add("generaldelta")
264 264 if self.ui.configbool('experimental', 'treemanifest', False):
265 265 self.requirements.add("treemanifest")
266 266 if self.ui.configbool('experimental', 'manifestv2', False):
267 267 self.requirements.add("manifestv2")
268 268 else:
269 269 raise error.RepoError(_("repository %s not found") % path)
270 270 elif create:
271 271 raise error.RepoError(_("repository %s already exists") % path)
272 272 else:
273 273 try:
274 274 self.requirements = scmutil.readrequires(
275 275 self.vfs, self.supported)
276 276 except IOError as inst:
277 277 if inst.errno != errno.ENOENT:
278 278 raise
279 279
280 280 self.sharedpath = self.path
281 281 try:
282 282 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
283 283 realpath=True)
284 284 s = vfs.base
285 285 if not vfs.exists():
286 286 raise error.RepoError(
287 287 _('.hg/sharedpath points to nonexistent directory %s') % s)
288 288 self.sharedpath = s
289 289 except IOError as inst:
290 290 if inst.errno != errno.ENOENT:
291 291 raise
292 292
293 293 self.store = store.store(
294 294 self.requirements, self.sharedpath, scmutil.vfs)
295 295 self.spath = self.store.path
296 296 self.svfs = self.store.vfs
297 297 self.sjoin = self.store.join
298 298 self.vfs.createmode = self.store.createmode
299 299 self._applyopenerreqs()
300 300 if create:
301 301 self._writerequirements()
302 302
303 303 self._dirstatevalidatewarned = False
304 304
305 305 self._branchcaches = {}
306 306 self._revbranchcache = None
307 307 self.filterpats = {}
308 308 self._datafilters = {}
309 309 self._transref = self._lockref = self._wlockref = None
310 310
311 311 # A cache for various files under .hg/ that tracks file changes,
312 312 # (used by the filecache decorator)
313 313 #
314 314 # Maps a property name to its util.filecacheentry
315 315 self._filecache = {}
316 316
317 317 # hold sets of revision to be filtered
318 318 # should be cleared when something might have changed the filter value:
319 319 # - new changesets,
320 320 # - phase change,
321 321 # - new obsolescence marker,
322 322 # - working directory parent change,
323 323 # - bookmark changes
324 324 self.filteredrevcache = {}
325 325
326 326 # generic mapping between names and nodes
327 327 self.names = namespaces.namespaces()
328 328
329 329 def close(self):
330 330 self._writecaches()
331 331
332 332 def _writecaches(self):
333 333 if self._revbranchcache:
334 334 self._revbranchcache.write()
335 335
336 336 def _restrictcapabilities(self, caps):
337 337 if self.ui.configbool('experimental', 'bundle2-advertise', True):
338 338 caps = set(caps)
339 339 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self))
340 340 caps.add('bundle2=' + urllib.quote(capsblob))
341 341 return caps
342 342
343 343 def _applyopenerreqs(self):
344 344 self.svfs.options = dict((r, 1) for r in self.requirements
345 345 if r in self.openerreqs)
346 346 # experimental config: format.chunkcachesize
347 347 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
348 348 if chunkcachesize is not None:
349 349 self.svfs.options['chunkcachesize'] = chunkcachesize
350 350 # experimental config: format.maxchainlen
351 351 maxchainlen = self.ui.configint('format', 'maxchainlen')
352 352 if maxchainlen is not None:
353 353 self.svfs.options['maxchainlen'] = maxchainlen
354 354 # experimental config: format.manifestcachesize
355 355 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
356 356 if manifestcachesize is not None:
357 357 self.svfs.options['manifestcachesize'] = manifestcachesize
358 358 # experimental config: format.aggressivemergedeltas
359 359 aggressivemergedeltas = self.ui.configbool('format',
360 360 'aggressivemergedeltas', False)
361 361 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
362 362
363 363 def _writerequirements(self):
364 364 scmutil.writerequires(self.vfs, self.requirements)
365 365
366 366 def _checknested(self, path):
367 367 """Determine if path is a legal nested repository."""
368 368 if not path.startswith(self.root):
369 369 return False
370 370 subpath = path[len(self.root) + 1:]
371 371 normsubpath = util.pconvert(subpath)
372 372
373 373 # XXX: Checking against the current working copy is wrong in
374 374 # the sense that it can reject things like
375 375 #
376 376 # $ hg cat -r 10 sub/x.txt
377 377 #
378 378 # if sub/ is no longer a subrepository in the working copy
379 379 # parent revision.
380 380 #
381 381 # However, it can of course also allow things that would have
382 382 # been rejected before, such as the above cat command if sub/
383 383 # is a subrepository now, but was a normal directory before.
384 384 # The old path auditor would have rejected by mistake since it
385 385 # panics when it sees sub/.hg/.
386 386 #
387 387 # All in all, checking against the working copy seems sensible
388 388 # since we want to prevent access to nested repositories on
389 389 # the filesystem *now*.
390 390 ctx = self[None]
391 391 parts = util.splitpath(subpath)
392 392 while parts:
393 393 prefix = '/'.join(parts)
394 394 if prefix in ctx.substate:
395 395 if prefix == normsubpath:
396 396 return True
397 397 else:
398 398 sub = ctx.sub(prefix)
399 399 return sub.checknested(subpath[len(prefix) + 1:])
400 400 else:
401 401 parts.pop()
402 402 return False
403 403
404 404 def peer(self):
405 405 return localpeer(self) # not cached to avoid reference cycle
406 406
407 407 def unfiltered(self):
408 408 """Return unfiltered version of the repository
409 409
410 410 Intended to be overwritten by filtered repo."""
411 411 return self
412 412
413 413 def filtered(self, name):
414 414 """Return a filtered version of a repository"""
415 415 # build a new class with the mixin and the current class
416 416 # (possibly subclass of the repo)
417 417 class proxycls(repoview.repoview, self.unfiltered().__class__):
418 418 pass
419 419 return proxycls(self, name)
420 420
421 421 @repofilecache('bookmarks')
422 422 def _bookmarks(self):
423 423 return bookmarks.bmstore(self)
424 424
425 425 @repofilecache('bookmarks.current')
426 426 def _activebookmark(self):
427 427 return bookmarks.readactive(self)
428 428
429 429 def bookmarkheads(self, bookmark):
430 430 name = bookmark.split('@', 1)[0]
431 431 heads = []
432 432 for mark, n in self._bookmarks.iteritems():
433 433 if mark.split('@', 1)[0] == name:
434 434 heads.append(n)
435 435 return heads
436 436
437 437 # _phaserevs and _phasesets depend on changelog. what we need is to
438 438 # call _phasecache.invalidate() if '00changelog.i' was changed, but it
439 439 # can't be easily expressed in filecache mechanism.
440 440 @storecache('phaseroots', '00changelog.i')
441 441 def _phasecache(self):
442 442 return phases.phasecache(self, self._phasedefaults)
443 443
444 444 @storecache('obsstore')
445 445 def obsstore(self):
446 446 # read default format for new obsstore.
447 447 # developer config: format.obsstore-version
448 448 defaultformat = self.ui.configint('format', 'obsstore-version', None)
449 449 # rely on obsstore class default when possible.
450 450 kwargs = {}
451 451 if defaultformat is not None:
452 452 kwargs['defaultformat'] = defaultformat
453 453 readonly = not obsolete.isenabled(self, obsolete.createmarkersopt)
454 454 store = obsolete.obsstore(self.svfs, readonly=readonly,
455 455 **kwargs)
456 456 if store and readonly:
457 457 self.ui.warn(
458 458 _('obsolete feature not enabled but %i markers found!\n')
459 459 % len(list(store)))
460 460 return store
461 461
462 462 @storecache('00changelog.i')
463 463 def changelog(self):
464 464 c = changelog.changelog(self.svfs)
465 465 if 'HG_PENDING' in os.environ:
466 466 p = os.environ['HG_PENDING']
467 467 if p.startswith(self.root):
468 468 c.readpending('00changelog.i.a')
469 469 return c
470 470
471 471 @storecache('00manifest.i')
472 472 def manifest(self):
473 473 return manifest.manifest(self.svfs)
474 474
475 475 def dirlog(self, dir):
476 476 return self.manifest.dirlog(dir)
477 477
478 478 @repofilecache('dirstate')
479 479 def dirstate(self):
480 480 return dirstate.dirstate(self.vfs, self.ui, self.root,
481 481 self._dirstatevalidate)
482 482
483 483 def _dirstatevalidate(self, node):
484 484 try:
485 485 self.changelog.rev(node)
486 486 return node
487 487 except error.LookupError:
488 488 if not self._dirstatevalidatewarned:
489 489 self._dirstatevalidatewarned = True
490 490 self.ui.warn(_("warning: ignoring unknown"
491 491 " working parent %s!\n") % short(node))
492 492 return nullid
493 493
494 494 def __getitem__(self, changeid):
495 495 if changeid is None or changeid == wdirrev:
496 496 return context.workingctx(self)
497 497 if isinstance(changeid, slice):
498 498 return [context.changectx(self, i)
499 499 for i in xrange(*changeid.indices(len(self)))
500 500 if i not in self.changelog.filteredrevs]
501 501 return context.changectx(self, changeid)
502 502
503 503 def __contains__(self, changeid):
504 504 try:
505 505 self[changeid]
506 506 return True
507 507 except error.RepoLookupError:
508 508 return False
509 509
510 510 def __nonzero__(self):
511 511 return True
512 512
513 513 def __len__(self):
514 514 return len(self.changelog)
515 515
516 516 def __iter__(self):
517 517 return iter(self.changelog)
518 518
519 519 def revs(self, expr, *args):
520 520 '''Return a list of revisions matching the given revset'''
521 521 expr = revset.formatspec(expr, *args)
522 522 m = revset.match(None, expr)
523 523 return m(self)
524 524
525 525 def set(self, expr, *args):
526 526 '''
527 527 Yield a context for each matching revision, after doing arg
528 528 replacement via revset.formatspec
529 529 '''
530 530 for r in self.revs(expr, *args):
531 531 yield self[r]
532 532
533 533 def url(self):
534 534 return 'file:' + self.root
535 535
536 536 def hook(self, name, throw=False, **args):
537 537 """Call a hook, passing this repo instance.
538 538
539 539 This a convenience method to aid invoking hooks. Extensions likely
540 540 won't call this unless they have registered a custom hook or are
541 541 replacing code that is expected to call a hook.
542 542 """
543 543 return hook.hook(self.ui, self, name, throw, **args)
544 544
545 545 @unfilteredmethod
546 546 def _tag(self, names, node, message, local, user, date, extra=None,
547 547 editor=False):
548 548 if isinstance(names, str):
549 549 names = (names,)
550 550
551 551 branches = self.branchmap()
552 552 for name in names:
553 553 self.hook('pretag', throw=True, node=hex(node), tag=name,
554 554 local=local)
555 555 if name in branches:
556 556 self.ui.warn(_("warning: tag %s conflicts with existing"
557 557 " branch name\n") % name)
558 558
559 559 def writetags(fp, names, munge, prevtags):
560 560 fp.seek(0, 2)
561 561 if prevtags and prevtags[-1] != '\n':
562 562 fp.write('\n')
563 563 for name in names:
564 564 if munge:
565 565 m = munge(name)
566 566 else:
567 567 m = name
568 568
569 569 if (self._tagscache.tagtypes and
570 570 name in self._tagscache.tagtypes):
571 571 old = self.tags().get(name, nullid)
572 572 fp.write('%s %s\n' % (hex(old), m))
573 573 fp.write('%s %s\n' % (hex(node), m))
574 574 fp.close()
575 575
576 576 prevtags = ''
577 577 if local:
578 578 try:
579 579 fp = self.vfs('localtags', 'r+')
580 580 except IOError:
581 581 fp = self.vfs('localtags', 'a')
582 582 else:
583 583 prevtags = fp.read()
584 584
585 585 # local tags are stored in the current charset
586 586 writetags(fp, names, None, prevtags)
587 587 for name in names:
588 588 self.hook('tag', node=hex(node), tag=name, local=local)
589 589 return
590 590
591 591 try:
592 592 fp = self.wfile('.hgtags', 'rb+')
593 593 except IOError as e:
594 594 if e.errno != errno.ENOENT:
595 595 raise
596 596 fp = self.wfile('.hgtags', 'ab')
597 597 else:
598 598 prevtags = fp.read()
599 599
600 600 # committed tags are stored in UTF-8
601 601 writetags(fp, names, encoding.fromlocal, prevtags)
602 602
603 603 fp.close()
604 604
605 605 self.invalidatecaches()
606 606
607 607 if '.hgtags' not in self.dirstate:
608 608 self[None].add(['.hgtags'])
609 609
610 610 m = matchmod.exact(self.root, '', ['.hgtags'])
611 611 tagnode = self.commit(message, user, date, extra=extra, match=m,
612 612 editor=editor)
613 613
614 614 for name in names:
615 615 self.hook('tag', node=hex(node), tag=name, local=local)
616 616
617 617 return tagnode
618 618
619 619 def tag(self, names, node, message, local, user, date, editor=False):
620 620 '''tag a revision with one or more symbolic names.
621 621
622 622 names is a list of strings or, when adding a single tag, names may be a
623 623 string.
624 624
625 625 if local is True, the tags are stored in a per-repository file.
626 626 otherwise, they are stored in the .hgtags file, and a new
627 627 changeset is committed with the change.
628 628
629 629 keyword arguments:
630 630
631 631 local: whether to store tags in non-version-controlled file
632 632 (default False)
633 633
634 634 message: commit message to use if committing
635 635
636 636 user: name of user to use if committing
637 637
638 638 date: date tuple to use if committing'''
639 639
640 640 if not local:
641 641 m = matchmod.exact(self.root, '', ['.hgtags'])
642 642 if any(self.status(match=m, unknown=True, ignored=True)):
643 643 raise util.Abort(_('working copy of .hgtags is changed'),
644 644 hint=_('please commit .hgtags manually'))
645 645
646 646 self.tags() # instantiate the cache
647 647 self._tag(names, node, message, local, user, date, editor=editor)
648 648
649 649 @filteredpropertycache
650 650 def _tagscache(self):
651 651 '''Returns a tagscache object that contains various tags related
652 652 caches.'''
653 653
654 654 # This simplifies its cache management by having one decorated
655 655 # function (this one) and the rest simply fetch things from it.
656 656 class tagscache(object):
657 657 def __init__(self):
658 658 # These two define the set of tags for this repository. tags
659 659 # maps tag name to node; tagtypes maps tag name to 'global' or
660 660 # 'local'. (Global tags are defined by .hgtags across all
661 661 # heads, and local tags are defined in .hg/localtags.)
662 662 # They constitute the in-memory cache of tags.
663 663 self.tags = self.tagtypes = None
664 664
665 665 self.nodetagscache = self.tagslist = None
666 666
667 667 cache = tagscache()
668 668 cache.tags, cache.tagtypes = self._findtags()
669 669
670 670 return cache
671 671
672 672 def tags(self):
673 673 '''return a mapping of tag to node'''
674 674 t = {}
675 675 if self.changelog.filteredrevs:
676 676 tags, tt = self._findtags()
677 677 else:
678 678 tags = self._tagscache.tags
679 679 for k, v in tags.iteritems():
680 680 try:
681 681 # ignore tags to unknown nodes
682 682 self.changelog.rev(v)
683 683 t[k] = v
684 684 except (error.LookupError, ValueError):
685 685 pass
686 686 return t
687 687
688 688 def _findtags(self):
689 689 '''Do the hard work of finding tags. Return a pair of dicts
690 690 (tags, tagtypes) where tags maps tag name to node, and tagtypes
691 691 maps tag name to a string like \'global\' or \'local\'.
692 692 Subclasses or extensions are free to add their own tags, but
693 693 should be aware that the returned dicts will be retained for the
694 694 duration of the localrepo object.'''
695 695
696 696 # XXX what tagtype should subclasses/extensions use? Currently
697 697 # mq and bookmarks add tags, but do not set the tagtype at all.
698 698 # Should each extension invent its own tag type? Should there
699 699 # be one tagtype for all such "virtual" tags? Or is the status
700 700 # quo fine?
701 701
702 702 alltags = {} # map tag name to (node, hist)
703 703 tagtypes = {}
704 704
705 705 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
706 706 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
707 707
708 708 # Build the return dicts. Have to re-encode tag names because
709 709 # the tags module always uses UTF-8 (in order not to lose info
710 710 # writing to the cache), but the rest of Mercurial wants them in
711 711 # local encoding.
712 712 tags = {}
713 713 for (name, (node, hist)) in alltags.iteritems():
714 714 if node != nullid:
715 715 tags[encoding.tolocal(name)] = node
716 716 tags['tip'] = self.changelog.tip()
717 717 tagtypes = dict([(encoding.tolocal(name), value)
718 718 for (name, value) in tagtypes.iteritems()])
719 719 return (tags, tagtypes)
720 720
721 721 def tagtype(self, tagname):
722 722 '''
723 723 return the type of the given tag. result can be:
724 724
725 725 'local' : a local tag
726 726 'global' : a global tag
727 727 None : tag does not exist
728 728 '''
729 729
730 730 return self._tagscache.tagtypes.get(tagname)
731 731
732 732 def tagslist(self):
733 733 '''return a list of tags ordered by revision'''
734 734 if not self._tagscache.tagslist:
735 735 l = []
736 736 for t, n in self.tags().iteritems():
737 737 l.append((self.changelog.rev(n), t, n))
738 738 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
739 739
740 740 return self._tagscache.tagslist
741 741
742 742 def nodetags(self, node):
743 743 '''return the tags associated with a node'''
744 744 if not self._tagscache.nodetagscache:
745 745 nodetagscache = {}
746 746 for t, n in self._tagscache.tags.iteritems():
747 747 nodetagscache.setdefault(n, []).append(t)
748 748 for tags in nodetagscache.itervalues():
749 749 tags.sort()
750 750 self._tagscache.nodetagscache = nodetagscache
751 751 return self._tagscache.nodetagscache.get(node, [])
752 752
753 753 def nodebookmarks(self, node):
754 754 marks = []
755 755 for bookmark, n in self._bookmarks.iteritems():
756 756 if n == node:
757 757 marks.append(bookmark)
758 758 return sorted(marks)
759 759
760 760 def branchmap(self):
761 761 '''returns a dictionary {branch: [branchheads]} with branchheads
762 762 ordered by increasing revision number'''
763 763 branchmap.updatecache(self)
764 764 return self._branchcaches[self.filtername]
765 765
766 766 @unfilteredmethod
767 767 def revbranchcache(self):
768 768 if not self._revbranchcache:
769 769 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
770 770 return self._revbranchcache
771 771
772 772 def branchtip(self, branch, ignoremissing=False):
773 773 '''return the tip node for a given branch
774 774
775 775 If ignoremissing is True, then this method will not raise an error.
776 776 This is helpful for callers that only expect None for a missing branch
777 777 (e.g. namespace).
778 778
779 779 '''
780 780 try:
781 781 return self.branchmap().branchtip(branch)
782 782 except KeyError:
783 783 if not ignoremissing:
784 784 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
785 785 else:
786 786 pass
787 787
788 788 def lookup(self, key):
789 789 return self[key].node()
790 790
791 791 def lookupbranch(self, key, remote=None):
792 792 repo = remote or self
793 793 if key in repo.branchmap():
794 794 return key
795 795
796 796 repo = (remote and remote.local()) and remote or self
797 797 return repo[key].branch()
798 798
799 799 def known(self, nodes):
800 800 nm = self.changelog.nodemap
801 801 pc = self._phasecache
802 802 result = []
803 803 for n in nodes:
804 804 r = nm.get(n)
805 805 resp = not (r is None or pc.phase(self, r) >= phases.secret)
806 806 result.append(resp)
807 807 return result
808 808
809 809 def local(self):
810 810 return self
811 811
812 812 def publishing(self):
813 813 # it's safe (and desirable) to trust the publish flag unconditionally
814 814 # so that we don't finalize changes shared between users via ssh or nfs
815 815 return self.ui.configbool('phases', 'publish', True, untrusted=True)
816 816
817 817 def cancopy(self):
818 818 # so statichttprepo's override of local() works
819 819 if not self.local():
820 820 return False
821 821 if not self.publishing():
822 822 return True
823 823 # if publishing we can't copy if there is filtered content
824 824 return not self.filtered('visible').changelog.filteredrevs
825 825
826 826 def shared(self):
827 827 '''the type of shared repository (None if not shared)'''
828 828 if self.sharedpath != self.path:
829 829 return 'store'
830 830 return None
831 831
832 832 def join(self, f, *insidef):
833 833 return self.vfs.join(os.path.join(f, *insidef))
834 834
835 835 def wjoin(self, f, *insidef):
836 836 return self.vfs.reljoin(self.root, f, *insidef)
837 837
838 838 def file(self, f):
839 839 if f[0] == '/':
840 840 f = f[1:]
841 841 return filelog.filelog(self.svfs, f)
842 842
843 843 def changectx(self, changeid):
844 844 return self[changeid]
845 845
846 846 def parents(self, changeid=None):
847 847 '''get list of changectxs for parents of changeid'''
848 848 return self[changeid].parents()
849 849
850 850 def setparents(self, p1, p2=nullid):
851 851 self.dirstate.beginparentchange()
852 852 copies = self.dirstate.setparents(p1, p2)
853 853 pctx = self[p1]
854 854 if copies:
855 855 # Adjust copy records, the dirstate cannot do it, it
856 856 # requires access to parents manifests. Preserve them
857 857 # only for entries added to first parent.
858 858 for f in copies:
859 859 if f not in pctx and copies[f] in pctx:
860 860 self.dirstate.copy(copies[f], f)
861 861 if p2 == nullid:
862 862 for f, s in sorted(self.dirstate.copies().items()):
863 863 if f not in pctx and s not in pctx:
864 864 self.dirstate.copy(None, f)
865 865 self.dirstate.endparentchange()
866 866
867 867 def filectx(self, path, changeid=None, fileid=None):
868 868 """changeid can be a changeset revision, node, or tag.
869 869 fileid can be a file revision or node."""
870 870 return context.filectx(self, path, changeid, fileid)
871 871
872 872 def getcwd(self):
873 873 return self.dirstate.getcwd()
874 874
875 875 def pathto(self, f, cwd=None):
876 876 return self.dirstate.pathto(f, cwd)
877 877
878 878 def wfile(self, f, mode='r'):
879 879 return self.wvfs(f, mode)
880 880
881 881 def _link(self, f):
882 882 return self.wvfs.islink(f)
883 883
884 884 def _loadfilter(self, filter):
885 885 if filter not in self.filterpats:
886 886 l = []
887 887 for pat, cmd in self.ui.configitems(filter):
888 888 if cmd == '!':
889 889 continue
890 890 mf = matchmod.match(self.root, '', [pat])
891 891 fn = None
892 892 params = cmd
893 893 for name, filterfn in self._datafilters.iteritems():
894 894 if cmd.startswith(name):
895 895 fn = filterfn
896 896 params = cmd[len(name):].lstrip()
897 897 break
898 898 if not fn:
899 899 fn = lambda s, c, **kwargs: util.filter(s, c)
900 900 # Wrap old filters not supporting keyword arguments
901 901 if not inspect.getargspec(fn)[2]:
902 902 oldfn = fn
903 903 fn = lambda s, c, **kwargs: oldfn(s, c)
904 904 l.append((mf, fn, params))
905 905 self.filterpats[filter] = l
906 906 return self.filterpats[filter]
907 907
908 908 def _filter(self, filterpats, filename, data):
909 909 for mf, fn, cmd in filterpats:
910 910 if mf(filename):
911 911 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
912 912 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
913 913 break
914 914
915 915 return data
916 916
917 917 @unfilteredpropertycache
918 918 def _encodefilterpats(self):
919 919 return self._loadfilter('encode')
920 920
921 921 @unfilteredpropertycache
922 922 def _decodefilterpats(self):
923 923 return self._loadfilter('decode')
924 924
925 925 def adddatafilter(self, name, filter):
926 926 self._datafilters[name] = filter
927 927
928 928 def wread(self, filename):
929 929 if self._link(filename):
930 930 data = self.wvfs.readlink(filename)
931 931 else:
932 932 data = self.wvfs.read(filename)
933 933 return self._filter(self._encodefilterpats, filename, data)
934 934
935 935 def wwrite(self, filename, data, flags):
936 936 """write ``data`` into ``filename`` in the working directory
937 937
938 938 This returns length of written (maybe decoded) data.
939 939 """
940 940 data = self._filter(self._decodefilterpats, filename, data)
941 941 if 'l' in flags:
942 942 self.wvfs.symlink(data, filename)
943 943 else:
944 944 self.wvfs.write(filename, data)
945 945 if 'x' in flags:
946 946 self.wvfs.setflags(filename, False, True)
947 947 return len(data)
948 948
949 949 def wwritedata(self, filename, data):
950 950 return self._filter(self._decodefilterpats, filename, data)
951 951
952 952 def currenttransaction(self):
953 953 """return the current transaction or None if non exists"""
954 954 if self._transref:
955 955 tr = self._transref()
956 956 else:
957 957 tr = None
958 958
959 959 if tr and tr.running():
960 960 return tr
961 961 return None
962 962
963 963 def transaction(self, desc, report=None):
964 964 if (self.ui.configbool('devel', 'all-warnings')
965 965 or self.ui.configbool('devel', 'check-locks')):
966 966 l = self._lockref and self._lockref()
967 967 if l is None or not l.held:
968 968 self.ui.develwarn('transaction with no lock')
969 969 tr = self.currenttransaction()
970 970 if tr is not None:
971 971 return tr.nest()
972 972
973 973 # abort here if the journal already exists
974 974 if self.svfs.exists("journal"):
975 975 raise error.RepoError(
976 976 _("abandoned transaction found"),
977 977 hint=_("run 'hg recover' to clean up transaction"))
978 978
979 979 # make journal.dirstate contain in-memory changes at this point
980 980 self.dirstate.write()
981 981
982 982 idbase = "%.40f#%f" % (random.random(), time.time())
983 983 txnid = 'TXN:' + util.sha1(idbase).hexdigest()
984 984 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
985 985
986 986 self._writejournal(desc)
987 987 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
988 988 if report:
989 989 rp = report
990 990 else:
991 991 rp = self.ui.warn
992 992 vfsmap = {'plain': self.vfs} # root of .hg/
993 993 # we must avoid cyclic reference between repo and transaction.
994 994 reporef = weakref.ref(self)
995 995 def validate(tr):
996 996 """will run pre-closing hooks"""
997 997 pending = lambda: tr.writepending() and self.root or ""
998 998 reporef().hook('pretxnclose', throw=True, pending=pending,
999 999 txnname=desc, **tr.hookargs)
1000 1000
1001 1001 tr = transaction.transaction(rp, self.svfs, vfsmap,
1002 1002 "journal",
1003 1003 "undo",
1004 1004 aftertrans(renames),
1005 1005 self.store.createmode,
1006 1006 validator=validate)
1007 1007
1008 1008 tr.hookargs['txnid'] = txnid
1009 1009 # note: writing the fncache only during finalize mean that the file is
1010 1010 # outdated when running hooks. As fncache is used for streaming clone,
1011 1011 # this is not expected to break anything that happen during the hooks.
1012 1012 tr.addfinalize('flush-fncache', self.store.write)
1013 1013 def txnclosehook(tr2):
1014 1014 """To be run if transaction is successful, will schedule a hook run
1015 1015 """
1016 1016 def hook():
1017 1017 reporef().hook('txnclose', throw=False, txnname=desc,
1018 1018 **tr2.hookargs)
1019 1019 reporef()._afterlock(hook)
1020 1020 tr.addfinalize('txnclose-hook', txnclosehook)
1021 1021 def txnaborthook(tr2):
1022 1022 """To be run if transaction is aborted
1023 1023 """
1024 1024 reporef().hook('txnabort', throw=False, txnname=desc,
1025 1025 **tr2.hookargs)
1026 1026 tr.addabort('txnabort-hook', txnaborthook)
1027 1027 # avoid eager cache invalidation. in-memory data should be identical
1028 1028 # to stored data if transaction has no error.
1029 1029 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1030 1030 self._transref = weakref.ref(tr)
1031 1031 return tr
1032 1032
1033 1033 def _journalfiles(self):
1034 1034 return ((self.svfs, 'journal'),
1035 1035 (self.vfs, 'journal.dirstate'),
1036 1036 (self.vfs, 'journal.branch'),
1037 1037 (self.vfs, 'journal.desc'),
1038 1038 (self.vfs, 'journal.bookmarks'),
1039 1039 (self.svfs, 'journal.phaseroots'))
1040 1040
1041 1041 def undofiles(self):
1042 1042 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1043 1043
1044 1044 def _writejournal(self, desc):
1045 1045 self.vfs.write("journal.dirstate",
1046 1046 self.vfs.tryread("dirstate"))
1047 1047 self.vfs.write("journal.branch",
1048 1048 encoding.fromlocal(self.dirstate.branch()))
1049 1049 self.vfs.write("journal.desc",
1050 1050 "%d\n%s\n" % (len(self), desc))
1051 1051 self.vfs.write("journal.bookmarks",
1052 1052 self.vfs.tryread("bookmarks"))
1053 1053 self.svfs.write("journal.phaseroots",
1054 1054 self.svfs.tryread("phaseroots"))
1055 1055
1056 1056 def recover(self):
1057 1057 lock = self.lock()
1058 1058 try:
1059 1059 if self.svfs.exists("journal"):
1060 1060 self.ui.status(_("rolling back interrupted transaction\n"))
1061 1061 vfsmap = {'': self.svfs,
1062 1062 'plain': self.vfs,}
1063 1063 transaction.rollback(self.svfs, vfsmap, "journal",
1064 1064 self.ui.warn)
1065 1065 self.invalidate()
1066 1066 return True
1067 1067 else:
1068 1068 self.ui.warn(_("no interrupted transaction available\n"))
1069 1069 return False
1070 1070 finally:
1071 1071 lock.release()
1072 1072
1073 1073 def rollback(self, dryrun=False, force=False):
1074 1074 wlock = lock = None
1075 1075 try:
1076 1076 wlock = self.wlock()
1077 1077 lock = self.lock()
1078 1078 if self.svfs.exists("undo"):
1079 1079 return self._rollback(dryrun, force)
1080 1080 else:
1081 1081 self.ui.warn(_("no rollback information available\n"))
1082 1082 return 1
1083 1083 finally:
1084 1084 release(lock, wlock)
1085 1085
1086 1086 @unfilteredmethod # Until we get smarter cache management
1087 1087 def _rollback(self, dryrun, force):
1088 1088 ui = self.ui
1089 1089 try:
1090 1090 args = self.vfs.read('undo.desc').splitlines()
1091 1091 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1092 1092 if len(args) >= 3:
1093 1093 detail = args[2]
1094 1094 oldtip = oldlen - 1
1095 1095
1096 1096 if detail and ui.verbose:
1097 1097 msg = (_('repository tip rolled back to revision %s'
1098 1098 ' (undo %s: %s)\n')
1099 1099 % (oldtip, desc, detail))
1100 1100 else:
1101 1101 msg = (_('repository tip rolled back to revision %s'
1102 1102 ' (undo %s)\n')
1103 1103 % (oldtip, desc))
1104 1104 except IOError:
1105 1105 msg = _('rolling back unknown transaction\n')
1106 1106 desc = None
1107 1107
1108 1108 if not force and self['.'] != self['tip'] and desc == 'commit':
1109 1109 raise util.Abort(
1110 1110 _('rollback of last commit while not checked out '
1111 1111 'may lose data'), hint=_('use -f to force'))
1112 1112
1113 1113 ui.status(msg)
1114 1114 if dryrun:
1115 1115 return 0
1116 1116
1117 1117 parents = self.dirstate.parents()
1118 1118 self.destroying()
1119 1119 vfsmap = {'plain': self.vfs, '': self.svfs}
1120 1120 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn)
1121 1121 if self.vfs.exists('undo.bookmarks'):
1122 1122 self.vfs.rename('undo.bookmarks', 'bookmarks')
1123 1123 if self.svfs.exists('undo.phaseroots'):
1124 1124 self.svfs.rename('undo.phaseroots', 'phaseroots')
1125 1125 self.invalidate()
1126 1126
1127 1127 parentgone = (parents[0] not in self.changelog.nodemap or
1128 1128 parents[1] not in self.changelog.nodemap)
1129 1129 if parentgone:
1130 1130 self.vfs.rename('undo.dirstate', 'dirstate')
1131 1131 try:
1132 1132 branch = self.vfs.read('undo.branch')
1133 1133 self.dirstate.setbranch(encoding.tolocal(branch))
1134 1134 except IOError:
1135 1135 ui.warn(_('named branch could not be reset: '
1136 1136 'current branch is still \'%s\'\n')
1137 1137 % self.dirstate.branch())
1138 1138
1139 1139 self.dirstate.invalidate()
1140 1140 parents = tuple([p.rev() for p in self.parents()])
1141 1141 if len(parents) > 1:
1142 1142 ui.status(_('working directory now based on '
1143 1143 'revisions %d and %d\n') % parents)
1144 1144 else:
1145 1145 ui.status(_('working directory now based on '
1146 1146 'revision %d\n') % parents)
1147 1147 ms = mergemod.mergestate(self)
1148 1148 ms.reset(self['.'].node())
1149 1149
1150 1150 # TODO: if we know which new heads may result from this rollback, pass
1151 1151 # them to destroy(), which will prevent the branchhead cache from being
1152 1152 # invalidated.
1153 1153 self.destroyed()
1154 1154 return 0
1155 1155
1156 1156 def invalidatecaches(self):
1157 1157
1158 1158 if '_tagscache' in vars(self):
1159 1159 # can't use delattr on proxy
1160 1160 del self.__dict__['_tagscache']
1161 1161
1162 1162 self.unfiltered()._branchcaches.clear()
1163 1163 self.invalidatevolatilesets()
1164 1164
1165 1165 def invalidatevolatilesets(self):
1166 1166 self.filteredrevcache.clear()
1167 1167 obsolete.clearobscaches(self)
1168 1168
1169 1169 def invalidatedirstate(self):
1170 1170 '''Invalidates the dirstate, causing the next call to dirstate
1171 1171 to check if it was modified since the last time it was read,
1172 1172 rereading it if it has.
1173 1173
1174 1174 This is different to dirstate.invalidate() that it doesn't always
1175 1175 rereads the dirstate. Use dirstate.invalidate() if you want to
1176 1176 explicitly read the dirstate again (i.e. restoring it to a previous
1177 1177 known good state).'''
1178 1178 if hasunfilteredcache(self, 'dirstate'):
1179 1179 for k in self.dirstate._filecache:
1180 1180 try:
1181 1181 delattr(self.dirstate, k)
1182 1182 except AttributeError:
1183 1183 pass
1184 1184 delattr(self.unfiltered(), 'dirstate')
1185 1185
1186 1186 def invalidate(self):
1187 1187 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1188 1188 for k in self._filecache:
1189 1189 # dirstate is invalidated separately in invalidatedirstate()
1190 1190 if k == 'dirstate':
1191 1191 continue
1192 1192
1193 1193 try:
1194 1194 delattr(unfiltered, k)
1195 1195 except AttributeError:
1196 1196 pass
1197 1197 self.invalidatecaches()
1198 1198 self.store.invalidatecaches()
1199 1199
1200 1200 def invalidateall(self):
1201 1201 '''Fully invalidates both store and non-store parts, causing the
1202 1202 subsequent operation to reread any outside changes.'''
1203 1203 # extension should hook this to invalidate its caches
1204 1204 self.invalidate()
1205 1205 self.invalidatedirstate()
1206 1206
1207 1207 def _refreshfilecachestats(self, tr):
1208 1208 """Reload stats of cached files so that they are flagged as valid"""
1209 1209 for k, ce in self._filecache.items():
1210 1210 if k == 'dirstate' or k not in self.__dict__:
1211 1211 continue
1212 1212 ce.refresh()
1213 1213
1214 1214 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1215 parentenvvar=None):
1215 inheritchecker=None, parentenvvar=None):
1216 1216 parentlock = None
1217 1217 # the contents of parentenvvar are used by the underlying lock to
1218 1218 # determine whether it can be inherited
1219 1219 if parentenvvar is not None:
1220 1220 parentlock = os.environ.get(parentenvvar)
1221 1221 try:
1222 1222 l = lockmod.lock(vfs, lockname, 0, releasefn=releasefn,
1223 1223 acquirefn=acquirefn, desc=desc,
1224 inheritchecker=inheritchecker,
1224 1225 parentlock=parentlock)
1225 1226 except error.LockHeld as inst:
1226 1227 if not wait:
1227 1228 raise
1228 1229 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1229 1230 (desc, inst.locker))
1230 1231 # default to 600 seconds timeout
1231 1232 l = lockmod.lock(vfs, lockname,
1232 1233 int(self.ui.config("ui", "timeout", "600")),
1233 1234 releasefn=releasefn, acquirefn=acquirefn,
1234 1235 desc=desc)
1235 1236 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1236 1237 return l
1237 1238
1238 1239 def _afterlock(self, callback):
1239 1240 """add a callback to be run when the repository is fully unlocked
1240 1241
1241 1242 The callback will be executed when the outermost lock is released
1242 1243 (with wlock being higher level than 'lock')."""
1243 1244 for ref in (self._wlockref, self._lockref):
1244 1245 l = ref and ref()
1245 1246 if l and l.held:
1246 1247 l.postrelease.append(callback)
1247 1248 break
1248 1249 else: # no lock have been found.
1249 1250 callback()
1250 1251
1251 1252 def lock(self, wait=True):
1252 1253 '''Lock the repository store (.hg/store) and return a weak reference
1253 1254 to the lock. Use this before modifying the store (e.g. committing or
1254 1255 stripping). If you are opening a transaction, get a lock as well.)
1255 1256
1256 1257 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1257 1258 'wlock' first to avoid a dead-lock hazard.'''
1258 1259 l = self._lockref and self._lockref()
1259 1260 if l is not None and l.held:
1260 1261 l.lock()
1261 1262 return l
1262 1263
1263 1264 l = self._lock(self.svfs, "lock", wait, None,
1264 1265 self.invalidate, _('repository %s') % self.origroot)
1265 1266 self._lockref = weakref.ref(l)
1266 1267 return l
1267 1268
1269 def _wlockchecktransaction(self):
1270 if self.currenttransaction() is not None:
1271 raise error.LockInheritanceContractViolation(
1272 'wlock cannot be inherited in the middle of a transaction')
1273
1268 1274 def wlock(self, wait=True):
1269 1275 '''Lock the non-store parts of the repository (everything under
1270 1276 .hg except .hg/store) and return a weak reference to the lock.
1271 1277
1272 1278 Use this before modifying files in .hg.
1273 1279
1274 1280 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1275 1281 'wlock' first to avoid a dead-lock hazard.'''
1276 1282 l = self._wlockref and self._wlockref()
1277 1283 if l is not None and l.held:
1278 1284 l.lock()
1279 1285 return l
1280 1286
1281 1287 # We do not need to check for non-waiting lock aquisition. Such
1282 1288 # acquisition would not cause dead-lock as they would just fail.
1283 1289 if wait and (self.ui.configbool('devel', 'all-warnings')
1284 1290 or self.ui.configbool('devel', 'check-locks')):
1285 1291 l = self._lockref and self._lockref()
1286 1292 if l is not None and l.held:
1287 1293 self.ui.develwarn('"wlock" acquired after "lock"')
1288 1294
1289 1295 def unlock():
1290 1296 if self.dirstate.pendingparentchange():
1291 1297 self.dirstate.invalidate()
1292 1298 else:
1293 1299 self.dirstate.write()
1294 1300
1295 1301 self._filecache['dirstate'].refresh()
1296 1302
1297 1303 l = self._lock(self.vfs, "wlock", wait, unlock,
1298 1304 self.invalidatedirstate, _('working directory of %s') %
1299 self.origroot, parentenvvar='HG_WLOCK_LOCKER')
1305 self.origroot,
1306 inheritchecker=self._wlockchecktransaction,
1307 parentenvvar='HG_WLOCK_LOCKER')
1300 1308 self._wlockref = weakref.ref(l)
1301 1309 return l
1302 1310
1303 1311 def _currentlock(self, lockref):
1304 1312 """Returns the lock if it's held, or None if it's not."""
1305 1313 if lockref is None:
1306 1314 return None
1307 1315 l = lockref()
1308 1316 if l is None or not l.held:
1309 1317 return None
1310 1318 return l
1311 1319
1312 1320 def currentwlock(self):
1313 1321 """Returns the wlock if it's held, or None if it's not."""
1314 1322 return self._currentlock(self._wlockref)
1315 1323
1316 1324 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1317 1325 """
1318 1326 commit an individual file as part of a larger transaction
1319 1327 """
1320 1328
1321 1329 fname = fctx.path()
1322 1330 fparent1 = manifest1.get(fname, nullid)
1323 1331 fparent2 = manifest2.get(fname, nullid)
1324 1332 if isinstance(fctx, context.filectx):
1325 1333 node = fctx.filenode()
1326 1334 if node in [fparent1, fparent2]:
1327 1335 self.ui.debug('reusing %s filelog entry\n' % fname)
1328 1336 return node
1329 1337
1330 1338 flog = self.file(fname)
1331 1339 meta = {}
1332 1340 copy = fctx.renamed()
1333 1341 if copy and copy[0] != fname:
1334 1342 # Mark the new revision of this file as a copy of another
1335 1343 # file. This copy data will effectively act as a parent
1336 1344 # of this new revision. If this is a merge, the first
1337 1345 # parent will be the nullid (meaning "look up the copy data")
1338 1346 # and the second one will be the other parent. For example:
1339 1347 #
1340 1348 # 0 --- 1 --- 3 rev1 changes file foo
1341 1349 # \ / rev2 renames foo to bar and changes it
1342 1350 # \- 2 -/ rev3 should have bar with all changes and
1343 1351 # should record that bar descends from
1344 1352 # bar in rev2 and foo in rev1
1345 1353 #
1346 1354 # this allows this merge to succeed:
1347 1355 #
1348 1356 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1349 1357 # \ / merging rev3 and rev4 should use bar@rev2
1350 1358 # \- 2 --- 4 as the merge base
1351 1359 #
1352 1360
1353 1361 cfname = copy[0]
1354 1362 crev = manifest1.get(cfname)
1355 1363 newfparent = fparent2
1356 1364
1357 1365 if manifest2: # branch merge
1358 1366 if fparent2 == nullid or crev is None: # copied on remote side
1359 1367 if cfname in manifest2:
1360 1368 crev = manifest2[cfname]
1361 1369 newfparent = fparent1
1362 1370
1363 1371 # Here, we used to search backwards through history to try to find
1364 1372 # where the file copy came from if the source of a copy was not in
1365 1373 # the parent directory. However, this doesn't actually make sense to
1366 1374 # do (what does a copy from something not in your working copy even
1367 1375 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1368 1376 # the user that copy information was dropped, so if they didn't
1369 1377 # expect this outcome it can be fixed, but this is the correct
1370 1378 # behavior in this circumstance.
1371 1379
1372 1380 if crev:
1373 1381 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1374 1382 meta["copy"] = cfname
1375 1383 meta["copyrev"] = hex(crev)
1376 1384 fparent1, fparent2 = nullid, newfparent
1377 1385 else:
1378 1386 self.ui.warn(_("warning: can't find ancestor for '%s' "
1379 1387 "copied from '%s'!\n") % (fname, cfname))
1380 1388
1381 1389 elif fparent1 == nullid:
1382 1390 fparent1, fparent2 = fparent2, nullid
1383 1391 elif fparent2 != nullid:
1384 1392 # is one parent an ancestor of the other?
1385 1393 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1386 1394 if fparent1 in fparentancestors:
1387 1395 fparent1, fparent2 = fparent2, nullid
1388 1396 elif fparent2 in fparentancestors:
1389 1397 fparent2 = nullid
1390 1398
1391 1399 # is the file changed?
1392 1400 text = fctx.data()
1393 1401 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1394 1402 changelist.append(fname)
1395 1403 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1396 1404 # are just the flags changed during merge?
1397 1405 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1398 1406 changelist.append(fname)
1399 1407
1400 1408 return fparent1
1401 1409
1402 1410 @unfilteredmethod
1403 1411 def commit(self, text="", user=None, date=None, match=None, force=False,
1404 1412 editor=False, extra=None):
1405 1413 """Add a new revision to current repository.
1406 1414
1407 1415 Revision information is gathered from the working directory,
1408 1416 match can be used to filter the committed files. If editor is
1409 1417 supplied, it is called to get a commit message.
1410 1418 """
1411 1419 if extra is None:
1412 1420 extra = {}
1413 1421
1414 1422 def fail(f, msg):
1415 1423 raise util.Abort('%s: %s' % (f, msg))
1416 1424
1417 1425 if not match:
1418 1426 match = matchmod.always(self.root, '')
1419 1427
1420 1428 if not force:
1421 1429 vdirs = []
1422 1430 match.explicitdir = vdirs.append
1423 1431 match.bad = fail
1424 1432
1425 1433 wlock = self.wlock()
1426 1434 try:
1427 1435 wctx = self[None]
1428 1436 merge = len(wctx.parents()) > 1
1429 1437
1430 1438 if not force and merge and match.ispartial():
1431 1439 raise util.Abort(_('cannot partially commit a merge '
1432 1440 '(do not specify files or patterns)'))
1433 1441
1434 1442 status = self.status(match=match, clean=force)
1435 1443 if force:
1436 1444 status.modified.extend(status.clean) # mq may commit clean files
1437 1445
1438 1446 # check subrepos
1439 1447 subs = []
1440 1448 commitsubs = set()
1441 1449 newstate = wctx.substate.copy()
1442 1450 # only manage subrepos and .hgsubstate if .hgsub is present
1443 1451 if '.hgsub' in wctx:
1444 1452 # we'll decide whether to track this ourselves, thanks
1445 1453 for c in status.modified, status.added, status.removed:
1446 1454 if '.hgsubstate' in c:
1447 1455 c.remove('.hgsubstate')
1448 1456
1449 1457 # compare current state to last committed state
1450 1458 # build new substate based on last committed state
1451 1459 oldstate = wctx.p1().substate
1452 1460 for s in sorted(newstate.keys()):
1453 1461 if not match(s):
1454 1462 # ignore working copy, use old state if present
1455 1463 if s in oldstate:
1456 1464 newstate[s] = oldstate[s]
1457 1465 continue
1458 1466 if not force:
1459 1467 raise util.Abort(
1460 1468 _("commit with new subrepo %s excluded") % s)
1461 1469 dirtyreason = wctx.sub(s).dirtyreason(True)
1462 1470 if dirtyreason:
1463 1471 if not self.ui.configbool('ui', 'commitsubrepos'):
1464 1472 raise util.Abort(dirtyreason,
1465 1473 hint=_("use --subrepos for recursive commit"))
1466 1474 subs.append(s)
1467 1475 commitsubs.add(s)
1468 1476 else:
1469 1477 bs = wctx.sub(s).basestate()
1470 1478 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1471 1479 if oldstate.get(s, (None, None, None))[1] != bs:
1472 1480 subs.append(s)
1473 1481
1474 1482 # check for removed subrepos
1475 1483 for p in wctx.parents():
1476 1484 r = [s for s in p.substate if s not in newstate]
1477 1485 subs += [s for s in r if match(s)]
1478 1486 if subs:
1479 1487 if (not match('.hgsub') and
1480 1488 '.hgsub' in (wctx.modified() + wctx.added())):
1481 1489 raise util.Abort(
1482 1490 _("can't commit subrepos without .hgsub"))
1483 1491 status.modified.insert(0, '.hgsubstate')
1484 1492
1485 1493 elif '.hgsub' in status.removed:
1486 1494 # clean up .hgsubstate when .hgsub is removed
1487 1495 if ('.hgsubstate' in wctx and
1488 1496 '.hgsubstate' not in (status.modified + status.added +
1489 1497 status.removed)):
1490 1498 status.removed.insert(0, '.hgsubstate')
1491 1499
1492 1500 # make sure all explicit patterns are matched
1493 1501 if not force and (match.isexact() or match.prefix()):
1494 1502 matched = set(status.modified + status.added + status.removed)
1495 1503
1496 1504 for f in match.files():
1497 1505 f = self.dirstate.normalize(f)
1498 1506 if f == '.' or f in matched or f in wctx.substate:
1499 1507 continue
1500 1508 if f in status.deleted:
1501 1509 fail(f, _('file not found!'))
1502 1510 if f in vdirs: # visited directory
1503 1511 d = f + '/'
1504 1512 for mf in matched:
1505 1513 if mf.startswith(d):
1506 1514 break
1507 1515 else:
1508 1516 fail(f, _("no match under directory!"))
1509 1517 elif f not in self.dirstate:
1510 1518 fail(f, _("file not tracked!"))
1511 1519
1512 1520 cctx = context.workingcommitctx(self, status,
1513 1521 text, user, date, extra)
1514 1522
1515 1523 # internal config: ui.allowemptycommit
1516 1524 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1517 1525 or extra.get('close') or merge or cctx.files()
1518 1526 or self.ui.configbool('ui', 'allowemptycommit'))
1519 1527 if not allowemptycommit:
1520 1528 return None
1521 1529
1522 1530 if merge and cctx.deleted():
1523 1531 raise util.Abort(_("cannot commit merge with missing files"))
1524 1532
1525 1533 ms = mergemod.mergestate(self)
1526 1534 for f in status.modified:
1527 1535 if f in ms and ms[f] == 'u':
1528 1536 raise util.Abort(_('unresolved merge conflicts '
1529 1537 '(see "hg help resolve")'))
1530 1538
1531 1539 if editor:
1532 1540 cctx._text = editor(self, cctx, subs)
1533 1541 edited = (text != cctx._text)
1534 1542
1535 1543 # Save commit message in case this transaction gets rolled back
1536 1544 # (e.g. by a pretxncommit hook). Leave the content alone on
1537 1545 # the assumption that the user will use the same editor again.
1538 1546 msgfn = self.savecommitmessage(cctx._text)
1539 1547
1540 1548 # commit subs and write new state
1541 1549 if subs:
1542 1550 for s in sorted(commitsubs):
1543 1551 sub = wctx.sub(s)
1544 1552 self.ui.status(_('committing subrepository %s\n') %
1545 1553 subrepo.subrelpath(sub))
1546 1554 sr = sub.commit(cctx._text, user, date)
1547 1555 newstate[s] = (newstate[s][0], sr)
1548 1556 subrepo.writestate(self, newstate)
1549 1557
1550 1558 p1, p2 = self.dirstate.parents()
1551 1559 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1552 1560 try:
1553 1561 self.hook("precommit", throw=True, parent1=hookp1,
1554 1562 parent2=hookp2)
1555 1563 ret = self.commitctx(cctx, True)
1556 1564 except: # re-raises
1557 1565 if edited:
1558 1566 self.ui.write(
1559 1567 _('note: commit message saved in %s\n') % msgfn)
1560 1568 raise
1561 1569
1562 1570 # update bookmarks, dirstate and mergestate
1563 1571 bookmarks.update(self, [p1, p2], ret)
1564 1572 cctx.markcommitted(ret)
1565 1573 ms.reset()
1566 1574 finally:
1567 1575 wlock.release()
1568 1576
1569 1577 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1570 1578 # hack for command that use a temporary commit (eg: histedit)
1571 1579 # temporary commit got stripped before hook release
1572 1580 if self.changelog.hasnode(ret):
1573 1581 self.hook("commit", node=node, parent1=parent1,
1574 1582 parent2=parent2)
1575 1583 self._afterlock(commithook)
1576 1584 return ret
1577 1585
1578 1586 @unfilteredmethod
1579 1587 def commitctx(self, ctx, error=False):
1580 1588 """Add a new revision to current repository.
1581 1589 Revision information is passed via the context argument.
1582 1590 """
1583 1591
1584 1592 tr = None
1585 1593 p1, p2 = ctx.p1(), ctx.p2()
1586 1594 user = ctx.user()
1587 1595
1588 1596 lock = self.lock()
1589 1597 try:
1590 1598 tr = self.transaction("commit")
1591 1599 trp = weakref.proxy(tr)
1592 1600
1593 1601 if ctx.files():
1594 1602 m1 = p1.manifest()
1595 1603 m2 = p2.manifest()
1596 1604 m = m1.copy()
1597 1605
1598 1606 # check in files
1599 1607 added = []
1600 1608 changed = []
1601 1609 removed = list(ctx.removed())
1602 1610 linkrev = len(self)
1603 1611 self.ui.note(_("committing files:\n"))
1604 1612 for f in sorted(ctx.modified() + ctx.added()):
1605 1613 self.ui.note(f + "\n")
1606 1614 try:
1607 1615 fctx = ctx[f]
1608 1616 if fctx is None:
1609 1617 removed.append(f)
1610 1618 else:
1611 1619 added.append(f)
1612 1620 m[f] = self._filecommit(fctx, m1, m2, linkrev,
1613 1621 trp, changed)
1614 1622 m.setflag(f, fctx.flags())
1615 1623 except OSError as inst:
1616 1624 self.ui.warn(_("trouble committing %s!\n") % f)
1617 1625 raise
1618 1626 except IOError as inst:
1619 1627 errcode = getattr(inst, 'errno', errno.ENOENT)
1620 1628 if error or errcode and errcode != errno.ENOENT:
1621 1629 self.ui.warn(_("trouble committing %s!\n") % f)
1622 1630 raise
1623 1631
1624 1632 # update manifest
1625 1633 self.ui.note(_("committing manifest\n"))
1626 1634 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1627 1635 drop = [f for f in removed if f in m]
1628 1636 for f in drop:
1629 1637 del m[f]
1630 1638 mn = self.manifest.add(m, trp, linkrev,
1631 1639 p1.manifestnode(), p2.manifestnode(),
1632 1640 added, drop)
1633 1641 files = changed + removed
1634 1642 else:
1635 1643 mn = p1.manifestnode()
1636 1644 files = []
1637 1645
1638 1646 # update changelog
1639 1647 self.ui.note(_("committing changelog\n"))
1640 1648 self.changelog.delayupdate(tr)
1641 1649 n = self.changelog.add(mn, files, ctx.description(),
1642 1650 trp, p1.node(), p2.node(),
1643 1651 user, ctx.date(), ctx.extra().copy())
1644 1652 p = lambda: tr.writepending() and self.root or ""
1645 1653 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1646 1654 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1647 1655 parent2=xp2, pending=p)
1648 1656 # set the new commit is proper phase
1649 1657 targetphase = subrepo.newcommitphase(self.ui, ctx)
1650 1658 if targetphase:
1651 1659 # retract boundary do not alter parent changeset.
1652 1660 # if a parent have higher the resulting phase will
1653 1661 # be compliant anyway
1654 1662 #
1655 1663 # if minimal phase was 0 we don't need to retract anything
1656 1664 phases.retractboundary(self, tr, targetphase, [n])
1657 1665 tr.close()
1658 1666 branchmap.updatecache(self.filtered('served'))
1659 1667 return n
1660 1668 finally:
1661 1669 if tr:
1662 1670 tr.release()
1663 1671 lock.release()
1664 1672
1665 1673 @unfilteredmethod
1666 1674 def destroying(self):
1667 1675 '''Inform the repository that nodes are about to be destroyed.
1668 1676 Intended for use by strip and rollback, so there's a common
1669 1677 place for anything that has to be done before destroying history.
1670 1678
1671 1679 This is mostly useful for saving state that is in memory and waiting
1672 1680 to be flushed when the current lock is released. Because a call to
1673 1681 destroyed is imminent, the repo will be invalidated causing those
1674 1682 changes to stay in memory (waiting for the next unlock), or vanish
1675 1683 completely.
1676 1684 '''
1677 1685 # When using the same lock to commit and strip, the phasecache is left
1678 1686 # dirty after committing. Then when we strip, the repo is invalidated,
1679 1687 # causing those changes to disappear.
1680 1688 if '_phasecache' in vars(self):
1681 1689 self._phasecache.write()
1682 1690
1683 1691 @unfilteredmethod
1684 1692 def destroyed(self):
1685 1693 '''Inform the repository that nodes have been destroyed.
1686 1694 Intended for use by strip and rollback, so there's a common
1687 1695 place for anything that has to be done after destroying history.
1688 1696 '''
1689 1697 # When one tries to:
1690 1698 # 1) destroy nodes thus calling this method (e.g. strip)
1691 1699 # 2) use phasecache somewhere (e.g. commit)
1692 1700 #
1693 1701 # then 2) will fail because the phasecache contains nodes that were
1694 1702 # removed. We can either remove phasecache from the filecache,
1695 1703 # causing it to reload next time it is accessed, or simply filter
1696 1704 # the removed nodes now and write the updated cache.
1697 1705 self._phasecache.filterunknown(self)
1698 1706 self._phasecache.write()
1699 1707
1700 1708 # update the 'served' branch cache to help read only server process
1701 1709 # Thanks to branchcache collaboration this is done from the nearest
1702 1710 # filtered subset and it is expected to be fast.
1703 1711 branchmap.updatecache(self.filtered('served'))
1704 1712
1705 1713 # Ensure the persistent tag cache is updated. Doing it now
1706 1714 # means that the tag cache only has to worry about destroyed
1707 1715 # heads immediately after a strip/rollback. That in turn
1708 1716 # guarantees that "cachetip == currenttip" (comparing both rev
1709 1717 # and node) always means no nodes have been added or destroyed.
1710 1718
1711 1719 # XXX this is suboptimal when qrefresh'ing: we strip the current
1712 1720 # head, refresh the tag cache, then immediately add a new head.
1713 1721 # But I think doing it this way is necessary for the "instant
1714 1722 # tag cache retrieval" case to work.
1715 1723 self.invalidate()
1716 1724
1717 1725 def walk(self, match, node=None):
1718 1726 '''
1719 1727 walk recursively through the directory tree or a given
1720 1728 changeset, finding all files matched by the match
1721 1729 function
1722 1730 '''
1723 1731 return self[node].walk(match)
1724 1732
1725 1733 def status(self, node1='.', node2=None, match=None,
1726 1734 ignored=False, clean=False, unknown=False,
1727 1735 listsubrepos=False):
1728 1736 '''a convenience method that calls node1.status(node2)'''
1729 1737 return self[node1].status(node2, match, ignored, clean, unknown,
1730 1738 listsubrepos)
1731 1739
1732 1740 def heads(self, start=None):
1733 1741 heads = self.changelog.heads(start)
1734 1742 # sort the output in rev descending order
1735 1743 return sorted(heads, key=self.changelog.rev, reverse=True)
1736 1744
1737 1745 def branchheads(self, branch=None, start=None, closed=False):
1738 1746 '''return a (possibly filtered) list of heads for the given branch
1739 1747
1740 1748 Heads are returned in topological order, from newest to oldest.
1741 1749 If branch is None, use the dirstate branch.
1742 1750 If start is not None, return only heads reachable from start.
1743 1751 If closed is True, return heads that are marked as closed as well.
1744 1752 '''
1745 1753 if branch is None:
1746 1754 branch = self[None].branch()
1747 1755 branches = self.branchmap()
1748 1756 if branch not in branches:
1749 1757 return []
1750 1758 # the cache returns heads ordered lowest to highest
1751 1759 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1752 1760 if start is not None:
1753 1761 # filter out the heads that cannot be reached from startrev
1754 1762 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1755 1763 bheads = [h for h in bheads if h in fbheads]
1756 1764 return bheads
1757 1765
1758 1766 def branches(self, nodes):
1759 1767 if not nodes:
1760 1768 nodes = [self.changelog.tip()]
1761 1769 b = []
1762 1770 for n in nodes:
1763 1771 t = n
1764 1772 while True:
1765 1773 p = self.changelog.parents(n)
1766 1774 if p[1] != nullid or p[0] == nullid:
1767 1775 b.append((t, n, p[0], p[1]))
1768 1776 break
1769 1777 n = p[0]
1770 1778 return b
1771 1779
1772 1780 def between(self, pairs):
1773 1781 r = []
1774 1782
1775 1783 for top, bottom in pairs:
1776 1784 n, l, i = top, [], 0
1777 1785 f = 1
1778 1786
1779 1787 while n != bottom and n != nullid:
1780 1788 p = self.changelog.parents(n)[0]
1781 1789 if i == f:
1782 1790 l.append(n)
1783 1791 f = f * 2
1784 1792 n = p
1785 1793 i += 1
1786 1794
1787 1795 r.append(l)
1788 1796
1789 1797 return r
1790 1798
1791 1799 def checkpush(self, pushop):
1792 1800 """Extensions can override this function if additional checks have
1793 1801 to be performed before pushing, or call it if they override push
1794 1802 command.
1795 1803 """
1796 1804 pass
1797 1805
1798 1806 @unfilteredpropertycache
1799 1807 def prepushoutgoinghooks(self):
1800 1808 """Return util.hooks consists of "(repo, remote, outgoing)"
1801 1809 functions, which are called before pushing changesets.
1802 1810 """
1803 1811 return util.hooks()
1804 1812
1805 1813 def clone(self, remote, heads=[], stream=None):
1806 1814 '''clone remote repository.
1807 1815
1808 1816 keyword arguments:
1809 1817 heads: list of revs to clone (forces use of pull)
1810 1818 stream: use streaming clone if possible'''
1811 1819 # internal config: ui.quietbookmarkmove
1812 1820 quiet = self.ui.backupconfig('ui', 'quietbookmarkmove')
1813 1821 try:
1814 1822 self.ui.setconfig('ui', 'quietbookmarkmove', True, 'clone')
1815 1823 pullop = exchange.pull(self, remote, heads,
1816 1824 streamclonerequested=stream)
1817 1825 return pullop.cgresult
1818 1826 finally:
1819 1827 self.ui.restoreconfig(quiet)
1820 1828
1821 1829 def pushkey(self, namespace, key, old, new):
1822 1830 try:
1823 1831 tr = self.currenttransaction()
1824 1832 hookargs = {}
1825 1833 if tr is not None:
1826 1834 hookargs.update(tr.hookargs)
1827 1835 pending = lambda: tr.writepending() and self.root or ""
1828 1836 hookargs['pending'] = pending
1829 1837 hookargs['namespace'] = namespace
1830 1838 hookargs['key'] = key
1831 1839 hookargs['old'] = old
1832 1840 hookargs['new'] = new
1833 1841 self.hook('prepushkey', throw=True, **hookargs)
1834 1842 except error.HookAbort as exc:
1835 1843 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
1836 1844 if exc.hint:
1837 1845 self.ui.write_err(_("(%s)\n") % exc.hint)
1838 1846 return False
1839 1847 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
1840 1848 ret = pushkey.push(self, namespace, key, old, new)
1841 1849 def runhook():
1842 1850 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
1843 1851 ret=ret)
1844 1852 self._afterlock(runhook)
1845 1853 return ret
1846 1854
1847 1855 def listkeys(self, namespace):
1848 1856 self.hook('prelistkeys', throw=True, namespace=namespace)
1849 1857 self.ui.debug('listing keys for "%s"\n' % namespace)
1850 1858 values = pushkey.list(self, namespace)
1851 1859 self.hook('listkeys', namespace=namespace, values=values)
1852 1860 return values
1853 1861
1854 1862 def debugwireargs(self, one, two, three=None, four=None, five=None):
1855 1863 '''used to test argument passing over the wire'''
1856 1864 return "%s %s %s %s %s" % (one, two, three, four, five)
1857 1865
1858 1866 def savecommitmessage(self, text):
1859 1867 fp = self.vfs('last-message.txt', 'wb')
1860 1868 try:
1861 1869 fp.write(text)
1862 1870 finally:
1863 1871 fp.close()
1864 1872 return self.pathto(fp.name[len(self.root) + 1:])
1865 1873
1866 1874 # used to avoid circular references so destructors work
1867 1875 def aftertrans(files):
1868 1876 renamefiles = [tuple(t) for t in files]
1869 1877 def a():
1870 1878 for vfs, src, dest in renamefiles:
1871 1879 try:
1872 1880 vfs.rename(src, dest)
1873 1881 except OSError: # journal file does not yet exist
1874 1882 pass
1875 1883 return a
1876 1884
1877 1885 def undoname(fn):
1878 1886 base, name = os.path.split(fn)
1879 1887 assert name.startswith('journal')
1880 1888 return os.path.join(base, name.replace('journal', 'undo', 1))
1881 1889
1882 1890 def instance(ui, path, create):
1883 1891 return localrepository(ui, util.urllocalpath(path), create)
1884 1892
1885 1893 def islocal(path):
1886 1894 return True
@@ -1,271 +1,271
1 1 from __future__ import absolute_import
2 2
3 3 import copy
4 4 import os
5 5 import silenttestrunner
6 6 import tempfile
7 7 import types
8 8 import unittest
9 9
10 10 from mercurial import (
11 11 error,
12 12 lock,
13 13 scmutil,
14 14 )
15 15
16 16 testlockname = 'testlock'
17 17
18 18 # work around http://bugs.python.org/issue1515
19 19 if types.MethodType not in copy._deepcopy_dispatch:
20 20 def _deepcopy_method(x, memo):
21 21 return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class)
22 22 copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
23 23
24 24 class lockwrapper(lock.lock):
25 25 def __init__(self, pidoffset, *args, **kwargs):
26 26 # lock.lock.__init__() calls lock(), so the pidoffset assignment needs
27 27 # to be earlier
28 28 self._pidoffset = pidoffset
29 29 super(lockwrapper, self).__init__(*args, **kwargs)
30 30 def _getpid(self):
31 31 return os.getpid() + self._pidoffset
32 32
33 33 class teststate(object):
34 34 def __init__(self, testcase, dir, pidoffset=0):
35 35 self._testcase = testcase
36 36 self._acquirecalled = False
37 37 self._releasecalled = False
38 38 self._postreleasecalled = False
39 39 self.vfs = scmutil.vfs(dir, audit=False)
40 40 self._pidoffset = pidoffset
41 41
42 42 def makelock(self, *args, **kwargs):
43 43 l = lockwrapper(self._pidoffset, self.vfs, testlockname,
44 44 releasefn=self.releasefn, acquirefn=self.acquirefn,
45 45 *args, **kwargs)
46 46 l.postrelease.append(self.postreleasefn)
47 47 return l
48 48
49 49 def acquirefn(self):
50 50 self._acquirecalled = True
51 51
52 52 def releasefn(self):
53 53 self._releasecalled = True
54 54
55 55 def postreleasefn(self):
56 56 self._postreleasecalled = True
57 57
58 58 def assertacquirecalled(self, called):
59 59 self._testcase.assertEqual(
60 60 self._acquirecalled, called,
61 61 'expected acquire to be %s but was actually %s' % (
62 62 self._tocalled(called),
63 63 self._tocalled(self._acquirecalled),
64 64 ))
65 65
66 66 def resetacquirefn(self):
67 67 self._acquirecalled = False
68 68
69 69 def assertreleasecalled(self, called):
70 70 self._testcase.assertEqual(
71 71 self._releasecalled, called,
72 72 'expected release to be %s but was actually %s' % (
73 73 self._tocalled(called),
74 74 self._tocalled(self._releasecalled),
75 75 ))
76 76
77 77 def assertpostreleasecalled(self, called):
78 78 self._testcase.assertEqual(
79 79 self._postreleasecalled, called,
80 80 'expected postrelease to be %s but was actually %s' % (
81 81 self._tocalled(called),
82 82 self._tocalled(self._postreleasecalled),
83 83 ))
84 84
85 85 def assertlockexists(self, exists):
86 86 actual = self.vfs.lexists(testlockname)
87 87 self._testcase.assertEqual(
88 88 actual, exists,
89 89 'expected lock to %s but actually did %s' % (
90 90 self._toexists(exists),
91 91 self._toexists(actual),
92 92 ))
93 93
94 94 def _tocalled(self, called):
95 95 if called:
96 96 return 'called'
97 97 else:
98 98 return 'not called'
99 99
100 100 def _toexists(self, exists):
101 101 if exists:
102 102 return 'exist'
103 103 else:
104 104 return 'not exist'
105 105
106 106 class testlock(unittest.TestCase):
107 107 def testlock(self):
108 108 state = teststate(self, tempfile.mkdtemp(dir=os.getcwd()))
109 109 lock = state.makelock()
110 110 state.assertacquirecalled(True)
111 111 lock.release()
112 112 state.assertreleasecalled(True)
113 113 state.assertpostreleasecalled(True)
114 114 state.assertlockexists(False)
115 115
116 116 def testrecursivelock(self):
117 117 state = teststate(self, tempfile.mkdtemp(dir=os.getcwd()))
118 118 lock = state.makelock()
119 119 state.assertacquirecalled(True)
120 120
121 121 state.resetacquirefn()
122 122 lock.lock()
123 123 # recursive lock should not call acquirefn again
124 124 state.assertacquirecalled(False)
125 125
126 126 lock.release() # brings lock refcount down from 2 to 1
127 127 state.assertreleasecalled(False)
128 128 state.assertpostreleasecalled(False)
129 129 state.assertlockexists(True)
130 130
131 131 lock.release() # releases the lock
132 132 state.assertreleasecalled(True)
133 133 state.assertpostreleasecalled(True)
134 134 state.assertlockexists(False)
135 135
136 136 def testlockfork(self):
137 137 state = teststate(self, tempfile.mkdtemp(dir=os.getcwd()))
138 138 lock = state.makelock()
139 139 state.assertacquirecalled(True)
140 140
141 141 # fake a fork
142 142 forklock = copy.deepcopy(lock)
143 143 forklock._pidoffset = 1
144 144 forklock.release()
145 145 state.assertreleasecalled(False)
146 146 state.assertpostreleasecalled(False)
147 147 state.assertlockexists(True)
148 148
149 149 # release the actual lock
150 150 lock.release()
151 151 state.assertreleasecalled(True)
152 152 state.assertpostreleasecalled(True)
153 153 state.assertlockexists(False)
154 154
155 155 def testinheritlock(self):
156 156 d = tempfile.mkdtemp(dir=os.getcwd())
157 157 parentstate = teststate(self, d)
158 158 parentlock = parentstate.makelock()
159 159 parentstate.assertacquirecalled(True)
160 160
161 161 # set up lock inheritance
162 162 with parentlock.inherit() as lockname:
163 163 parentstate.assertreleasecalled(True)
164 164 parentstate.assertpostreleasecalled(False)
165 165 parentstate.assertlockexists(True)
166 166
167 167 childstate = teststate(self, d, pidoffset=1)
168 168 childlock = childstate.makelock(parentlock=lockname)
169 169 childstate.assertacquirecalled(True)
170 170
171 171 childlock.release()
172 172 childstate.assertreleasecalled(True)
173 173 childstate.assertpostreleasecalled(False)
174 174 childstate.assertlockexists(True)
175 175
176 176 parentstate.resetacquirefn()
177 177
178 178 parentstate.assertacquirecalled(True)
179 179
180 180 parentlock.release()
181 181 parentstate.assertreleasecalled(True)
182 182 parentstate.assertpostreleasecalled(True)
183 183 parentstate.assertlockexists(False)
184 184
185 185 def testmultilock(self):
186 186 d = tempfile.mkdtemp(dir=os.getcwd())
187 187 state0 = teststate(self, d)
188 188 lock0 = state0.makelock()
189 189 state0.assertacquirecalled(True)
190 190
191 191 with lock0.inherit() as lock0name:
192 192 state0.assertreleasecalled(True)
193 193 state0.assertpostreleasecalled(False)
194 194 state0.assertlockexists(True)
195 195
196 196 state1 = teststate(self, d, pidoffset=1)
197 197 lock1 = state1.makelock(parentlock=lock0name)
198 198 state1.assertacquirecalled(True)
199 199
200 200 # from within lock1, acquire another lock
201 201 with lock1.inherit() as lock1name:
202 202 # since the file on disk is lock0's this should have the same
203 203 # name
204 204 self.assertEqual(lock0name, lock1name)
205 205
206 206 state2 = teststate(self, d, pidoffset=2)
207 207 lock2 = state2.makelock(parentlock=lock1name)
208 208 state2.assertacquirecalled(True)
209 209
210 210 lock2.release()
211 211 state2.assertreleasecalled(True)
212 212 state2.assertpostreleasecalled(False)
213 213 state2.assertlockexists(True)
214 214
215 215 state1.resetacquirefn()
216 216
217 217 state1.assertacquirecalled(True)
218 218
219 219 lock1.release()
220 220 state1.assertreleasecalled(True)
221 221 state1.assertpostreleasecalled(False)
222 222 state1.assertlockexists(True)
223 223
224 224 lock0.release()
225 225
226 226 def testinheritlockfork(self):
227 227 d = tempfile.mkdtemp(dir=os.getcwd())
228 228 parentstate = teststate(self, d)
229 229 parentlock = parentstate.makelock()
230 230 parentstate.assertacquirecalled(True)
231 231
232 232 # set up lock inheritance
233 233 with parentlock.inherit() as lockname:
234 234 childstate = teststate(self, d, pidoffset=1)
235 235 childlock = childstate.makelock(parentlock=lockname)
236 236 childstate.assertacquirecalled(True)
237 237
238 238 # fork the child lock
239 239 forkchildlock = copy.deepcopy(childlock)
240 240 forkchildlock._pidoffset += 1
241 241 forkchildlock.release()
242 242 childstate.assertreleasecalled(False)
243 243 childstate.assertpostreleasecalled(False)
244 244 childstate.assertlockexists(True)
245 245
246 246 # release the child lock
247 247 childlock.release()
248 248 childstate.assertreleasecalled(True)
249 249 childstate.assertpostreleasecalled(False)
250 250 childstate.assertlockexists(True)
251 251
252 252 parentlock.release()
253 253
254 254 def testinheritcheck(self):
255 255 d = tempfile.mkdtemp(dir=os.getcwd())
256 256 state = teststate(self, d)
257 257 def check():
258 258 raise error.LockInheritanceContractViolation('check failed')
259 259 lock = state.makelock(inheritchecker=check)
260 260 state.assertacquirecalled(True)
261 261
262 262 def tryinherit():
263 with lock.inherit() as lockname:
263 with lock.inherit():
264 264 pass
265 265
266 266 self.assertRaises(error.LockInheritanceContractViolation, tryinherit)
267 267
268 268 lock.release()
269 269
270 270 if __name__ == '__main__':
271 271 silenttestrunner.main(__name__)
General Comments 0
You need to be logged in to leave comments. Login now