PageRenderTime 50ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/mercurial/discovery.py

https://bitbucket.org/mirror/mercurial/
Python | 366 lines | 355 code | 2 blank | 9 comment | 4 complexity | e22df8dfad2e902b924c174037461148 MD5 | raw file
Possible License(s): GPL-2.0
  1. # discovery.py - protocol changeset discovery functions
  2. #
  3. # Copyright 2010 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. from node import nullid, short
  8. from i18n import _
  9. import util, setdiscovery, treediscovery, phases, obsolete, bookmarks
  10. import branchmap
  11. def findcommonincoming(repo, remote, heads=None, force=False):
  12. """Return a tuple (common, anyincoming, heads) used to identify the common
  13. subset of nodes between repo and remote.
  14. "common" is a list of (at least) the heads of the common subset.
  15. "anyincoming" is testable as a boolean indicating if any nodes are missing
  16. locally. If remote does not support getbundle, this actually is a list of
  17. roots of the nodes that would be incoming, to be supplied to
  18. changegroupsubset. No code except for pull should be relying on this fact
  19. any longer.
  20. "heads" is either the supplied heads, or else the remote's heads.
  21. If you pass heads and they are all known locally, the response lists just
  22. these heads in "common" and in "heads".
  23. Please use findcommonoutgoing to compute the set of outgoing nodes to give
  24. extensions a good hook into outgoing.
  25. """
  26. if not remote.capable('getbundle'):
  27. return treediscovery.findcommonincoming(repo, remote, heads, force)
  28. if heads:
  29. allknown = True
  30. knownnode = repo.changelog.hasnode # no nodemap until it is filtered
  31. for h in heads:
  32. if not knownnode(h):
  33. allknown = False
  34. break
  35. if allknown:
  36. return (heads, False, heads)
  37. res = setdiscovery.findcommonheads(repo.ui, repo, remote,
  38. abortwhenunrelated=not force)
  39. common, anyinc, srvheads = res
  40. return (list(common), anyinc, heads or list(srvheads))
  41. class outgoing(object):
  42. '''Represents the set of nodes present in a local repo but not in a
  43. (possibly) remote one.
  44. Members:
  45. missing is a list of all nodes present in local but not in remote.
  46. common is a list of all nodes shared between the two repos.
  47. excluded is the list of missing changeset that shouldn't be sent remotely.
  48. missingheads is the list of heads of missing.
  49. commonheads is the list of heads of common.
  50. The sets are computed on demand from the heads, unless provided upfront
  51. by discovery.'''
  52. def __init__(self, revlog, commonheads, missingheads):
  53. self.commonheads = commonheads
  54. self.missingheads = missingheads
  55. self._revlog = revlog
  56. self._common = None
  57. self._missing = None
  58. self.excluded = []
  59. def _computecommonmissing(self):
  60. sets = self._revlog.findcommonmissing(self.commonheads,
  61. self.missingheads)
  62. self._common, self._missing = sets
  63. @util.propertycache
  64. def common(self):
  65. if self._common is None:
  66. self._computecommonmissing()
  67. return self._common
  68. @util.propertycache
  69. def missing(self):
  70. if self._missing is None:
  71. self._computecommonmissing()
  72. return self._missing
  73. def findcommonoutgoing(repo, other, onlyheads=None, force=False,
  74. commoninc=None, portable=False):
  75. '''Return an outgoing instance to identify the nodes present in repo but
  76. not in other.
  77. If onlyheads is given, only nodes ancestral to nodes in onlyheads
  78. (inclusive) are included. If you already know the local repo's heads,
  79. passing them in onlyheads is faster than letting them be recomputed here.
  80. If commoninc is given, it must be the result of a prior call to
  81. findcommonincoming(repo, other, force) to avoid recomputing it here.
  82. If portable is given, compute more conservative common and missingheads,
  83. to make bundles created from the instance more portable.'''
  84. # declare an empty outgoing object to be filled later
  85. og = outgoing(repo.changelog, None, None)
  86. # get common set if not provided
  87. if commoninc is None:
  88. commoninc = findcommonincoming(repo, other, force=force)
  89. og.commonheads, _any, _hds = commoninc
  90. # compute outgoing
  91. mayexclude = (repo._phasecache.phaseroots[phases.secret] or repo.obsstore)
  92. if not mayexclude:
  93. og.missingheads = onlyheads or repo.heads()
  94. elif onlyheads is None:
  95. # use visible heads as it should be cached
  96. og.missingheads = repo.filtered("served").heads()
  97. og.excluded = [ctx.node() for ctx in repo.set('secret() or extinct()')]
  98. else:
  99. # compute common, missing and exclude secret stuff
  100. sets = repo.changelog.findcommonmissing(og.commonheads, onlyheads)
  101. og._common, allmissing = sets
  102. og._missing = missing = []
  103. og.excluded = excluded = []
  104. for node in allmissing:
  105. ctx = repo[node]
  106. if ctx.phase() >= phases.secret or ctx.extinct():
  107. excluded.append(node)
  108. else:
  109. missing.append(node)
  110. if len(missing) == len(allmissing):
  111. missingheads = onlyheads
  112. else: # update missing heads
  113. missingheads = phases.newheads(repo, onlyheads, excluded)
  114. og.missingheads = missingheads
  115. if portable:
  116. # recompute common and missingheads as if -r<rev> had been given for
  117. # each head of missing, and --base <rev> for each head of the proper
  118. # ancestors of missing
  119. og._computecommonmissing()
  120. cl = repo.changelog
  121. missingrevs = set(cl.rev(n) for n in og._missing)
  122. og._common = set(cl.ancestors(missingrevs)) - missingrevs
  123. commonheads = set(og.commonheads)
  124. og.missingheads = [h for h in og.missingheads if h not in commonheads]
  125. return og
  126. def _headssummary(repo, remote, outgoing):
  127. """compute a summary of branch and heads status before and after push
  128. return {'branch': ([remoteheads], [newheads], [unsyncedheads])} mapping
  129. - branch: the branch name
  130. - remoteheads: the list of remote heads known locally
  131. None if the branch is new
  132. - newheads: the new remote heads (known locally) with outgoing pushed
  133. - unsyncedheads: the list of remote heads unknown locally.
  134. """
  135. cl = repo.changelog
  136. headssum = {}
  137. # A. Create set of branches involved in the push.
  138. branches = set(repo[n].branch() for n in outgoing.missing)
  139. remotemap = remote.branchmap()
  140. newbranches = branches - set(remotemap)
  141. branches.difference_update(newbranches)
  142. # A. register remote heads
  143. remotebranches = set()
  144. for branch, heads in remote.branchmap().iteritems():
  145. remotebranches.add(branch)
  146. known = []
  147. unsynced = []
  148. knownnode = cl.hasnode # do not use nodemap until it is filtered
  149. for h in heads:
  150. if knownnode(h):
  151. known.append(h)
  152. else:
  153. unsynced.append(h)
  154. headssum[branch] = (known, list(known), unsynced)
  155. # B. add new branch data
  156. missingctx = list(repo[n] for n in outgoing.missing)
  157. touchedbranches = set()
  158. for ctx in missingctx:
  159. branch = ctx.branch()
  160. touchedbranches.add(branch)
  161. if branch not in headssum:
  162. headssum[branch] = (None, [], [])
  163. # C drop data about untouched branches:
  164. for branch in remotebranches - touchedbranches:
  165. del headssum[branch]
  166. # D. Update newmap with outgoing changes.
  167. # This will possibly add new heads and remove existing ones.
  168. newmap = branchmap.branchcache((branch, heads[1])
  169. for branch, heads in headssum.iteritems()
  170. if heads[0] is not None)
  171. newmap.update(repo, (ctx.rev() for ctx in missingctx))
  172. for branch, newheads in newmap.iteritems():
  173. headssum[branch][1][:] = newheads
  174. return headssum
  175. def _oldheadssummary(repo, remoteheads, outgoing, inc=False):
  176. """Compute branchmapsummary for repo without branchmap support"""
  177. # 1-4b. old servers: Check for new topological heads.
  178. # Construct {old,new}map with branch = None (topological branch).
  179. # (code based on update)
  180. knownnode = repo.changelog.hasnode # no nodemap until it is filtered
  181. oldheads = set(h for h in remoteheads if knownnode(h))
  182. # all nodes in outgoing.missing are children of either:
  183. # - an element of oldheads
  184. # - another element of outgoing.missing
  185. # - nullrev
  186. # This explains why the new head are very simple to compute.
  187. r = repo.set('heads(%ln + %ln)', oldheads, outgoing.missing)
  188. newheads = list(c.node() for c in r)
  189. unsynced = inc and set([None]) or set()
  190. return {None: (oldheads, newheads, unsynced)}
  191. def checkheads(repo, remote, outgoing, remoteheads, newbranch=False, inc=False,
  192. newbookmarks=[]):
  193. """Check that a push won't add any outgoing head
  194. raise Abort error and display ui message as needed.
  195. """
  196. # Check for each named branch if we're creating new remote heads.
  197. # To be a remote head after push, node must be either:
  198. # - unknown locally
  199. # - a local outgoing head descended from update
  200. # - a remote head that's known locally and not
  201. # ancestral to an outgoing head
  202. if remoteheads == [nullid]:
  203. # remote is empty, nothing to check.
  204. return
  205. if remote.capable('branchmap'):
  206. headssum = _headssummary(repo, remote, outgoing)
  207. else:
  208. headssum = _oldheadssummary(repo, remoteheads, outgoing, inc)
  209. newbranches = [branch for branch, heads in headssum.iteritems()
  210. if heads[0] is None]
  211. # 1. Check for new branches on the remote.
  212. if newbranches and not newbranch: # new branch requires --new-branch
  213. branchnames = ', '.join(sorted(newbranches))
  214. raise util.Abort(_("push creates new remote branches: %s!")
  215. % branchnames,
  216. hint=_("use 'hg push --new-branch' to create"
  217. " new remote branches"))
  218. # 2. Compute newly pushed bookmarks. We don't warn about bookmarked heads.
  219. localbookmarks = repo._bookmarks
  220. remotebookmarks = remote.listkeys('bookmarks')
  221. bookmarkedheads = set()
  222. for bm in localbookmarks:
  223. rnode = remotebookmarks.get(bm)
  224. if rnode and rnode in repo:
  225. lctx, rctx = repo[bm], repo[rnode]
  226. if bookmarks.validdest(repo, rctx, lctx):
  227. bookmarkedheads.add(lctx.node())
  228. else:
  229. if bm in newbookmarks:
  230. bookmarkedheads.add(repo[bm].node())
  231. # 3. Check for new heads.
  232. # If there are more heads after the push than before, a suitable
  233. # error message, depending on unsynced status, is displayed.
  234. error = None
  235. allmissing = set(outgoing.missing)
  236. allfuturecommon = set(c.node() for c in repo.set('%ld', outgoing.common))
  237. allfuturecommon.update(allmissing)
  238. for branch, heads in sorted(headssum.iteritems()):
  239. remoteheads, newheads, unsyncedheads = heads
  240. candidate_newhs = set(newheads)
  241. # add unsynced data
  242. if remoteheads is None:
  243. oldhs = set()
  244. else:
  245. oldhs = set(remoteheads)
  246. oldhs.update(unsyncedheads)
  247. candidate_newhs.update(unsyncedheads)
  248. dhs = None # delta heads, the new heads on branch
  249. discardedheads = set()
  250. if repo.obsstore:
  251. # remove future heads which are actually obsoleted by another
  252. # pushed element:
  253. #
  254. # XXX as above, There are several cases this case does not handle
  255. # XXX properly
  256. #
  257. # (1) if <nh> is public, it won't be affected by obsolete marker
  258. # and a new is created
  259. #
  260. # (2) if the new heads have ancestors which are not obsolete and
  261. # not ancestors of any other heads we will have a new head too.
  262. #
  263. # These two cases will be easy to handle for known changeset but
  264. # much more tricky for unsynced changes.
  265. newhs = set()
  266. for nh in candidate_newhs:
  267. if nh in repo and repo[nh].phase() <= phases.public:
  268. newhs.add(nh)
  269. else:
  270. for suc in obsolete.allsuccessors(repo.obsstore, [nh]):
  271. if suc != nh and suc in allfuturecommon:
  272. discardedheads.add(nh)
  273. break
  274. else:
  275. newhs.add(nh)
  276. else:
  277. newhs = candidate_newhs
  278. unsynced = sorted(h for h in unsyncedheads if h not in discardedheads)
  279. if unsynced:
  280. if len(unsynced) <= 4 or repo.ui.verbose:
  281. heads = ' '.join(short(h) for h in unsynced)
  282. else:
  283. heads = (' '.join(short(h) for h in unsynced[:4]) +
  284. ' ' + _("and %s others") % (len(unsynced) - 4))
  285. if branch is None:
  286. repo.ui.status(_("remote has heads that are "
  287. "not known locally: %s\n") % heads)
  288. else:
  289. repo.ui.status(_("remote has heads on branch '%s' that are "
  290. "not known locally: %s\n") % (branch, heads))
  291. if remoteheads is None:
  292. if len(newhs) > 1:
  293. dhs = list(newhs)
  294. if error is None:
  295. error = (_("push creates new branch '%s' "
  296. "with multiple heads") % (branch))
  297. hint = _("merge or"
  298. " see \"hg help push\" for details about"
  299. " pushing new heads")
  300. elif len(newhs) > len(oldhs):
  301. # remove bookmarked or existing remote heads from the new heads list
  302. dhs = sorted(newhs - bookmarkedheads - oldhs)
  303. if dhs:
  304. if error is None:
  305. if branch not in ('default', None):
  306. error = _("push creates new remote head %s "
  307. "on branch '%s'!") % (short(dhs[0]), branch)
  308. elif repo[dhs[0]].bookmarks():
  309. error = _("push creates new remote head %s "
  310. "with bookmark '%s'!") % (
  311. short(dhs[0]), repo[dhs[0]].bookmarks()[0])
  312. else:
  313. error = _("push creates new remote head %s!"
  314. ) % short(dhs[0])
  315. if unsyncedheads:
  316. hint = _("pull and merge or"
  317. " see \"hg help push\" for details about"
  318. " pushing new heads")
  319. else:
  320. hint = _("merge or"
  321. " see \"hg help push\" for details about"
  322. " pushing new heads")
  323. if branch is None:
  324. repo.ui.note(_("new remote heads:\n"))
  325. else:
  326. repo.ui.note(_("new remote heads on branch '%s':\n") % branch)
  327. for h in dhs:
  328. repo.ui.note((" %s\n") % short(h))
  329. if error:
  330. raise util.Abort(error, hint=hint)