PageRenderTime 64ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/mercurial/changegroup.py

https://bitbucket.org/mirror/mercurial/
Python | 752 lines | 740 code | 4 blank | 8 comment | 6 complexity | 9eb30c4fcd1d92b2264362fcc92239cd MD5 | raw file
Possible License(s): GPL-2.0
  1. # changegroup.py - Mercurial changegroup manipulation functions
  2. #
  3. # Copyright 2006 Matt Mackall <mpm@selenic.com>
  4. #
  5. # This software may be used and distributed according to the terms of the
  6. # GNU General Public License version 2 or any later version.
  7. import weakref
  8. from i18n import _
  9. from node import nullrev, nullid, hex, short
  10. import mdiff, util, dagutil
  11. import struct, os, bz2, zlib, tempfile
  12. import discovery, error, phases, branchmap
  13. _BUNDLE10_DELTA_HEADER = "20s20s20s20s"
  14. def readexactly(stream, n):
  15. '''read n bytes from stream.read and abort if less was available'''
  16. s = stream.read(n)
  17. if len(s) < n:
  18. raise util.Abort(_("stream ended unexpectedly"
  19. " (got %d bytes, expected %d)")
  20. % (len(s), n))
  21. return s
  22. def getchunk(stream):
  23. """return the next chunk from stream as a string"""
  24. d = readexactly(stream, 4)
  25. l = struct.unpack(">l", d)[0]
  26. if l <= 4:
  27. if l:
  28. raise util.Abort(_("invalid chunk length %d") % l)
  29. return ""
  30. return readexactly(stream, l - 4)
  31. def chunkheader(length):
  32. """return a changegroup chunk header (string)"""
  33. return struct.pack(">l", length + 4)
  34. def closechunk():
  35. """return a changegroup chunk header (string) for a zero-length chunk"""
  36. return struct.pack(">l", 0)
  37. class nocompress(object):
  38. def compress(self, x):
  39. return x
  40. def flush(self):
  41. return ""
  42. bundletypes = {
  43. "": ("", nocompress), # only when using unbundle on ssh and old http servers
  44. # since the unification ssh accepts a header but there
  45. # is no capability signaling it.
  46. "HG10UN": ("HG10UN", nocompress),
  47. "HG10BZ": ("HG10", lambda: bz2.BZ2Compressor()),
  48. "HG10GZ": ("HG10GZ", lambda: zlib.compressobj()),
  49. }
  50. # hgweb uses this list to communicate its preferred type
  51. bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN']
  52. def writebundle(cg, filename, bundletype, vfs=None):
  53. """Write a bundle file and return its filename.
  54. Existing files will not be overwritten.
  55. If no filename is specified, a temporary file is created.
  56. bz2 compression can be turned off.
  57. The bundle file will be deleted in case of errors.
  58. """
  59. fh = None
  60. cleanup = None
  61. try:
  62. if filename:
  63. if vfs:
  64. fh = vfs.open(filename, "wb")
  65. else:
  66. fh = open(filename, "wb")
  67. else:
  68. fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
  69. fh = os.fdopen(fd, "wb")
  70. cleanup = filename
  71. header, compressor = bundletypes[bundletype]
  72. fh.write(header)
  73. z = compressor()
  74. # parse the changegroup data, otherwise we will block
  75. # in case of sshrepo because we don't know the end of the stream
  76. # an empty chunkgroup is the end of the changegroup
  77. # a changegroup has at least 2 chunkgroups (changelog and manifest).
  78. # after that, an empty chunkgroup is the end of the changegroup
  79. for chunk in cg.getchunks():
  80. fh.write(z.compress(chunk))
  81. fh.write(z.flush())
  82. cleanup = None
  83. return filename
  84. finally:
  85. if fh is not None:
  86. fh.close()
  87. if cleanup is not None:
  88. if filename and vfs:
  89. vfs.unlink(cleanup)
  90. else:
  91. os.unlink(cleanup)
  92. def decompressor(fh, alg):
  93. if alg == 'UN':
  94. return fh
  95. elif alg == 'GZ':
  96. def generator(f):
  97. zd = zlib.decompressobj()
  98. for chunk in util.filechunkiter(f):
  99. yield zd.decompress(chunk)
  100. elif alg == 'BZ':
  101. def generator(f):
  102. zd = bz2.BZ2Decompressor()
  103. zd.decompress("BZ")
  104. for chunk in util.filechunkiter(f, 4096):
  105. yield zd.decompress(chunk)
  106. else:
  107. raise util.Abort("unknown bundle compression '%s'" % alg)
  108. return util.chunkbuffer(generator(fh))
  109. class unbundle10(object):
  110. deltaheader = _BUNDLE10_DELTA_HEADER
  111. deltaheadersize = struct.calcsize(deltaheader)
  112. def __init__(self, fh, alg):
  113. self._stream = decompressor(fh, alg)
  114. self._type = alg
  115. self.callback = None
  116. def compressed(self):
  117. return self._type != 'UN'
  118. def read(self, l):
  119. return self._stream.read(l)
  120. def seek(self, pos):
  121. return self._stream.seek(pos)
  122. def tell(self):
  123. return self._stream.tell()
  124. def close(self):
  125. return self._stream.close()
  126. def chunklength(self):
  127. d = readexactly(self._stream, 4)
  128. l = struct.unpack(">l", d)[0]
  129. if l <= 4:
  130. if l:
  131. raise util.Abort(_("invalid chunk length %d") % l)
  132. return 0
  133. if self.callback:
  134. self.callback()
  135. return l - 4
  136. def changelogheader(self):
  137. """v10 does not have a changelog header chunk"""
  138. return {}
  139. def manifestheader(self):
  140. """v10 does not have a manifest header chunk"""
  141. return {}
  142. def filelogheader(self):
  143. """return the header of the filelogs chunk, v10 only has the filename"""
  144. l = self.chunklength()
  145. if not l:
  146. return {}
  147. fname = readexactly(self._stream, l)
  148. return {'filename': fname}
  149. def _deltaheader(self, headertuple, prevnode):
  150. node, p1, p2, cs = headertuple
  151. if prevnode is None:
  152. deltabase = p1
  153. else:
  154. deltabase = prevnode
  155. return node, p1, p2, deltabase, cs
  156. def deltachunk(self, prevnode):
  157. l = self.chunklength()
  158. if not l:
  159. return {}
  160. headerdata = readexactly(self._stream, self.deltaheadersize)
  161. header = struct.unpack(self.deltaheader, headerdata)
  162. delta = readexactly(self._stream, l - self.deltaheadersize)
  163. node, p1, p2, deltabase, cs = self._deltaheader(header, prevnode)
  164. return {'node': node, 'p1': p1, 'p2': p2, 'cs': cs,
  165. 'deltabase': deltabase, 'delta': delta}
  166. def getchunks(self):
  167. """returns all the chunks contains in the bundle
  168. Used when you need to forward the binary stream to a file or another
  169. network API. To do so, it parse the changegroup data, otherwise it will
  170. block in case of sshrepo because it don't know the end of the stream.
  171. """
  172. # an empty chunkgroup is the end of the changegroup
  173. # a changegroup has at least 2 chunkgroups (changelog and manifest).
  174. # after that, an empty chunkgroup is the end of the changegroup
  175. empty = False
  176. count = 0
  177. while not empty or count <= 2:
  178. empty = True
  179. count += 1
  180. while True:
  181. chunk = getchunk(self)
  182. if not chunk:
  183. break
  184. empty = False
  185. yield chunkheader(len(chunk))
  186. pos = 0
  187. while pos < len(chunk):
  188. next = pos + 2**20
  189. yield chunk[pos:next]
  190. pos = next
  191. yield closechunk()
  192. class headerlessfixup(object):
  193. def __init__(self, fh, h):
  194. self._h = h
  195. self._fh = fh
  196. def read(self, n):
  197. if self._h:
  198. d, self._h = self._h[:n], self._h[n:]
  199. if len(d) < n:
  200. d += readexactly(self._fh, n - len(d))
  201. return d
  202. return readexactly(self._fh, n)
  203. class bundle10(object):
  204. deltaheader = _BUNDLE10_DELTA_HEADER
  205. def __init__(self, repo, bundlecaps=None):
  206. """Given a source repo, construct a bundler.
  207. bundlecaps is optional and can be used to specify the set of
  208. capabilities which can be used to build the bundle.
  209. """
  210. # Set of capabilities we can use to build the bundle.
  211. if bundlecaps is None:
  212. bundlecaps = set()
  213. self._bundlecaps = bundlecaps
  214. self._changelog = repo.changelog
  215. self._manifest = repo.manifest
  216. reorder = repo.ui.config('bundle', 'reorder', 'auto')
  217. if reorder == 'auto':
  218. reorder = None
  219. else:
  220. reorder = util.parsebool(reorder)
  221. self._repo = repo
  222. self._reorder = reorder
  223. self._progress = repo.ui.progress
  224. def close(self):
  225. return closechunk()
  226. def fileheader(self, fname):
  227. return chunkheader(len(fname)) + fname
  228. def group(self, nodelist, revlog, lookup, units=None, reorder=None):
  229. """Calculate a delta group, yielding a sequence of changegroup chunks
  230. (strings).
  231. Given a list of changeset revs, return a set of deltas and
  232. metadata corresponding to nodes. The first delta is
  233. first parent(nodelist[0]) -> nodelist[0], the receiver is
  234. guaranteed to have this parent as it has all history before
  235. these changesets. In the case firstparent is nullrev the
  236. changegroup starts with a full revision.
  237. If units is not None, progress detail will be generated, units specifies
  238. the type of revlog that is touched (changelog, manifest, etc.).
  239. """
  240. # if we don't have any revisions touched by these changesets, bail
  241. if len(nodelist) == 0:
  242. yield self.close()
  243. return
  244. # for generaldelta revlogs, we linearize the revs; this will both be
  245. # much quicker and generate a much smaller bundle
  246. if (revlog._generaldelta and reorder is not False) or reorder:
  247. dag = dagutil.revlogdag(revlog)
  248. revs = set(revlog.rev(n) for n in nodelist)
  249. revs = dag.linearize(revs)
  250. else:
  251. revs = sorted([revlog.rev(n) for n in nodelist])
  252. # add the parent of the first rev
  253. p = revlog.parentrevs(revs[0])[0]
  254. revs.insert(0, p)
  255. # build deltas
  256. total = len(revs) - 1
  257. msgbundling = _('bundling')
  258. for r in xrange(len(revs) - 1):
  259. if units is not None:
  260. self._progress(msgbundling, r + 1, unit=units, total=total)
  261. prev, curr = revs[r], revs[r + 1]
  262. linknode = lookup(revlog.node(curr))
  263. for c in self.revchunk(revlog, curr, prev, linknode):
  264. yield c
  265. yield self.close()
  266. # filter any nodes that claim to be part of the known set
  267. def prune(self, revlog, missing, commonrevs, source):
  268. rr, rl = revlog.rev, revlog.linkrev
  269. return [n for n in missing if rl(rr(n)) not in commonrevs]
  270. def generate(self, commonrevs, clnodes, fastpathlinkrev, source):
  271. '''yield a sequence of changegroup chunks (strings)'''
  272. repo = self._repo
  273. cl = self._changelog
  274. mf = self._manifest
  275. reorder = self._reorder
  276. progress = self._progress
  277. # for progress output
  278. msgbundling = _('bundling')
  279. mfs = {} # needed manifests
  280. fnodes = {} # needed file nodes
  281. changedfiles = set()
  282. # Callback for the changelog, used to collect changed files and manifest
  283. # nodes.
  284. # Returns the linkrev node (identity in the changelog case).
  285. def lookupcl(x):
  286. c = cl.read(x)
  287. changedfiles.update(c[3])
  288. # record the first changeset introducing this manifest version
  289. mfs.setdefault(c[0], x)
  290. return x
  291. # Callback for the manifest, used to collect linkrevs for filelog
  292. # revisions.
  293. # Returns the linkrev node (collected in lookupcl).
  294. def lookupmf(x):
  295. clnode = mfs[x]
  296. if not fastpathlinkrev:
  297. mdata = mf.readfast(x)
  298. for f, n in mdata.iteritems():
  299. if f in changedfiles:
  300. # record the first changeset introducing this filelog
  301. # version
  302. fnodes[f].setdefault(n, clnode)
  303. return clnode
  304. for chunk in self.group(clnodes, cl, lookupcl, units=_('changesets'),
  305. reorder=reorder):
  306. yield chunk
  307. progress(msgbundling, None)
  308. for f in changedfiles:
  309. fnodes[f] = {}
  310. mfnodes = self.prune(mf, mfs, commonrevs, source)
  311. for chunk in self.group(mfnodes, mf, lookupmf, units=_('manifests'),
  312. reorder=reorder):
  313. yield chunk
  314. progress(msgbundling, None)
  315. mfs.clear()
  316. needed = set(cl.rev(x) for x in clnodes)
  317. def linknodes(filerevlog, fname):
  318. if fastpathlinkrev:
  319. llr = filerevlog.linkrev
  320. def genfilenodes():
  321. for r in filerevlog:
  322. linkrev = llr(r)
  323. if linkrev in needed:
  324. yield filerevlog.node(r), cl.node(linkrev)
  325. fnodes[fname] = dict(genfilenodes())
  326. return fnodes.get(fname, {})
  327. for chunk in self.generatefiles(changedfiles, linknodes, commonrevs,
  328. source):
  329. yield chunk
  330. yield self.close()
  331. progress(msgbundling, None)
  332. if clnodes:
  333. repo.hook('outgoing', node=hex(clnodes[0]), source=source)
  334. def generatefiles(self, changedfiles, linknodes, commonrevs, source):
  335. repo = self._repo
  336. progress = self._progress
  337. reorder = self._reorder
  338. msgbundling = _('bundling')
  339. total = len(changedfiles)
  340. # for progress output
  341. msgfiles = _('files')
  342. for i, fname in enumerate(sorted(changedfiles)):
  343. filerevlog = repo.file(fname)
  344. if not filerevlog:
  345. raise util.Abort(_("empty or missing revlog for %s") % fname)
  346. linkrevnodes = linknodes(filerevlog, fname)
  347. # Lookup for filenodes, we collected the linkrev nodes above in the
  348. # fastpath case and with lookupmf in the slowpath case.
  349. def lookupfilelog(x):
  350. return linkrevnodes[x]
  351. filenodes = self.prune(filerevlog, linkrevnodes, commonrevs, source)
  352. if filenodes:
  353. progress(msgbundling, i + 1, item=fname, unit=msgfiles,
  354. total=total)
  355. yield self.fileheader(fname)
  356. for chunk in self.group(filenodes, filerevlog, lookupfilelog,
  357. reorder=reorder):
  358. yield chunk
  359. def revchunk(self, revlog, rev, prev, linknode):
  360. node = revlog.node(rev)
  361. p1, p2 = revlog.parentrevs(rev)
  362. base = prev
  363. prefix = ''
  364. if base == nullrev:
  365. delta = revlog.revision(node)
  366. prefix = mdiff.trivialdiffheader(len(delta))
  367. else:
  368. delta = revlog.revdiff(base, rev)
  369. p1n, p2n = revlog.parents(node)
  370. basenode = revlog.node(base)
  371. meta = self.builddeltaheader(node, p1n, p2n, basenode, linknode)
  372. meta += prefix
  373. l = len(meta) + len(delta)
  374. yield chunkheader(l)
  375. yield meta
  376. yield delta
  377. def builddeltaheader(self, node, p1n, p2n, basenode, linknode):
  378. # do nothing with basenode, it is implicitly the previous one in HG10
  379. return struct.pack(self.deltaheader, node, p1n, p2n, linknode)
  380. def _changegroupinfo(repo, nodes, source):
  381. if repo.ui.verbose or source == 'bundle':
  382. repo.ui.status(_("%d changesets found\n") % len(nodes))
  383. if repo.ui.debugflag:
  384. repo.ui.debug("list of changesets:\n")
  385. for node in nodes:
  386. repo.ui.debug("%s\n" % hex(node))
  387. def getsubset(repo, outgoing, bundler, source, fastpath=False):
  388. repo = repo.unfiltered()
  389. commonrevs = outgoing.common
  390. csets = outgoing.missing
  391. heads = outgoing.missingheads
  392. # We go through the fast path if we get told to, or if all (unfiltered
  393. # heads have been requested (since we then know there all linkrevs will
  394. # be pulled by the client).
  395. heads.sort()
  396. fastpathlinkrev = fastpath or (
  397. repo.filtername is None and heads == sorted(repo.heads()))
  398. repo.hook('preoutgoing', throw=True, source=source)
  399. _changegroupinfo(repo, csets, source)
  400. gengroup = bundler.generate(commonrevs, csets, fastpathlinkrev, source)
  401. return unbundle10(util.chunkbuffer(gengroup), 'UN')
  402. def changegroupsubset(repo, roots, heads, source):
  403. """Compute a changegroup consisting of all the nodes that are
  404. descendants of any of the roots and ancestors of any of the heads.
  405. Return a chunkbuffer object whose read() method will return
  406. successive changegroup chunks.
  407. It is fairly complex as determining which filenodes and which
  408. manifest nodes need to be included for the changeset to be complete
  409. is non-trivial.
  410. Another wrinkle is doing the reverse, figuring out which changeset in
  411. the changegroup a particular filenode or manifestnode belongs to.
  412. """
  413. cl = repo.changelog
  414. if not roots:
  415. roots = [nullid]
  416. # TODO: remove call to nodesbetween.
  417. csets, roots, heads = cl.nodesbetween(roots, heads)
  418. discbases = []
  419. for n in roots:
  420. discbases.extend([p for p in cl.parents(n) if p != nullid])
  421. outgoing = discovery.outgoing(cl, discbases, heads)
  422. bundler = bundle10(repo)
  423. return getsubset(repo, outgoing, bundler, source)
  424. def getlocalbundle(repo, source, outgoing, bundlecaps=None):
  425. """Like getbundle, but taking a discovery.outgoing as an argument.
  426. This is only implemented for local repos and reuses potentially
  427. precomputed sets in outgoing."""
  428. if not outgoing.missing:
  429. return None
  430. bundler = bundle10(repo, bundlecaps)
  431. return getsubset(repo, outgoing, bundler, source)
  432. def _computeoutgoing(repo, heads, common):
  433. """Computes which revs are outgoing given a set of common
  434. and a set of heads.
  435. This is a separate function so extensions can have access to
  436. the logic.
  437. Returns a discovery.outgoing object.
  438. """
  439. cl = repo.changelog
  440. if common:
  441. hasnode = cl.hasnode
  442. common = [n for n in common if hasnode(n)]
  443. else:
  444. common = [nullid]
  445. if not heads:
  446. heads = cl.heads()
  447. return discovery.outgoing(cl, common, heads)
  448. def getbundle(repo, source, heads=None, common=None, bundlecaps=None):
  449. """Like changegroupsubset, but returns the set difference between the
  450. ancestors of heads and the ancestors common.
  451. If heads is None, use the local heads. If common is None, use [nullid].
  452. The nodes in common might not all be known locally due to the way the
  453. current discovery protocol works.
  454. """
  455. outgoing = _computeoutgoing(repo, heads, common)
  456. return getlocalbundle(repo, source, outgoing, bundlecaps=bundlecaps)
  457. def changegroup(repo, basenodes, source):
  458. # to avoid a race we use changegroupsubset() (issue1320)
  459. return changegroupsubset(repo, basenodes, repo.heads(), source)
  460. def addchangegroupfiles(repo, source, revmap, trp, pr, needfiles):
  461. revisions = 0
  462. files = 0
  463. while True:
  464. chunkdata = source.filelogheader()
  465. if not chunkdata:
  466. break
  467. f = chunkdata["filename"]
  468. repo.ui.debug("adding %s revisions\n" % f)
  469. pr()
  470. fl = repo.file(f)
  471. o = len(fl)
  472. if not fl.addgroup(source, revmap, trp):
  473. raise util.Abort(_("received file revlog group is empty"))
  474. revisions += len(fl) - o
  475. files += 1
  476. if f in needfiles:
  477. needs = needfiles[f]
  478. for new in xrange(o, len(fl)):
  479. n = fl.node(new)
  480. if n in needs:
  481. needs.remove(n)
  482. else:
  483. raise util.Abort(
  484. _("received spurious file revlog entry"))
  485. if not needs:
  486. del needfiles[f]
  487. repo.ui.progress(_('files'), None)
  488. for f, needs in needfiles.iteritems():
  489. fl = repo.file(f)
  490. for n in needs:
  491. try:
  492. fl.rev(n)
  493. except error.LookupError:
  494. raise util.Abort(
  495. _('missing file data for %s:%s - run hg verify') %
  496. (f, hex(n)))
  497. return revisions, files
  498. def addchangegroup(repo, source, srctype, url, emptyok=False):
  499. """Add the changegroup returned by source.read() to this repo.
  500. srctype is a string like 'push', 'pull', or 'unbundle'. url is
  501. the URL of the repo where this changegroup is coming from.
  502. Return an integer summarizing the change to this repo:
  503. - nothing changed or no source: 0
  504. - more heads than before: 1+added heads (2..n)
  505. - fewer heads than before: -1-removed heads (-2..-n)
  506. - number of heads stays the same: 1
  507. """
  508. repo = repo.unfiltered()
  509. def csmap(x):
  510. repo.ui.debug("add changeset %s\n" % short(x))
  511. return len(cl)
  512. def revmap(x):
  513. return cl.rev(x)
  514. if not source:
  515. return 0
  516. repo.hook('prechangegroup', throw=True, source=srctype, url=url)
  517. changesets = files = revisions = 0
  518. efiles = set()
  519. # write changelog data to temp files so concurrent readers will not see
  520. # inconsistent view
  521. cl = repo.changelog
  522. cl.delayupdate()
  523. oldheads = cl.heads()
  524. tr = repo.transaction("\n".join([srctype, util.hidepassword(url)]))
  525. try:
  526. trp = weakref.proxy(tr)
  527. # pull off the changeset group
  528. repo.ui.status(_("adding changesets\n"))
  529. clstart = len(cl)
  530. class prog(object):
  531. step = _('changesets')
  532. count = 1
  533. ui = repo.ui
  534. total = None
  535. def __call__(repo):
  536. repo.ui.progress(repo.step, repo.count, unit=_('chunks'),
  537. total=repo.total)
  538. repo.count += 1
  539. pr = prog()
  540. source.callback = pr
  541. source.changelogheader()
  542. srccontent = cl.addgroup(source, csmap, trp)
  543. if not (srccontent or emptyok):
  544. raise util.Abort(_("received changelog group is empty"))
  545. clend = len(cl)
  546. changesets = clend - clstart
  547. for c in xrange(clstart, clend):
  548. efiles.update(repo[c].files())
  549. efiles = len(efiles)
  550. repo.ui.progress(_('changesets'), None)
  551. # pull off the manifest group
  552. repo.ui.status(_("adding manifests\n"))
  553. pr.step = _('manifests')
  554. pr.count = 1
  555. pr.total = changesets # manifests <= changesets
  556. # no need to check for empty manifest group here:
  557. # if the result of the merge of 1 and 2 is the same in 3 and 4,
  558. # no new manifest will be created and the manifest group will
  559. # be empty during the pull
  560. source.manifestheader()
  561. repo.manifest.addgroup(source, revmap, trp)
  562. repo.ui.progress(_('manifests'), None)
  563. needfiles = {}
  564. if repo.ui.configbool('server', 'validate', default=False):
  565. # validate incoming csets have their manifests
  566. for cset in xrange(clstart, clend):
  567. mfest = repo.changelog.read(repo.changelog.node(cset))[0]
  568. mfest = repo.manifest.readdelta(mfest)
  569. # store file nodes we must see
  570. for f, n in mfest.iteritems():
  571. needfiles.setdefault(f, set()).add(n)
  572. # process the files
  573. repo.ui.status(_("adding file changes\n"))
  574. pr.step = _('files')
  575. pr.count = 1
  576. pr.total = efiles
  577. source.callback = None
  578. newrevs, newfiles = addchangegroupfiles(repo, source, revmap, trp, pr,
  579. needfiles)
  580. revisions += newrevs
  581. files += newfiles
  582. dh = 0
  583. if oldheads:
  584. heads = cl.heads()
  585. dh = len(heads) - len(oldheads)
  586. for h in heads:
  587. if h not in oldheads and repo[h].closesbranch():
  588. dh -= 1
  589. htext = ""
  590. if dh:
  591. htext = _(" (%+d heads)") % dh
  592. repo.ui.status(_("added %d changesets"
  593. " with %d changes to %d files%s\n")
  594. % (changesets, revisions, files, htext))
  595. repo.invalidatevolatilesets()
  596. if changesets > 0:
  597. p = lambda: cl.writepending() and repo.root or ""
  598. if 'node' not in tr.hookargs:
  599. tr.hookargs['node'] = hex(cl.node(clstart))
  600. repo.hook('pretxnchangegroup', throw=True, source=srctype,
  601. url=url, pending=p, **tr.hookargs)
  602. added = [cl.node(r) for r in xrange(clstart, clend)]
  603. publishing = repo.ui.configbool('phases', 'publish', True)
  604. if srctype in ('push', 'serve'):
  605. # Old servers can not push the boundary themselves.
  606. # New servers won't push the boundary if changeset already
  607. # exists locally as secret
  608. #
  609. # We should not use added here but the list of all change in
  610. # the bundle
  611. if publishing:
  612. phases.advanceboundary(repo, phases.public, srccontent)
  613. else:
  614. phases.advanceboundary(repo, phases.draft, srccontent)
  615. phases.retractboundary(repo, phases.draft, added)
  616. elif srctype != 'strip':
  617. # publishing only alter behavior during push
  618. #
  619. # strip should not touch boundary at all
  620. phases.retractboundary(repo, phases.draft, added)
  621. # make changelog see real files again
  622. cl.finalize(trp)
  623. tr.close()
  624. if changesets > 0:
  625. if srctype != 'strip':
  626. # During strip, branchcache is invalid but coming call to
  627. # `destroyed` will repair it.
  628. # In other case we can safely update cache on disk.
  629. branchmap.updatecache(repo.filtered('served'))
  630. def runhooks():
  631. # These hooks run when the lock releases, not when the
  632. # transaction closes. So it's possible for the changelog
  633. # to have changed since we last saw it.
  634. if clstart >= len(repo):
  635. return
  636. # forcefully update the on-disk branch cache
  637. repo.ui.debug("updating the branch cache\n")
  638. repo.hook("changegroup", source=srctype, url=url,
  639. **tr.hookargs)
  640. for n in added:
  641. repo.hook("incoming", node=hex(n), source=srctype,
  642. url=url)
  643. newheads = [h for h in repo.heads() if h not in oldheads]
  644. repo.ui.log("incoming",
  645. "%s incoming changes - new heads: %s\n",
  646. len(added),
  647. ', '.join([hex(c[:6]) for c in newheads]))
  648. repo._afterlock(runhooks)
  649. finally:
  650. tr.release()
  651. # never return 0 here:
  652. if dh < 0:
  653. return dh - 1
  654. else:
  655. return dh + 1