##// END OF EJS Templates
changegroupsubset: simplify prune...
Matt Mackall -
r13708:ce9b3043 default
parent child Browse files
Show More
@@ -1,1959 +1,1954 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
8 8 from node import bin, hex, nullid, nullrev, short
9 9 from i18n import _
10 10 import repo, changegroup, subrepo, discovery, pushkey
11 11 import changelog, dirstate, filelog, manifest, context, bookmarks
12 12 import lock, transaction, store, encoding
13 13 import util, extensions, hook, error
14 14 import match as matchmod
15 15 import merge as mergemod
16 16 import tags as tagsmod
17 17 import url as urlmod
18 18 from lock import release
19 19 import weakref, errno, os, time, inspect
20 20 propertycache = util.propertycache
21 21
22 22 class localrepository(repo.repository):
23 23 capabilities = set(('lookup', 'changegroupsubset', 'branchmap', 'pushkey'))
24 24 supportedformats = set(('revlogv1', 'parentdelta'))
25 25 supported = supportedformats | set(('store', 'fncache', 'shared',
26 26 'dotencode'))
27 27
28 28 def __init__(self, baseui, path=None, create=0):
29 29 repo.repository.__init__(self)
30 30 self.root = os.path.realpath(util.expandpath(path))
31 31 self.path = os.path.join(self.root, ".hg")
32 32 self.origroot = path
33 33 self.auditor = util.path_auditor(self.root, self._checknested)
34 34 self.opener = util.opener(self.path)
35 35 self.wopener = util.opener(self.root)
36 36 self.baseui = baseui
37 37 self.ui = baseui.copy()
38 38
39 39 try:
40 40 self.ui.readconfig(self.join("hgrc"), self.root)
41 41 extensions.loadall(self.ui)
42 42 except IOError:
43 43 pass
44 44
45 45 if not os.path.isdir(self.path):
46 46 if create:
47 47 if not os.path.exists(path):
48 48 util.makedirs(path)
49 49 os.mkdir(self.path)
50 50 requirements = ["revlogv1"]
51 51 if self.ui.configbool('format', 'usestore', True):
52 52 os.mkdir(os.path.join(self.path, "store"))
53 53 requirements.append("store")
54 54 if self.ui.configbool('format', 'usefncache', True):
55 55 requirements.append("fncache")
56 56 if self.ui.configbool('format', 'dotencode', True):
57 57 requirements.append('dotencode')
58 58 # create an invalid changelog
59 59 self.opener("00changelog.i", "a").write(
60 60 '\0\0\0\2' # represents revlogv2
61 61 ' dummy changelog to prevent using the old repo layout'
62 62 )
63 63 if self.ui.configbool('format', 'parentdelta', False):
64 64 requirements.append("parentdelta")
65 65 else:
66 66 raise error.RepoError(_("repository %s not found") % path)
67 67 elif create:
68 68 raise error.RepoError(_("repository %s already exists") % path)
69 69 else:
70 70 # find requirements
71 71 requirements = set()
72 72 try:
73 73 requirements = set(self.opener("requires").read().splitlines())
74 74 except IOError, inst:
75 75 if inst.errno != errno.ENOENT:
76 76 raise
77 77 for r in requirements - self.supported:
78 78 raise error.RequirementError(
79 79 _("requirement '%s' not supported") % r)
80 80
81 81 self.sharedpath = self.path
82 82 try:
83 83 s = os.path.realpath(self.opener("sharedpath").read())
84 84 if not os.path.exists(s):
85 85 raise error.RepoError(
86 86 _('.hg/sharedpath points to nonexistent directory %s') % s)
87 87 self.sharedpath = s
88 88 except IOError, inst:
89 89 if inst.errno != errno.ENOENT:
90 90 raise
91 91
92 92 self.store = store.store(requirements, self.sharedpath, util.opener)
93 93 self.spath = self.store.path
94 94 self.sopener = self.store.opener
95 95 self.sjoin = self.store.join
96 96 self.opener.createmode = self.store.createmode
97 97 self._applyrequirements(requirements)
98 98 if create:
99 99 self._writerequirements()
100 100
101 101 # These two define the set of tags for this repository. _tags
102 102 # maps tag name to node; _tagtypes maps tag name to 'global' or
103 103 # 'local'. (Global tags are defined by .hgtags across all
104 104 # heads, and local tags are defined in .hg/localtags.) They
105 105 # constitute the in-memory cache of tags.
106 106 self._tags = None
107 107 self._tagtypes = None
108 108
109 109 self._branchcache = None
110 110 self._branchcachetip = None
111 111 self.nodetagscache = None
112 112 self.filterpats = {}
113 113 self._datafilters = {}
114 114 self._transref = self._lockref = self._wlockref = None
115 115
116 116 def _applyrequirements(self, requirements):
117 117 self.requirements = requirements
118 118 self.sopener.options = {}
119 119 if 'parentdelta' in requirements:
120 120 self.sopener.options['parentdelta'] = 1
121 121
122 122 def _writerequirements(self):
123 123 reqfile = self.opener("requires", "w")
124 124 for r in self.requirements:
125 125 reqfile.write("%s\n" % r)
126 126 reqfile.close()
127 127
128 128 def _checknested(self, path):
129 129 """Determine if path is a legal nested repository."""
130 130 if not path.startswith(self.root):
131 131 return False
132 132 subpath = path[len(self.root) + 1:]
133 133
134 134 # XXX: Checking against the current working copy is wrong in
135 135 # the sense that it can reject things like
136 136 #
137 137 # $ hg cat -r 10 sub/x.txt
138 138 #
139 139 # if sub/ is no longer a subrepository in the working copy
140 140 # parent revision.
141 141 #
142 142 # However, it can of course also allow things that would have
143 143 # been rejected before, such as the above cat command if sub/
144 144 # is a subrepository now, but was a normal directory before.
145 145 # The old path auditor would have rejected by mistake since it
146 146 # panics when it sees sub/.hg/.
147 147 #
148 148 # All in all, checking against the working copy seems sensible
149 149 # since we want to prevent access to nested repositories on
150 150 # the filesystem *now*.
151 151 ctx = self[None]
152 152 parts = util.splitpath(subpath)
153 153 while parts:
154 154 prefix = os.sep.join(parts)
155 155 if prefix in ctx.substate:
156 156 if prefix == subpath:
157 157 return True
158 158 else:
159 159 sub = ctx.sub(prefix)
160 160 return sub.checknested(subpath[len(prefix) + 1:])
161 161 else:
162 162 parts.pop()
163 163 return False
164 164
165 165 @util.propertycache
166 166 def _bookmarks(self):
167 167 return bookmarks.read(self)
168 168
169 169 @util.propertycache
170 170 def _bookmarkcurrent(self):
171 171 return bookmarks.readcurrent(self)
172 172
173 173 @propertycache
174 174 def changelog(self):
175 175 c = changelog.changelog(self.sopener)
176 176 if 'HG_PENDING' in os.environ:
177 177 p = os.environ['HG_PENDING']
178 178 if p.startswith(self.root):
179 179 c.readpending('00changelog.i.a')
180 180 self.sopener.options['defversion'] = c.version
181 181 return c
182 182
183 183 @propertycache
184 184 def manifest(self):
185 185 return manifest.manifest(self.sopener)
186 186
187 187 @propertycache
188 188 def dirstate(self):
189 189 warned = [0]
190 190 def validate(node):
191 191 try:
192 192 r = self.changelog.rev(node)
193 193 return node
194 194 except error.LookupError:
195 195 if not warned[0]:
196 196 warned[0] = True
197 197 self.ui.warn(_("warning: ignoring unknown"
198 198 " working parent %s!\n") % short(node))
199 199 return nullid
200 200
201 201 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
202 202
203 203 def __getitem__(self, changeid):
204 204 if changeid is None:
205 205 return context.workingctx(self)
206 206 return context.changectx(self, changeid)
207 207
208 208 def __contains__(self, changeid):
209 209 try:
210 210 return bool(self.lookup(changeid))
211 211 except error.RepoLookupError:
212 212 return False
213 213
214 214 def __nonzero__(self):
215 215 return True
216 216
217 217 def __len__(self):
218 218 return len(self.changelog)
219 219
220 220 def __iter__(self):
221 221 for i in xrange(len(self)):
222 222 yield i
223 223
224 224 def url(self):
225 225 return 'file:' + self.root
226 226
227 227 def hook(self, name, throw=False, **args):
228 228 return hook.hook(self.ui, self, name, throw, **args)
229 229
230 230 tag_disallowed = ':\r\n'
231 231
232 232 def _tag(self, names, node, message, local, user, date, extra={}):
233 233 if isinstance(names, str):
234 234 allchars = names
235 235 names = (names,)
236 236 else:
237 237 allchars = ''.join(names)
238 238 for c in self.tag_disallowed:
239 239 if c in allchars:
240 240 raise util.Abort(_('%r cannot be used in a tag name') % c)
241 241
242 242 branches = self.branchmap()
243 243 for name in names:
244 244 self.hook('pretag', throw=True, node=hex(node), tag=name,
245 245 local=local)
246 246 if name in branches:
247 247 self.ui.warn(_("warning: tag %s conflicts with existing"
248 248 " branch name\n") % name)
249 249
250 250 def writetags(fp, names, munge, prevtags):
251 251 fp.seek(0, 2)
252 252 if prevtags and prevtags[-1] != '\n':
253 253 fp.write('\n')
254 254 for name in names:
255 255 m = munge and munge(name) or name
256 256 if self._tagtypes and name in self._tagtypes:
257 257 old = self._tags.get(name, nullid)
258 258 fp.write('%s %s\n' % (hex(old), m))
259 259 fp.write('%s %s\n' % (hex(node), m))
260 260 fp.close()
261 261
262 262 prevtags = ''
263 263 if local:
264 264 try:
265 265 fp = self.opener('localtags', 'r+')
266 266 except IOError:
267 267 fp = self.opener('localtags', 'a')
268 268 else:
269 269 prevtags = fp.read()
270 270
271 271 # local tags are stored in the current charset
272 272 writetags(fp, names, None, prevtags)
273 273 for name in names:
274 274 self.hook('tag', node=hex(node), tag=name, local=local)
275 275 return
276 276
277 277 try:
278 278 fp = self.wfile('.hgtags', 'rb+')
279 279 except IOError:
280 280 fp = self.wfile('.hgtags', 'ab')
281 281 else:
282 282 prevtags = fp.read()
283 283
284 284 # committed tags are stored in UTF-8
285 285 writetags(fp, names, encoding.fromlocal, prevtags)
286 286
287 287 fp.close()
288 288
289 289 if '.hgtags' not in self.dirstate:
290 290 self[None].add(['.hgtags'])
291 291
292 292 m = matchmod.exact(self.root, '', ['.hgtags'])
293 293 tagnode = self.commit(message, user, date, extra=extra, match=m)
294 294
295 295 for name in names:
296 296 self.hook('tag', node=hex(node), tag=name, local=local)
297 297
298 298 return tagnode
299 299
300 300 def tag(self, names, node, message, local, user, date):
301 301 '''tag a revision with one or more symbolic names.
302 302
303 303 names is a list of strings or, when adding a single tag, names may be a
304 304 string.
305 305
306 306 if local is True, the tags are stored in a per-repository file.
307 307 otherwise, they are stored in the .hgtags file, and a new
308 308 changeset is committed with the change.
309 309
310 310 keyword arguments:
311 311
312 312 local: whether to store tags in non-version-controlled file
313 313 (default False)
314 314
315 315 message: commit message to use if committing
316 316
317 317 user: name of user to use if committing
318 318
319 319 date: date tuple to use if committing'''
320 320
321 321 if not local:
322 322 for x in self.status()[:5]:
323 323 if '.hgtags' in x:
324 324 raise util.Abort(_('working copy of .hgtags is changed '
325 325 '(please commit .hgtags manually)'))
326 326
327 327 self.tags() # instantiate the cache
328 328 self._tag(names, node, message, local, user, date)
329 329
330 330 def tags(self):
331 331 '''return a mapping of tag to node'''
332 332 if self._tags is None:
333 333 (self._tags, self._tagtypes) = self._findtags()
334 334
335 335 return self._tags
336 336
337 337 def _findtags(self):
338 338 '''Do the hard work of finding tags. Return a pair of dicts
339 339 (tags, tagtypes) where tags maps tag name to node, and tagtypes
340 340 maps tag name to a string like \'global\' or \'local\'.
341 341 Subclasses or extensions are free to add their own tags, but
342 342 should be aware that the returned dicts will be retained for the
343 343 duration of the localrepo object.'''
344 344
345 345 # XXX what tagtype should subclasses/extensions use? Currently
346 346 # mq and bookmarks add tags, but do not set the tagtype at all.
347 347 # Should each extension invent its own tag type? Should there
348 348 # be one tagtype for all such "virtual" tags? Or is the status
349 349 # quo fine?
350 350
351 351 alltags = {} # map tag name to (node, hist)
352 352 tagtypes = {}
353 353
354 354 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
355 355 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
356 356
357 357 # Build the return dicts. Have to re-encode tag names because
358 358 # the tags module always uses UTF-8 (in order not to lose info
359 359 # writing to the cache), but the rest of Mercurial wants them in
360 360 # local encoding.
361 361 tags = {}
362 362 for (name, (node, hist)) in alltags.iteritems():
363 363 if node != nullid:
364 364 tags[encoding.tolocal(name)] = node
365 365 tags['tip'] = self.changelog.tip()
366 366 tagtypes = dict([(encoding.tolocal(name), value)
367 367 for (name, value) in tagtypes.iteritems()])
368 368 return (tags, tagtypes)
369 369
370 370 def tagtype(self, tagname):
371 371 '''
372 372 return the type of the given tag. result can be:
373 373
374 374 'local' : a local tag
375 375 'global' : a global tag
376 376 None : tag does not exist
377 377 '''
378 378
379 379 self.tags()
380 380
381 381 return self._tagtypes.get(tagname)
382 382
383 383 def tagslist(self):
384 384 '''return a list of tags ordered by revision'''
385 385 l = []
386 386 for t, n in self.tags().iteritems():
387 387 try:
388 388 r = self.changelog.rev(n)
389 389 except:
390 390 r = -2 # sort to the beginning of the list if unknown
391 391 l.append((r, t, n))
392 392 return [(t, n) for r, t, n in sorted(l)]
393 393
394 394 def nodetags(self, node):
395 395 '''return the tags associated with a node'''
396 396 if not self.nodetagscache:
397 397 self.nodetagscache = {}
398 398 for t, n in self.tags().iteritems():
399 399 self.nodetagscache.setdefault(n, []).append(t)
400 400 for tags in self.nodetagscache.itervalues():
401 401 tags.sort()
402 402 return self.nodetagscache.get(node, [])
403 403
404 404 def nodebookmarks(self, node):
405 405 marks = []
406 406 for bookmark, n in self._bookmarks.iteritems():
407 407 if n == node:
408 408 marks.append(bookmark)
409 409 return sorted(marks)
410 410
411 411 def _branchtags(self, partial, lrev):
412 412 # TODO: rename this function?
413 413 tiprev = len(self) - 1
414 414 if lrev != tiprev:
415 415 ctxgen = (self[r] for r in xrange(lrev + 1, tiprev + 1))
416 416 self._updatebranchcache(partial, ctxgen)
417 417 self._writebranchcache(partial, self.changelog.tip(), tiprev)
418 418
419 419 return partial
420 420
421 421 def updatebranchcache(self):
422 422 tip = self.changelog.tip()
423 423 if self._branchcache is not None and self._branchcachetip == tip:
424 424 return self._branchcache
425 425
426 426 oldtip = self._branchcachetip
427 427 self._branchcachetip = tip
428 428 if oldtip is None or oldtip not in self.changelog.nodemap:
429 429 partial, last, lrev = self._readbranchcache()
430 430 else:
431 431 lrev = self.changelog.rev(oldtip)
432 432 partial = self._branchcache
433 433
434 434 self._branchtags(partial, lrev)
435 435 # this private cache holds all heads (not just tips)
436 436 self._branchcache = partial
437 437
438 438 def branchmap(self):
439 439 '''returns a dictionary {branch: [branchheads]}'''
440 440 self.updatebranchcache()
441 441 return self._branchcache
442 442
443 443 def branchtags(self):
444 444 '''return a dict where branch names map to the tipmost head of
445 445 the branch, open heads come before closed'''
446 446 bt = {}
447 447 for bn, heads in self.branchmap().iteritems():
448 448 tip = heads[-1]
449 449 for h in reversed(heads):
450 450 if 'close' not in self.changelog.read(h)[5]:
451 451 tip = h
452 452 break
453 453 bt[bn] = tip
454 454 return bt
455 455
456 456 def _readbranchcache(self):
457 457 partial = {}
458 458 try:
459 459 f = self.opener("cache/branchheads")
460 460 lines = f.read().split('\n')
461 461 f.close()
462 462 except (IOError, OSError):
463 463 return {}, nullid, nullrev
464 464
465 465 try:
466 466 last, lrev = lines.pop(0).split(" ", 1)
467 467 last, lrev = bin(last), int(lrev)
468 468 if lrev >= len(self) or self[lrev].node() != last:
469 469 # invalidate the cache
470 470 raise ValueError('invalidating branch cache (tip differs)')
471 471 for l in lines:
472 472 if not l:
473 473 continue
474 474 node, label = l.split(" ", 1)
475 475 label = encoding.tolocal(label.strip())
476 476 partial.setdefault(label, []).append(bin(node))
477 477 except KeyboardInterrupt:
478 478 raise
479 479 except Exception, inst:
480 480 if self.ui.debugflag:
481 481 self.ui.warn(str(inst), '\n')
482 482 partial, last, lrev = {}, nullid, nullrev
483 483 return partial, last, lrev
484 484
485 485 def _writebranchcache(self, branches, tip, tiprev):
486 486 try:
487 487 f = self.opener("cache/branchheads", "w", atomictemp=True)
488 488 f.write("%s %s\n" % (hex(tip), tiprev))
489 489 for label, nodes in branches.iteritems():
490 490 for node in nodes:
491 491 f.write("%s %s\n" % (hex(node), encoding.fromlocal(label)))
492 492 f.rename()
493 493 except (IOError, OSError):
494 494 pass
495 495
496 496 def _updatebranchcache(self, partial, ctxgen):
497 497 # collect new branch entries
498 498 newbranches = {}
499 499 for c in ctxgen:
500 500 newbranches.setdefault(c.branch(), []).append(c.node())
501 501 # if older branchheads are reachable from new ones, they aren't
502 502 # really branchheads. Note checking parents is insufficient:
503 503 # 1 (branch a) -> 2 (branch b) -> 3 (branch a)
504 504 for branch, newnodes in newbranches.iteritems():
505 505 bheads = partial.setdefault(branch, [])
506 506 bheads.extend(newnodes)
507 507 if len(bheads) <= 1:
508 508 continue
509 509 # starting from tip means fewer passes over reachable
510 510 while newnodes:
511 511 latest = newnodes.pop()
512 512 if latest not in bheads:
513 513 continue
514 514 minbhrev = self[min([self[bh].rev() for bh in bheads])].node()
515 515 reachable = self.changelog.reachable(latest, minbhrev)
516 516 reachable.remove(latest)
517 517 bheads = [b for b in bheads if b not in reachable]
518 518 partial[branch] = bheads
519 519
520 520 def lookup(self, key):
521 521 if isinstance(key, int):
522 522 return self.changelog.node(key)
523 523 elif key == '.':
524 524 return self.dirstate.parents()[0]
525 525 elif key == 'null':
526 526 return nullid
527 527 elif key == 'tip':
528 528 return self.changelog.tip()
529 529 n = self.changelog._match(key)
530 530 if n:
531 531 return n
532 532 if key in self._bookmarks:
533 533 return self._bookmarks[key]
534 534 if key in self.tags():
535 535 return self.tags()[key]
536 536 if key in self.branchtags():
537 537 return self.branchtags()[key]
538 538 n = self.changelog._partialmatch(key)
539 539 if n:
540 540 return n
541 541
542 542 # can't find key, check if it might have come from damaged dirstate
543 543 if key in self.dirstate.parents():
544 544 raise error.Abort(_("working directory has unknown parent '%s'!")
545 545 % short(key))
546 546 try:
547 547 if len(key) == 20:
548 548 key = hex(key)
549 549 except:
550 550 pass
551 551 raise error.RepoLookupError(_("unknown revision '%s'") % key)
552 552
553 553 def lookupbranch(self, key, remote=None):
554 554 repo = remote or self
555 555 if key in repo.branchmap():
556 556 return key
557 557
558 558 repo = (remote and remote.local()) and remote or self
559 559 return repo[key].branch()
560 560
561 561 def local(self):
562 562 return True
563 563
564 564 def join(self, f):
565 565 return os.path.join(self.path, f)
566 566
567 567 def wjoin(self, f):
568 568 return os.path.join(self.root, f)
569 569
570 570 def file(self, f):
571 571 if f[0] == '/':
572 572 f = f[1:]
573 573 return filelog.filelog(self.sopener, f)
574 574
575 575 def changectx(self, changeid):
576 576 return self[changeid]
577 577
578 578 def parents(self, changeid=None):
579 579 '''get list of changectxs for parents of changeid'''
580 580 return self[changeid].parents()
581 581
582 582 def filectx(self, path, changeid=None, fileid=None):
583 583 """changeid can be a changeset revision, node, or tag.
584 584 fileid can be a file revision or node."""
585 585 return context.filectx(self, path, changeid, fileid)
586 586
587 587 def getcwd(self):
588 588 return self.dirstate.getcwd()
589 589
590 590 def pathto(self, f, cwd=None):
591 591 return self.dirstate.pathto(f, cwd)
592 592
593 593 def wfile(self, f, mode='r'):
594 594 return self.wopener(f, mode)
595 595
596 596 def _link(self, f):
597 597 return os.path.islink(self.wjoin(f))
598 598
599 599 def _loadfilter(self, filter):
600 600 if filter not in self.filterpats:
601 601 l = []
602 602 for pat, cmd in self.ui.configitems(filter):
603 603 if cmd == '!':
604 604 continue
605 605 mf = matchmod.match(self.root, '', [pat])
606 606 fn = None
607 607 params = cmd
608 608 for name, filterfn in self._datafilters.iteritems():
609 609 if cmd.startswith(name):
610 610 fn = filterfn
611 611 params = cmd[len(name):].lstrip()
612 612 break
613 613 if not fn:
614 614 fn = lambda s, c, **kwargs: util.filter(s, c)
615 615 # Wrap old filters not supporting keyword arguments
616 616 if not inspect.getargspec(fn)[2]:
617 617 oldfn = fn
618 618 fn = lambda s, c, **kwargs: oldfn(s, c)
619 619 l.append((mf, fn, params))
620 620 self.filterpats[filter] = l
621 621 return self.filterpats[filter]
622 622
623 623 def _filter(self, filterpats, filename, data):
624 624 for mf, fn, cmd in filterpats:
625 625 if mf(filename):
626 626 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
627 627 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
628 628 break
629 629
630 630 return data
631 631
632 632 @propertycache
633 633 def _encodefilterpats(self):
634 634 return self._loadfilter('encode')
635 635
636 636 @propertycache
637 637 def _decodefilterpats(self):
638 638 return self._loadfilter('decode')
639 639
640 640 def adddatafilter(self, name, filter):
641 641 self._datafilters[name] = filter
642 642
643 643 def wread(self, filename):
644 644 if self._link(filename):
645 645 data = os.readlink(self.wjoin(filename))
646 646 else:
647 647 data = self.wopener(filename, 'r').read()
648 648 return self._filter(self._encodefilterpats, filename, data)
649 649
650 650 def wwrite(self, filename, data, flags):
651 651 data = self._filter(self._decodefilterpats, filename, data)
652 652 if 'l' in flags:
653 653 self.wopener.symlink(data, filename)
654 654 else:
655 655 self.wopener(filename, 'w').write(data)
656 656 if 'x' in flags:
657 657 util.set_flags(self.wjoin(filename), False, True)
658 658
659 659 def wwritedata(self, filename, data):
660 660 return self._filter(self._decodefilterpats, filename, data)
661 661
662 662 def transaction(self, desc):
663 663 tr = self._transref and self._transref() or None
664 664 if tr and tr.running():
665 665 return tr.nest()
666 666
667 667 # abort here if the journal already exists
668 668 if os.path.exists(self.sjoin("journal")):
669 669 raise error.RepoError(
670 670 _("abandoned transaction found - run hg recover"))
671 671
672 672 # save dirstate for rollback
673 673 try:
674 674 ds = self.opener("dirstate").read()
675 675 except IOError:
676 676 ds = ""
677 677 self.opener("journal.dirstate", "w").write(ds)
678 678 self.opener("journal.branch", "w").write(
679 679 encoding.fromlocal(self.dirstate.branch()))
680 680 self.opener("journal.desc", "w").write("%d\n%s\n" % (len(self), desc))
681 681
682 682 renames = [(self.sjoin("journal"), self.sjoin("undo")),
683 683 (self.join("journal.dirstate"), self.join("undo.dirstate")),
684 684 (self.join("journal.branch"), self.join("undo.branch")),
685 685 (self.join("journal.desc"), self.join("undo.desc"))]
686 686 tr = transaction.transaction(self.ui.warn, self.sopener,
687 687 self.sjoin("journal"),
688 688 aftertrans(renames),
689 689 self.store.createmode)
690 690 self._transref = weakref.ref(tr)
691 691 return tr
692 692
693 693 def recover(self):
694 694 lock = self.lock()
695 695 try:
696 696 if os.path.exists(self.sjoin("journal")):
697 697 self.ui.status(_("rolling back interrupted transaction\n"))
698 698 transaction.rollback(self.sopener, self.sjoin("journal"),
699 699 self.ui.warn)
700 700 self.invalidate()
701 701 return True
702 702 else:
703 703 self.ui.warn(_("no interrupted transaction available\n"))
704 704 return False
705 705 finally:
706 706 lock.release()
707 707
708 708 def rollback(self, dryrun=False):
709 709 wlock = lock = None
710 710 try:
711 711 wlock = self.wlock()
712 712 lock = self.lock()
713 713 if os.path.exists(self.sjoin("undo")):
714 714 try:
715 715 args = self.opener("undo.desc", "r").read().splitlines()
716 716 if len(args) >= 3 and self.ui.verbose:
717 717 desc = _("repository tip rolled back to revision %s"
718 718 " (undo %s: %s)\n") % (
719 719 int(args[0]) - 1, args[1], args[2])
720 720 elif len(args) >= 2:
721 721 desc = _("repository tip rolled back to revision %s"
722 722 " (undo %s)\n") % (
723 723 int(args[0]) - 1, args[1])
724 724 except IOError:
725 725 desc = _("rolling back unknown transaction\n")
726 726 self.ui.status(desc)
727 727 if dryrun:
728 728 return
729 729 transaction.rollback(self.sopener, self.sjoin("undo"),
730 730 self.ui.warn)
731 731 util.rename(self.join("undo.dirstate"), self.join("dirstate"))
732 732 if os.path.exists(self.join('undo.bookmarks')):
733 733 util.rename(self.join('undo.bookmarks'),
734 734 self.join('bookmarks'))
735 735 try:
736 736 branch = self.opener("undo.branch").read()
737 737 self.dirstate.setbranch(branch)
738 738 except IOError:
739 739 self.ui.warn(_("Named branch could not be reset, "
740 740 "current branch still is: %s\n")
741 741 % self.dirstate.branch())
742 742 self.invalidate()
743 743 self.dirstate.invalidate()
744 744 self.destroyed()
745 745 parents = tuple([p.rev() for p in self.parents()])
746 746 if len(parents) > 1:
747 747 self.ui.status(_("working directory now based on "
748 748 "revisions %d and %d\n") % parents)
749 749 else:
750 750 self.ui.status(_("working directory now based on "
751 751 "revision %d\n") % parents)
752 752 else:
753 753 self.ui.warn(_("no rollback information available\n"))
754 754 return 1
755 755 finally:
756 756 release(lock, wlock)
757 757
758 758 def invalidatecaches(self):
759 759 self._tags = None
760 760 self._tagtypes = None
761 761 self.nodetagscache = None
762 762 self._branchcache = None # in UTF-8
763 763 self._branchcachetip = None
764 764
765 765 def invalidate(self):
766 766 for a in ("changelog", "manifest", "_bookmarks", "_bookmarkcurrent"):
767 767 if a in self.__dict__:
768 768 delattr(self, a)
769 769 self.invalidatecaches()
770 770
771 771 def _lock(self, lockname, wait, releasefn, acquirefn, desc):
772 772 try:
773 773 l = lock.lock(lockname, 0, releasefn, desc=desc)
774 774 except error.LockHeld, inst:
775 775 if not wait:
776 776 raise
777 777 self.ui.warn(_("waiting for lock on %s held by %r\n") %
778 778 (desc, inst.locker))
779 779 # default to 600 seconds timeout
780 780 l = lock.lock(lockname, int(self.ui.config("ui", "timeout", "600")),
781 781 releasefn, desc=desc)
782 782 if acquirefn:
783 783 acquirefn()
784 784 return l
785 785
786 786 def lock(self, wait=True):
787 787 '''Lock the repository store (.hg/store) and return a weak reference
788 788 to the lock. Use this before modifying the store (e.g. committing or
789 789 stripping). If you are opening a transaction, get a lock as well.)'''
790 790 l = self._lockref and self._lockref()
791 791 if l is not None and l.held:
792 792 l.lock()
793 793 return l
794 794
795 795 l = self._lock(self.sjoin("lock"), wait, self.store.write,
796 796 self.invalidate, _('repository %s') % self.origroot)
797 797 self._lockref = weakref.ref(l)
798 798 return l
799 799
800 800 def wlock(self, wait=True):
801 801 '''Lock the non-store parts of the repository (everything under
802 802 .hg except .hg/store) and return a weak reference to the lock.
803 803 Use this before modifying files in .hg.'''
804 804 l = self._wlockref and self._wlockref()
805 805 if l is not None and l.held:
806 806 l.lock()
807 807 return l
808 808
809 809 l = self._lock(self.join("wlock"), wait, self.dirstate.write,
810 810 self.dirstate.invalidate, _('working directory of %s') %
811 811 self.origroot)
812 812 self._wlockref = weakref.ref(l)
813 813 return l
814 814
815 815 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
816 816 """
817 817 commit an individual file as part of a larger transaction
818 818 """
819 819
820 820 fname = fctx.path()
821 821 text = fctx.data()
822 822 flog = self.file(fname)
823 823 fparent1 = manifest1.get(fname, nullid)
824 824 fparent2 = fparent2o = manifest2.get(fname, nullid)
825 825
826 826 meta = {}
827 827 copy = fctx.renamed()
828 828 if copy and copy[0] != fname:
829 829 # Mark the new revision of this file as a copy of another
830 830 # file. This copy data will effectively act as a parent
831 831 # of this new revision. If this is a merge, the first
832 832 # parent will be the nullid (meaning "look up the copy data")
833 833 # and the second one will be the other parent. For example:
834 834 #
835 835 # 0 --- 1 --- 3 rev1 changes file foo
836 836 # \ / rev2 renames foo to bar and changes it
837 837 # \- 2 -/ rev3 should have bar with all changes and
838 838 # should record that bar descends from
839 839 # bar in rev2 and foo in rev1
840 840 #
841 841 # this allows this merge to succeed:
842 842 #
843 843 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
844 844 # \ / merging rev3 and rev4 should use bar@rev2
845 845 # \- 2 --- 4 as the merge base
846 846 #
847 847
848 848 cfname = copy[0]
849 849 crev = manifest1.get(cfname)
850 850 newfparent = fparent2
851 851
852 852 if manifest2: # branch merge
853 853 if fparent2 == nullid or crev is None: # copied on remote side
854 854 if cfname in manifest2:
855 855 crev = manifest2[cfname]
856 856 newfparent = fparent1
857 857
858 858 # find source in nearest ancestor if we've lost track
859 859 if not crev:
860 860 self.ui.debug(" %s: searching for copy revision for %s\n" %
861 861 (fname, cfname))
862 862 for ancestor in self[None].ancestors():
863 863 if cfname in ancestor:
864 864 crev = ancestor[cfname].filenode()
865 865 break
866 866
867 867 if crev:
868 868 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
869 869 meta["copy"] = cfname
870 870 meta["copyrev"] = hex(crev)
871 871 fparent1, fparent2 = nullid, newfparent
872 872 else:
873 873 self.ui.warn(_("warning: can't find ancestor for '%s' "
874 874 "copied from '%s'!\n") % (fname, cfname))
875 875
876 876 elif fparent2 != nullid:
877 877 # is one parent an ancestor of the other?
878 878 fparentancestor = flog.ancestor(fparent1, fparent2)
879 879 if fparentancestor == fparent1:
880 880 fparent1, fparent2 = fparent2, nullid
881 881 elif fparentancestor == fparent2:
882 882 fparent2 = nullid
883 883
884 884 # is the file changed?
885 885 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
886 886 changelist.append(fname)
887 887 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
888 888
889 889 # are just the flags changed during merge?
890 890 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
891 891 changelist.append(fname)
892 892
893 893 return fparent1
894 894
895 895 def commit(self, text="", user=None, date=None, match=None, force=False,
896 896 editor=False, extra={}):
897 897 """Add a new revision to current repository.
898 898
899 899 Revision information is gathered from the working directory,
900 900 match can be used to filter the committed files. If editor is
901 901 supplied, it is called to get a commit message.
902 902 """
903 903
904 904 def fail(f, msg):
905 905 raise util.Abort('%s: %s' % (f, msg))
906 906
907 907 if not match:
908 908 match = matchmod.always(self.root, '')
909 909
910 910 if not force:
911 911 vdirs = []
912 912 match.dir = vdirs.append
913 913 match.bad = fail
914 914
915 915 wlock = self.wlock()
916 916 try:
917 917 wctx = self[None]
918 918 merge = len(wctx.parents()) > 1
919 919
920 920 if (not force and merge and match and
921 921 (match.files() or match.anypats())):
922 922 raise util.Abort(_('cannot partially commit a merge '
923 923 '(do not specify files or patterns)'))
924 924
925 925 changes = self.status(match=match, clean=force)
926 926 if force:
927 927 changes[0].extend(changes[6]) # mq may commit unchanged files
928 928
929 929 # check subrepos
930 930 subs = []
931 931 removedsubs = set()
932 932 for p in wctx.parents():
933 933 removedsubs.update(s for s in p.substate if match(s))
934 934 for s in wctx.substate:
935 935 removedsubs.discard(s)
936 936 if match(s) and wctx.sub(s).dirty():
937 937 subs.append(s)
938 938 if (subs or removedsubs):
939 939 if (not match('.hgsub') and
940 940 '.hgsub' in (wctx.modified() + wctx.added())):
941 941 raise util.Abort(_("can't commit subrepos without .hgsub"))
942 942 if '.hgsubstate' not in changes[0]:
943 943 changes[0].insert(0, '.hgsubstate')
944 944
945 945 if subs and not self.ui.configbool('ui', 'commitsubrepos', True):
946 946 changedsubs = [s for s in subs if wctx.sub(s).dirty(True)]
947 947 if changedsubs:
948 948 raise util.Abort(_("uncommitted changes in subrepo %s")
949 949 % changedsubs[0])
950 950
951 951 # make sure all explicit patterns are matched
952 952 if not force and match.files():
953 953 matched = set(changes[0] + changes[1] + changes[2])
954 954
955 955 for f in match.files():
956 956 if f == '.' or f in matched or f in wctx.substate:
957 957 continue
958 958 if f in changes[3]: # missing
959 959 fail(f, _('file not found!'))
960 960 if f in vdirs: # visited directory
961 961 d = f + '/'
962 962 for mf in matched:
963 963 if mf.startswith(d):
964 964 break
965 965 else:
966 966 fail(f, _("no match under directory!"))
967 967 elif f not in self.dirstate:
968 968 fail(f, _("file not tracked!"))
969 969
970 970 if (not force and not extra.get("close") and not merge
971 971 and not (changes[0] or changes[1] or changes[2])
972 972 and wctx.branch() == wctx.p1().branch()):
973 973 return None
974 974
975 975 ms = mergemod.mergestate(self)
976 976 for f in changes[0]:
977 977 if f in ms and ms[f] == 'u':
978 978 raise util.Abort(_("unresolved merge conflicts "
979 979 "(see hg help resolve)"))
980 980
981 981 cctx = context.workingctx(self, text, user, date, extra, changes)
982 982 if editor:
983 983 cctx._text = editor(self, cctx, subs)
984 984 edited = (text != cctx._text)
985 985
986 986 # commit subs
987 987 if subs or removedsubs:
988 988 state = wctx.substate.copy()
989 989 for s in sorted(subs):
990 990 sub = wctx.sub(s)
991 991 self.ui.status(_('committing subrepository %s\n') %
992 992 subrepo.subrelpath(sub))
993 993 sr = sub.commit(cctx._text, user, date)
994 994 state[s] = (state[s][0], sr)
995 995 subrepo.writestate(self, state)
996 996
997 997 # Save commit message in case this transaction gets rolled back
998 998 # (e.g. by a pretxncommit hook). Leave the content alone on
999 999 # the assumption that the user will use the same editor again.
1000 1000 msgfile = self.opener('last-message.txt', 'wb')
1001 1001 msgfile.write(cctx._text)
1002 1002 msgfile.close()
1003 1003
1004 1004 p1, p2 = self.dirstate.parents()
1005 1005 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1006 1006 try:
1007 1007 self.hook("precommit", throw=True, parent1=hookp1, parent2=hookp2)
1008 1008 ret = self.commitctx(cctx, True)
1009 1009 except:
1010 1010 if edited:
1011 1011 msgfn = self.pathto(msgfile.name[len(self.root)+1:])
1012 1012 self.ui.write(
1013 1013 _('note: commit message saved in %s\n') % msgfn)
1014 1014 raise
1015 1015
1016 1016 # update bookmarks, dirstate and mergestate
1017 1017 parents = (p1, p2)
1018 1018 if p2 == nullid:
1019 1019 parents = (p1,)
1020 1020 bookmarks.update(self, parents, ret)
1021 1021 for f in changes[0] + changes[1]:
1022 1022 self.dirstate.normal(f)
1023 1023 for f in changes[2]:
1024 1024 self.dirstate.forget(f)
1025 1025 self.dirstate.setparents(ret)
1026 1026 ms.reset()
1027 1027 finally:
1028 1028 wlock.release()
1029 1029
1030 1030 self.hook("commit", node=hex(ret), parent1=hookp1, parent2=hookp2)
1031 1031 return ret
1032 1032
1033 1033 def commitctx(self, ctx, error=False):
1034 1034 """Add a new revision to current repository.
1035 1035 Revision information is passed via the context argument.
1036 1036 """
1037 1037
1038 1038 tr = lock = None
1039 1039 removed = list(ctx.removed())
1040 1040 p1, p2 = ctx.p1(), ctx.p2()
1041 1041 m1 = p1.manifest().copy()
1042 1042 m2 = p2.manifest()
1043 1043 user = ctx.user()
1044 1044
1045 1045 lock = self.lock()
1046 1046 try:
1047 1047 tr = self.transaction("commit")
1048 1048 trp = weakref.proxy(tr)
1049 1049
1050 1050 # check in files
1051 1051 new = {}
1052 1052 changed = []
1053 1053 linkrev = len(self)
1054 1054 for f in sorted(ctx.modified() + ctx.added()):
1055 1055 self.ui.note(f + "\n")
1056 1056 try:
1057 1057 fctx = ctx[f]
1058 1058 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1059 1059 changed)
1060 1060 m1.set(f, fctx.flags())
1061 1061 except OSError, inst:
1062 1062 self.ui.warn(_("trouble committing %s!\n") % f)
1063 1063 raise
1064 1064 except IOError, inst:
1065 1065 errcode = getattr(inst, 'errno', errno.ENOENT)
1066 1066 if error or errcode and errcode != errno.ENOENT:
1067 1067 self.ui.warn(_("trouble committing %s!\n") % f)
1068 1068 raise
1069 1069 else:
1070 1070 removed.append(f)
1071 1071
1072 1072 # update manifest
1073 1073 m1.update(new)
1074 1074 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1075 1075 drop = [f for f in removed if f in m1]
1076 1076 for f in drop:
1077 1077 del m1[f]
1078 1078 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1079 1079 p2.manifestnode(), (new, drop))
1080 1080
1081 1081 # update changelog
1082 1082 self.changelog.delayupdate()
1083 1083 n = self.changelog.add(mn, changed + removed, ctx.description(),
1084 1084 trp, p1.node(), p2.node(),
1085 1085 user, ctx.date(), ctx.extra().copy())
1086 1086 p = lambda: self.changelog.writepending() and self.root or ""
1087 1087 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1088 1088 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1089 1089 parent2=xp2, pending=p)
1090 1090 self.changelog.finalize(trp)
1091 1091 tr.close()
1092 1092
1093 1093 if self._branchcache:
1094 1094 self.updatebranchcache()
1095 1095 return n
1096 1096 finally:
1097 1097 if tr:
1098 1098 tr.release()
1099 1099 lock.release()
1100 1100
1101 1101 def destroyed(self):
1102 1102 '''Inform the repository that nodes have been destroyed.
1103 1103 Intended for use by strip and rollback, so there's a common
1104 1104 place for anything that has to be done after destroying history.'''
1105 1105 # XXX it might be nice if we could take the list of destroyed
1106 1106 # nodes, but I don't see an easy way for rollback() to do that
1107 1107
1108 1108 # Ensure the persistent tag cache is updated. Doing it now
1109 1109 # means that the tag cache only has to worry about destroyed
1110 1110 # heads immediately after a strip/rollback. That in turn
1111 1111 # guarantees that "cachetip == currenttip" (comparing both rev
1112 1112 # and node) always means no nodes have been added or destroyed.
1113 1113
1114 1114 # XXX this is suboptimal when qrefresh'ing: we strip the current
1115 1115 # head, refresh the tag cache, then immediately add a new head.
1116 1116 # But I think doing it this way is necessary for the "instant
1117 1117 # tag cache retrieval" case to work.
1118 1118 self.invalidatecaches()
1119 1119
1120 1120 def walk(self, match, node=None):
1121 1121 '''
1122 1122 walk recursively through the directory tree or a given
1123 1123 changeset, finding all files matched by the match
1124 1124 function
1125 1125 '''
1126 1126 return self[node].walk(match)
1127 1127
1128 1128 def status(self, node1='.', node2=None, match=None,
1129 1129 ignored=False, clean=False, unknown=False,
1130 1130 listsubrepos=False):
1131 1131 """return status of files between two nodes or node and working directory
1132 1132
1133 1133 If node1 is None, use the first dirstate parent instead.
1134 1134 If node2 is None, compare node1 with working directory.
1135 1135 """
1136 1136
1137 1137 def mfmatches(ctx):
1138 1138 mf = ctx.manifest().copy()
1139 1139 for fn in mf.keys():
1140 1140 if not match(fn):
1141 1141 del mf[fn]
1142 1142 return mf
1143 1143
1144 1144 if isinstance(node1, context.changectx):
1145 1145 ctx1 = node1
1146 1146 else:
1147 1147 ctx1 = self[node1]
1148 1148 if isinstance(node2, context.changectx):
1149 1149 ctx2 = node2
1150 1150 else:
1151 1151 ctx2 = self[node2]
1152 1152
1153 1153 working = ctx2.rev() is None
1154 1154 parentworking = working and ctx1 == self['.']
1155 1155 match = match or matchmod.always(self.root, self.getcwd())
1156 1156 listignored, listclean, listunknown = ignored, clean, unknown
1157 1157
1158 1158 # load earliest manifest first for caching reasons
1159 1159 if not working and ctx2.rev() < ctx1.rev():
1160 1160 ctx2.manifest()
1161 1161
1162 1162 if not parentworking:
1163 1163 def bad(f, msg):
1164 1164 if f not in ctx1:
1165 1165 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1166 1166 match.bad = bad
1167 1167
1168 1168 if working: # we need to scan the working dir
1169 1169 subrepos = []
1170 1170 if '.hgsub' in self.dirstate:
1171 1171 subrepos = ctx1.substate.keys()
1172 1172 s = self.dirstate.status(match, subrepos, listignored,
1173 1173 listclean, listunknown)
1174 1174 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1175 1175
1176 1176 # check for any possibly clean files
1177 1177 if parentworking and cmp:
1178 1178 fixup = []
1179 1179 # do a full compare of any files that might have changed
1180 1180 for f in sorted(cmp):
1181 1181 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1182 1182 or ctx1[f].cmp(ctx2[f])):
1183 1183 modified.append(f)
1184 1184 else:
1185 1185 fixup.append(f)
1186 1186
1187 1187 # update dirstate for files that are actually clean
1188 1188 if fixup:
1189 1189 if listclean:
1190 1190 clean += fixup
1191 1191
1192 1192 try:
1193 1193 # updating the dirstate is optional
1194 1194 # so we don't wait on the lock
1195 1195 wlock = self.wlock(False)
1196 1196 try:
1197 1197 for f in fixup:
1198 1198 self.dirstate.normal(f)
1199 1199 finally:
1200 1200 wlock.release()
1201 1201 except error.LockError:
1202 1202 pass
1203 1203
1204 1204 if not parentworking:
1205 1205 mf1 = mfmatches(ctx1)
1206 1206 if working:
1207 1207 # we are comparing working dir against non-parent
1208 1208 # generate a pseudo-manifest for the working dir
1209 1209 mf2 = mfmatches(self['.'])
1210 1210 for f in cmp + modified + added:
1211 1211 mf2[f] = None
1212 1212 mf2.set(f, ctx2.flags(f))
1213 1213 for f in removed:
1214 1214 if f in mf2:
1215 1215 del mf2[f]
1216 1216 else:
1217 1217 # we are comparing two revisions
1218 1218 deleted, unknown, ignored = [], [], []
1219 1219 mf2 = mfmatches(ctx2)
1220 1220
1221 1221 modified, added, clean = [], [], []
1222 1222 for fn in mf2:
1223 1223 if fn in mf1:
1224 1224 if (mf1.flags(fn) != mf2.flags(fn) or
1225 1225 (mf1[fn] != mf2[fn] and
1226 1226 (mf2[fn] or ctx1[fn].cmp(ctx2[fn])))):
1227 1227 modified.append(fn)
1228 1228 elif listclean:
1229 1229 clean.append(fn)
1230 1230 del mf1[fn]
1231 1231 else:
1232 1232 added.append(fn)
1233 1233 removed = mf1.keys()
1234 1234
1235 1235 r = modified, added, removed, deleted, unknown, ignored, clean
1236 1236
1237 1237 if listsubrepos:
1238 1238 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
1239 1239 if working:
1240 1240 rev2 = None
1241 1241 else:
1242 1242 rev2 = ctx2.substate[subpath][1]
1243 1243 try:
1244 1244 submatch = matchmod.narrowmatcher(subpath, match)
1245 1245 s = sub.status(rev2, match=submatch, ignored=listignored,
1246 1246 clean=listclean, unknown=listunknown,
1247 1247 listsubrepos=True)
1248 1248 for rfiles, sfiles in zip(r, s):
1249 1249 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1250 1250 except error.LookupError:
1251 1251 self.ui.status(_("skipping missing subrepository: %s\n")
1252 1252 % subpath)
1253 1253
1254 1254 for l in r:
1255 1255 l.sort()
1256 1256 return r
1257 1257
1258 1258 def heads(self, start=None):
1259 1259 heads = self.changelog.heads(start)
1260 1260 # sort the output in rev descending order
1261 1261 return sorted(heads, key=self.changelog.rev, reverse=True)
1262 1262
1263 1263 def branchheads(self, branch=None, start=None, closed=False):
1264 1264 '''return a (possibly filtered) list of heads for the given branch
1265 1265
1266 1266 Heads are returned in topological order, from newest to oldest.
1267 1267 If branch is None, use the dirstate branch.
1268 1268 If start is not None, return only heads reachable from start.
1269 1269 If closed is True, return heads that are marked as closed as well.
1270 1270 '''
1271 1271 if branch is None:
1272 1272 branch = self[None].branch()
1273 1273 branches = self.branchmap()
1274 1274 if branch not in branches:
1275 1275 return []
1276 1276 # the cache returns heads ordered lowest to highest
1277 1277 bheads = list(reversed(branches[branch]))
1278 1278 if start is not None:
1279 1279 # filter out the heads that cannot be reached from startrev
1280 1280 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1281 1281 bheads = [h for h in bheads if h in fbheads]
1282 1282 if not closed:
1283 1283 bheads = [h for h in bheads if
1284 1284 ('close' not in self.changelog.read(h)[5])]
1285 1285 return bheads
1286 1286
1287 1287 def branches(self, nodes):
1288 1288 if not nodes:
1289 1289 nodes = [self.changelog.tip()]
1290 1290 b = []
1291 1291 for n in nodes:
1292 1292 t = n
1293 1293 while 1:
1294 1294 p = self.changelog.parents(n)
1295 1295 if p[1] != nullid or p[0] == nullid:
1296 1296 b.append((t, n, p[0], p[1]))
1297 1297 break
1298 1298 n = p[0]
1299 1299 return b
1300 1300
1301 1301 def between(self, pairs):
1302 1302 r = []
1303 1303
1304 1304 for top, bottom in pairs:
1305 1305 n, l, i = top, [], 0
1306 1306 f = 1
1307 1307
1308 1308 while n != bottom and n != nullid:
1309 1309 p = self.changelog.parents(n)[0]
1310 1310 if i == f:
1311 1311 l.append(n)
1312 1312 f = f * 2
1313 1313 n = p
1314 1314 i += 1
1315 1315
1316 1316 r.append(l)
1317 1317
1318 1318 return r
1319 1319
1320 1320 def pull(self, remote, heads=None, force=False):
1321 1321 lock = self.lock()
1322 1322 try:
1323 1323 tmp = discovery.findcommonincoming(self, remote, heads=heads,
1324 1324 force=force)
1325 1325 common, fetch, rheads = tmp
1326 1326 if not fetch:
1327 1327 self.ui.status(_("no changes found\n"))
1328 1328 result = 0
1329 1329 else:
1330 1330 if heads is None and fetch == [nullid]:
1331 1331 self.ui.status(_("requesting all changes\n"))
1332 1332 elif heads is None and remote.capable('changegroupsubset'):
1333 1333 # issue1320, avoid a race if remote changed after discovery
1334 1334 heads = rheads
1335 1335
1336 1336 if heads is None:
1337 1337 cg = remote.changegroup(fetch, 'pull')
1338 1338 elif not remote.capable('changegroupsubset'):
1339 1339 raise util.Abort(_("partial pull cannot be done because "
1340 1340 "other repository doesn't support "
1341 1341 "changegroupsubset."))
1342 1342 else:
1343 1343 cg = remote.changegroupsubset(fetch, heads, 'pull')
1344 1344 result = self.addchangegroup(cg, 'pull', remote.url(),
1345 1345 lock=lock)
1346 1346 finally:
1347 1347 lock.release()
1348 1348
1349 1349 return result
1350 1350
1351 1351 def checkpush(self, force, revs):
1352 1352 """Extensions can override this function if additional checks have
1353 1353 to be performed before pushing, or call it if they override push
1354 1354 command.
1355 1355 """
1356 1356 pass
1357 1357
1358 1358 def push(self, remote, force=False, revs=None, newbranch=False):
1359 1359 '''Push outgoing changesets (limited by revs) from the current
1360 1360 repository to remote. Return an integer:
1361 1361 - 0 means HTTP error *or* nothing to push
1362 1362 - 1 means we pushed and remote head count is unchanged *or*
1363 1363 we have outgoing changesets but refused to push
1364 1364 - other values as described by addchangegroup()
1365 1365 '''
1366 1366 # there are two ways to push to remote repo:
1367 1367 #
1368 1368 # addchangegroup assumes local user can lock remote
1369 1369 # repo (local filesystem, old ssh servers).
1370 1370 #
1371 1371 # unbundle assumes local user cannot lock remote repo (new ssh
1372 1372 # servers, http servers).
1373 1373
1374 1374 self.checkpush(force, revs)
1375 1375 lock = None
1376 1376 unbundle = remote.capable('unbundle')
1377 1377 if not unbundle:
1378 1378 lock = remote.lock()
1379 1379 try:
1380 1380 cg, remote_heads = discovery.prepush(self, remote, force, revs,
1381 1381 newbranch)
1382 1382 ret = remote_heads
1383 1383 if cg is not None:
1384 1384 if unbundle:
1385 1385 # local repo finds heads on server, finds out what
1386 1386 # revs it must push. once revs transferred, if server
1387 1387 # finds it has different heads (someone else won
1388 1388 # commit/push race), server aborts.
1389 1389 if force:
1390 1390 remote_heads = ['force']
1391 1391 # ssh: return remote's addchangegroup()
1392 1392 # http: return remote's addchangegroup() or 0 for error
1393 1393 ret = remote.unbundle(cg, remote_heads, 'push')
1394 1394 else:
1395 1395 # we return an integer indicating remote head count change
1396 1396 ret = remote.addchangegroup(cg, 'push', self.url(),
1397 1397 lock=lock)
1398 1398 finally:
1399 1399 if lock is not None:
1400 1400 lock.release()
1401 1401
1402 1402 self.ui.debug("checking for updated bookmarks\n")
1403 1403 rb = remote.listkeys('bookmarks')
1404 1404 for k in rb.keys():
1405 1405 if k in self._bookmarks:
1406 1406 nr, nl = rb[k], hex(self._bookmarks[k])
1407 1407 if nr in self:
1408 1408 cr = self[nr]
1409 1409 cl = self[nl]
1410 1410 if cl in cr.descendants():
1411 1411 r = remote.pushkey('bookmarks', k, nr, nl)
1412 1412 if r:
1413 1413 self.ui.status(_("updating bookmark %s\n") % k)
1414 1414 else:
1415 1415 self.ui.warn(_('updating bookmark %s'
1416 1416 ' failed!\n') % k)
1417 1417
1418 1418 return ret
1419 1419
1420 1420 def changegroupinfo(self, nodes, source):
1421 1421 if self.ui.verbose or source == 'bundle':
1422 1422 self.ui.status(_("%d changesets found\n") % len(nodes))
1423 1423 if self.ui.debugflag:
1424 1424 self.ui.debug("list of changesets:\n")
1425 1425 for node in nodes:
1426 1426 self.ui.debug("%s\n" % hex(node))
1427 1427
1428 1428 def changegroupsubset(self, bases, heads, source):
1429 1429 """Compute a changegroup consisting of all the nodes that are
1430 1430 descendents of any of the bases and ancestors of any of the heads.
1431 1431 Return a chunkbuffer object whose read() method will return
1432 1432 successive changegroup chunks.
1433 1433
1434 1434 It is fairly complex as determining which filenodes and which
1435 1435 manifest nodes need to be included for the changeset to be complete
1436 1436 is non-trivial.
1437 1437
1438 1438 Another wrinkle is doing the reverse, figuring out which changeset in
1439 1439 the changegroup a particular filenode or manifestnode belongs to.
1440 1440 """
1441 1441
1442 1442 cl = self.changelog
1443 1443 mf = self.manifest
1444 1444 mfs = {} # needed manifests
1445 1445 fnodes = {} # needed file nodes
1446 1446
1447 1447 if not bases:
1448 1448 bases = [nullid]
1449 1449 csets, bases, heads = cl.nodesbetween(bases, heads)
1450 1450
1451 1451 # can we go through the fast path ?
1452 1452 heads.sort()
1453 1453 if heads == sorted(self.heads()):
1454 1454 return self._changegroup(csets, source)
1455 1455
1456 1456 # slow path
1457 1457 self.hook('preoutgoing', throw=True, source=source)
1458 1458 self.changegroupinfo(csets, source)
1459 1459
1460 1460 # We assume that all ancestors of bases are known
1461 1461 commonrevs = set(cl.ancestors(*[cl.rev(n) for n in bases]))
1462 1462
1463 1463 # A function generating function that sets up the initial environment
1464 1464 # the inner function.
1465 1465 def filenode_collector(changedfiles):
1466 1466 # This gathers information from each manifestnode included in the
1467 1467 # changegroup about which filenodes the manifest node references
1468 1468 # so we can include those in the changegroup too.
1469 1469 #
1470 1470 # It also remembers which changenode each filenode belongs to. It
1471 1471 # does this by assuming the a filenode belongs to the changenode
1472 1472 # the first manifest that references it belongs to.
1473 1473 def collect(mnode):
1474 1474 r = mf.rev(mnode)
1475 1475 if mf.deltaparent(r) in mf.parentrevs(r):
1476 1476 # If the previous rev is one of the parents,
1477 1477 # we only need to see a diff.
1478 1478 deltamf = mf.readdelta(mnode)
1479 1479 # For each line in the delta
1480 1480 for f, fnode in deltamf.iteritems():
1481 1481 # And if the file is in the list of files we care
1482 1482 # about.
1483 1483 if f in changedfiles:
1484 1484 # Get the changenode this manifest belongs to
1485 1485 clnode = mfs[mnode]
1486 1486 # Create the set of filenodes for the file if
1487 1487 # there isn't one already.
1488 1488 ndset = fnodes.setdefault(f, {})
1489 1489 # And set the filenode's changelog node to the
1490 1490 # manifest's if it hasn't been set already.
1491 1491 ndset.setdefault(fnode, clnode)
1492 1492 else:
1493 1493 # Otherwise we need a full manifest.
1494 1494 m = mf.read(mnode)
1495 1495 # For every file in we care about.
1496 1496 for f in changedfiles:
1497 1497 fnode = m.get(f, None)
1498 1498 # If it's in the manifest
1499 1499 if fnode is not None:
1500 1500 # See comments above.
1501 1501 clnode = mfs[mnode]
1502 1502 ndset = fnodes.setdefault(f, {})
1503 1503 ndset.setdefault(fnode, clnode)
1504 1504 return collect
1505 1505
1506 1506 # If we determine that a particular file or manifest node must be a
1507 1507 # node that the recipient of the changegroup will already have, we can
1508 1508 # also assume the recipient will have all the parents. This function
1509 1509 # prunes them from the set of missing nodes.
1510 1510 def prune(revlog, missingnodes):
1511 hasset = set()
1512 # If a 'missing' filenode thinks it belongs to a changenode we
1513 # assume the recipient must have, then the recipient must have
1514 # that filenode.
1511 # drop any nodes that claim to be part of a cset in commonrevs
1512 drop = set()
1515 1513 for n in missingnodes:
1516 clrev = revlog.linkrev(revlog.rev(n))
1517 if clrev in commonrevs:
1518 hasset.add(n)
1519 for n in hasset:
1514 if revlog.linkrev(revlog.rev(n)) in commonrevs:
1515 drop.add(n)
1516 for n in drop:
1520 1517 missingnodes.pop(n, None)
1521 for r in revlog.ancestors(*[revlog.rev(n) for n in hasset]):
1522 missingnodes.pop(revlog.node(r), None)
1523 1518
1524 1519 # Now that we have all theses utility functions to help out and
1525 1520 # logically divide up the task, generate the group.
1526 1521 def gengroup():
1527 1522 # The set of changed files starts empty.
1528 1523 changedfiles = set()
1529 1524 collect = changegroup.collector(cl, mfs, changedfiles)
1530 1525
1531 1526 # Create a changenode group generator that will call our functions
1532 1527 # back to lookup the owning changenode and collect information.
1533 1528 group = cl.group(csets, lambda x: x, collect)
1534 1529 for cnt, chnk in enumerate(group):
1535 1530 yield chnk
1536 1531 # revlog.group yields three entries per node, so
1537 1532 # dividing by 3 gives an approximation of how many
1538 1533 # nodes have been processed.
1539 1534 self.ui.progress(_('bundling'), cnt / 3,
1540 1535 unit=_('changesets'))
1541 1536 changecount = cnt / 3
1542 1537 self.ui.progress(_('bundling'), None)
1543 1538
1544 1539 prune(mf, mfs)
1545 1540 # Create a generator for the manifestnodes that calls our lookup
1546 1541 # and data collection functions back.
1547 1542 group = mf.group(sorted(mfs, key=mf.rev),
1548 1543 lambda mnode: mfs[mnode],
1549 1544 filenode_collector(changedfiles))
1550 1545 efiles = {}
1551 1546 for cnt, chnk in enumerate(group):
1552 1547 if cnt % 3 == 1:
1553 1548 mnode = chnk[:20]
1554 1549 efiles.update(mf.readdelta(mnode))
1555 1550 yield chnk
1556 1551 # see above comment for why we divide by 3
1557 1552 self.ui.progress(_('bundling'), cnt / 3,
1558 1553 unit=_('manifests'), total=changecount)
1559 1554 self.ui.progress(_('bundling'), None)
1560 1555 efiles = len(efiles)
1561 1556
1562 1557 mfs.clear()
1563 1558
1564 1559 # Go through all our files in order sorted by name.
1565 1560 for idx, fname in enumerate(sorted(changedfiles)):
1566 1561 filerevlog = self.file(fname)
1567 1562 if not len(filerevlog):
1568 1563 raise util.Abort(_("empty or missing revlog for %s") % fname)
1569 1564 # Toss out the filenodes that the recipient isn't really
1570 1565 # missing.
1571 1566 missingfnodes = fnodes.pop(fname, {})
1572 1567 prune(filerevlog, missingfnodes)
1573 1568 # If any filenodes are left, generate the group for them,
1574 1569 # otherwise don't bother.
1575 1570 if missingfnodes:
1576 1571 yield changegroup.chunkheader(len(fname))
1577 1572 yield fname
1578 1573 # Create a group generator and only pass in a changenode
1579 1574 # lookup function as we need to collect no information
1580 1575 # from filenodes.
1581 1576 group = filerevlog.group(
1582 1577 sorted(missingfnodes, key=filerevlog.rev),
1583 1578 lambda fnode: missingfnodes[fnode])
1584 1579 for chnk in group:
1585 1580 # even though we print the same progress on
1586 1581 # most loop iterations, put the progress call
1587 1582 # here so that time estimates (if any) can be updated
1588 1583 self.ui.progress(
1589 1584 _('bundling'), idx, item=fname,
1590 1585 unit=_('files'), total=efiles)
1591 1586 yield chnk
1592 1587 # Signal that no more groups are left.
1593 1588 yield changegroup.closechunk()
1594 1589 self.ui.progress(_('bundling'), None)
1595 1590
1596 1591 if csets:
1597 1592 self.hook('outgoing', node=hex(csets[0]), source=source)
1598 1593
1599 1594 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1600 1595
1601 1596 def changegroup(self, basenodes, source):
1602 1597 # to avoid a race we use changegroupsubset() (issue1320)
1603 1598 return self.changegroupsubset(basenodes, self.heads(), source)
1604 1599
1605 1600 def _changegroup(self, nodes, source):
1606 1601 """Compute the changegroup of all nodes that we have that a recipient
1607 1602 doesn't. Return a chunkbuffer object whose read() method will return
1608 1603 successive changegroup chunks.
1609 1604
1610 1605 This is much easier than the previous function as we can assume that
1611 1606 the recipient has any changenode we aren't sending them.
1612 1607
1613 1608 nodes is the set of nodes to send"""
1614 1609
1615 1610 self.hook('preoutgoing', throw=True, source=source)
1616 1611
1617 1612 cl = self.changelog
1618 1613 revset = set([cl.rev(n) for n in nodes])
1619 1614 self.changegroupinfo(nodes, source)
1620 1615
1621 1616 def identity(x):
1622 1617 return x
1623 1618
1624 1619 def gennodelst(log):
1625 1620 for r in log:
1626 1621 if log.linkrev(r) in revset:
1627 1622 yield log.node(r)
1628 1623
1629 1624 def lookuplinkrev_func(revlog):
1630 1625 def lookuplinkrev(n):
1631 1626 return cl.node(revlog.linkrev(revlog.rev(n)))
1632 1627 return lookuplinkrev
1633 1628
1634 1629 def gengroup():
1635 1630 '''yield a sequence of changegroup chunks (strings)'''
1636 1631 # construct a list of all changed files
1637 1632 changedfiles = set()
1638 1633 mmfs = {}
1639 1634 collect = changegroup.collector(cl, mmfs, changedfiles)
1640 1635
1641 1636 for cnt, chnk in enumerate(cl.group(nodes, identity, collect)):
1642 1637 # revlog.group yields three entries per node, so
1643 1638 # dividing by 3 gives an approximation of how many
1644 1639 # nodes have been processed.
1645 1640 self.ui.progress(_('bundling'), cnt / 3, unit=_('changesets'))
1646 1641 yield chnk
1647 1642 changecount = cnt / 3
1648 1643 self.ui.progress(_('bundling'), None)
1649 1644
1650 1645 mnfst = self.manifest
1651 1646 nodeiter = gennodelst(mnfst)
1652 1647 efiles = {}
1653 1648 for cnt, chnk in enumerate(mnfst.group(nodeiter,
1654 1649 lookuplinkrev_func(mnfst))):
1655 1650 if cnt % 3 == 1:
1656 1651 mnode = chnk[:20]
1657 1652 efiles.update(mnfst.readdelta(mnode))
1658 1653 # see above comment for why we divide by 3
1659 1654 self.ui.progress(_('bundling'), cnt / 3,
1660 1655 unit=_('manifests'), total=changecount)
1661 1656 yield chnk
1662 1657 efiles = len(efiles)
1663 1658 self.ui.progress(_('bundling'), None)
1664 1659
1665 1660 for idx, fname in enumerate(sorted(changedfiles)):
1666 1661 filerevlog = self.file(fname)
1667 1662 if not len(filerevlog):
1668 1663 raise util.Abort(_("empty or missing revlog for %s") % fname)
1669 1664 nodeiter = gennodelst(filerevlog)
1670 1665 nodeiter = list(nodeiter)
1671 1666 if nodeiter:
1672 1667 yield changegroup.chunkheader(len(fname))
1673 1668 yield fname
1674 1669 lookup = lookuplinkrev_func(filerevlog)
1675 1670 for chnk in filerevlog.group(nodeiter, lookup):
1676 1671 self.ui.progress(
1677 1672 _('bundling'), idx, item=fname,
1678 1673 total=efiles, unit=_('files'))
1679 1674 yield chnk
1680 1675 self.ui.progress(_('bundling'), None)
1681 1676
1682 1677 yield changegroup.closechunk()
1683 1678
1684 1679 if nodes:
1685 1680 self.hook('outgoing', node=hex(nodes[0]), source=source)
1686 1681
1687 1682 return changegroup.unbundle10(util.chunkbuffer(gengroup()), 'UN')
1688 1683
1689 1684 def addchangegroup(self, source, srctype, url, emptyok=False, lock=None):
1690 1685 """Add the changegroup returned by source.read() to this repo.
1691 1686 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1692 1687 the URL of the repo where this changegroup is coming from.
1693 1688 If lock is not None, the function takes ownership of the lock
1694 1689 and releases it after the changegroup is added.
1695 1690
1696 1691 Return an integer summarizing the change to this repo:
1697 1692 - nothing changed or no source: 0
1698 1693 - more heads than before: 1+added heads (2..n)
1699 1694 - fewer heads than before: -1-removed heads (-2..-n)
1700 1695 - number of heads stays the same: 1
1701 1696 """
1702 1697 def csmap(x):
1703 1698 self.ui.debug("add changeset %s\n" % short(x))
1704 1699 return len(cl)
1705 1700
1706 1701 def revmap(x):
1707 1702 return cl.rev(x)
1708 1703
1709 1704 if not source:
1710 1705 return 0
1711 1706
1712 1707 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1713 1708
1714 1709 changesets = files = revisions = 0
1715 1710 efiles = set()
1716 1711
1717 1712 # write changelog data to temp files so concurrent readers will not see
1718 1713 # inconsistent view
1719 1714 cl = self.changelog
1720 1715 cl.delayupdate()
1721 1716 oldheads = len(cl.heads())
1722 1717
1723 1718 tr = self.transaction("\n".join([srctype, urlmod.hidepassword(url)]))
1724 1719 try:
1725 1720 trp = weakref.proxy(tr)
1726 1721 # pull off the changeset group
1727 1722 self.ui.status(_("adding changesets\n"))
1728 1723 clstart = len(cl)
1729 1724 class prog(object):
1730 1725 step = _('changesets')
1731 1726 count = 1
1732 1727 ui = self.ui
1733 1728 total = None
1734 1729 def __call__(self):
1735 1730 self.ui.progress(self.step, self.count, unit=_('chunks'),
1736 1731 total=self.total)
1737 1732 self.count += 1
1738 1733 pr = prog()
1739 1734 source.callback = pr
1740 1735
1741 1736 if (cl.addgroup(source, csmap, trp) is None
1742 1737 and not emptyok):
1743 1738 raise util.Abort(_("received changelog group is empty"))
1744 1739 clend = len(cl)
1745 1740 changesets = clend - clstart
1746 1741 for c in xrange(clstart, clend):
1747 1742 efiles.update(self[c].files())
1748 1743 efiles = len(efiles)
1749 1744 self.ui.progress(_('changesets'), None)
1750 1745
1751 1746 # pull off the manifest group
1752 1747 self.ui.status(_("adding manifests\n"))
1753 1748 pr.step = _('manifests')
1754 1749 pr.count = 1
1755 1750 pr.total = changesets # manifests <= changesets
1756 1751 # no need to check for empty manifest group here:
1757 1752 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1758 1753 # no new manifest will be created and the manifest group will
1759 1754 # be empty during the pull
1760 1755 self.manifest.addgroup(source, revmap, trp)
1761 1756 self.ui.progress(_('manifests'), None)
1762 1757
1763 1758 needfiles = {}
1764 1759 if self.ui.configbool('server', 'validate', default=False):
1765 1760 # validate incoming csets have their manifests
1766 1761 for cset in xrange(clstart, clend):
1767 1762 mfest = self.changelog.read(self.changelog.node(cset))[0]
1768 1763 mfest = self.manifest.readdelta(mfest)
1769 1764 # store file nodes we must see
1770 1765 for f, n in mfest.iteritems():
1771 1766 needfiles.setdefault(f, set()).add(n)
1772 1767
1773 1768 # process the files
1774 1769 self.ui.status(_("adding file changes\n"))
1775 1770 pr.step = 'files'
1776 1771 pr.count = 1
1777 1772 pr.total = efiles
1778 1773 source.callback = None
1779 1774
1780 1775 while 1:
1781 1776 f = source.chunk()
1782 1777 if not f:
1783 1778 break
1784 1779 self.ui.debug("adding %s revisions\n" % f)
1785 1780 pr()
1786 1781 fl = self.file(f)
1787 1782 o = len(fl)
1788 1783 if fl.addgroup(source, revmap, trp) is None:
1789 1784 raise util.Abort(_("received file revlog group is empty"))
1790 1785 revisions += len(fl) - o
1791 1786 files += 1
1792 1787 if f in needfiles:
1793 1788 needs = needfiles[f]
1794 1789 for new in xrange(o, len(fl)):
1795 1790 n = fl.node(new)
1796 1791 if n in needs:
1797 1792 needs.remove(n)
1798 1793 if not needs:
1799 1794 del needfiles[f]
1800 1795 self.ui.progress(_('files'), None)
1801 1796
1802 1797 for f, needs in needfiles.iteritems():
1803 1798 fl = self.file(f)
1804 1799 for n in needs:
1805 1800 try:
1806 1801 fl.rev(n)
1807 1802 except error.LookupError:
1808 1803 raise util.Abort(
1809 1804 _('missing file data for %s:%s - run hg verify') %
1810 1805 (f, hex(n)))
1811 1806
1812 1807 newheads = len(cl.heads())
1813 1808 heads = ""
1814 1809 if oldheads and newheads != oldheads:
1815 1810 heads = _(" (%+d heads)") % (newheads - oldheads)
1816 1811
1817 1812 self.ui.status(_("added %d changesets"
1818 1813 " with %d changes to %d files%s\n")
1819 1814 % (changesets, revisions, files, heads))
1820 1815
1821 1816 if changesets > 0:
1822 1817 p = lambda: cl.writepending() and self.root or ""
1823 1818 self.hook('pretxnchangegroup', throw=True,
1824 1819 node=hex(cl.node(clstart)), source=srctype,
1825 1820 url=url, pending=p)
1826 1821
1827 1822 # make changelog see real files again
1828 1823 cl.finalize(trp)
1829 1824
1830 1825 tr.close()
1831 1826 finally:
1832 1827 tr.release()
1833 1828 if lock:
1834 1829 lock.release()
1835 1830
1836 1831 if changesets > 0:
1837 1832 # forcefully update the on-disk branch cache
1838 1833 self.ui.debug("updating the branch cache\n")
1839 1834 self.updatebranchcache()
1840 1835 self.hook("changegroup", node=hex(cl.node(clstart)),
1841 1836 source=srctype, url=url)
1842 1837
1843 1838 for i in xrange(clstart, clend):
1844 1839 self.hook("incoming", node=hex(cl.node(i)),
1845 1840 source=srctype, url=url)
1846 1841
1847 1842 # never return 0 here:
1848 1843 if newheads < oldheads:
1849 1844 return newheads - oldheads - 1
1850 1845 else:
1851 1846 return newheads - oldheads + 1
1852 1847
1853 1848
1854 1849 def stream_in(self, remote, requirements):
1855 1850 lock = self.lock()
1856 1851 try:
1857 1852 fp = remote.stream_out()
1858 1853 l = fp.readline()
1859 1854 try:
1860 1855 resp = int(l)
1861 1856 except ValueError:
1862 1857 raise error.ResponseError(
1863 1858 _('Unexpected response from remote server:'), l)
1864 1859 if resp == 1:
1865 1860 raise util.Abort(_('operation forbidden by server'))
1866 1861 elif resp == 2:
1867 1862 raise util.Abort(_('locking the remote repository failed'))
1868 1863 elif resp != 0:
1869 1864 raise util.Abort(_('the server sent an unknown error code'))
1870 1865 self.ui.status(_('streaming all changes\n'))
1871 1866 l = fp.readline()
1872 1867 try:
1873 1868 total_files, total_bytes = map(int, l.split(' ', 1))
1874 1869 except (ValueError, TypeError):
1875 1870 raise error.ResponseError(
1876 1871 _('Unexpected response from remote server:'), l)
1877 1872 self.ui.status(_('%d files to transfer, %s of data\n') %
1878 1873 (total_files, util.bytecount(total_bytes)))
1879 1874 start = time.time()
1880 1875 for i in xrange(total_files):
1881 1876 # XXX doesn't support '\n' or '\r' in filenames
1882 1877 l = fp.readline()
1883 1878 try:
1884 1879 name, size = l.split('\0', 1)
1885 1880 size = int(size)
1886 1881 except (ValueError, TypeError):
1887 1882 raise error.ResponseError(
1888 1883 _('Unexpected response from remote server:'), l)
1889 1884 self.ui.debug('adding %s (%s)\n' % (name, util.bytecount(size)))
1890 1885 # for backwards compat, name was partially encoded
1891 1886 ofp = self.sopener(store.decodedir(name), 'w')
1892 1887 for chunk in util.filechunkiter(fp, limit=size):
1893 1888 ofp.write(chunk)
1894 1889 ofp.close()
1895 1890 elapsed = time.time() - start
1896 1891 if elapsed <= 0:
1897 1892 elapsed = 0.001
1898 1893 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1899 1894 (util.bytecount(total_bytes), elapsed,
1900 1895 util.bytecount(total_bytes / elapsed)))
1901 1896
1902 1897 # new requirements = old non-format requirements + new format-related
1903 1898 # requirements from the streamed-in repository
1904 1899 requirements.update(set(self.requirements) - self.supportedformats)
1905 1900 self._applyrequirements(requirements)
1906 1901 self._writerequirements()
1907 1902
1908 1903 self.invalidate()
1909 1904 return len(self.heads()) + 1
1910 1905 finally:
1911 1906 lock.release()
1912 1907
1913 1908 def clone(self, remote, heads=[], stream=False):
1914 1909 '''clone remote repository.
1915 1910
1916 1911 keyword arguments:
1917 1912 heads: list of revs to clone (forces use of pull)
1918 1913 stream: use streaming clone if possible'''
1919 1914
1920 1915 # now, all clients that can request uncompressed clones can
1921 1916 # read repo formats supported by all servers that can serve
1922 1917 # them.
1923 1918
1924 1919 # if revlog format changes, client will have to check version
1925 1920 # and format flags on "stream" capability, and use
1926 1921 # uncompressed only if compatible.
1927 1922
1928 1923 if stream and not heads:
1929 1924 # 'stream' means remote revlog format is revlogv1 only
1930 1925 if remote.capable('stream'):
1931 1926 return self.stream_in(remote, set(('revlogv1',)))
1932 1927 # otherwise, 'streamreqs' contains the remote revlog format
1933 1928 streamreqs = remote.capable('streamreqs')
1934 1929 if streamreqs:
1935 1930 streamreqs = set(streamreqs.split(','))
1936 1931 # if we support it, stream in and adjust our requirements
1937 1932 if not streamreqs - self.supportedformats:
1938 1933 return self.stream_in(remote, streamreqs)
1939 1934 return self.pull(remote, heads)
1940 1935
1941 1936 def pushkey(self, namespace, key, old, new):
1942 1937 return pushkey.push(self, namespace, key, old, new)
1943 1938
1944 1939 def listkeys(self, namespace):
1945 1940 return pushkey.list(self, namespace)
1946 1941
1947 1942 # used to avoid circular references so destructors work
1948 1943 def aftertrans(files):
1949 1944 renamefiles = [tuple(t) for t in files]
1950 1945 def a():
1951 1946 for src, dest in renamefiles:
1952 1947 util.rename(src, dest)
1953 1948 return a
1954 1949
1955 1950 def instance(ui, path, create):
1956 1951 return localrepository(ui, util.drop_scheme('file', path), create)
1957 1952
1958 1953 def islocal(path):
1959 1954 return True
General Comments 0
You need to be logged in to leave comments. Login now