##// END OF EJS Templates
histedit: mark defaultrev option experimental
Matt Mackall -
r25824:8e77e833 default
parent child Browse files
Show More
@@ -1,1167 +1,1168 b''
1 1 # histedit.py - interactive history editing for mercurial
2 2 #
3 3 # Copyright 2009 Augie Fackler <raf@durin42.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7 """interactive history editing
8 8
9 9 With this extension installed, Mercurial gains one new command: histedit. Usage
10 10 is as follows, assuming the following history::
11 11
12 12 @ 3[tip] 7c2fd3b9020c 2009-04-27 18:04 -0500 durin42
13 13 | Add delta
14 14 |
15 15 o 2 030b686bedc4 2009-04-27 18:04 -0500 durin42
16 16 | Add gamma
17 17 |
18 18 o 1 c561b4e977df 2009-04-27 18:04 -0500 durin42
19 19 | Add beta
20 20 |
21 21 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
22 22 Add alpha
23 23
24 24 If you were to run ``hg histedit c561b4e977df``, you would see the following
25 25 file open in your editor::
26 26
27 27 pick c561b4e977df Add beta
28 28 pick 030b686bedc4 Add gamma
29 29 pick 7c2fd3b9020c Add delta
30 30
31 31 # Edit history between c561b4e977df and 7c2fd3b9020c
32 32 #
33 33 # Commits are listed from least to most recent
34 34 #
35 35 # Commands:
36 36 # p, pick = use commit
37 37 # e, edit = use commit, but stop for amending
38 38 # f, fold = use commit, but combine it with the one above
39 39 # r, roll = like fold, but discard this commit's description
40 40 # d, drop = remove commit from history
41 41 # m, mess = edit message without changing commit content
42 42 #
43 43
44 44 In this file, lines beginning with ``#`` are ignored. You must specify a rule
45 45 for each revision in your history. For example, if you had meant to add gamma
46 46 before beta, and then wanted to add delta in the same revision as beta, you
47 47 would reorganize the file to look like this::
48 48
49 49 pick 030b686bedc4 Add gamma
50 50 pick c561b4e977df Add beta
51 51 fold 7c2fd3b9020c Add delta
52 52
53 53 # Edit history between c561b4e977df and 7c2fd3b9020c
54 54 #
55 55 # Commits are listed from least to most recent
56 56 #
57 57 # Commands:
58 58 # p, pick = use commit
59 59 # e, edit = use commit, but stop for amending
60 60 # f, fold = use commit, but combine it with the one above
61 61 # r, roll = like fold, but discard this commit's description
62 62 # d, drop = remove commit from history
63 63 # m, mess = edit message without changing commit content
64 64 #
65 65
66 66 At which point you close the editor and ``histedit`` starts working. When you
67 67 specify a ``fold`` operation, ``histedit`` will open an editor when it folds
68 68 those revisions together, offering you a chance to clean up the commit message::
69 69
70 70 Add beta
71 71 ***
72 72 Add delta
73 73
74 74 Edit the commit message to your liking, then close the editor. For
75 75 this example, let's assume that the commit message was changed to
76 76 ``Add beta and delta.`` After histedit has run and had a chance to
77 77 remove any old or temporary revisions it needed, the history looks
78 78 like this::
79 79
80 80 @ 2[tip] 989b4d060121 2009-04-27 18:04 -0500 durin42
81 81 | Add beta and delta.
82 82 |
83 83 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
84 84 | Add gamma
85 85 |
86 86 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
87 87 Add alpha
88 88
89 89 Note that ``histedit`` does *not* remove any revisions (even its own temporary
90 90 ones) until after it has completed all the editing operations, so it will
91 91 probably perform several strip operations when it's done. For the above example,
92 92 it had to run strip twice. Strip can be slow depending on a variety of factors,
93 93 so you might need to be a little patient. You can choose to keep the original
94 94 revisions by passing the ``--keep`` flag.
95 95
96 96 The ``edit`` operation will drop you back to a command prompt,
97 97 allowing you to edit files freely, or even use ``hg record`` to commit
98 98 some changes as a separate commit. When you're done, any remaining
99 99 uncommitted changes will be committed as well. When done, run ``hg
100 100 histedit --continue`` to finish this step. You'll be prompted for a
101 101 new commit message, but the default commit message will be the
102 102 original message for the ``edit`` ed revision.
103 103
104 104 The ``message`` operation will give you a chance to revise a commit
105 105 message without changing the contents. It's a shortcut for doing
106 106 ``edit`` immediately followed by `hg histedit --continue``.
107 107
108 108 If ``histedit`` encounters a conflict when moving a revision (while
109 109 handling ``pick`` or ``fold``), it'll stop in a similar manner to
110 110 ``edit`` with the difference that it won't prompt you for a commit
111 111 message when done. If you decide at this point that you don't like how
112 112 much work it will be to rearrange history, or that you made a mistake,
113 113 you can use ``hg histedit --abort`` to abandon the new changes you
114 114 have made and return to the state before you attempted to edit your
115 115 history.
116 116
117 117 If we clone the histedit-ed example repository above and add four more
118 118 changes, such that we have the following history::
119 119
120 120 @ 6[tip] 038383181893 2009-04-27 18:04 -0500 stefan
121 121 | Add theta
122 122 |
123 123 o 5 140988835471 2009-04-27 18:04 -0500 stefan
124 124 | Add eta
125 125 |
126 126 o 4 122930637314 2009-04-27 18:04 -0500 stefan
127 127 | Add zeta
128 128 |
129 129 o 3 836302820282 2009-04-27 18:04 -0500 stefan
130 130 | Add epsilon
131 131 |
132 132 o 2 989b4d060121 2009-04-27 18:04 -0500 durin42
133 133 | Add beta and delta.
134 134 |
135 135 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
136 136 | Add gamma
137 137 |
138 138 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
139 139 Add alpha
140 140
141 141 If you run ``hg histedit --outgoing`` on the clone then it is the same
142 142 as running ``hg histedit 836302820282``. If you need plan to push to a
143 143 repository that Mercurial does not detect to be related to the source
144 144 repo, you can add a ``--force`` option.
145 145
146 146 Histedit rule lines are truncated to 80 characters by default. You
147 147 can customise this behaviour by setting a different length in your
148 148 configuration file::
149 149
150 150 [histedit]
151 151 linelen = 120 # truncate rule lines at 120 characters
152 152 """
153 153
154 154 try:
155 155 import cPickle as pickle
156 156 pickle.dump # import now
157 157 except ImportError:
158 158 import pickle
159 159 import errno
160 160 import os
161 161 import sys
162 162
163 163 from mercurial import cmdutil
164 164 from mercurial import discovery
165 165 from mercurial import error
166 166 from mercurial import changegroup
167 167 from mercurial import copies
168 168 from mercurial import context
169 169 from mercurial import exchange
170 170 from mercurial import extensions
171 171 from mercurial import hg
172 172 from mercurial import node
173 173 from mercurial import repair
174 174 from mercurial import scmutil
175 175 from mercurial import util
176 176 from mercurial import obsolete
177 177 from mercurial import merge as mergemod
178 178 from mercurial.lock import release
179 179 from mercurial.i18n import _
180 180
181 181 cmdtable = {}
182 182 command = cmdutil.command(cmdtable)
183 183
184 184 # Note for extension authors: ONLY specify testedwith = 'internal' for
185 185 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
186 186 # be specifying the version(s) of Mercurial they are tested with, or
187 187 # leave the attribute unspecified.
188 188 testedwith = 'internal'
189 189
190 190 # i18n: command names and abbreviations must remain untranslated
191 191 editcomment = _("""# Edit history between %s and %s
192 192 #
193 193 # Commits are listed from least to most recent
194 194 #
195 195 # Commands:
196 196 # p, pick = use commit
197 197 # e, edit = use commit, but stop for amending
198 198 # f, fold = use commit, but combine it with the one above
199 199 # r, roll = like fold, but discard this commit's description
200 200 # d, drop = remove commit from history
201 201 # m, mess = edit message without changing commit content
202 202 #
203 203 """)
204 204
205 205 class histeditstate(object):
206 206 def __init__(self, repo, parentctxnode=None, rules=None, keep=None,
207 207 topmost=None, replacements=None, lock=None, wlock=None):
208 208 self.repo = repo
209 209 self.rules = rules
210 210 self.keep = keep
211 211 self.topmost = topmost
212 212 self.parentctxnode = parentctxnode
213 213 self.lock = lock
214 214 self.wlock = wlock
215 215 self.backupfile = None
216 216 if replacements is None:
217 217 self.replacements = []
218 218 else:
219 219 self.replacements = replacements
220 220
221 221 def read(self):
222 222 """Load histedit state from disk and set fields appropriately."""
223 223 try:
224 224 fp = self.repo.vfs('histedit-state', 'r')
225 225 except IOError as err:
226 226 if err.errno != errno.ENOENT:
227 227 raise
228 228 raise util.Abort(_('no histedit in progress'))
229 229
230 230 try:
231 231 data = pickle.load(fp)
232 232 parentctxnode, rules, keep, topmost, replacements = data
233 233 backupfile = None
234 234 except pickle.UnpicklingError:
235 235 data = self._load()
236 236 parentctxnode, rules, keep, topmost, replacements, backupfile = data
237 237
238 238 self.parentctxnode = parentctxnode
239 239 self.rules = rules
240 240 self.keep = keep
241 241 self.topmost = topmost
242 242 self.replacements = replacements
243 243 self.backupfile = backupfile
244 244
245 245 def write(self):
246 246 fp = self.repo.vfs('histedit-state', 'w')
247 247 fp.write('v1\n')
248 248 fp.write('%s\n' % node.hex(self.parentctxnode))
249 249 fp.write('%s\n' % node.hex(self.topmost))
250 250 fp.write('%s\n' % self.keep)
251 251 fp.write('%d\n' % len(self.rules))
252 252 for rule in self.rules:
253 253 fp.write('%s\n' % rule[0]) # action
254 254 fp.write('%s\n' % rule[1]) # remainder
255 255 fp.write('%d\n' % len(self.replacements))
256 256 for replacement in self.replacements:
257 257 fp.write('%s%s\n' % (node.hex(replacement[0]), ''.join(node.hex(r)
258 258 for r in replacement[1])))
259 259 backupfile = self.backupfile
260 260 if not backupfile:
261 261 backupfile = ''
262 262 fp.write('%s\n' % backupfile)
263 263 fp.close()
264 264
265 265 def _load(self):
266 266 fp = self.repo.vfs('histedit-state', 'r')
267 267 lines = [l[:-1] for l in fp.readlines()]
268 268
269 269 index = 0
270 270 lines[index] # version number
271 271 index += 1
272 272
273 273 parentctxnode = node.bin(lines[index])
274 274 index += 1
275 275
276 276 topmost = node.bin(lines[index])
277 277 index += 1
278 278
279 279 keep = lines[index] == 'True'
280 280 index += 1
281 281
282 282 # Rules
283 283 rules = []
284 284 rulelen = int(lines[index])
285 285 index += 1
286 286 for i in xrange(rulelen):
287 287 ruleaction = lines[index]
288 288 index += 1
289 289 rule = lines[index]
290 290 index += 1
291 291 rules.append((ruleaction, rule))
292 292
293 293 # Replacements
294 294 replacements = []
295 295 replacementlen = int(lines[index])
296 296 index += 1
297 297 for i in xrange(replacementlen):
298 298 replacement = lines[index]
299 299 original = node.bin(replacement[:40])
300 300 succ = [node.bin(replacement[i:i + 40]) for i in
301 301 range(40, len(replacement), 40)]
302 302 replacements.append((original, succ))
303 303 index += 1
304 304
305 305 backupfile = lines[index]
306 306 index += 1
307 307
308 308 fp.close()
309 309
310 310 return parentctxnode, rules, keep, topmost, replacements, backupfile
311 311
312 312 def clear(self):
313 313 self.repo.vfs.unlink('histedit-state')
314 314
315 315 class histeditaction(object):
316 316 def __init__(self, state, node):
317 317 self.state = state
318 318 self.repo = state.repo
319 319 self.node = node
320 320
321 321 @classmethod
322 322 def fromrule(cls, state, rule):
323 323 """Parses the given rule, returning an instance of the histeditaction.
324 324 """
325 325 repo = state.repo
326 326 rulehash = rule.strip().split(' ', 1)[0]
327 327 try:
328 328 node = repo[rulehash].node()
329 329 except error.RepoError:
330 330 raise util.Abort(_('unknown changeset %s listed') % rulehash[:12])
331 331 return cls(state, node)
332 332
333 333 def run(self):
334 334 """Runs the action. The default behavior is simply apply the action's
335 335 rulectx onto the current parentctx."""
336 336 self.applychange()
337 337 self.continuedirty()
338 338 return self.continueclean()
339 339
340 340 def applychange(self):
341 341 """Applies the changes from this action's rulectx onto the current
342 342 parentctx, but does not commit them."""
343 343 repo = self.repo
344 344 rulectx = repo[self.node]
345 345 hg.update(repo, self.state.parentctxnode)
346 346 stats = applychanges(repo.ui, repo, rulectx, {})
347 347 if stats and stats[3] > 0:
348 348 raise error.InterventionRequired(_('Fix up the change and run '
349 349 'hg histedit --continue'))
350 350
351 351 def continuedirty(self):
352 352 """Continues the action when changes have been applied to the working
353 353 copy. The default behavior is to commit the dirty changes."""
354 354 repo = self.repo
355 355 rulectx = repo[self.node]
356 356
357 357 editor = self.commiteditor()
358 358 commit = commitfuncfor(repo, rulectx)
359 359
360 360 commit(text=rulectx.description(), user=rulectx.user(),
361 361 date=rulectx.date(), extra=rulectx.extra(), editor=editor)
362 362
363 363 def commiteditor(self):
364 364 """The editor to be used to edit the commit message."""
365 365 return False
366 366
367 367 def continueclean(self):
368 368 """Continues the action when the working copy is clean. The default
369 369 behavior is to accept the current commit as the new version of the
370 370 rulectx."""
371 371 ctx = self.repo['.']
372 372 if ctx.node() == self.state.parentctxnode:
373 373 self.repo.ui.warn(_('%s: empty changeset\n') %
374 374 node.short(self.node))
375 375 return ctx, [(self.node, tuple())]
376 376 if ctx.node() == self.node:
377 377 # Nothing changed
378 378 return ctx, []
379 379 return ctx, [(self.node, (ctx.node(),))]
380 380
381 381 def commitfuncfor(repo, src):
382 382 """Build a commit function for the replacement of <src>
383 383
384 384 This function ensure we apply the same treatment to all changesets.
385 385
386 386 - Add a 'histedit_source' entry in extra.
387 387
388 388 Note that fold has its own separated logic because its handling is a bit
389 389 different and not easily factored out of the fold method.
390 390 """
391 391 phasemin = src.phase()
392 392 def commitfunc(**kwargs):
393 393 phasebackup = repo.ui.backupconfig('phases', 'new-commit')
394 394 try:
395 395 repo.ui.setconfig('phases', 'new-commit', phasemin,
396 396 'histedit')
397 397 extra = kwargs.get('extra', {}).copy()
398 398 extra['histedit_source'] = src.hex()
399 399 kwargs['extra'] = extra
400 400 return repo.commit(**kwargs)
401 401 finally:
402 402 repo.ui.restoreconfig(phasebackup)
403 403 return commitfunc
404 404
405 405 def applychanges(ui, repo, ctx, opts):
406 406 """Merge changeset from ctx (only) in the current working directory"""
407 407 wcpar = repo.dirstate.parents()[0]
408 408 if ctx.p1().node() == wcpar:
409 409 # edition ar "in place" we do not need to make any merge,
410 410 # just applies changes on parent for edition
411 411 cmdutil.revert(ui, repo, ctx, (wcpar, node.nullid), all=True)
412 412 stats = None
413 413 else:
414 414 try:
415 415 # ui.forcemerge is an internal variable, do not document
416 416 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
417 417 'histedit')
418 418 stats = mergemod.graft(repo, ctx, ctx.p1(), ['local', 'histedit'])
419 419 finally:
420 420 repo.ui.setconfig('ui', 'forcemerge', '', 'histedit')
421 421 return stats
422 422
423 423 def collapse(repo, first, last, commitopts, skipprompt=False):
424 424 """collapse the set of revisions from first to last as new one.
425 425
426 426 Expected commit options are:
427 427 - message
428 428 - date
429 429 - username
430 430 Commit message is edited in all cases.
431 431
432 432 This function works in memory."""
433 433 ctxs = list(repo.set('%d::%d', first, last))
434 434 if not ctxs:
435 435 return None
436 436 for c in ctxs:
437 437 if not c.mutable():
438 438 raise util.Abort(
439 439 _("cannot fold into public change %s") % node.short(c.node()))
440 440 base = first.parents()[0]
441 441
442 442 # commit a new version of the old changeset, including the update
443 443 # collect all files which might be affected
444 444 files = set()
445 445 for ctx in ctxs:
446 446 files.update(ctx.files())
447 447
448 448 # Recompute copies (avoid recording a -> b -> a)
449 449 copied = copies.pathcopies(base, last)
450 450
451 451 # prune files which were reverted by the updates
452 452 def samefile(f):
453 453 if f in last.manifest():
454 454 a = last.filectx(f)
455 455 if f in base.manifest():
456 456 b = base.filectx(f)
457 457 return (a.data() == b.data()
458 458 and a.flags() == b.flags())
459 459 else:
460 460 return False
461 461 else:
462 462 return f not in base.manifest()
463 463 files = [f for f in files if not samefile(f)]
464 464 # commit version of these files as defined by head
465 465 headmf = last.manifest()
466 466 def filectxfn(repo, ctx, path):
467 467 if path in headmf:
468 468 fctx = last[path]
469 469 flags = fctx.flags()
470 470 mctx = context.memfilectx(repo,
471 471 fctx.path(), fctx.data(),
472 472 islink='l' in flags,
473 473 isexec='x' in flags,
474 474 copied=copied.get(path))
475 475 return mctx
476 476 return None
477 477
478 478 if commitopts.get('message'):
479 479 message = commitopts['message']
480 480 else:
481 481 message = first.description()
482 482 user = commitopts.get('user')
483 483 date = commitopts.get('date')
484 484 extra = commitopts.get('extra')
485 485
486 486 parents = (first.p1().node(), first.p2().node())
487 487 editor = None
488 488 if not skipprompt:
489 489 editor = cmdutil.getcommiteditor(edit=True, editform='histedit.fold')
490 490 new = context.memctx(repo,
491 491 parents=parents,
492 492 text=message,
493 493 files=files,
494 494 filectxfn=filectxfn,
495 495 user=user,
496 496 date=date,
497 497 extra=extra,
498 498 editor=editor)
499 499 return repo.commitctx(new)
500 500
501 501 class pick(histeditaction):
502 502 def run(self):
503 503 rulectx = self.repo[self.node]
504 504 if rulectx.parents()[0].node() == self.state.parentctxnode:
505 505 self.repo.ui.debug('node %s unchanged\n' % node.short(self.node))
506 506 return rulectx, []
507 507
508 508 return super(pick, self).run()
509 509
510 510 class edit(histeditaction):
511 511 def run(self):
512 512 repo = self.repo
513 513 rulectx = repo[self.node]
514 514 hg.update(repo, self.state.parentctxnode)
515 515 applychanges(repo.ui, repo, rulectx, {})
516 516 raise error.InterventionRequired(
517 517 _('Make changes as needed, you may commit or record as needed '
518 518 'now.\nWhen you are finished, run hg histedit --continue to '
519 519 'resume.'))
520 520
521 521 def commiteditor(self):
522 522 return cmdutil.getcommiteditor(edit=True, editform='histedit.edit')
523 523
524 524 class fold(histeditaction):
525 525 def continuedirty(self):
526 526 repo = self.repo
527 527 rulectx = repo[self.node]
528 528
529 529 commit = commitfuncfor(repo, rulectx)
530 530 commit(text='fold-temp-revision %s' % node.short(self.node),
531 531 user=rulectx.user(), date=rulectx.date(),
532 532 extra=rulectx.extra())
533 533
534 534 def continueclean(self):
535 535 repo = self.repo
536 536 ctx = repo['.']
537 537 rulectx = repo[self.node]
538 538 parentctxnode = self.state.parentctxnode
539 539 if ctx.node() == parentctxnode:
540 540 repo.ui.warn(_('%s: empty changeset\n') %
541 541 node.short(self.node))
542 542 return ctx, [(self.node, (parentctxnode,))]
543 543
544 544 parentctx = repo[parentctxnode]
545 545 newcommits = set(c.node() for c in repo.set('(%d::. - %d)', parentctx,
546 546 parentctx))
547 547 if not newcommits:
548 548 repo.ui.warn(_('%s: cannot fold - working copy is not a '
549 549 'descendant of previous commit %s\n') %
550 550 (node.short(self.node), node.short(parentctxnode)))
551 551 return ctx, [(self.node, (ctx.node(),))]
552 552
553 553 middlecommits = newcommits.copy()
554 554 middlecommits.discard(ctx.node())
555 555
556 556 return self.finishfold(repo.ui, repo, parentctx, rulectx, ctx.node(),
557 557 middlecommits)
558 558
559 559 def skipprompt(self):
560 560 return False
561 561
562 562 def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges):
563 563 parent = ctx.parents()[0].node()
564 564 hg.update(repo, parent)
565 565 ### prepare new commit data
566 566 commitopts = {}
567 567 commitopts['user'] = ctx.user()
568 568 # commit message
569 569 if self.skipprompt():
570 570 newmessage = ctx.description()
571 571 else:
572 572 newmessage = '\n***\n'.join(
573 573 [ctx.description()] +
574 574 [repo[r].description() for r in internalchanges] +
575 575 [oldctx.description()]) + '\n'
576 576 commitopts['message'] = newmessage
577 577 # date
578 578 commitopts['date'] = max(ctx.date(), oldctx.date())
579 579 extra = ctx.extra().copy()
580 580 # histedit_source
581 581 # note: ctx is likely a temporary commit but that the best we can do
582 582 # here. This is sufficient to solve issue3681 anyway.
583 583 extra['histedit_source'] = '%s,%s' % (ctx.hex(), oldctx.hex())
584 584 commitopts['extra'] = extra
585 585 phasebackup = repo.ui.backupconfig('phases', 'new-commit')
586 586 try:
587 587 phasemin = max(ctx.phase(), oldctx.phase())
588 588 repo.ui.setconfig('phases', 'new-commit', phasemin, 'histedit')
589 589 n = collapse(repo, ctx, repo[newnode], commitopts,
590 590 skipprompt=self.skipprompt())
591 591 finally:
592 592 repo.ui.restoreconfig(phasebackup)
593 593 if n is None:
594 594 return ctx, []
595 595 hg.update(repo, n)
596 596 replacements = [(oldctx.node(), (newnode,)),
597 597 (ctx.node(), (n,)),
598 598 (newnode, (n,)),
599 599 ]
600 600 for ich in internalchanges:
601 601 replacements.append((ich, (n,)))
602 602 return repo[n], replacements
603 603
604 604 class rollup(fold):
605 605 def skipprompt(self):
606 606 return True
607 607
608 608 class drop(histeditaction):
609 609 def run(self):
610 610 parentctx = self.repo[self.state.parentctxnode]
611 611 return parentctx, [(self.node, tuple())]
612 612
613 613 class message(histeditaction):
614 614 def commiteditor(self):
615 615 return cmdutil.getcommiteditor(edit=True, editform='histedit.mess')
616 616
617 617 def findoutgoing(ui, repo, remote=None, force=False, opts={}):
618 618 """utility function to find the first outgoing changeset
619 619
620 620 Used by initialisation code"""
621 621 dest = ui.expandpath(remote or 'default-push', remote or 'default')
622 622 dest, revs = hg.parseurl(dest, None)[:2]
623 623 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
624 624
625 625 revs, checkout = hg.addbranchrevs(repo, repo, revs, None)
626 626 other = hg.peer(repo, opts, dest)
627 627
628 628 if revs:
629 629 revs = [repo.lookup(rev) for rev in revs]
630 630
631 631 outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force)
632 632 if not outgoing.missing:
633 633 raise util.Abort(_('no outgoing ancestors'))
634 634 roots = list(repo.revs("roots(%ln)", outgoing.missing))
635 635 if 1 < len(roots):
636 636 msg = _('there are ambiguous outgoing revisions')
637 637 hint = _('see "hg help histedit" for more detail')
638 638 raise util.Abort(msg, hint=hint)
639 639 return repo.lookup(roots[0])
640 640
641 641 actiontable = {'p': pick,
642 642 'pick': pick,
643 643 'e': edit,
644 644 'edit': edit,
645 645 'f': fold,
646 646 'fold': fold,
647 647 'r': rollup,
648 648 'roll': rollup,
649 649 'd': drop,
650 650 'drop': drop,
651 651 'm': message,
652 652 'mess': message,
653 653 }
654 654
655 655 @command('histedit',
656 656 [('', 'commands', '',
657 657 _('read history edits from the specified file'), _('FILE')),
658 658 ('c', 'continue', False, _('continue an edit already in progress')),
659 659 ('', 'edit-plan', False, _('edit remaining actions list')),
660 660 ('k', 'keep', False,
661 661 _("don't strip old nodes after edit is complete")),
662 662 ('', 'abort', False, _('abort an edit in progress')),
663 663 ('o', 'outgoing', False, _('changesets not found in destination')),
664 664 ('f', 'force', False,
665 665 _('force outgoing even for unrelated repositories')),
666 666 ('r', 'rev', [], _('first revision to be edited'), _('REV'))],
667 667 _("ANCESTOR | --outgoing [URL]"))
668 668 def histedit(ui, repo, *freeargs, **opts):
669 669 """interactively edit changeset history
670 670
671 671 This command edits changesets between ANCESTOR and the parent of
672 672 the working directory.
673 673
674 674 With --outgoing, this edits changesets not found in the
675 675 destination repository. If URL of the destination is omitted, the
676 676 'default-push' (or 'default') path will be used.
677 677
678 678 For safety, this command is aborted, also if there are ambiguous
679 679 outgoing revisions which may confuse users: for example, there are
680 680 multiple branches containing outgoing revisions.
681 681
682 682 Use "min(outgoing() and ::.)" or similar revset specification
683 683 instead of --outgoing to specify edit target revision exactly in
684 684 such ambiguous situation. See :hg:`help revsets` for detail about
685 685 selecting revisions.
686 686
687 687 Returns 0 on success, 1 if user intervention is required (not only
688 688 for intentional "edit" command, but also for resolving unexpected
689 689 conflicts).
690 690 """
691 691 state = histeditstate(repo)
692 692 try:
693 693 state.wlock = repo.wlock()
694 694 state.lock = repo.lock()
695 695 _histedit(ui, repo, state, *freeargs, **opts)
696 696 finally:
697 697 release(state.lock, state.wlock)
698 698
699 699 def _histedit(ui, repo, state, *freeargs, **opts):
700 700 # TODO only abort if we try and histedit mq patches, not just
701 701 # blanket if mq patches are applied somewhere
702 702 mq = getattr(repo, 'mq', None)
703 703 if mq and mq.applied:
704 704 raise util.Abort(_('source has mq patches applied'))
705 705
706 706 # basic argument incompatibility processing
707 707 outg = opts.get('outgoing')
708 708 cont = opts.get('continue')
709 709 editplan = opts.get('edit_plan')
710 710 abort = opts.get('abort')
711 711 force = opts.get('force')
712 712 rules = opts.get('commands', '')
713 713 revs = opts.get('rev', [])
714 714 goal = 'new' # This invocation goal, in new, continue, abort
715 715 if force and not outg:
716 716 raise util.Abort(_('--force only allowed with --outgoing'))
717 717 if cont:
718 718 if any((outg, abort, revs, freeargs, rules, editplan)):
719 719 raise util.Abort(_('no arguments allowed with --continue'))
720 720 goal = 'continue'
721 721 elif abort:
722 722 if any((outg, revs, freeargs, rules, editplan)):
723 723 raise util.Abort(_('no arguments allowed with --abort'))
724 724 goal = 'abort'
725 725 elif editplan:
726 726 if any((outg, revs, freeargs)):
727 727 raise util.Abort(_('only --commands argument allowed with '
728 728 '--edit-plan'))
729 729 goal = 'edit-plan'
730 730 else:
731 731 if os.path.exists(os.path.join(repo.path, 'histedit-state')):
732 732 raise util.Abort(_('history edit already in progress, try '
733 733 '--continue or --abort'))
734 734 if outg:
735 735 if revs:
736 736 raise util.Abort(_('no revisions allowed with --outgoing'))
737 737 if len(freeargs) > 1:
738 738 raise util.Abort(
739 739 _('only one repo argument allowed with --outgoing'))
740 740 else:
741 741 revs.extend(freeargs)
742 742 if len(revs) == 0:
743 # experimental config: histedit.defaultrev
743 744 histeditdefault = ui.config('histedit', 'defaultrev')
744 745 if histeditdefault:
745 746 revs.append(histeditdefault)
746 747 if len(revs) != 1:
747 748 raise util.Abort(
748 749 _('histedit requires exactly one ancestor revision'))
749 750
750 751
751 752 replacements = []
752 753 state.keep = opts.get('keep', False)
753 754 supportsmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
754 755
755 756 # rebuild state
756 757 if goal == 'continue':
757 758 state.read()
758 759 state = bootstrapcontinue(ui, state, opts)
759 760 elif goal == 'edit-plan':
760 761 state.read()
761 762 if not rules:
762 763 comment = editcomment % (node.short(state.parentctxnode),
763 764 node.short(state.topmost))
764 765 rules = ruleeditor(repo, ui, state.rules, comment)
765 766 else:
766 767 if rules == '-':
767 768 f = sys.stdin
768 769 else:
769 770 f = open(rules)
770 771 rules = f.read()
771 772 f.close()
772 773 rules = [l for l in (r.strip() for r in rules.splitlines())
773 774 if l and not l.startswith('#')]
774 775 rules = verifyrules(rules, repo, [repo[c] for [_a, c] in state.rules])
775 776 state.rules = rules
776 777 state.write()
777 778 return
778 779 elif goal == 'abort':
779 780 state.read()
780 781 mapping, tmpnodes, leafs, _ntm = processreplacement(state)
781 782 ui.debug('restore wc to old parent %s\n' % node.short(state.topmost))
782 783
783 784 # Recover our old commits if necessary
784 785 if not state.topmost in repo and state.backupfile:
785 786 backupfile = repo.join(state.backupfile)
786 787 f = hg.openpath(ui, backupfile)
787 788 gen = exchange.readbundle(ui, f, backupfile)
788 789 changegroup.addchangegroup(repo, gen, 'histedit',
789 790 'bundle:' + backupfile)
790 791 os.remove(backupfile)
791 792
792 793 # check whether we should update away
793 794 parentnodes = [c.node() for c in repo[None].parents()]
794 795 for n in leafs | set([state.parentctxnode]):
795 796 if n in parentnodes:
796 797 hg.clean(repo, state.topmost)
797 798 break
798 799 else:
799 800 pass
800 801 if supportsmarkers:
801 802 obsolete.createmarkers(repo,
802 803 ((repo[t],()) for t in sorted(tmpnodes)))
803 804 obsolete.createmarkers(repo, ((repo[t],()) for t in sorted(leafs)))
804 805 else:
805 806 cleanupnode(ui, repo, 'created', tmpnodes)
806 807 cleanupnode(ui, repo, 'temp', leafs)
807 808 state.clear()
808 809 return
809 810 else:
810 811 cmdutil.checkunfinished(repo)
811 812 cmdutil.bailifchanged(repo)
812 813
813 814 topmost, empty = repo.dirstate.parents()
814 815 if outg:
815 816 if freeargs:
816 817 remote = freeargs[0]
817 818 else:
818 819 remote = None
819 820 root = findoutgoing(ui, repo, remote, force, opts)
820 821 else:
821 822 rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs)))
822 823 if len(rr) != 1:
823 824 raise util.Abort(_('The specified revisions must have '
824 825 'exactly one common root'))
825 826 root = rr[0].node()
826 827
827 828 revs = between(repo, root, topmost, state.keep)
828 829 if not revs:
829 830 raise util.Abort(_('%s is not an ancestor of working directory') %
830 831 node.short(root))
831 832
832 833 ctxs = [repo[r] for r in revs]
833 834 if not rules:
834 835 comment = editcomment % (node.short(root), node.short(topmost))
835 836 rules = ruleeditor(repo, ui, [['pick', c] for c in ctxs], comment)
836 837 else:
837 838 if rules == '-':
838 839 f = sys.stdin
839 840 else:
840 841 f = open(rules)
841 842 rules = f.read()
842 843 f.close()
843 844 rules = [l for l in (r.strip() for r in rules.splitlines())
844 845 if l and not l.startswith('#')]
845 846 rules = verifyrules(rules, repo, ctxs)
846 847
847 848 parentctxnode = repo[root].parents()[0].node()
848 849
849 850 state.parentctxnode = parentctxnode
850 851 state.rules = rules
851 852 state.topmost = topmost
852 853 state.replacements = replacements
853 854
854 855 # Create a backup so we can always abort completely.
855 856 backupfile = None
856 857 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
857 858 backupfile = repair._bundle(repo, [parentctxnode], [topmost], root,
858 859 'histedit')
859 860 state.backupfile = backupfile
860 861
861 862 while state.rules:
862 863 state.write()
863 864 action, ha = state.rules.pop(0)
864 865 ui.debug('histedit: processing %s %s\n' % (action, ha[:12]))
865 866 actobj = actiontable[action].fromrule(state, ha)
866 867 parentctx, replacement_ = actobj.run()
867 868 state.parentctxnode = parentctx.node()
868 869 state.replacements.extend(replacement_)
869 870 state.write()
870 871
871 872 hg.update(repo, state.parentctxnode)
872 873
873 874 mapping, tmpnodes, created, ntm = processreplacement(state)
874 875 if mapping:
875 876 for prec, succs in mapping.iteritems():
876 877 if not succs:
877 878 ui.debug('histedit: %s is dropped\n' % node.short(prec))
878 879 else:
879 880 ui.debug('histedit: %s is replaced by %s\n' % (
880 881 node.short(prec), node.short(succs[0])))
881 882 if len(succs) > 1:
882 883 m = 'histedit: %s'
883 884 for n in succs[1:]:
884 885 ui.debug(m % node.short(n))
885 886
886 887 if not state.keep:
887 888 if mapping:
888 889 movebookmarks(ui, repo, mapping, state.topmost, ntm)
889 890 # TODO update mq state
890 891 if supportsmarkers:
891 892 markers = []
892 893 # sort by revision number because it sound "right"
893 894 for prec in sorted(mapping, key=repo.changelog.rev):
894 895 succs = mapping[prec]
895 896 markers.append((repo[prec],
896 897 tuple(repo[s] for s in succs)))
897 898 if markers:
898 899 obsolete.createmarkers(repo, markers)
899 900 else:
900 901 cleanupnode(ui, repo, 'replaced', mapping)
901 902 if supportsmarkers:
902 903 obsolete.createmarkers(repo, ((repo[t],()) for t in sorted(tmpnodes)))
903 904 else:
904 905 cleanupnode(ui, repo, 'temp', tmpnodes)
905 906 state.clear()
906 907 if os.path.exists(repo.sjoin('undo')):
907 908 os.unlink(repo.sjoin('undo'))
908 909
909 910 def bootstrapcontinue(ui, state, opts):
910 911 repo = state.repo
911 912 if state.rules:
912 913 action, currentnode = state.rules.pop(0)
913 914
914 915 actobj = actiontable[action].fromrule(state, currentnode)
915 916
916 917 s = repo.status()
917 918 if s.modified or s.added or s.removed or s.deleted:
918 919 actobj.continuedirty()
919 920 s = repo.status()
920 921 if s.modified or s.added or s.removed or s.deleted:
921 922 raise util.Abort(_("working copy still dirty"))
922 923
923 924 parentctx, replacements = actobj.continueclean()
924 925
925 926 state.parentctxnode = parentctx.node()
926 927 state.replacements.extend(replacements)
927 928
928 929 return state
929 930
930 931 def between(repo, old, new, keep):
931 932 """select and validate the set of revision to edit
932 933
933 934 When keep is false, the specified set can't have children."""
934 935 ctxs = list(repo.set('%n::%n', old, new))
935 936 if ctxs and not keep:
936 937 if (not obsolete.isenabled(repo, obsolete.allowunstableopt) and
937 938 repo.revs('(%ld::) - (%ld)', ctxs, ctxs)):
938 939 raise util.Abort(_('cannot edit history that would orphan nodes'))
939 940 if repo.revs('(%ld) and merge()', ctxs):
940 941 raise util.Abort(_('cannot edit history that contains merges'))
941 942 root = ctxs[0] # list is already sorted by repo.set
942 943 if not root.mutable():
943 944 raise util.Abort(_('cannot edit public changeset: %s') % root,
944 945 hint=_('see "hg help phases" for details'))
945 946 return [c.node() for c in ctxs]
946 947
947 948 def makedesc(repo, action, rev):
948 949 """build a initial action line for a ctx
949 950
950 951 line are in the form:
951 952
952 953 <action> <hash> <rev> <summary>
953 954 """
954 955 ctx = repo[rev]
955 956 summary = ''
956 957 if ctx.description():
957 958 summary = ctx.description().splitlines()[0]
958 959 line = '%s %s %d %s' % (action, ctx, ctx.rev(), summary)
959 960 # trim to 80 columns so it's not stupidly wide in my editor
960 961 maxlen = repo.ui.configint('histedit', 'linelen', default=80)
961 962 maxlen = max(maxlen, 22) # avoid truncating hash
962 963 return util.ellipsis(line, maxlen)
963 964
964 965 def ruleeditor(repo, ui, rules, editcomment=""):
965 966 """open an editor to edit rules
966 967
967 968 rules are in the format [ [act, ctx], ...] like in state.rules
968 969 """
969 970 rules = '\n'.join([makedesc(repo, act, rev) for [act, rev] in rules])
970 971 rules += '\n\n'
971 972 rules += editcomment
972 973 rules = ui.edit(rules, ui.username())
973 974
974 975 # Save edit rules in .hg/histedit-last-edit.txt in case
975 976 # the user needs to ask for help after something
976 977 # surprising happens.
977 978 f = open(repo.join('histedit-last-edit.txt'), 'w')
978 979 f.write(rules)
979 980 f.close()
980 981
981 982 return rules
982 983
983 984 def verifyrules(rules, repo, ctxs):
984 985 """Verify that there exists exactly one edit rule per given changeset.
985 986
986 987 Will abort if there are to many or too few rules, a malformed rule,
987 988 or a rule on a changeset outside of the user-given range.
988 989 """
989 990 parsed = []
990 991 expected = set(c.hex() for c in ctxs)
991 992 seen = set()
992 993 for r in rules:
993 994 if ' ' not in r:
994 995 raise util.Abort(_('malformed line "%s"') % r)
995 996 action, rest = r.split(' ', 1)
996 997 ha = rest.strip().split(' ', 1)[0]
997 998 try:
998 999 ha = repo[ha].hex()
999 1000 except error.RepoError:
1000 1001 raise util.Abort(_('unknown changeset %s listed') % ha[:12])
1001 1002 if ha not in expected:
1002 1003 raise util.Abort(
1003 1004 _('may not use changesets other than the ones listed'))
1004 1005 if ha in seen:
1005 1006 raise util.Abort(_('duplicated command for changeset %s') %
1006 1007 ha[:12])
1007 1008 seen.add(ha)
1008 1009 if action not in actiontable:
1009 1010 raise util.Abort(_('unknown action "%s"') % action)
1010 1011 parsed.append([action, ha])
1011 1012 missing = sorted(expected - seen) # sort to stabilize output
1012 1013 if missing:
1013 1014 raise util.Abort(_('missing rules for changeset %s') %
1014 1015 missing[0][:12],
1015 1016 hint=_('do you want to use the drop action?'))
1016 1017 return parsed
1017 1018
1018 1019 def processreplacement(state):
1019 1020 """process the list of replacements to return
1020 1021
1021 1022 1) the final mapping between original and created nodes
1022 1023 2) the list of temporary node created by histedit
1023 1024 3) the list of new commit created by histedit"""
1024 1025 replacements = state.replacements
1025 1026 allsuccs = set()
1026 1027 replaced = set()
1027 1028 fullmapping = {}
1028 1029 # initialise basic set
1029 1030 # fullmapping record all operation recorded in replacement
1030 1031 for rep in replacements:
1031 1032 allsuccs.update(rep[1])
1032 1033 replaced.add(rep[0])
1033 1034 fullmapping.setdefault(rep[0], set()).update(rep[1])
1034 1035 new = allsuccs - replaced
1035 1036 tmpnodes = allsuccs & replaced
1036 1037 # Reduce content fullmapping into direct relation between original nodes
1037 1038 # and final node created during history edition
1038 1039 # Dropped changeset are replaced by an empty list
1039 1040 toproceed = set(fullmapping)
1040 1041 final = {}
1041 1042 while toproceed:
1042 1043 for x in list(toproceed):
1043 1044 succs = fullmapping[x]
1044 1045 for s in list(succs):
1045 1046 if s in toproceed:
1046 1047 # non final node with unknown closure
1047 1048 # We can't process this now
1048 1049 break
1049 1050 elif s in final:
1050 1051 # non final node, replace with closure
1051 1052 succs.remove(s)
1052 1053 succs.update(final[s])
1053 1054 else:
1054 1055 final[x] = succs
1055 1056 toproceed.remove(x)
1056 1057 # remove tmpnodes from final mapping
1057 1058 for n in tmpnodes:
1058 1059 del final[n]
1059 1060 # we expect all changes involved in final to exist in the repo
1060 1061 # turn `final` into list (topologically sorted)
1061 1062 nm = state.repo.changelog.nodemap
1062 1063 for prec, succs in final.items():
1063 1064 final[prec] = sorted(succs, key=nm.get)
1064 1065
1065 1066 # computed topmost element (necessary for bookmark)
1066 1067 if new:
1067 1068 newtopmost = sorted(new, key=state.repo.changelog.rev)[-1]
1068 1069 elif not final:
1069 1070 # Nothing rewritten at all. we won't need `newtopmost`
1070 1071 # It is the same as `oldtopmost` and `processreplacement` know it
1071 1072 newtopmost = None
1072 1073 else:
1073 1074 # every body died. The newtopmost is the parent of the root.
1074 1075 r = state.repo.changelog.rev
1075 1076 newtopmost = state.repo[sorted(final, key=r)[0]].p1().node()
1076 1077
1077 1078 return final, tmpnodes, new, newtopmost
1078 1079
1079 1080 def movebookmarks(ui, repo, mapping, oldtopmost, newtopmost):
1080 1081 """Move bookmark from old to newly created node"""
1081 1082 if not mapping:
1082 1083 # if nothing got rewritten there is not purpose for this function
1083 1084 return
1084 1085 moves = []
1085 1086 for bk, old in sorted(repo._bookmarks.iteritems()):
1086 1087 if old == oldtopmost:
1087 1088 # special case ensure bookmark stay on tip.
1088 1089 #
1089 1090 # This is arguably a feature and we may only want that for the
1090 1091 # active bookmark. But the behavior is kept compatible with the old
1091 1092 # version for now.
1092 1093 moves.append((bk, newtopmost))
1093 1094 continue
1094 1095 base = old
1095 1096 new = mapping.get(base, None)
1096 1097 if new is None:
1097 1098 continue
1098 1099 while not new:
1099 1100 # base is killed, trying with parent
1100 1101 base = repo[base].p1().node()
1101 1102 new = mapping.get(base, (base,))
1102 1103 # nothing to move
1103 1104 moves.append((bk, new[-1]))
1104 1105 if moves:
1105 1106 marks = repo._bookmarks
1106 1107 for mark, new in moves:
1107 1108 old = marks[mark]
1108 1109 ui.note(_('histedit: moving bookmarks %s from %s to %s\n')
1109 1110 % (mark, node.short(old), node.short(new)))
1110 1111 marks[mark] = new
1111 1112 marks.write()
1112 1113
1113 1114 def cleanupnode(ui, repo, name, nodes):
1114 1115 """strip a group of nodes from the repository
1115 1116
1116 1117 The set of node to strip may contains unknown nodes."""
1117 1118 ui.debug('should strip %s nodes %s\n' %
1118 1119 (name, ', '.join([node.short(n) for n in nodes])))
1119 1120 lock = None
1120 1121 try:
1121 1122 lock = repo.lock()
1122 1123 # Find all node that need to be stripped
1123 1124 # (we hg %lr instead of %ln to silently ignore unknown item
1124 1125 nm = repo.changelog.nodemap
1125 1126 nodes = sorted(n for n in nodes if n in nm)
1126 1127 roots = [c.node() for c in repo.set("roots(%ln)", nodes)]
1127 1128 for c in roots:
1128 1129 # We should process node in reverse order to strip tip most first.
1129 1130 # but this trigger a bug in changegroup hook.
1130 1131 # This would reduce bundle overhead
1131 1132 repair.strip(ui, repo, c)
1132 1133 finally:
1133 1134 release(lock)
1134 1135
1135 1136 def stripwrapper(orig, ui, repo, nodelist, *args, **kwargs):
1136 1137 if isinstance(nodelist, str):
1137 1138 nodelist = [nodelist]
1138 1139 if os.path.exists(os.path.join(repo.path, 'histedit-state')):
1139 1140 state = histeditstate(repo)
1140 1141 state.read()
1141 1142 histedit_nodes = set([repo[rulehash].node() for (action, rulehash)
1142 1143 in state.rules if rulehash in repo])
1143 1144 strip_nodes = set([repo[n].node() for n in nodelist])
1144 1145 common_nodes = histedit_nodes & strip_nodes
1145 1146 if common_nodes:
1146 1147 raise util.Abort(_("histedit in progress, can't strip %s")
1147 1148 % ', '.join(node.short(x) for x in common_nodes))
1148 1149 return orig(ui, repo, nodelist, *args, **kwargs)
1149 1150
1150 1151 extensions.wrapfunction(repair, 'strip', stripwrapper)
1151 1152
1152 1153 def summaryhook(ui, repo):
1153 1154 if not os.path.exists(repo.join('histedit-state')):
1154 1155 return
1155 1156 state = histeditstate(repo)
1156 1157 state.read()
1157 1158 if state.rules:
1158 1159 # i18n: column positioning for "hg summary"
1159 1160 ui.write(_('hist: %s (histedit --continue)\n') %
1160 1161 (ui.label(_('%d remaining'), 'histedit.remaining') %
1161 1162 len(state.rules)))
1162 1163
1163 1164 def extsetup(ui):
1164 1165 cmdutil.summaryhooks.add('histedit', summaryhook)
1165 1166 cmdutil.unfinishedstates.append(
1166 1167 ['histedit-state', False, True, _('histedit in progress'),
1167 1168 _("use 'hg histedit --continue' or 'hg histedit --abort'")])
General Comments 0
You need to be logged in to leave comments. Login now