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