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