##// END OF EJS Templates
rebase: add date parameter to concludenode function...
Stanislau Hlebik -
r26868:a2aa39a7 default
parent child Browse files
Show More
@@ -1,1230 +1,1232
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, date=None):
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 if date is None:
612 date = ctx.date()
611 newnode = repo.commit(text=commitmsg, user=ctx.user(),
613 newnode = repo.commit(text=commitmsg, user=ctx.user(),
612 date=ctx.date(), extra=extra, editor=editor)
614 date=date, extra=extra, editor=editor)
613 finally:
615 finally:
614 repo.ui.restoreconfig(backup)
616 repo.ui.restoreconfig(backup)
615
617
616 repo.dirstate.setbranch(repo[newnode].branch())
618 repo.dirstate.setbranch(repo[newnode].branch())
617 dsguard.close()
619 dsguard.close()
618 return newnode
620 return newnode
619 finally:
621 finally:
620 release(dsguard)
622 release(dsguard)
621
623
622 def rebasenode(repo, rev, p1, base, state, collapse, target):
624 def rebasenode(repo, rev, p1, base, state, collapse, target):
623 'Rebase a single revision rev on top of p1 using base as merge ancestor'
625 'Rebase a single revision rev on top of p1 using base as merge ancestor'
624 # Merge phase
626 # Merge phase
625 # Update to target and merge it with local
627 # Update to target and merge it with local
626 if repo['.'].rev() != p1:
628 if repo['.'].rev() != p1:
627 repo.ui.debug(" update to %d:%s\n" % (p1, repo[p1]))
629 repo.ui.debug(" update to %d:%s\n" % (p1, repo[p1]))
628 merge.update(repo, p1, False, True, False)
630 merge.update(repo, p1, False, True, False)
629 else:
631 else:
630 repo.ui.debug(" already in target\n")
632 repo.ui.debug(" already in target\n")
631 repo.dirstate.write(repo.currenttransaction())
633 repo.dirstate.write(repo.currenttransaction())
632 repo.ui.debug(" merge against %d:%s\n" % (rev, repo[rev]))
634 repo.ui.debug(" merge against %d:%s\n" % (rev, repo[rev]))
633 if base is not None:
635 if base is not None:
634 repo.ui.debug(" detach base %d:%s\n" % (base, repo[base]))
636 repo.ui.debug(" detach base %d:%s\n" % (base, repo[base]))
635 # When collapsing in-place, the parent is the common ancestor, we
637 # When collapsing in-place, the parent is the common ancestor, we
636 # have to allow merging with it.
638 # have to allow merging with it.
637 stats = merge.update(repo, rev, True, True, False, base, collapse,
639 stats = merge.update(repo, rev, True, True, False, base, collapse,
638 labels=['dest', 'source'])
640 labels=['dest', 'source'])
639 if collapse:
641 if collapse:
640 copies.duplicatecopies(repo, rev, target)
642 copies.duplicatecopies(repo, rev, target)
641 else:
643 else:
642 # If we're not using --collapse, we need to
644 # If we're not using --collapse, we need to
643 # duplicate copies between the revision we're
645 # duplicate copies between the revision we're
644 # rebasing and its first parent, but *not*
646 # rebasing and its first parent, but *not*
645 # duplicate any copies that have already been
647 # duplicate any copies that have already been
646 # performed in the destination.
648 # performed in the destination.
647 p1rev = repo[rev].p1().rev()
649 p1rev = repo[rev].p1().rev()
648 copies.duplicatecopies(repo, rev, p1rev, skiprev=target)
650 copies.duplicatecopies(repo, rev, p1rev, skiprev=target)
649 return stats
651 return stats
650
652
651 def nearestrebased(repo, rev, state):
653 def nearestrebased(repo, rev, state):
652 """return the nearest ancestors of rev in the rebase result"""
654 """return the nearest ancestors of rev in the rebase result"""
653 rebased = [r for r in state if state[r] > nullmerge]
655 rebased = [r for r in state if state[r] > nullmerge]
654 candidates = repo.revs('max(%ld and (::%d))', rebased, rev)
656 candidates = repo.revs('max(%ld and (::%d))', rebased, rev)
655 if candidates:
657 if candidates:
656 return state[candidates.first()]
658 return state[candidates.first()]
657 else:
659 else:
658 return None
660 return None
659
661
660 def defineparents(repo, rev, target, state, targetancestors):
662 def defineparents(repo, rev, target, state, targetancestors):
661 'Return the new parent relationship of the revision that will be rebased'
663 'Return the new parent relationship of the revision that will be rebased'
662 parents = repo[rev].parents()
664 parents = repo[rev].parents()
663 p1 = p2 = nullrev
665 p1 = p2 = nullrev
664
666
665 p1n = parents[0].rev()
667 p1n = parents[0].rev()
666 if p1n in targetancestors:
668 if p1n in targetancestors:
667 p1 = target
669 p1 = target
668 elif p1n in state:
670 elif p1n in state:
669 if state[p1n] == nullmerge:
671 if state[p1n] == nullmerge:
670 p1 = target
672 p1 = target
671 elif state[p1n] in (revignored, revprecursor):
673 elif state[p1n] in (revignored, revprecursor):
672 p1 = nearestrebased(repo, p1n, state)
674 p1 = nearestrebased(repo, p1n, state)
673 if p1 is None:
675 if p1 is None:
674 p1 = target
676 p1 = target
675 else:
677 else:
676 p1 = state[p1n]
678 p1 = state[p1n]
677 else: # p1n external
679 else: # p1n external
678 p1 = target
680 p1 = target
679 p2 = p1n
681 p2 = p1n
680
682
681 if len(parents) == 2 and parents[1].rev() not in targetancestors:
683 if len(parents) == 2 and parents[1].rev() not in targetancestors:
682 p2n = parents[1].rev()
684 p2n = parents[1].rev()
683 # interesting second parent
685 # interesting second parent
684 if p2n in state:
686 if p2n in state:
685 if p1 == target: # p1n in targetancestors or external
687 if p1 == target: # p1n in targetancestors or external
686 p1 = state[p2n]
688 p1 = state[p2n]
687 elif state[p2n] in (revignored, revprecursor):
689 elif state[p2n] in (revignored, revprecursor):
688 p2 = nearestrebased(repo, p2n, state)
690 p2 = nearestrebased(repo, p2n, state)
689 if p2 is None:
691 if p2 is None:
690 # no ancestors rebased yet, detach
692 # no ancestors rebased yet, detach
691 p2 = target
693 p2 = target
692 else:
694 else:
693 p2 = state[p2n]
695 p2 = state[p2n]
694 else: # p2n external
696 else: # p2n external
695 if p2 != nullrev: # p1n external too => rev is a merged revision
697 if p2 != nullrev: # p1n external too => rev is a merged revision
696 raise error.Abort(_('cannot use revision %d as base, result '
698 raise error.Abort(_('cannot use revision %d as base, result '
697 'would have 3 parents') % rev)
699 'would have 3 parents') % rev)
698 p2 = p2n
700 p2 = p2n
699 repo.ui.debug(" future parents are %d and %d\n" %
701 repo.ui.debug(" future parents are %d and %d\n" %
700 (repo[p1].rev(), repo[p2].rev()))
702 (repo[p1].rev(), repo[p2].rev()))
701
703
702 if rev == min(state):
704 if rev == min(state):
703 # Case (1) initial changeset of a non-detaching rebase.
705 # Case (1) initial changeset of a non-detaching rebase.
704 # Let the merge mechanism find the base itself.
706 # Let the merge mechanism find the base itself.
705 base = None
707 base = None
706 elif not repo[rev].p2():
708 elif not repo[rev].p2():
707 # Case (2) detaching the node with a single parent, use this parent
709 # Case (2) detaching the node with a single parent, use this parent
708 base = repo[rev].p1().rev()
710 base = repo[rev].p1().rev()
709 else:
711 else:
710 # Assuming there is a p1, this is the case where there also is a p2.
712 # 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.
713 # We are thus rebasing a merge and need to pick the right merge base.
712 #
714 #
713 # Imagine we have:
715 # Imagine we have:
714 # - M: current rebase revision in this step
716 # - M: current rebase revision in this step
715 # - A: one parent of M
717 # - A: one parent of M
716 # - B: other parent of M
718 # - B: other parent of M
717 # - D: destination of this merge step (p1 var)
719 # - D: destination of this merge step (p1 var)
718 #
720 #
719 # Consider the case where D is a descendant of A or B and the other is
721 # 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.
722 # 'outside'. In this case, the right merge base is the D ancestor.
721 #
723 #
722 # An informal proof, assuming A is 'outside' and B is the D ancestor:
724 # An informal proof, assuming A is 'outside' and B is the D ancestor:
723 #
725 #
724 # If we pick B as the base, the merge involves:
726 # If we pick B as the base, the merge involves:
725 # - changes from B to M (actual changeset payload)
727 # - changes from B to M (actual changeset payload)
726 # - changes from B to D (induced by rebase) as D is a rebased
728 # - changes from B to D (induced by rebase) as D is a rebased
727 # version of B)
729 # version of B)
728 # Which exactly represent the rebase operation.
730 # Which exactly represent the rebase operation.
729 #
731 #
730 # If we pick A as the base, the merge involves:
732 # If we pick A as the base, the merge involves:
731 # - changes from A to M (actual changeset payload)
733 # - changes from A to M (actual changeset payload)
732 # - changes from A to D (with include changes between unrelated A and B
734 # - changes from A to D (with include changes between unrelated A and B
733 # plus changes induced by rebase)
735 # plus changes induced by rebase)
734 # Which does not represent anything sensible and creates a lot of
736 # Which does not represent anything sensible and creates a lot of
735 # conflicts. A is thus not the right choice - B is.
737 # conflicts. A is thus not the right choice - B is.
736 #
738 #
737 # Note: The base found in this 'proof' is only correct in the specified
739 # 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
740 # 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
741 # or if the other is not parent 'outside' (especially not if the other
740 # parent has been rebased). The current implementation does not
742 # parent has been rebased). The current implementation does not
741 # make it feasible to consider different cases separately. In these
743 # make it feasible to consider different cases separately. In these
742 # other cases we currently just leave it to the user to correctly
744 # other cases we currently just leave it to the user to correctly
743 # resolve an impossible merge using a wrong ancestor.
745 # resolve an impossible merge using a wrong ancestor.
744 for p in repo[rev].parents():
746 for p in repo[rev].parents():
745 if state.get(p.rev()) == p1:
747 if state.get(p.rev()) == p1:
746 base = p.rev()
748 base = p.rev()
747 break
749 break
748 else: # fallback when base not found
750 else: # fallback when base not found
749 base = None
751 base = None
750
752
751 # Raise because this function is called wrong (see issue 4106)
753 # Raise because this function is called wrong (see issue 4106)
752 raise AssertionError('no base found to rebase on '
754 raise AssertionError('no base found to rebase on '
753 '(defineparents called wrong)')
755 '(defineparents called wrong)')
754 return p1, p2, base
756 return p1, p2, base
755
757
756 def isagitpatch(repo, patchname):
758 def isagitpatch(repo, patchname):
757 'Return true if the given patch is in git format'
759 'Return true if the given patch is in git format'
758 mqpatch = os.path.join(repo.mq.path, patchname)
760 mqpatch = os.path.join(repo.mq.path, patchname)
759 for line in patch.linereader(file(mqpatch, 'rb')):
761 for line in patch.linereader(file(mqpatch, 'rb')):
760 if line.startswith('diff --git'):
762 if line.startswith('diff --git'):
761 return True
763 return True
762 return False
764 return False
763
765
764 def updatemq(repo, state, skipped, **opts):
766 def updatemq(repo, state, skipped, **opts):
765 'Update rebased mq patches - finalize and then import them'
767 'Update rebased mq patches - finalize and then import them'
766 mqrebase = {}
768 mqrebase = {}
767 mq = repo.mq
769 mq = repo.mq
768 original_series = mq.fullseries[:]
770 original_series = mq.fullseries[:]
769 skippedpatches = set()
771 skippedpatches = set()
770
772
771 for p in mq.applied:
773 for p in mq.applied:
772 rev = repo[p.node].rev()
774 rev = repo[p.node].rev()
773 if rev in state:
775 if rev in state:
774 repo.ui.debug('revision %d is an mq patch (%s), finalize it.\n' %
776 repo.ui.debug('revision %d is an mq patch (%s), finalize it.\n' %
775 (rev, p.name))
777 (rev, p.name))
776 mqrebase[rev] = (p.name, isagitpatch(repo, p.name))
778 mqrebase[rev] = (p.name, isagitpatch(repo, p.name))
777 else:
779 else:
778 # Applied but not rebased, not sure this should happen
780 # Applied but not rebased, not sure this should happen
779 skippedpatches.add(p.name)
781 skippedpatches.add(p.name)
780
782
781 if mqrebase:
783 if mqrebase:
782 mq.finish(repo, mqrebase.keys())
784 mq.finish(repo, mqrebase.keys())
783
785
784 # We must start import from the newest revision
786 # We must start import from the newest revision
785 for rev in sorted(mqrebase, reverse=True):
787 for rev in sorted(mqrebase, reverse=True):
786 if rev not in skipped:
788 if rev not in skipped:
787 name, isgit = mqrebase[rev]
789 name, isgit = mqrebase[rev]
788 repo.ui.note(_('updating mq patch %s to %s:%s\n') %
790 repo.ui.note(_('updating mq patch %s to %s:%s\n') %
789 (name, state[rev], repo[state[rev]]))
791 (name, state[rev], repo[state[rev]]))
790 mq.qimport(repo, (), patchname=name, git=isgit,
792 mq.qimport(repo, (), patchname=name, git=isgit,
791 rev=[str(state[rev])])
793 rev=[str(state[rev])])
792 else:
794 else:
793 # Rebased and skipped
795 # Rebased and skipped
794 skippedpatches.add(mqrebase[rev][0])
796 skippedpatches.add(mqrebase[rev][0])
795
797
796 # Patches were either applied and rebased and imported in
798 # Patches were either applied and rebased and imported in
797 # order, applied and removed or unapplied. Discard the removed
799 # order, applied and removed or unapplied. Discard the removed
798 # ones while preserving the original series order and guards.
800 # ones while preserving the original series order and guards.
799 newseries = [s for s in original_series
801 newseries = [s for s in original_series
800 if mq.guard_re.split(s, 1)[0] not in skippedpatches]
802 if mq.guard_re.split(s, 1)[0] not in skippedpatches]
801 mq.fullseries[:] = newseries
803 mq.fullseries[:] = newseries
802 mq.seriesdirty = True
804 mq.seriesdirty = True
803 mq.savedirty()
805 mq.savedirty()
804
806
805 def updatebookmarks(repo, targetnode, nstate, originalbookmarks):
807 def updatebookmarks(repo, targetnode, nstate, originalbookmarks):
806 'Move bookmarks to their correct changesets, and delete divergent ones'
808 'Move bookmarks to their correct changesets, and delete divergent ones'
807 marks = repo._bookmarks
809 marks = repo._bookmarks
808 for k, v in originalbookmarks.iteritems():
810 for k, v in originalbookmarks.iteritems():
809 if v in nstate:
811 if v in nstate:
810 # update the bookmarks for revs that have moved
812 # update the bookmarks for revs that have moved
811 marks[k] = nstate[v]
813 marks[k] = nstate[v]
812 bookmarks.deletedivergent(repo, [targetnode], k)
814 bookmarks.deletedivergent(repo, [targetnode], k)
813
815
814 marks.write()
816 marks.write()
815
817
816 def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches,
818 def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches,
817 external, activebookmark):
819 external, activebookmark):
818 'Store the current status to allow recovery'
820 'Store the current status to allow recovery'
819 f = repo.vfs("rebasestate", "w")
821 f = repo.vfs("rebasestate", "w")
820 f.write(repo[originalwd].hex() + '\n')
822 f.write(repo[originalwd].hex() + '\n')
821 f.write(repo[target].hex() + '\n')
823 f.write(repo[target].hex() + '\n')
822 f.write(repo[external].hex() + '\n')
824 f.write(repo[external].hex() + '\n')
823 f.write('%d\n' % int(collapse))
825 f.write('%d\n' % int(collapse))
824 f.write('%d\n' % int(keep))
826 f.write('%d\n' % int(keep))
825 f.write('%d\n' % int(keepbranches))
827 f.write('%d\n' % int(keepbranches))
826 f.write('%s\n' % (activebookmark or ''))
828 f.write('%s\n' % (activebookmark or ''))
827 for d, v in state.iteritems():
829 for d, v in state.iteritems():
828 oldrev = repo[d].hex()
830 oldrev = repo[d].hex()
829 if v >= 0:
831 if v >= 0:
830 newrev = repo[v].hex()
832 newrev = repo[v].hex()
831 elif v == revtodo:
833 elif v == revtodo:
832 # To maintain format compatibility, we have to use nullid.
834 # To maintain format compatibility, we have to use nullid.
833 # Please do remove this special case when upgrading the format.
835 # Please do remove this special case when upgrading the format.
834 newrev = hex(nullid)
836 newrev = hex(nullid)
835 else:
837 else:
836 newrev = v
838 newrev = v
837 f.write("%s:%s\n" % (oldrev, newrev))
839 f.write("%s:%s\n" % (oldrev, newrev))
838 f.close()
840 f.close()
839 repo.ui.debug('rebase status stored\n')
841 repo.ui.debug('rebase status stored\n')
840
842
841 def clearstatus(repo):
843 def clearstatus(repo):
842 'Remove the status files'
844 'Remove the status files'
843 _clearrebasesetvisibiliy(repo)
845 _clearrebasesetvisibiliy(repo)
844 util.unlinkpath(repo.join("rebasestate"), ignoremissing=True)
846 util.unlinkpath(repo.join("rebasestate"), ignoremissing=True)
845
847
846 def restorestatus(repo):
848 def restorestatus(repo):
847 'Restore a previously stored status'
849 'Restore a previously stored status'
848 keepbranches = None
850 keepbranches = None
849 target = None
851 target = None
850 collapse = False
852 collapse = False
851 external = nullrev
853 external = nullrev
852 activebookmark = None
854 activebookmark = None
853 state = {}
855 state = {}
854
856
855 try:
857 try:
856 f = repo.vfs("rebasestate")
858 f = repo.vfs("rebasestate")
857 for i, l in enumerate(f.read().splitlines()):
859 for i, l in enumerate(f.read().splitlines()):
858 if i == 0:
860 if i == 0:
859 originalwd = repo[l].rev()
861 originalwd = repo[l].rev()
860 elif i == 1:
862 elif i == 1:
861 target = repo[l].rev()
863 target = repo[l].rev()
862 elif i == 2:
864 elif i == 2:
863 external = repo[l].rev()
865 external = repo[l].rev()
864 elif i == 3:
866 elif i == 3:
865 collapse = bool(int(l))
867 collapse = bool(int(l))
866 elif i == 4:
868 elif i == 4:
867 keep = bool(int(l))
869 keep = bool(int(l))
868 elif i == 5:
870 elif i == 5:
869 keepbranches = bool(int(l))
871 keepbranches = bool(int(l))
870 elif i == 6 and not (len(l) == 81 and ':' in l):
872 elif i == 6 and not (len(l) == 81 and ':' in l):
871 # line 6 is a recent addition, so for backwards compatibility
873 # line 6 is a recent addition, so for backwards compatibility
872 # check that the line doesn't look like the oldrev:newrev lines
874 # check that the line doesn't look like the oldrev:newrev lines
873 activebookmark = l
875 activebookmark = l
874 else:
876 else:
875 oldrev, newrev = l.split(':')
877 oldrev, newrev = l.split(':')
876 if newrev in (str(nullmerge), str(revignored),
878 if newrev in (str(nullmerge), str(revignored),
877 str(revprecursor)):
879 str(revprecursor)):
878 state[repo[oldrev].rev()] = int(newrev)
880 state[repo[oldrev].rev()] = int(newrev)
879 elif newrev == nullid:
881 elif newrev == nullid:
880 state[repo[oldrev].rev()] = revtodo
882 state[repo[oldrev].rev()] = revtodo
881 # Legacy compat special case
883 # Legacy compat special case
882 else:
884 else:
883 state[repo[oldrev].rev()] = repo[newrev].rev()
885 state[repo[oldrev].rev()] = repo[newrev].rev()
884
886
885 except IOError as err:
887 except IOError as err:
886 if err.errno != errno.ENOENT:
888 if err.errno != errno.ENOENT:
887 raise
889 raise
888 raise error.Abort(_('no rebase in progress'))
890 raise error.Abort(_('no rebase in progress'))
889
891
890 if keepbranches is None:
892 if keepbranches is None:
891 raise error.Abort(_('.hg/rebasestate is incomplete'))
893 raise error.Abort(_('.hg/rebasestate is incomplete'))
892
894
893 skipped = set()
895 skipped = set()
894 # recompute the set of skipped revs
896 # recompute the set of skipped revs
895 if not collapse:
897 if not collapse:
896 seen = set([target])
898 seen = set([target])
897 for old, new in sorted(state.items()):
899 for old, new in sorted(state.items()):
898 if new != revtodo and new in seen:
900 if new != revtodo and new in seen:
899 skipped.add(old)
901 skipped.add(old)
900 seen.add(new)
902 seen.add(new)
901 repo.ui.debug('computed skipped revs: %s\n' %
903 repo.ui.debug('computed skipped revs: %s\n' %
902 (' '.join(str(r) for r in sorted(skipped)) or None))
904 (' '.join(str(r) for r in sorted(skipped)) or None))
903 repo.ui.debug('rebase status resumed\n')
905 repo.ui.debug('rebase status resumed\n')
904 _setrebasesetvisibility(repo, state.keys())
906 _setrebasesetvisibility(repo, state.keys())
905 return (originalwd, target, state, skipped,
907 return (originalwd, target, state, skipped,
906 collapse, keep, keepbranches, external, activebookmark)
908 collapse, keep, keepbranches, external, activebookmark)
907
909
908 def needupdate(repo, state):
910 def needupdate(repo, state):
909 '''check whether we should `update --clean` away from a merge, or if
911 '''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'''
912 somehow the working dir got forcibly updated, e.g. by older hg'''
911 parents = [p.rev() for p in repo.parents()]
913 parents = [p.rev() for p in repo.parents()]
912
914
913 # Are we in a merge state at all?
915 # Are we in a merge state at all?
914 if len(parents) < 2:
916 if len(parents) < 2:
915 return False
917 return False
916
918
917 # We should be standing on the first as-of-yet unrebased commit.
919 # We should be standing on the first as-of-yet unrebased commit.
918 firstunrebased = min([old for old, new in state.iteritems()
920 firstunrebased = min([old for old, new in state.iteritems()
919 if new == nullrev])
921 if new == nullrev])
920 if firstunrebased in parents:
922 if firstunrebased in parents:
921 return True
923 return True
922
924
923 return False
925 return False
924
926
925 def abort(repo, originalwd, target, state, activebookmark=None):
927 def abort(repo, originalwd, target, state, activebookmark=None):
926 '''Restore the repository to its original state. Additional args:
928 '''Restore the repository to its original state. Additional args:
927
929
928 activebookmark: the name of the bookmark that should be active after the
930 activebookmark: the name of the bookmark that should be active after the
929 restore'''
931 restore'''
930
932
931 try:
933 try:
932 # If the first commits in the rebased set get skipped during the rebase,
934 # 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
935 # their values within the state mapping will be the target rev id. The
934 # dstates list must must not contain the target rev (issue4896)
936 # dstates list must must not contain the target rev (issue4896)
935 dstates = [s for s in state.values() if s >= 0 and s != target]
937 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()]
938 immutable = [d for d in dstates if not repo[d].mutable()]
937 cleanup = True
939 cleanup = True
938 if immutable:
940 if immutable:
939 repo.ui.warn(_("warning: can't clean up public changesets %s\n")
941 repo.ui.warn(_("warning: can't clean up public changesets %s\n")
940 % ', '.join(str(repo[r]) for r in immutable),
942 % ', '.join(str(repo[r]) for r in immutable),
941 hint=_('see "hg help phases" for details'))
943 hint=_('see "hg help phases" for details'))
942 cleanup = False
944 cleanup = False
943
945
944 descendants = set()
946 descendants = set()
945 if dstates:
947 if dstates:
946 descendants = set(repo.changelog.descendants(dstates))
948 descendants = set(repo.changelog.descendants(dstates))
947 if descendants - set(dstates):
949 if descendants - set(dstates):
948 repo.ui.warn(_("warning: new changesets detected on target branch, "
950 repo.ui.warn(_("warning: new changesets detected on target branch, "
949 "can't strip\n"))
951 "can't strip\n"))
950 cleanup = False
952 cleanup = False
951
953
952 if cleanup:
954 if cleanup:
953 # Update away from the rebase if necessary
955 # Update away from the rebase if necessary
954 if needupdate(repo, state):
956 if needupdate(repo, state):
955 merge.update(repo, originalwd, False, True, False)
957 merge.update(repo, originalwd, False, True, False)
956
958
957 # Strip from the first rebased revision
959 # Strip from the first rebased revision
958 rebased = filter(lambda x: x >= 0 and x != target, state.values())
960 rebased = filter(lambda x: x >= 0 and x != target, state.values())
959 if rebased:
961 if rebased:
960 strippoints = [
962 strippoints = [
961 c.node() for c in repo.set('roots(%ld)', rebased)]
963 c.node() for c in repo.set('roots(%ld)', rebased)]
962 # no backup of rebased cset versions needed
964 # no backup of rebased cset versions needed
963 repair.strip(repo.ui, repo, strippoints)
965 repair.strip(repo.ui, repo, strippoints)
964
966
965 if activebookmark and activebookmark in repo._bookmarks:
967 if activebookmark and activebookmark in repo._bookmarks:
966 bookmarks.activate(repo, activebookmark)
968 bookmarks.activate(repo, activebookmark)
967
969
968 finally:
970 finally:
969 clearstatus(repo)
971 clearstatus(repo)
970 repo.ui.warn(_('rebase aborted\n'))
972 repo.ui.warn(_('rebase aborted\n'))
971 return 0
973 return 0
972
974
973 def buildstate(repo, dest, rebaseset, collapse, obsoletenotrebased):
975 def buildstate(repo, dest, rebaseset, collapse, obsoletenotrebased):
974 '''Define which revisions are going to be rebased and where
976 '''Define which revisions are going to be rebased and where
975
977
976 repo: repo
978 repo: repo
977 dest: context
979 dest: context
978 rebaseset: set of rev
980 rebaseset: set of rev
979 '''
981 '''
980 _setrebasesetvisibility(repo, rebaseset)
982 _setrebasesetvisibility(repo, rebaseset)
981
983
982 # This check isn't strictly necessary, since mq detects commits over an
984 # This check isn't strictly necessary, since mq detects commits over an
983 # applied patch. But it prevents messing up the working directory when
985 # applied patch. But it prevents messing up the working directory when
984 # a partially completed rebase is blocked by mq.
986 # a partially completed rebase is blocked by mq.
985 if 'qtip' in repo.tags() and (dest.node() in
987 if 'qtip' in repo.tags() and (dest.node() in
986 [s.node for s in repo.mq.applied]):
988 [s.node for s in repo.mq.applied]):
987 raise error.Abort(_('cannot rebase onto an applied mq patch'))
989 raise error.Abort(_('cannot rebase onto an applied mq patch'))
988
990
989 roots = list(repo.set('roots(%ld)', rebaseset))
991 roots = list(repo.set('roots(%ld)', rebaseset))
990 if not roots:
992 if not roots:
991 raise error.Abort(_('no matching revisions'))
993 raise error.Abort(_('no matching revisions'))
992 roots.sort()
994 roots.sort()
993 state = {}
995 state = {}
994 detachset = set()
996 detachset = set()
995 for root in roots:
997 for root in roots:
996 commonbase = root.ancestor(dest)
998 commonbase = root.ancestor(dest)
997 if commonbase == root:
999 if commonbase == root:
998 raise error.Abort(_('source is ancestor of destination'))
1000 raise error.Abort(_('source is ancestor of destination'))
999 if commonbase == dest:
1001 if commonbase == dest:
1000 samebranch = root.branch() == dest.branch()
1002 samebranch = root.branch() == dest.branch()
1001 if not collapse and samebranch and root in dest.children():
1003 if not collapse and samebranch and root in dest.children():
1002 repo.ui.debug('source is a child of destination\n')
1004 repo.ui.debug('source is a child of destination\n')
1003 return None
1005 return None
1004
1006
1005 repo.ui.debug('rebase onto %d starting from %s\n' % (dest, root))
1007 repo.ui.debug('rebase onto %d starting from %s\n' % (dest, root))
1006 state.update(dict.fromkeys(rebaseset, revtodo))
1008 state.update(dict.fromkeys(rebaseset, revtodo))
1007 # Rebase tries to turn <dest> into a parent of <root> while
1009 # Rebase tries to turn <dest> into a parent of <root> while
1008 # preserving the number of parents of rebased changesets:
1010 # preserving the number of parents of rebased changesets:
1009 #
1011 #
1010 # - A changeset with a single parent will always be rebased as a
1012 # - A changeset with a single parent will always be rebased as a
1011 # changeset with a single parent.
1013 # changeset with a single parent.
1012 #
1014 #
1013 # - A merge will be rebased as merge unless its parents are both
1015 # - A merge will be rebased as merge unless its parents are both
1014 # ancestors of <dest> or are themselves in the rebased set and
1016 # ancestors of <dest> or are themselves in the rebased set and
1015 # pruned while rebased.
1017 # pruned while rebased.
1016 #
1018 #
1017 # If one parent of <root> is an ancestor of <dest>, the rebased
1019 # 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
1020 # version of this parent will be <dest>. This is always true with
1019 # --base option.
1021 # --base option.
1020 #
1022 #
1021 # Otherwise, we need to *replace* the original parents with
1023 # Otherwise, we need to *replace* the original parents with
1022 # <dest>. This "detaches" the rebased set from its former location
1024 # <dest>. This "detaches" the rebased set from its former location
1023 # and rebases it onto <dest>. Changes introduced by ancestors of
1025 # and rebases it onto <dest>. Changes introduced by ancestors of
1024 # <root> not common with <dest> (the detachset, marked as
1026 # <root> not common with <dest> (the detachset, marked as
1025 # nullmerge) are "removed" from the rebased changesets.
1027 # nullmerge) are "removed" from the rebased changesets.
1026 #
1028 #
1027 # - If <root> has a single parent, set it to <dest>.
1029 # - If <root> has a single parent, set it to <dest>.
1028 #
1030 #
1029 # - If <root> is a merge, we cannot decide which parent to
1031 # - If <root> is a merge, we cannot decide which parent to
1030 # replace, the rebase operation is not clearly defined.
1032 # replace, the rebase operation is not clearly defined.
1031 #
1033 #
1032 # The table below sums up this behavior:
1034 # The table below sums up this behavior:
1033 #
1035 #
1034 # +------------------+----------------------+-------------------------+
1036 # +------------------+----------------------+-------------------------+
1035 # | | one parent | merge |
1037 # | | one parent | merge |
1036 # +------------------+----------------------+-------------------------+
1038 # +------------------+----------------------+-------------------------+
1037 # | parent in | new parent is <dest> | parents in ::<dest> are |
1039 # | parent in | new parent is <dest> | parents in ::<dest> are |
1038 # | ::<dest> | | remapped to <dest> |
1040 # | ::<dest> | | remapped to <dest> |
1039 # +------------------+----------------------+-------------------------+
1041 # +------------------+----------------------+-------------------------+
1040 # | unrelated source | new parent is <dest> | ambiguous, abort |
1042 # | unrelated source | new parent is <dest> | ambiguous, abort |
1041 # +------------------+----------------------+-------------------------+
1043 # +------------------+----------------------+-------------------------+
1042 #
1044 #
1043 # The actual abort is handled by `defineparents`
1045 # The actual abort is handled by `defineparents`
1044 if len(root.parents()) <= 1:
1046 if len(root.parents()) <= 1:
1045 # ancestors of <root> not ancestors of <dest>
1047 # ancestors of <root> not ancestors of <dest>
1046 detachset.update(repo.changelog.findmissingrevs([commonbase.rev()],
1048 detachset.update(repo.changelog.findmissingrevs([commonbase.rev()],
1047 [root.rev()]))
1049 [root.rev()]))
1048 for r in detachset:
1050 for r in detachset:
1049 if r not in state:
1051 if r not in state:
1050 state[r] = nullmerge
1052 state[r] = nullmerge
1051 if len(roots) > 1:
1053 if len(roots) > 1:
1052 # If we have multiple roots, we may have "hole" in the rebase set.
1054 # 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
1055 # 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
1056 # other root are. We use the special `revignored` to inform rebase that
1055 # the revision should be ignored but that `defineparents` should search
1057 # the revision should be ignored but that `defineparents` should search
1056 # a rebase destination that make sense regarding rebased topology.
1058 # a rebase destination that make sense regarding rebased topology.
1057 rebasedomain = set(repo.revs('%ld::%ld', rebaseset, rebaseset))
1059 rebasedomain = set(repo.revs('%ld::%ld', rebaseset, rebaseset))
1058 for ignored in set(rebasedomain) - set(rebaseset):
1060 for ignored in set(rebasedomain) - set(rebaseset):
1059 state[ignored] = revignored
1061 state[ignored] = revignored
1060 for r in obsoletenotrebased:
1062 for r in obsoletenotrebased:
1061 state[r] = revprecursor
1063 state[r] = revprecursor
1062 return repo['.'].rev(), dest.rev(), state
1064 return repo['.'].rev(), dest.rev(), state
1063
1065
1064 def clearrebased(ui, repo, state, skipped, collapsedas=None):
1066 def clearrebased(ui, repo, state, skipped, collapsedas=None):
1065 """dispose of rebased revision at the end of the rebase
1067 """dispose of rebased revision at the end of the rebase
1066
1068
1067 If `collapsedas` is not None, the rebase was a collapse whose result if the
1069 If `collapsedas` is not None, the rebase was a collapse whose result if the
1068 `collapsedas` node."""
1070 `collapsedas` node."""
1069 if obsolete.isenabled(repo, obsolete.createmarkersopt):
1071 if obsolete.isenabled(repo, obsolete.createmarkersopt):
1070 markers = []
1072 markers = []
1071 for rev, newrev in sorted(state.items()):
1073 for rev, newrev in sorted(state.items()):
1072 if newrev >= 0:
1074 if newrev >= 0:
1073 if rev in skipped:
1075 if rev in skipped:
1074 succs = ()
1076 succs = ()
1075 elif collapsedas is not None:
1077 elif collapsedas is not None:
1076 succs = (repo[collapsedas],)
1078 succs = (repo[collapsedas],)
1077 else:
1079 else:
1078 succs = (repo[newrev],)
1080 succs = (repo[newrev],)
1079 markers.append((repo[rev], succs))
1081 markers.append((repo[rev], succs))
1080 if markers:
1082 if markers:
1081 obsolete.createmarkers(repo, markers)
1083 obsolete.createmarkers(repo, markers)
1082 else:
1084 else:
1083 rebased = [rev for rev in state if state[rev] > nullmerge]
1085 rebased = [rev for rev in state if state[rev] > nullmerge]
1084 if rebased:
1086 if rebased:
1085 stripped = []
1087 stripped = []
1086 for root in repo.set('roots(%ld)', rebased):
1088 for root in repo.set('roots(%ld)', rebased):
1087 if set(repo.changelog.descendants([root.rev()])) - set(state):
1089 if set(repo.changelog.descendants([root.rev()])) - set(state):
1088 ui.warn(_("warning: new changesets detected "
1090 ui.warn(_("warning: new changesets detected "
1089 "on source branch, not stripping\n"))
1091 "on source branch, not stripping\n"))
1090 else:
1092 else:
1091 stripped.append(root.node())
1093 stripped.append(root.node())
1092 if stripped:
1094 if stripped:
1093 # backup the old csets by default
1095 # backup the old csets by default
1094 repair.strip(ui, repo, stripped, "all")
1096 repair.strip(ui, repo, stripped, "all")
1095
1097
1096
1098
1097 def pullrebase(orig, ui, repo, *args, **opts):
1099 def pullrebase(orig, ui, repo, *args, **opts):
1098 'Call rebase after pull if the latter has been invoked with --rebase'
1100 'Call rebase after pull if the latter has been invoked with --rebase'
1099 if opts.get('rebase'):
1101 if opts.get('rebase'):
1100 wlock = lock = None
1102 wlock = lock = None
1101 try:
1103 try:
1102 wlock = repo.wlock()
1104 wlock = repo.wlock()
1103 lock = repo.lock()
1105 lock = repo.lock()
1104 if opts.get('update'):
1106 if opts.get('update'):
1105 del opts['update']
1107 del opts['update']
1106 ui.debug('--update and --rebase are not compatible, ignoring '
1108 ui.debug('--update and --rebase are not compatible, ignoring '
1107 'the update flag\n')
1109 'the update flag\n')
1108
1110
1109 movemarkfrom = repo['.'].node()
1111 movemarkfrom = repo['.'].node()
1110 revsprepull = len(repo)
1112 revsprepull = len(repo)
1111 origpostincoming = commands.postincoming
1113 origpostincoming = commands.postincoming
1112 def _dummy(*args, **kwargs):
1114 def _dummy(*args, **kwargs):
1113 pass
1115 pass
1114 commands.postincoming = _dummy
1116 commands.postincoming = _dummy
1115 try:
1117 try:
1116 orig(ui, repo, *args, **opts)
1118 orig(ui, repo, *args, **opts)
1117 finally:
1119 finally:
1118 commands.postincoming = origpostincoming
1120 commands.postincoming = origpostincoming
1119 revspostpull = len(repo)
1121 revspostpull = len(repo)
1120 if revspostpull > revsprepull:
1122 if revspostpull > revsprepull:
1121 # --rev option from pull conflict with rebase own --rev
1123 # --rev option from pull conflict with rebase own --rev
1122 # dropping it
1124 # dropping it
1123 if 'rev' in opts:
1125 if 'rev' in opts:
1124 del opts['rev']
1126 del opts['rev']
1125 # positional argument from pull conflicts with rebase's own
1127 # positional argument from pull conflicts with rebase's own
1126 # --source.
1128 # --source.
1127 if 'source' in opts:
1129 if 'source' in opts:
1128 del opts['source']
1130 del opts['source']
1129 rebase(ui, repo, **opts)
1131 rebase(ui, repo, **opts)
1130 branch = repo[None].branch()
1132 branch = repo[None].branch()
1131 dest = repo[branch].rev()
1133 dest = repo[branch].rev()
1132 if dest != repo['.'].rev():
1134 if dest != repo['.'].rev():
1133 # there was nothing to rebase we force an update
1135 # there was nothing to rebase we force an update
1134 hg.update(repo, dest)
1136 hg.update(repo, dest)
1135 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
1137 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
1136 ui.status(_("updating bookmark %s\n")
1138 ui.status(_("updating bookmark %s\n")
1137 % repo._activebookmark)
1139 % repo._activebookmark)
1138 finally:
1140 finally:
1139 release(lock, wlock)
1141 release(lock, wlock)
1140 else:
1142 else:
1141 if opts.get('tool'):
1143 if opts.get('tool'):
1142 raise error.Abort(_('--tool can only be used with --rebase'))
1144 raise error.Abort(_('--tool can only be used with --rebase'))
1143 orig(ui, repo, *args, **opts)
1145 orig(ui, repo, *args, **opts)
1144
1146
1145 def _setrebasesetvisibility(repo, revs):
1147 def _setrebasesetvisibility(repo, revs):
1146 """store the currently rebased set on the repo object
1148 """store the currently rebased set on the repo object
1147
1149
1148 This is used by another function to prevent rebased revision to because
1150 This is used by another function to prevent rebased revision to because
1149 hidden (see issue4505)"""
1151 hidden (see issue4505)"""
1150 repo = repo.unfiltered()
1152 repo = repo.unfiltered()
1151 revs = set(revs)
1153 revs = set(revs)
1152 repo._rebaseset = revs
1154 repo._rebaseset = revs
1153 # invalidate cache if visibility changes
1155 # invalidate cache if visibility changes
1154 hiddens = repo.filteredrevcache.get('visible', set())
1156 hiddens = repo.filteredrevcache.get('visible', set())
1155 if revs & hiddens:
1157 if revs & hiddens:
1156 repo.invalidatevolatilesets()
1158 repo.invalidatevolatilesets()
1157
1159
1158 def _clearrebasesetvisibiliy(repo):
1160 def _clearrebasesetvisibiliy(repo):
1159 """remove rebaseset data from the repo"""
1161 """remove rebaseset data from the repo"""
1160 repo = repo.unfiltered()
1162 repo = repo.unfiltered()
1161 if '_rebaseset' in vars(repo):
1163 if '_rebaseset' in vars(repo):
1162 del repo._rebaseset
1164 del repo._rebaseset
1163
1165
1164 def _rebasedvisible(orig, repo):
1166 def _rebasedvisible(orig, repo):
1165 """ensure rebased revs stay visible (see issue4505)"""
1167 """ensure rebased revs stay visible (see issue4505)"""
1166 blockers = orig(repo)
1168 blockers = orig(repo)
1167 blockers.update(getattr(repo, '_rebaseset', ()))
1169 blockers.update(getattr(repo, '_rebaseset', ()))
1168 return blockers
1170 return blockers
1169
1171
1170 def _computeobsoletenotrebased(repo, rebasesetrevs, dest):
1172 def _computeobsoletenotrebased(repo, rebasesetrevs, dest):
1171 """return a mapping obsolete => successor for all obsolete nodes to be
1173 """return a mapping obsolete => successor for all obsolete nodes to be
1172 rebased that have a successors in the destination"""
1174 rebased that have a successors in the destination"""
1173 obsoletenotrebased = {}
1175 obsoletenotrebased = {}
1174
1176
1175 # Build a mapping successor => obsolete nodes for the obsolete
1177 # Build a mapping successor => obsolete nodes for the obsolete
1176 # nodes to be rebased
1178 # nodes to be rebased
1177 allsuccessors = {}
1179 allsuccessors = {}
1178 cl = repo.changelog
1180 cl = repo.changelog
1179 for r in rebasesetrevs:
1181 for r in rebasesetrevs:
1180 n = repo[r]
1182 n = repo[r]
1181 if n.obsolete():
1183 if n.obsolete():
1182 node = cl.node(r)
1184 node = cl.node(r)
1183 for s in obsolete.allsuccessors(repo.obsstore, [node]):
1185 for s in obsolete.allsuccessors(repo.obsstore, [node]):
1184 try:
1186 try:
1185 allsuccessors[cl.rev(s)] = cl.rev(node)
1187 allsuccessors[cl.rev(s)] = cl.rev(node)
1186 except LookupError:
1188 except LookupError:
1187 pass
1189 pass
1188
1190
1189 if allsuccessors:
1191 if allsuccessors:
1190 # Look for successors of obsolete nodes to be rebased among
1192 # Look for successors of obsolete nodes to be rebased among
1191 # the ancestors of dest
1193 # the ancestors of dest
1192 ancs = cl.ancestors([repo[dest].rev()],
1194 ancs = cl.ancestors([repo[dest].rev()],
1193 stoprev=min(allsuccessors),
1195 stoprev=min(allsuccessors),
1194 inclusive=True)
1196 inclusive=True)
1195 for s in allsuccessors:
1197 for s in allsuccessors:
1196 if s in ancs:
1198 if s in ancs:
1197 obsoletenotrebased[allsuccessors[s]] = s
1199 obsoletenotrebased[allsuccessors[s]] = s
1198 return obsoletenotrebased
1200 return obsoletenotrebased
1199
1201
1200 def summaryhook(ui, repo):
1202 def summaryhook(ui, repo):
1201 if not os.path.exists(repo.join('rebasestate')):
1203 if not os.path.exists(repo.join('rebasestate')):
1202 return
1204 return
1203 try:
1205 try:
1204 state = restorestatus(repo)[2]
1206 state = restorestatus(repo)[2]
1205 except error.RepoLookupError:
1207 except error.RepoLookupError:
1206 # i18n: column positioning for "hg summary"
1208 # i18n: column positioning for "hg summary"
1207 msg = _('rebase: (use "hg rebase --abort" to clear broken state)\n')
1209 msg = _('rebase: (use "hg rebase --abort" to clear broken state)\n')
1208 ui.write(msg)
1210 ui.write(msg)
1209 return
1211 return
1210 numrebased = len([i for i in state.itervalues() if i >= 0])
1212 numrebased = len([i for i in state.itervalues() if i >= 0])
1211 # i18n: column positioning for "hg summary"
1213 # i18n: column positioning for "hg summary"
1212 ui.write(_('rebase: %s, %s (rebase --continue)\n') %
1214 ui.write(_('rebase: %s, %s (rebase --continue)\n') %
1213 (ui.label(_('%d rebased'), 'rebase.rebased') % numrebased,
1215 (ui.label(_('%d rebased'), 'rebase.rebased') % numrebased,
1214 ui.label(_('%d remaining'), 'rebase.remaining') %
1216 ui.label(_('%d remaining'), 'rebase.remaining') %
1215 (len(state) - numrebased)))
1217 (len(state) - numrebased)))
1216
1218
1217 def uisetup(ui):
1219 def uisetup(ui):
1218 #Replace pull with a decorator to provide --rebase option
1220 #Replace pull with a decorator to provide --rebase option
1219 entry = extensions.wrapcommand(commands.table, 'pull', pullrebase)
1221 entry = extensions.wrapcommand(commands.table, 'pull', pullrebase)
1220 entry[1].append(('', 'rebase', None,
1222 entry[1].append(('', 'rebase', None,
1221 _("rebase working directory to branch head")))
1223 _("rebase working directory to branch head")))
1222 entry[1].append(('t', 'tool', '',
1224 entry[1].append(('t', 'tool', '',
1223 _("specify merge tool for rebase")))
1225 _("specify merge tool for rebase")))
1224 cmdutil.summaryhooks.add('rebase', summaryhook)
1226 cmdutil.summaryhooks.add('rebase', summaryhook)
1225 cmdutil.unfinishedstates.append(
1227 cmdutil.unfinishedstates.append(
1226 ['rebasestate', False, False, _('rebase in progress'),
1228 ['rebasestate', False, False, _('rebase in progress'),
1227 _("use 'hg rebase --continue' or 'hg rebase --abort'")])
1229 _("use 'hg rebase --continue' or 'hg rebase --abort'")])
1228 # ensure rebased rev are not hidden
1230 # ensure rebased rev are not hidden
1229 extensions.wrapfunction(repoview, '_getdynamicblockers', _rebasedvisible)
1231 extensions.wrapfunction(repoview, '_getdynamicblockers', _rebasedvisible)
1230 revset.symbols['_destrebase'] = _revsetdestrebase
1232 revset.symbols['_destrebase'] = _revsetdestrebase
General Comments 0
You need to be logged in to leave comments. Login now