##// END OF EJS Templates
histedit: remove "name" parameter from cleanupnode functions...
Jun Wu -
r33348:72c25a91 default
parent child Browse files
Show More
@@ -1,1677 +1,1677 b''
1 # histedit.py - interactive history editing for mercurial
1 # histedit.py - interactive history editing for mercurial
2 #
2 #
3 # Copyright 2009 Augie Fackler <raf@durin42.com>
3 # Copyright 2009 Augie Fackler <raf@durin42.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 """interactive history editing
7 """interactive history editing
8
8
9 With this extension installed, Mercurial gains one new command: histedit. Usage
9 With this extension installed, Mercurial gains one new command: histedit. Usage
10 is as follows, assuming the following history::
10 is as follows, assuming the following history::
11
11
12 @ 3[tip] 7c2fd3b9020c 2009-04-27 18:04 -0500 durin42
12 @ 3[tip] 7c2fd3b9020c 2009-04-27 18:04 -0500 durin42
13 | Add delta
13 | Add delta
14 |
14 |
15 o 2 030b686bedc4 2009-04-27 18:04 -0500 durin42
15 o 2 030b686bedc4 2009-04-27 18:04 -0500 durin42
16 | Add gamma
16 | Add gamma
17 |
17 |
18 o 1 c561b4e977df 2009-04-27 18:04 -0500 durin42
18 o 1 c561b4e977df 2009-04-27 18:04 -0500 durin42
19 | Add beta
19 | Add beta
20 |
20 |
21 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
21 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
22 Add alpha
22 Add alpha
23
23
24 If you were to run ``hg histedit c561b4e977df``, you would see the following
24 If you were to run ``hg histedit c561b4e977df``, you would see the following
25 file open in your editor::
25 file open in your editor::
26
26
27 pick c561b4e977df Add beta
27 pick c561b4e977df Add beta
28 pick 030b686bedc4 Add gamma
28 pick 030b686bedc4 Add gamma
29 pick 7c2fd3b9020c Add delta
29 pick 7c2fd3b9020c Add delta
30
30
31 # Edit history between c561b4e977df and 7c2fd3b9020c
31 # Edit history between c561b4e977df and 7c2fd3b9020c
32 #
32 #
33 # Commits are listed from least to most recent
33 # Commits are listed from least to most recent
34 #
34 #
35 # Commands:
35 # Commands:
36 # p, pick = use commit
36 # p, pick = use commit
37 # e, edit = use commit, but stop for amending
37 # e, edit = use commit, but stop for amending
38 # f, fold = use commit, but combine it with the one above
38 # f, fold = use commit, but combine it with the one above
39 # r, roll = like fold, but discard this commit's description and date
39 # r, roll = like fold, but discard this commit's description and date
40 # d, drop = remove commit from history
40 # d, drop = remove commit from history
41 # m, mess = edit commit message without changing commit content
41 # m, mess = edit commit message without changing commit content
42 #
42 #
43
43
44 In this file, lines beginning with ``#`` are ignored. You must specify a rule
44 In this file, lines beginning with ``#`` are ignored. You must specify a rule
45 for each revision in your history. For example, if you had meant to add gamma
45 for each revision in your history. For example, if you had meant to add gamma
46 before beta, and then wanted to add delta in the same revision as beta, you
46 before beta, and then wanted to add delta in the same revision as beta, you
47 would reorganize the file to look like this::
47 would reorganize the file to look like this::
48
48
49 pick 030b686bedc4 Add gamma
49 pick 030b686bedc4 Add gamma
50 pick c561b4e977df Add beta
50 pick c561b4e977df Add beta
51 fold 7c2fd3b9020c Add delta
51 fold 7c2fd3b9020c Add delta
52
52
53 # Edit history between c561b4e977df and 7c2fd3b9020c
53 # Edit history between c561b4e977df and 7c2fd3b9020c
54 #
54 #
55 # Commits are listed from least to most recent
55 # Commits are listed from least to most recent
56 #
56 #
57 # Commands:
57 # Commands:
58 # p, pick = use commit
58 # p, pick = use commit
59 # e, edit = use commit, but stop for amending
59 # e, edit = use commit, but stop for amending
60 # f, fold = use commit, but combine it with the one above
60 # f, fold = use commit, but combine it with the one above
61 # r, roll = like fold, but discard this commit's description and date
61 # r, roll = like fold, but discard this commit's description and date
62 # d, drop = remove commit from history
62 # d, drop = remove commit from history
63 # m, mess = edit commit message without changing commit content
63 # m, mess = edit commit message without changing commit content
64 #
64 #
65
65
66 At which point you close the editor and ``histedit`` starts working. When you
66 At which point you close the editor and ``histedit`` starts working. When you
67 specify a ``fold`` operation, ``histedit`` will open an editor when it folds
67 specify a ``fold`` operation, ``histedit`` will open an editor when it folds
68 those revisions together, offering you a chance to clean up the commit message::
68 those revisions together, offering you a chance to clean up the commit message::
69
69
70 Add beta
70 Add beta
71 ***
71 ***
72 Add delta
72 Add delta
73
73
74 Edit the commit message to your liking, then close the editor. The date used
74 Edit the commit message to your liking, then close the editor. The date used
75 for the commit will be the later of the two commits' dates. For this example,
75 for the commit will be the later of the two commits' dates. For this example,
76 let's assume that the commit message was changed to ``Add beta and delta.``
76 let's assume that the commit message was changed to ``Add beta and delta.``
77 After histedit has run and had a chance to remove any old or temporary
77 After histedit has run and had a chance to remove any old or temporary
78 revisions it needed, the history looks like this::
78 revisions it needed, the history looks like this::
79
79
80 @ 2[tip] 989b4d060121 2009-04-27 18:04 -0500 durin42
80 @ 2[tip] 989b4d060121 2009-04-27 18:04 -0500 durin42
81 | Add beta and delta.
81 | Add beta and delta.
82 |
82 |
83 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
83 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
84 | Add gamma
84 | Add gamma
85 |
85 |
86 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
86 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
87 Add alpha
87 Add alpha
88
88
89 Note that ``histedit`` does *not* remove any revisions (even its own temporary
89 Note that ``histedit`` does *not* remove any revisions (even its own temporary
90 ones) until after it has completed all the editing operations, so it will
90 ones) until after it has completed all the editing operations, so it will
91 probably perform several strip operations when it's done. For the above example,
91 probably perform several strip operations when it's done. For the above example,
92 it had to run strip twice. Strip can be slow depending on a variety of factors,
92 it had to run strip twice. Strip can be slow depending on a variety of factors,
93 so you might need to be a little patient. You can choose to keep the original
93 so you might need to be a little patient. You can choose to keep the original
94 revisions by passing the ``--keep`` flag.
94 revisions by passing the ``--keep`` flag.
95
95
96 The ``edit`` operation will drop you back to a command prompt,
96 The ``edit`` operation will drop you back to a command prompt,
97 allowing you to edit files freely, or even use ``hg record`` to commit
97 allowing you to edit files freely, or even use ``hg record`` to commit
98 some changes as a separate commit. When you're done, any remaining
98 some changes as a separate commit. When you're done, any remaining
99 uncommitted changes will be committed as well. When done, run ``hg
99 uncommitted changes will be committed as well. When done, run ``hg
100 histedit --continue`` to finish this step. If there are uncommitted
100 histedit --continue`` to finish this step. If there are uncommitted
101 changes, you'll be prompted for a new commit message, but the default
101 changes, you'll be prompted for a new commit message, but the default
102 commit message will be the original message for the ``edit`` ed
102 commit message will be the original message for the ``edit`` ed
103 revision, and the date of the original commit will be preserved.
103 revision, and the date of the original commit will be preserved.
104
104
105 The ``message`` operation will give you a chance to revise a commit
105 The ``message`` operation will give you a chance to revise a commit
106 message without changing the contents. It's a shortcut for doing
106 message without changing the contents. It's a shortcut for doing
107 ``edit`` immediately followed by `hg histedit --continue``.
107 ``edit`` immediately followed by `hg histedit --continue``.
108
108
109 If ``histedit`` encounters a conflict when moving a revision (while
109 If ``histedit`` encounters a conflict when moving a revision (while
110 handling ``pick`` or ``fold``), it'll stop in a similar manner to
110 handling ``pick`` or ``fold``), it'll stop in a similar manner to
111 ``edit`` with the difference that it won't prompt you for a commit
111 ``edit`` with the difference that it won't prompt you for a commit
112 message when done. If you decide at this point that you don't like how
112 message when done. If you decide at this point that you don't like how
113 much work it will be to rearrange history, or that you made a mistake,
113 much work it will be to rearrange history, or that you made a mistake,
114 you can use ``hg histedit --abort`` to abandon the new changes you
114 you can use ``hg histedit --abort`` to abandon the new changes you
115 have made and return to the state before you attempted to edit your
115 have made and return to the state before you attempted to edit your
116 history.
116 history.
117
117
118 If we clone the histedit-ed example repository above and add four more
118 If we clone the histedit-ed example repository above and add four more
119 changes, such that we have the following history::
119 changes, such that we have the following history::
120
120
121 @ 6[tip] 038383181893 2009-04-27 18:04 -0500 stefan
121 @ 6[tip] 038383181893 2009-04-27 18:04 -0500 stefan
122 | Add theta
122 | Add theta
123 |
123 |
124 o 5 140988835471 2009-04-27 18:04 -0500 stefan
124 o 5 140988835471 2009-04-27 18:04 -0500 stefan
125 | Add eta
125 | Add eta
126 |
126 |
127 o 4 122930637314 2009-04-27 18:04 -0500 stefan
127 o 4 122930637314 2009-04-27 18:04 -0500 stefan
128 | Add zeta
128 | Add zeta
129 |
129 |
130 o 3 836302820282 2009-04-27 18:04 -0500 stefan
130 o 3 836302820282 2009-04-27 18:04 -0500 stefan
131 | Add epsilon
131 | Add epsilon
132 |
132 |
133 o 2 989b4d060121 2009-04-27 18:04 -0500 durin42
133 o 2 989b4d060121 2009-04-27 18:04 -0500 durin42
134 | Add beta and delta.
134 | Add beta and delta.
135 |
135 |
136 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
136 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
137 | Add gamma
137 | Add gamma
138 |
138 |
139 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
139 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
140 Add alpha
140 Add alpha
141
141
142 If you run ``hg histedit --outgoing`` on the clone then it is the same
142 If you run ``hg histedit --outgoing`` on the clone then it is the same
143 as running ``hg histedit 836302820282``. If you need plan to push to a
143 as running ``hg histedit 836302820282``. If you need plan to push to a
144 repository that Mercurial does not detect to be related to the source
144 repository that Mercurial does not detect to be related to the source
145 repo, you can add a ``--force`` option.
145 repo, you can add a ``--force`` option.
146
146
147 Config
147 Config
148 ------
148 ------
149
149
150 Histedit rule lines are truncated to 80 characters by default. You
150 Histedit rule lines are truncated to 80 characters by default. You
151 can customize this behavior by setting a different length in your
151 can customize this behavior by setting a different length in your
152 configuration file::
152 configuration file::
153
153
154 [histedit]
154 [histedit]
155 linelen = 120 # truncate rule lines at 120 characters
155 linelen = 120 # truncate rule lines at 120 characters
156
156
157 ``hg histedit`` attempts to automatically choose an appropriate base
157 ``hg histedit`` attempts to automatically choose an appropriate base
158 revision to use. To change which base revision is used, define a
158 revision to use. To change which base revision is used, define a
159 revset in your configuration file::
159 revset in your configuration file::
160
160
161 [histedit]
161 [histedit]
162 defaultrev = only(.) & draft()
162 defaultrev = only(.) & draft()
163
163
164 By default each edited revision needs to be present in histedit commands.
164 By default each edited revision needs to be present in histedit commands.
165 To remove revision you need to use ``drop`` operation. You can configure
165 To remove revision you need to use ``drop`` operation. You can configure
166 the drop to be implicit for missing commits by adding::
166 the drop to be implicit for missing commits by adding::
167
167
168 [histedit]
168 [histedit]
169 dropmissing = True
169 dropmissing = True
170
170
171 By default, histedit will close the transaction after each action. For
171 By default, histedit will close the transaction after each action. For
172 performance purposes, you can configure histedit to use a single transaction
172 performance purposes, you can configure histedit to use a single transaction
173 across the entire histedit. WARNING: This setting introduces a significant risk
173 across the entire histedit. WARNING: This setting introduces a significant risk
174 of losing the work you've done in a histedit if the histedit aborts
174 of losing the work you've done in a histedit if the histedit aborts
175 unexpectedly::
175 unexpectedly::
176
176
177 [histedit]
177 [histedit]
178 singletransaction = True
178 singletransaction = True
179
179
180 """
180 """
181
181
182 from __future__ import absolute_import
182 from __future__ import absolute_import
183
183
184 import errno
184 import errno
185 import os
185 import os
186
186
187 from mercurial.i18n import _
187 from mercurial.i18n import _
188 from mercurial import (
188 from mercurial import (
189 bundle2,
189 bundle2,
190 cmdutil,
190 cmdutil,
191 context,
191 context,
192 copies,
192 copies,
193 destutil,
193 destutil,
194 discovery,
194 discovery,
195 error,
195 error,
196 exchange,
196 exchange,
197 extensions,
197 extensions,
198 hg,
198 hg,
199 lock,
199 lock,
200 merge as mergemod,
200 merge as mergemod,
201 mergeutil,
201 mergeutil,
202 node,
202 node,
203 obsolete,
203 obsolete,
204 registrar,
204 registrar,
205 repair,
205 repair,
206 scmutil,
206 scmutil,
207 util,
207 util,
208 )
208 )
209
209
210 pickle = util.pickle
210 pickle = util.pickle
211 release = lock.release
211 release = lock.release
212 cmdtable = {}
212 cmdtable = {}
213 command = registrar.command(cmdtable)
213 command = registrar.command(cmdtable)
214
214
215 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
215 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
216 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
216 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
217 # be specifying the version(s) of Mercurial they are tested with, or
217 # be specifying the version(s) of Mercurial they are tested with, or
218 # leave the attribute unspecified.
218 # leave the attribute unspecified.
219 testedwith = 'ships-with-hg-core'
219 testedwith = 'ships-with-hg-core'
220
220
221 actiontable = {}
221 actiontable = {}
222 primaryactions = set()
222 primaryactions = set()
223 secondaryactions = set()
223 secondaryactions = set()
224 tertiaryactions = set()
224 tertiaryactions = set()
225 internalactions = set()
225 internalactions = set()
226
226
227 def geteditcomment(ui, first, last):
227 def geteditcomment(ui, first, last):
228 """ construct the editor comment
228 """ construct the editor comment
229 The comment includes::
229 The comment includes::
230 - an intro
230 - an intro
231 - sorted primary commands
231 - sorted primary commands
232 - sorted short commands
232 - sorted short commands
233 - sorted long commands
233 - sorted long commands
234 - additional hints
234 - additional hints
235
235
236 Commands are only included once.
236 Commands are only included once.
237 """
237 """
238 intro = _("""Edit history between %s and %s
238 intro = _("""Edit history between %s and %s
239
239
240 Commits are listed from least to most recent
240 Commits are listed from least to most recent
241
241
242 You can reorder changesets by reordering the lines
242 You can reorder changesets by reordering the lines
243
243
244 Commands:
244 Commands:
245 """)
245 """)
246 actions = []
246 actions = []
247 def addverb(v):
247 def addverb(v):
248 a = actiontable[v]
248 a = actiontable[v]
249 lines = a.message.split("\n")
249 lines = a.message.split("\n")
250 if len(a.verbs):
250 if len(a.verbs):
251 v = ', '.join(sorted(a.verbs, key=lambda v: len(v)))
251 v = ', '.join(sorted(a.verbs, key=lambda v: len(v)))
252 actions.append(" %s = %s" % (v, lines[0]))
252 actions.append(" %s = %s" % (v, lines[0]))
253 actions.extend([' %s' for l in lines[1:]])
253 actions.extend([' %s' for l in lines[1:]])
254
254
255 for v in (
255 for v in (
256 sorted(primaryactions) +
256 sorted(primaryactions) +
257 sorted(secondaryactions) +
257 sorted(secondaryactions) +
258 sorted(tertiaryactions)
258 sorted(tertiaryactions)
259 ):
259 ):
260 addverb(v)
260 addverb(v)
261 actions.append('')
261 actions.append('')
262
262
263 hints = []
263 hints = []
264 if ui.configbool('histedit', 'dropmissing'):
264 if ui.configbool('histedit', 'dropmissing'):
265 hints.append("Deleting a changeset from the list "
265 hints.append("Deleting a changeset from the list "
266 "will DISCARD it from the edited history!")
266 "will DISCARD it from the edited history!")
267
267
268 lines = (intro % (first, last)).split('\n') + actions + hints
268 lines = (intro % (first, last)).split('\n') + actions + hints
269
269
270 return ''.join(['# %s\n' % l if l else '#\n' for l in lines])
270 return ''.join(['# %s\n' % l if l else '#\n' for l in lines])
271
271
272 class histeditstate(object):
272 class histeditstate(object):
273 def __init__(self, repo, parentctxnode=None, actions=None, keep=None,
273 def __init__(self, repo, parentctxnode=None, actions=None, keep=None,
274 topmost=None, replacements=None, lock=None, wlock=None):
274 topmost=None, replacements=None, lock=None, wlock=None):
275 self.repo = repo
275 self.repo = repo
276 self.actions = actions
276 self.actions = actions
277 self.keep = keep
277 self.keep = keep
278 self.topmost = topmost
278 self.topmost = topmost
279 self.parentctxnode = parentctxnode
279 self.parentctxnode = parentctxnode
280 self.lock = lock
280 self.lock = lock
281 self.wlock = wlock
281 self.wlock = wlock
282 self.backupfile = None
282 self.backupfile = None
283 self.tr = None
283 self.tr = None
284 if replacements is None:
284 if replacements is None:
285 self.replacements = []
285 self.replacements = []
286 else:
286 else:
287 self.replacements = replacements
287 self.replacements = replacements
288
288
289 def read(self):
289 def read(self):
290 """Load histedit state from disk and set fields appropriately."""
290 """Load histedit state from disk and set fields appropriately."""
291 try:
291 try:
292 state = self.repo.vfs.read('histedit-state')
292 state = self.repo.vfs.read('histedit-state')
293 except IOError as err:
293 except IOError as err:
294 if err.errno != errno.ENOENT:
294 if err.errno != errno.ENOENT:
295 raise
295 raise
296 cmdutil.wrongtooltocontinue(self.repo, _('histedit'))
296 cmdutil.wrongtooltocontinue(self.repo, _('histedit'))
297
297
298 if state.startswith('v1\n'):
298 if state.startswith('v1\n'):
299 data = self._load()
299 data = self._load()
300 parentctxnode, rules, keep, topmost, replacements, backupfile = data
300 parentctxnode, rules, keep, topmost, replacements, backupfile = data
301 else:
301 else:
302 data = pickle.loads(state)
302 data = pickle.loads(state)
303 parentctxnode, rules, keep, topmost, replacements = data
303 parentctxnode, rules, keep, topmost, replacements = data
304 backupfile = None
304 backupfile = None
305
305
306 self.parentctxnode = parentctxnode
306 self.parentctxnode = parentctxnode
307 rules = "\n".join(["%s %s" % (verb, rest) for [verb, rest] in rules])
307 rules = "\n".join(["%s %s" % (verb, rest) for [verb, rest] in rules])
308 actions = parserules(rules, self)
308 actions = parserules(rules, self)
309 self.actions = actions
309 self.actions = actions
310 self.keep = keep
310 self.keep = keep
311 self.topmost = topmost
311 self.topmost = topmost
312 self.replacements = replacements
312 self.replacements = replacements
313 self.backupfile = backupfile
313 self.backupfile = backupfile
314
314
315 def write(self, tr=None):
315 def write(self, tr=None):
316 if tr:
316 if tr:
317 tr.addfilegenerator('histedit-state', ('histedit-state',),
317 tr.addfilegenerator('histedit-state', ('histedit-state',),
318 self._write, location='plain')
318 self._write, location='plain')
319 else:
319 else:
320 with self.repo.vfs("histedit-state", "w") as f:
320 with self.repo.vfs("histedit-state", "w") as f:
321 self._write(f)
321 self._write(f)
322
322
323 def _write(self, fp):
323 def _write(self, fp):
324 fp.write('v1\n')
324 fp.write('v1\n')
325 fp.write('%s\n' % node.hex(self.parentctxnode))
325 fp.write('%s\n' % node.hex(self.parentctxnode))
326 fp.write('%s\n' % node.hex(self.topmost))
326 fp.write('%s\n' % node.hex(self.topmost))
327 fp.write('%s\n' % self.keep)
327 fp.write('%s\n' % self.keep)
328 fp.write('%d\n' % len(self.actions))
328 fp.write('%d\n' % len(self.actions))
329 for action in self.actions:
329 for action in self.actions:
330 fp.write('%s\n' % action.tostate())
330 fp.write('%s\n' % action.tostate())
331 fp.write('%d\n' % len(self.replacements))
331 fp.write('%d\n' % len(self.replacements))
332 for replacement in self.replacements:
332 for replacement in self.replacements:
333 fp.write('%s%s\n' % (node.hex(replacement[0]), ''.join(node.hex(r)
333 fp.write('%s%s\n' % (node.hex(replacement[0]), ''.join(node.hex(r)
334 for r in replacement[1])))
334 for r in replacement[1])))
335 backupfile = self.backupfile
335 backupfile = self.backupfile
336 if not backupfile:
336 if not backupfile:
337 backupfile = ''
337 backupfile = ''
338 fp.write('%s\n' % backupfile)
338 fp.write('%s\n' % backupfile)
339
339
340 def _load(self):
340 def _load(self):
341 fp = self.repo.vfs('histedit-state', 'r')
341 fp = self.repo.vfs('histedit-state', 'r')
342 lines = [l[:-1] for l in fp.readlines()]
342 lines = [l[:-1] for l in fp.readlines()]
343
343
344 index = 0
344 index = 0
345 lines[index] # version number
345 lines[index] # version number
346 index += 1
346 index += 1
347
347
348 parentctxnode = node.bin(lines[index])
348 parentctxnode = node.bin(lines[index])
349 index += 1
349 index += 1
350
350
351 topmost = node.bin(lines[index])
351 topmost = node.bin(lines[index])
352 index += 1
352 index += 1
353
353
354 keep = lines[index] == 'True'
354 keep = lines[index] == 'True'
355 index += 1
355 index += 1
356
356
357 # Rules
357 # Rules
358 rules = []
358 rules = []
359 rulelen = int(lines[index])
359 rulelen = int(lines[index])
360 index += 1
360 index += 1
361 for i in xrange(rulelen):
361 for i in xrange(rulelen):
362 ruleaction = lines[index]
362 ruleaction = lines[index]
363 index += 1
363 index += 1
364 rule = lines[index]
364 rule = lines[index]
365 index += 1
365 index += 1
366 rules.append((ruleaction, rule))
366 rules.append((ruleaction, rule))
367
367
368 # Replacements
368 # Replacements
369 replacements = []
369 replacements = []
370 replacementlen = int(lines[index])
370 replacementlen = int(lines[index])
371 index += 1
371 index += 1
372 for i in xrange(replacementlen):
372 for i in xrange(replacementlen):
373 replacement = lines[index]
373 replacement = lines[index]
374 original = node.bin(replacement[:40])
374 original = node.bin(replacement[:40])
375 succ = [node.bin(replacement[i:i + 40]) for i in
375 succ = [node.bin(replacement[i:i + 40]) for i in
376 range(40, len(replacement), 40)]
376 range(40, len(replacement), 40)]
377 replacements.append((original, succ))
377 replacements.append((original, succ))
378 index += 1
378 index += 1
379
379
380 backupfile = lines[index]
380 backupfile = lines[index]
381 index += 1
381 index += 1
382
382
383 fp.close()
383 fp.close()
384
384
385 return parentctxnode, rules, keep, topmost, replacements, backupfile
385 return parentctxnode, rules, keep, topmost, replacements, backupfile
386
386
387 def clear(self):
387 def clear(self):
388 if self.inprogress():
388 if self.inprogress():
389 self.repo.vfs.unlink('histedit-state')
389 self.repo.vfs.unlink('histedit-state')
390
390
391 def inprogress(self):
391 def inprogress(self):
392 return self.repo.vfs.exists('histedit-state')
392 return self.repo.vfs.exists('histedit-state')
393
393
394
394
395 class histeditaction(object):
395 class histeditaction(object):
396 def __init__(self, state, node):
396 def __init__(self, state, node):
397 self.state = state
397 self.state = state
398 self.repo = state.repo
398 self.repo = state.repo
399 self.node = node
399 self.node = node
400
400
401 @classmethod
401 @classmethod
402 def fromrule(cls, state, rule):
402 def fromrule(cls, state, rule):
403 """Parses the given rule, returning an instance of the histeditaction.
403 """Parses the given rule, returning an instance of the histeditaction.
404 """
404 """
405 rulehash = rule.strip().split(' ', 1)[0]
405 rulehash = rule.strip().split(' ', 1)[0]
406 try:
406 try:
407 rev = node.bin(rulehash)
407 rev = node.bin(rulehash)
408 except TypeError:
408 except TypeError:
409 raise error.ParseError("invalid changeset %s" % rulehash)
409 raise error.ParseError("invalid changeset %s" % rulehash)
410 return cls(state, rev)
410 return cls(state, rev)
411
411
412 def verify(self, prev, expected, seen):
412 def verify(self, prev, expected, seen):
413 """ Verifies semantic correctness of the rule"""
413 """ Verifies semantic correctness of the rule"""
414 repo = self.repo
414 repo = self.repo
415 ha = node.hex(self.node)
415 ha = node.hex(self.node)
416 try:
416 try:
417 self.node = repo[ha].node()
417 self.node = repo[ha].node()
418 except error.RepoError:
418 except error.RepoError:
419 raise error.ParseError(_('unknown changeset %s listed')
419 raise error.ParseError(_('unknown changeset %s listed')
420 % ha[:12])
420 % ha[:12])
421 if self.node is not None:
421 if self.node is not None:
422 self._verifynodeconstraints(prev, expected, seen)
422 self._verifynodeconstraints(prev, expected, seen)
423
423
424 def _verifynodeconstraints(self, prev, expected, seen):
424 def _verifynodeconstraints(self, prev, expected, seen):
425 # by default command need a node in the edited list
425 # by default command need a node in the edited list
426 if self.node not in expected:
426 if self.node not in expected:
427 raise error.ParseError(_('%s "%s" changeset was not a candidate')
427 raise error.ParseError(_('%s "%s" changeset was not a candidate')
428 % (self.verb, node.short(self.node)),
428 % (self.verb, node.short(self.node)),
429 hint=_('only use listed changesets'))
429 hint=_('only use listed changesets'))
430 # and only one command per node
430 # and only one command per node
431 if self.node in seen:
431 if self.node in seen:
432 raise error.ParseError(_('duplicated command for changeset %s') %
432 raise error.ParseError(_('duplicated command for changeset %s') %
433 node.short(self.node))
433 node.short(self.node))
434
434
435 def torule(self):
435 def torule(self):
436 """build a histedit rule line for an action
436 """build a histedit rule line for an action
437
437
438 by default lines are in the form:
438 by default lines are in the form:
439 <hash> <rev> <summary>
439 <hash> <rev> <summary>
440 """
440 """
441 ctx = self.repo[self.node]
441 ctx = self.repo[self.node]
442 summary = _getsummary(ctx)
442 summary = _getsummary(ctx)
443 line = '%s %s %d %s' % (self.verb, ctx, ctx.rev(), summary)
443 line = '%s %s %d %s' % (self.verb, ctx, ctx.rev(), summary)
444 # trim to 75 columns by default so it's not stupidly wide in my editor
444 # trim to 75 columns by default so it's not stupidly wide in my editor
445 # (the 5 more are left for verb)
445 # (the 5 more are left for verb)
446 maxlen = self.repo.ui.configint('histedit', 'linelen', default=80)
446 maxlen = self.repo.ui.configint('histedit', 'linelen', default=80)
447 maxlen = max(maxlen, 22) # avoid truncating hash
447 maxlen = max(maxlen, 22) # avoid truncating hash
448 return util.ellipsis(line, maxlen)
448 return util.ellipsis(line, maxlen)
449
449
450 def tostate(self):
450 def tostate(self):
451 """Print an action in format used by histedit state files
451 """Print an action in format used by histedit state files
452 (the first line is a verb, the remainder is the second)
452 (the first line is a verb, the remainder is the second)
453 """
453 """
454 return "%s\n%s" % (self.verb, node.hex(self.node))
454 return "%s\n%s" % (self.verb, node.hex(self.node))
455
455
456 def run(self):
456 def run(self):
457 """Runs the action. The default behavior is simply apply the action's
457 """Runs the action. The default behavior is simply apply the action's
458 rulectx onto the current parentctx."""
458 rulectx onto the current parentctx."""
459 self.applychange()
459 self.applychange()
460 self.continuedirty()
460 self.continuedirty()
461 return self.continueclean()
461 return self.continueclean()
462
462
463 def applychange(self):
463 def applychange(self):
464 """Applies the changes from this action's rulectx onto the current
464 """Applies the changes from this action's rulectx onto the current
465 parentctx, but does not commit them."""
465 parentctx, but does not commit them."""
466 repo = self.repo
466 repo = self.repo
467 rulectx = repo[self.node]
467 rulectx = repo[self.node]
468 repo.ui.pushbuffer(error=True, labeled=True)
468 repo.ui.pushbuffer(error=True, labeled=True)
469 hg.update(repo, self.state.parentctxnode, quietempty=True)
469 hg.update(repo, self.state.parentctxnode, quietempty=True)
470 stats = applychanges(repo.ui, repo, rulectx, {})
470 stats = applychanges(repo.ui, repo, rulectx, {})
471 if stats and stats[3] > 0:
471 if stats and stats[3] > 0:
472 buf = repo.ui.popbuffer()
472 buf = repo.ui.popbuffer()
473 repo.ui.write(*buf)
473 repo.ui.write(*buf)
474 raise error.InterventionRequired(
474 raise error.InterventionRequired(
475 _('Fix up the change (%s %s)') %
475 _('Fix up the change (%s %s)') %
476 (self.verb, node.short(self.node)),
476 (self.verb, node.short(self.node)),
477 hint=_('hg histedit --continue to resume'))
477 hint=_('hg histedit --continue to resume'))
478 else:
478 else:
479 repo.ui.popbuffer()
479 repo.ui.popbuffer()
480
480
481 def continuedirty(self):
481 def continuedirty(self):
482 """Continues the action when changes have been applied to the working
482 """Continues the action when changes have been applied to the working
483 copy. The default behavior is to commit the dirty changes."""
483 copy. The default behavior is to commit the dirty changes."""
484 repo = self.repo
484 repo = self.repo
485 rulectx = repo[self.node]
485 rulectx = repo[self.node]
486
486
487 editor = self.commiteditor()
487 editor = self.commiteditor()
488 commit = commitfuncfor(repo, rulectx)
488 commit = commitfuncfor(repo, rulectx)
489
489
490 commit(text=rulectx.description(), user=rulectx.user(),
490 commit(text=rulectx.description(), user=rulectx.user(),
491 date=rulectx.date(), extra=rulectx.extra(), editor=editor)
491 date=rulectx.date(), extra=rulectx.extra(), editor=editor)
492
492
493 def commiteditor(self):
493 def commiteditor(self):
494 """The editor to be used to edit the commit message."""
494 """The editor to be used to edit the commit message."""
495 return False
495 return False
496
496
497 def continueclean(self):
497 def continueclean(self):
498 """Continues the action when the working copy is clean. The default
498 """Continues the action when the working copy is clean. The default
499 behavior is to accept the current commit as the new version of the
499 behavior is to accept the current commit as the new version of the
500 rulectx."""
500 rulectx."""
501 ctx = self.repo['.']
501 ctx = self.repo['.']
502 if ctx.node() == self.state.parentctxnode:
502 if ctx.node() == self.state.parentctxnode:
503 self.repo.ui.warn(_('%s: skipping changeset (no changes)\n') %
503 self.repo.ui.warn(_('%s: skipping changeset (no changes)\n') %
504 node.short(self.node))
504 node.short(self.node))
505 return ctx, [(self.node, tuple())]
505 return ctx, [(self.node, tuple())]
506 if ctx.node() == self.node:
506 if ctx.node() == self.node:
507 # Nothing changed
507 # Nothing changed
508 return ctx, []
508 return ctx, []
509 return ctx, [(self.node, (ctx.node(),))]
509 return ctx, [(self.node, (ctx.node(),))]
510
510
511 def commitfuncfor(repo, src):
511 def commitfuncfor(repo, src):
512 """Build a commit function for the replacement of <src>
512 """Build a commit function for the replacement of <src>
513
513
514 This function ensure we apply the same treatment to all changesets.
514 This function ensure we apply the same treatment to all changesets.
515
515
516 - Add a 'histedit_source' entry in extra.
516 - Add a 'histedit_source' entry in extra.
517
517
518 Note that fold has its own separated logic because its handling is a bit
518 Note that fold has its own separated logic because its handling is a bit
519 different and not easily factored out of the fold method.
519 different and not easily factored out of the fold method.
520 """
520 """
521 phasemin = src.phase()
521 phasemin = src.phase()
522 def commitfunc(**kwargs):
522 def commitfunc(**kwargs):
523 overrides = {('phases', 'new-commit'): phasemin}
523 overrides = {('phases', 'new-commit'): phasemin}
524 with repo.ui.configoverride(overrides, 'histedit'):
524 with repo.ui.configoverride(overrides, 'histedit'):
525 extra = kwargs.get('extra', {}).copy()
525 extra = kwargs.get('extra', {}).copy()
526 extra['histedit_source'] = src.hex()
526 extra['histedit_source'] = src.hex()
527 kwargs['extra'] = extra
527 kwargs['extra'] = extra
528 return repo.commit(**kwargs)
528 return repo.commit(**kwargs)
529 return commitfunc
529 return commitfunc
530
530
531 def applychanges(ui, repo, ctx, opts):
531 def applychanges(ui, repo, ctx, opts):
532 """Merge changeset from ctx (only) in the current working directory"""
532 """Merge changeset from ctx (only) in the current working directory"""
533 wcpar = repo.dirstate.parents()[0]
533 wcpar = repo.dirstate.parents()[0]
534 if ctx.p1().node() == wcpar:
534 if ctx.p1().node() == wcpar:
535 # edits are "in place" we do not need to make any merge,
535 # edits are "in place" we do not need to make any merge,
536 # just applies changes on parent for editing
536 # just applies changes on parent for editing
537 cmdutil.revert(ui, repo, ctx, (wcpar, node.nullid), all=True)
537 cmdutil.revert(ui, repo, ctx, (wcpar, node.nullid), all=True)
538 stats = None
538 stats = None
539 else:
539 else:
540 try:
540 try:
541 # ui.forcemerge is an internal variable, do not document
541 # ui.forcemerge is an internal variable, do not document
542 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
542 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
543 'histedit')
543 'histedit')
544 stats = mergemod.graft(repo, ctx, ctx.p1(), ['local', 'histedit'])
544 stats = mergemod.graft(repo, ctx, ctx.p1(), ['local', 'histedit'])
545 finally:
545 finally:
546 repo.ui.setconfig('ui', 'forcemerge', '', 'histedit')
546 repo.ui.setconfig('ui', 'forcemerge', '', 'histedit')
547 return stats
547 return stats
548
548
549 def collapse(repo, first, last, commitopts, skipprompt=False):
549 def collapse(repo, first, last, commitopts, skipprompt=False):
550 """collapse the set of revisions from first to last as new one.
550 """collapse the set of revisions from first to last as new one.
551
551
552 Expected commit options are:
552 Expected commit options are:
553 - message
553 - message
554 - date
554 - date
555 - username
555 - username
556 Commit message is edited in all cases.
556 Commit message is edited in all cases.
557
557
558 This function works in memory."""
558 This function works in memory."""
559 ctxs = list(repo.set('%d::%d', first, last))
559 ctxs = list(repo.set('%d::%d', first, last))
560 if not ctxs:
560 if not ctxs:
561 return None
561 return None
562 for c in ctxs:
562 for c in ctxs:
563 if not c.mutable():
563 if not c.mutable():
564 raise error.ParseError(
564 raise error.ParseError(
565 _("cannot fold into public change %s") % node.short(c.node()))
565 _("cannot fold into public change %s") % node.short(c.node()))
566 base = first.parents()[0]
566 base = first.parents()[0]
567
567
568 # commit a new version of the old changeset, including the update
568 # commit a new version of the old changeset, including the update
569 # collect all files which might be affected
569 # collect all files which might be affected
570 files = set()
570 files = set()
571 for ctx in ctxs:
571 for ctx in ctxs:
572 files.update(ctx.files())
572 files.update(ctx.files())
573
573
574 # Recompute copies (avoid recording a -> b -> a)
574 # Recompute copies (avoid recording a -> b -> a)
575 copied = copies.pathcopies(base, last)
575 copied = copies.pathcopies(base, last)
576
576
577 # prune files which were reverted by the updates
577 # prune files which were reverted by the updates
578 files = [f for f in files if not cmdutil.samefile(f, last, base)]
578 files = [f for f in files if not cmdutil.samefile(f, last, base)]
579 # commit version of these files as defined by head
579 # commit version of these files as defined by head
580 headmf = last.manifest()
580 headmf = last.manifest()
581 def filectxfn(repo, ctx, path):
581 def filectxfn(repo, ctx, path):
582 if path in headmf:
582 if path in headmf:
583 fctx = last[path]
583 fctx = last[path]
584 flags = fctx.flags()
584 flags = fctx.flags()
585 mctx = context.memfilectx(repo,
585 mctx = context.memfilectx(repo,
586 fctx.path(), fctx.data(),
586 fctx.path(), fctx.data(),
587 islink='l' in flags,
587 islink='l' in flags,
588 isexec='x' in flags,
588 isexec='x' in flags,
589 copied=copied.get(path))
589 copied=copied.get(path))
590 return mctx
590 return mctx
591 return None
591 return None
592
592
593 if commitopts.get('message'):
593 if commitopts.get('message'):
594 message = commitopts['message']
594 message = commitopts['message']
595 else:
595 else:
596 message = first.description()
596 message = first.description()
597 user = commitopts.get('user')
597 user = commitopts.get('user')
598 date = commitopts.get('date')
598 date = commitopts.get('date')
599 extra = commitopts.get('extra')
599 extra = commitopts.get('extra')
600
600
601 parents = (first.p1().node(), first.p2().node())
601 parents = (first.p1().node(), first.p2().node())
602 editor = None
602 editor = None
603 if not skipprompt:
603 if not skipprompt:
604 editor = cmdutil.getcommiteditor(edit=True, editform='histedit.fold')
604 editor = cmdutil.getcommiteditor(edit=True, editform='histedit.fold')
605 new = context.memctx(repo,
605 new = context.memctx(repo,
606 parents=parents,
606 parents=parents,
607 text=message,
607 text=message,
608 files=files,
608 files=files,
609 filectxfn=filectxfn,
609 filectxfn=filectxfn,
610 user=user,
610 user=user,
611 date=date,
611 date=date,
612 extra=extra,
612 extra=extra,
613 editor=editor)
613 editor=editor)
614 return repo.commitctx(new)
614 return repo.commitctx(new)
615
615
616 def _isdirtywc(repo):
616 def _isdirtywc(repo):
617 return repo[None].dirty(missing=True)
617 return repo[None].dirty(missing=True)
618
618
619 def abortdirty():
619 def abortdirty():
620 raise error.Abort(_('working copy has pending changes'),
620 raise error.Abort(_('working copy has pending changes'),
621 hint=_('amend, commit, or revert them and run histedit '
621 hint=_('amend, commit, or revert them and run histedit '
622 '--continue, or abort with histedit --abort'))
622 '--continue, or abort with histedit --abort'))
623
623
624 def action(verbs, message, priority=False, internal=False):
624 def action(verbs, message, priority=False, internal=False):
625 def wrap(cls):
625 def wrap(cls):
626 assert not priority or not internal
626 assert not priority or not internal
627 verb = verbs[0]
627 verb = verbs[0]
628 if priority:
628 if priority:
629 primaryactions.add(verb)
629 primaryactions.add(verb)
630 elif internal:
630 elif internal:
631 internalactions.add(verb)
631 internalactions.add(verb)
632 elif len(verbs) > 1:
632 elif len(verbs) > 1:
633 secondaryactions.add(verb)
633 secondaryactions.add(verb)
634 else:
634 else:
635 tertiaryactions.add(verb)
635 tertiaryactions.add(verb)
636
636
637 cls.verb = verb
637 cls.verb = verb
638 cls.verbs = verbs
638 cls.verbs = verbs
639 cls.message = message
639 cls.message = message
640 for verb in verbs:
640 for verb in verbs:
641 actiontable[verb] = cls
641 actiontable[verb] = cls
642 return cls
642 return cls
643 return wrap
643 return wrap
644
644
645 @action(['pick', 'p'],
645 @action(['pick', 'p'],
646 _('use commit'),
646 _('use commit'),
647 priority=True)
647 priority=True)
648 class pick(histeditaction):
648 class pick(histeditaction):
649 def run(self):
649 def run(self):
650 rulectx = self.repo[self.node]
650 rulectx = self.repo[self.node]
651 if rulectx.parents()[0].node() == self.state.parentctxnode:
651 if rulectx.parents()[0].node() == self.state.parentctxnode:
652 self.repo.ui.debug('node %s unchanged\n' % node.short(self.node))
652 self.repo.ui.debug('node %s unchanged\n' % node.short(self.node))
653 return rulectx, []
653 return rulectx, []
654
654
655 return super(pick, self).run()
655 return super(pick, self).run()
656
656
657 @action(['edit', 'e'],
657 @action(['edit', 'e'],
658 _('use commit, but stop for amending'),
658 _('use commit, but stop for amending'),
659 priority=True)
659 priority=True)
660 class edit(histeditaction):
660 class edit(histeditaction):
661 def run(self):
661 def run(self):
662 repo = self.repo
662 repo = self.repo
663 rulectx = repo[self.node]
663 rulectx = repo[self.node]
664 hg.update(repo, self.state.parentctxnode, quietempty=True)
664 hg.update(repo, self.state.parentctxnode, quietempty=True)
665 applychanges(repo.ui, repo, rulectx, {})
665 applychanges(repo.ui, repo, rulectx, {})
666 raise error.InterventionRequired(
666 raise error.InterventionRequired(
667 _('Editing (%s), you may commit or record as needed now.')
667 _('Editing (%s), you may commit or record as needed now.')
668 % node.short(self.node),
668 % node.short(self.node),
669 hint=_('hg histedit --continue to resume'))
669 hint=_('hg histedit --continue to resume'))
670
670
671 def commiteditor(self):
671 def commiteditor(self):
672 return cmdutil.getcommiteditor(edit=True, editform='histedit.edit')
672 return cmdutil.getcommiteditor(edit=True, editform='histedit.edit')
673
673
674 @action(['fold', 'f'],
674 @action(['fold', 'f'],
675 _('use commit, but combine it with the one above'))
675 _('use commit, but combine it with the one above'))
676 class fold(histeditaction):
676 class fold(histeditaction):
677 def verify(self, prev, expected, seen):
677 def verify(self, prev, expected, seen):
678 """ Verifies semantic correctness of the fold rule"""
678 """ Verifies semantic correctness of the fold rule"""
679 super(fold, self).verify(prev, expected, seen)
679 super(fold, self).verify(prev, expected, seen)
680 repo = self.repo
680 repo = self.repo
681 if not prev:
681 if not prev:
682 c = repo[self.node].parents()[0]
682 c = repo[self.node].parents()[0]
683 elif not prev.verb in ('pick', 'base'):
683 elif not prev.verb in ('pick', 'base'):
684 return
684 return
685 else:
685 else:
686 c = repo[prev.node]
686 c = repo[prev.node]
687 if not c.mutable():
687 if not c.mutable():
688 raise error.ParseError(
688 raise error.ParseError(
689 _("cannot fold into public change %s") % node.short(c.node()))
689 _("cannot fold into public change %s") % node.short(c.node()))
690
690
691
691
692 def continuedirty(self):
692 def continuedirty(self):
693 repo = self.repo
693 repo = self.repo
694 rulectx = repo[self.node]
694 rulectx = repo[self.node]
695
695
696 commit = commitfuncfor(repo, rulectx)
696 commit = commitfuncfor(repo, rulectx)
697 commit(text='fold-temp-revision %s' % node.short(self.node),
697 commit(text='fold-temp-revision %s' % node.short(self.node),
698 user=rulectx.user(), date=rulectx.date(),
698 user=rulectx.user(), date=rulectx.date(),
699 extra=rulectx.extra())
699 extra=rulectx.extra())
700
700
701 def continueclean(self):
701 def continueclean(self):
702 repo = self.repo
702 repo = self.repo
703 ctx = repo['.']
703 ctx = repo['.']
704 rulectx = repo[self.node]
704 rulectx = repo[self.node]
705 parentctxnode = self.state.parentctxnode
705 parentctxnode = self.state.parentctxnode
706 if ctx.node() == parentctxnode:
706 if ctx.node() == parentctxnode:
707 repo.ui.warn(_('%s: empty changeset\n') %
707 repo.ui.warn(_('%s: empty changeset\n') %
708 node.short(self.node))
708 node.short(self.node))
709 return ctx, [(self.node, (parentctxnode,))]
709 return ctx, [(self.node, (parentctxnode,))]
710
710
711 parentctx = repo[parentctxnode]
711 parentctx = repo[parentctxnode]
712 newcommits = set(c.node() for c in repo.set('(%d::. - %d)', parentctx,
712 newcommits = set(c.node() for c in repo.set('(%d::. - %d)', parentctx,
713 parentctx))
713 parentctx))
714 if not newcommits:
714 if not newcommits:
715 repo.ui.warn(_('%s: cannot fold - working copy is not a '
715 repo.ui.warn(_('%s: cannot fold - working copy is not a '
716 'descendant of previous commit %s\n') %
716 'descendant of previous commit %s\n') %
717 (node.short(self.node), node.short(parentctxnode)))
717 (node.short(self.node), node.short(parentctxnode)))
718 return ctx, [(self.node, (ctx.node(),))]
718 return ctx, [(self.node, (ctx.node(),))]
719
719
720 middlecommits = newcommits.copy()
720 middlecommits = newcommits.copy()
721 middlecommits.discard(ctx.node())
721 middlecommits.discard(ctx.node())
722
722
723 return self.finishfold(repo.ui, repo, parentctx, rulectx, ctx.node(),
723 return self.finishfold(repo.ui, repo, parentctx, rulectx, ctx.node(),
724 middlecommits)
724 middlecommits)
725
725
726 def skipprompt(self):
726 def skipprompt(self):
727 """Returns true if the rule should skip the message editor.
727 """Returns true if the rule should skip the message editor.
728
728
729 For example, 'fold' wants to show an editor, but 'rollup'
729 For example, 'fold' wants to show an editor, but 'rollup'
730 doesn't want to.
730 doesn't want to.
731 """
731 """
732 return False
732 return False
733
733
734 def mergedescs(self):
734 def mergedescs(self):
735 """Returns true if the rule should merge messages of multiple changes.
735 """Returns true if the rule should merge messages of multiple changes.
736
736
737 This exists mainly so that 'rollup' rules can be a subclass of
737 This exists mainly so that 'rollup' rules can be a subclass of
738 'fold'.
738 'fold'.
739 """
739 """
740 return True
740 return True
741
741
742 def firstdate(self):
742 def firstdate(self):
743 """Returns true if the rule should preserve the date of the first
743 """Returns true if the rule should preserve the date of the first
744 change.
744 change.
745
745
746 This exists mainly so that 'rollup' rules can be a subclass of
746 This exists mainly so that 'rollup' rules can be a subclass of
747 'fold'.
747 'fold'.
748 """
748 """
749 return False
749 return False
750
750
751 def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges):
751 def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges):
752 parent = ctx.parents()[0].node()
752 parent = ctx.parents()[0].node()
753 repo.ui.pushbuffer()
753 repo.ui.pushbuffer()
754 hg.update(repo, parent)
754 hg.update(repo, parent)
755 repo.ui.popbuffer()
755 repo.ui.popbuffer()
756 ### prepare new commit data
756 ### prepare new commit data
757 commitopts = {}
757 commitopts = {}
758 commitopts['user'] = ctx.user()
758 commitopts['user'] = ctx.user()
759 # commit message
759 # commit message
760 if not self.mergedescs():
760 if not self.mergedescs():
761 newmessage = ctx.description()
761 newmessage = ctx.description()
762 else:
762 else:
763 newmessage = '\n***\n'.join(
763 newmessage = '\n***\n'.join(
764 [ctx.description()] +
764 [ctx.description()] +
765 [repo[r].description() for r in internalchanges] +
765 [repo[r].description() for r in internalchanges] +
766 [oldctx.description()]) + '\n'
766 [oldctx.description()]) + '\n'
767 commitopts['message'] = newmessage
767 commitopts['message'] = newmessage
768 # date
768 # date
769 if self.firstdate():
769 if self.firstdate():
770 commitopts['date'] = ctx.date()
770 commitopts['date'] = ctx.date()
771 else:
771 else:
772 commitopts['date'] = max(ctx.date(), oldctx.date())
772 commitopts['date'] = max(ctx.date(), oldctx.date())
773 extra = ctx.extra().copy()
773 extra = ctx.extra().copy()
774 # histedit_source
774 # histedit_source
775 # note: ctx is likely a temporary commit but that the best we can do
775 # note: ctx is likely a temporary commit but that the best we can do
776 # here. This is sufficient to solve issue3681 anyway.
776 # here. This is sufficient to solve issue3681 anyway.
777 extra['histedit_source'] = '%s,%s' % (ctx.hex(), oldctx.hex())
777 extra['histedit_source'] = '%s,%s' % (ctx.hex(), oldctx.hex())
778 commitopts['extra'] = extra
778 commitopts['extra'] = extra
779 phasemin = max(ctx.phase(), oldctx.phase())
779 phasemin = max(ctx.phase(), oldctx.phase())
780 overrides = {('phases', 'new-commit'): phasemin}
780 overrides = {('phases', 'new-commit'): phasemin}
781 with repo.ui.configoverride(overrides, 'histedit'):
781 with repo.ui.configoverride(overrides, 'histedit'):
782 n = collapse(repo, ctx, repo[newnode], commitopts,
782 n = collapse(repo, ctx, repo[newnode], commitopts,
783 skipprompt=self.skipprompt())
783 skipprompt=self.skipprompt())
784 if n is None:
784 if n is None:
785 return ctx, []
785 return ctx, []
786 repo.ui.pushbuffer()
786 repo.ui.pushbuffer()
787 hg.update(repo, n)
787 hg.update(repo, n)
788 repo.ui.popbuffer()
788 repo.ui.popbuffer()
789 replacements = [(oldctx.node(), (newnode,)),
789 replacements = [(oldctx.node(), (newnode,)),
790 (ctx.node(), (n,)),
790 (ctx.node(), (n,)),
791 (newnode, (n,)),
791 (newnode, (n,)),
792 ]
792 ]
793 for ich in internalchanges:
793 for ich in internalchanges:
794 replacements.append((ich, (n,)))
794 replacements.append((ich, (n,)))
795 return repo[n], replacements
795 return repo[n], replacements
796
796
797 class base(histeditaction):
797 class base(histeditaction):
798
798
799 def run(self):
799 def run(self):
800 if self.repo['.'].node() != self.node:
800 if self.repo['.'].node() != self.node:
801 mergemod.update(self.repo, self.node, False, True)
801 mergemod.update(self.repo, self.node, False, True)
802 # branchmerge, force)
802 # branchmerge, force)
803 return self.continueclean()
803 return self.continueclean()
804
804
805 def continuedirty(self):
805 def continuedirty(self):
806 abortdirty()
806 abortdirty()
807
807
808 def continueclean(self):
808 def continueclean(self):
809 basectx = self.repo['.']
809 basectx = self.repo['.']
810 return basectx, []
810 return basectx, []
811
811
812 def _verifynodeconstraints(self, prev, expected, seen):
812 def _verifynodeconstraints(self, prev, expected, seen):
813 # base can only be use with a node not in the edited set
813 # base can only be use with a node not in the edited set
814 if self.node in expected:
814 if self.node in expected:
815 msg = _('%s "%s" changeset was an edited list candidate')
815 msg = _('%s "%s" changeset was an edited list candidate')
816 raise error.ParseError(
816 raise error.ParseError(
817 msg % (self.verb, node.short(self.node)),
817 msg % (self.verb, node.short(self.node)),
818 hint=_('base must only use unlisted changesets'))
818 hint=_('base must only use unlisted changesets'))
819
819
820 @action(['_multifold'],
820 @action(['_multifold'],
821 _(
821 _(
822 """fold subclass used for when multiple folds happen in a row
822 """fold subclass used for when multiple folds happen in a row
823
823
824 We only want to fire the editor for the folded message once when
824 We only want to fire the editor for the folded message once when
825 (say) four changes are folded down into a single change. This is
825 (say) four changes are folded down into a single change. This is
826 similar to rollup, but we should preserve both messages so that
826 similar to rollup, but we should preserve both messages so that
827 when the last fold operation runs we can show the user all the
827 when the last fold operation runs we can show the user all the
828 commit messages in their editor.
828 commit messages in their editor.
829 """),
829 """),
830 internal=True)
830 internal=True)
831 class _multifold(fold):
831 class _multifold(fold):
832 def skipprompt(self):
832 def skipprompt(self):
833 return True
833 return True
834
834
835 @action(["roll", "r"],
835 @action(["roll", "r"],
836 _("like fold, but discard this commit's description and date"))
836 _("like fold, but discard this commit's description and date"))
837 class rollup(fold):
837 class rollup(fold):
838 def mergedescs(self):
838 def mergedescs(self):
839 return False
839 return False
840
840
841 def skipprompt(self):
841 def skipprompt(self):
842 return True
842 return True
843
843
844 def firstdate(self):
844 def firstdate(self):
845 return True
845 return True
846
846
847 @action(["drop", "d"],
847 @action(["drop", "d"],
848 _('remove commit from history'))
848 _('remove commit from history'))
849 class drop(histeditaction):
849 class drop(histeditaction):
850 def run(self):
850 def run(self):
851 parentctx = self.repo[self.state.parentctxnode]
851 parentctx = self.repo[self.state.parentctxnode]
852 return parentctx, [(self.node, tuple())]
852 return parentctx, [(self.node, tuple())]
853
853
854 @action(["mess", "m"],
854 @action(["mess", "m"],
855 _('edit commit message without changing commit content'),
855 _('edit commit message without changing commit content'),
856 priority=True)
856 priority=True)
857 class message(histeditaction):
857 class message(histeditaction):
858 def commiteditor(self):
858 def commiteditor(self):
859 return cmdutil.getcommiteditor(edit=True, editform='histedit.mess')
859 return cmdutil.getcommiteditor(edit=True, editform='histedit.mess')
860
860
861 def findoutgoing(ui, repo, remote=None, force=False, opts=None):
861 def findoutgoing(ui, repo, remote=None, force=False, opts=None):
862 """utility function to find the first outgoing changeset
862 """utility function to find the first outgoing changeset
863
863
864 Used by initialization code"""
864 Used by initialization code"""
865 if opts is None:
865 if opts is None:
866 opts = {}
866 opts = {}
867 dest = ui.expandpath(remote or 'default-push', remote or 'default')
867 dest = ui.expandpath(remote or 'default-push', remote or 'default')
868 dest, revs = hg.parseurl(dest, None)[:2]
868 dest, revs = hg.parseurl(dest, None)[:2]
869 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
869 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
870
870
871 revs, checkout = hg.addbranchrevs(repo, repo, revs, None)
871 revs, checkout = hg.addbranchrevs(repo, repo, revs, None)
872 other = hg.peer(repo, opts, dest)
872 other = hg.peer(repo, opts, dest)
873
873
874 if revs:
874 if revs:
875 revs = [repo.lookup(rev) for rev in revs]
875 revs = [repo.lookup(rev) for rev in revs]
876
876
877 outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force)
877 outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force)
878 if not outgoing.missing:
878 if not outgoing.missing:
879 raise error.Abort(_('no outgoing ancestors'))
879 raise error.Abort(_('no outgoing ancestors'))
880 roots = list(repo.revs("roots(%ln)", outgoing.missing))
880 roots = list(repo.revs("roots(%ln)", outgoing.missing))
881 if 1 < len(roots):
881 if 1 < len(roots):
882 msg = _('there are ambiguous outgoing revisions')
882 msg = _('there are ambiguous outgoing revisions')
883 hint = _("see 'hg help histedit' for more detail")
883 hint = _("see 'hg help histedit' for more detail")
884 raise error.Abort(msg, hint=hint)
884 raise error.Abort(msg, hint=hint)
885 return repo.lookup(roots[0])
885 return repo.lookup(roots[0])
886
886
887
887
888 @command('histedit',
888 @command('histedit',
889 [('', 'commands', '',
889 [('', 'commands', '',
890 _('read history edits from the specified file'), _('FILE')),
890 _('read history edits from the specified file'), _('FILE')),
891 ('c', 'continue', False, _('continue an edit already in progress')),
891 ('c', 'continue', False, _('continue an edit already in progress')),
892 ('', 'edit-plan', False, _('edit remaining actions list')),
892 ('', 'edit-plan', False, _('edit remaining actions list')),
893 ('k', 'keep', False,
893 ('k', 'keep', False,
894 _("don't strip old nodes after edit is complete")),
894 _("don't strip old nodes after edit is complete")),
895 ('', 'abort', False, _('abort an edit in progress')),
895 ('', 'abort', False, _('abort an edit in progress')),
896 ('o', 'outgoing', False, _('changesets not found in destination')),
896 ('o', 'outgoing', False, _('changesets not found in destination')),
897 ('f', 'force', False,
897 ('f', 'force', False,
898 _('force outgoing even for unrelated repositories')),
898 _('force outgoing even for unrelated repositories')),
899 ('r', 'rev', [], _('first revision to be edited'), _('REV'))],
899 ('r', 'rev', [], _('first revision to be edited'), _('REV'))],
900 _("[OPTIONS] ([ANCESTOR] | --outgoing [URL])"))
900 _("[OPTIONS] ([ANCESTOR] | --outgoing [URL])"))
901 def histedit(ui, repo, *freeargs, **opts):
901 def histedit(ui, repo, *freeargs, **opts):
902 """interactively edit changeset history
902 """interactively edit changeset history
903
903
904 This command lets you edit a linear series of changesets (up to
904 This command lets you edit a linear series of changesets (up to
905 and including the working directory, which should be clean).
905 and including the working directory, which should be clean).
906 You can:
906 You can:
907
907
908 - `pick` to [re]order a changeset
908 - `pick` to [re]order a changeset
909
909
910 - `drop` to omit changeset
910 - `drop` to omit changeset
911
911
912 - `mess` to reword the changeset commit message
912 - `mess` to reword the changeset commit message
913
913
914 - `fold` to combine it with the preceding changeset (using the later date)
914 - `fold` to combine it with the preceding changeset (using the later date)
915
915
916 - `roll` like fold, but discarding this commit's description and date
916 - `roll` like fold, but discarding this commit's description and date
917
917
918 - `edit` to edit this changeset (preserving date)
918 - `edit` to edit this changeset (preserving date)
919
919
920 There are a number of ways to select the root changeset:
920 There are a number of ways to select the root changeset:
921
921
922 - Specify ANCESTOR directly
922 - Specify ANCESTOR directly
923
923
924 - Use --outgoing -- it will be the first linear changeset not
924 - Use --outgoing -- it will be the first linear changeset not
925 included in destination. (See :hg:`help config.paths.default-push`)
925 included in destination. (See :hg:`help config.paths.default-push`)
926
926
927 - Otherwise, the value from the "histedit.defaultrev" config option
927 - Otherwise, the value from the "histedit.defaultrev" config option
928 is used as a revset to select the base revision when ANCESTOR is not
928 is used as a revset to select the base revision when ANCESTOR is not
929 specified. The first revision returned by the revset is used. By
929 specified. The first revision returned by the revset is used. By
930 default, this selects the editable history that is unique to the
930 default, this selects the editable history that is unique to the
931 ancestry of the working directory.
931 ancestry of the working directory.
932
932
933 .. container:: verbose
933 .. container:: verbose
934
934
935 If you use --outgoing, this command will abort if there are ambiguous
935 If you use --outgoing, this command will abort if there are ambiguous
936 outgoing revisions. For example, if there are multiple branches
936 outgoing revisions. For example, if there are multiple branches
937 containing outgoing revisions.
937 containing outgoing revisions.
938
938
939 Use "min(outgoing() and ::.)" or similar revset specification
939 Use "min(outgoing() and ::.)" or similar revset specification
940 instead of --outgoing to specify edit target revision exactly in
940 instead of --outgoing to specify edit target revision exactly in
941 such ambiguous situation. See :hg:`help revsets` for detail about
941 such ambiguous situation. See :hg:`help revsets` for detail about
942 selecting revisions.
942 selecting revisions.
943
943
944 .. container:: verbose
944 .. container:: verbose
945
945
946 Examples:
946 Examples:
947
947
948 - A number of changes have been made.
948 - A number of changes have been made.
949 Revision 3 is no longer needed.
949 Revision 3 is no longer needed.
950
950
951 Start history editing from revision 3::
951 Start history editing from revision 3::
952
952
953 hg histedit -r 3
953 hg histedit -r 3
954
954
955 An editor opens, containing the list of revisions,
955 An editor opens, containing the list of revisions,
956 with specific actions specified::
956 with specific actions specified::
957
957
958 pick 5339bf82f0ca 3 Zworgle the foobar
958 pick 5339bf82f0ca 3 Zworgle the foobar
959 pick 8ef592ce7cc4 4 Bedazzle the zerlog
959 pick 8ef592ce7cc4 4 Bedazzle the zerlog
960 pick 0a9639fcda9d 5 Morgify the cromulancy
960 pick 0a9639fcda9d 5 Morgify the cromulancy
961
961
962 Additional information about the possible actions
962 Additional information about the possible actions
963 to take appears below the list of revisions.
963 to take appears below the list of revisions.
964
964
965 To remove revision 3 from the history,
965 To remove revision 3 from the history,
966 its action (at the beginning of the relevant line)
966 its action (at the beginning of the relevant line)
967 is changed to 'drop'::
967 is changed to 'drop'::
968
968
969 drop 5339bf82f0ca 3 Zworgle the foobar
969 drop 5339bf82f0ca 3 Zworgle the foobar
970 pick 8ef592ce7cc4 4 Bedazzle the zerlog
970 pick 8ef592ce7cc4 4 Bedazzle the zerlog
971 pick 0a9639fcda9d 5 Morgify the cromulancy
971 pick 0a9639fcda9d 5 Morgify the cromulancy
972
972
973 - A number of changes have been made.
973 - A number of changes have been made.
974 Revision 2 and 4 need to be swapped.
974 Revision 2 and 4 need to be swapped.
975
975
976 Start history editing from revision 2::
976 Start history editing from revision 2::
977
977
978 hg histedit -r 2
978 hg histedit -r 2
979
979
980 An editor opens, containing the list of revisions,
980 An editor opens, containing the list of revisions,
981 with specific actions specified::
981 with specific actions specified::
982
982
983 pick 252a1af424ad 2 Blorb a morgwazzle
983 pick 252a1af424ad 2 Blorb a morgwazzle
984 pick 5339bf82f0ca 3 Zworgle the foobar
984 pick 5339bf82f0ca 3 Zworgle the foobar
985 pick 8ef592ce7cc4 4 Bedazzle the zerlog
985 pick 8ef592ce7cc4 4 Bedazzle the zerlog
986
986
987 To swap revision 2 and 4, its lines are swapped
987 To swap revision 2 and 4, its lines are swapped
988 in the editor::
988 in the editor::
989
989
990 pick 8ef592ce7cc4 4 Bedazzle the zerlog
990 pick 8ef592ce7cc4 4 Bedazzle the zerlog
991 pick 5339bf82f0ca 3 Zworgle the foobar
991 pick 5339bf82f0ca 3 Zworgle the foobar
992 pick 252a1af424ad 2 Blorb a morgwazzle
992 pick 252a1af424ad 2 Blorb a morgwazzle
993
993
994 Returns 0 on success, 1 if user intervention is required (not only
994 Returns 0 on success, 1 if user intervention is required (not only
995 for intentional "edit" command, but also for resolving unexpected
995 for intentional "edit" command, but also for resolving unexpected
996 conflicts).
996 conflicts).
997 """
997 """
998 state = histeditstate(repo)
998 state = histeditstate(repo)
999 try:
999 try:
1000 state.wlock = repo.wlock()
1000 state.wlock = repo.wlock()
1001 state.lock = repo.lock()
1001 state.lock = repo.lock()
1002 _histedit(ui, repo, state, *freeargs, **opts)
1002 _histedit(ui, repo, state, *freeargs, **opts)
1003 finally:
1003 finally:
1004 release(state.lock, state.wlock)
1004 release(state.lock, state.wlock)
1005
1005
1006 goalcontinue = 'continue'
1006 goalcontinue = 'continue'
1007 goalabort = 'abort'
1007 goalabort = 'abort'
1008 goaleditplan = 'edit-plan'
1008 goaleditplan = 'edit-plan'
1009 goalnew = 'new'
1009 goalnew = 'new'
1010
1010
1011 def _getgoal(opts):
1011 def _getgoal(opts):
1012 if opts.get('continue'):
1012 if opts.get('continue'):
1013 return goalcontinue
1013 return goalcontinue
1014 if opts.get('abort'):
1014 if opts.get('abort'):
1015 return goalabort
1015 return goalabort
1016 if opts.get('edit_plan'):
1016 if opts.get('edit_plan'):
1017 return goaleditplan
1017 return goaleditplan
1018 return goalnew
1018 return goalnew
1019
1019
1020 def _readfile(ui, path):
1020 def _readfile(ui, path):
1021 if path == '-':
1021 if path == '-':
1022 with ui.timeblockedsection('histedit'):
1022 with ui.timeblockedsection('histedit'):
1023 return ui.fin.read()
1023 return ui.fin.read()
1024 else:
1024 else:
1025 with open(path, 'rb') as f:
1025 with open(path, 'rb') as f:
1026 return f.read()
1026 return f.read()
1027
1027
1028 def _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs):
1028 def _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs):
1029 # TODO only abort if we try to histedit mq patches, not just
1029 # TODO only abort if we try to histedit mq patches, not just
1030 # blanket if mq patches are applied somewhere
1030 # blanket if mq patches are applied somewhere
1031 mq = getattr(repo, 'mq', None)
1031 mq = getattr(repo, 'mq', None)
1032 if mq and mq.applied:
1032 if mq and mq.applied:
1033 raise error.Abort(_('source has mq patches applied'))
1033 raise error.Abort(_('source has mq patches applied'))
1034
1034
1035 # basic argument incompatibility processing
1035 # basic argument incompatibility processing
1036 outg = opts.get('outgoing')
1036 outg = opts.get('outgoing')
1037 editplan = opts.get('edit_plan')
1037 editplan = opts.get('edit_plan')
1038 abort = opts.get('abort')
1038 abort = opts.get('abort')
1039 force = opts.get('force')
1039 force = opts.get('force')
1040 if force and not outg:
1040 if force and not outg:
1041 raise error.Abort(_('--force only allowed with --outgoing'))
1041 raise error.Abort(_('--force only allowed with --outgoing'))
1042 if goal == 'continue':
1042 if goal == 'continue':
1043 if any((outg, abort, revs, freeargs, rules, editplan)):
1043 if any((outg, abort, revs, freeargs, rules, editplan)):
1044 raise error.Abort(_('no arguments allowed with --continue'))
1044 raise error.Abort(_('no arguments allowed with --continue'))
1045 elif goal == 'abort':
1045 elif goal == 'abort':
1046 if any((outg, revs, freeargs, rules, editplan)):
1046 if any((outg, revs, freeargs, rules, editplan)):
1047 raise error.Abort(_('no arguments allowed with --abort'))
1047 raise error.Abort(_('no arguments allowed with --abort'))
1048 elif goal == 'edit-plan':
1048 elif goal == 'edit-plan':
1049 if any((outg, revs, freeargs)):
1049 if any((outg, revs, freeargs)):
1050 raise error.Abort(_('only --commands argument allowed with '
1050 raise error.Abort(_('only --commands argument allowed with '
1051 '--edit-plan'))
1051 '--edit-plan'))
1052 else:
1052 else:
1053 if os.path.exists(os.path.join(repo.path, 'histedit-state')):
1053 if os.path.exists(os.path.join(repo.path, 'histedit-state')):
1054 raise error.Abort(_('history edit already in progress, try '
1054 raise error.Abort(_('history edit already in progress, try '
1055 '--continue or --abort'))
1055 '--continue or --abort'))
1056 if outg:
1056 if outg:
1057 if revs:
1057 if revs:
1058 raise error.Abort(_('no revisions allowed with --outgoing'))
1058 raise error.Abort(_('no revisions allowed with --outgoing'))
1059 if len(freeargs) > 1:
1059 if len(freeargs) > 1:
1060 raise error.Abort(
1060 raise error.Abort(
1061 _('only one repo argument allowed with --outgoing'))
1061 _('only one repo argument allowed with --outgoing'))
1062 else:
1062 else:
1063 revs.extend(freeargs)
1063 revs.extend(freeargs)
1064 if len(revs) == 0:
1064 if len(revs) == 0:
1065 defaultrev = destutil.desthistedit(ui, repo)
1065 defaultrev = destutil.desthistedit(ui, repo)
1066 if defaultrev is not None:
1066 if defaultrev is not None:
1067 revs.append(defaultrev)
1067 revs.append(defaultrev)
1068
1068
1069 if len(revs) != 1:
1069 if len(revs) != 1:
1070 raise error.Abort(
1070 raise error.Abort(
1071 _('histedit requires exactly one ancestor revision'))
1071 _('histedit requires exactly one ancestor revision'))
1072
1072
1073 def _histedit(ui, repo, state, *freeargs, **opts):
1073 def _histedit(ui, repo, state, *freeargs, **opts):
1074 goal = _getgoal(opts)
1074 goal = _getgoal(opts)
1075 revs = opts.get('rev', [])
1075 revs = opts.get('rev', [])
1076 rules = opts.get('commands', '')
1076 rules = opts.get('commands', '')
1077 state.keep = opts.get('keep', False)
1077 state.keep = opts.get('keep', False)
1078
1078
1079 _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs)
1079 _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs)
1080
1080
1081 # rebuild state
1081 # rebuild state
1082 if goal == goalcontinue:
1082 if goal == goalcontinue:
1083 state.read()
1083 state.read()
1084 state = bootstrapcontinue(ui, state, opts)
1084 state = bootstrapcontinue(ui, state, opts)
1085 elif goal == goaleditplan:
1085 elif goal == goaleditplan:
1086 _edithisteditplan(ui, repo, state, rules)
1086 _edithisteditplan(ui, repo, state, rules)
1087 return
1087 return
1088 elif goal == goalabort:
1088 elif goal == goalabort:
1089 _aborthistedit(ui, repo, state)
1089 _aborthistedit(ui, repo, state)
1090 return
1090 return
1091 else:
1091 else:
1092 # goal == goalnew
1092 # goal == goalnew
1093 _newhistedit(ui, repo, state, revs, freeargs, opts)
1093 _newhistedit(ui, repo, state, revs, freeargs, opts)
1094
1094
1095 _continuehistedit(ui, repo, state)
1095 _continuehistedit(ui, repo, state)
1096 _finishhistedit(ui, repo, state)
1096 _finishhistedit(ui, repo, state)
1097
1097
1098 def _continuehistedit(ui, repo, state):
1098 def _continuehistedit(ui, repo, state):
1099 """This function runs after either:
1099 """This function runs after either:
1100 - bootstrapcontinue (if the goal is 'continue')
1100 - bootstrapcontinue (if the goal is 'continue')
1101 - _newhistedit (if the goal is 'new')
1101 - _newhistedit (if the goal is 'new')
1102 """
1102 """
1103 # preprocess rules so that we can hide inner folds from the user
1103 # preprocess rules so that we can hide inner folds from the user
1104 # and only show one editor
1104 # and only show one editor
1105 actions = state.actions[:]
1105 actions = state.actions[:]
1106 for idx, (action, nextact) in enumerate(
1106 for idx, (action, nextact) in enumerate(
1107 zip(actions, actions[1:] + [None])):
1107 zip(actions, actions[1:] + [None])):
1108 if action.verb == 'fold' and nextact and nextact.verb == 'fold':
1108 if action.verb == 'fold' and nextact and nextact.verb == 'fold':
1109 state.actions[idx].__class__ = _multifold
1109 state.actions[idx].__class__ = _multifold
1110
1110
1111 total = len(state.actions)
1111 total = len(state.actions)
1112 pos = 0
1112 pos = 0
1113 state.tr = None
1113 state.tr = None
1114
1114
1115 # Force an initial state file write, so the user can run --abort/continue
1115 # Force an initial state file write, so the user can run --abort/continue
1116 # even if there's an exception before the first transaction serialize.
1116 # even if there's an exception before the first transaction serialize.
1117 state.write()
1117 state.write()
1118 try:
1118 try:
1119 # Don't use singletransaction by default since it rolls the entire
1119 # Don't use singletransaction by default since it rolls the entire
1120 # transaction back if an unexpected exception happens (like a
1120 # transaction back if an unexpected exception happens (like a
1121 # pretxncommit hook throws, or the user aborts the commit msg editor).
1121 # pretxncommit hook throws, or the user aborts the commit msg editor).
1122 if ui.configbool("histedit", "singletransaction", False):
1122 if ui.configbool("histedit", "singletransaction", False):
1123 # Don't use a 'with' for the transaction, since actions may close
1123 # Don't use a 'with' for the transaction, since actions may close
1124 # and reopen a transaction. For example, if the action executes an
1124 # and reopen a transaction. For example, if the action executes an
1125 # external process it may choose to commit the transaction first.
1125 # external process it may choose to commit the transaction first.
1126 state.tr = repo.transaction('histedit')
1126 state.tr = repo.transaction('histedit')
1127
1127
1128 while state.actions:
1128 while state.actions:
1129 state.write(tr=state.tr)
1129 state.write(tr=state.tr)
1130 actobj = state.actions[0]
1130 actobj = state.actions[0]
1131 pos += 1
1131 pos += 1
1132 ui.progress(_("editing"), pos, actobj.torule(),
1132 ui.progress(_("editing"), pos, actobj.torule(),
1133 _('changes'), total)
1133 _('changes'), total)
1134 ui.debug('histedit: processing %s %s\n' % (actobj.verb,\
1134 ui.debug('histedit: processing %s %s\n' % (actobj.verb,\
1135 actobj.torule()))
1135 actobj.torule()))
1136 parentctx, replacement_ = actobj.run()
1136 parentctx, replacement_ = actobj.run()
1137 state.parentctxnode = parentctx.node()
1137 state.parentctxnode = parentctx.node()
1138 state.replacements.extend(replacement_)
1138 state.replacements.extend(replacement_)
1139 state.actions.pop(0)
1139 state.actions.pop(0)
1140
1140
1141 if state.tr is not None:
1141 if state.tr is not None:
1142 state.tr.close()
1142 state.tr.close()
1143 except error.InterventionRequired:
1143 except error.InterventionRequired:
1144 if state.tr is not None:
1144 if state.tr is not None:
1145 state.tr.close()
1145 state.tr.close()
1146 raise
1146 raise
1147 except Exception:
1147 except Exception:
1148 if state.tr is not None:
1148 if state.tr is not None:
1149 state.tr.abort()
1149 state.tr.abort()
1150 raise
1150 raise
1151
1151
1152 state.write()
1152 state.write()
1153 ui.progress(_("editing"), None)
1153 ui.progress(_("editing"), None)
1154
1154
1155 def _finishhistedit(ui, repo, state):
1155 def _finishhistedit(ui, repo, state):
1156 """This action runs when histedit is finishing its session"""
1156 """This action runs when histedit is finishing its session"""
1157 repo.ui.pushbuffer()
1157 repo.ui.pushbuffer()
1158 hg.update(repo, state.parentctxnode, quietempty=True)
1158 hg.update(repo, state.parentctxnode, quietempty=True)
1159 repo.ui.popbuffer()
1159 repo.ui.popbuffer()
1160
1160
1161 mapping, tmpnodes, created, ntm = processreplacement(state)
1161 mapping, tmpnodes, created, ntm = processreplacement(state)
1162 if mapping:
1162 if mapping:
1163 for prec, succs in mapping.iteritems():
1163 for prec, succs in mapping.iteritems():
1164 if not succs:
1164 if not succs:
1165 ui.debug('histedit: %s is dropped\n' % node.short(prec))
1165 ui.debug('histedit: %s is dropped\n' % node.short(prec))
1166 else:
1166 else:
1167 ui.debug('histedit: %s is replaced by %s\n' % (
1167 ui.debug('histedit: %s is replaced by %s\n' % (
1168 node.short(prec), node.short(succs[0])))
1168 node.short(prec), node.short(succs[0])))
1169 if len(succs) > 1:
1169 if len(succs) > 1:
1170 m = 'histedit: %s'
1170 m = 'histedit: %s'
1171 for n in succs[1:]:
1171 for n in succs[1:]:
1172 ui.debug(m % node.short(n))
1172 ui.debug(m % node.short(n))
1173
1173
1174 safecleanupnode(ui, repo, 'temp', tmpnodes)
1174 safecleanupnode(ui, repo, tmpnodes)
1175
1175
1176 if not state.keep:
1176 if not state.keep:
1177 if mapping:
1177 if mapping:
1178 movebookmarks(ui, repo, mapping, state.topmost, ntm)
1178 movebookmarks(ui, repo, mapping, state.topmost, ntm)
1179 # TODO update mq state
1179 # TODO update mq state
1180 safecleanupnode(ui, repo, 'replaced', mapping)
1180 safecleanupnode(ui, repo, mapping)
1181
1181
1182 state.clear()
1182 state.clear()
1183 if os.path.exists(repo.sjoin('undo')):
1183 if os.path.exists(repo.sjoin('undo')):
1184 os.unlink(repo.sjoin('undo'))
1184 os.unlink(repo.sjoin('undo'))
1185 if repo.vfs.exists('histedit-last-edit.txt'):
1185 if repo.vfs.exists('histedit-last-edit.txt'):
1186 repo.vfs.unlink('histedit-last-edit.txt')
1186 repo.vfs.unlink('histedit-last-edit.txt')
1187
1187
1188 def _aborthistedit(ui, repo, state):
1188 def _aborthistedit(ui, repo, state):
1189 try:
1189 try:
1190 state.read()
1190 state.read()
1191 __, leafs, tmpnodes, __ = processreplacement(state)
1191 __, leafs, tmpnodes, __ = processreplacement(state)
1192 ui.debug('restore wc to old parent %s\n'
1192 ui.debug('restore wc to old parent %s\n'
1193 % node.short(state.topmost))
1193 % node.short(state.topmost))
1194
1194
1195 # Recover our old commits if necessary
1195 # Recover our old commits if necessary
1196 if not state.topmost in repo and state.backupfile:
1196 if not state.topmost in repo and state.backupfile:
1197 backupfile = repo.vfs.join(state.backupfile)
1197 backupfile = repo.vfs.join(state.backupfile)
1198 f = hg.openpath(ui, backupfile)
1198 f = hg.openpath(ui, backupfile)
1199 gen = exchange.readbundle(ui, f, backupfile)
1199 gen = exchange.readbundle(ui, f, backupfile)
1200 with repo.transaction('histedit.abort') as tr:
1200 with repo.transaction('histedit.abort') as tr:
1201 bundle2.applybundle(repo, gen, tr, source='histedit',
1201 bundle2.applybundle(repo, gen, tr, source='histedit',
1202 url='bundle:' + backupfile)
1202 url='bundle:' + backupfile)
1203
1203
1204 os.remove(backupfile)
1204 os.remove(backupfile)
1205
1205
1206 # check whether we should update away
1206 # check whether we should update away
1207 if repo.unfiltered().revs('parents() and (%n or %ln::)',
1207 if repo.unfiltered().revs('parents() and (%n or %ln::)',
1208 state.parentctxnode, leafs | tmpnodes):
1208 state.parentctxnode, leafs | tmpnodes):
1209 hg.clean(repo, state.topmost, show_stats=True, quietempty=True)
1209 hg.clean(repo, state.topmost, show_stats=True, quietempty=True)
1210 cleanupnode(ui, repo, 'created', tmpnodes)
1210 cleanupnode(ui, repo, tmpnodes)
1211 cleanupnode(ui, repo, 'temp', leafs)
1211 cleanupnode(ui, repo, leafs)
1212 except Exception:
1212 except Exception:
1213 if state.inprogress():
1213 if state.inprogress():
1214 ui.warn(_('warning: encountered an exception during histedit '
1214 ui.warn(_('warning: encountered an exception during histedit '
1215 '--abort; the repository may not have been completely '
1215 '--abort; the repository may not have been completely '
1216 'cleaned up\n'))
1216 'cleaned up\n'))
1217 raise
1217 raise
1218 finally:
1218 finally:
1219 state.clear()
1219 state.clear()
1220
1220
1221 def _edithisteditplan(ui, repo, state, rules):
1221 def _edithisteditplan(ui, repo, state, rules):
1222 state.read()
1222 state.read()
1223 if not rules:
1223 if not rules:
1224 comment = geteditcomment(ui,
1224 comment = geteditcomment(ui,
1225 node.short(state.parentctxnode),
1225 node.short(state.parentctxnode),
1226 node.short(state.topmost))
1226 node.short(state.topmost))
1227 rules = ruleeditor(repo, ui, state.actions, comment)
1227 rules = ruleeditor(repo, ui, state.actions, comment)
1228 else:
1228 else:
1229 rules = _readfile(ui, rules)
1229 rules = _readfile(ui, rules)
1230 actions = parserules(rules, state)
1230 actions = parserules(rules, state)
1231 ctxs = [repo[act.node] \
1231 ctxs = [repo[act.node] \
1232 for act in state.actions if act.node]
1232 for act in state.actions if act.node]
1233 warnverifyactions(ui, repo, actions, state, ctxs)
1233 warnverifyactions(ui, repo, actions, state, ctxs)
1234 state.actions = actions
1234 state.actions = actions
1235 state.write()
1235 state.write()
1236
1236
1237 def _newhistedit(ui, repo, state, revs, freeargs, opts):
1237 def _newhistedit(ui, repo, state, revs, freeargs, opts):
1238 outg = opts.get('outgoing')
1238 outg = opts.get('outgoing')
1239 rules = opts.get('commands', '')
1239 rules = opts.get('commands', '')
1240 force = opts.get('force')
1240 force = opts.get('force')
1241
1241
1242 cmdutil.checkunfinished(repo)
1242 cmdutil.checkunfinished(repo)
1243 cmdutil.bailifchanged(repo)
1243 cmdutil.bailifchanged(repo)
1244
1244
1245 topmost, empty = repo.dirstate.parents()
1245 topmost, empty = repo.dirstate.parents()
1246 if outg:
1246 if outg:
1247 if freeargs:
1247 if freeargs:
1248 remote = freeargs[0]
1248 remote = freeargs[0]
1249 else:
1249 else:
1250 remote = None
1250 remote = None
1251 root = findoutgoing(ui, repo, remote, force, opts)
1251 root = findoutgoing(ui, repo, remote, force, opts)
1252 else:
1252 else:
1253 rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs)))
1253 rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs)))
1254 if len(rr) != 1:
1254 if len(rr) != 1:
1255 raise error.Abort(_('The specified revisions must have '
1255 raise error.Abort(_('The specified revisions must have '
1256 'exactly one common root'))
1256 'exactly one common root'))
1257 root = rr[0].node()
1257 root = rr[0].node()
1258
1258
1259 revs = between(repo, root, topmost, state.keep)
1259 revs = between(repo, root, topmost, state.keep)
1260 if not revs:
1260 if not revs:
1261 raise error.Abort(_('%s is not an ancestor of working directory') %
1261 raise error.Abort(_('%s is not an ancestor of working directory') %
1262 node.short(root))
1262 node.short(root))
1263
1263
1264 ctxs = [repo[r] for r in revs]
1264 ctxs = [repo[r] for r in revs]
1265 if not rules:
1265 if not rules:
1266 comment = geteditcomment(ui, node.short(root), node.short(topmost))
1266 comment = geteditcomment(ui, node.short(root), node.short(topmost))
1267 actions = [pick(state, r) for r in revs]
1267 actions = [pick(state, r) for r in revs]
1268 rules = ruleeditor(repo, ui, actions, comment)
1268 rules = ruleeditor(repo, ui, actions, comment)
1269 else:
1269 else:
1270 rules = _readfile(ui, rules)
1270 rules = _readfile(ui, rules)
1271 actions = parserules(rules, state)
1271 actions = parserules(rules, state)
1272 warnverifyactions(ui, repo, actions, state, ctxs)
1272 warnverifyactions(ui, repo, actions, state, ctxs)
1273
1273
1274 parentctxnode = repo[root].parents()[0].node()
1274 parentctxnode = repo[root].parents()[0].node()
1275
1275
1276 state.parentctxnode = parentctxnode
1276 state.parentctxnode = parentctxnode
1277 state.actions = actions
1277 state.actions = actions
1278 state.topmost = topmost
1278 state.topmost = topmost
1279 state.replacements = []
1279 state.replacements = []
1280
1280
1281 # Create a backup so we can always abort completely.
1281 # Create a backup so we can always abort completely.
1282 backupfile = None
1282 backupfile = None
1283 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1283 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1284 backupfile = repair._bundle(repo, [parentctxnode], [topmost], root,
1284 backupfile = repair._bundle(repo, [parentctxnode], [topmost], root,
1285 'histedit')
1285 'histedit')
1286 state.backupfile = backupfile
1286 state.backupfile = backupfile
1287
1287
1288 def _getsummary(ctx):
1288 def _getsummary(ctx):
1289 # a common pattern is to extract the summary but default to the empty
1289 # a common pattern is to extract the summary but default to the empty
1290 # string
1290 # string
1291 summary = ctx.description() or ''
1291 summary = ctx.description() or ''
1292 if summary:
1292 if summary:
1293 summary = summary.splitlines()[0]
1293 summary = summary.splitlines()[0]
1294 return summary
1294 return summary
1295
1295
1296 def bootstrapcontinue(ui, state, opts):
1296 def bootstrapcontinue(ui, state, opts):
1297 repo = state.repo
1297 repo = state.repo
1298
1298
1299 ms = mergemod.mergestate.read(repo)
1299 ms = mergemod.mergestate.read(repo)
1300 mergeutil.checkunresolved(ms)
1300 mergeutil.checkunresolved(ms)
1301
1301
1302 if state.actions:
1302 if state.actions:
1303 actobj = state.actions.pop(0)
1303 actobj = state.actions.pop(0)
1304
1304
1305 if _isdirtywc(repo):
1305 if _isdirtywc(repo):
1306 actobj.continuedirty()
1306 actobj.continuedirty()
1307 if _isdirtywc(repo):
1307 if _isdirtywc(repo):
1308 abortdirty()
1308 abortdirty()
1309
1309
1310 parentctx, replacements = actobj.continueclean()
1310 parentctx, replacements = actobj.continueclean()
1311
1311
1312 state.parentctxnode = parentctx.node()
1312 state.parentctxnode = parentctx.node()
1313 state.replacements.extend(replacements)
1313 state.replacements.extend(replacements)
1314
1314
1315 return state
1315 return state
1316
1316
1317 def between(repo, old, new, keep):
1317 def between(repo, old, new, keep):
1318 """select and validate the set of revision to edit
1318 """select and validate the set of revision to edit
1319
1319
1320 When keep is false, the specified set can't have children."""
1320 When keep is false, the specified set can't have children."""
1321 ctxs = list(repo.set('%n::%n', old, new))
1321 ctxs = list(repo.set('%n::%n', old, new))
1322 if ctxs and not keep:
1322 if ctxs and not keep:
1323 if (not obsolete.isenabled(repo, obsolete.allowunstableopt) and
1323 if (not obsolete.isenabled(repo, obsolete.allowunstableopt) and
1324 repo.revs('(%ld::) - (%ld)', ctxs, ctxs)):
1324 repo.revs('(%ld::) - (%ld)', ctxs, ctxs)):
1325 raise error.Abort(_('can only histedit a changeset together '
1325 raise error.Abort(_('can only histedit a changeset together '
1326 'with all its descendants'))
1326 'with all its descendants'))
1327 if repo.revs('(%ld) and merge()', ctxs):
1327 if repo.revs('(%ld) and merge()', ctxs):
1328 raise error.Abort(_('cannot edit history that contains merges'))
1328 raise error.Abort(_('cannot edit history that contains merges'))
1329 root = ctxs[0] # list is already sorted by repo.set
1329 root = ctxs[0] # list is already sorted by repo.set
1330 if not root.mutable():
1330 if not root.mutable():
1331 raise error.Abort(_('cannot edit public changeset: %s') % root,
1331 raise error.Abort(_('cannot edit public changeset: %s') % root,
1332 hint=_("see 'hg help phases' for details"))
1332 hint=_("see 'hg help phases' for details"))
1333 return [c.node() for c in ctxs]
1333 return [c.node() for c in ctxs]
1334
1334
1335 def ruleeditor(repo, ui, actions, editcomment=""):
1335 def ruleeditor(repo, ui, actions, editcomment=""):
1336 """open an editor to edit rules
1336 """open an editor to edit rules
1337
1337
1338 rules are in the format [ [act, ctx], ...] like in state.rules
1338 rules are in the format [ [act, ctx], ...] like in state.rules
1339 """
1339 """
1340 if repo.ui.configbool("experimental", "histedit.autoverb"):
1340 if repo.ui.configbool("experimental", "histedit.autoverb"):
1341 newact = util.sortdict()
1341 newact = util.sortdict()
1342 for act in actions:
1342 for act in actions:
1343 ctx = repo[act.node]
1343 ctx = repo[act.node]
1344 summary = _getsummary(ctx)
1344 summary = _getsummary(ctx)
1345 fword = summary.split(' ', 1)[0].lower()
1345 fword = summary.split(' ', 1)[0].lower()
1346 added = False
1346 added = False
1347
1347
1348 # if it doesn't end with the special character '!' just skip this
1348 # if it doesn't end with the special character '!' just skip this
1349 if fword.endswith('!'):
1349 if fword.endswith('!'):
1350 fword = fword[:-1]
1350 fword = fword[:-1]
1351 if fword in primaryactions | secondaryactions | tertiaryactions:
1351 if fword in primaryactions | secondaryactions | tertiaryactions:
1352 act.verb = fword
1352 act.verb = fword
1353 # get the target summary
1353 # get the target summary
1354 tsum = summary[len(fword) + 1:].lstrip()
1354 tsum = summary[len(fword) + 1:].lstrip()
1355 # safe but slow: reverse iterate over the actions so we
1355 # safe but slow: reverse iterate over the actions so we
1356 # don't clash on two commits having the same summary
1356 # don't clash on two commits having the same summary
1357 for na, l in reversed(list(newact.iteritems())):
1357 for na, l in reversed(list(newact.iteritems())):
1358 actx = repo[na.node]
1358 actx = repo[na.node]
1359 asum = _getsummary(actx)
1359 asum = _getsummary(actx)
1360 if asum == tsum:
1360 if asum == tsum:
1361 added = True
1361 added = True
1362 l.append(act)
1362 l.append(act)
1363 break
1363 break
1364
1364
1365 if not added:
1365 if not added:
1366 newact[act] = []
1366 newact[act] = []
1367
1367
1368 # copy over and flatten the new list
1368 # copy over and flatten the new list
1369 actions = []
1369 actions = []
1370 for na, l in newact.iteritems():
1370 for na, l in newact.iteritems():
1371 actions.append(na)
1371 actions.append(na)
1372 actions += l
1372 actions += l
1373
1373
1374 rules = '\n'.join([act.torule() for act in actions])
1374 rules = '\n'.join([act.torule() for act in actions])
1375 rules += '\n\n'
1375 rules += '\n\n'
1376 rules += editcomment
1376 rules += editcomment
1377 rules = ui.edit(rules, ui.username(), {'prefix': 'histedit'},
1377 rules = ui.edit(rules, ui.username(), {'prefix': 'histedit'},
1378 repopath=repo.path)
1378 repopath=repo.path)
1379
1379
1380 # Save edit rules in .hg/histedit-last-edit.txt in case
1380 # Save edit rules in .hg/histedit-last-edit.txt in case
1381 # the user needs to ask for help after something
1381 # the user needs to ask for help after something
1382 # surprising happens.
1382 # surprising happens.
1383 f = open(repo.vfs.join('histedit-last-edit.txt'), 'w')
1383 f = open(repo.vfs.join('histedit-last-edit.txt'), 'w')
1384 f.write(rules)
1384 f.write(rules)
1385 f.close()
1385 f.close()
1386
1386
1387 return rules
1387 return rules
1388
1388
1389 def parserules(rules, state):
1389 def parserules(rules, state):
1390 """Read the histedit rules string and return list of action objects """
1390 """Read the histedit rules string and return list of action objects """
1391 rules = [l for l in (r.strip() for r in rules.splitlines())
1391 rules = [l for l in (r.strip() for r in rules.splitlines())
1392 if l and not l.startswith('#')]
1392 if l and not l.startswith('#')]
1393 actions = []
1393 actions = []
1394 for r in rules:
1394 for r in rules:
1395 if ' ' not in r:
1395 if ' ' not in r:
1396 raise error.ParseError(_('malformed line "%s"') % r)
1396 raise error.ParseError(_('malformed line "%s"') % r)
1397 verb, rest = r.split(' ', 1)
1397 verb, rest = r.split(' ', 1)
1398
1398
1399 if verb not in actiontable:
1399 if verb not in actiontable:
1400 raise error.ParseError(_('unknown action "%s"') % verb)
1400 raise error.ParseError(_('unknown action "%s"') % verb)
1401
1401
1402 action = actiontable[verb].fromrule(state, rest)
1402 action = actiontable[verb].fromrule(state, rest)
1403 actions.append(action)
1403 actions.append(action)
1404 return actions
1404 return actions
1405
1405
1406 def warnverifyactions(ui, repo, actions, state, ctxs):
1406 def warnverifyactions(ui, repo, actions, state, ctxs):
1407 try:
1407 try:
1408 verifyactions(actions, state, ctxs)
1408 verifyactions(actions, state, ctxs)
1409 except error.ParseError:
1409 except error.ParseError:
1410 if repo.vfs.exists('histedit-last-edit.txt'):
1410 if repo.vfs.exists('histedit-last-edit.txt'):
1411 ui.warn(_('warning: histedit rules saved '
1411 ui.warn(_('warning: histedit rules saved '
1412 'to: .hg/histedit-last-edit.txt\n'))
1412 'to: .hg/histedit-last-edit.txt\n'))
1413 raise
1413 raise
1414
1414
1415 def verifyactions(actions, state, ctxs):
1415 def verifyactions(actions, state, ctxs):
1416 """Verify that there exists exactly one action per given changeset and
1416 """Verify that there exists exactly one action per given changeset and
1417 other constraints.
1417 other constraints.
1418
1418
1419 Will abort if there are to many or too few rules, a malformed rule,
1419 Will abort if there are to many or too few rules, a malformed rule,
1420 or a rule on a changeset outside of the user-given range.
1420 or a rule on a changeset outside of the user-given range.
1421 """
1421 """
1422 expected = set(c.node() for c in ctxs)
1422 expected = set(c.node() for c in ctxs)
1423 seen = set()
1423 seen = set()
1424 prev = None
1424 prev = None
1425 for action in actions:
1425 for action in actions:
1426 action.verify(prev, expected, seen)
1426 action.verify(prev, expected, seen)
1427 prev = action
1427 prev = action
1428 if action.node is not None:
1428 if action.node is not None:
1429 seen.add(action.node)
1429 seen.add(action.node)
1430 missing = sorted(expected - seen) # sort to stabilize output
1430 missing = sorted(expected - seen) # sort to stabilize output
1431
1431
1432 if state.repo.ui.configbool('histedit', 'dropmissing'):
1432 if state.repo.ui.configbool('histedit', 'dropmissing'):
1433 if len(actions) == 0:
1433 if len(actions) == 0:
1434 raise error.ParseError(_('no rules provided'),
1434 raise error.ParseError(_('no rules provided'),
1435 hint=_('use strip extension to remove commits'))
1435 hint=_('use strip extension to remove commits'))
1436
1436
1437 drops = [drop(state, n) for n in missing]
1437 drops = [drop(state, n) for n in missing]
1438 # put the in the beginning so they execute immediately and
1438 # put the in the beginning so they execute immediately and
1439 # don't show in the edit-plan in the future
1439 # don't show in the edit-plan in the future
1440 actions[:0] = drops
1440 actions[:0] = drops
1441 elif missing:
1441 elif missing:
1442 raise error.ParseError(_('missing rules for changeset %s') %
1442 raise error.ParseError(_('missing rules for changeset %s') %
1443 node.short(missing[0]),
1443 node.short(missing[0]),
1444 hint=_('use "drop %s" to discard, see also: '
1444 hint=_('use "drop %s" to discard, see also: '
1445 "'hg help -e histedit.config'")
1445 "'hg help -e histedit.config'")
1446 % node.short(missing[0]))
1446 % node.short(missing[0]))
1447
1447
1448 def adjustreplacementsfrommarkers(repo, oldreplacements):
1448 def adjustreplacementsfrommarkers(repo, oldreplacements):
1449 """Adjust replacements from obsolescence markers
1449 """Adjust replacements from obsolescence markers
1450
1450
1451 Replacements structure is originally generated based on
1451 Replacements structure is originally generated based on
1452 histedit's state and does not account for changes that are
1452 histedit's state and does not account for changes that are
1453 not recorded there. This function fixes that by adding
1453 not recorded there. This function fixes that by adding
1454 data read from obsolescence markers"""
1454 data read from obsolescence markers"""
1455 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1455 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1456 return oldreplacements
1456 return oldreplacements
1457
1457
1458 unfi = repo.unfiltered()
1458 unfi = repo.unfiltered()
1459 nm = unfi.changelog.nodemap
1459 nm = unfi.changelog.nodemap
1460 obsstore = repo.obsstore
1460 obsstore = repo.obsstore
1461 newreplacements = list(oldreplacements)
1461 newreplacements = list(oldreplacements)
1462 oldsuccs = [r[1] for r in oldreplacements]
1462 oldsuccs = [r[1] for r in oldreplacements]
1463 # successors that have already been added to succstocheck once
1463 # successors that have already been added to succstocheck once
1464 seensuccs = set().union(*oldsuccs) # create a set from an iterable of tuples
1464 seensuccs = set().union(*oldsuccs) # create a set from an iterable of tuples
1465 succstocheck = list(seensuccs)
1465 succstocheck = list(seensuccs)
1466 while succstocheck:
1466 while succstocheck:
1467 n = succstocheck.pop()
1467 n = succstocheck.pop()
1468 missing = nm.get(n) is None
1468 missing = nm.get(n) is None
1469 markers = obsstore.successors.get(n, ())
1469 markers = obsstore.successors.get(n, ())
1470 if missing and not markers:
1470 if missing and not markers:
1471 # dead end, mark it as such
1471 # dead end, mark it as such
1472 newreplacements.append((n, ()))
1472 newreplacements.append((n, ()))
1473 for marker in markers:
1473 for marker in markers:
1474 nsuccs = marker[1]
1474 nsuccs = marker[1]
1475 newreplacements.append((n, nsuccs))
1475 newreplacements.append((n, nsuccs))
1476 for nsucc in nsuccs:
1476 for nsucc in nsuccs:
1477 if nsucc not in seensuccs:
1477 if nsucc not in seensuccs:
1478 seensuccs.add(nsucc)
1478 seensuccs.add(nsucc)
1479 succstocheck.append(nsucc)
1479 succstocheck.append(nsucc)
1480
1480
1481 return newreplacements
1481 return newreplacements
1482
1482
1483 def processreplacement(state):
1483 def processreplacement(state):
1484 """process the list of replacements to return
1484 """process the list of replacements to return
1485
1485
1486 1) the final mapping between original and created nodes
1486 1) the final mapping between original and created nodes
1487 2) the list of temporary node created by histedit
1487 2) the list of temporary node created by histedit
1488 3) the list of new commit created by histedit"""
1488 3) the list of new commit created by histedit"""
1489 replacements = adjustreplacementsfrommarkers(state.repo, state.replacements)
1489 replacements = adjustreplacementsfrommarkers(state.repo, state.replacements)
1490 allsuccs = set()
1490 allsuccs = set()
1491 replaced = set()
1491 replaced = set()
1492 fullmapping = {}
1492 fullmapping = {}
1493 # initialize basic set
1493 # initialize basic set
1494 # fullmapping records all operations recorded in replacement
1494 # fullmapping records all operations recorded in replacement
1495 for rep in replacements:
1495 for rep in replacements:
1496 allsuccs.update(rep[1])
1496 allsuccs.update(rep[1])
1497 replaced.add(rep[0])
1497 replaced.add(rep[0])
1498 fullmapping.setdefault(rep[0], set()).update(rep[1])
1498 fullmapping.setdefault(rep[0], set()).update(rep[1])
1499 new = allsuccs - replaced
1499 new = allsuccs - replaced
1500 tmpnodes = allsuccs & replaced
1500 tmpnodes = allsuccs & replaced
1501 # Reduce content fullmapping into direct relation between original nodes
1501 # Reduce content fullmapping into direct relation between original nodes
1502 # and final node created during history edition
1502 # and final node created during history edition
1503 # Dropped changeset are replaced by an empty list
1503 # Dropped changeset are replaced by an empty list
1504 toproceed = set(fullmapping)
1504 toproceed = set(fullmapping)
1505 final = {}
1505 final = {}
1506 while toproceed:
1506 while toproceed:
1507 for x in list(toproceed):
1507 for x in list(toproceed):
1508 succs = fullmapping[x]
1508 succs = fullmapping[x]
1509 for s in list(succs):
1509 for s in list(succs):
1510 if s in toproceed:
1510 if s in toproceed:
1511 # non final node with unknown closure
1511 # non final node with unknown closure
1512 # We can't process this now
1512 # We can't process this now
1513 break
1513 break
1514 elif s in final:
1514 elif s in final:
1515 # non final node, replace with closure
1515 # non final node, replace with closure
1516 succs.remove(s)
1516 succs.remove(s)
1517 succs.update(final[s])
1517 succs.update(final[s])
1518 else:
1518 else:
1519 final[x] = succs
1519 final[x] = succs
1520 toproceed.remove(x)
1520 toproceed.remove(x)
1521 # remove tmpnodes from final mapping
1521 # remove tmpnodes from final mapping
1522 for n in tmpnodes:
1522 for n in tmpnodes:
1523 del final[n]
1523 del final[n]
1524 # we expect all changes involved in final to exist in the repo
1524 # we expect all changes involved in final to exist in the repo
1525 # turn `final` into list (topologically sorted)
1525 # turn `final` into list (topologically sorted)
1526 nm = state.repo.changelog.nodemap
1526 nm = state.repo.changelog.nodemap
1527 for prec, succs in final.items():
1527 for prec, succs in final.items():
1528 final[prec] = sorted(succs, key=nm.get)
1528 final[prec] = sorted(succs, key=nm.get)
1529
1529
1530 # computed topmost element (necessary for bookmark)
1530 # computed topmost element (necessary for bookmark)
1531 if new:
1531 if new:
1532 newtopmost = sorted(new, key=state.repo.changelog.rev)[-1]
1532 newtopmost = sorted(new, key=state.repo.changelog.rev)[-1]
1533 elif not final:
1533 elif not final:
1534 # Nothing rewritten at all. we won't need `newtopmost`
1534 # Nothing rewritten at all. we won't need `newtopmost`
1535 # It is the same as `oldtopmost` and `processreplacement` know it
1535 # It is the same as `oldtopmost` and `processreplacement` know it
1536 newtopmost = None
1536 newtopmost = None
1537 else:
1537 else:
1538 # every body died. The newtopmost is the parent of the root.
1538 # every body died. The newtopmost is the parent of the root.
1539 r = state.repo.changelog.rev
1539 r = state.repo.changelog.rev
1540 newtopmost = state.repo[sorted(final, key=r)[0]].p1().node()
1540 newtopmost = state.repo[sorted(final, key=r)[0]].p1().node()
1541
1541
1542 return final, tmpnodes, new, newtopmost
1542 return final, tmpnodes, new, newtopmost
1543
1543
1544 def movetopmostbookmarks(repo, oldtopmost, newtopmost):
1544 def movetopmostbookmarks(repo, oldtopmost, newtopmost):
1545 """Move bookmark from oldtopmost to newly created topmost
1545 """Move bookmark from oldtopmost to newly created topmost
1546
1546
1547 This is arguably a feature and we may only want that for the active
1547 This is arguably a feature and we may only want that for the active
1548 bookmark. But the behavior is kept compatible with the old version for now.
1548 bookmark. But the behavior is kept compatible with the old version for now.
1549 """
1549 """
1550 if not oldtopmost or not newtopmost:
1550 if not oldtopmost or not newtopmost:
1551 return
1551 return
1552 oldbmarks = repo.nodebookmarks(oldtopmost)
1552 oldbmarks = repo.nodebookmarks(oldtopmost)
1553 if oldbmarks:
1553 if oldbmarks:
1554 with repo.lock(), repo.transaction('histedit') as tr:
1554 with repo.lock(), repo.transaction('histedit') as tr:
1555 marks = repo._bookmarks
1555 marks = repo._bookmarks
1556 for name in oldbmarks:
1556 for name in oldbmarks:
1557 marks[name] = newtopmost
1557 marks[name] = newtopmost
1558 marks.recordchange(tr)
1558 marks.recordchange(tr)
1559
1559
1560 def movebookmarks(ui, repo, mapping, oldtopmost, newtopmost):
1560 def movebookmarks(ui, repo, mapping, oldtopmost, newtopmost):
1561 """Move bookmark from old to newly created node"""
1561 """Move bookmark from old to newly created node"""
1562 if not mapping:
1562 if not mapping:
1563 # if nothing got rewritten there is not purpose for this function
1563 # if nothing got rewritten there is not purpose for this function
1564 return
1564 return
1565 movetopmostbookmarks(repo, oldtopmost, newtopmost)
1565 movetopmostbookmarks(repo, oldtopmost, newtopmost)
1566 moves = []
1566 moves = []
1567 for bk, old in sorted(repo._bookmarks.iteritems()):
1567 for bk, old in sorted(repo._bookmarks.iteritems()):
1568 base = old
1568 base = old
1569 new = mapping.get(base, None)
1569 new = mapping.get(base, None)
1570 if new is None:
1570 if new is None:
1571 continue
1571 continue
1572 while not new:
1572 while not new:
1573 # base is killed, trying with parent
1573 # base is killed, trying with parent
1574 base = repo[base].p1().node()
1574 base = repo[base].p1().node()
1575 new = mapping.get(base, (base,))
1575 new = mapping.get(base, (base,))
1576 # nothing to move
1576 # nothing to move
1577 moves.append((bk, new[-1]))
1577 moves.append((bk, new[-1]))
1578 if moves:
1578 if moves:
1579 lock = tr = None
1579 lock = tr = None
1580 try:
1580 try:
1581 lock = repo.lock()
1581 lock = repo.lock()
1582 tr = repo.transaction('histedit')
1582 tr = repo.transaction('histedit')
1583 marks = repo._bookmarks
1583 marks = repo._bookmarks
1584 for mark, new in moves:
1584 for mark, new in moves:
1585 old = marks[mark]
1585 old = marks[mark]
1586 marks[mark] = new
1586 marks[mark] = new
1587 marks.recordchange(tr)
1587 marks.recordchange(tr)
1588 tr.close()
1588 tr.close()
1589 finally:
1589 finally:
1590 release(tr, lock)
1590 release(tr, lock)
1591
1591
1592 def cleanupnode(ui, repo, name, nodes):
1592 def cleanupnode(ui, repo, nodes):
1593 """strip a group of nodes from the repository
1593 """strip a group of nodes from the repository
1594
1594
1595 The set of node to strip may contains unknown nodes."""
1595 The set of node to strip may contains unknown nodes."""
1596 with repo.lock():
1596 with repo.lock():
1597 # do not let filtering get in the way of the cleanse
1597 # do not let filtering get in the way of the cleanse
1598 # we should probably get rid of obsolescence marker created during the
1598 # we should probably get rid of obsolescence marker created during the
1599 # histedit, but we currently do not have such information.
1599 # histedit, but we currently do not have such information.
1600 repo = repo.unfiltered()
1600 repo = repo.unfiltered()
1601 # Find all nodes that need to be stripped
1601 # Find all nodes that need to be stripped
1602 # (we use %lr instead of %ln to silently ignore unknown items)
1602 # (we use %lr instead of %ln to silently ignore unknown items)
1603 nm = repo.changelog.nodemap
1603 nm = repo.changelog.nodemap
1604 nodes = sorted(n for n in nodes if n in nm)
1604 nodes = sorted(n for n in nodes if n in nm)
1605 roots = [c.node() for c in repo.set("roots(%ln)", nodes)]
1605 roots = [c.node() for c in repo.set("roots(%ln)", nodes)]
1606 for c in roots:
1606 for c in roots:
1607 # We should process node in reverse order to strip tip most first.
1607 # We should process node in reverse order to strip tip most first.
1608 # but this trigger a bug in changegroup hook.
1608 # but this trigger a bug in changegroup hook.
1609 # This would reduce bundle overhead
1609 # This would reduce bundle overhead
1610 repair.strip(ui, repo, c)
1610 repair.strip(ui, repo, c)
1611
1611
1612 def safecleanupnode(ui, repo, name, nodes):
1612 def safecleanupnode(ui, repo, nodes):
1613 """strip or obsolete nodes
1613 """strip or obsolete nodes
1614
1614
1615 nodes could be either a set or dict which maps to replacements.
1615 nodes could be either a set or dict which maps to replacements.
1616 nodes could be unknown (outside the repo).
1616 nodes could be unknown (outside the repo).
1617 """
1617 """
1618 supportsmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
1618 supportsmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
1619 if supportsmarkers:
1619 if supportsmarkers:
1620 if util.safehasattr(nodes, 'get'):
1620 if util.safehasattr(nodes, 'get'):
1621 # nodes is a dict-like mapping
1621 # nodes is a dict-like mapping
1622 # use unfiltered repo for successors in case they are hidden
1622 # use unfiltered repo for successors in case they are hidden
1623 urepo = repo.unfiltered()
1623 urepo = repo.unfiltered()
1624 def getmarker(prec):
1624 def getmarker(prec):
1625 succs = tuple(urepo[n] for n in nodes.get(prec, ()))
1625 succs = tuple(urepo[n] for n in nodes.get(prec, ()))
1626 return (repo[prec], succs)
1626 return (repo[prec], succs)
1627 else:
1627 else:
1628 # nodes is a set-like
1628 # nodes is a set-like
1629 def getmarker(prec):
1629 def getmarker(prec):
1630 return (repo[prec], ())
1630 return (repo[prec], ())
1631 # sort by revision number because it sound "right"
1631 # sort by revision number because it sound "right"
1632 sortednodes = sorted([n for n in nodes if n in repo],
1632 sortednodes = sorted([n for n in nodes if n in repo],
1633 key=repo.changelog.rev)
1633 key=repo.changelog.rev)
1634 markers = [getmarker(t) for t in sortednodes]
1634 markers = [getmarker(t) for t in sortednodes]
1635 if markers:
1635 if markers:
1636 obsolete.createmarkers(repo, markers, operation='histedit')
1636 obsolete.createmarkers(repo, markers, operation='histedit')
1637 else:
1637 else:
1638 return cleanupnode(ui, repo, name, nodes)
1638 return cleanupnode(ui, repo, nodes)
1639
1639
1640 def stripwrapper(orig, ui, repo, nodelist, *args, **kwargs):
1640 def stripwrapper(orig, ui, repo, nodelist, *args, **kwargs):
1641 if isinstance(nodelist, str):
1641 if isinstance(nodelist, str):
1642 nodelist = [nodelist]
1642 nodelist = [nodelist]
1643 if os.path.exists(os.path.join(repo.path, 'histedit-state')):
1643 if os.path.exists(os.path.join(repo.path, 'histedit-state')):
1644 state = histeditstate(repo)
1644 state = histeditstate(repo)
1645 state.read()
1645 state.read()
1646 histedit_nodes = {action.node for action
1646 histedit_nodes = {action.node for action
1647 in state.actions if action.node}
1647 in state.actions if action.node}
1648 common_nodes = histedit_nodes & set(nodelist)
1648 common_nodes = histedit_nodes & set(nodelist)
1649 if common_nodes:
1649 if common_nodes:
1650 raise error.Abort(_("histedit in progress, can't strip %s")
1650 raise error.Abort(_("histedit in progress, can't strip %s")
1651 % ', '.join(node.short(x) for x in common_nodes))
1651 % ', '.join(node.short(x) for x in common_nodes))
1652 return orig(ui, repo, nodelist, *args, **kwargs)
1652 return orig(ui, repo, nodelist, *args, **kwargs)
1653
1653
1654 extensions.wrapfunction(repair, 'strip', stripwrapper)
1654 extensions.wrapfunction(repair, 'strip', stripwrapper)
1655
1655
1656 def summaryhook(ui, repo):
1656 def summaryhook(ui, repo):
1657 if not os.path.exists(repo.vfs.join('histedit-state')):
1657 if not os.path.exists(repo.vfs.join('histedit-state')):
1658 return
1658 return
1659 state = histeditstate(repo)
1659 state = histeditstate(repo)
1660 state.read()
1660 state.read()
1661 if state.actions:
1661 if state.actions:
1662 # i18n: column positioning for "hg summary"
1662 # i18n: column positioning for "hg summary"
1663 ui.write(_('hist: %s (histedit --continue)\n') %
1663 ui.write(_('hist: %s (histedit --continue)\n') %
1664 (ui.label(_('%d remaining'), 'histedit.remaining') %
1664 (ui.label(_('%d remaining'), 'histedit.remaining') %
1665 len(state.actions)))
1665 len(state.actions)))
1666
1666
1667 def extsetup(ui):
1667 def extsetup(ui):
1668 cmdutil.summaryhooks.add('histedit', summaryhook)
1668 cmdutil.summaryhooks.add('histedit', summaryhook)
1669 cmdutil.unfinishedstates.append(
1669 cmdutil.unfinishedstates.append(
1670 ['histedit-state', False, True, _('histedit in progress'),
1670 ['histedit-state', False, True, _('histedit in progress'),
1671 _("use 'hg histedit --continue' or 'hg histedit --abort'")])
1671 _("use 'hg histedit --continue' or 'hg histedit --abort'")])
1672 cmdutil.afterresolvedstates.append(
1672 cmdutil.afterresolvedstates.append(
1673 ['histedit-state', _('hg histedit --continue')])
1673 ['histedit-state', _('hg histedit --continue')])
1674 if ui.configbool("experimental", "histeditng"):
1674 if ui.configbool("experimental", "histeditng"):
1675 globals()['base'] = action(['base', 'b'],
1675 globals()['base'] = action(['base', 'b'],
1676 _('checkout changeset and apply further changesets from there')
1676 _('checkout changeset and apply further changesets from there')
1677 )(base)
1677 )(base)
General Comments 0
You need to be logged in to leave comments. Login now