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