PageRenderTime 80ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/hgext/rebase.py

https://bitbucket.org/mirror/mercurial/
Python | 970 lines | 939 code | 12 blank | 19 comment | 28 complexity | 8960cb7713e546f6b59865548a66edda MD5 | raw file
Possible License(s): GPL-2.0
  1. # rebase.py - rebasing feature for mercurial
  2. #
  3. # Copyright 2008 Stefano Tortarolo <stefano.tortarolo at gmail dot 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. '''command to move sets of revisions to a different ancestor
  8. This extension lets you rebase changesets in an existing Mercurial
  9. repository.
  10. For more information:
  11. http://mercurial.selenic.com/wiki/RebaseExtension
  12. '''
  13. from mercurial import hg, util, repair, merge, cmdutil, commands, bookmarks
  14. from mercurial import extensions, patch, scmutil, phases, obsolete, error
  15. from mercurial.commands import templateopts
  16. from mercurial.node import nullrev
  17. from mercurial.lock import release
  18. from mercurial.i18n import _
  19. import os, errno
  20. nullmerge = -2
  21. revignored = -3
  22. cmdtable = {}
  23. command = cmdutil.command(cmdtable)
  24. testedwith = 'internal'
  25. def _savegraft(ctx, extra):
  26. s = ctx.extra().get('source', None)
  27. if s is not None:
  28. extra['source'] = s
  29. def _savebranch(ctx, extra):
  30. extra['branch'] = ctx.branch()
  31. def _makeextrafn(copiers):
  32. """make an extrafn out of the given copy-functions.
  33. A copy function takes a context and an extra dict, and mutates the
  34. extra dict as needed based on the given context.
  35. """
  36. def extrafn(ctx, extra):
  37. for c in copiers:
  38. c(ctx, extra)
  39. return extrafn
  40. @command('rebase',
  41. [('s', 'source', '',
  42. _('rebase from the specified changeset'), _('REV')),
  43. ('b', 'base', '',
  44. _('rebase from the base of the specified changeset '
  45. '(up to greatest common ancestor of base and dest)'),
  46. _('REV')),
  47. ('r', 'rev', [],
  48. _('rebase these revisions'),
  49. _('REV')),
  50. ('d', 'dest', '',
  51. _('rebase onto the specified changeset'), _('REV')),
  52. ('', 'collapse', False, _('collapse the rebased changesets')),
  53. ('m', 'message', '',
  54. _('use text as collapse commit message'), _('TEXT')),
  55. ('e', 'edit', False, _('invoke editor on commit messages')),
  56. ('l', 'logfile', '',
  57. _('read collapse commit message from file'), _('FILE')),
  58. ('', 'keep', False, _('keep original changesets')),
  59. ('', 'keepbranches', False, _('keep original branch names')),
  60. ('D', 'detach', False, _('(DEPRECATED)')),
  61. ('t', 'tool', '', _('specify merge tool')),
  62. ('c', 'continue', False, _('continue an interrupted rebase')),
  63. ('a', 'abort', False, _('abort an interrupted rebase'))] +
  64. templateopts,
  65. _('[-s REV | -b REV] [-d REV] [OPTION]'))
  66. def rebase(ui, repo, **opts):
  67. """move changeset (and descendants) to a different branch
  68. Rebase uses repeated merging to graft changesets from one part of
  69. history (the source) onto another (the destination). This can be
  70. useful for linearizing *local* changes relative to a master
  71. development tree.
  72. You should not rebase changesets that have already been shared
  73. with others. Doing so will force everybody else to perform the
  74. same rebase or they will end up with duplicated changesets after
  75. pulling in your rebased changesets.
  76. In its default configuration, Mercurial will prevent you from
  77. rebasing published changes. See :hg:`help phases` for details.
  78. If you don't specify a destination changeset (``-d/--dest``),
  79. rebase uses the current branch tip as the destination. (The
  80. destination changeset is not modified by rebasing, but new
  81. changesets are added as its descendants.)
  82. You can specify which changesets to rebase in two ways: as a
  83. "source" changeset or as a "base" changeset. Both are shorthand
  84. for a topologically related set of changesets (the "source
  85. branch"). If you specify source (``-s/--source``), rebase will
  86. rebase that changeset and all of its descendants onto dest. If you
  87. specify base (``-b/--base``), rebase will select ancestors of base
  88. back to but not including the common ancestor with dest. Thus,
  89. ``-b`` is less precise but more convenient than ``-s``: you can
  90. specify any changeset in the source branch, and rebase will select
  91. the whole branch. If you specify neither ``-s`` nor ``-b``, rebase
  92. uses the parent of the working directory as the base.
  93. For advanced usage, a third way is available through the ``--rev``
  94. option. It allows you to specify an arbitrary set of changesets to
  95. rebase. Descendants of revs you specify with this option are not
  96. automatically included in the rebase.
  97. By default, rebase recreates the changesets in the source branch
  98. as descendants of dest and then destroys the originals. Use
  99. ``--keep`` to preserve the original source changesets. Some
  100. changesets in the source branch (e.g. merges from the destination
  101. branch) may be dropped if they no longer contribute any change.
  102. One result of the rules for selecting the destination changeset
  103. and source branch is that, unlike ``merge``, rebase will do
  104. nothing if you are at the branch tip of a named branch
  105. with two heads. You need to explicitly specify source and/or
  106. destination (or ``update`` to the other head, if it's the head of
  107. the intended source branch).
  108. If a rebase is interrupted to manually resolve a merge, it can be
  109. continued with --continue/-c or aborted with --abort/-a.
  110. Returns 0 on success, 1 if nothing to rebase or there are
  111. unresolved conflicts.
  112. """
  113. originalwd = target = None
  114. activebookmark = None
  115. external = nullrev
  116. state = {}
  117. skipped = set()
  118. targetancestors = set()
  119. editor = cmdutil.getcommiteditor(**opts)
  120. lock = wlock = None
  121. try:
  122. wlock = repo.wlock()
  123. lock = repo.lock()
  124. # Validate input and define rebasing points
  125. destf = opts.get('dest', None)
  126. srcf = opts.get('source', None)
  127. basef = opts.get('base', None)
  128. revf = opts.get('rev', [])
  129. contf = opts.get('continue')
  130. abortf = opts.get('abort')
  131. collapsef = opts.get('collapse', False)
  132. collapsemsg = cmdutil.logmessage(ui, opts)
  133. e = opts.get('extrafn') # internal, used by e.g. hgsubversion
  134. extrafns = [_savegraft]
  135. if e:
  136. extrafns = [e]
  137. keepf = opts.get('keep', False)
  138. keepbranchesf = opts.get('keepbranches', False)
  139. # keepopen is not meant for use on the command line, but by
  140. # other extensions
  141. keepopen = opts.get('keepopen', False)
  142. if collapsemsg and not collapsef:
  143. raise util.Abort(
  144. _('message can only be specified with collapse'))
  145. if contf or abortf:
  146. if contf and abortf:
  147. raise util.Abort(_('cannot use both abort and continue'))
  148. if collapsef:
  149. raise util.Abort(
  150. _('cannot use collapse with continue or abort'))
  151. if srcf or basef or destf:
  152. raise util.Abort(
  153. _('abort and continue do not allow specifying revisions'))
  154. if opts.get('tool', False):
  155. ui.warn(_('tool option will be ignored\n'))
  156. try:
  157. (originalwd, target, state, skipped, collapsef, keepf,
  158. keepbranchesf, external, activebookmark) = restorestatus(repo)
  159. except error.RepoLookupError:
  160. if abortf:
  161. clearstatus(repo)
  162. repo.ui.warn(_('rebase aborted (no revision is removed,'
  163. ' only broken state is cleared)\n'))
  164. return 0
  165. else:
  166. msg = _('cannot continue inconsistent rebase')
  167. hint = _('use "hg rebase --abort" to clear broken state')
  168. raise util.Abort(msg, hint=hint)
  169. if abortf:
  170. return abort(repo, originalwd, target, state)
  171. else:
  172. if srcf and basef:
  173. raise util.Abort(_('cannot specify both a '
  174. 'source and a base'))
  175. if revf and basef:
  176. raise util.Abort(_('cannot specify both a '
  177. 'revision and a base'))
  178. if revf and srcf:
  179. raise util.Abort(_('cannot specify both a '
  180. 'revision and a source'))
  181. cmdutil.checkunfinished(repo)
  182. cmdutil.bailifchanged(repo)
  183. if not destf:
  184. # Destination defaults to the latest revision in the
  185. # current branch
  186. branch = repo[None].branch()
  187. dest = repo[branch]
  188. else:
  189. dest = scmutil.revsingle(repo, destf)
  190. if revf:
  191. rebaseset = scmutil.revrange(repo, revf)
  192. if not rebaseset:
  193. ui.status(_('empty "rev" revision set - '
  194. 'nothing to rebase\n'))
  195. return 1
  196. elif srcf:
  197. src = scmutil.revrange(repo, [srcf])
  198. if not src:
  199. ui.status(_('empty "source" revision set - '
  200. 'nothing to rebase\n'))
  201. return 1
  202. rebaseset = repo.revs('(%ld)::', src)
  203. assert rebaseset
  204. else:
  205. base = scmutil.revrange(repo, [basef or '.'])
  206. if not base:
  207. ui.status(_('empty "base" revision set - '
  208. "can't compute rebase set\n"))
  209. return 1
  210. rebaseset = repo.revs(
  211. '(children(ancestor(%ld, %d)) and ::(%ld))::',
  212. base, dest, base)
  213. if not rebaseset:
  214. if base == [dest.rev()]:
  215. if basef:
  216. ui.status(_('nothing to rebase - %s is both "base"'
  217. ' and destination\n') % dest)
  218. else:
  219. ui.status(_('nothing to rebase - working directory '
  220. 'parent is also destination\n'))
  221. elif not repo.revs('%ld - ::%d', base, dest):
  222. if basef:
  223. ui.status(_('nothing to rebase - "base" %s is '
  224. 'already an ancestor of destination '
  225. '%s\n') %
  226. ('+'.join(str(repo[r]) for r in base),
  227. dest))
  228. else:
  229. ui.status(_('nothing to rebase - working '
  230. 'directory parent is already an '
  231. 'ancestor of destination %s\n') % dest)
  232. else: # can it happen?
  233. ui.status(_('nothing to rebase from %s to %s\n') %
  234. ('+'.join(str(repo[r]) for r in base), dest))
  235. return 1
  236. if (not (keepf or obsolete._enabled)
  237. and repo.revs('first(children(%ld) - %ld)',
  238. rebaseset, rebaseset)):
  239. raise util.Abort(
  240. _("can't remove original changesets with"
  241. " unrebased descendants"),
  242. hint=_('use --keep to keep original changesets'))
  243. result = buildstate(repo, dest, rebaseset, collapsef)
  244. if not result:
  245. # Empty state built, nothing to rebase
  246. ui.status(_('nothing to rebase\n'))
  247. return 1
  248. root = min(rebaseset)
  249. if not keepf and not repo[root].mutable():
  250. raise util.Abort(_("can't rebase immutable changeset %s")
  251. % repo[root],
  252. hint=_('see hg help phases for details'))
  253. originalwd, target, state = result
  254. if collapsef:
  255. targetancestors = repo.changelog.ancestors([target],
  256. inclusive=True)
  257. external = externalparent(repo, state, targetancestors)
  258. if dest.closesbranch() and not keepbranchesf:
  259. ui.status(_('reopening closed branch head %s\n') % dest)
  260. if keepbranchesf:
  261. # insert _savebranch at the start of extrafns so if
  262. # there's a user-provided extrafn it can clobber branch if
  263. # desired
  264. extrafns.insert(0, _savebranch)
  265. if collapsef:
  266. branches = set()
  267. for rev in state:
  268. branches.add(repo[rev].branch())
  269. if len(branches) > 1:
  270. raise util.Abort(_('cannot collapse multiple named '
  271. 'branches'))
  272. # Rebase
  273. if not targetancestors:
  274. targetancestors = repo.changelog.ancestors([target], inclusive=True)
  275. # Keep track of the current bookmarks in order to reset them later
  276. currentbookmarks = repo._bookmarks.copy()
  277. activebookmark = activebookmark or repo._bookmarkcurrent
  278. if activebookmark:
  279. bookmarks.unsetcurrent(repo)
  280. extrafn = _makeextrafn(extrafns)
  281. sortedstate = sorted(state)
  282. total = len(sortedstate)
  283. pos = 0
  284. for rev in sortedstate:
  285. pos += 1
  286. if state[rev] == -1:
  287. ui.progress(_("rebasing"), pos, ("%d:%s" % (rev, repo[rev])),
  288. _('changesets'), total)
  289. p1, p2 = defineparents(repo, rev, target, state,
  290. targetancestors)
  291. storestatus(repo, originalwd, target, state, collapsef, keepf,
  292. keepbranchesf, external, activebookmark)
  293. if len(repo.parents()) == 2:
  294. repo.ui.debug('resuming interrupted rebase\n')
  295. else:
  296. try:
  297. ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
  298. 'rebase')
  299. stats = rebasenode(repo, rev, p1, state, collapsef)
  300. if stats and stats[3] > 0:
  301. raise error.InterventionRequired(
  302. _('unresolved conflicts (see hg '
  303. 'resolve, then hg rebase --continue)'))
  304. finally:
  305. ui.setconfig('ui', 'forcemerge', '', 'rebase')
  306. if collapsef:
  307. cmdutil.duplicatecopies(repo, rev, target)
  308. else:
  309. # If we're not using --collapse, we need to
  310. # duplicate copies between the revision we're
  311. # rebasing and its first parent, but *not*
  312. # duplicate any copies that have already been
  313. # performed in the destination.
  314. p1rev = repo[rev].p1().rev()
  315. cmdutil.duplicatecopies(repo, rev, p1rev, skiprev=target)
  316. if not collapsef:
  317. newrev = concludenode(repo, rev, p1, p2, extrafn=extrafn,
  318. editor=editor)
  319. else:
  320. # Skip commit if we are collapsing
  321. repo.setparents(repo[p1].node())
  322. newrev = None
  323. # Update the state
  324. if newrev is not None:
  325. state[rev] = repo[newrev].rev()
  326. else:
  327. if not collapsef:
  328. ui.note(_('no changes, revision %d skipped\n') % rev)
  329. ui.debug('next revision set to %s\n' % p1)
  330. skipped.add(rev)
  331. state[rev] = p1
  332. ui.progress(_('rebasing'), None)
  333. ui.note(_('rebase merging completed\n'))
  334. if collapsef and not keepopen:
  335. p1, p2 = defineparents(repo, min(state), target,
  336. state, targetancestors)
  337. if collapsemsg:
  338. commitmsg = collapsemsg
  339. else:
  340. commitmsg = 'Collapsed revision'
  341. for rebased in state:
  342. if rebased not in skipped and state[rebased] > nullmerge:
  343. commitmsg += '\n* %s' % repo[rebased].description()
  344. editor = cmdutil.getcommiteditor(edit=True)
  345. newrev = concludenode(repo, rev, p1, external, commitmsg=commitmsg,
  346. extrafn=extrafn, editor=editor)
  347. for oldrev in state.iterkeys():
  348. if state[oldrev] > nullmerge:
  349. state[oldrev] = newrev
  350. if 'qtip' in repo.tags():
  351. updatemq(repo, state, skipped, **opts)
  352. if currentbookmarks:
  353. # Nodeids are needed to reset bookmarks
  354. nstate = {}
  355. for k, v in state.iteritems():
  356. if v > nullmerge:
  357. nstate[repo[k].node()] = repo[v].node()
  358. # XXX this is the same as dest.node() for the non-continue path --
  359. # this should probably be cleaned up
  360. targetnode = repo[target].node()
  361. # restore original working directory
  362. # (we do this before stripping)
  363. newwd = state.get(originalwd, originalwd)
  364. if newwd not in [c.rev() for c in repo[None].parents()]:
  365. ui.note(_("update back to initial working directory parent\n"))
  366. hg.updaterepo(repo, newwd, False)
  367. if not keepf:
  368. collapsedas = None
  369. if collapsef:
  370. collapsedas = newrev
  371. clearrebased(ui, repo, state, skipped, collapsedas)
  372. if currentbookmarks:
  373. updatebookmarks(repo, targetnode, nstate, currentbookmarks)
  374. if activebookmark not in repo._bookmarks:
  375. # active bookmark was divergent one and has been deleted
  376. activebookmark = None
  377. clearstatus(repo)
  378. ui.note(_("rebase completed\n"))
  379. util.unlinkpath(repo.sjoin('undo'), ignoremissing=True)
  380. if skipped:
  381. ui.note(_("%d revisions have been skipped\n") % len(skipped))
  382. if (activebookmark and
  383. repo['.'].node() == repo._bookmarks[activebookmark]):
  384. bookmarks.setcurrent(repo, activebookmark)
  385. finally:
  386. release(lock, wlock)
  387. def externalparent(repo, state, targetancestors):
  388. """Return the revision that should be used as the second parent
  389. when the revisions in state is collapsed on top of targetancestors.
  390. Abort if there is more than one parent.
  391. """
  392. parents = set()
  393. source = min(state)
  394. for rev in state:
  395. if rev == source:
  396. continue
  397. for p in repo[rev].parents():
  398. if (p.rev() not in state
  399. and p.rev() not in targetancestors):
  400. parents.add(p.rev())
  401. if not parents:
  402. return nullrev
  403. if len(parents) == 1:
  404. return parents.pop()
  405. raise util.Abort(_('unable to collapse on top of %s, there is more '
  406. 'than one external parent: %s') %
  407. (max(targetancestors),
  408. ', '.join(str(p) for p in sorted(parents))))
  409. def concludenode(repo, rev, p1, p2, commitmsg=None, editor=None, extrafn=None):
  410. 'Commit the changes and store useful information in extra'
  411. try:
  412. repo.setparents(repo[p1].node(), repo[p2].node())
  413. ctx = repo[rev]
  414. if commitmsg is None:
  415. commitmsg = ctx.description()
  416. extra = {'rebase_source': ctx.hex()}
  417. if extrafn:
  418. extrafn(ctx, extra)
  419. # Commit might fail if unresolved files exist
  420. newrev = repo.commit(text=commitmsg, user=ctx.user(),
  421. date=ctx.date(), extra=extra, editor=editor)
  422. repo.dirstate.setbranch(repo[newrev].branch())
  423. targetphase = max(ctx.phase(), phases.draft)
  424. # retractboundary doesn't overwrite upper phase inherited from parent
  425. newnode = repo[newrev].node()
  426. if newnode:
  427. phases.retractboundary(repo, targetphase, [newnode])
  428. return newrev
  429. except util.Abort:
  430. # Invalidate the previous setparents
  431. repo.dirstate.invalidate()
  432. raise
  433. def rebasenode(repo, rev, p1, state, collapse):
  434. 'Rebase a single revision'
  435. # Merge phase
  436. # Update to target and merge it with local
  437. if repo['.'].rev() != repo[p1].rev():
  438. repo.ui.debug(" update to %d:%s\n" % (repo[p1].rev(), repo[p1]))
  439. merge.update(repo, p1, False, True, False)
  440. else:
  441. repo.ui.debug(" already in target\n")
  442. repo.dirstate.write()
  443. repo.ui.debug(" merge against %d:%s\n" % (repo[rev].rev(), repo[rev]))
  444. if repo[rev].rev() == repo[min(state)].rev():
  445. # Case (1) initial changeset of a non-detaching rebase.
  446. # Let the merge mechanism find the base itself.
  447. base = None
  448. elif not repo[rev].p2():
  449. # Case (2) detaching the node with a single parent, use this parent
  450. base = repo[rev].p1().node()
  451. else:
  452. # In case of merge, we need to pick the right parent as merge base.
  453. #
  454. # Imagine we have:
  455. # - M: currently rebase revision in this step
  456. # - A: one parent of M
  457. # - B: second parent of M
  458. # - D: destination of this merge step (p1 var)
  459. #
  460. # If we are rebasing on D, D is the successors of A or B. The right
  461. # merge base is the one D succeed to. We pretend it is B for the rest
  462. # of this comment
  463. #
  464. # If we pick B as the base, the merge involves:
  465. # - changes from B to M (actual changeset payload)
  466. # - changes from B to D (induced by rebase) as D is a rebased
  467. # version of B)
  468. # Which exactly represent the rebase operation.
  469. #
  470. # If we pick the A as the base, the merge involves
  471. # - changes from A to M (actual changeset payload)
  472. # - changes from A to D (with include changes between unrelated A and B
  473. # plus changes induced by rebase)
  474. # Which does not represent anything sensible and creates a lot of
  475. # conflicts.
  476. for p in repo[rev].parents():
  477. if state.get(p.rev()) == repo[p1].rev():
  478. base = p.node()
  479. break
  480. else: # fallback when base not found
  481. base = None
  482. # Raise because this function is called wrong (see issue 4106)
  483. raise AssertionError('no base found to rebase on '
  484. '(rebasenode called wrong)')
  485. if base is not None:
  486. repo.ui.debug(" detach base %d:%s\n" % (repo[base].rev(), repo[base]))
  487. # When collapsing in-place, the parent is the common ancestor, we
  488. # have to allow merging with it.
  489. return merge.update(repo, rev, True, True, False, base, collapse,
  490. labels=['dest', 'source'])
  491. def nearestrebased(repo, rev, state):
  492. """return the nearest ancestors of rev in the rebase result"""
  493. rebased = [r for r in state if state[r] > nullmerge]
  494. candidates = repo.revs('max(%ld and (::%d))', rebased, rev)
  495. if candidates:
  496. return state[candidates[0]]
  497. else:
  498. return None
  499. def defineparents(repo, rev, target, state, targetancestors):
  500. 'Return the new parent relationship of the revision that will be rebased'
  501. parents = repo[rev].parents()
  502. p1 = p2 = nullrev
  503. P1n = parents[0].rev()
  504. if P1n in targetancestors:
  505. p1 = target
  506. elif P1n in state:
  507. if state[P1n] == nullmerge:
  508. p1 = target
  509. elif state[P1n] == revignored:
  510. p1 = nearestrebased(repo, P1n, state)
  511. if p1 is None:
  512. p1 = target
  513. else:
  514. p1 = state[P1n]
  515. else: # P1n external
  516. p1 = target
  517. p2 = P1n
  518. if len(parents) == 2 and parents[1].rev() not in targetancestors:
  519. P2n = parents[1].rev()
  520. # interesting second parent
  521. if P2n in state:
  522. if p1 == target: # P1n in targetancestors or external
  523. p1 = state[P2n]
  524. elif state[P2n] == revignored:
  525. p2 = nearestrebased(repo, P2n, state)
  526. if p2 is None:
  527. # no ancestors rebased yet, detach
  528. p2 = target
  529. else:
  530. p2 = state[P2n]
  531. else: # P2n external
  532. if p2 != nullrev: # P1n external too => rev is a merged revision
  533. raise util.Abort(_('cannot use revision %d as base, result '
  534. 'would have 3 parents') % rev)
  535. p2 = P2n
  536. repo.ui.debug(" future parents are %d and %d\n" %
  537. (repo[p1].rev(), repo[p2].rev()))
  538. return p1, p2
  539. def isagitpatch(repo, patchname):
  540. 'Return true if the given patch is in git format'
  541. mqpatch = os.path.join(repo.mq.path, patchname)
  542. for line in patch.linereader(file(mqpatch, 'rb')):
  543. if line.startswith('diff --git'):
  544. return True
  545. return False
  546. def updatemq(repo, state, skipped, **opts):
  547. 'Update rebased mq patches - finalize and then import them'
  548. mqrebase = {}
  549. mq = repo.mq
  550. original_series = mq.fullseries[:]
  551. skippedpatches = set()
  552. for p in mq.applied:
  553. rev = repo[p.node].rev()
  554. if rev in state:
  555. repo.ui.debug('revision %d is an mq patch (%s), finalize it.\n' %
  556. (rev, p.name))
  557. mqrebase[rev] = (p.name, isagitpatch(repo, p.name))
  558. else:
  559. # Applied but not rebased, not sure this should happen
  560. skippedpatches.add(p.name)
  561. if mqrebase:
  562. mq.finish(repo, mqrebase.keys())
  563. # We must start import from the newest revision
  564. for rev in sorted(mqrebase, reverse=True):
  565. if rev not in skipped:
  566. name, isgit = mqrebase[rev]
  567. repo.ui.debug('import mq patch %d (%s)\n' % (state[rev], name))
  568. mq.qimport(repo, (), patchname=name, git=isgit,
  569. rev=[str(state[rev])])
  570. else:
  571. # Rebased and skipped
  572. skippedpatches.add(mqrebase[rev][0])
  573. # Patches were either applied and rebased and imported in
  574. # order, applied and removed or unapplied. Discard the removed
  575. # ones while preserving the original series order and guards.
  576. newseries = [s for s in original_series
  577. if mq.guard_re.split(s, 1)[0] not in skippedpatches]
  578. mq.fullseries[:] = newseries
  579. mq.seriesdirty = True
  580. mq.savedirty()
  581. def updatebookmarks(repo, targetnode, nstate, originalbookmarks):
  582. 'Move bookmarks to their correct changesets, and delete divergent ones'
  583. marks = repo._bookmarks
  584. for k, v in originalbookmarks.iteritems():
  585. if v in nstate:
  586. # update the bookmarks for revs that have moved
  587. marks[k] = nstate[v]
  588. bookmarks.deletedivergent(repo, [targetnode], k)
  589. marks.write()
  590. def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches,
  591. external, activebookmark):
  592. 'Store the current status to allow recovery'
  593. f = repo.opener("rebasestate", "w")
  594. f.write(repo[originalwd].hex() + '\n')
  595. f.write(repo[target].hex() + '\n')
  596. f.write(repo[external].hex() + '\n')
  597. f.write('%d\n' % int(collapse))
  598. f.write('%d\n' % int(keep))
  599. f.write('%d\n' % int(keepbranches))
  600. f.write('%s\n' % (activebookmark or ''))
  601. for d, v in state.iteritems():
  602. oldrev = repo[d].hex()
  603. if v > nullmerge:
  604. newrev = repo[v].hex()
  605. else:
  606. newrev = v
  607. f.write("%s:%s\n" % (oldrev, newrev))
  608. f.close()
  609. repo.ui.debug('rebase status stored\n')
  610. def clearstatus(repo):
  611. 'Remove the status files'
  612. util.unlinkpath(repo.join("rebasestate"), ignoremissing=True)
  613. def restorestatus(repo):
  614. 'Restore a previously stored status'
  615. try:
  616. keepbranches = None
  617. target = None
  618. collapse = False
  619. external = nullrev
  620. activebookmark = None
  621. state = {}
  622. f = repo.opener("rebasestate")
  623. for i, l in enumerate(f.read().splitlines()):
  624. if i == 0:
  625. originalwd = repo[l].rev()
  626. elif i == 1:
  627. target = repo[l].rev()
  628. elif i == 2:
  629. external = repo[l].rev()
  630. elif i == 3:
  631. collapse = bool(int(l))
  632. elif i == 4:
  633. keep = bool(int(l))
  634. elif i == 5:
  635. keepbranches = bool(int(l))
  636. elif i == 6 and not (len(l) == 81 and ':' in l):
  637. # line 6 is a recent addition, so for backwards compatibility
  638. # check that the line doesn't look like the oldrev:newrev lines
  639. activebookmark = l
  640. else:
  641. oldrev, newrev = l.split(':')
  642. if newrev in (str(nullmerge), str(revignored)):
  643. state[repo[oldrev].rev()] = int(newrev)
  644. else:
  645. state[repo[oldrev].rev()] = repo[newrev].rev()
  646. if keepbranches is None:
  647. raise util.Abort(_('.hg/rebasestate is incomplete'))
  648. skipped = set()
  649. # recompute the set of skipped revs
  650. if not collapse:
  651. seen = set([target])
  652. for old, new in sorted(state.items()):
  653. if new != nullrev and new in seen:
  654. skipped.add(old)
  655. seen.add(new)
  656. repo.ui.debug('computed skipped revs: %s\n' %
  657. (' '.join(str(r) for r in sorted(skipped)) or None))
  658. repo.ui.debug('rebase status resumed\n')
  659. return (originalwd, target, state, skipped,
  660. collapse, keep, keepbranches, external, activebookmark)
  661. except IOError, err:
  662. if err.errno != errno.ENOENT:
  663. raise
  664. raise util.Abort(_('no rebase in progress'))
  665. def inrebase(repo, originalwd, state):
  666. '''check whether the working dir is in an interrupted rebase'''
  667. parents = [p.rev() for p in repo.parents()]
  668. if originalwd in parents:
  669. return True
  670. for newrev in state.itervalues():
  671. if newrev in parents:
  672. return True
  673. return False
  674. def abort(repo, originalwd, target, state):
  675. 'Restore the repository to its original state'
  676. dstates = [s for s in state.values() if s > nullrev]
  677. immutable = [d for d in dstates if not repo[d].mutable()]
  678. cleanup = True
  679. if immutable:
  680. repo.ui.warn(_("warning: can't clean up immutable changesets %s\n")
  681. % ', '.join(str(repo[r]) for r in immutable),
  682. hint=_('see hg help phases for details'))
  683. cleanup = False
  684. descendants = set()
  685. if dstates:
  686. descendants = set(repo.changelog.descendants(dstates))
  687. if descendants - set(dstates):
  688. repo.ui.warn(_("warning: new changesets detected on target branch, "
  689. "can't strip\n"))
  690. cleanup = False
  691. if cleanup:
  692. # Update away from the rebase if necessary
  693. if inrebase(repo, originalwd, state):
  694. merge.update(repo, repo[originalwd].rev(), False, True, False)
  695. # Strip from the first rebased revision
  696. rebased = filter(lambda x: x > -1 and x != target, state.values())
  697. if rebased:
  698. strippoints = [c.node() for c in repo.set('roots(%ld)', rebased)]
  699. # no backup of rebased cset versions needed
  700. repair.strip(repo.ui, repo, strippoints)
  701. clearstatus(repo)
  702. repo.ui.warn(_('rebase aborted\n'))
  703. return 0
  704. def buildstate(repo, dest, rebaseset, collapse):
  705. '''Define which revisions are going to be rebased and where
  706. repo: repo
  707. dest: context
  708. rebaseset: set of rev
  709. '''
  710. # This check isn't strictly necessary, since mq detects commits over an
  711. # applied patch. But it prevents messing up the working directory when
  712. # a partially completed rebase is blocked by mq.
  713. if 'qtip' in repo.tags() and (dest.node() in
  714. [s.node for s in repo.mq.applied]):
  715. raise util.Abort(_('cannot rebase onto an applied mq patch'))
  716. roots = list(repo.set('roots(%ld)', rebaseset))
  717. if not roots:
  718. raise util.Abort(_('no matching revisions'))
  719. roots.sort()
  720. state = {}
  721. detachset = set()
  722. for root in roots:
  723. commonbase = root.ancestor(dest)
  724. if commonbase == root:
  725. raise util.Abort(_('source is ancestor of destination'))
  726. if commonbase == dest:
  727. samebranch = root.branch() == dest.branch()
  728. if not collapse and samebranch and root in dest.children():
  729. repo.ui.debug('source is a child of destination\n')
  730. return None
  731. repo.ui.debug('rebase onto %d starting from %s\n' % (dest, root))
  732. state.update(dict.fromkeys(rebaseset, nullrev))
  733. # Rebase tries to turn <dest> into a parent of <root> while
  734. # preserving the number of parents of rebased changesets:
  735. #
  736. # - A changeset with a single parent will always be rebased as a
  737. # changeset with a single parent.
  738. #
  739. # - A merge will be rebased as merge unless its parents are both
  740. # ancestors of <dest> or are themselves in the rebased set and
  741. # pruned while rebased.
  742. #
  743. # If one parent of <root> is an ancestor of <dest>, the rebased
  744. # version of this parent will be <dest>. This is always true with
  745. # --base option.
  746. #
  747. # Otherwise, we need to *replace* the original parents with
  748. # <dest>. This "detaches" the rebased set from its former location
  749. # and rebases it onto <dest>. Changes introduced by ancestors of
  750. # <root> not common with <dest> (the detachset, marked as
  751. # nullmerge) are "removed" from the rebased changesets.
  752. #
  753. # - If <root> has a single parent, set it to <dest>.
  754. #
  755. # - If <root> is a merge, we cannot decide which parent to
  756. # replace, the rebase operation is not clearly defined.
  757. #
  758. # The table below sums up this behavior:
  759. #
  760. # +------------------+----------------------+-------------------------+
  761. # | | one parent | merge |
  762. # +------------------+----------------------+-------------------------+
  763. # | parent in | new parent is <dest> | parents in ::<dest> are |
  764. # | ::<dest> | | remapped to <dest> |
  765. # +------------------+----------------------+-------------------------+
  766. # | unrelated source | new parent is <dest> | ambiguous, abort |
  767. # +------------------+----------------------+-------------------------+
  768. #
  769. # The actual abort is handled by `defineparents`
  770. if len(root.parents()) <= 1:
  771. # ancestors of <root> not ancestors of <dest>
  772. detachset.update(repo.changelog.findmissingrevs([commonbase.rev()],
  773. [root.rev()]))
  774. for r in detachset:
  775. if r not in state:
  776. state[r] = nullmerge
  777. if len(roots) > 1:
  778. # If we have multiple roots, we may have "hole" in the rebase set.
  779. # Rebase roots that descend from those "hole" should not be detached as
  780. # other root are. We use the special `revignored` to inform rebase that
  781. # the revision should be ignored but that `defineparents` should search
  782. # a rebase destination that make sense regarding rebased topology.
  783. rebasedomain = set(repo.revs('%ld::%ld', rebaseset, rebaseset))
  784. for ignored in set(rebasedomain) - set(rebaseset):
  785. state[ignored] = revignored
  786. return repo['.'].rev(), dest.rev(), state
  787. def clearrebased(ui, repo, state, skipped, collapsedas=None):
  788. """dispose of rebased revision at the end of the rebase
  789. If `collapsedas` is not None, the rebase was a collapse whose result if the
  790. `collapsedas` node."""
  791. if obsolete._enabled:
  792. markers = []
  793. for rev, newrev in sorted(state.items()):
  794. if newrev >= 0:
  795. if rev in skipped:
  796. succs = ()
  797. elif collapsedas is not None:
  798. succs = (repo[collapsedas],)
  799. else:
  800. succs = (repo[newrev],)
  801. markers.append((repo[rev], succs))
  802. if markers:
  803. obsolete.createmarkers(repo, markers)
  804. else:
  805. rebased = [rev for rev in state if state[rev] > nullmerge]
  806. if rebased:
  807. stripped = []
  808. for root in repo.set('roots(%ld)', rebased):
  809. if set(repo.changelog.descendants([root.rev()])) - set(state):
  810. ui.warn(_("warning: new changesets detected "
  811. "on source branch, not stripping\n"))
  812. else:
  813. stripped.append(root.node())
  814. if stripped:
  815. # backup the old csets by default
  816. repair.strip(ui, repo, stripped, "all")
  817. def pullrebase(orig, ui, repo, *args, **opts):
  818. 'Call rebase after pull if the latter has been invoked with --rebase'
  819. if opts.get('rebase'):
  820. if opts.get('update'):
  821. del opts['update']
  822. ui.debug('--update and --rebase are not compatible, ignoring '
  823. 'the update flag\n')
  824. movemarkfrom = repo['.'].node()
  825. revsprepull = len(repo)
  826. origpostincoming = commands.postincoming
  827. def _dummy(*args, **kwargs):
  828. pass
  829. commands.postincoming = _dummy
  830. try:
  831. orig(ui, repo, *args, **opts)
  832. finally:
  833. commands.postincoming = origpostincoming
  834. revspostpull = len(repo)
  835. if revspostpull > revsprepull:
  836. # --rev option from pull conflict with rebase own --rev
  837. # dropping it
  838. if 'rev' in opts:
  839. del opts['rev']
  840. rebase(ui, repo, **opts)
  841. branch = repo[None].branch()
  842. dest = repo[branch].rev()
  843. if dest != repo['.'].rev():
  844. # there was nothing to rebase we force an update
  845. hg.update(repo, dest)
  846. if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
  847. ui.status(_("updating bookmark %s\n")
  848. % repo._bookmarkcurrent)
  849. else:
  850. if opts.get('tool'):
  851. raise util.Abort(_('--tool can only be used with --rebase'))
  852. orig(ui, repo, *args, **opts)
  853. def summaryhook(ui, repo):
  854. if not os.path.exists(repo.join('rebasestate')):
  855. return
  856. try:
  857. state = restorestatus(repo)[2]
  858. except error.RepoLookupError:
  859. # i18n: column positioning for "hg summary"
  860. msg = _('rebase: (use "hg rebase --abort" to clear broken state)\n')
  861. ui.write(msg)
  862. return
  863. numrebased = len([i for i in state.itervalues() if i != -1])
  864. # i18n: column positioning for "hg summary"
  865. ui.write(_('rebase: %s, %s (rebase --continue)\n') %
  866. (ui.label(_('%d rebased'), 'rebase.rebased') % numrebased,
  867. ui.label(_('%d remaining'), 'rebase.remaining') %
  868. (len(state) - numrebased)))
  869. def uisetup(ui):
  870. 'Replace pull with a decorator to provide --rebase option'
  871. entry = extensions.wrapcommand(commands.table, 'pull', pullrebase)
  872. entry[1].append(('', 'rebase', None,
  873. _("rebase working directory to branch head")))
  874. entry[1].append(('t', 'tool', '',
  875. _("specify merge tool for rebase")))
  876. cmdutil.summaryhooks.add('rebase', summaryhook)
  877. cmdutil.unfinishedstates.append(
  878. ['rebasestate', False, False, _('rebase in progress'),
  879. _("use 'hg rebase --continue' or 'hg rebase --abort'")])