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