##// END OF EJS Templates
rebase: add returning value from pullrebase function...
liscju -
r26960:6979fe2a stable
parent child Browse files
Show More
@@ -1,1230 +1,1233
1 # rebase.py - rebasing feature for mercurial
1 # rebase.py - rebasing feature for mercurial
2 #
2 #
3 # Copyright 2008 Stefano Tortarolo <stefano.tortarolo at gmail dot com>
3 # Copyright 2008 Stefano Tortarolo <stefano.tortarolo at gmail dot com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
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.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''command to move sets of revisions to a different ancestor
8 '''command to move sets of revisions to a different ancestor
9
9
10 This extension lets you rebase changesets in an existing Mercurial
10 This extension lets you rebase changesets in an existing Mercurial
11 repository.
11 repository.
12
12
13 For more information:
13 For more information:
14 https://mercurial-scm.org/wiki/RebaseExtension
14 https://mercurial-scm.org/wiki/RebaseExtension
15 '''
15 '''
16
16
17 from mercurial import hg, util, repair, merge, cmdutil, commands, bookmarks
17 from mercurial import hg, util, repair, merge, cmdutil, commands, bookmarks
18 from mercurial import extensions, patch, scmutil, phases, obsolete, error
18 from mercurial import extensions, patch, scmutil, phases, obsolete, error
19 from mercurial import copies, repoview, revset
19 from mercurial import copies, repoview, revset
20 from mercurial.commands import templateopts
20 from mercurial.commands import templateopts
21 from mercurial.node import nullrev, nullid, hex, short
21 from mercurial.node import nullrev, nullid, hex, short
22 from mercurial.lock import release
22 from mercurial.lock import release
23 from mercurial.i18n import _
23 from mercurial.i18n import _
24 import os, errno
24 import os, errno
25
25
26 # The following constants are used throughout the rebase module. The ordering of
26 # The following constants are used throughout the rebase module. The ordering of
27 # their values must be maintained.
27 # their values must be maintained.
28
28
29 # Indicates that a revision needs to be rebased
29 # Indicates that a revision needs to be rebased
30 revtodo = -1
30 revtodo = -1
31 nullmerge = -2
31 nullmerge = -2
32 revignored = -3
32 revignored = -3
33 # To do with obsolescence
33 # To do with obsolescence
34 revprecursor = -4
34 revprecursor = -4
35
35
36 cmdtable = {}
36 cmdtable = {}
37 command = cmdutil.command(cmdtable)
37 command = cmdutil.command(cmdtable)
38 # Note for extension authors: ONLY specify testedwith = 'internal' for
38 # Note for extension authors: ONLY specify testedwith = 'internal' for
39 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
39 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
40 # be specifying the version(s) of Mercurial they are tested with, or
40 # be specifying the version(s) of Mercurial they are tested with, or
41 # leave the attribute unspecified.
41 # leave the attribute unspecified.
42 testedwith = 'internal'
42 testedwith = 'internal'
43
43
44 def _nothingtorebase():
44 def _nothingtorebase():
45 return 1
45 return 1
46
46
47 def _savegraft(ctx, extra):
47 def _savegraft(ctx, extra):
48 s = ctx.extra().get('source', None)
48 s = ctx.extra().get('source', None)
49 if s is not None:
49 if s is not None:
50 extra['source'] = s
50 extra['source'] = s
51
51
52 def _savebranch(ctx, extra):
52 def _savebranch(ctx, extra):
53 extra['branch'] = ctx.branch()
53 extra['branch'] = ctx.branch()
54
54
55 def _makeextrafn(copiers):
55 def _makeextrafn(copiers):
56 """make an extrafn out of the given copy-functions.
56 """make an extrafn out of the given copy-functions.
57
57
58 A copy function takes a context and an extra dict, and mutates the
58 A copy function takes a context and an extra dict, and mutates the
59 extra dict as needed based on the given context.
59 extra dict as needed based on the given context.
60 """
60 """
61 def extrafn(ctx, extra):
61 def extrafn(ctx, extra):
62 for c in copiers:
62 for c in copiers:
63 c(ctx, extra)
63 c(ctx, extra)
64 return extrafn
64 return extrafn
65
65
66 def _destrebase(repo):
66 def _destrebase(repo):
67 # Destination defaults to the latest revision in the
67 # Destination defaults to the latest revision in the
68 # current branch
68 # current branch
69 branch = repo[None].branch()
69 branch = repo[None].branch()
70 return repo[branch].rev()
70 return repo[branch].rev()
71
71
72 def _revsetdestrebase(repo, subset, x):
72 def _revsetdestrebase(repo, subset, x):
73 # ``_rebasedefaultdest()``
73 # ``_rebasedefaultdest()``
74
74
75 # default destination for rebase.
75 # default destination for rebase.
76 # # XXX: Currently private because I expect the signature to change.
76 # # XXX: Currently private because I expect the signature to change.
77 # # XXX: - taking rev as arguments,
77 # # XXX: - taking rev as arguments,
78 # # XXX: - bailing out in case of ambiguity vs returning all data.
78 # # XXX: - bailing out in case of ambiguity vs returning all data.
79 # # XXX: - probably merging with the merge destination.
79 # # XXX: - probably merging with the merge destination.
80 # i18n: "_rebasedefaultdest" is a keyword
80 # i18n: "_rebasedefaultdest" is a keyword
81 revset.getargs(x, 0, 0, _("_rebasedefaultdest takes no arguments"))
81 revset.getargs(x, 0, 0, _("_rebasedefaultdest takes no arguments"))
82 return subset & revset.baseset([_destrebase(repo)])
82 return subset & revset.baseset([_destrebase(repo)])
83
83
84 @command('rebase',
84 @command('rebase',
85 [('s', 'source', '',
85 [('s', 'source', '',
86 _('rebase the specified changeset and descendants'), _('REV')),
86 _('rebase the specified changeset and descendants'), _('REV')),
87 ('b', 'base', '',
87 ('b', 'base', '',
88 _('rebase everything from branching point of specified changeset'),
88 _('rebase everything from branching point of specified changeset'),
89 _('REV')),
89 _('REV')),
90 ('r', 'rev', [],
90 ('r', 'rev', [],
91 _('rebase these revisions'),
91 _('rebase these revisions'),
92 _('REV')),
92 _('REV')),
93 ('d', 'dest', '',
93 ('d', 'dest', '',
94 _('rebase onto the specified changeset'), _('REV')),
94 _('rebase onto the specified changeset'), _('REV')),
95 ('', 'collapse', False, _('collapse the rebased changesets')),
95 ('', 'collapse', False, _('collapse the rebased changesets')),
96 ('m', 'message', '',
96 ('m', 'message', '',
97 _('use text as collapse commit message'), _('TEXT')),
97 _('use text as collapse commit message'), _('TEXT')),
98 ('e', 'edit', False, _('invoke editor on commit messages')),
98 ('e', 'edit', False, _('invoke editor on commit messages')),
99 ('l', 'logfile', '',
99 ('l', 'logfile', '',
100 _('read collapse commit message from file'), _('FILE')),
100 _('read collapse commit message from file'), _('FILE')),
101 ('k', 'keep', False, _('keep original changesets')),
101 ('k', 'keep', False, _('keep original changesets')),
102 ('', 'keepbranches', False, _('keep original branch names')),
102 ('', 'keepbranches', False, _('keep original branch names')),
103 ('D', 'detach', False, _('(DEPRECATED)')),
103 ('D', 'detach', False, _('(DEPRECATED)')),
104 ('i', 'interactive', False, _('(DEPRECATED)')),
104 ('i', 'interactive', False, _('(DEPRECATED)')),
105 ('t', 'tool', '', _('specify merge tool')),
105 ('t', 'tool', '', _('specify merge tool')),
106 ('c', 'continue', False, _('continue an interrupted rebase')),
106 ('c', 'continue', False, _('continue an interrupted rebase')),
107 ('a', 'abort', False, _('abort an interrupted rebase'))] +
107 ('a', 'abort', False, _('abort an interrupted rebase'))] +
108 templateopts,
108 templateopts,
109 _('[-s REV | -b REV] [-d REV] [OPTION]'))
109 _('[-s REV | -b REV] [-d REV] [OPTION]'))
110 def rebase(ui, repo, **opts):
110 def rebase(ui, repo, **opts):
111 """move changeset (and descendants) to a different branch
111 """move changeset (and descendants) to a different branch
112
112
113 Rebase uses repeated merging to graft changesets from one part of
113 Rebase uses repeated merging to graft changesets from one part of
114 history (the source) onto another (the destination). This can be
114 history (the source) onto another (the destination). This can be
115 useful for linearizing *local* changes relative to a master
115 useful for linearizing *local* changes relative to a master
116 development tree.
116 development tree.
117
117
118 You should not rebase changesets that have already been shared
118 You should not rebase changesets that have already been shared
119 with others. Doing so will force everybody else to perform the
119 with others. Doing so will force everybody else to perform the
120 same rebase or they will end up with duplicated changesets after
120 same rebase or they will end up with duplicated changesets after
121 pulling in your rebased changesets.
121 pulling in your rebased changesets.
122
122
123 In its default configuration, Mercurial will prevent you from
123 In its default configuration, Mercurial will prevent you from
124 rebasing published changes. See :hg:`help phases` for details.
124 rebasing published changes. See :hg:`help phases` for details.
125
125
126 If you don't specify a destination changeset (``-d/--dest``),
126 If you don't specify a destination changeset (``-d/--dest``),
127 rebase uses the current branch tip as the destination. (The
127 rebase uses the current branch tip as the destination. (The
128 destination changeset is not modified by rebasing, but new
128 destination changeset is not modified by rebasing, but new
129 changesets are added as its descendants.)
129 changesets are added as its descendants.)
130
130
131 You can specify which changesets to rebase in two ways: as a
131 You can specify which changesets to rebase in two ways: as a
132 "source" changeset or as a "base" changeset. Both are shorthand
132 "source" changeset or as a "base" changeset. Both are shorthand
133 for a topologically related set of changesets (the "source
133 for a topologically related set of changesets (the "source
134 branch"). If you specify source (``-s/--source``), rebase will
134 branch"). If you specify source (``-s/--source``), rebase will
135 rebase that changeset and all of its descendants onto dest. If you
135 rebase that changeset and all of its descendants onto dest. If you
136 specify base (``-b/--base``), rebase will select ancestors of base
136 specify base (``-b/--base``), rebase will select ancestors of base
137 back to but not including the common ancestor with dest. Thus,
137 back to but not including the common ancestor with dest. Thus,
138 ``-b`` is less precise but more convenient than ``-s``: you can
138 ``-b`` is less precise but more convenient than ``-s``: you can
139 specify any changeset in the source branch, and rebase will select
139 specify any changeset in the source branch, and rebase will select
140 the whole branch. If you specify neither ``-s`` nor ``-b``, rebase
140 the whole branch. If you specify neither ``-s`` nor ``-b``, rebase
141 uses the parent of the working directory as the base.
141 uses the parent of the working directory as the base.
142
142
143 For advanced usage, a third way is available through the ``--rev``
143 For advanced usage, a third way is available through the ``--rev``
144 option. It allows you to specify an arbitrary set of changesets to
144 option. It allows you to specify an arbitrary set of changesets to
145 rebase. Descendants of revs you specify with this option are not
145 rebase. Descendants of revs you specify with this option are not
146 automatically included in the rebase.
146 automatically included in the rebase.
147
147
148 By default, rebase recreates the changesets in the source branch
148 By default, rebase recreates the changesets in the source branch
149 as descendants of dest and then destroys the originals. Use
149 as descendants of dest and then destroys the originals. Use
150 ``--keep`` to preserve the original source changesets. Some
150 ``--keep`` to preserve the original source changesets. Some
151 changesets in the source branch (e.g. merges from the destination
151 changesets in the source branch (e.g. merges from the destination
152 branch) may be dropped if they no longer contribute any change.
152 branch) may be dropped if they no longer contribute any change.
153
153
154 One result of the rules for selecting the destination changeset
154 One result of the rules for selecting the destination changeset
155 and source branch is that, unlike ``merge``, rebase will do
155 and source branch is that, unlike ``merge``, rebase will do
156 nothing if you are at the branch tip of a named branch
156 nothing if you are at the branch tip of a named branch
157 with two heads. You need to explicitly specify source and/or
157 with two heads. You need to explicitly specify source and/or
158 destination (or ``update`` to the other head, if it's the head of
158 destination (or ``update`` to the other head, if it's the head of
159 the intended source branch).
159 the intended source branch).
160
160
161 If a rebase is interrupted to manually resolve a merge, it can be
161 If a rebase is interrupted to manually resolve a merge, it can be
162 continued with --continue/-c or aborted with --abort/-a.
162 continued with --continue/-c or aborted with --abort/-a.
163
163
164 .. container:: verbose
164 .. container:: verbose
165
165
166 Examples:
166 Examples:
167
167
168 - move "local changes" (current commit back to branching point)
168 - move "local changes" (current commit back to branching point)
169 to the current branch tip after a pull::
169 to the current branch tip after a pull::
170
170
171 hg rebase
171 hg rebase
172
172
173 - move a single changeset to the stable branch::
173 - move a single changeset to the stable branch::
174
174
175 hg rebase -r 5f493448 -d stable
175 hg rebase -r 5f493448 -d stable
176
176
177 - splice a commit and all its descendants onto another part of history::
177 - splice a commit and all its descendants onto another part of history::
178
178
179 hg rebase --source c0c3 --dest 4cf9
179 hg rebase --source c0c3 --dest 4cf9
180
180
181 - rebase everything on a branch marked by a bookmark onto the
181 - rebase everything on a branch marked by a bookmark onto the
182 default branch::
182 default branch::
183
183
184 hg rebase --base myfeature --dest default
184 hg rebase --base myfeature --dest default
185
185
186 - collapse a sequence of changes into a single commit::
186 - collapse a sequence of changes into a single commit::
187
187
188 hg rebase --collapse -r 1520:1525 -d .
188 hg rebase --collapse -r 1520:1525 -d .
189
189
190 - move a named branch while preserving its name::
190 - move a named branch while preserving its name::
191
191
192 hg rebase -r "branch(featureX)" -d 1.3 --keepbranches
192 hg rebase -r "branch(featureX)" -d 1.3 --keepbranches
193
193
194 Returns 0 on success, 1 if nothing to rebase or there are
194 Returns 0 on success, 1 if nothing to rebase or there are
195 unresolved conflicts.
195 unresolved conflicts.
196
196
197 """
197 """
198 originalwd = target = None
198 originalwd = target = None
199 activebookmark = None
199 activebookmark = None
200 external = nullrev
200 external = nullrev
201 # Mapping between the old revision id and either what is the new rebased
201 # Mapping between the old revision id and either what is the new rebased
202 # revision or what needs to be done with the old revision. The state dict
202 # revision or what needs to be done with the old revision. The state dict
203 # will be what contains most of the rebase progress state.
203 # will be what contains most of the rebase progress state.
204 state = {}
204 state = {}
205 skipped = set()
205 skipped = set()
206 targetancestors = set()
206 targetancestors = set()
207
207
208
208
209 lock = wlock = None
209 lock = wlock = None
210 try:
210 try:
211 wlock = repo.wlock()
211 wlock = repo.wlock()
212 lock = repo.lock()
212 lock = repo.lock()
213
213
214 # Validate input and define rebasing points
214 # Validate input and define rebasing points
215 destf = opts.get('dest', None)
215 destf = opts.get('dest', None)
216 srcf = opts.get('source', None)
216 srcf = opts.get('source', None)
217 basef = opts.get('base', None)
217 basef = opts.get('base', None)
218 revf = opts.get('rev', [])
218 revf = opts.get('rev', [])
219 contf = opts.get('continue')
219 contf = opts.get('continue')
220 abortf = opts.get('abort')
220 abortf = opts.get('abort')
221 collapsef = opts.get('collapse', False)
221 collapsef = opts.get('collapse', False)
222 collapsemsg = cmdutil.logmessage(ui, opts)
222 collapsemsg = cmdutil.logmessage(ui, opts)
223 e = opts.get('extrafn') # internal, used by e.g. hgsubversion
223 e = opts.get('extrafn') # internal, used by e.g. hgsubversion
224 extrafns = [_savegraft]
224 extrafns = [_savegraft]
225 if e:
225 if e:
226 extrafns = [e]
226 extrafns = [e]
227 keepf = opts.get('keep', False)
227 keepf = opts.get('keep', False)
228 keepbranchesf = opts.get('keepbranches', False)
228 keepbranchesf = opts.get('keepbranches', False)
229 # keepopen is not meant for use on the command line, but by
229 # keepopen is not meant for use on the command line, but by
230 # other extensions
230 # other extensions
231 keepopen = opts.get('keepopen', False)
231 keepopen = opts.get('keepopen', False)
232
232
233 if opts.get('interactive'):
233 if opts.get('interactive'):
234 try:
234 try:
235 if extensions.find('histedit'):
235 if extensions.find('histedit'):
236 enablehistedit = ''
236 enablehistedit = ''
237 except KeyError:
237 except KeyError:
238 enablehistedit = " --config extensions.histedit="
238 enablehistedit = " --config extensions.histedit="
239 help = "hg%s help -e histedit" % enablehistedit
239 help = "hg%s help -e histedit" % enablehistedit
240 msg = _("interactive history editing is supported by the "
240 msg = _("interactive history editing is supported by the "
241 "'histedit' extension (see \"%s\")") % help
241 "'histedit' extension (see \"%s\")") % help
242 raise error.Abort(msg)
242 raise error.Abort(msg)
243
243
244 if collapsemsg and not collapsef:
244 if collapsemsg and not collapsef:
245 raise error.Abort(
245 raise error.Abort(
246 _('message can only be specified with collapse'))
246 _('message can only be specified with collapse'))
247
247
248 if contf or abortf:
248 if contf or abortf:
249 if contf and abortf:
249 if contf and abortf:
250 raise error.Abort(_('cannot use both abort and continue'))
250 raise error.Abort(_('cannot use both abort and continue'))
251 if collapsef:
251 if collapsef:
252 raise error.Abort(
252 raise error.Abort(
253 _('cannot use collapse with continue or abort'))
253 _('cannot use collapse with continue or abort'))
254 if srcf or basef or destf:
254 if srcf or basef or destf:
255 raise error.Abort(
255 raise error.Abort(
256 _('abort and continue do not allow specifying revisions'))
256 _('abort and continue do not allow specifying revisions'))
257 if abortf and opts.get('tool', False):
257 if abortf and opts.get('tool', False):
258 ui.warn(_('tool option will be ignored\n'))
258 ui.warn(_('tool option will be ignored\n'))
259
259
260 try:
260 try:
261 (originalwd, target, state, skipped, collapsef, keepf,
261 (originalwd, target, state, skipped, collapsef, keepf,
262 keepbranchesf, external, activebookmark) = restorestatus(repo)
262 keepbranchesf, external, activebookmark) = restorestatus(repo)
263 except error.RepoLookupError:
263 except error.RepoLookupError:
264 if abortf:
264 if abortf:
265 clearstatus(repo)
265 clearstatus(repo)
266 repo.ui.warn(_('rebase aborted (no revision is removed,'
266 repo.ui.warn(_('rebase aborted (no revision is removed,'
267 ' only broken state is cleared)\n'))
267 ' only broken state is cleared)\n'))
268 return 0
268 return 0
269 else:
269 else:
270 msg = _('cannot continue inconsistent rebase')
270 msg = _('cannot continue inconsistent rebase')
271 hint = _('use "hg rebase --abort" to clear broken state')
271 hint = _('use "hg rebase --abort" to clear broken state')
272 raise error.Abort(msg, hint=hint)
272 raise error.Abort(msg, hint=hint)
273 if abortf:
273 if abortf:
274 return abort(repo, originalwd, target, state,
274 return abort(repo, originalwd, target, state,
275 activebookmark=activebookmark)
275 activebookmark=activebookmark)
276 else:
276 else:
277 if srcf and basef:
277 if srcf and basef:
278 raise error.Abort(_('cannot specify both a '
278 raise error.Abort(_('cannot specify both a '
279 'source and a base'))
279 'source and a base'))
280 if revf and basef:
280 if revf and basef:
281 raise error.Abort(_('cannot specify both a '
281 raise error.Abort(_('cannot specify both a '
282 'revision and a base'))
282 'revision and a base'))
283 if revf and srcf:
283 if revf and srcf:
284 raise error.Abort(_('cannot specify both a '
284 raise error.Abort(_('cannot specify both a '
285 'revision and a source'))
285 'revision and a source'))
286
286
287 cmdutil.checkunfinished(repo)
287 cmdutil.checkunfinished(repo)
288 cmdutil.bailifchanged(repo)
288 cmdutil.bailifchanged(repo)
289
289
290 if destf:
290 if destf:
291 dest = scmutil.revsingle(repo, destf)
291 dest = scmutil.revsingle(repo, destf)
292 else:
292 else:
293 dest = repo[_destrebase(repo)]
293 dest = repo[_destrebase(repo)]
294 destf = str(dest)
294 destf = str(dest)
295
295
296 if revf:
296 if revf:
297 rebaseset = scmutil.revrange(repo, revf)
297 rebaseset = scmutil.revrange(repo, revf)
298 if not rebaseset:
298 if not rebaseset:
299 ui.status(_('empty "rev" revision set - '
299 ui.status(_('empty "rev" revision set - '
300 'nothing to rebase\n'))
300 'nothing to rebase\n'))
301 return _nothingtorebase()
301 return _nothingtorebase()
302 elif srcf:
302 elif srcf:
303 src = scmutil.revrange(repo, [srcf])
303 src = scmutil.revrange(repo, [srcf])
304 if not src:
304 if not src:
305 ui.status(_('empty "source" revision set - '
305 ui.status(_('empty "source" revision set - '
306 'nothing to rebase\n'))
306 'nothing to rebase\n'))
307 return _nothingtorebase()
307 return _nothingtorebase()
308 rebaseset = repo.revs('(%ld)::', src)
308 rebaseset = repo.revs('(%ld)::', src)
309 assert rebaseset
309 assert rebaseset
310 else:
310 else:
311 base = scmutil.revrange(repo, [basef or '.'])
311 base = scmutil.revrange(repo, [basef or '.'])
312 if not base:
312 if not base:
313 ui.status(_('empty "base" revision set - '
313 ui.status(_('empty "base" revision set - '
314 "can't compute rebase set\n"))
314 "can't compute rebase set\n"))
315 return _nothingtorebase()
315 return _nothingtorebase()
316 commonanc = repo.revs('ancestor(%ld, %d)', base, dest).first()
316 commonanc = repo.revs('ancestor(%ld, %d)', base, dest).first()
317 if commonanc is not None:
317 if commonanc is not None:
318 rebaseset = repo.revs('(%d::(%ld) - %d)::',
318 rebaseset = repo.revs('(%d::(%ld) - %d)::',
319 commonanc, base, commonanc)
319 commonanc, base, commonanc)
320 else:
320 else:
321 rebaseset = []
321 rebaseset = []
322
322
323 if not rebaseset:
323 if not rebaseset:
324 # transform to list because smartsets are not comparable to
324 # transform to list because smartsets are not comparable to
325 # lists. This should be improved to honor laziness of
325 # lists. This should be improved to honor laziness of
326 # smartset.
326 # smartset.
327 if list(base) == [dest.rev()]:
327 if list(base) == [dest.rev()]:
328 if basef:
328 if basef:
329 ui.status(_('nothing to rebase - %s is both "base"'
329 ui.status(_('nothing to rebase - %s is both "base"'
330 ' and destination\n') % dest)
330 ' and destination\n') % dest)
331 else:
331 else:
332 ui.status(_('nothing to rebase - working directory '
332 ui.status(_('nothing to rebase - working directory '
333 'parent is also destination\n'))
333 'parent is also destination\n'))
334 elif not repo.revs('%ld - ::%d', base, dest):
334 elif not repo.revs('%ld - ::%d', base, dest):
335 if basef:
335 if basef:
336 ui.status(_('nothing to rebase - "base" %s is '
336 ui.status(_('nothing to rebase - "base" %s is '
337 'already an ancestor of destination '
337 'already an ancestor of destination '
338 '%s\n') %
338 '%s\n') %
339 ('+'.join(str(repo[r]) for r in base),
339 ('+'.join(str(repo[r]) for r in base),
340 dest))
340 dest))
341 else:
341 else:
342 ui.status(_('nothing to rebase - working '
342 ui.status(_('nothing to rebase - working '
343 'directory parent is already an '
343 'directory parent is already an '
344 'ancestor of destination %s\n') % dest)
344 'ancestor of destination %s\n') % dest)
345 else: # can it happen?
345 else: # can it happen?
346 ui.status(_('nothing to rebase from %s to %s\n') %
346 ui.status(_('nothing to rebase from %s to %s\n') %
347 ('+'.join(str(repo[r]) for r in base), dest))
347 ('+'.join(str(repo[r]) for r in base), dest))
348 return _nothingtorebase()
348 return _nothingtorebase()
349
349
350 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
350 allowunstable = obsolete.isenabled(repo, obsolete.allowunstableopt)
351 if (not (keepf or allowunstable)
351 if (not (keepf or allowunstable)
352 and repo.revs('first(children(%ld) - %ld)',
352 and repo.revs('first(children(%ld) - %ld)',
353 rebaseset, rebaseset)):
353 rebaseset, rebaseset)):
354 raise error.Abort(
354 raise error.Abort(
355 _("can't remove original changesets with"
355 _("can't remove original changesets with"
356 " unrebased descendants"),
356 " unrebased descendants"),
357 hint=_('use --keep to keep original changesets'))
357 hint=_('use --keep to keep original changesets'))
358
358
359 obsoletenotrebased = {}
359 obsoletenotrebased = {}
360 if ui.configbool('experimental', 'rebaseskipobsolete'):
360 if ui.configbool('experimental', 'rebaseskipobsolete'):
361 rebasesetrevs = set(rebaseset)
361 rebasesetrevs = set(rebaseset)
362 obsoletenotrebased = _computeobsoletenotrebased(repo,
362 obsoletenotrebased = _computeobsoletenotrebased(repo,
363 rebasesetrevs,
363 rebasesetrevs,
364 dest)
364 dest)
365
365
366 # - plain prune (no successor) changesets are rebased
366 # - plain prune (no successor) changesets are rebased
367 # - split changesets are not rebased if at least one of the
367 # - split changesets are not rebased if at least one of the
368 # changeset resulting from the split is an ancestor of dest
368 # changeset resulting from the split is an ancestor of dest
369 rebaseset = rebasesetrevs - set(obsoletenotrebased)
369 rebaseset = rebasesetrevs - set(obsoletenotrebased)
370 result = buildstate(repo, dest, rebaseset, collapsef,
370 result = buildstate(repo, dest, rebaseset, collapsef,
371 obsoletenotrebased)
371 obsoletenotrebased)
372
372
373 if not result:
373 if not result:
374 # Empty state built, nothing to rebase
374 # Empty state built, nothing to rebase
375 ui.status(_('nothing to rebase\n'))
375 ui.status(_('nothing to rebase\n'))
376 return _nothingtorebase()
376 return _nothingtorebase()
377
377
378 root = min(rebaseset)
378 root = min(rebaseset)
379 if not keepf and not repo[root].mutable():
379 if not keepf and not repo[root].mutable():
380 raise error.Abort(_("can't rebase public changeset %s")
380 raise error.Abort(_("can't rebase public changeset %s")
381 % repo[root],
381 % repo[root],
382 hint=_('see "hg help phases" for details'))
382 hint=_('see "hg help phases" for details'))
383
383
384 originalwd, target, state = result
384 originalwd, target, state = result
385 if collapsef:
385 if collapsef:
386 targetancestors = repo.changelog.ancestors([target],
386 targetancestors = repo.changelog.ancestors([target],
387 inclusive=True)
387 inclusive=True)
388 external = externalparent(repo, state, targetancestors)
388 external = externalparent(repo, state, targetancestors)
389
389
390 if dest.closesbranch() and not keepbranchesf:
390 if dest.closesbranch() and not keepbranchesf:
391 ui.status(_('reopening closed branch head %s\n') % dest)
391 ui.status(_('reopening closed branch head %s\n') % dest)
392
392
393 if keepbranchesf:
393 if keepbranchesf:
394 # insert _savebranch at the start of extrafns so if
394 # insert _savebranch at the start of extrafns so if
395 # there's a user-provided extrafn it can clobber branch if
395 # there's a user-provided extrafn it can clobber branch if
396 # desired
396 # desired
397 extrafns.insert(0, _savebranch)
397 extrafns.insert(0, _savebranch)
398 if collapsef:
398 if collapsef:
399 branches = set()
399 branches = set()
400 for rev in state:
400 for rev in state:
401 branches.add(repo[rev].branch())
401 branches.add(repo[rev].branch())
402 if len(branches) > 1:
402 if len(branches) > 1:
403 raise error.Abort(_('cannot collapse multiple named '
403 raise error.Abort(_('cannot collapse multiple named '
404 'branches'))
404 'branches'))
405
405
406 # Rebase
406 # Rebase
407 if not targetancestors:
407 if not targetancestors:
408 targetancestors = repo.changelog.ancestors([target], inclusive=True)
408 targetancestors = repo.changelog.ancestors([target], inclusive=True)
409
409
410 # Keep track of the current bookmarks in order to reset them later
410 # Keep track of the current bookmarks in order to reset them later
411 currentbookmarks = repo._bookmarks.copy()
411 currentbookmarks = repo._bookmarks.copy()
412 activebookmark = activebookmark or repo._activebookmark
412 activebookmark = activebookmark or repo._activebookmark
413 if activebookmark:
413 if activebookmark:
414 bookmarks.deactivate(repo)
414 bookmarks.deactivate(repo)
415
415
416 extrafn = _makeextrafn(extrafns)
416 extrafn = _makeextrafn(extrafns)
417
417
418 sortedstate = sorted(state)
418 sortedstate = sorted(state)
419 total = len(sortedstate)
419 total = len(sortedstate)
420 pos = 0
420 pos = 0
421 for rev in sortedstate:
421 for rev in sortedstate:
422 ctx = repo[rev]
422 ctx = repo[rev]
423 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
423 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
424 ctx.description().split('\n', 1)[0])
424 ctx.description().split('\n', 1)[0])
425 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
425 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
426 if names:
426 if names:
427 desc += ' (%s)' % ' '.join(names)
427 desc += ' (%s)' % ' '.join(names)
428 pos += 1
428 pos += 1
429 if state[rev] == revtodo:
429 if state[rev] == revtodo:
430 ui.status(_('rebasing %s\n') % desc)
430 ui.status(_('rebasing %s\n') % desc)
431 ui.progress(_("rebasing"), pos, ("%d:%s" % (rev, ctx)),
431 ui.progress(_("rebasing"), pos, ("%d:%s" % (rev, ctx)),
432 _('changesets'), total)
432 _('changesets'), total)
433 p1, p2, base = defineparents(repo, rev, target, state,
433 p1, p2, base = defineparents(repo, rev, target, state,
434 targetancestors)
434 targetancestors)
435 storestatus(repo, originalwd, target, state, collapsef, keepf,
435 storestatus(repo, originalwd, target, state, collapsef, keepf,
436 keepbranchesf, external, activebookmark)
436 keepbranchesf, external, activebookmark)
437 if len(repo.parents()) == 2:
437 if len(repo.parents()) == 2:
438 repo.ui.debug('resuming interrupted rebase\n')
438 repo.ui.debug('resuming interrupted rebase\n')
439 else:
439 else:
440 try:
440 try:
441 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
441 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
442 'rebase')
442 'rebase')
443 stats = rebasenode(repo, rev, p1, base, state,
443 stats = rebasenode(repo, rev, p1, base, state,
444 collapsef, target)
444 collapsef, target)
445 if stats and stats[3] > 0:
445 if stats and stats[3] > 0:
446 raise error.InterventionRequired(
446 raise error.InterventionRequired(
447 _('unresolved conflicts (see hg '
447 _('unresolved conflicts (see hg '
448 'resolve, then hg rebase --continue)'))
448 'resolve, then hg rebase --continue)'))
449 finally:
449 finally:
450 ui.setconfig('ui', 'forcemerge', '', 'rebase')
450 ui.setconfig('ui', 'forcemerge', '', 'rebase')
451 if not collapsef:
451 if not collapsef:
452 merging = p2 != nullrev
452 merging = p2 != nullrev
453 editform = cmdutil.mergeeditform(merging, 'rebase')
453 editform = cmdutil.mergeeditform(merging, 'rebase')
454 editor = cmdutil.getcommiteditor(editform=editform, **opts)
454 editor = cmdutil.getcommiteditor(editform=editform, **opts)
455 newnode = concludenode(repo, rev, p1, p2, extrafn=extrafn,
455 newnode = concludenode(repo, rev, p1, p2, extrafn=extrafn,
456 editor=editor,
456 editor=editor,
457 keepbranches=keepbranchesf)
457 keepbranches=keepbranchesf)
458 else:
458 else:
459 # Skip commit if we are collapsing
459 # Skip commit if we are collapsing
460 repo.dirstate.beginparentchange()
460 repo.dirstate.beginparentchange()
461 repo.setparents(repo[p1].node())
461 repo.setparents(repo[p1].node())
462 repo.dirstate.endparentchange()
462 repo.dirstate.endparentchange()
463 newnode = None
463 newnode = None
464 # Update the state
464 # Update the state
465 if newnode is not None:
465 if newnode is not None:
466 state[rev] = repo[newnode].rev()
466 state[rev] = repo[newnode].rev()
467 ui.debug('rebased as %s\n' % short(newnode))
467 ui.debug('rebased as %s\n' % short(newnode))
468 else:
468 else:
469 if not collapsef:
469 if not collapsef:
470 ui.warn(_('note: rebase of %d:%s created no changes '
470 ui.warn(_('note: rebase of %d:%s created no changes '
471 'to commit\n') % (rev, ctx))
471 'to commit\n') % (rev, ctx))
472 skipped.add(rev)
472 skipped.add(rev)
473 state[rev] = p1
473 state[rev] = p1
474 ui.debug('next revision set to %s\n' % p1)
474 ui.debug('next revision set to %s\n' % p1)
475 elif state[rev] == nullmerge:
475 elif state[rev] == nullmerge:
476 ui.debug('ignoring null merge rebase of %s\n' % rev)
476 ui.debug('ignoring null merge rebase of %s\n' % rev)
477 elif state[rev] == revignored:
477 elif state[rev] == revignored:
478 ui.status(_('not rebasing ignored %s\n') % desc)
478 ui.status(_('not rebasing ignored %s\n') % desc)
479 elif state[rev] == revprecursor:
479 elif state[rev] == revprecursor:
480 targetctx = repo[obsoletenotrebased[rev]]
480 targetctx = repo[obsoletenotrebased[rev]]
481 desctarget = '%d:%s "%s"' % (targetctx.rev(), targetctx,
481 desctarget = '%d:%s "%s"' % (targetctx.rev(), targetctx,
482 targetctx.description().split('\n', 1)[0])
482 targetctx.description().split('\n', 1)[0])
483 msg = _('note: not rebasing %s, already in destination as %s\n')
483 msg = _('note: not rebasing %s, already in destination as %s\n')
484 ui.status(msg % (desc, desctarget))
484 ui.status(msg % (desc, desctarget))
485 else:
485 else:
486 ui.status(_('already rebased %s as %s\n') %
486 ui.status(_('already rebased %s as %s\n') %
487 (desc, repo[state[rev]]))
487 (desc, repo[state[rev]]))
488
488
489 ui.progress(_('rebasing'), None)
489 ui.progress(_('rebasing'), None)
490 ui.note(_('rebase merging completed\n'))
490 ui.note(_('rebase merging completed\n'))
491
491
492 if collapsef and not keepopen:
492 if collapsef and not keepopen:
493 p1, p2, _base = defineparents(repo, min(state), target,
493 p1, p2, _base = defineparents(repo, min(state), target,
494 state, targetancestors)
494 state, targetancestors)
495 editopt = opts.get('edit')
495 editopt = opts.get('edit')
496 editform = 'rebase.collapse'
496 editform = 'rebase.collapse'
497 if collapsemsg:
497 if collapsemsg:
498 commitmsg = collapsemsg
498 commitmsg = collapsemsg
499 else:
499 else:
500 commitmsg = 'Collapsed revision'
500 commitmsg = 'Collapsed revision'
501 for rebased in state:
501 for rebased in state:
502 if rebased not in skipped and state[rebased] > nullmerge:
502 if rebased not in skipped and state[rebased] > nullmerge:
503 commitmsg += '\n* %s' % repo[rebased].description()
503 commitmsg += '\n* %s' % repo[rebased].description()
504 editopt = True
504 editopt = True
505 editor = cmdutil.getcommiteditor(edit=editopt, editform=editform)
505 editor = cmdutil.getcommiteditor(edit=editopt, editform=editform)
506 newnode = concludenode(repo, rev, p1, external, commitmsg=commitmsg,
506 newnode = concludenode(repo, rev, p1, external, commitmsg=commitmsg,
507 extrafn=extrafn, editor=editor,
507 extrafn=extrafn, editor=editor,
508 keepbranches=keepbranchesf)
508 keepbranches=keepbranchesf)
509 if newnode is None:
509 if newnode is None:
510 newrev = target
510 newrev = target
511 else:
511 else:
512 newrev = repo[newnode].rev()
512 newrev = repo[newnode].rev()
513 for oldrev in state.iterkeys():
513 for oldrev in state.iterkeys():
514 if state[oldrev] > nullmerge:
514 if state[oldrev] > nullmerge:
515 state[oldrev] = newrev
515 state[oldrev] = newrev
516
516
517 if 'qtip' in repo.tags():
517 if 'qtip' in repo.tags():
518 updatemq(repo, state, skipped, **opts)
518 updatemq(repo, state, skipped, **opts)
519
519
520 if currentbookmarks:
520 if currentbookmarks:
521 # Nodeids are needed to reset bookmarks
521 # Nodeids are needed to reset bookmarks
522 nstate = {}
522 nstate = {}
523 for k, v in state.iteritems():
523 for k, v in state.iteritems():
524 if v > nullmerge:
524 if v > nullmerge:
525 nstate[repo[k].node()] = repo[v].node()
525 nstate[repo[k].node()] = repo[v].node()
526 # XXX this is the same as dest.node() for the non-continue path --
526 # XXX this is the same as dest.node() for the non-continue path --
527 # this should probably be cleaned up
527 # this should probably be cleaned up
528 targetnode = repo[target].node()
528 targetnode = repo[target].node()
529
529
530 # restore original working directory
530 # restore original working directory
531 # (we do this before stripping)
531 # (we do this before stripping)
532 newwd = state.get(originalwd, originalwd)
532 newwd = state.get(originalwd, originalwd)
533 if newwd < 0:
533 if newwd < 0:
534 # original directory is a parent of rebase set root or ignored
534 # original directory is a parent of rebase set root or ignored
535 newwd = originalwd
535 newwd = originalwd
536 if newwd not in [c.rev() for c in repo[None].parents()]:
536 if newwd not in [c.rev() for c in repo[None].parents()]:
537 ui.note(_("update back to initial working directory parent\n"))
537 ui.note(_("update back to initial working directory parent\n"))
538 hg.updaterepo(repo, newwd, False)
538 hg.updaterepo(repo, newwd, False)
539
539
540 if not keepf:
540 if not keepf:
541 collapsedas = None
541 collapsedas = None
542 if collapsef:
542 if collapsef:
543 collapsedas = newnode
543 collapsedas = newnode
544 clearrebased(ui, repo, state, skipped, collapsedas)
544 clearrebased(ui, repo, state, skipped, collapsedas)
545
545
546 if currentbookmarks:
546 if currentbookmarks:
547 updatebookmarks(repo, targetnode, nstate, currentbookmarks)
547 updatebookmarks(repo, targetnode, nstate, currentbookmarks)
548 if activebookmark not in repo._bookmarks:
548 if activebookmark not in repo._bookmarks:
549 # active bookmark was divergent one and has been deleted
549 # active bookmark was divergent one and has been deleted
550 activebookmark = None
550 activebookmark = None
551
551
552 clearstatus(repo)
552 clearstatus(repo)
553 ui.note(_("rebase completed\n"))
553 ui.note(_("rebase completed\n"))
554 util.unlinkpath(repo.sjoin('undo'), ignoremissing=True)
554 util.unlinkpath(repo.sjoin('undo'), ignoremissing=True)
555 if skipped:
555 if skipped:
556 ui.note(_("%d revisions have been skipped\n") % len(skipped))
556 ui.note(_("%d revisions have been skipped\n") % len(skipped))
557
557
558 if (activebookmark and
558 if (activebookmark and
559 repo['.'].node() == repo._bookmarks[activebookmark]):
559 repo['.'].node() == repo._bookmarks[activebookmark]):
560 bookmarks.activate(repo, activebookmark)
560 bookmarks.activate(repo, activebookmark)
561
561
562 finally:
562 finally:
563 release(lock, wlock)
563 release(lock, wlock)
564
564
565 def externalparent(repo, state, targetancestors):
565 def externalparent(repo, state, targetancestors):
566 """Return the revision that should be used as the second parent
566 """Return the revision that should be used as the second parent
567 when the revisions in state is collapsed on top of targetancestors.
567 when the revisions in state is collapsed on top of targetancestors.
568 Abort if there is more than one parent.
568 Abort if there is more than one parent.
569 """
569 """
570 parents = set()
570 parents = set()
571 source = min(state)
571 source = min(state)
572 for rev in state:
572 for rev in state:
573 if rev == source:
573 if rev == source:
574 continue
574 continue
575 for p in repo[rev].parents():
575 for p in repo[rev].parents():
576 if (p.rev() not in state
576 if (p.rev() not in state
577 and p.rev() not in targetancestors):
577 and p.rev() not in targetancestors):
578 parents.add(p.rev())
578 parents.add(p.rev())
579 if not parents:
579 if not parents:
580 return nullrev
580 return nullrev
581 if len(parents) == 1:
581 if len(parents) == 1:
582 return parents.pop()
582 return parents.pop()
583 raise error.Abort(_('unable to collapse on top of %s, there is more '
583 raise error.Abort(_('unable to collapse on top of %s, there is more '
584 'than one external parent: %s') %
584 'than one external parent: %s') %
585 (max(targetancestors),
585 (max(targetancestors),
586 ', '.join(str(p) for p in sorted(parents))))
586 ', '.join(str(p) for p in sorted(parents))))
587
587
588 def concludenode(repo, rev, p1, p2, commitmsg=None, editor=None, extrafn=None,
588 def concludenode(repo, rev, p1, p2, commitmsg=None, editor=None, extrafn=None,
589 keepbranches=False):
589 keepbranches=False):
590 '''Commit the wd changes with parents p1 and p2. Reuse commit info from rev
590 '''Commit the wd changes with parents p1 and p2. Reuse commit info from rev
591 but also store useful information in extra.
591 but also store useful information in extra.
592 Return node of committed revision.'''
592 Return node of committed revision.'''
593 dsguard = cmdutil.dirstateguard(repo, 'rebase')
593 dsguard = cmdutil.dirstateguard(repo, 'rebase')
594 try:
594 try:
595 repo.setparents(repo[p1].node(), repo[p2].node())
595 repo.setparents(repo[p1].node(), repo[p2].node())
596 ctx = repo[rev]
596 ctx = repo[rev]
597 if commitmsg is None:
597 if commitmsg is None:
598 commitmsg = ctx.description()
598 commitmsg = ctx.description()
599 keepbranch = keepbranches and repo[p1].branch() != ctx.branch()
599 keepbranch = keepbranches and repo[p1].branch() != ctx.branch()
600 extra = {'rebase_source': ctx.hex()}
600 extra = {'rebase_source': ctx.hex()}
601 if extrafn:
601 if extrafn:
602 extrafn(ctx, extra)
602 extrafn(ctx, extra)
603
603
604 backup = repo.ui.backupconfig('phases', 'new-commit')
604 backup = repo.ui.backupconfig('phases', 'new-commit')
605 try:
605 try:
606 targetphase = max(ctx.phase(), phases.draft)
606 targetphase = max(ctx.phase(), phases.draft)
607 repo.ui.setconfig('phases', 'new-commit', targetphase, 'rebase')
607 repo.ui.setconfig('phases', 'new-commit', targetphase, 'rebase')
608 if keepbranch:
608 if keepbranch:
609 repo.ui.setconfig('ui', 'allowemptycommit', True)
609 repo.ui.setconfig('ui', 'allowemptycommit', True)
610 # Commit might fail if unresolved files exist
610 # Commit might fail if unresolved files exist
611 newnode = repo.commit(text=commitmsg, user=ctx.user(),
611 newnode = repo.commit(text=commitmsg, user=ctx.user(),
612 date=ctx.date(), extra=extra, editor=editor)
612 date=ctx.date(), extra=extra, editor=editor)
613 finally:
613 finally:
614 repo.ui.restoreconfig(backup)
614 repo.ui.restoreconfig(backup)
615
615
616 repo.dirstate.setbranch(repo[newnode].branch())
616 repo.dirstate.setbranch(repo[newnode].branch())
617 dsguard.close()
617 dsguard.close()
618 return newnode
618 return newnode
619 finally:
619 finally:
620 release(dsguard)
620 release(dsguard)
621
621
622 def rebasenode(repo, rev, p1, base, state, collapse, target):
622 def rebasenode(repo, rev, p1, base, state, collapse, target):
623 'Rebase a single revision rev on top of p1 using base as merge ancestor'
623 'Rebase a single revision rev on top of p1 using base as merge ancestor'
624 # Merge phase
624 # Merge phase
625 # Update to target and merge it with local
625 # Update to target and merge it with local
626 if repo['.'].rev() != p1:
626 if repo['.'].rev() != p1:
627 repo.ui.debug(" update to %d:%s\n" % (p1, repo[p1]))
627 repo.ui.debug(" update to %d:%s\n" % (p1, repo[p1]))
628 merge.update(repo, p1, False, True, False)
628 merge.update(repo, p1, False, True, False)
629 else:
629 else:
630 repo.ui.debug(" already in target\n")
630 repo.ui.debug(" already in target\n")
631 repo.dirstate.write(repo.currenttransaction())
631 repo.dirstate.write(repo.currenttransaction())
632 repo.ui.debug(" merge against %d:%s\n" % (rev, repo[rev]))
632 repo.ui.debug(" merge against %d:%s\n" % (rev, repo[rev]))
633 if base is not None:
633 if base is not None:
634 repo.ui.debug(" detach base %d:%s\n" % (base, repo[base]))
634 repo.ui.debug(" detach base %d:%s\n" % (base, repo[base]))
635 # When collapsing in-place, the parent is the common ancestor, we
635 # When collapsing in-place, the parent is the common ancestor, we
636 # have to allow merging with it.
636 # have to allow merging with it.
637 stats = merge.update(repo, rev, True, True, False, base, collapse,
637 stats = merge.update(repo, rev, True, True, False, base, collapse,
638 labels=['dest', 'source'])
638 labels=['dest', 'source'])
639 if collapse:
639 if collapse:
640 copies.duplicatecopies(repo, rev, target)
640 copies.duplicatecopies(repo, rev, target)
641 else:
641 else:
642 # If we're not using --collapse, we need to
642 # If we're not using --collapse, we need to
643 # duplicate copies between the revision we're
643 # duplicate copies between the revision we're
644 # rebasing and its first parent, but *not*
644 # rebasing and its first parent, but *not*
645 # duplicate any copies that have already been
645 # duplicate any copies that have already been
646 # performed in the destination.
646 # performed in the destination.
647 p1rev = repo[rev].p1().rev()
647 p1rev = repo[rev].p1().rev()
648 copies.duplicatecopies(repo, rev, p1rev, skiprev=target)
648 copies.duplicatecopies(repo, rev, p1rev, skiprev=target)
649 return stats
649 return stats
650
650
651 def nearestrebased(repo, rev, state):
651 def nearestrebased(repo, rev, state):
652 """return the nearest ancestors of rev in the rebase result"""
652 """return the nearest ancestors of rev in the rebase result"""
653 rebased = [r for r in state if state[r] > nullmerge]
653 rebased = [r for r in state if state[r] > nullmerge]
654 candidates = repo.revs('max(%ld and (::%d))', rebased, rev)
654 candidates = repo.revs('max(%ld and (::%d))', rebased, rev)
655 if candidates:
655 if candidates:
656 return state[candidates.first()]
656 return state[candidates.first()]
657 else:
657 else:
658 return None
658 return None
659
659
660 def defineparents(repo, rev, target, state, targetancestors):
660 def defineparents(repo, rev, target, state, targetancestors):
661 'Return the new parent relationship of the revision that will be rebased'
661 'Return the new parent relationship of the revision that will be rebased'
662 parents = repo[rev].parents()
662 parents = repo[rev].parents()
663 p1 = p2 = nullrev
663 p1 = p2 = nullrev
664
664
665 p1n = parents[0].rev()
665 p1n = parents[0].rev()
666 if p1n in targetancestors:
666 if p1n in targetancestors:
667 p1 = target
667 p1 = target
668 elif p1n in state:
668 elif p1n in state:
669 if state[p1n] == nullmerge:
669 if state[p1n] == nullmerge:
670 p1 = target
670 p1 = target
671 elif state[p1n] in (revignored, revprecursor):
671 elif state[p1n] in (revignored, revprecursor):
672 p1 = nearestrebased(repo, p1n, state)
672 p1 = nearestrebased(repo, p1n, state)
673 if p1 is None:
673 if p1 is None:
674 p1 = target
674 p1 = target
675 else:
675 else:
676 p1 = state[p1n]
676 p1 = state[p1n]
677 else: # p1n external
677 else: # p1n external
678 p1 = target
678 p1 = target
679 p2 = p1n
679 p2 = p1n
680
680
681 if len(parents) == 2 and parents[1].rev() not in targetancestors:
681 if len(parents) == 2 and parents[1].rev() not in targetancestors:
682 p2n = parents[1].rev()
682 p2n = parents[1].rev()
683 # interesting second parent
683 # interesting second parent
684 if p2n in state:
684 if p2n in state:
685 if p1 == target: # p1n in targetancestors or external
685 if p1 == target: # p1n in targetancestors or external
686 p1 = state[p2n]
686 p1 = state[p2n]
687 elif state[p2n] in (revignored, revprecursor):
687 elif state[p2n] in (revignored, revprecursor):
688 p2 = nearestrebased(repo, p2n, state)
688 p2 = nearestrebased(repo, p2n, state)
689 if p2 is None:
689 if p2 is None:
690 # no ancestors rebased yet, detach
690 # no ancestors rebased yet, detach
691 p2 = target
691 p2 = target
692 else:
692 else:
693 p2 = state[p2n]
693 p2 = state[p2n]
694 else: # p2n external
694 else: # p2n external
695 if p2 != nullrev: # p1n external too => rev is a merged revision
695 if p2 != nullrev: # p1n external too => rev is a merged revision
696 raise error.Abort(_('cannot use revision %d as base, result '
696 raise error.Abort(_('cannot use revision %d as base, result '
697 'would have 3 parents') % rev)
697 'would have 3 parents') % rev)
698 p2 = p2n
698 p2 = p2n
699 repo.ui.debug(" future parents are %d and %d\n" %
699 repo.ui.debug(" future parents are %d and %d\n" %
700 (repo[p1].rev(), repo[p2].rev()))
700 (repo[p1].rev(), repo[p2].rev()))
701
701
702 if rev == min(state):
702 if rev == min(state):
703 # Case (1) initial changeset of a non-detaching rebase.
703 # Case (1) initial changeset of a non-detaching rebase.
704 # Let the merge mechanism find the base itself.
704 # Let the merge mechanism find the base itself.
705 base = None
705 base = None
706 elif not repo[rev].p2():
706 elif not repo[rev].p2():
707 # Case (2) detaching the node with a single parent, use this parent
707 # Case (2) detaching the node with a single parent, use this parent
708 base = repo[rev].p1().rev()
708 base = repo[rev].p1().rev()
709 else:
709 else:
710 # Assuming there is a p1, this is the case where there also is a p2.
710 # Assuming there is a p1, this is the case where there also is a p2.
711 # We are thus rebasing a merge and need to pick the right merge base.
711 # We are thus rebasing a merge and need to pick the right merge base.
712 #
712 #
713 # Imagine we have:
713 # Imagine we have:
714 # - M: current rebase revision in this step
714 # - M: current rebase revision in this step
715 # - A: one parent of M
715 # - A: one parent of M
716 # - B: other parent of M
716 # - B: other parent of M
717 # - D: destination of this merge step (p1 var)
717 # - D: destination of this merge step (p1 var)
718 #
718 #
719 # Consider the case where D is a descendant of A or B and the other is
719 # Consider the case where D is a descendant of A or B and the other is
720 # 'outside'. In this case, the right merge base is the D ancestor.
720 # 'outside'. In this case, the right merge base is the D ancestor.
721 #
721 #
722 # An informal proof, assuming A is 'outside' and B is the D ancestor:
722 # An informal proof, assuming A is 'outside' and B is the D ancestor:
723 #
723 #
724 # If we pick B as the base, the merge involves:
724 # If we pick B as the base, the merge involves:
725 # - changes from B to M (actual changeset payload)
725 # - changes from B to M (actual changeset payload)
726 # - changes from B to D (induced by rebase) as D is a rebased
726 # - changes from B to D (induced by rebase) as D is a rebased
727 # version of B)
727 # version of B)
728 # Which exactly represent the rebase operation.
728 # Which exactly represent the rebase operation.
729 #
729 #
730 # If we pick A as the base, the merge involves:
730 # If we pick A as the base, the merge involves:
731 # - changes from A to M (actual changeset payload)
731 # - changes from A to M (actual changeset payload)
732 # - changes from A to D (with include changes between unrelated A and B
732 # - changes from A to D (with include changes between unrelated A and B
733 # plus changes induced by rebase)
733 # plus changes induced by rebase)
734 # Which does not represent anything sensible and creates a lot of
734 # Which does not represent anything sensible and creates a lot of
735 # conflicts. A is thus not the right choice - B is.
735 # conflicts. A is thus not the right choice - B is.
736 #
736 #
737 # Note: The base found in this 'proof' is only correct in the specified
737 # Note: The base found in this 'proof' is only correct in the specified
738 # case. This base does not make sense if is not D a descendant of A or B
738 # case. This base does not make sense if is not D a descendant of A or B
739 # or if the other is not parent 'outside' (especially not if the other
739 # or if the other is not parent 'outside' (especially not if the other
740 # parent has been rebased). The current implementation does not
740 # parent has been rebased). The current implementation does not
741 # make it feasible to consider different cases separately. In these
741 # make it feasible to consider different cases separately. In these
742 # other cases we currently just leave it to the user to correctly
742 # other cases we currently just leave it to the user to correctly
743 # resolve an impossible merge using a wrong ancestor.
743 # resolve an impossible merge using a wrong ancestor.
744 for p in repo[rev].parents():
744 for p in repo[rev].parents():
745 if state.get(p.rev()) == p1:
745 if state.get(p.rev()) == p1:
746 base = p.rev()
746 base = p.rev()
747 break
747 break
748 else: # fallback when base not found
748 else: # fallback when base not found
749 base = None
749 base = None
750
750
751 # Raise because this function is called wrong (see issue 4106)
751 # Raise because this function is called wrong (see issue 4106)
752 raise AssertionError('no base found to rebase on '
752 raise AssertionError('no base found to rebase on '
753 '(defineparents called wrong)')
753 '(defineparents called wrong)')
754 return p1, p2, base
754 return p1, p2, base
755
755
756 def isagitpatch(repo, patchname):
756 def isagitpatch(repo, patchname):
757 'Return true if the given patch is in git format'
757 'Return true if the given patch is in git format'
758 mqpatch = os.path.join(repo.mq.path, patchname)
758 mqpatch = os.path.join(repo.mq.path, patchname)
759 for line in patch.linereader(file(mqpatch, 'rb')):
759 for line in patch.linereader(file(mqpatch, 'rb')):
760 if line.startswith('diff --git'):
760 if line.startswith('diff --git'):
761 return True
761 return True
762 return False
762 return False
763
763
764 def updatemq(repo, state, skipped, **opts):
764 def updatemq(repo, state, skipped, **opts):
765 'Update rebased mq patches - finalize and then import them'
765 'Update rebased mq patches - finalize and then import them'
766 mqrebase = {}
766 mqrebase = {}
767 mq = repo.mq
767 mq = repo.mq
768 original_series = mq.fullseries[:]
768 original_series = mq.fullseries[:]
769 skippedpatches = set()
769 skippedpatches = set()
770
770
771 for p in mq.applied:
771 for p in mq.applied:
772 rev = repo[p.node].rev()
772 rev = repo[p.node].rev()
773 if rev in state:
773 if rev in state:
774 repo.ui.debug('revision %d is an mq patch (%s), finalize it.\n' %
774 repo.ui.debug('revision %d is an mq patch (%s), finalize it.\n' %
775 (rev, p.name))
775 (rev, p.name))
776 mqrebase[rev] = (p.name, isagitpatch(repo, p.name))
776 mqrebase[rev] = (p.name, isagitpatch(repo, p.name))
777 else:
777 else:
778 # Applied but not rebased, not sure this should happen
778 # Applied but not rebased, not sure this should happen
779 skippedpatches.add(p.name)
779 skippedpatches.add(p.name)
780
780
781 if mqrebase:
781 if mqrebase:
782 mq.finish(repo, mqrebase.keys())
782 mq.finish(repo, mqrebase.keys())
783
783
784 # We must start import from the newest revision
784 # We must start import from the newest revision
785 for rev in sorted(mqrebase, reverse=True):
785 for rev in sorted(mqrebase, reverse=True):
786 if rev not in skipped:
786 if rev not in skipped:
787 name, isgit = mqrebase[rev]
787 name, isgit = mqrebase[rev]
788 repo.ui.note(_('updating mq patch %s to %s:%s\n') %
788 repo.ui.note(_('updating mq patch %s to %s:%s\n') %
789 (name, state[rev], repo[state[rev]]))
789 (name, state[rev], repo[state[rev]]))
790 mq.qimport(repo, (), patchname=name, git=isgit,
790 mq.qimport(repo, (), patchname=name, git=isgit,
791 rev=[str(state[rev])])
791 rev=[str(state[rev])])
792 else:
792 else:
793 # Rebased and skipped
793 # Rebased and skipped
794 skippedpatches.add(mqrebase[rev][0])
794 skippedpatches.add(mqrebase[rev][0])
795
795
796 # Patches were either applied and rebased and imported in
796 # Patches were either applied and rebased and imported in
797 # order, applied and removed or unapplied. Discard the removed
797 # order, applied and removed or unapplied. Discard the removed
798 # ones while preserving the original series order and guards.
798 # ones while preserving the original series order and guards.
799 newseries = [s for s in original_series
799 newseries = [s for s in original_series
800 if mq.guard_re.split(s, 1)[0] not in skippedpatches]
800 if mq.guard_re.split(s, 1)[0] not in skippedpatches]
801 mq.fullseries[:] = newseries
801 mq.fullseries[:] = newseries
802 mq.seriesdirty = True
802 mq.seriesdirty = True
803 mq.savedirty()
803 mq.savedirty()
804
804
805 def updatebookmarks(repo, targetnode, nstate, originalbookmarks):
805 def updatebookmarks(repo, targetnode, nstate, originalbookmarks):
806 'Move bookmarks to their correct changesets, and delete divergent ones'
806 'Move bookmarks to their correct changesets, and delete divergent ones'
807 marks = repo._bookmarks
807 marks = repo._bookmarks
808 for k, v in originalbookmarks.iteritems():
808 for k, v in originalbookmarks.iteritems():
809 if v in nstate:
809 if v in nstate:
810 # update the bookmarks for revs that have moved
810 # update the bookmarks for revs that have moved
811 marks[k] = nstate[v]
811 marks[k] = nstate[v]
812 bookmarks.deletedivergent(repo, [targetnode], k)
812 bookmarks.deletedivergent(repo, [targetnode], k)
813
813
814 marks.write()
814 marks.write()
815
815
816 def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches,
816 def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches,
817 external, activebookmark):
817 external, activebookmark):
818 'Store the current status to allow recovery'
818 'Store the current status to allow recovery'
819 f = repo.vfs("rebasestate", "w")
819 f = repo.vfs("rebasestate", "w")
820 f.write(repo[originalwd].hex() + '\n')
820 f.write(repo[originalwd].hex() + '\n')
821 f.write(repo[target].hex() + '\n')
821 f.write(repo[target].hex() + '\n')
822 f.write(repo[external].hex() + '\n')
822 f.write(repo[external].hex() + '\n')
823 f.write('%d\n' % int(collapse))
823 f.write('%d\n' % int(collapse))
824 f.write('%d\n' % int(keep))
824 f.write('%d\n' % int(keep))
825 f.write('%d\n' % int(keepbranches))
825 f.write('%d\n' % int(keepbranches))
826 f.write('%s\n' % (activebookmark or ''))
826 f.write('%s\n' % (activebookmark or ''))
827 for d, v in state.iteritems():
827 for d, v in state.iteritems():
828 oldrev = repo[d].hex()
828 oldrev = repo[d].hex()
829 if v >= 0:
829 if v >= 0:
830 newrev = repo[v].hex()
830 newrev = repo[v].hex()
831 elif v == revtodo:
831 elif v == revtodo:
832 # To maintain format compatibility, we have to use nullid.
832 # To maintain format compatibility, we have to use nullid.
833 # Please do remove this special case when upgrading the format.
833 # Please do remove this special case when upgrading the format.
834 newrev = hex(nullid)
834 newrev = hex(nullid)
835 else:
835 else:
836 newrev = v
836 newrev = v
837 f.write("%s:%s\n" % (oldrev, newrev))
837 f.write("%s:%s\n" % (oldrev, newrev))
838 f.close()
838 f.close()
839 repo.ui.debug('rebase status stored\n')
839 repo.ui.debug('rebase status stored\n')
840
840
841 def clearstatus(repo):
841 def clearstatus(repo):
842 'Remove the status files'
842 'Remove the status files'
843 _clearrebasesetvisibiliy(repo)
843 _clearrebasesetvisibiliy(repo)
844 util.unlinkpath(repo.join("rebasestate"), ignoremissing=True)
844 util.unlinkpath(repo.join("rebasestate"), ignoremissing=True)
845
845
846 def restorestatus(repo):
846 def restorestatus(repo):
847 'Restore a previously stored status'
847 'Restore a previously stored status'
848 keepbranches = None
848 keepbranches = None
849 target = None
849 target = None
850 collapse = False
850 collapse = False
851 external = nullrev
851 external = nullrev
852 activebookmark = None
852 activebookmark = None
853 state = {}
853 state = {}
854
854
855 try:
855 try:
856 f = repo.vfs("rebasestate")
856 f = repo.vfs("rebasestate")
857 for i, l in enumerate(f.read().splitlines()):
857 for i, l in enumerate(f.read().splitlines()):
858 if i == 0:
858 if i == 0:
859 originalwd = repo[l].rev()
859 originalwd = repo[l].rev()
860 elif i == 1:
860 elif i == 1:
861 target = repo[l].rev()
861 target = repo[l].rev()
862 elif i == 2:
862 elif i == 2:
863 external = repo[l].rev()
863 external = repo[l].rev()
864 elif i == 3:
864 elif i == 3:
865 collapse = bool(int(l))
865 collapse = bool(int(l))
866 elif i == 4:
866 elif i == 4:
867 keep = bool(int(l))
867 keep = bool(int(l))
868 elif i == 5:
868 elif i == 5:
869 keepbranches = bool(int(l))
869 keepbranches = bool(int(l))
870 elif i == 6 and not (len(l) == 81 and ':' in l):
870 elif i == 6 and not (len(l) == 81 and ':' in l):
871 # line 6 is a recent addition, so for backwards compatibility
871 # line 6 is a recent addition, so for backwards compatibility
872 # check that the line doesn't look like the oldrev:newrev lines
872 # check that the line doesn't look like the oldrev:newrev lines
873 activebookmark = l
873 activebookmark = l
874 else:
874 else:
875 oldrev, newrev = l.split(':')
875 oldrev, newrev = l.split(':')
876 if newrev in (str(nullmerge), str(revignored),
876 if newrev in (str(nullmerge), str(revignored),
877 str(revprecursor)):
877 str(revprecursor)):
878 state[repo[oldrev].rev()] = int(newrev)
878 state[repo[oldrev].rev()] = int(newrev)
879 elif newrev == nullid:
879 elif newrev == nullid:
880 state[repo[oldrev].rev()] = revtodo
880 state[repo[oldrev].rev()] = revtodo
881 # Legacy compat special case
881 # Legacy compat special case
882 else:
882 else:
883 state[repo[oldrev].rev()] = repo[newrev].rev()
883 state[repo[oldrev].rev()] = repo[newrev].rev()
884
884
885 except IOError as err:
885 except IOError as err:
886 if err.errno != errno.ENOENT:
886 if err.errno != errno.ENOENT:
887 raise
887 raise
888 raise error.Abort(_('no rebase in progress'))
888 raise error.Abort(_('no rebase in progress'))
889
889
890 if keepbranches is None:
890 if keepbranches is None:
891 raise error.Abort(_('.hg/rebasestate is incomplete'))
891 raise error.Abort(_('.hg/rebasestate is incomplete'))
892
892
893 skipped = set()
893 skipped = set()
894 # recompute the set of skipped revs
894 # recompute the set of skipped revs
895 if not collapse:
895 if not collapse:
896 seen = set([target])
896 seen = set([target])
897 for old, new in sorted(state.items()):
897 for old, new in sorted(state.items()):
898 if new != revtodo and new in seen:
898 if new != revtodo and new in seen:
899 skipped.add(old)
899 skipped.add(old)
900 seen.add(new)
900 seen.add(new)
901 repo.ui.debug('computed skipped revs: %s\n' %
901 repo.ui.debug('computed skipped revs: %s\n' %
902 (' '.join(str(r) for r in sorted(skipped)) or None))
902 (' '.join(str(r) for r in sorted(skipped)) or None))
903 repo.ui.debug('rebase status resumed\n')
903 repo.ui.debug('rebase status resumed\n')
904 _setrebasesetvisibility(repo, state.keys())
904 _setrebasesetvisibility(repo, state.keys())
905 return (originalwd, target, state, skipped,
905 return (originalwd, target, state, skipped,
906 collapse, keep, keepbranches, external, activebookmark)
906 collapse, keep, keepbranches, external, activebookmark)
907
907
908 def needupdate(repo, state):
908 def needupdate(repo, state):
909 '''check whether we should `update --clean` away from a merge, or if
909 '''check whether we should `update --clean` away from a merge, or if
910 somehow the working dir got forcibly updated, e.g. by older hg'''
910 somehow the working dir got forcibly updated, e.g. by older hg'''
911 parents = [p.rev() for p in repo.parents()]
911 parents = [p.rev() for p in repo.parents()]
912
912
913 # Are we in a merge state at all?
913 # Are we in a merge state at all?
914 if len(parents) < 2:
914 if len(parents) < 2:
915 return False
915 return False
916
916
917 # We should be standing on the first as-of-yet unrebased commit.
917 # We should be standing on the first as-of-yet unrebased commit.
918 firstunrebased = min([old for old, new in state.iteritems()
918 firstunrebased = min([old for old, new in state.iteritems()
919 if new == nullrev])
919 if new == nullrev])
920 if firstunrebased in parents:
920 if firstunrebased in parents:
921 return True
921 return True
922
922
923 return False
923 return False
924
924
925 def abort(repo, originalwd, target, state, activebookmark=None):
925 def abort(repo, originalwd, target, state, activebookmark=None):
926 '''Restore the repository to its original state. Additional args:
926 '''Restore the repository to its original state. Additional args:
927
927
928 activebookmark: the name of the bookmark that should be active after the
928 activebookmark: the name of the bookmark that should be active after the
929 restore'''
929 restore'''
930
930
931 try:
931 try:
932 # If the first commits in the rebased set get skipped during the rebase,
932 # If the first commits in the rebased set get skipped during the rebase,
933 # their values within the state mapping will be the target rev id. The
933 # their values within the state mapping will be the target rev id. The
934 # dstates list must must not contain the target rev (issue4896)
934 # dstates list must must not contain the target rev (issue4896)
935 dstates = [s for s in state.values() if s >= 0 and s != target]
935 dstates = [s for s in state.values() if s >= 0 and s != target]
936 immutable = [d for d in dstates if not repo[d].mutable()]
936 immutable = [d for d in dstates if not repo[d].mutable()]
937 cleanup = True
937 cleanup = True
938 if immutable:
938 if immutable:
939 repo.ui.warn(_("warning: can't clean up public changesets %s\n")
939 repo.ui.warn(_("warning: can't clean up public changesets %s\n")
940 % ', '.join(str(repo[r]) for r in immutable),
940 % ', '.join(str(repo[r]) for r in immutable),
941 hint=_('see "hg help phases" for details'))
941 hint=_('see "hg help phases" for details'))
942 cleanup = False
942 cleanup = False
943
943
944 descendants = set()
944 descendants = set()
945 if dstates:
945 if dstates:
946 descendants = set(repo.changelog.descendants(dstates))
946 descendants = set(repo.changelog.descendants(dstates))
947 if descendants - set(dstates):
947 if descendants - set(dstates):
948 repo.ui.warn(_("warning: new changesets detected on target branch, "
948 repo.ui.warn(_("warning: new changesets detected on target branch, "
949 "can't strip\n"))
949 "can't strip\n"))
950 cleanup = False
950 cleanup = False
951
951
952 if cleanup:
952 if cleanup:
953 # Update away from the rebase if necessary
953 # Update away from the rebase if necessary
954 if needupdate(repo, state):
954 if needupdate(repo, state):
955 merge.update(repo, originalwd, False, True, False)
955 merge.update(repo, originalwd, False, True, False)
956
956
957 # Strip from the first rebased revision
957 # Strip from the first rebased revision
958 rebased = filter(lambda x: x >= 0 and x != target, state.values())
958 rebased = filter(lambda x: x >= 0 and x != target, state.values())
959 if rebased:
959 if rebased:
960 strippoints = [
960 strippoints = [
961 c.node() for c in repo.set('roots(%ld)', rebased)]
961 c.node() for c in repo.set('roots(%ld)', rebased)]
962 # no backup of rebased cset versions needed
962 # no backup of rebased cset versions needed
963 repair.strip(repo.ui, repo, strippoints)
963 repair.strip(repo.ui, repo, strippoints)
964
964
965 if activebookmark and activebookmark in repo._bookmarks:
965 if activebookmark and activebookmark in repo._bookmarks:
966 bookmarks.activate(repo, activebookmark)
966 bookmarks.activate(repo, activebookmark)
967
967
968 finally:
968 finally:
969 clearstatus(repo)
969 clearstatus(repo)
970 repo.ui.warn(_('rebase aborted\n'))
970 repo.ui.warn(_('rebase aborted\n'))
971 return 0
971 return 0
972
972
973 def buildstate(repo, dest, rebaseset, collapse, obsoletenotrebased):
973 def buildstate(repo, dest, rebaseset, collapse, obsoletenotrebased):
974 '''Define which revisions are going to be rebased and where
974 '''Define which revisions are going to be rebased and where
975
975
976 repo: repo
976 repo: repo
977 dest: context
977 dest: context
978 rebaseset: set of rev
978 rebaseset: set of rev
979 '''
979 '''
980 _setrebasesetvisibility(repo, rebaseset)
980 _setrebasesetvisibility(repo, rebaseset)
981
981
982 # This check isn't strictly necessary, since mq detects commits over an
982 # This check isn't strictly necessary, since mq detects commits over an
983 # applied patch. But it prevents messing up the working directory when
983 # applied patch. But it prevents messing up the working directory when
984 # a partially completed rebase is blocked by mq.
984 # a partially completed rebase is blocked by mq.
985 if 'qtip' in repo.tags() and (dest.node() in
985 if 'qtip' in repo.tags() and (dest.node() in
986 [s.node for s in repo.mq.applied]):
986 [s.node for s in repo.mq.applied]):
987 raise error.Abort(_('cannot rebase onto an applied mq patch'))
987 raise error.Abort(_('cannot rebase onto an applied mq patch'))
988
988
989 roots = list(repo.set('roots(%ld)', rebaseset))
989 roots = list(repo.set('roots(%ld)', rebaseset))
990 if not roots:
990 if not roots:
991 raise error.Abort(_('no matching revisions'))
991 raise error.Abort(_('no matching revisions'))
992 roots.sort()
992 roots.sort()
993 state = {}
993 state = {}
994 detachset = set()
994 detachset = set()
995 for root in roots:
995 for root in roots:
996 commonbase = root.ancestor(dest)
996 commonbase = root.ancestor(dest)
997 if commonbase == root:
997 if commonbase == root:
998 raise error.Abort(_('source is ancestor of destination'))
998 raise error.Abort(_('source is ancestor of destination'))
999 if commonbase == dest:
999 if commonbase == dest:
1000 samebranch = root.branch() == dest.branch()
1000 samebranch = root.branch() == dest.branch()
1001 if not collapse and samebranch and root in dest.children():
1001 if not collapse and samebranch and root in dest.children():
1002 repo.ui.debug('source is a child of destination\n')
1002 repo.ui.debug('source is a child of destination\n')
1003 return None
1003 return None
1004
1004
1005 repo.ui.debug('rebase onto %d starting from %s\n' % (dest, root))
1005 repo.ui.debug('rebase onto %d starting from %s\n' % (dest, root))
1006 state.update(dict.fromkeys(rebaseset, revtodo))
1006 state.update(dict.fromkeys(rebaseset, revtodo))
1007 # Rebase tries to turn <dest> into a parent of <root> while
1007 # Rebase tries to turn <dest> into a parent of <root> while
1008 # preserving the number of parents of rebased changesets:
1008 # preserving the number of parents of rebased changesets:
1009 #
1009 #
1010 # - A changeset with a single parent will always be rebased as a
1010 # - A changeset with a single parent will always be rebased as a
1011 # changeset with a single parent.
1011 # changeset with a single parent.
1012 #
1012 #
1013 # - A merge will be rebased as merge unless its parents are both
1013 # - A merge will be rebased as merge unless its parents are both
1014 # ancestors of <dest> or are themselves in the rebased set and
1014 # ancestors of <dest> or are themselves in the rebased set and
1015 # pruned while rebased.
1015 # pruned while rebased.
1016 #
1016 #
1017 # If one parent of <root> is an ancestor of <dest>, the rebased
1017 # If one parent of <root> is an ancestor of <dest>, the rebased
1018 # version of this parent will be <dest>. This is always true with
1018 # version of this parent will be <dest>. This is always true with
1019 # --base option.
1019 # --base option.
1020 #
1020 #
1021 # Otherwise, we need to *replace* the original parents with
1021 # Otherwise, we need to *replace* the original parents with
1022 # <dest>. This "detaches" the rebased set from its former location
1022 # <dest>. This "detaches" the rebased set from its former location
1023 # and rebases it onto <dest>. Changes introduced by ancestors of
1023 # and rebases it onto <dest>. Changes introduced by ancestors of
1024 # <root> not common with <dest> (the detachset, marked as
1024 # <root> not common with <dest> (the detachset, marked as
1025 # nullmerge) are "removed" from the rebased changesets.
1025 # nullmerge) are "removed" from the rebased changesets.
1026 #
1026 #
1027 # - If <root> has a single parent, set it to <dest>.
1027 # - If <root> has a single parent, set it to <dest>.
1028 #
1028 #
1029 # - If <root> is a merge, we cannot decide which parent to
1029 # - If <root> is a merge, we cannot decide which parent to
1030 # replace, the rebase operation is not clearly defined.
1030 # replace, the rebase operation is not clearly defined.
1031 #
1031 #
1032 # The table below sums up this behavior:
1032 # The table below sums up this behavior:
1033 #
1033 #
1034 # +------------------+----------------------+-------------------------+
1034 # +------------------+----------------------+-------------------------+
1035 # | | one parent | merge |
1035 # | | one parent | merge |
1036 # +------------------+----------------------+-------------------------+
1036 # +------------------+----------------------+-------------------------+
1037 # | parent in | new parent is <dest> | parents in ::<dest> are |
1037 # | parent in | new parent is <dest> | parents in ::<dest> are |
1038 # | ::<dest> | | remapped to <dest> |
1038 # | ::<dest> | | remapped to <dest> |
1039 # +------------------+----------------------+-------------------------+
1039 # +------------------+----------------------+-------------------------+
1040 # | unrelated source | new parent is <dest> | ambiguous, abort |
1040 # | unrelated source | new parent is <dest> | ambiguous, abort |
1041 # +------------------+----------------------+-------------------------+
1041 # +------------------+----------------------+-------------------------+
1042 #
1042 #
1043 # The actual abort is handled by `defineparents`
1043 # The actual abort is handled by `defineparents`
1044 if len(root.parents()) <= 1:
1044 if len(root.parents()) <= 1:
1045 # ancestors of <root> not ancestors of <dest>
1045 # ancestors of <root> not ancestors of <dest>
1046 detachset.update(repo.changelog.findmissingrevs([commonbase.rev()],
1046 detachset.update(repo.changelog.findmissingrevs([commonbase.rev()],
1047 [root.rev()]))
1047 [root.rev()]))
1048 for r in detachset:
1048 for r in detachset:
1049 if r not in state:
1049 if r not in state:
1050 state[r] = nullmerge
1050 state[r] = nullmerge
1051 if len(roots) > 1:
1051 if len(roots) > 1:
1052 # If we have multiple roots, we may have "hole" in the rebase set.
1052 # If we have multiple roots, we may have "hole" in the rebase set.
1053 # Rebase roots that descend from those "hole" should not be detached as
1053 # Rebase roots that descend from those "hole" should not be detached as
1054 # other root are. We use the special `revignored` to inform rebase that
1054 # other root are. We use the special `revignored` to inform rebase that
1055 # the revision should be ignored but that `defineparents` should search
1055 # the revision should be ignored but that `defineparents` should search
1056 # a rebase destination that make sense regarding rebased topology.
1056 # a rebase destination that make sense regarding rebased topology.
1057 rebasedomain = set(repo.revs('%ld::%ld', rebaseset, rebaseset))
1057 rebasedomain = set(repo.revs('%ld::%ld', rebaseset, rebaseset))
1058 for ignored in set(rebasedomain) - set(rebaseset):
1058 for ignored in set(rebasedomain) - set(rebaseset):
1059 state[ignored] = revignored
1059 state[ignored] = revignored
1060 for r in obsoletenotrebased:
1060 for r in obsoletenotrebased:
1061 state[r] = revprecursor
1061 state[r] = revprecursor
1062 return repo['.'].rev(), dest.rev(), state
1062 return repo['.'].rev(), dest.rev(), state
1063
1063
1064 def clearrebased(ui, repo, state, skipped, collapsedas=None):
1064 def clearrebased(ui, repo, state, skipped, collapsedas=None):
1065 """dispose of rebased revision at the end of the rebase
1065 """dispose of rebased revision at the end of the rebase
1066
1066
1067 If `collapsedas` is not None, the rebase was a collapse whose result if the
1067 If `collapsedas` is not None, the rebase was a collapse whose result if the
1068 `collapsedas` node."""
1068 `collapsedas` node."""
1069 if obsolete.isenabled(repo, obsolete.createmarkersopt):
1069 if obsolete.isenabled(repo, obsolete.createmarkersopt):
1070 markers = []
1070 markers = []
1071 for rev, newrev in sorted(state.items()):
1071 for rev, newrev in sorted(state.items()):
1072 if newrev >= 0:
1072 if newrev >= 0:
1073 if rev in skipped:
1073 if rev in skipped:
1074 succs = ()
1074 succs = ()
1075 elif collapsedas is not None:
1075 elif collapsedas is not None:
1076 succs = (repo[collapsedas],)
1076 succs = (repo[collapsedas],)
1077 else:
1077 else:
1078 succs = (repo[newrev],)
1078 succs = (repo[newrev],)
1079 markers.append((repo[rev], succs))
1079 markers.append((repo[rev], succs))
1080 if markers:
1080 if markers:
1081 obsolete.createmarkers(repo, markers)
1081 obsolete.createmarkers(repo, markers)
1082 else:
1082 else:
1083 rebased = [rev for rev in state if state[rev] > nullmerge]
1083 rebased = [rev for rev in state if state[rev] > nullmerge]
1084 if rebased:
1084 if rebased:
1085 stripped = []
1085 stripped = []
1086 for root in repo.set('roots(%ld)', rebased):
1086 for root in repo.set('roots(%ld)', rebased):
1087 if set(repo.changelog.descendants([root.rev()])) - set(state):
1087 if set(repo.changelog.descendants([root.rev()])) - set(state):
1088 ui.warn(_("warning: new changesets detected "
1088 ui.warn(_("warning: new changesets detected "
1089 "on source branch, not stripping\n"))
1089 "on source branch, not stripping\n"))
1090 else:
1090 else:
1091 stripped.append(root.node())
1091 stripped.append(root.node())
1092 if stripped:
1092 if stripped:
1093 # backup the old csets by default
1093 # backup the old csets by default
1094 repair.strip(ui, repo, stripped, "all")
1094 repair.strip(ui, repo, stripped, "all")
1095
1095
1096
1096
1097 def pullrebase(orig, ui, repo, *args, **opts):
1097 def pullrebase(orig, ui, repo, *args, **opts):
1098 'Call rebase after pull if the latter has been invoked with --rebase'
1098 'Call rebase after pull if the latter has been invoked with --rebase'
1099 ret = None
1099 if opts.get('rebase'):
1100 if opts.get('rebase'):
1100 wlock = lock = None
1101 wlock = lock = None
1101 try:
1102 try:
1102 wlock = repo.wlock()
1103 wlock = repo.wlock()
1103 lock = repo.lock()
1104 lock = repo.lock()
1104 if opts.get('update'):
1105 if opts.get('update'):
1105 del opts['update']
1106 del opts['update']
1106 ui.debug('--update and --rebase are not compatible, ignoring '
1107 ui.debug('--update and --rebase are not compatible, ignoring '
1107 'the update flag\n')
1108 'the update flag\n')
1108
1109
1109 movemarkfrom = repo['.'].node()
1110 movemarkfrom = repo['.'].node()
1110 revsprepull = len(repo)
1111 revsprepull = len(repo)
1111 origpostincoming = commands.postincoming
1112 origpostincoming = commands.postincoming
1112 def _dummy(*args, **kwargs):
1113 def _dummy(*args, **kwargs):
1113 pass
1114 pass
1114 commands.postincoming = _dummy
1115 commands.postincoming = _dummy
1115 try:
1116 try:
1116 orig(ui, repo, *args, **opts)
1117 ret = orig(ui, repo, *args, **opts)
1117 finally:
1118 finally:
1118 commands.postincoming = origpostincoming
1119 commands.postincoming = origpostincoming
1119 revspostpull = len(repo)
1120 revspostpull = len(repo)
1120 if revspostpull > revsprepull:
1121 if revspostpull > revsprepull:
1121 # --rev option from pull conflict with rebase own --rev
1122 # --rev option from pull conflict with rebase own --rev
1122 # dropping it
1123 # dropping it
1123 if 'rev' in opts:
1124 if 'rev' in opts:
1124 del opts['rev']
1125 del opts['rev']
1125 # positional argument from pull conflicts with rebase's own
1126 # positional argument from pull conflicts with rebase's own
1126 # --source.
1127 # --source.
1127 if 'source' in opts:
1128 if 'source' in opts:
1128 del opts['source']
1129 del opts['source']
1129 rebase(ui, repo, **opts)
1130 rebase(ui, repo, **opts)
1130 branch = repo[None].branch()
1131 branch = repo[None].branch()
1131 dest = repo[branch].rev()
1132 dest = repo[branch].rev()
1132 if dest != repo['.'].rev():
1133 if dest != repo['.'].rev():
1133 # there was nothing to rebase we force an update
1134 # there was nothing to rebase we force an update
1134 hg.update(repo, dest)
1135 hg.update(repo, dest)
1135 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
1136 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
1136 ui.status(_("updating bookmark %s\n")
1137 ui.status(_("updating bookmark %s\n")
1137 % repo._activebookmark)
1138 % repo._activebookmark)
1138 finally:
1139 finally:
1139 release(lock, wlock)
1140 release(lock, wlock)
1140 else:
1141 else:
1141 if opts.get('tool'):
1142 if opts.get('tool'):
1142 raise error.Abort(_('--tool can only be used with --rebase'))
1143 raise error.Abort(_('--tool can only be used with --rebase'))
1143 orig(ui, repo, *args, **opts)
1144 ret = orig(ui, repo, *args, **opts)
1145
1146 return ret
1144
1147
1145 def _setrebasesetvisibility(repo, revs):
1148 def _setrebasesetvisibility(repo, revs):
1146 """store the currently rebased set on the repo object
1149 """store the currently rebased set on the repo object
1147
1150
1148 This is used by another function to prevent rebased revision to because
1151 This is used by another function to prevent rebased revision to because
1149 hidden (see issue4505)"""
1152 hidden (see issue4505)"""
1150 repo = repo.unfiltered()
1153 repo = repo.unfiltered()
1151 revs = set(revs)
1154 revs = set(revs)
1152 repo._rebaseset = revs
1155 repo._rebaseset = revs
1153 # invalidate cache if visibility changes
1156 # invalidate cache if visibility changes
1154 hiddens = repo.filteredrevcache.get('visible', set())
1157 hiddens = repo.filteredrevcache.get('visible', set())
1155 if revs & hiddens:
1158 if revs & hiddens:
1156 repo.invalidatevolatilesets()
1159 repo.invalidatevolatilesets()
1157
1160
1158 def _clearrebasesetvisibiliy(repo):
1161 def _clearrebasesetvisibiliy(repo):
1159 """remove rebaseset data from the repo"""
1162 """remove rebaseset data from the repo"""
1160 repo = repo.unfiltered()
1163 repo = repo.unfiltered()
1161 if '_rebaseset' in vars(repo):
1164 if '_rebaseset' in vars(repo):
1162 del repo._rebaseset
1165 del repo._rebaseset
1163
1166
1164 def _rebasedvisible(orig, repo):
1167 def _rebasedvisible(orig, repo):
1165 """ensure rebased revs stay visible (see issue4505)"""
1168 """ensure rebased revs stay visible (see issue4505)"""
1166 blockers = orig(repo)
1169 blockers = orig(repo)
1167 blockers.update(getattr(repo, '_rebaseset', ()))
1170 blockers.update(getattr(repo, '_rebaseset', ()))
1168 return blockers
1171 return blockers
1169
1172
1170 def _computeobsoletenotrebased(repo, rebasesetrevs, dest):
1173 def _computeobsoletenotrebased(repo, rebasesetrevs, dest):
1171 """return a mapping obsolete => successor for all obsolete nodes to be
1174 """return a mapping obsolete => successor for all obsolete nodes to be
1172 rebased that have a successors in the destination"""
1175 rebased that have a successors in the destination"""
1173 obsoletenotrebased = {}
1176 obsoletenotrebased = {}
1174
1177
1175 # Build a mapping successor => obsolete nodes for the obsolete
1178 # Build a mapping successor => obsolete nodes for the obsolete
1176 # nodes to be rebased
1179 # nodes to be rebased
1177 allsuccessors = {}
1180 allsuccessors = {}
1178 cl = repo.changelog
1181 cl = repo.changelog
1179 for r in rebasesetrevs:
1182 for r in rebasesetrevs:
1180 n = repo[r]
1183 n = repo[r]
1181 if n.obsolete():
1184 if n.obsolete():
1182 node = cl.node(r)
1185 node = cl.node(r)
1183 for s in obsolete.allsuccessors(repo.obsstore, [node]):
1186 for s in obsolete.allsuccessors(repo.obsstore, [node]):
1184 try:
1187 try:
1185 allsuccessors[cl.rev(s)] = cl.rev(node)
1188 allsuccessors[cl.rev(s)] = cl.rev(node)
1186 except LookupError:
1189 except LookupError:
1187 pass
1190 pass
1188
1191
1189 if allsuccessors:
1192 if allsuccessors:
1190 # Look for successors of obsolete nodes to be rebased among
1193 # Look for successors of obsolete nodes to be rebased among
1191 # the ancestors of dest
1194 # the ancestors of dest
1192 ancs = cl.ancestors([repo[dest].rev()],
1195 ancs = cl.ancestors([repo[dest].rev()],
1193 stoprev=min(allsuccessors),
1196 stoprev=min(allsuccessors),
1194 inclusive=True)
1197 inclusive=True)
1195 for s in allsuccessors:
1198 for s in allsuccessors:
1196 if s in ancs:
1199 if s in ancs:
1197 obsoletenotrebased[allsuccessors[s]] = s
1200 obsoletenotrebased[allsuccessors[s]] = s
1198 return obsoletenotrebased
1201 return obsoletenotrebased
1199
1202
1200 def summaryhook(ui, repo):
1203 def summaryhook(ui, repo):
1201 if not os.path.exists(repo.join('rebasestate')):
1204 if not os.path.exists(repo.join('rebasestate')):
1202 return
1205 return
1203 try:
1206 try:
1204 state = restorestatus(repo)[2]
1207 state = restorestatus(repo)[2]
1205 except error.RepoLookupError:
1208 except error.RepoLookupError:
1206 # i18n: column positioning for "hg summary"
1209 # i18n: column positioning for "hg summary"
1207 msg = _('rebase: (use "hg rebase --abort" to clear broken state)\n')
1210 msg = _('rebase: (use "hg rebase --abort" to clear broken state)\n')
1208 ui.write(msg)
1211 ui.write(msg)
1209 return
1212 return
1210 numrebased = len([i for i in state.itervalues() if i >= 0])
1213 numrebased = len([i for i in state.itervalues() if i >= 0])
1211 # i18n: column positioning for "hg summary"
1214 # i18n: column positioning for "hg summary"
1212 ui.write(_('rebase: %s, %s (rebase --continue)\n') %
1215 ui.write(_('rebase: %s, %s (rebase --continue)\n') %
1213 (ui.label(_('%d rebased'), 'rebase.rebased') % numrebased,
1216 (ui.label(_('%d rebased'), 'rebase.rebased') % numrebased,
1214 ui.label(_('%d remaining'), 'rebase.remaining') %
1217 ui.label(_('%d remaining'), 'rebase.remaining') %
1215 (len(state) - numrebased)))
1218 (len(state) - numrebased)))
1216
1219
1217 def uisetup(ui):
1220 def uisetup(ui):
1218 #Replace pull with a decorator to provide --rebase option
1221 #Replace pull with a decorator to provide --rebase option
1219 entry = extensions.wrapcommand(commands.table, 'pull', pullrebase)
1222 entry = extensions.wrapcommand(commands.table, 'pull', pullrebase)
1220 entry[1].append(('', 'rebase', None,
1223 entry[1].append(('', 'rebase', None,
1221 _("rebase working directory to branch head")))
1224 _("rebase working directory to branch head")))
1222 entry[1].append(('t', 'tool', '',
1225 entry[1].append(('t', 'tool', '',
1223 _("specify merge tool for rebase")))
1226 _("specify merge tool for rebase")))
1224 cmdutil.summaryhooks.add('rebase', summaryhook)
1227 cmdutil.summaryhooks.add('rebase', summaryhook)
1225 cmdutil.unfinishedstates.append(
1228 cmdutil.unfinishedstates.append(
1226 ['rebasestate', False, False, _('rebase in progress'),
1229 ['rebasestate', False, False, _('rebase in progress'),
1227 _("use 'hg rebase --continue' or 'hg rebase --abort'")])
1230 _("use 'hg rebase --continue' or 'hg rebase --abort'")])
1228 # ensure rebased rev are not hidden
1231 # ensure rebased rev are not hidden
1229 extensions.wrapfunction(repoview, '_getdynamicblockers', _rebasedvisible)
1232 extensions.wrapfunction(repoview, '_getdynamicblockers', _rebasedvisible)
1230 revset.symbols['_destrebase'] = _revsetdestrebase
1233 revset.symbols['_destrebase'] = _revsetdestrebase
General Comments 0
You need to be logged in to leave comments. Login now