Debian Codegraph @

hgext/rebase.py

raw
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
8 '''command to move sets of revisions to a different ancestor
9
10 This extension lets you rebase changesets in an existing Mercurial
11 repository.
12
13 For more information:
14 https://mercurial-scm.org/wiki/RebaseExtension
15 '''
16
17 from __future__ import annotations
18
19 import os
20
21 from mercurial.i18n import _
22 from mercurial.node import (
23 nullrev,
24 short,
25 wdirrev,
26 )
27 from mercurial import (
28 bookmarks,
29 cmdutil,
30 commands,
31 copies,
32 destutil,
33 error,
34 extensions,
35 logcmdutil,
36 merge as mergemod,
37 mergestate as mergestatemod,
38 mergeutil,
39 obsolete,
40 obsutil,
41 patch,
42 phases,
43 pycompat,
44 registrar,
45 repair,
46 revset,
47 revsetlang,
48 rewriteutil,
49 scmutil,
50 smartset,
51 state as statemod,
52 util,
53 )
54
55
56 # The following constants are used throughout the rebase module. The ordering of
57 # their values must be maintained.
58
59 # Indicates that a revision needs to be rebased
60 revtodo = -1
61 revtodostr = b'-1'
62
63 # legacy revstates no longer needed in current code
64 # -2: nullmerge, -3: revignored, -4: revprecursor, -5: revpruned
65 legacystates = {b'-2', b'-3', b'-4', b'-5'}
66
67 cmdtable = {}
68 command = registrar.command(cmdtable)
69
70 configtable = {}
71 configitem = registrar.configitem(configtable)
72 configitem(
73 b'devel',
74 b'rebase.force-in-memory-merge',
75 default=False,
76 )
77 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
78 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
79 # be specifying the version(s) of Mercurial they are tested with, or
80 # leave the attribute unspecified.
81 testedwith = b'ships-with-hg-core'
82
83
84 def _nothingtorebase():
85 return 1
86
87
88 def _savebranch(ctx, extra):
89 extra[b'branch'] = ctx.branch()
90
91
92 def _destrebase(repo, sourceset, destspace=None):
93 """small wrapper around destmerge to pass the right extra args
94
95 Please wrap destutil.destmerge instead."""
96 return destutil.destmerge(
97 repo,
98 action=b'rebase',
99 sourceset=sourceset,
100 onheadcheck=False,
101 destspace=destspace,
102 )
103
104
105 revsetpredicate = registrar.revsetpredicate()
106
107
108 @revsetpredicate(b'_destrebase')
109 def _revsetdestrebase(repo, subset, x):
110 # ``_rebasedefaultdest()``
111
112 # default destination for rebase.
113 # # XXX: Currently private because I expect the signature to change.
114 # # XXX: - bailing out in case of ambiguity vs returning all data.
115 # i18n: "_rebasedefaultdest" is a keyword
116 sourceset = None
117 if x is not None:
118 sourceset = revset.getset(repo, smartset.fullreposet(repo), x)
119 return subset & smartset.baseset([_destrebase(repo, sourceset)])
120
121
122 @revsetpredicate(b'_destautoorphanrebase')
123 def _revsetdestautoorphanrebase(repo, subset, x):
124 # ``_destautoorphanrebase()``
125
126 # automatic rebase destination for a single orphan revision.
127 unfi = repo.unfiltered()
128 obsoleted = unfi.revs(b'obsolete()')
129
130 src = revset.getset(repo, subset, x).first()
131
132 # Empty src or already obsoleted - Do not return a destination
133 if not src or src in obsoleted:
134 return smartset.baseset()
135 dests = destutil.orphanpossibledestination(repo, src)
136 if len(dests) > 1:
137 raise error.StateError(
138 _(b"ambiguous automatic rebase: %r could end up on any of %r")
139 % (src, dests)
140 )
141 # We have zero or one destination, so we can just return here.
142 return smartset.baseset(dests)
143
144
145 def _ctxdesc(ctx):
146 """short description for a context"""
147 return cmdutil.format_changeset_summary(
148 ctx.repo().ui, ctx, command=b'rebase'
149 )
150
151
152 class rebaseruntime:
153 """This class is a container for rebase runtime state"""
154
155 def __init__(self, repo, ui, inmemory=False, dryrun=False, opts=None):
156 if opts is None:
157 opts = {}
158
159 # prepared: whether we have rebasestate prepared or not. Currently it
160 # decides whether "self.repo" is unfiltered or not.
161 # The rebasestate has explicit hash to hash instructions not depending
162 # on visibility. If rebasestate exists (in-memory or on-disk), use
163 # unfiltered repo to avoid visibility issues.
164 # Before knowing rebasestate (i.e. when starting a new rebase (not
165 # --continue or --abort)), the original repo should be used so
166 # visibility-dependent revsets are correct.
167 self.prepared = False
168 self.resume = False
169 self._repo = repo
170
171 self.ui = ui
172 self.opts = opts
173 self.originalwd = None
174 self.external = nullrev
175 # Mapping between the old revision id and either what is the new rebased
176 # revision or what needs to be done with the old revision. The state
177 # dict will be what contains most of the rebase progress state.
178 self.state = {}
179 self.activebookmark = None
180 self.destmap = {}
181 self.skipped = set()
182
183 self.collapsef = opts.get('collapse', False)
184 self.collapsemsg = cmdutil.logmessage(ui, pycompat.byteskwargs(opts))
185 self.date = opts.get('date', None)
186
187 e = opts.get('extrafn') # internal, used by e.g. hgsubversion
188 self.extrafns = [rewriteutil.preserve_extras_on_rebase]
189 if e:
190 self.extrafns = [e]
191
192 self.backupf = ui.configbool(b'rewrite', b'backup-bundle')
193 self.keepf = opts.get('keep', False)
194 self.keepbranchesf = opts.get('keepbranches', False)
195 self.skipemptysuccessorf = rewriteutil.skip_empty_successor(
196 repo.ui, b'rebase'
197 )
198 self.obsolete_with_successor_in_destination = {}
199 self.obsolete_with_successor_in_rebase_set = set()
200 self.inmemory = inmemory
201 self.dryrun = dryrun
202 self.stateobj = statemod.cmdstate(repo, b'rebasestate')
203
204 @property
205 def repo(self):
206 if self.prepared:
207 return self._repo.unfiltered()
208 else:
209 return self._repo
210
211 def storestatus(self, tr=None):
212 """Store the current status to allow recovery"""
213 if tr:
214 tr.addfilegenerator(
215 b'rebasestate',
216 (b'rebasestate',),
217 self._writestatus,
218 location=b'plain',
219 )
220 else:
221 with self.repo.vfs(b"rebasestate", b"w") as f:
222 self._writestatus(f)
223
224 def _writestatus(self, f):
225 repo = self.repo
226 assert repo.filtername is None
227 f.write(repo[self.originalwd].hex() + b'\n')
228 # was "dest". we now write dest per src root below.
229 f.write(b'\n')
230 f.write(repo[self.external].hex() + b'\n')
231 f.write(b'%d\n' % int(self.collapsef))
232 f.write(b'%d\n' % int(self.keepf))
233 f.write(b'%d\n' % int(self.keepbranchesf))
234 f.write(b'%s\n' % (self.activebookmark or b''))
235 destmap = self.destmap
236 for d, v in self.state.items():
237 oldrev = repo[d].hex()
238 if v >= 0:
239 newrev = repo[v].hex()
240 else:
241 newrev = b"%d" % v
242 destnode = repo[destmap[d]].hex()
243 f.write(b"%s:%s:%s\n" % (oldrev, newrev, destnode))
244 repo.ui.debug(b'rebase status stored\n')
245
246 def restorestatus(self):
247 """Restore a previously stored status"""
248 if not self.stateobj.exists():
249 cmdutil.wrongtooltocontinue(self.repo, _(b'rebase'))
250
251 data = self._read()
252 self.repo.ui.debug(b'rebase status resumed\n')
253
254 self.originalwd = data[b'originalwd']
255 self.destmap = data[b'destmap']
256 self.state = data[b'state']
257 self.skipped = data[b'skipped']
258 self.collapsef = data[b'collapse']
259 self.keepf = data[b'keep']
260 self.keepbranchesf = data[b'keepbranches']
261 self.external = data[b'external']
262 self.activebookmark = data[b'activebookmark']
263
264 def _read(self):
265 self.prepared = True
266 repo = self.repo
267 assert repo.filtername is None
268 data = {
269 b'keepbranches': None,
270 b'collapse': None,
271 b'activebookmark': None,
272 b'external': nullrev,
273 b'keep': None,
274 b'originalwd': None,
275 }
276 legacydest = None
277 state = {}
278 destmap = {}
279
280 if True:
281 f = repo.vfs(b"rebasestate")
282 for i, l in enumerate(f.read().splitlines()):
283 if i == 0:
284 data[b'originalwd'] = repo[l].rev()
285 elif i == 1:
286 # this line should be empty in newer version. but legacy
287 # clients may still use it
288 if l:
289 legacydest = repo[l].rev()
290 elif i == 2:
291 data[b'external'] = repo[l].rev()
292 elif i == 3:
293 data[b'collapse'] = bool(int(l))
294 elif i == 4:
295 data[b'keep'] = bool(int(l))
296 elif i == 5:
297 data[b'keepbranches'] = bool(int(l))
298 elif i == 6 and not (len(l) == 81 and b':' in l):
299 # line 6 is a recent addition, so for backwards
300 # compatibility check that the line doesn't look like the
301 # oldrev:newrev lines
302 data[b'activebookmark'] = l
303 else:
304 args = l.split(b':')
305 oldrev = repo[args[0]].rev()
306 newrev = args[1]
307 if newrev in legacystates:
308 continue
309 if len(args) > 2:
310 destrev = repo[args[2]].rev()
311 else:
312 destrev = legacydest
313 destmap[oldrev] = destrev
314 if newrev == revtodostr:
315 state[oldrev] = revtodo
316 # Legacy compat special case
317 else:
318 state[oldrev] = repo[newrev].rev()
319
320 if data[b'keepbranches'] is None:
321 raise error.Abort(_(b'.hg/rebasestate is incomplete'))
322
323 data[b'destmap'] = destmap
324 data[b'state'] = state
325 skipped = set()
326 # recompute the set of skipped revs
327 if not data[b'collapse']:
328 seen = set(destmap.values())
329 for old, new in sorted(state.items()):
330 if new != revtodo and new in seen:
331 skipped.add(old)
332 seen.add(new)
333 data[b'skipped'] = skipped
334 repo.ui.debug(
335 b'computed skipped revs: %s\n'
336 % (b' '.join(b'%d' % r for r in sorted(skipped)) or b'')
337 )
338
339 return data
340
341 def _handleskippingobsolete(self):
342 """Compute structures necessary for skipping obsolete revisions"""
343 if self.keepf:
344 return
345 if not self.ui.configbool(b'experimental', b'rebaseskipobsolete'):
346 return
347 obsoleteset = {r for r in self.state if self.repo[r].obsolete()}
348 (
349 self.obsolete_with_successor_in_destination,
350 self.obsolete_with_successor_in_rebase_set,
351 ) = _compute_obsolete_sets(self.repo, obsoleteset, self.destmap)
352 skippedset = set(self.obsolete_with_successor_in_destination)
353 skippedset.update(self.obsolete_with_successor_in_rebase_set)
354 _checkobsrebase(self.repo, self.ui, obsoleteset, skippedset)
355 if obsolete.isenabled(self.repo, obsolete.allowdivergenceopt):
356 self.obsolete_with_successor_in_rebase_set = set()
357 else:
358 for rev in self.repo.revs(
359 b'descendants(%ld) and not %ld',
360 self.obsolete_with_successor_in_rebase_set,
361 self.obsolete_with_successor_in_rebase_set,
362 ):
363 self.state.pop(rev, None)
364 self.destmap.pop(rev, None)
365
366 def _prepareabortorcontinue(
367 self, isabort, backup=True, suppwarns=False, dryrun=False, confirm=False
368 ):
369 self.resume = True
370 try:
371 self.restorestatus()
372 # Calculate self.obsolete_* sets
373 self._handleskippingobsolete()
374 self.collapsemsg = restorecollapsemsg(self.repo, isabort)
375 except error.RepoLookupError:
376 if isabort:
377 clearstatus(self.repo)
378 clearcollapsemsg(self.repo)
379 self.repo.ui.warn(
380 _(
381 b'rebase aborted (no revision is removed,'
382 b' only broken state is cleared)\n'
383 )
384 )
385 return 0
386 else:
387 msg = _(b'cannot continue inconsistent rebase')
388 hint = _(b'use "hg rebase --abort" to clear broken state')
389 raise error.Abort(msg, hint=hint)
390
391 if isabort:
392 backup = backup and self.backupf
393 return self._abort(
394 backup=backup,
395 suppwarns=suppwarns,
396 dryrun=dryrun,
397 confirm=confirm,
398 )
399
400 def _preparenewrebase(self, destmap):
401 if not destmap:
402 return _nothingtorebase()
403
404 result = buildstate(self.repo, destmap, self.collapsef)
405
406 if not result:
407 # Empty state built, nothing to rebase
408 self.ui.status(_(b'nothing to rebase\n'))
409 return _nothingtorebase()
410
411 (self.originalwd, self.destmap, self.state) = result
412 if self.collapsef:
413 dests = set(self.destmap.values())
414 if len(dests) != 1:
415 raise error.InputError(
416 _(b'--collapse does not work with multiple destinations')
417 )
418 destrev = next(iter(dests))
419 destancestors = self.repo.changelog.ancestors(
420 [destrev], inclusive=True
421 )
422 self.external = externalparent(self.repo, self.state, destancestors)
423
424 for destrev in sorted(set(destmap.values())):
425 dest = self.repo[destrev]
426 if dest.closesbranch() and not self.keepbranchesf:
427 self.ui.status(_(b'reopening closed branch head %s\n') % dest)
428
429 # Calculate self.obsolete_* sets
430 self._handleskippingobsolete()
431
432 if not self.keepf:
433 rebaseset = set(destmap.keys())
434 rebaseset -= set(self.obsolete_with_successor_in_destination)
435 rebaseset -= self.obsolete_with_successor_in_rebase_set
436 # We have our own divergence-checking in the rebase extension
437 overrides = {}
438 if obsolete.isenabled(self.repo, obsolete.createmarkersopt):
439 overrides = {
440 (b'experimental', b'evolution.allowdivergence'): b'true'
441 }
442 try:
443 with self.ui.configoverride(overrides):
444 rewriteutil.precheck(self.repo, rebaseset, action=b'rebase')
445 except error.Abort as e:
446 if e.hint is None:
447 e.hint = _(b'use --keep to keep original changesets')
448 raise e
449
450 self.prepared = True
451
452 def _assignworkingcopy(self):
453 if self.inmemory:
454 from mercurial.context import overlayworkingctx
455
456 self.wctx = overlayworkingctx(self.repo)
457 self.repo.ui.debug(b"rebasing in memory\n")
458 else:
459 self.wctx = self.repo[None]
460 self.repo.ui.debug(b"rebasing on disk\n")
461 self.repo.ui.log(
462 b"rebase",
463 b"using in-memory rebase: %r\n",
464 self.inmemory,
465 rebase_imm_used=self.inmemory,
466 )
467
468 def _performrebase(self, tr):
469 self._assignworkingcopy()
470 repo, ui = self.repo, self.ui
471 if self.keepbranchesf:
472 # insert _savebranch at the start of extrafns so if
473 # there's a user-provided extrafn it can clobber branch if
474 # desired
475 self.extrafns.insert(0, _savebranch)
476 if self.collapsef:
477 branches = set()
478 for rev in self.state:
479 branches.add(repo[rev].branch())
480 if len(branches) > 1:
481 raise error.InputError(
482 _(b'cannot collapse multiple named branches')
483 )
484
485 # Keep track of the active bookmarks in order to reset them later
486 self.activebookmark = self.activebookmark or repo._activebookmark
487 if self.activebookmark:
488 bookmarks.deactivate(repo)
489
490 # Store the state before we begin so users can run 'hg rebase --abort'
491 # if we fail before the transaction closes.
492 self.storestatus()
493 if tr:
494 # When using single transaction, store state when transaction
495 # commits.
496 self.storestatus(tr)
497
498 cands = [k for k, v in self.state.items() if v == revtodo]
499 p = repo.ui.makeprogress(
500 _(b"rebasing"), unit=_(b'changesets'), total=len(cands)
501 )
502
503 def progress(ctx):
504 p.increment(item=(b"%d:%s" % (ctx.rev(), ctx)))
505
506 for subset in sortsource(self.destmap):
507 sortedrevs = self.repo.revs(b'sort(%ld, -topo)', subset)
508 for rev in sortedrevs:
509 self._rebasenode(tr, rev, progress)
510 p.complete()
511 ui.note(_(b'rebase merging completed\n'))
512
513 def _concludenode(self, rev, editor, commitmsg=None):
514 """Commit the wd changes with parents p1 and p2.
515
516 Reuse commit info from rev but also store useful information in extra.
517 Return node of committed revision."""
518 repo = self.repo
519 ctx = repo[rev]
520 if commitmsg is None:
521 commitmsg = ctx.description()
522
523 # Skip replacement if collapsing, as that degenerates to p1 for all
524 # nodes.
525 if not self.collapsef:
526 cl = repo.changelog
527 commitmsg = rewriteutil.update_hash_refs(
528 repo,
529 commitmsg,
530 {
531 cl.node(oldrev): [cl.node(newrev)]
532 for oldrev, newrev in self.state.items()
533 if newrev != revtodo
534 },
535 )
536
537 date = self.date
538 if date is None:
539 date = ctx.date()
540 extra = {}
541 if repo.ui.configbool(b'rebase', b'store-source'):
542 extra = {b'rebase_source': ctx.hex()}
543 for c in self.extrafns:
544 c(ctx, extra)
545 destphase = max(ctx.phase(), phases.draft)
546 overrides = {
547 (b'phases', b'new-commit'): destphase,
548 (b'ui', b'allowemptycommit'): not self.skipemptysuccessorf,
549 }
550 with repo.ui.configoverride(overrides, b'rebase'):
551 if self.inmemory:
552 newnode = commitmemorynode(
553 self._repo,
554 wctx=self.wctx,
555 extra=extra,
556 commitmsg=commitmsg,
557 editor=editor,
558 user=ctx.user(),
559 date=date,
560 )
561 else:
562 newnode = commitnode(
563 self._repo,
564 extra=extra,
565 commitmsg=commitmsg,
566 editor=editor,
567 user=ctx.user(),
568 date=date,
569 )
570
571 return newnode
572
573 def _rebasenode(self, tr, rev, progressfn):
574 repo, ui, opts = self.repo, self.ui, self.opts
575 ctx = repo[rev]
576 desc = _ctxdesc(ctx)
577 if self.state[rev] == rev:
578 ui.status(_(b'already rebased %s\n') % desc)
579 elif rev in self.obsolete_with_successor_in_rebase_set:
580 msg = (
581 _(
582 b'note: not rebasing %s and its descendants as '
583 b'this would cause divergence\n'
584 )
585 % desc
586 )
587 repo.ui.status(msg)
588 self.skipped.add(rev)
589 elif rev in self.obsolete_with_successor_in_destination:
590 succ = self.obsolete_with_successor_in_destination[rev]
591 if succ is None:
592 msg = _(b'note: not rebasing %s, it has no successor\n') % desc
593 else:
594 succdesc = _ctxdesc(repo[succ])
595 msg = _(
596 b'note: not rebasing %s, already in destination as %s\n'
597 ) % (desc, succdesc)
598 repo.ui.status(msg)
599 # Make clearrebased aware state[rev] is not a true successor
600 self.skipped.add(rev)
601 # Record rev as moved to its desired destination in self.state.
602 # This helps bookmark and working parent movement.
603 dest = max(
604 adjustdest(repo, rev, self.destmap, self.state, self.skipped)
605 )
606 self.state[rev] = dest
607 elif self.state[rev] == revtodo:
608 ui.status(_(b'rebasing %s\n') % desc)
609 progressfn(ctx)
610 p1, p2, base = defineparents(
611 repo,
612 rev,
613 self.destmap,
614 self.state,
615 self.skipped,
616 self.obsolete_with_successor_in_destination,
617 )
618 if self.resume and self.wctx.p1().rev() == p1:
619 repo.ui.debug(b'resuming interrupted rebase\n')
620 self.resume = False
621 else:
622 overrides = {(b'ui', b'forcemerge'): opts.get('tool', b'')}
623 with ui.configoverride(overrides, b'rebase'):
624 try:
625 rebasenode(
626 repo,
627 rev,
628 p1,
629 p2,
630 base,
631 self.collapsef,
632 wctx=self.wctx,
633 )
634 except error.InMemoryMergeConflictsError:
635 if self.dryrun:
636 raise error.ConflictResolutionRequired(b'rebase')
637 if self.collapsef:
638 # TODO: Make the overlayworkingctx reflected
639 # in the working copy here instead of re-raising
640 # so the entire rebase operation is retried.
641 raise
642 ui.status(
643 _(
644 b"hit merge conflicts; rebasing that "
645 b"commit again in the working copy\n"
646 )
647 )
648 try:
649 scmutil.bail_if_changed(repo)
650 except error.Abort:
651 clearstatus(repo)
652 clearcollapsemsg(repo)
653 raise
654 self.inmemory = False
655 self._assignworkingcopy()
656 mergemod.update(repo[p1], wc=self.wctx)
657 rebasenode(
658 repo,
659 rev,
660 p1,
661 p2,
662 base,
663 self.collapsef,
664 wctx=self.wctx,
665 )
666 if not self.collapsef:
667 merging = p2 != nullrev
668 editform = cmdutil.mergeeditform(merging, b'rebase')
669 editor = cmdutil.getcommiteditor(editform=editform, **opts)
670 # We need to set parents again here just in case we're continuing
671 # a rebase started with an old hg version (before 9c9cfecd4600),
672 # because those old versions would have left us with two dirstate
673 # parents, and we don't want to create a merge commit here (unless
674 # we're rebasing a merge commit).
675 self.wctx.setparents(repo[p1].node(), repo[p2].node())
676 newnode = self._concludenode(rev, editor)
677 else:
678 # Skip commit if we are collapsing
679 newnode = None
680 # Update the state
681 if newnode is not None:
682 self.state[rev] = repo[newnode].rev()
683 ui.debug(b'rebased as %s\n' % short(newnode))
684 if repo[newnode].isempty():
685 ui.warn(
686 _(
687 b'note: created empty successor for %s, its '
688 b'destination already has all its changes\n'
689 )
690 % desc
691 )
692 else:
693 if not self.collapsef:
694 ui.warn(
695 _(
696 b'note: not rebasing %s, its destination already '
697 b'has all its changes\n'
698 )
699 % desc
700 )
701 self.skipped.add(rev)
702 self.state[rev] = p1
703 ui.debug(b'next revision set to %d\n' % p1)
704 else:
705 ui.status(
706 _(b'already rebased %s as %s\n') % (desc, repo[self.state[rev]])
707 )
708 if not tr:
709 # When not using single transaction, store state after each
710 # commit is completely done. On InterventionRequired, we thus
711 # won't store the status. Instead, we'll hit the "len(parents) == 2"
712 # case and realize that the commit was in progress.
713 self.storestatus()
714
715 def _finishrebase(self):
716 repo, ui, opts = self.repo, self.ui, self.opts
717 fm = ui.formatter(b'rebase', pycompat.byteskwargs(opts))
718 fm.startitem()
719 if self.collapsef:
720 p1, p2, _base = defineparents(
721 repo,
722 min(self.state),
723 self.destmap,
724 self.state,
725 self.skipped,
726 self.obsolete_with_successor_in_destination,
727 )
728 editopt = opts.get('edit')
729 editform = b'rebase.collapse'
730 if self.collapsemsg:
731 commitmsg = self.collapsemsg
732 else:
733 commitmsg = b'Collapsed revision'
734 for rebased in sorted(self.state):
735 if rebased not in self.skipped:
736 commitmsg += b'\n* %s' % repo[rebased].description()
737 editopt = True
738 editor = cmdutil.getcommiteditor(edit=editopt, editform=editform)
739 revtoreuse = max(self.state)
740
741 self.wctx.setparents(repo[p1].node(), repo[self.external].node())
742 newnode = self._concludenode(
743 revtoreuse, editor, commitmsg=commitmsg
744 )
745
746 if newnode is not None:
747 newrev = repo[newnode].rev()
748 for oldrev in self.state:
749 self.state[oldrev] = newrev
750
751 if b'qtip' in repo.tags():
752 updatemq(repo, self.state, self.skipped, **opts)
753
754 # restore original working directory
755 # (we do this before stripping)
756 newwd = self.state.get(self.originalwd, self.originalwd)
757 if newwd < 0:
758 # original directory is a parent of rebase set root or ignored
759 newwd = self.originalwd
760 if newwd not in [c.rev() for c in repo[None].parents()]:
761 ui.note(_(b"update back to initial working directory parent\n"))
762 mergemod.update(repo[newwd])
763
764 collapsedas = None
765 if self.collapsef and not self.keepf:
766 collapsedas = newnode
767 clearrebased(
768 ui,
769 repo,
770 self.destmap,
771 self.state,
772 self.skipped,
773 collapsedas,
774 self.keepf,
775 fm=fm,
776 backup=self.backupf,
777 )
778
779 clearstatus(repo)
780 clearcollapsemsg(repo)
781
782 ui.note(_(b"rebase completed\n"))
783 util.unlinkpath(repo.sjoin(b'undo'), ignoremissing=True)
784 if self.skipped:
785 skippedlen = len(self.skipped)
786 ui.note(_(b"%d revisions have been skipped\n") % skippedlen)
787 fm.end()
788
789 if (
790 self.activebookmark
791 and self.activebookmark in repo._bookmarks
792 and repo[b'.'].node() == repo._bookmarks[self.activebookmark]
793 ):
794 bookmarks.activate(repo, self.activebookmark)
795
796 def _abort(self, backup=True, suppwarns=False, dryrun=False, confirm=False):
797 '''Restore the repository to its original state.'''
798
799 repo = self.repo
800 try:
801 # If the first commits in the rebased set get skipped during the
802 # rebase, their values within the state mapping will be the dest
803 # rev id. The rebased list must must not contain the dest rev
804 # (issue4896)
805 rebased = [
806 s
807 for r, s in self.state.items()
808 if s >= 0 and s != r and s != self.destmap[r]
809 ]
810 immutable = [d for d in rebased if not repo[d].mutable()]
811 cleanup = True
812 if immutable:
813 repo.ui.warn(
814 _(b"warning: can't clean up public changesets %s\n")
815 % b', '.join(bytes(repo[r]) for r in immutable),
816 hint=_(b"see 'hg help phases' for details"),
817 )
818 cleanup = False
819
820 descendants = set()
821 if rebased:
822 descendants = set(repo.changelog.descendants(rebased))
823 if descendants - set(rebased):
824 repo.ui.warn(
825 _(
826 b"warning: new changesets detected on "
827 b"destination branch, can't strip\n"
828 )
829 )
830 cleanup = False
831
832 if cleanup:
833 if rebased:
834 strippoints = [
835 c.node() for c in repo.set(b'roots(%ld)', rebased)
836 ]
837
838 updateifonnodes = set(rebased)
839 updateifonnodes.update(self.destmap.values())
840
841 if not confirm:
842 # note: when dry run is set the `rebased` and `destmap`
843 # variables seem to contain "bad" contents, so do not
844 # rely on them. As dryrun does not need this part of
845 # the cleanup, this is "fine"
846 updateifonnodes.add(self.originalwd)
847
848 shouldupdate = repo[b'.'].rev() in updateifonnodes
849
850 # Update away from the rebase if necessary
851 if not dryrun and shouldupdate:
852 mergemod.clean_update(repo[self.originalwd])
853
854 # Strip from the first rebased revision
855 if rebased:
856 repair.strip(repo.ui, repo, strippoints, backup=backup)
857
858 if self.activebookmark and self.activebookmark in repo._bookmarks:
859 bookmarks.activate(repo, self.activebookmark)
860
861 finally:
862 clearstatus(repo)
863 clearcollapsemsg(repo)
864 if not suppwarns:
865 repo.ui.warn(_(b'rebase aborted\n'))
866 return 0
867
868
869 @command(
870 b'rebase',
871 [
872 (
873 b's',
874 b'source',
875 [],
876 _(b'rebase the specified changesets and their descendants'),
877 _(b'REV'),
878 ),
879 (
880 b'b',
881 b'base',
882 [],
883 _(b'rebase everything from branching point of specified changeset'),
884 _(b'REV'),
885 ),
886 (b'r', b'rev', [], _(b'rebase these revisions'), _(b'REV')),
887 (
888 b'd',
889 b'dest',
890 b'',
891 _(b'rebase onto the specified changeset'),
892 _(b'REV'),
893 ),
894 (b'', b'collapse', False, _(b'collapse the rebased changesets')),
895 (
896 b'm',
897 b'message',
898 b'',
899 _(b'use text as collapse commit message'),
900 _(b'TEXT'),
901 ),
902 (b'e', b'edit', False, _(b'invoke editor on commit messages')),
903 (
904 b'l',
905 b'logfile',
906 b'',
907 _(b'read collapse commit message from file'),
908 _(b'FILE'),
909 ),
910 (b'k', b'keep', False, _(b'keep original changesets')),
911 (b'', b'keepbranches', False, _(b'keep original branch names')),
912 (b'D', b'detach', False, _(b'(DEPRECATED)')),
913 (b'i', b'interactive', False, _(b'(DEPRECATED)')),
914 (b't', b'tool', b'', _(b'specify merge tool')),
915 (b'', b'stop', False, _(b'stop interrupted rebase')),
916 (b'c', b'continue', False, _(b'continue an interrupted rebase')),
917 (b'a', b'abort', False, _(b'abort an interrupted rebase')),
918 (
919 b'',
920 b'auto-orphans',
921 b'',
922 _(
923 b'automatically rebase orphan revisions '
924 b'in the specified revset (EXPERIMENTAL)'
925 ),
926 ),
927 ]
928 + cmdutil.dryrunopts
929 + cmdutil.formatteropts
930 + cmdutil.confirmopts,
931 _(b'[[-s REV]... | [-b REV]... | [-r REV]...] [-d REV] [OPTION]...'),
932 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
933 )
934 def rebase(ui, repo, **opts):
935 """move changeset (and descendants) to a different branch
936
937 Rebase uses repeated merging to graft changesets from one part of
938 history (the source) onto another (the destination). This can be
939 useful for linearizing *local* changes relative to a master
940 development tree.
941
942 Published commits cannot be rebased (see :hg:`help phases`).
943 To copy commits, see :hg:`help graft`.
944
945 If you don't specify a destination changeset (``-d/--dest``), rebase
946 will use the same logic as :hg:`merge` to pick a destination. if
947 the current branch contains exactly one other head, the other head
948 is merged with by default. Otherwise, an explicit revision with
949 which to merge with must be provided. (destination changeset is not
950 modified by rebasing, but new changesets are added as its
951 descendants.)
952
953 Here are the ways to select changesets:
954
955 1. Explicitly select them using ``--rev``.
956
957 2. Use ``--source`` to select a root changeset and include all of its
958 descendants.
959
960 3. Use ``--base`` to select a changeset; rebase will find ancestors
961 and their descendants which are not also ancestors of the destination.
962
963 4. If you do not specify any of ``--rev``, ``--source``, or ``--base``,
964 rebase will use ``--base .`` as above.
965
966 If ``--source`` or ``--rev`` is used, special names ``SRC`` and ``ALLSRC``
967 can be used in ``--dest``. Destination would be calculated per source
968 revision with ``SRC`` substituted by that single source revision and
969 ``ALLSRC`` substituted by all source revisions.
970
971 Rebase will destroy original changesets unless you use ``--keep``.
972 It will also move your bookmarks (even if you do).
973
974 Some changesets may be dropped if they do not contribute changes
975 (e.g. merges from the destination branch).
976
977 Unlike ``merge``, rebase will do nothing if you are at the branch tip of
978 a named branch with two heads. You will need to explicitly specify source
979 and/or destination.
980
981 If you need to use a tool to automate merge/conflict decisions, you
982 can specify one with ``--tool``, see :hg:`help merge-tools`.
983 As a caveat: the tool will not be used to mediate when a file was
984 deleted, there is no hook presently available for this.
985
986 If a rebase is interrupted to manually resolve a conflict, it can be
987 continued with --continue/-c, aborted with --abort/-a, or stopped with
988 --stop.
989
990 .. container:: verbose
991
992 Examples:
993
994 - move "local changes" (current commit back to branching point)
995 to the current branch tip after a pull::
996
997 hg rebase
998
999 - move a single changeset to the stable branch::
1000
1001 hg rebase -r 5f493448 -d stable
1002
1003 - splice a commit and all its descendants onto another part of history::
1004
1005 hg rebase --source c0c3 --dest 4cf9
1006
1007 - rebase everything on a branch marked by a bookmark onto the
1008 default branch::
1009
1010 hg rebase --base myfeature --dest default
1011
1012 - collapse a sequence of changes into a single commit::
1013
1014 hg rebase --collapse -r 1520:1525 -d .
1015
1016 - move a named branch while preserving its name::
1017
1018 hg rebase -r "branch(featureX)" -d 1.3 --keepbranches
1019
1020 - stabilize orphaned changesets so history looks linear::
1021
1022 hg rebase -r 'orphan()-obsolete()'\
1023 -d 'first(max((successors(max(roots(ALLSRC) & ::SRC)^)-obsolete())::) +\
1024 max(::((roots(ALLSRC) & ::SRC)^)-obsolete()))'
1025
1026 Configuration Options:
1027
1028 You can make rebase require a destination if you set the following config
1029 option::
1030
1031 [commands]
1032 rebase.requiredest = True
1033
1034 By default, rebase will close the transaction after each commit. For
1035 performance purposes, you can configure rebase to use a single transaction
1036 across the entire rebase. WARNING: This setting introduces a significant
1037 risk of losing the work you've done in a rebase if the rebase aborts
1038 unexpectedly::
1039
1040 [rebase]
1041 singletransaction = True
1042
1043 By default, rebase writes to the working copy, but you can configure it to
1044 run in-memory for better performance. When the rebase is not moving the
1045 parent(s) of the working copy (AKA the "currently checked out changesets"),
1046 this may also allow it to run even if the working copy is dirty::
1047
1048 [rebase]
1049 experimental.inmemory = True
1050
1051 Return Values:
1052
1053 Returns 0 on success, 1 if nothing to rebase or there are
1054 unresolved conflicts.
1055
1056 """
1057 inmemory = ui.configbool(b'rebase', b'experimental.inmemory')
1058 action = cmdutil.check_at_most_one_arg(opts, 'abort', 'stop', 'continue')
1059 if action:
1060 cmdutil.check_incompatible_arguments(
1061 opts, action, ['confirm', 'dry_run']
1062 )
1063 cmdutil.check_incompatible_arguments(
1064 opts, action, ['rev', 'source', 'base', 'dest']
1065 )
1066 cmdutil.check_at_most_one_arg(opts, 'confirm', 'dry_run')
1067 cmdutil.check_at_most_one_arg(opts, 'rev', 'source', 'base')
1068
1069 if action or repo.currenttransaction() is not None:
1070 # in-memory rebase is not compatible with resuming rebases.
1071 # (Or if it is run within a transaction, since the restart logic can
1072 # fail the entire transaction.)
1073 inmemory = False
1074
1075 if opts.get('auto_orphans'):
1076 disallowed_opts = set(opts) - {'auto_orphans'}
1077 cmdutil.check_incompatible_arguments(
1078 opts, 'auto_orphans', disallowed_opts
1079 )
1080
1081 userrevs = list(repo.revs(opts.get('auto_orphans')))
1082 opts['rev'] = [revsetlang.formatspec(b'%ld and orphan()', userrevs)]
1083 opts['dest'] = b'_destautoorphanrebase(SRC)'
1084
1085 if opts.get('dry_run') or opts.get('confirm'):
1086 return _dryrunrebase(ui, repo, action, opts)
1087 elif action == 'stop':
1088 rbsrt = rebaseruntime(repo, ui)
1089 with repo.wlock(), repo.lock():
1090 rbsrt.restorestatus()
1091 if rbsrt.collapsef:
1092 raise error.StateError(_(b"cannot stop in --collapse session"))
1093 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
1094 if not (rbsrt.keepf or allowunstable):
1095 raise error.StateError(
1096 _(
1097 b"cannot remove original changesets with"
1098 b" unrebased descendants"
1099 ),
1100 hint=_(
1101 b'either enable obsmarkers to allow unstable '
1102 b'revisions or use --keep to keep original '
1103 b'changesets'
1104 ),
1105 )
1106 # update to the current working revision
1107 # to clear interrupted merge
1108 mergemod.clean_update(repo[rbsrt.originalwd])
1109 rbsrt._finishrebase()
1110 return 0
1111 elif inmemory:
1112 try:
1113 # in-memory merge doesn't support conflicts, so if we hit any, abort
1114 # and re-run as an on-disk merge.
1115 overrides = {(b'rebase', b'singletransaction'): True}
1116 with ui.configoverride(overrides, b'rebase'):
1117 return _dorebase(ui, repo, action, opts, inmemory=inmemory)
1118 except error.InMemoryMergeConflictsError:
1119 if ui.configbool(b'devel', b'rebase.force-in-memory-merge'):
1120 raise
1121 ui.warn(
1122 _(
1123 b'hit merge conflicts; re-running rebase without in-memory'
1124 b' merge\n'
1125 )
1126 )
1127 clearstatus(repo)
1128 clearcollapsemsg(repo)
1129 return _dorebase(ui, repo, action, opts, inmemory=False)
1130 else:
1131 return _dorebase(ui, repo, action, opts)
1132
1133
1134 def _dryrunrebase(ui, repo, action, opts):
1135 rbsrt = rebaseruntime(repo, ui, inmemory=True, dryrun=True, opts=opts)
1136 confirm = opts.get('confirm')
1137 if confirm:
1138 ui.status(_(b'starting in-memory rebase\n'))
1139 else:
1140 ui.status(
1141 _(b'starting dry-run rebase; repository will not be changed\n')
1142 )
1143 with repo.wlock(), repo.lock():
1144 needsabort = True
1145 try:
1146 overrides = {(b'rebase', b'singletransaction'): True}
1147 with ui.configoverride(overrides, b'rebase'):
1148 res = _origrebase(
1149 ui,
1150 repo,
1151 action,
1152 opts,
1153 rbsrt,
1154 )
1155 if res == _nothingtorebase():
1156 needsabort = False
1157 return res
1158 except error.ConflictResolutionRequired:
1159 ui.status(_(b'hit a merge conflict\n'))
1160 return 1
1161 except error.Abort:
1162 needsabort = False
1163 raise
1164 else:
1165 if confirm:
1166 ui.status(_(b'rebase completed successfully\n'))
1167 if not ui.promptchoice(_(b'apply changes (yn)?$$ &Yes $$ &No')):
1168 # finish unfinished rebase
1169 rbsrt._finishrebase()
1170 else:
1171 rbsrt._prepareabortorcontinue(
1172 isabort=True,
1173 backup=False,
1174 suppwarns=True,
1175 confirm=confirm,
1176 )
1177 needsabort = False
1178 else:
1179 ui.status(
1180 _(
1181 b'dry-run rebase completed successfully; run without'
1182 b' -n/--dry-run to perform this rebase\n'
1183 )
1184 )
1185 return 0
1186 finally:
1187 if needsabort:
1188 # no need to store backup in case of dryrun
1189 rbsrt._prepareabortorcontinue(
1190 isabort=True,
1191 backup=False,
1192 suppwarns=True,
1193 dryrun=opts.get('dry_run'),
1194 )
1195
1196
1197 def _dorebase(ui, repo, action, opts, inmemory=False):
1198 rbsrt = rebaseruntime(repo, ui, inmemory, opts=opts)
1199 return _origrebase(ui, repo, action, opts, rbsrt)
1200
1201
1202 def _origrebase(ui, repo, action, opts, rbsrt):
1203 assert action != 'stop'
1204 with repo.wlock(), repo.lock():
1205 if opts.get('interactive'):
1206 try:
1207 if extensions.find(b'histedit'):
1208 enablehistedit = b''
1209 except KeyError:
1210 enablehistedit = b" --config extensions.histedit="
1211 help = b"hg%s help -e histedit" % enablehistedit
1212 msg = (
1213 _(
1214 b"interactive history editing is supported by the "
1215 b"'histedit' extension (see \"%s\")"
1216 )
1217 % help
1218 )
1219 raise error.InputError(msg)
1220
1221 if rbsrt.collapsemsg and not rbsrt.collapsef:
1222 raise error.InputError(
1223 _(b'message can only be specified with collapse')
1224 )
1225
1226 if action:
1227 if rbsrt.collapsef:
1228 raise error.InputError(
1229 _(b'cannot use collapse with continue or abort')
1230 )
1231 if action == 'abort' and opts.get('tool', False):
1232 ui.warn(_(b'tool option will be ignored\n'))
1233 if action == 'continue':
1234 ms = mergestatemod.mergestate.read(repo)
1235 mergeutil.checkunresolved(ms)
1236
1237 retcode = rbsrt._prepareabortorcontinue(isabort=(action == 'abort'))
1238 if retcode is not None:
1239 return retcode
1240 else:
1241 # search default destination in this space
1242 # used in the 'hg pull --rebase' case, see issue 5214.
1243 destspace = opts.get('_destspace')
1244 destmap = _definedestmap(
1245 ui,
1246 repo,
1247 rbsrt.inmemory,
1248 opts.get('dest', None),
1249 opts.get('source', []),
1250 opts.get('base', []),
1251 opts.get('rev', []),
1252 destspace=destspace,
1253 )
1254 retcode = rbsrt._preparenewrebase(destmap)
1255 if retcode is not None:
1256 return retcode
1257 storecollapsemsg(repo, rbsrt.collapsemsg)
1258
1259 tr = None
1260
1261 singletr = ui.configbool(b'rebase', b'singletransaction')
1262 if singletr:
1263 tr = repo.transaction(b'rebase')
1264
1265 # If `rebase.singletransaction` is enabled, wrap the entire operation in
1266 # one transaction here. Otherwise, transactions are obtained when
1267 # committing each node, which is slower but allows partial success.
1268 with util.acceptintervention(tr):
1269 rbsrt._performrebase(tr)
1270 if not rbsrt.dryrun:
1271 rbsrt._finishrebase()
1272
1273
1274 def _definedestmap(ui, repo, inmemory, destf, srcf, basef, revf, destspace):
1275 """use revisions argument to define destmap {srcrev: destrev}"""
1276 if revf is None:
1277 revf = []
1278
1279 # destspace is here to work around issues with `hg pull --rebase` see
1280 # issue5214 for details
1281
1282 cmdutil.checkunfinished(repo)
1283 if not inmemory:
1284 scmutil.bail_if_changed(repo)
1285
1286 if ui.configbool(b'commands', b'rebase.requiredest') and not destf:
1287 raise error.InputError(
1288 _(b'you must specify a destination'),
1289 hint=_(b'use: hg rebase -d REV'),
1290 )
1291
1292 dest = None
1293
1294 if revf:
1295 rebaseset = logcmdutil.revrange(repo, revf)
1296 if not rebaseset:
1297 ui.status(_(b'empty "rev" revision set - nothing to rebase\n'))
1298 return None
1299 elif srcf:
1300 src = logcmdutil.revrange(repo, srcf)
1301 if not src:
1302 ui.status(_(b'empty "source" revision set - nothing to rebase\n'))
1303 return None
1304 # `+ (%ld)` to work around `wdir()::` being empty
1305 rebaseset = repo.revs(b'(%ld):: + (%ld)', src, src)
1306 else:
1307 base = logcmdutil.revrange(repo, basef or [b'.'])
1308 if not base:
1309 ui.status(
1310 _(b'empty "base" revision set - ' b"can't compute rebase set\n")
1311 )
1312 return None
1313 if destf:
1314 # --base does not support multiple destinations
1315 dest = logcmdutil.revsingle(repo, destf)
1316 else:
1317 dest = repo[_destrebase(repo, base, destspace=destspace)]
1318 destf = bytes(dest)
1319
1320 roots = [] # selected children of branching points
1321 bpbase = {} # {branchingpoint: [origbase]}
1322 for b in base: # group bases by branching points
1323 bp = repo.revs(b'ancestor(%d, %d)', b, dest.rev()).first()
1324 bpbase[bp] = bpbase.get(bp, []) + [b]
1325 if None in bpbase:
1326 # emulate the old behavior, showing "nothing to rebase" (a better
1327 # behavior may be abort with "cannot find branching point" error)
1328 bpbase.clear()
1329 for bp, bs in bpbase.items(): # calculate roots
1330 roots += list(repo.revs(b'children(%d) & ancestors(%ld)', bp, bs))
1331
1332 rebaseset = repo.revs(b'%ld::', roots)
1333
1334 if not rebaseset:
1335 # transform to list because smartsets are not comparable to
1336 # lists. This should be improved to honor laziness of
1337 # smartset.
1338 if list(base) == [dest.rev()]:
1339 if basef:
1340 ui.status(
1341 _(
1342 b'nothing to rebase - %s is both "base"'
1343 b' and destination\n'
1344 )
1345 % dest
1346 )
1347 else:
1348 ui.status(
1349 _(
1350 b'nothing to rebase - working directory '
1351 b'parent is also destination\n'
1352 )
1353 )
1354 elif not repo.revs(b'%ld - ::%d', base, dest.rev()):
1355 if basef:
1356 ui.status(
1357 _(
1358 b'nothing to rebase - "base" %s is '
1359 b'already an ancestor of destination '
1360 b'%s\n'
1361 )
1362 % (b'+'.join(bytes(repo[r]) for r in base), dest)
1363 )
1364 else:
1365 ui.status(
1366 _(
1367 b'nothing to rebase - working '
1368 b'directory parent is already an '
1369 b'ancestor of destination %s\n'
1370 )
1371 % dest
1372 )
1373 else: # can it happen?
1374 ui.status(
1375 _(b'nothing to rebase from %s to %s\n')
1376 % (b'+'.join(bytes(repo[r]) for r in base), dest)
1377 )
1378 return None
1379
1380 if wdirrev in rebaseset:
1381 raise error.InputError(_(b'cannot rebase the working copy'))
1382 rebasingwcp = repo[b'.'].rev() in rebaseset
1383 ui.log(
1384 b"rebase",
1385 b"rebasing working copy parent: %r\n",
1386 rebasingwcp,
1387 rebase_rebasing_wcp=rebasingwcp,
1388 )
1389 if inmemory and rebasingwcp:
1390 # Check these since we did not before.
1391 cmdutil.checkunfinished(repo)
1392 scmutil.bail_if_changed(repo)
1393
1394 if not destf:
1395 dest = repo[_destrebase(repo, rebaseset, destspace=destspace)]
1396 destf = bytes(dest)
1397
1398 allsrc = revsetlang.formatspec(b'%ld', rebaseset)
1399 alias = {b'ALLSRC': allsrc}
1400
1401 if dest is None:
1402 try:
1403 # fast path: try to resolve dest without SRC alias
1404 dest = scmutil.revsingle(repo, destf, localalias=alias)
1405 except error.RepoLookupError:
1406 # multi-dest path: resolve dest for each SRC separately
1407 destmap = {}
1408 for r in rebaseset:
1409 alias[b'SRC'] = revsetlang.formatspec(b'%d', r)
1410 # use repo.anyrevs instead of scmutil.revsingle because we
1411 # don't want to abort if destset is empty.
1412 destset = repo.anyrevs([destf], user=True, localalias=alias)
1413 size = len(destset)
1414 if size == 1:
1415 destmap[r] = destset.first()
1416 elif size == 0:
1417 ui.note(_(b'skipping %s - empty destination\n') % repo[r])
1418 else:
1419 raise error.InputError(
1420 _(b'rebase destination for %s is not unique') % repo[r]
1421 )
1422
1423 if dest is not None:
1424 # single-dest case: assign dest to each rev in rebaseset
1425 destrev = dest.rev()
1426 destmap = {r: destrev for r in rebaseset} # {srcrev: destrev}
1427
1428 if not destmap:
1429 ui.status(_(b'nothing to rebase - empty destination\n'))
1430 return None
1431
1432 return destmap
1433
1434
1435 def externalparent(repo, state, destancestors):
1436 """Return the revision that should be used as the second parent
1437 when the revisions in state is collapsed on top of destancestors.
1438 Abort if there is more than one parent.
1439 """
1440 parents = set()
1441 source = min(state)
1442 for rev in state:
1443 if rev == source:
1444 continue
1445 for p in repo[rev].parents():
1446 if p.rev() not in state and p.rev() not in destancestors:
1447 parents.add(p.rev())
1448 if not parents:
1449 return nullrev
1450 if len(parents) == 1:
1451 return parents.pop()
1452 raise error.StateError(
1453 _(
1454 b'unable to collapse on top of %d, there is more '
1455 b'than one external parent: %s'
1456 )
1457 % (max(destancestors), b', '.join(b"%d" % p for p in sorted(parents)))
1458 )
1459
1460
1461 def commitmemorynode(repo, wctx, editor, extra, user, date, commitmsg):
1462 """Commit the memory changes with parents p1 and p2.
1463 Return node of committed revision."""
1464 # By convention, ``extra['branch']`` (set by extrafn) clobbers
1465 # ``branch`` (used when passing ``--keepbranches``).
1466 branch = None
1467 if b'branch' in extra:
1468 branch = extra[b'branch']
1469
1470 # FIXME: We call _compact() because it's required to correctly detect
1471 # changed files. This was added to fix a regression shortly before the 5.5
1472 # release. A proper fix will be done in the default branch.
1473 wctx._compact()
1474 memctx = wctx.tomemctx(
1475 commitmsg,
1476 date=date,
1477 extra=extra,
1478 user=user,
1479 branch=branch,
1480 editor=editor,
1481 )
1482 if memctx.isempty() and not repo.ui.configbool(b'ui', b'allowemptycommit'):
1483 return None
1484 commitres = repo.commitctx(memctx)
1485 wctx.clean() # Might be reused
1486 return commitres
1487
1488
1489 def commitnode(repo, editor, extra, user, date, commitmsg):
1490 """Commit the wd changes with parents p1 and p2.
1491 Return node of committed revision."""
1492 tr = util.nullcontextmanager
1493 if not repo.ui.configbool(b'rebase', b'singletransaction'):
1494 tr = lambda: repo.transaction(b'rebase')
1495 with tr():
1496 # Commit might fail if unresolved files exist
1497 newnode = repo.commit(
1498 text=commitmsg, user=user, date=date, extra=extra, editor=editor
1499 )
1500
1501 repo.dirstate.setbranch(
1502 repo[newnode].branch(), repo.currenttransaction()
1503 )
1504 return newnode
1505
1506
1507 def rebasenode(repo, rev, p1, p2, base, collapse, wctx):
1508 """Rebase a single revision rev on top of p1 using base as merge ancestor"""
1509 # Merge phase
1510 # Update to destination and merge it with local
1511 p1ctx = repo[p1]
1512 if wctx.isinmemory():
1513 wctx.setbase(p1ctx)
1514 scope = util.nullcontextmanager
1515 else:
1516 if repo[b'.'].rev() != p1:
1517 repo.ui.debug(b" update to %d:%s\n" % (p1, p1ctx))
1518 mergemod.clean_update(p1ctx)
1519 else:
1520 repo.ui.debug(b" already in destination\n")
1521 scope = lambda: repo.dirstate.changing_parents(repo)
1522 # This is, alas, necessary to invalidate workingctx's manifest cache,
1523 # as well as other data we litter on it in other places.
1524 wctx = repo[None]
1525 repo.dirstate.write(repo.currenttransaction())
1526 ctx = repo[rev]
1527 repo.ui.debug(b" merge against %d:%s\n" % (rev, ctx))
1528 if base is not None:
1529 repo.ui.debug(b" detach base %d:%s\n" % (base, repo[base]))
1530
1531 with scope():
1532 # See explanation in merge.graft()
1533 mergeancestor = repo.changelog.isancestor(p1ctx.node(), ctx.node())
1534 stats = mergemod._update(
1535 repo,
1536 rev,
1537 branchmerge=True,
1538 force=True,
1539 ancestor=base,
1540 mergeancestor=mergeancestor,
1541 labels=[b'dest', b'source', b'parent of source'],
1542 wc=wctx,
1543 )
1544 wctx.setparents(p1ctx.node(), repo[p2].node())
1545 if collapse:
1546 copies.graftcopies(wctx, ctx, p1ctx)
1547 else:
1548 # If we're not using --collapse, we need to
1549 # duplicate copies between the revision we're
1550 # rebasing and its first parent.
1551 copies.graftcopies(wctx, ctx, ctx.p1())
1552
1553 if stats.unresolvedcount > 0:
1554 if wctx.isinmemory():
1555 raise error.InMemoryMergeConflictsError()
1556 else:
1557 raise error.ConflictResolutionRequired(b'rebase')
1558
1559
1560 def adjustdest(repo, rev, destmap, state, skipped):
1561 r"""adjust rebase destination given the current rebase state
1562
1563 rev is what is being rebased. Return a list of two revs, which are the
1564 adjusted destinations for rev's p1 and p2, respectively. If a parent is
1565 nullrev, return dest without adjustment for it.
1566
1567 For example, when doing rebasing B+E to F, C to G, rebase will first move B
1568 to B1, and E's destination will be adjusted from F to B1.
1569
1570 B1 <- written during rebasing B
1571 |
1572 F <- original destination of B, E
1573 |
1574 | E <- rev, which is being rebased
1575 | |
1576 | D <- prev, one parent of rev being checked
1577 | |
1578 | x <- skipped, ex. no successor or successor in (::dest)
1579 | |
1580 | C <- rebased as C', different destination
1581 | |
1582 | B <- rebased as B1 C'
1583 |/ |
1584 A G <- destination of C, different
1585
1586 Another example about merge changeset, rebase -r C+G+H -d K, rebase will
1587 first move C to C1, G to G1, and when it's checking H, the adjusted
1588 destinations will be [C1, G1].
1589
1590 H C1 G1
1591 /| | /
1592 F G |/
1593 K | | -> K
1594 | C D |
1595 | |/ |
1596 | B | ...
1597 |/ |/
1598 A A
1599
1600 Besides, adjust dest according to existing rebase information. For example,
1601
1602 B C D B needs to be rebased on top of C, C needs to be rebased on top
1603 \|/ of D. We will rebase C first.
1604 A
1605
1606 C' After rebasing C, when considering B's destination, use C'
1607 | instead of the original C.
1608 B D
1609 \ /
1610 A
1611 """
1612 # pick already rebased revs with same dest from state as interesting source
1613 dest = destmap[rev]
1614 source = [
1615 s
1616 for s, d in state.items()
1617 if d > 0 and destmap[s] == dest and s not in skipped
1618 ]
1619
1620 result = []
1621 for prev in repo.changelog.parentrevs(rev):
1622 adjusted = dest
1623 if prev != nullrev:
1624 candidate = repo.revs(b'max(%ld and (::%d))', source, prev).first()
1625 if candidate is not None:
1626 adjusted = state[candidate]
1627 if adjusted == dest and dest in state:
1628 adjusted = state[dest]
1629 if adjusted == revtodo:
1630 # sortsource should produce an order that makes this impossible
1631 raise error.ProgrammingError(
1632 b'rev %d should be rebased already at this time' % dest
1633 )
1634 result.append(adjusted)
1635 return result
1636
1637
1638 def _checkobsrebase(repo, ui, rebaseobsrevs, rebaseobsskipped):
1639 """
1640 Abort if rebase will create divergence or rebase is noop because of markers
1641
1642 `rebaseobsrevs`: set of obsolete revision in source
1643 `rebaseobsskipped`: set of revisions from source skipped because they have
1644 successors in destination or no non-obsolete successor.
1645 """
1646 # Obsolete node with successors not in dest leads to divergence
1647 divergenceok = obsolete.isenabled(repo, obsolete.allowdivergenceopt)
1648 divergencebasecandidates = rebaseobsrevs - rebaseobsskipped
1649
1650 if divergencebasecandidates and not divergenceok:
1651 divhashes = (bytes(repo[r]) for r in divergencebasecandidates)
1652 msg = _(b"this rebase will cause divergences from: %s")
1653 h = _(
1654 b"to force the rebase please set "
1655 b"experimental.evolution.allowdivergence=True"
1656 )
1657 raise error.StateError(msg % (b",".join(divhashes),), hint=h)
1658
1659
1660 def successorrevs(unfi, rev):
1661 """yield revision numbers for successors of rev"""
1662 assert unfi.filtername is None
1663 get_rev = unfi.changelog.index.get_rev
1664 for s in obsutil.allsuccessors(unfi.obsstore, [unfi[rev].node()]):
1665 r = get_rev(s)
1666 if r is not None:
1667 yield r
1668
1669
1670 def defineparents(repo, rev, destmap, state, skipped, obsskipped):
1671 """Return new parents and optionally a merge base for rev being rebased
1672
1673 The destination specified by "dest" cannot always be used directly because
1674 previously rebase result could affect destination. For example,
1675
1676 D E rebase -r C+D+E -d B
1677 |/ C will be rebased to C'
1678 B C D's new destination will be C' instead of B
1679 |/ E's new destination will be C' instead of B
1680 A
1681
1682 The new parents of a merge is slightly more complicated. See the comment
1683 block below.
1684 """
1685 # use unfiltered changelog since successorrevs may return filtered nodes
1686 assert repo.filtername is None
1687 cl = repo.changelog
1688 isancestor = cl.isancestorrev
1689
1690 dest = destmap[rev]
1691 oldps = repo.changelog.parentrevs(rev) # old parents
1692 newps = [nullrev, nullrev] # new parents
1693 dests = adjustdest(repo, rev, destmap, state, skipped)
1694 bases = list(oldps) # merge base candidates, initially just old parents
1695
1696 if all(r == nullrev for r in oldps[1:]):
1697 # For non-merge changeset, just move p to adjusted dest as requested.
1698 newps[0] = dests[0]
1699 else:
1700 # For merge changeset, if we move p to dests[i] unconditionally, both
1701 # parents may change and the end result looks like "the merge loses a
1702 # parent", which is a surprise. This is a limit because "--dest" only
1703 # accepts one dest per src.
1704 #
1705 # Therefore, only move p with reasonable conditions (in this order):
1706 # 1. use dest, if dest is a descendent of (p or one of p's successors)
1707 # 2. use p's rebased result, if p is rebased (state[p] > 0)
1708 #
1709 # Comparing with adjustdest, the logic here does some additional work:
1710 # 1. decide which parents will not be moved towards dest
1711 # 2. if the above decision is "no", should a parent still be moved
1712 # because it was rebased?
1713 #
1714 # For example:
1715 #
1716 # C # "rebase -r C -d D" is an error since none of the parents
1717 # /| # can be moved. "rebase -r B+C -d D" will move C's parent
1718 # A B D # B (using rule "2."), since B will be rebased.
1719 #
1720 # The loop tries to be not rely on the fact that a Mercurial node has
1721 # at most 2 parents.
1722 for i, p in enumerate(oldps):
1723 np = p # new parent
1724 if any(isancestor(x, dests[i]) for x in successorrevs(repo, p)):
1725 np = dests[i]
1726 elif p in state and state[p] > 0:
1727 np = state[p]
1728
1729 # If one parent becomes an ancestor of the other, drop the ancestor
1730 for j, x in enumerate(newps[:i]):
1731 if x == nullrev:
1732 continue
1733 if isancestor(np, x): # CASE-1
1734 np = nullrev
1735 elif isancestor(x, np): # CASE-2
1736 newps[j] = np
1737 np = nullrev
1738 # New parents forming an ancestor relationship does not
1739 # mean the old parents have a similar relationship. Do not
1740 # set bases[x] to nullrev.
1741 bases[j], bases[i] = bases[i], bases[j]
1742
1743 newps[i] = np
1744
1745 # "rebasenode" updates to new p1, and the old p1 will be used as merge
1746 # base. If only p2 changes, merging using unchanged p1 as merge base is
1747 # suboptimal. Therefore swap parents to make the merge sane.
1748 if newps[1] != nullrev and oldps[0] == newps[0]:
1749 assert len(newps) == 2 and len(oldps) == 2
1750 newps.reverse()
1751 bases.reverse()
1752
1753 # No parent change might be an error because we fail to make rev a
1754 # descendent of requested dest. This can happen, for example:
1755 #
1756 # C # rebase -r C -d D
1757 # /| # None of A and B will be changed to D and rebase fails.
1758 # A B D
1759 if set(newps) == set(oldps) and dest not in newps:
1760 raise error.InputError(
1761 _(
1762 b'cannot rebase %d:%s without '
1763 b'moving at least one of its parents'
1764 )
1765 % (rev, repo[rev])
1766 )
1767
1768 # Source should not be ancestor of dest. The check here guarantees it's
1769 # impossible. With multi-dest, the initial check does not cover complex
1770 # cases since we don't have abstractions to dry-run rebase cheaply.
1771 if any(p != nullrev and isancestor(rev, p) for p in newps):
1772 raise error.InputError(_(b'source is ancestor of destination'))
1773
1774 # Check if the merge will contain unwanted changes. That may happen if
1775 # there are multiple special (non-changelog ancestor) merge bases, which
1776 # cannot be handled well by the 3-way merge algorithm. For example:
1777 #
1778 # F
1779 # /|
1780 # D E # "rebase -r D+E+F -d Z", when rebasing F, if "D" was chosen
1781 # | | # as merge base, the difference between D and F will include
1782 # B C # C, so the rebased F will contain C surprisingly. If "E" was
1783 # |/ # chosen, the rebased F will contain B.
1784 # A Z
1785 #
1786 # But our merge base candidates (D and E in above case) could still be
1787 # better than the default (ancestor(F, Z) == null). Therefore still
1788 # pick one (so choose p1 above).
1789 if sum(1 for b in set(bases) if b != nullrev and b not in newps) > 1:
1790 unwanted = [None, None] # unwanted[i]: unwanted revs if choose bases[i]
1791 for i, base in enumerate(bases):
1792 if base == nullrev or base in newps:
1793 continue
1794 # Revisions in the side (not chosen as merge base) branch that
1795 # might contain "surprising" contents
1796 other_bases = set(bases) - {base}
1797 siderevs = list(
1798 repo.revs(b'(%ld %% (%d+%d))', other_bases, base, dest)
1799 )
1800
1801 # If those revisions are covered by rebaseset, the result is good.
1802 # A merge in rebaseset would be considered to cover its ancestors.
1803 if siderevs:
1804 rebaseset = [
1805 r for r, d in state.items() if d > 0 and r not in obsskipped
1806 ]
1807 merges = [
1808 r for r in rebaseset if cl.parentrevs(r)[1] != nullrev
1809 ]
1810 unwanted[i] = list(
1811 repo.revs(
1812 b'%ld - (::%ld) - %ld', siderevs, merges, rebaseset
1813 )
1814 )
1815
1816 if any(revs is not None for revs in unwanted):
1817 # Choose a merge base that has a minimal number of unwanted revs.
1818 l, i = min(
1819 (len(revs), i)
1820 for i, revs in enumerate(unwanted)
1821 if revs is not None
1822 )
1823
1824 # The merge will include unwanted revisions. Abort now. Revisit this if
1825 # we have a more advanced merge algorithm that handles multiple bases.
1826 if l > 0:
1827 unwanteddesc = _(b' or ').join(
1828 b', '.join(b'%d:%s' % (r, repo[r]) for r in revs)
1829 for revs in unwanted
1830 if revs is not None
1831 )
1832 raise error.InputError(
1833 _(b'rebasing %d:%s will include unwanted changes from %s')
1834 % (rev, repo[rev], unwanteddesc)
1835 )
1836
1837 # newps[0] should match merge base if possible. Currently, if newps[i]
1838 # is nullrev, the only case is newps[i] and newps[j] (j < i), one is
1839 # the other's ancestor. In that case, it's fine to not swap newps here.
1840 # (see CASE-1 and CASE-2 above)
1841 if i != 0:
1842 if newps[i] != nullrev:
1843 newps[0], newps[i] = newps[i], newps[0]
1844 bases[0], bases[i] = bases[i], bases[0]
1845
1846 # "rebasenode" updates to new p1, use the corresponding merge base.
1847 base = bases[0]
1848
1849 repo.ui.debug(b" future parents are %d and %d\n" % tuple(newps))
1850
1851 return newps[0], newps[1], base
1852
1853
1854 def isagitpatch(repo, patchname):
1855 """Return true if the given patch is in git format"""
1856 mqpatch = os.path.join(repo.mq.path, patchname)
1857
1858 with open(mqpatch, 'rb') as fp:
1859 for line in patch.linereader(fp):
1860 if line.startswith(b'diff --git'):
1861 return True
1862 return False
1863
1864
1865 def updatemq(repo, state, skipped, **opts):
1866 """Update rebased mq patches - finalize and then import them"""
1867 mqrebase = {}
1868 mq = repo.mq
1869 original_series = mq.fullseries[:]
1870 skippedpatches = set()
1871
1872 for p in mq.applied:
1873 rev = repo[p.node].rev()
1874 if rev in state:
1875 repo.ui.debug(
1876 b'revision %d is an mq patch (%s), finalize it.\n'
1877 % (rev, p.name)
1878 )
1879 mqrebase[rev] = (p.name, isagitpatch(repo, p.name))
1880 else:
1881 # Applied but not rebased, not sure this should happen
1882 skippedpatches.add(p.name)
1883
1884 if mqrebase:
1885 mq.finish(repo, mqrebase.keys())
1886
1887 # We must start import from the newest revision
1888 for rev in sorted(mqrebase, reverse=True):
1889 if rev not in skipped:
1890 name, isgit = mqrebase[rev]
1891 repo.ui.note(
1892 _(b'updating mq patch %s to %d:%s\n')
1893 % (name, state[rev], repo[state[rev]])
1894 )
1895 mq.qimport(
1896 repo,
1897 (),
1898 patchname=name,
1899 git=isgit,
1900 rev=[b"%d" % state[rev]],
1901 )
1902 else:
1903 # Rebased and skipped
1904 skippedpatches.add(mqrebase[rev][0])
1905
1906 # Patches were either applied and rebased and imported in
1907 # order, applied and removed or unapplied. Discard the removed
1908 # ones while preserving the original series order and guards.
1909 newseries = [
1910 s
1911 for s in original_series
1912 if mq.guard_re.split(s, 1)[0] not in skippedpatches
1913 ]
1914 mq.fullseries[:] = newseries
1915 mq.seriesdirty = True
1916 mq.savedirty()
1917
1918
1919 def storecollapsemsg(repo, collapsemsg):
1920 """Store the collapse message to allow recovery"""
1921 collapsemsg = collapsemsg or b''
1922 f = repo.vfs(b"last-message.txt", b"w")
1923 f.write(b"%s\n" % collapsemsg)
1924 f.close()
1925
1926
1927 def clearcollapsemsg(repo):
1928 """Remove collapse message file"""
1929 repo.vfs.unlinkpath(b"last-message.txt", ignoremissing=True)
1930
1931
1932 def restorecollapsemsg(repo, isabort):
1933 """Restore previously stored collapse message"""
1934 try:
1935 f = repo.vfs(b"last-message.txt")
1936 collapsemsg = f.readline().strip()
1937 f.close()
1938 except FileNotFoundError:
1939 if isabort:
1940 # Oh well, just abort like normal
1941 collapsemsg = b''
1942 else:
1943 raise error.Abort(_(b'missing .hg/last-message.txt for rebase'))
1944 return collapsemsg
1945
1946
1947 def clearstatus(repo):
1948 """Remove the status files"""
1949 # Make sure the active transaction won't write the state file
1950 tr = repo.currenttransaction()
1951 if tr:
1952 tr.removefilegenerator(b'rebasestate')
1953 repo.vfs.unlinkpath(b"rebasestate", ignoremissing=True)
1954
1955
1956 def sortsource(destmap):
1957 """yield source revisions in an order that we only rebase things once
1958
1959 If source and destination overlaps, we should filter out revisions
1960 depending on other revisions which hasn't been rebased yet.
1961
1962 Yield a sorted list of revisions each time.
1963
1964 For example, when rebasing A to B, B to C. This function yields [B], then
1965 [A], indicating B needs to be rebased first.
1966
1967 Raise if there is a cycle so the rebase is impossible.
1968 """
1969 srcset = set(destmap)
1970 while srcset:
1971 srclist = sorted(srcset)
1972 result = []
1973 for r in srclist:
1974 if destmap[r] not in srcset:
1975 result.append(r)
1976 if not result:
1977 raise error.InputError(_(b'source and destination form a cycle'))
1978 srcset -= set(result)
1979 yield result
1980
1981
1982 def buildstate(repo, destmap, collapse):
1983 """Define which revisions are going to be rebased and where
1984
1985 repo: repo
1986 destmap: {srcrev: destrev}
1987 """
1988 rebaseset = destmap.keys()
1989 originalwd = repo[b'.'].rev()
1990
1991 # This check isn't strictly necessary, since mq detects commits over an
1992 # applied patch. But it prevents messing up the working directory when
1993 # a partially completed rebase is blocked by mq.
1994 if b'qtip' in repo.tags():
1995 mqapplied = {repo[s.node].rev() for s in repo.mq.applied}
1996 if set(destmap.values()) & mqapplied:
1997 raise error.StateError(_(b'cannot rebase onto an applied mq patch'))
1998
1999 # Get "cycle" error early by exhausting the generator.
2000 sortedsrc = list(sortsource(destmap)) # a list of sorted revs
2001 if not sortedsrc:
2002 raise error.InputError(_(b'no matching revisions'))
2003
2004 # Only check the first batch of revisions to rebase not depending on other
2005 # rebaseset. This means "source is ancestor of destination" for the second
2006 # (and following) batches of revisions are not checked here. We rely on
2007 # "defineparents" to do that check.
2008 roots = list(repo.set(b'roots(%ld)', sortedsrc[0]))
2009 if not roots:
2010 raise error.InputError(_(b'no matching revisions'))
2011
2012 def revof(r):
2013 return r.rev()
2014
2015 roots = sorted(roots, key=revof)
2016 state = dict.fromkeys(rebaseset, revtodo)
2017 emptyrebase = len(sortedsrc) == 1
2018 for root in roots:
2019 dest = repo[destmap[root.rev()]]
2020 commonbase = root.ancestor(dest)
2021 if commonbase == root:
2022 raise error.InputError(_(b'source is ancestor of destination'))
2023 if commonbase == dest:
2024 wctx = repo[None]
2025 if dest == wctx.p1():
2026 # when rebasing to '.', it will use the current wd branch name
2027 samebranch = root.branch() == wctx.branch()
2028 else:
2029 samebranch = root.branch() == dest.branch()
2030 if not collapse and samebranch and dest in root.parents():
2031 # mark the revision as done by setting its new revision
2032 # equal to its old (current) revisions
2033 state[root.rev()] = root.rev()
2034 repo.ui.debug(b'source is a child of destination\n')
2035 continue
2036
2037 emptyrebase = False
2038 repo.ui.debug(b'rebase onto %s starting from %s\n' % (dest, root))
2039 if emptyrebase:
2040 return None
2041 for rev in sorted(state):
2042 parents = [p for p in repo.changelog.parentrevs(rev) if p != nullrev]
2043 # if all parents of this revision are done, then so is this revision
2044 if parents and all(state.get(p) == p for p in parents):
2045 state[rev] = rev
2046 return originalwd, destmap, state
2047
2048
2049 def clearrebased(
2050 ui,
2051 repo,
2052 destmap,
2053 state,
2054 skipped,
2055 collapsedas=None,
2056 keepf=False,
2057 fm=None,
2058 backup=True,
2059 ):
2060 """dispose of rebased revision at the end of the rebase
2061
2062 If `collapsedas` is not None, the rebase was a collapse whose result if the
2063 `collapsedas` node.
2064
2065 If `keepf` is not True, the rebase has --keep set and no nodes should be
2066 removed (but bookmarks still need to be moved).
2067
2068 If `backup` is False, no backup will be stored when stripping rebased
2069 revisions.
2070 """
2071 tonode = repo.changelog.node
2072 replacements = {}
2073 moves = {}
2074 stripcleanup = not obsolete.isenabled(repo, obsolete.createmarkersopt)
2075
2076 collapsednodes = []
2077 for rev, newrev in sorted(state.items()):
2078 if newrev >= 0 and newrev != rev:
2079 oldnode = tonode(rev)
2080 newnode = collapsedas or tonode(newrev)
2081 moves[oldnode] = newnode
2082 succs = None
2083 if rev in skipped:
2084 if stripcleanup or not repo[rev].obsolete():
2085 succs = ()
2086 elif collapsedas:
2087 collapsednodes.append(oldnode)
2088 else:
2089 succs = (newnode,)
2090 if succs is not None:
2091 replacements[(oldnode,)] = succs
2092 if collapsednodes:
2093 replacements[tuple(collapsednodes)] = (collapsedas,)
2094 if fm:
2095 hf = fm.hexfunc
2096 fl = fm.formatlist
2097 fd = fm.formatdict
2098 changes = {}
2099 for oldns, newn in replacements.items():
2100 for oldn in oldns:
2101 changes[hf(oldn)] = fl([hf(n) for n in newn], name=b'node')
2102 nodechanges = fd(changes, key=b"oldnode", value=b"newnodes")
2103 fm.data(nodechanges=nodechanges)
2104 if keepf:
2105 replacements = {}
2106 cmdutil.cleanup_nodes(repo, replacements, b'rebase', moves, backup=backup)
2107
2108
2109 def pullrebase(orig, ui, repo, *args, **opts):
2110 """Call rebase after pull if the latter has been invoked with --rebase"""
2111 if opts.get('rebase'):
2112 if ui.configbool(b'commands', b'rebase.requiredest'):
2113 msg = _(b'rebase destination required by configuration')
2114 hint = _(b'use hg pull followed by hg rebase -d DEST')
2115 raise error.InputError(msg, hint=hint)
2116
2117 with repo.wlock(), repo.lock():
2118 if opts.get('update'):
2119 del opts['update']
2120 ui.debug(
2121 b'--update and --rebase are not compatible, ignoring '
2122 b'the update flag\n'
2123 )
2124
2125 cmdutil.checkunfinished(repo, skipmerge=True)
2126 scmutil.bail_if_changed(
2127 repo,
2128 hint=_(
2129 b'cannot pull with rebase: '
2130 b'please commit or shelve your changes first'
2131 ),
2132 )
2133
2134 revsprepull = len(repo)
2135 origpostincoming = cmdutil.postincoming
2136
2137 def _dummy(*args, **kwargs):
2138 pass
2139
2140 cmdutil.postincoming = _dummy
2141 try:
2142 ret = orig(ui, repo, *args, **opts)
2143 finally:
2144 cmdutil.postincoming = origpostincoming
2145 revspostpull = len(repo)
2146 if revspostpull > revsprepull:
2147 # --rev option from pull conflict with rebase own --rev
2148 # dropping it
2149 if 'rev' in opts:
2150 del opts['rev']
2151 # positional argument from pull conflicts with rebase's own
2152 # --source.
2153 if 'source' in opts:
2154 del opts['source']
2155 # revsprepull is the len of the repo, not revnum of tip.
2156 destspace = list(repo.changelog.revs(start=revsprepull))
2157 opts['_destspace'] = destspace
2158 try:
2159 rebase(ui, repo, **opts)
2160 except error.NoMergeDestAbort:
2161 # we can maybe update instead
2162 rev, _a, _b = destutil.destupdate(repo)
2163 if rev == repo[b'.'].rev():
2164 ui.status(_(b'nothing to rebase\n'))
2165 else:
2166 ui.status(_(b'nothing to rebase - updating instead\n'))
2167 # not passing argument to get the bare update behavior
2168 # with warning and trumpets
2169 commands.update(ui, repo)
2170 else:
2171 if opts.get('tool'):
2172 raise error.InputError(_(b'--tool can only be used with --rebase'))
2173 ret = orig(ui, repo, *args, **opts)
2174
2175 return ret
2176
2177
2178 def _compute_obsolete_sets(repo, rebaseobsrevs, destmap):
2179 """Figure out what to do about about obsolete revisions
2180
2181 `obsolete_with_successor_in_destination` is a mapping mapping obsolete => successor for all
2182 obsolete nodes to be rebased given in `rebaseobsrevs`.
2183
2184 `obsolete_with_successor_in_rebase_set` is a set with obsolete revisions,
2185 without a successor in destination, that would cause divergence.
2186 """
2187 obsolete_with_successor_in_destination = {}
2188 obsolete_with_successor_in_rebase_set = set()
2189
2190 cl = repo.changelog
2191 get_rev = cl.index.get_rev
2192 extinctrevs = set(repo.revs(b'extinct()'))
2193 for srcrev in rebaseobsrevs:
2194 srcnode = cl.node(srcrev)
2195 # XXX: more advanced APIs are required to handle split correctly
2196 successors = set(obsutil.allsuccessors(repo.obsstore, [srcnode]))
2197 # obsutil.allsuccessors includes node itself
2198 successors.remove(srcnode)
2199 succrevs = {get_rev(s) for s in successors}
2200 succrevs.discard(None)
2201 if not successors or succrevs.issubset(extinctrevs):
2202 # no successor, or all successors are extinct
2203 obsolete_with_successor_in_destination[srcrev] = None
2204 else:
2205 dstrev = destmap[srcrev]
2206 for succrev in succrevs:
2207 if cl.isancestorrev(succrev, dstrev):
2208 obsolete_with_successor_in_destination[srcrev] = succrev
2209 break
2210 else:
2211 # If 'srcrev' has a successor in rebase set but none in
2212 # destination (which would be catched above), we shall skip it
2213 # and its descendants to avoid divergence.
2214 if srcrev in extinctrevs or any(s in destmap for s in succrevs):
2215 obsolete_with_successor_in_rebase_set.add(srcrev)
2216
2217 return (
2218 obsolete_with_successor_in_destination,
2219 obsolete_with_successor_in_rebase_set,
2220 )
2221
2222
2223 def abortrebase(ui, repo):
2224 with repo.wlock(), repo.lock():
2225 rbsrt = rebaseruntime(repo, ui)
2226 rbsrt._prepareabortorcontinue(isabort=True)
2227
2228
2229 def continuerebase(ui, repo):
2230 with repo.wlock(), repo.lock():
2231 rbsrt = rebaseruntime(repo, ui)
2232 ms = mergestatemod.mergestate.read(repo)
2233 mergeutil.checkunresolved(ms)
2234 retcode = rbsrt._prepareabortorcontinue(isabort=False)
2235 if retcode is not None:
2236 return retcode
2237 rbsrt._performrebase(None)
2238 rbsrt._finishrebase()
2239
2240
2241 def summaryhook(ui, repo):
2242 if not repo.vfs.exists(b'rebasestate'):
2243 return
2244 try:
2245 rbsrt = rebaseruntime(repo, ui, {})
2246 rbsrt.restorestatus()
2247 state = rbsrt.state
2248 except error.RepoLookupError:
2249 # i18n: column positioning for "hg summary"
2250 msg = _(b'rebase: (use "hg rebase --abort" to clear broken state)\n')
2251 ui.write(msg)
2252 return
2253 numrebased = len([i for i in state.values() if i >= 0])
2254 # i18n: column positioning for "hg summary"
2255 ui.write(
2256 _(b'rebase: %s, %s (rebase --continue)\n')
2257 % (
2258 ui.label(_(b'%d rebased'), b'rebase.rebased') % numrebased,
2259 ui.label(_(b'%d remaining'), b'rebase.remaining')
2260 % (len(state) - numrebased),
2261 )
2262 )
2263
2264
2265 def uisetup(ui):
2266 # Replace pull with a decorator to provide --rebase option
2267 entry = extensions.wrapcommand(commands.table, b'pull', pullrebase)
2268 entry[1].append(
2269 (b'', b'rebase', None, _(b"rebase working directory to branch head"))
2270 )
2271 entry[1].append((b't', b'tool', b'', _(b"specify merge tool for rebase")))
2272 cmdutil.summaryhooks.add(b'rebase', summaryhook)
2273 statemod.addunfinished(
2274 b'rebase',
2275 fname=b'rebasestate',
2276 stopflag=True,
2277 continueflag=True,
2278 abortfunc=abortrebase,
2279 continuefunc=continuerebase,
2280 )