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