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