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