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