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