Debian Codegraph @

hgext/histedit.py

raw
1 # histedit.py - interactive history editing for mercurial
2 #
3 # Copyright 2009 Augie Fackler <[email protected]>
4 #
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.
7 """interactive history editing
8
9 With this extension installed, Mercurial gains one new command: histedit. Usage
10 is as follows, assuming the following history::
11
12 @ 3[tip] 7c2fd3b9020c 2009-04-27 18:04 -0500 durin42
13 | Add delta
14 |
15 o 2 030b686bedc4 2009-04-27 18:04 -0500 durin42
16 | Add gamma
17 |
18 o 1 c561b4e977df 2009-04-27 18:04 -0500 durin42
19 | Add beta
20 |
21 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
22 Add alpha
23
24 If you were to run ``hg histedit c561b4e977df``, you would see the following
25 file open in your editor::
26
27 pick c561b4e977df Add beta
28 pick 030b686bedc4 Add gamma
29 pick 7c2fd3b9020c Add delta
30
31 # Edit history between c561b4e977df and 7c2fd3b9020c
32 #
33 # Commits are listed from least to most recent
34 #
35 # Commands:
36 # p, pick = use commit
37 # e, edit = use commit, but allow edits before making new commit
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
40 # d, drop = remove commit from history
41 # m, mess = edit commit message without changing commit content
42 # b, base = checkout changeset and apply further changesets from there
43 #
44
45 In this file, lines beginning with ``#`` are ignored. You must specify a rule
46 for each revision in your history. For example, if you had meant to add gamma
47 before beta, and then wanted to add delta in the same revision as beta, you
48 would reorganize the file to look like this::
49
50 pick 030b686bedc4 Add gamma
51 pick c561b4e977df Add beta
52 fold 7c2fd3b9020c Add delta
53
54 # Edit history between c561b4e977df and 7c2fd3b9020c
55 #
56 # Commits are listed from least to most recent
57 #
58 # Commands:
59 # p, pick = use commit
60 # e, edit = use commit, but allow edits before making new commit
61 # f, fold = use commit, but combine it with the one above
62 # r, roll = like fold, but discard this commit's description and date
63 # d, drop = remove commit from history
64 # m, mess = edit commit message without changing commit content
65 # b, base = checkout changeset and apply further changesets from there
66 #
67
68 At which point you close the editor and ``histedit`` starts working. When you
69 specify a ``fold`` operation, ``histedit`` will open an editor when it folds
70 those revisions together, offering you a chance to clean up the commit message::
71
72 Add beta
73 ***
74 Add delta
75
76 Edit the commit message to your liking, then close the editor. The date used
77 for the commit will be the later of the two commits' dates. For this example,
78 let's assume that the commit message was changed to ``Add beta and delta.``
79 After histedit has run and had a chance to remove any old or temporary
80 revisions it needed, the history looks like this::
81
82 @ 2[tip] 989b4d060121 2009-04-27 18:04 -0500 durin42
83 | Add beta and delta.
84 |
85 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
86 | Add gamma
87 |
88 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
89 Add alpha
90
91 Note that ``histedit`` does *not* remove any revisions (even its own temporary
92 ones) until after it has completed all the editing operations, so it will
93 probably perform several strip operations when it's done. For the above example,
94 it had to run strip twice. Strip can be slow depending on a variety of factors,
95 so you might need to be a little patient. You can choose to keep the original
96 revisions by passing the ``--keep`` flag.
97
98 The ``edit`` operation will drop you back to a command prompt,
99 allowing you to edit files freely, or even use ``hg record`` to commit
100 some changes as a separate commit. When you're done, any remaining
101 uncommitted changes will be committed as well. When done, run ``hg
102 histedit --continue`` to finish this step. If there are uncommitted
103 changes, you'll be prompted for a new commit message, but the default
104 commit message will be the original message for the ``edit`` ed
105 revision, and the date of the original commit will be preserved.
106
107 The ``message`` operation will give you a chance to revise a commit
108 message without changing the contents. It's a shortcut for doing
109 ``edit`` immediately followed by `hg histedit --continue``.
110
111 If ``histedit`` encounters a conflict when moving a revision (while
112 handling ``pick`` or ``fold``), it'll stop in a similar manner to
113 ``edit`` with the difference that it won't prompt you for a commit
114 message when done. If you decide at this point that you don't like how
115 much work it will be to rearrange history, or that you made a mistake,
116 you can use ``hg histedit --abort`` to abandon the new changes you
117 have made and return to the state before you attempted to edit your
118 history.
119
120 If we clone the histedit-ed example repository above and add four more
121 changes, such that we have the following history::
122
123 @ 6[tip] 038383181893 2009-04-27 18:04 -0500 stefan
124 | Add theta
125 |
126 o 5 140988835471 2009-04-27 18:04 -0500 stefan
127 | Add eta
128 |
129 o 4 122930637314 2009-04-27 18:04 -0500 stefan
130 | Add zeta
131 |
132 o 3 836302820282 2009-04-27 18:04 -0500 stefan
133 | Add epsilon
134 |
135 o 2 989b4d060121 2009-04-27 18:04 -0500 durin42
136 | Add beta and delta.
137 |
138 o 1 081603921c3f 2009-04-27 18:04 -0500 durin42
139 | Add gamma
140 |
141 o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42
142 Add alpha
143
144 If you run ``hg histedit --outgoing`` on the clone then it is the same
145 as running ``hg histedit 836302820282``. If you need plan to push to a
146 repository that Mercurial does not detect to be related to the source
147 repo, you can add a ``--force`` option.
148
149 Config
150 ------
151
152 Histedit rule lines are truncated to 80 characters by default. You
153 can customize this behavior by setting a different length in your
154 configuration file::
155
156 [histedit]
157 linelen = 120 # truncate rule lines at 120 characters
158
159 The summary of a change can be customized as well::
160
161 [histedit]
162 summary-template = '{rev} {bookmarks} {desc|firstline}'
163
164 The customized summary should be kept short enough that rule lines
165 will fit in the configured line length. See above if that requires
166 customization.
167
168 ``hg histedit`` attempts to automatically choose an appropriate base
169 revision to use. To change which base revision is used, define a
170 revset in your configuration file::
171
172 [histedit]
173 defaultrev = only(.) & draft()
174
175 By default each edited revision needs to be present in histedit commands.
176 To remove revision you need to use ``drop`` operation. You can configure
177 the drop to be implicit for missing commits by adding::
178
179 [histedit]
180 dropmissing = True
181
182 By default, histedit will close the transaction after each action. For
183 performance purposes, you can configure histedit to use a single transaction
184 across the entire histedit. WARNING: This setting introduces a significant risk
185 of losing the work you've done in a histedit if the histedit aborts
186 unexpectedly::
187
188 [histedit]
189 singletransaction = True
190
191 """
192
193 from __future__ import annotations
194
195 # chistedit dependencies that are not available everywhere
196 try:
197 import fcntl
198 import termios
199 except ImportError:
200 fcntl = None
201 termios = None
202
203 import binascii
204 import functools
205 import os
206 import pickle
207 import struct
208
209 from mercurial.i18n import _
210 from mercurial.node import (
211 bin,
212 hex,
213 short,
214 )
215 from mercurial import (
216 bundle2,
217 cmdutil,
218 context,
219 copies,
220 destutil,
221 discovery,
222 encoding,
223 error,
224 exchange,
225 extensions,
226 logcmdutil,
227 merge as mergemod,
228 mergestate as mergestatemod,
229 mergeutil,
230 obsolete,
231 pycompat,
232 registrar,
233 repair,
234 rewriteutil,
235 scmutil,
236 state as statemod,
237 util,
238 )
239 from mercurial.cmd_impls import (
240 update as up_impl,
241 )
242 from mercurial.merge_utils import (
243 update as update_util,
244 )
245 from mercurial.repo import (
246 factory as repo_factory,
247 )
248 from mercurial.utils import (
249 dateutil,
250 stringutil,
251 urlutil,
252 )
253
254 cmdtable = {}
255 command = registrar.command(cmdtable)
256
257 configtable = {}
258 configitem = registrar.configitem(configtable)
259 configitem(
260 b'experimental',
261 b'histedit.autoverb',
262 default=False,
263 )
264 configitem(
265 b'histedit',
266 b'defaultrev',
267 default=None,
268 )
269 configitem(
270 b'histedit',
271 b'dropmissing',
272 default=False,
273 )
274 configitem(
275 b'histedit',
276 b'linelen',
277 default=80,
278 )
279 configitem(
280 b'histedit',
281 b'singletransaction',
282 default=False,
283 )
284 configitem(
285 b'ui',
286 b'interface.histedit',
287 default=None,
288 )
289 configitem(b'histedit', b'summary-template', default=b'{rev} {desc|firstline}')
290 # TODO: Teach the text-based histedit interface to respect this config option
291 # before we make it non-experimental.
292 configitem(
293 b'histedit', b'later-commits-first', default=False, experimental=True
294 )
295
296 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
297 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
298 # be specifying the version(s) of Mercurial they are tested with, or
299 # leave the attribute unspecified.
300 testedwith = b'ships-with-hg-core'
301
302 actiontable = {}
303 primaryactions = set()
304 secondaryactions = set()
305 tertiaryactions = set()
306 internalactions = set()
307
308
309 def geteditcomment(ui, first, last):
310 """construct the editor comment
311 The comment includes::
312 - an intro
313 - sorted primary commands
314 - sorted short commands
315 - sorted long commands
316 - additional hints
317
318 Commands are only included once.
319 """
320 intro = _(
321 b"""Edit history between %s and %s
322
323 Commits are listed from least to most recent
324
325 You can reorder changesets by reordering the lines
326
327 Commands:
328 """
329 )
330 actions = []
331
332 def addverb(v):
333 a = actiontable[v]
334 lines = a.message.split(b"\n")
335 if len(a.verbs):
336 v = b', '.join(sorted(a.verbs, key=lambda v: len(v)))
337 actions.append(b" %s = %s" % (v, lines[0]))
338 actions.extend([b' %s'] * (len(lines) - 1))
339
340 for v in (
341 sorted(primaryactions)
342 + sorted(secondaryactions)
343 + sorted(tertiaryactions)
344 ):
345 addverb(v)
346 actions.append(b'')
347
348 hints = []
349 if ui.configbool(b'histedit', b'dropmissing'):
350 hints.append(
351 b"Deleting a changeset from the list "
352 b"will DISCARD it from the edited history!"
353 )
354
355 lines = (intro % (first, last)).split(b'\n') + actions + hints
356
357 return b''.join([b'# %s\n' % l if l else b'#\n' for l in lines])
358
359
360 class histeditstate:
361 def __init__(self, repo):
362 self.repo = repo
363 self.actions = None
364 self.keep = None
365 self.topmost = None
366 self.parentctxnode = None
367 self.lock = None
368 self.wlock = None
369 self.backupfile = None
370 self.stateobj = statemod.cmdstate(repo, b'histedit-state')
371 self.replacements = []
372
373 def read(self):
374 """Load histedit state from disk and set fields appropriately."""
375 if not self.stateobj.exists():
376 cmdutil.wrongtooltocontinue(self.repo, _(b'histedit'))
377
378 data = self._read()
379
380 self.parentctxnode = data[b'parentctxnode']
381 actions = parserules(data[b'rules'], self)
382 self.actions = actions
383 self.keep = data[b'keep']
384 self.topmost = data[b'topmost']
385 self.replacements = data[b'replacements']
386 self.backupfile = data[b'backupfile']
387
388 def _read(self):
389 fp = self.repo.vfs.read(b'histedit-state')
390 if fp.startswith(b'v1\n'):
391 data = self._load()
392 parentctxnode, rules, keep, topmost, replacements, backupfile = data
393 else:
394 data = pickle.loads(fp)
395 parentctxnode, rules, keep, topmost, replacements = data
396 backupfile = None
397 rules = b"\n".join([b"%s %s" % (verb, rest) for [verb, rest] in rules])
398
399 return {
400 b'parentctxnode': parentctxnode,
401 b"rules": rules,
402 b"keep": keep,
403 b"topmost": topmost,
404 b"replacements": replacements,
405 b"backupfile": backupfile,
406 }
407
408 def write(self, tr=None):
409 if tr:
410 tr.addfilegenerator(
411 b'histedit-state',
412 (b'histedit-state',),
413 self._write,
414 location=b'plain',
415 )
416 else:
417 with self.repo.vfs(b"histedit-state", b"w") as f:
418 self._write(f)
419
420 def _write(self, fp):
421 fp.write(b'v1\n')
422 fp.write(b'%s\n' % hex(self.parentctxnode))
423 fp.write(b'%s\n' % hex(self.topmost))
424 fp.write(b'%s\n' % (b'True' if self.keep else b'False'))
425 fp.write(b'%d\n' % len(self.actions))
426 for action in self.actions:
427 fp.write(b'%s\n' % action.tostate())
428 fp.write(b'%d\n' % len(self.replacements))
429 for replacement in self.replacements:
430 fp.write(
431 b'%s%s\n'
432 % (
433 hex(replacement[0]),
434 b''.join(hex(r) for r in replacement[1]),
435 )
436 )
437 backupfile = self.backupfile
438 if not backupfile:
439 backupfile = b''
440 fp.write(b'%s\n' % backupfile)
441
442 def _load(self):
443 fp = self.repo.vfs(b'histedit-state', b'r')
444 lines = [l[:-1] for l in fp.readlines()]
445
446 index = 0
447 lines[index] # version number
448 index += 1
449
450 parentctxnode = bin(lines[index])
451 index += 1
452
453 topmost = bin(lines[index])
454 index += 1
455
456 keep = lines[index] == b'True'
457 index += 1
458
459 # Rules
460 rules = []
461 rulelen = int(lines[index])
462 index += 1
463 for i in range(rulelen):
464 ruleaction = lines[index]
465 index += 1
466 rule = lines[index]
467 index += 1
468 rules.append((ruleaction, rule))
469
470 # Replacements
471 replacements = []
472 replacementlen = int(lines[index])
473 index += 1
474 for i in range(replacementlen):
475 replacement = lines[index]
476 original = bin(replacement[:40])
477 succ = [
478 bin(replacement[i : i + 40])
479 for i in range(40, len(replacement), 40)
480 ]
481 replacements.append((original, succ))
482 index += 1
483
484 backupfile = lines[index]
485 index += 1
486
487 fp.close()
488
489 return parentctxnode, rules, keep, topmost, replacements, backupfile
490
491 def clear(self):
492 if self.inprogress():
493 self.repo.vfs.unlink(b'histedit-state')
494
495 def inprogress(self):
496 return self.repo.vfs.exists(b'histedit-state')
497
498
499 class histeditaction:
500 def __init__(self, state, node):
501 self.state = state
502 self.repo = state.repo
503 self.node = node
504
505 @classmethod
506 def fromrule(cls, state, rule):
507 """Parses the given rule, returning an instance of the histeditaction."""
508 ruleid = rule.strip().split(b' ', 1)[0]
509 # ruleid can be anything from rev numbers, hashes, "bookmarks" etc
510 # Check for validation of rule ids and get the rulehash
511 try:
512 rev = bin(ruleid)
513 except binascii.Error:
514 try:
515 _ctx = scmutil.revsingle(state.repo, ruleid)
516 rulehash = _ctx.hex()
517 rev = bin(rulehash)
518 except error.RepoLookupError:
519 raise error.ParseError(_(b"invalid changeset %s") % ruleid)
520 return cls(state, rev)
521
522 def verify(self, prev, expected, seen):
523 """Verifies semantic correctness of the rule"""
524 repo = self.repo
525 ha = hex(self.node)
526 self.node = scmutil.resolvehexnodeidprefix(repo, ha)
527 if self.node is None:
528 raise error.ParseError(_(b'unknown changeset %s listed') % ha[:12])
529 self._verifynodeconstraints(prev, expected, seen)
530
531 def _verifynodeconstraints(self, prev, expected, seen):
532 # by default command need a node in the edited list
533 if self.node not in expected:
534 raise error.ParseError(
535 _(b'%s "%s" changeset was not a candidate')
536 % (self.verb, short(self.node)),
537 hint=_(b'only use listed changesets'),
538 )
539 # and only one command per node
540 if self.node in seen:
541 raise error.ParseError(
542 _(b'duplicated command for changeset %s') % short(self.node)
543 )
544
545 def torule(self):
546 """build a histedit rule line for an action
547
548 by default lines are in the form:
549 <hash> <rev> <summary>
550 """
551 ctx = self.repo[self.node]
552 ui = self.repo.ui
553 # We don't want color codes in the commit message template, so
554 # disable the label() template function while we render it.
555 with ui.configoverride(
556 {(b'templatealias', b'label(l,x)'): b"x"}, b'histedit'
557 ):
558 summary = cmdutil.rendertemplate(
559 ctx, ui.config(b'histedit', b'summary-template')
560 )
561 line = b'%s %s %s' % (self.verb, ctx, stringutil.firstline(summary))
562 # trim to 75 columns by default so it's not stupidly wide in my editor
563 # (the 5 more are left for verb)
564 maxlen = self.repo.ui.configint(b'histedit', b'linelen')
565 maxlen = max(maxlen, 22) # avoid truncating hash
566 return stringutil.ellipsis(line, maxlen)
567
568 def tostate(self):
569 """Print an action in format used by histedit state files
570 (the first line is a verb, the remainder is the second)
571 """
572 return b"%s\n%s" % (self.verb, hex(self.node))
573
574 def run(self):
575 """Runs the action. The default behavior is simply apply the action's
576 rulectx onto the current parentctx."""
577 self.applychange()
578 self.continuedirty()
579 return self.continueclean()
580
581 def applychange(self):
582 """Applies the changes from this action's rulectx onto the current
583 parentctx, but does not commit them."""
584 repo = self.repo
585 rulectx = repo[self.node]
586 with repo.ui.silent():
587 up_impl.update(repo, self.state.parentctxnode, quietempty=True)
588 stats = applychanges(repo.ui, repo, rulectx, {})
589 repo.dirstate.setbranch(rulectx.branch(), repo.currenttransaction())
590 if stats.unresolvedcount:
591 raise error.InterventionRequired(
592 _(b'Fix up the change (%s %s)') % (self.verb, short(self.node)),
593 hint=_(b'hg histedit --continue to resume'),
594 )
595
596 def continuedirty(self):
597 """Continues the action when changes have been applied to the working
598 copy. The default behavior is to commit the dirty changes."""
599 repo = self.repo
600 rulectx = repo[self.node]
601
602 editor = self.commiteditor()
603 commit = commitfuncfor(repo, rulectx)
604 if repo.ui.configbool(b'rewrite', b'update-timestamp'):
605 date = dateutil.makedate()
606 else:
607 date = rulectx.date()
608 commit(
609 text=rulectx.description(),
610 user=rulectx.user(),
611 date=date,
612 extra=rulectx.extra(),
613 editor=editor,
614 )
615
616 def commiteditor(self):
617 """The editor to be used to edit the commit message."""
618 return False
619
620 def continueclean(self):
621 """Continues the action when the working copy is clean. The default
622 behavior is to accept the current commit as the new version of the
623 rulectx."""
624 ctx = self.repo[b'.']
625 if ctx.node() == self.state.parentctxnode:
626 self.repo.ui.warn(
627 _(b'%s: skipping changeset (no changes)\n') % short(self.node)
628 )
629 return ctx, [(self.node, tuple())]
630 if ctx.node() == self.node:
631 # Nothing changed
632 return ctx, []
633 return ctx, [(self.node, (ctx.node(),))]
634
635
636 def commitfuncfor(repo, src):
637 """Build a commit function for the replacement of <src>
638
639 This function ensure we apply the same treatment to all changesets.
640
641 - Add a 'histedit_source' entry in extra.
642
643 Note that fold has its own separated logic because its handling is a bit
644 different and not easily factored out of the fold method.
645 """
646 phasemin = src.phase()
647
648 def commitfunc(**kwargs):
649 overrides = {(b'phases', b'new-commit'): phasemin}
650 with repo.ui.configoverride(overrides, b'histedit'):
651 extra = kwargs.get('extra', {}).copy()
652 extra[b'histedit_source'] = src.hex()
653 kwargs['extra'] = extra
654 return repo.commit(**kwargs)
655
656 return commitfunc
657
658
659 def applychanges(ui, repo, ctx, opts):
660 """Merge changeset from ctx (only) in the current working directory"""
661 if ctx.p1().node() == repo.dirstate.p1():
662 # edits are "in place" we do not need to make any merge,
663 # just applies changes on parent for editing
664 with ui.silent():
665 cmdutil.revert(ui, repo, ctx, all=True)
666 stats = update_util.UpdateResult(0, 0, 0, 0)
667 else:
668 try:
669 # ui.forcemerge is an internal variable, do not document
670 repo.ui.setconfig(
671 b'ui', b'forcemerge', opts.get(b'tool', b''), b'histedit'
672 )
673 stats = mergemod.graft(
674 repo,
675 ctx,
676 labels=[
677 b'already edited',
678 b'current change',
679 b'parent of current change',
680 ],
681 )
682 finally:
683 repo.ui.setconfig(b'ui', b'forcemerge', b'', b'histedit')
684 return stats
685
686
687 def collapse(repo, firstctx, lastctx, commitopts, skipprompt=False):
688 """collapse the set of revisions from first to last as new one.
689
690 Expected commit options are:
691 - message
692 - date
693 - username
694 Commit message is edited in all cases.
695
696 This function works in memory."""
697 ctxs = list(repo.set(b'%d::%d', firstctx.rev(), lastctx.rev()))
698 if not ctxs:
699 return None
700 for c in ctxs:
701 if not c.mutable():
702 raise error.ParseError(
703 _(b"cannot fold into public change %s") % short(c.node())
704 )
705 base = firstctx.p1()
706
707 # commit a new version of the old changeset, including the update
708 # collect all files which might be affected
709 files = set()
710 for ctx in ctxs:
711 files.update(ctx.files())
712
713 # Recompute copies (avoid recording a -> b -> a)
714 copied = copies.pathcopies(base, lastctx)
715
716 # prune files which were reverted by the updates
717 files = [f for f in files if not cmdutil.samefile(f, lastctx, base)]
718 # commit version of these files as defined by head
719 headmf = lastctx.manifest()
720
721 def filectxfn(repo, ctx, path):
722 if path in headmf:
723 fctx = lastctx[path]
724 flags = fctx.flags()
725 mctx = context.memfilectx(
726 repo,
727 ctx,
728 fctx.path(),
729 fctx.data(),
730 islink=b'l' in flags,
731 isexec=b'x' in flags,
732 copysource=copied.get(path),
733 )
734 return mctx
735 return None
736
737 if commitopts.get(b'message'):
738 message = commitopts[b'message']
739 else:
740 message = firstctx.description()
741 user = commitopts.get(b'user')
742 date = commitopts.get(b'date')
743 extra = commitopts.get(b'extra')
744
745 parents = (firstctx.p1().node(), firstctx.p2().node())
746 editor = None
747 if not skipprompt:
748 editor = cmdutil.getcommiteditor(edit=True, editform=b'histedit.fold')
749 new = context.memctx(
750 repo,
751 parents=parents,
752 text=message,
753 files=files,
754 filectxfn=filectxfn,
755 user=user,
756 date=date,
757 extra=extra,
758 editor=editor,
759 )
760 return repo.commitctx(new)
761
762
763 def _isdirtywc(repo):
764 return repo[None].dirty(missing=True)
765
766
767 def abortdirty():
768 raise error.StateError(
769 _(b'working copy has pending changes'),
770 hint=_(
771 b'amend, commit, or revert them and run histedit '
772 b'--continue, or abort with histedit --abort'
773 ),
774 )
775
776
777 def action(verbs, message, priority=False, internal=False):
778 def wrap(cls):
779 assert not priority or not internal
780 verb = verbs[0]
781 if priority:
782 primaryactions.add(verb)
783 elif internal:
784 internalactions.add(verb)
785 elif len(verbs) > 1:
786 secondaryactions.add(verb)
787 else:
788 tertiaryactions.add(verb)
789
790 cls.verb = verb
791 cls.verbs = verbs
792 cls.message = message
793 for verb in verbs:
794 actiontable[verb] = cls
795 return cls
796
797 return wrap
798
799
800 @action([b'pick', b'p'], _(b'use commit'), priority=True)
801 class pick(histeditaction):
802 def run(self):
803 rulectx = self.repo[self.node]
804 if rulectx.p1().node() == self.state.parentctxnode:
805 self.repo.ui.debug(b'node %s unchanged\n' % short(self.node))
806 return rulectx, []
807
808 return super().run()
809
810
811 @action(
812 [b'edit', b'e'],
813 _(b'use commit, but allow edits before making new commit'),
814 priority=True,
815 )
816 class edit(histeditaction):
817 def run(self):
818 repo = self.repo
819 rulectx = repo[self.node]
820 up_impl.update(repo, self.state.parentctxnode, quietempty=True)
821 applychanges(repo.ui, repo, rulectx, {})
822 hint = _(b'to edit %s, `hg histedit --continue` after making changes')
823 raise error.InterventionRequired(
824 _(b'Editing (%s), commit as needed now to split the change')
825 % short(self.node),
826 hint=hint % short(self.node),
827 )
828
829 def commiteditor(self):
830 return cmdutil.getcommiteditor(edit=True, editform=b'histedit.edit')
831
832
833 @action([b'fold', b'f'], _(b'use commit, but combine it with the one above'))
834 class fold(histeditaction):
835 def verify(self, prev, expected, seen):
836 """Verifies semantic correctness of the fold rule"""
837 super().verify(prev, expected, seen)
838 repo = self.repo
839 if not prev:
840 c = repo[self.node].p1()
841 elif not prev.verb in (b'pick', b'base'):
842 return
843 else:
844 c = repo[prev.node]
845 if not c.mutable():
846 raise error.ParseError(
847 _(b"cannot fold into public change %s") % short(c.node())
848 )
849
850 def continuedirty(self):
851 repo = self.repo
852 rulectx = repo[self.node]
853
854 commit = commitfuncfor(repo, rulectx)
855 commit(
856 text=b'fold-temp-revision %s' % short(self.node),
857 user=rulectx.user(),
858 date=rulectx.date(),
859 extra=rulectx.extra(),
860 )
861
862 def continueclean(self):
863 repo = self.repo
864 ctx = repo[b'.']
865 rulectx = repo[self.node]
866 parentctxnode = self.state.parentctxnode
867 if ctx.node() == parentctxnode:
868 repo.ui.warn(_(b'%s: empty changeset\n') % short(self.node))
869 return ctx, [(self.node, (parentctxnode,))]
870
871 parentctx = repo[parentctxnode]
872 newcommits = {
873 c.node()
874 for c in repo.set(b'(%d::. - %d)', parentctx.rev(), parentctx.rev())
875 }
876 if not newcommits:
877 repo.ui.warn(
878 _(
879 b'%s: cannot fold - working copy is not a '
880 b'descendant of previous commit %s\n'
881 )
882 % (short(self.node), short(parentctxnode))
883 )
884 return ctx, [(self.node, (ctx.node(),))]
885
886 middlecommits = newcommits.copy()
887 middlecommits.discard(ctx.node())
888
889 return self.finishfold(
890 repo.ui, repo, parentctx, rulectx, ctx.node(), middlecommits
891 )
892
893 def skipprompt(self):
894 """Returns true if the rule should skip the message editor.
895
896 For example, 'fold' wants to show an editor, but 'rollup'
897 doesn't want to.
898 """
899 return False
900
901 def mergedescs(self):
902 """Returns true if the rule should merge messages of multiple changes.
903
904 This exists mainly so that 'rollup' rules can be a subclass of
905 'fold'.
906 """
907 return True
908
909 def firstdate(self):
910 """Returns true if the rule should preserve the date of the first
911 change.
912
913 This exists mainly so that 'rollup' rules can be a subclass of
914 'fold'.
915 """
916 return False
917
918 def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges):
919 mergemod.update(ctx.p1())
920 ### prepare new commit data
921 commitopts = {}
922 commitopts[b'user'] = ctx.user()
923 # commit message
924 if not self.mergedescs():
925 newmessage = ctx.description()
926 else:
927 newmessage = (
928 b'\n***\n'.join(
929 [ctx.description()]
930 + [repo[r].description() for r in internalchanges]
931 + [oldctx.description()]
932 )
933 + b'\n'
934 )
935 commitopts[b'message'] = newmessage
936 # date
937 if self.firstdate():
938 commitopts[b'date'] = ctx.date()
939 else:
940 commitopts[b'date'] = max(ctx.date(), oldctx.date())
941 # if date is to be updated to current
942 if ui.configbool(b'rewrite', b'update-timestamp'):
943 commitopts[b'date'] = dateutil.makedate()
944
945 extra = ctx.extra().copy()
946 # histedit_source
947 # note: ctx is likely a temporary commit but that the best we can do
948 # here. This is sufficient to solve issue3681 anyway.
949 extra[b'histedit_source'] = b'%s,%s' % (ctx.hex(), oldctx.hex())
950 commitopts[b'extra'] = extra
951 phasemin = max(ctx.phase(), oldctx.phase())
952 overrides = {(b'phases', b'new-commit'): phasemin}
953 with repo.ui.configoverride(overrides, b'histedit'):
954 n = collapse(
955 repo,
956 ctx,
957 repo[newnode],
958 commitopts,
959 skipprompt=self.skipprompt(),
960 )
961 if n is None:
962 return ctx, []
963 mergemod.update(repo[n])
964 replacements = [
965 (oldctx.node(), (newnode,)),
966 (ctx.node(), (n,)),
967 (newnode, (n,)),
968 ]
969 for ich in internalchanges:
970 replacements.append((ich, (n,)))
971 return repo[n], replacements
972
973
974 @action(
975 [b'base', b'b'],
976 _(b'checkout changeset and apply further changesets from there'),
977 )
978 class base(histeditaction):
979 def run(self):
980 if self.repo[b'.'].node() != self.node:
981 mergemod.clean_update(self.repo[self.node])
982 return self.continueclean()
983
984 def continuedirty(self):
985 abortdirty()
986
987 def continueclean(self):
988 basectx = self.repo[b'.']
989 return basectx, []
990
991 def _verifynodeconstraints(self, prev, expected, seen):
992 # base can only be use with a node not in the edited set
993 if self.node in expected:
994 msg = _(b'%s "%s" changeset was an edited list candidate')
995 raise error.ParseError(
996 msg % (self.verb, short(self.node)),
997 hint=_(b'base must only use unlisted changesets'),
998 )
999
1000
1001 @action(
1002 [b'_multifold'],
1003 _(
1004 b"""fold subclass used for when multiple folds happen in a row
1005
1006 We only want to fire the editor for the folded message once when
1007 (say) four changes are folded down into a single change. This is
1008 similar to rollup, but we should preserve both messages so that
1009 when the last fold operation runs we can show the user all the
1010 commit messages in their editor.
1011 """
1012 ),
1013 internal=True,
1014 )
1015 class _multifold(fold):
1016 def skipprompt(self):
1017 return True
1018
1019
1020 @action(
1021 [b"roll", b"r"],
1022 _(b"like fold, but discard this commit's description and date"),
1023 )
1024 class rollup(fold):
1025 def mergedescs(self):
1026 return False
1027
1028 def skipprompt(self):
1029 return True
1030
1031 def firstdate(self):
1032 return True
1033
1034
1035 @action([b"drop", b"d"], _(b'remove commit from history'))
1036 class drop(histeditaction):
1037 def run(self):
1038 parentctx = self.repo[self.state.parentctxnode]
1039 return parentctx, [(self.node, tuple())]
1040
1041
1042 @action(
1043 [b"mess", b"m"],
1044 _(b'edit commit message without changing commit content'),
1045 priority=True,
1046 )
1047 class message(histeditaction):
1048 def commiteditor(self):
1049 return cmdutil.getcommiteditor(edit=True, editform=b'histedit.mess')
1050
1051
1052 def findoutgoing(ui, repo, remote=None, force=False, opts=None):
1053 """utility function to find the first outgoing changeset
1054
1055 Used by initialization code"""
1056 if opts is None:
1057 opts = {}
1058 path = urlutil.get_unique_push_path(b'histedit', repo, ui, remote)
1059
1060 ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(path.loc))
1061
1062 revs, checkout = urlutil.add_branch_revs(
1063 repo,
1064 repo,
1065 (path.branch, []),
1066 None,
1067 )
1068 other = repo_factory.peer(repo, opts, path)
1069
1070 if revs:
1071 revs = [repo.lookup(rev) for rev in revs]
1072
1073 outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force)
1074 if not outgoing.missing:
1075 raise error.StateError(_(b'no outgoing ancestors'))
1076 roots = list(repo.revs(b"roots(%ln)", outgoing.missing))
1077 if len(roots) > 1:
1078 msg = _(b'there are ambiguous outgoing revisions')
1079 hint = _(b"see 'hg help histedit' for more detail")
1080 raise error.StateError(msg, hint=hint)
1081 return repo[roots[0]].node()
1082
1083
1084 # Curses Support
1085 try:
1086 import curses
1087 except ImportError:
1088 curses = None
1089
1090 KEY_LIST = [b'pick', b'edit', b'fold', b'drop', b'mess', b'roll']
1091 ACTION_LABELS = {
1092 b'fold': b'^fold',
1093 b'roll': b'^roll',
1094 }
1095
1096 COLOR_HELP, COLOR_SELECTED, COLOR_OK, COLOR_WARN, COLOR_CURRENT = 1, 2, 3, 4, 5
1097 COLOR_DIFF_ADD_LINE, COLOR_DIFF_DEL_LINE, COLOR_DIFF_OFFSET = 6, 7, 8
1098 COLOR_ROLL, COLOR_ROLL_CURRENT, COLOR_ROLL_SELECTED = 9, 10, 11
1099
1100 E_QUIT, E_HISTEDIT = 1, 2
1101 E_PAGEDOWN, E_PAGEUP, E_LINEUP, E_LINEDOWN, E_RESIZE = 3, 4, 5, 6, 7
1102 MODE_INIT, MODE_PATCH, MODE_RULES, MODE_HELP = 0, 1, 2, 3
1103
1104 KEYTABLE = {
1105 b'global': {
1106 b'h': b'next-action',
1107 b'KEY_RIGHT': b'next-action',
1108 b'l': b'prev-action',
1109 b'KEY_LEFT': b'prev-action',
1110 b'q': b'quit',
1111 b'c': b'histedit',
1112 b'C': b'histedit',
1113 b'v': b'showpatch',
1114 b'?': b'help',
1115 },
1116 MODE_RULES: {
1117 b'd': b'action-drop',
1118 b'e': b'action-edit',
1119 b'f': b'action-fold',
1120 b'm': b'action-mess',
1121 b'p': b'action-pick',
1122 b'r': b'action-roll',
1123 b' ': b'select',
1124 b'j': b'down',
1125 b'k': b'up',
1126 b'KEY_DOWN': b'down',
1127 b'KEY_UP': b'up',
1128 b'J': b'move-down',
1129 b'K': b'move-up',
1130 b'KEY_NPAGE': b'move-down',
1131 b'KEY_PPAGE': b'move-up',
1132 b'0': b'goto', # Used for 0..9
1133 },
1134 MODE_PATCH: {
1135 b' ': b'page-down',
1136 b'KEY_NPAGE': b'page-down',
1137 b'KEY_PPAGE': b'page-up',
1138 b'j': b'line-down',
1139 b'k': b'line-up',
1140 b'KEY_DOWN': b'line-down',
1141 b'KEY_UP': b'line-up',
1142 b'J': b'down',
1143 b'K': b'up',
1144 },
1145 MODE_HELP: {},
1146 }
1147
1148
1149 def screen_size():
1150 return struct.unpack(b'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, b' '))
1151
1152
1153 class histeditrule:
1154 def __init__(self, ui, ctx, pos, action=b'pick'):
1155 self.ui = ui
1156 self.ctx = ctx
1157 self.action = action
1158 self.origpos = pos
1159 self.pos = pos
1160 self.conflicts = []
1161
1162 def __bytes__(self):
1163 # Example display of several histeditrules:
1164 #
1165 # #10 pick 316392:06a16c25c053 add option to skip tests
1166 # #11 ^roll 316393:71313c964cc5 <RED>oops a fixup commit</RED>
1167 # #12 pick 316394:ab31f3973b0d include mfbt for mozilla-config.h
1168 # #13 ^fold 316395:14ce5803f4c3 fix warnings
1169 #
1170 # The carets point to the changeset being folded into ("roll this
1171 # changeset into the changeset above").
1172 return b'%s%s' % (self.prefix, self.desc)
1173
1174 __str__ = encoding.strmethod(__bytes__)
1175
1176 @property
1177 def prefix(self):
1178 # Some actions ('fold' and 'roll') combine a patch with a
1179 # previous one. Add a marker showing which patch they apply
1180 # to.
1181 action = ACTION_LABELS.get(self.action, self.action)
1182
1183 h = self.ctx.hex()[0:12]
1184 r = self.ctx.rev()
1185
1186 return b"#%s %s %d:%s " % (
1187 (b'%d' % self.origpos).ljust(2),
1188 action.ljust(6),
1189 r,
1190 h,
1191 )
1192
1193 @util.propertycache
1194 def desc(self):
1195 summary = cmdutil.rendertemplate(
1196 self.ctx, self.ui.config(b'histedit', b'summary-template')
1197 )
1198 if summary:
1199 return summary
1200 # This is split off from the prefix property so that we can
1201 # separately make the description for 'roll' red (since it
1202 # will get discarded).
1203 return stringutil.firstline(self.ctx.description())
1204
1205 def checkconflicts(self, other):
1206 if other.pos > self.pos and other.origpos <= self.origpos:
1207 if set(other.ctx.files()) & set(self.ctx.files()) != set():
1208 self.conflicts.append(other)
1209 return self.conflicts
1210
1211 if other in self.conflicts:
1212 self.conflicts.remove(other)
1213 return self.conflicts
1214
1215
1216 def makecommands(rules):
1217 """Returns a list of commands consumable by histedit --commands based on
1218 our list of rules"""
1219 commands = []
1220 for rules in rules:
1221 commands.append(b'%s %s\n' % (rules.action, rules.ctx))
1222 return commands
1223
1224
1225 def addln(win, y, x, line, color=None):
1226 """Add a line to the given window left padding but 100% filled with
1227 whitespace characters, so that the color appears on the whole line"""
1228 maxy, maxx = win.getmaxyx()
1229 length = maxx - 1 - x
1230 line = bytes(line).ljust(length)[:length]
1231 if y < 0:
1232 y = maxy + y
1233 if x < 0:
1234 x = maxx + x
1235 if color:
1236 win.addstr(y, x, line, color)
1237 else:
1238 win.addstr(y, x, line)
1239
1240
1241 def _trunc_head(line, n):
1242 if len(line) <= n:
1243 return line
1244 return b'> ' + line[-(n - 2) :]
1245
1246
1247 def _trunc_tail(line, n):
1248 if len(line) <= n:
1249 return line
1250 return line[: n - 2] + b' >'
1251
1252
1253 class _chistedit_state:
1254 def __init__(
1255 self,
1256 repo,
1257 rules,
1258 stdscr,
1259 ):
1260 self.repo = repo
1261 self.rules = rules
1262 self.stdscr = stdscr
1263 self.later_on_top = repo.ui.configbool(
1264 b'histedit', b'later-commits-first'
1265 )
1266 # The current item in display order, initialized to point to the top
1267 # of the screen.
1268 self.pos = 0
1269 self.selected = None
1270 self.mode = (MODE_INIT, MODE_INIT)
1271 self.page_height = None
1272 self.modes = {
1273 MODE_RULES: {
1274 b'line_offset': 0,
1275 },
1276 MODE_PATCH: {
1277 b'line_offset': 0,
1278 },
1279 }
1280
1281 def render_commit(self, win):
1282 """Renders the commit window that shows the log of the current selected
1283 commit"""
1284 rule = self.rules[self.display_pos_to_rule_pos(self.pos)]
1285
1286 ctx = rule.ctx
1287 win.box()
1288
1289 maxy, maxx = win.getmaxyx()
1290 length = maxx - 3
1291
1292 line = b"changeset: %d:%s" % (ctx.rev(), ctx.hex()[:12])
1293 win.addstr(1, 1, line[:length])
1294
1295 line = b"user: %s" % ctx.user()
1296 win.addstr(2, 1, line[:length])
1297
1298 bms = self.repo.nodebookmarks(ctx.node())
1299 line = b"bookmark: %s" % b' '.join(bms)
1300 win.addstr(3, 1, line[:length])
1301
1302 line = b"summary: %s" % stringutil.firstline(ctx.description())
1303 win.addstr(4, 1, line[:length])
1304
1305 line = b"files: "
1306 win.addstr(5, 1, line)
1307 fnx = 1 + len(line)
1308 fnmaxx = length - fnx + 1
1309 y = 5
1310 fnmaxn = maxy - (1 + y) - 1
1311 files = ctx.files()
1312 for i, line1 in enumerate(files):
1313 if len(files) > fnmaxn and i == fnmaxn - 1:
1314 win.addstr(y, fnx, _trunc_tail(b','.join(files[i:]), fnmaxx))
1315 y = y + 1
1316 break
1317 win.addstr(y, fnx, _trunc_head(line1, fnmaxx))
1318 y = y + 1
1319
1320 conflicts = rule.conflicts
1321 if len(conflicts) > 0:
1322 conflictstr = b','.join(map(lambda r: r.ctx.hex()[:12], conflicts))
1323 conflictstr = b"changed files overlap with %s" % conflictstr
1324 else:
1325 conflictstr = b'no overlap'
1326
1327 win.addstr(y, 1, conflictstr[:length])
1328 win.noutrefresh()
1329
1330 def helplines(self):
1331 if self.mode[0] == MODE_PATCH:
1332 help = b"""\
1333 ?: help, k/up: line up, j/down: line down, v: stop viewing patch
1334 pgup: prev page, space/pgdn: next page, c: commit, q: abort
1335 """
1336 else:
1337 help = b"""\
1338 ?: help, k/up: move up, j/down: move down, space: select, v: view patch
1339 d: drop, e: edit, f: fold, m: mess, p: pick, r: roll
1340 pgup/K: move patch up, pgdn/J: move patch down, c: commit, q: abort
1341 """
1342 if self.later_on_top:
1343 help += b"Newer commits are shown above older commits.\n"
1344 else:
1345 help += b"Older commits are shown above newer commits.\n"
1346 return help.splitlines()
1347
1348 def render_help(self, win):
1349 maxy, maxx = win.getmaxyx()
1350 for y, line in enumerate(self.helplines()):
1351 if y >= maxy:
1352 break
1353 addln(win, y, 0, line, curses.color_pair(COLOR_HELP))
1354 win.noutrefresh()
1355
1356 def layout(self):
1357 maxy, maxx = self.stdscr.getmaxyx()
1358 helplen = len(self.helplines())
1359 mainlen = maxy - helplen - 12
1360 if mainlen < 1:
1361 raise error.Abort(
1362 _(b"terminal dimensions %d by %d too small for curses histedit")
1363 % (maxy, maxx),
1364 hint=_(
1365 b"enlarge your terminal or use --config ui.interface=text"
1366 ),
1367 )
1368 return {
1369 b'commit': (12, maxx),
1370 b'help': (helplen, maxx),
1371 b'main': (mainlen, maxx),
1372 }
1373
1374 def display_pos_to_rule_pos(self, display_pos):
1375 """Converts a position in display order to rule order.
1376
1377 The `display_pos` is the order from the top in display order, not
1378 considering which items are currently visible on the screen. Thus,
1379 `display_pos=0` is the item at the top (possibly after scrolling to
1380 the top)
1381 """
1382 if self.later_on_top:
1383 return len(self.rules) - 1 - display_pos
1384 else:
1385 return display_pos
1386
1387 def render_rules(self, rulesscr):
1388 start = self.modes[MODE_RULES][b'line_offset']
1389
1390 conflicts = [r.ctx for r in self.rules if r.conflicts]
1391 if len(conflicts) > 0:
1392 line = b"potential conflict in %s" % b','.join(
1393 map(pycompat.bytestr, conflicts)
1394 )
1395 addln(rulesscr, -1, 0, line, curses.color_pair(COLOR_WARN))
1396
1397 for display_pos in range(start, len(self.rules)):
1398 y = display_pos - start
1399 if y < 0 or y >= self.page_height:
1400 continue
1401 rule_pos = self.display_pos_to_rule_pos(display_pos)
1402 rule = self.rules[rule_pos]
1403 if len(rule.conflicts) > 0:
1404 rulesscr.addstr(y, 0, b" ", curses.color_pair(COLOR_WARN))
1405 else:
1406 rulesscr.addstr(y, 0, b" ", curses.COLOR_BLACK)
1407
1408 if display_pos == self.selected:
1409 rollcolor = COLOR_ROLL_SELECTED
1410 addln(rulesscr, y, 2, rule, curses.color_pair(COLOR_SELECTED))
1411 elif display_pos == self.pos:
1412 rollcolor = COLOR_ROLL_CURRENT
1413 addln(
1414 rulesscr,
1415 y,
1416 2,
1417 rule,
1418 curses.color_pair(COLOR_CURRENT) | curses.A_BOLD,
1419 )
1420 else:
1421 rollcolor = COLOR_ROLL
1422 addln(rulesscr, y, 2, rule)
1423
1424 if rule.action == b'roll':
1425 rulesscr.addstr(
1426 y,
1427 2 + len(rule.prefix),
1428 rule.desc,
1429 curses.color_pair(rollcolor),
1430 )
1431
1432 rulesscr.noutrefresh()
1433
1434 def render_string(self, win, output, diffcolors=False):
1435 maxy, maxx = win.getmaxyx()
1436 length = min(maxy - 1, len(output))
1437 for y in range(0, length):
1438 line = output[y]
1439 if diffcolors:
1440 if line.startswith(b'+'):
1441 win.addstr(
1442 y, 0, line, curses.color_pair(COLOR_DIFF_ADD_LINE)
1443 )
1444 elif line.startswith(b'-'):
1445 win.addstr(
1446 y, 0, line, curses.color_pair(COLOR_DIFF_DEL_LINE)
1447 )
1448 elif line.startswith(b'@@ '):
1449 win.addstr(y, 0, line, curses.color_pair(COLOR_DIFF_OFFSET))
1450 else:
1451 win.addstr(y, 0, line)
1452 else:
1453 win.addstr(y, 0, line)
1454 win.noutrefresh()
1455
1456 def render_patch(self, win):
1457 start = self.modes[MODE_PATCH][b'line_offset']
1458 content = self.modes[MODE_PATCH][b'patchcontents']
1459 self.render_string(win, content[start:], diffcolors=True)
1460
1461 def event(self, ch):
1462 """Change state based on the current character input
1463
1464 This takes the current state and based on the current character input from
1465 the user we change the state.
1466 """
1467 oldpos = self.pos
1468
1469 if ch in (curses.KEY_RESIZE, b"KEY_RESIZE"):
1470 return E_RESIZE
1471
1472 lookup_ch = ch
1473 if ch is not None and b'0' <= ch <= b'9':
1474 lookup_ch = b'0'
1475
1476 curmode, prevmode = self.mode
1477 action = KEYTABLE[curmode].get(
1478 lookup_ch, KEYTABLE[b'global'].get(lookup_ch)
1479 )
1480 if action is None:
1481 return
1482 if action in (b'down', b'move-down'):
1483 newpos = min(oldpos + 1, len(self.rules) - 1)
1484 self.move_cursor(oldpos, newpos)
1485 if self.selected is not None or action == b'move-down':
1486 self.swap(oldpos, newpos)
1487 elif action in (b'up', b'move-up'):
1488 newpos = max(0, oldpos - 1)
1489 self.move_cursor(oldpos, newpos)
1490 if self.selected is not None or action == b'move-up':
1491 self.swap(oldpos, newpos)
1492 elif action == b'next-action':
1493 self.cycle_action(oldpos, next=True)
1494 elif action == b'prev-action':
1495 self.cycle_action(oldpos, next=False)
1496 elif action == b'select':
1497 self.selected = oldpos if self.selected is None else None
1498 self.make_selection(self.selected)
1499 elif action == b'goto' and int(ch) < len(self.rules) <= 10:
1500 newrule = next(r for r in self.rules if r.origpos == int(ch))
1501 self.move_cursor(oldpos, newrule.pos)
1502 if self.selected is not None:
1503 self.swap(oldpos, newrule.pos)
1504 elif action.startswith(b'action-'):
1505 self.change_action(oldpos, action[7:])
1506 elif action == b'showpatch':
1507 self.change_mode(MODE_PATCH if curmode != MODE_PATCH else prevmode)
1508 elif action == b'help':
1509 self.change_mode(MODE_HELP if curmode != MODE_HELP else prevmode)
1510 elif action == b'quit':
1511 return E_QUIT
1512 elif action == b'histedit':
1513 return E_HISTEDIT
1514 elif action == b'page-down':
1515 return E_PAGEDOWN
1516 elif action == b'page-up':
1517 return E_PAGEUP
1518 elif action == b'line-down':
1519 return E_LINEDOWN
1520 elif action == b'line-up':
1521 return E_LINEUP
1522
1523 def patch_contents(self):
1524 repo = self.repo
1525 rule = self.rules[self.display_pos_to_rule_pos(self.pos)]
1526 displayer = logcmdutil.changesetdisplayer(
1527 repo.ui,
1528 repo,
1529 {b"patch": True, b"template": b"status"},
1530 buffered=True,
1531 )
1532 overrides = {(b'ui', b'verbose'): True}
1533 with repo.ui.configoverride(overrides, source=b'histedit'):
1534 displayer.show(rule.ctx)
1535 displayer.close()
1536 return displayer.hunk[rule.ctx.rev()].splitlines()
1537
1538 def move_cursor(self, oldpos, newpos):
1539 """Change the rule/changeset that the cursor is pointing to, regardless of
1540 current mode (you can switch between patches from the view patch window).
1541 """
1542 self.pos = newpos
1543
1544 mode, _ = self.mode
1545 if mode == MODE_RULES:
1546 # Scroll through the list by updating the view for MODE_RULES, so that
1547 # even if we are not currently viewing the rules, switching back will
1548 # result in the cursor's rule being visible.
1549 modestate = self.modes[MODE_RULES]
1550 if newpos < modestate[b'line_offset']:
1551 modestate[b'line_offset'] = newpos
1552 elif newpos > modestate[b'line_offset'] + self.page_height - 1:
1553 modestate[b'line_offset'] = newpos - self.page_height + 1
1554
1555 # Reset the patch view region to the top of the new patch.
1556 self.modes[MODE_PATCH][b'line_offset'] = 0
1557
1558 def change_mode(self, mode):
1559 curmode, _ = self.mode
1560 self.mode = (mode, curmode)
1561 if mode == MODE_PATCH:
1562 self.modes[MODE_PATCH][b'patchcontents'] = self.patch_contents()
1563
1564 def make_selection(self, pos):
1565 self.selected = pos
1566
1567 def swap(self, oldpos, newpos):
1568 """Swap two positions and calculate necessary conflicts in
1569 O(|newpos-oldpos|) time"""
1570 old_rule_pos = self.display_pos_to_rule_pos(oldpos)
1571 new_rule_pos = self.display_pos_to_rule_pos(newpos)
1572
1573 rules = self.rules
1574 assert 0 <= old_rule_pos < len(rules) and 0 <= new_rule_pos < len(rules)
1575
1576 rules[old_rule_pos], rules[new_rule_pos] = (
1577 rules[new_rule_pos],
1578 rules[old_rule_pos],
1579 )
1580
1581 # TODO: swap should not know about histeditrule's internals
1582 rules[new_rule_pos].pos = new_rule_pos
1583 rules[old_rule_pos].pos = old_rule_pos
1584
1585 start = min(old_rule_pos, new_rule_pos)
1586 end = max(old_rule_pos, new_rule_pos)
1587 for r in range(start, end + 1):
1588 rules[new_rule_pos].checkconflicts(rules[r])
1589 rules[old_rule_pos].checkconflicts(rules[r])
1590
1591 if self.selected:
1592 self.make_selection(newpos)
1593
1594 def change_action(self, pos, action):
1595 """Change the action state on the given position to the new action"""
1596 rule_pos = self.display_pos_to_rule_pos(pos)
1597 assert 0 <= rule_pos < len(self.rules)
1598 self.rules[rule_pos].action = action
1599
1600 def cycle_action(self, pos, next=False):
1601 """Changes the action state the next or the previous action from
1602 the action list"""
1603 rule_pos = self.display_pos_to_rule_pos(pos)
1604 assert 0 <= rule_pos < len(self.rules)
1605 current = self.rules[rule_pos].action
1606
1607 assert current in KEY_LIST
1608
1609 index = KEY_LIST.index(current)
1610 if next:
1611 index += 1
1612 else:
1613 index -= 1
1614 # using pos instead of rule_pos because change_action() also calls
1615 # display_pos_to_rule_pos()
1616 self.change_action(pos, KEY_LIST[index % len(KEY_LIST)])
1617
1618 def change_view(self, delta, unit):
1619 """Change the region of whatever is being viewed (a patch or the list of
1620 changesets). 'delta' is an amount (+/- 1) and 'unit' is 'page' or 'line'.
1621 """
1622 mode, _ = self.mode
1623 if mode != MODE_PATCH:
1624 return
1625 mode_state = self.modes[mode]
1626 num_lines = len(mode_state[b'patchcontents'])
1627 page_height = self.page_height
1628 unit = page_height if unit == b'page' else 1
1629 num_pages = 1 + (num_lines - 1) // page_height
1630 max_offset = (num_pages - 1) * page_height
1631 newline = mode_state[b'line_offset'] + delta * unit
1632 mode_state[b'line_offset'] = max(0, min(max_offset, newline))
1633
1634
1635 def _chisteditmain(repo, rules, stdscr):
1636 try:
1637 curses.use_default_colors()
1638 except curses.error:
1639 pass
1640
1641 # initialize color pattern
1642 curses.init_pair(COLOR_HELP, curses.COLOR_WHITE, curses.COLOR_BLUE)
1643 curses.init_pair(COLOR_SELECTED, curses.COLOR_BLACK, curses.COLOR_WHITE)
1644 curses.init_pair(COLOR_WARN, curses.COLOR_BLACK, curses.COLOR_YELLOW)
1645 curses.init_pair(COLOR_OK, curses.COLOR_BLACK, curses.COLOR_GREEN)
1646 curses.init_pair(COLOR_CURRENT, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
1647 curses.init_pair(COLOR_DIFF_ADD_LINE, curses.COLOR_GREEN, -1)
1648 curses.init_pair(COLOR_DIFF_DEL_LINE, curses.COLOR_RED, -1)
1649 curses.init_pair(COLOR_DIFF_OFFSET, curses.COLOR_MAGENTA, -1)
1650 curses.init_pair(COLOR_ROLL, curses.COLOR_RED, -1)
1651 curses.init_pair(
1652 COLOR_ROLL_CURRENT, curses.COLOR_BLACK, curses.COLOR_MAGENTA
1653 )
1654 curses.init_pair(COLOR_ROLL_SELECTED, curses.COLOR_RED, curses.COLOR_WHITE)
1655
1656 # don't display the cursor
1657 try:
1658 curses.curs_set(0)
1659 except curses.error:
1660 pass
1661
1662 def drawvertwin(size, y, x):
1663 win = curses.newwin(size[0], size[1], y, x)
1664 y += size[0]
1665 return win, y, x
1666
1667 state = _chistedit_state(repo, rules, stdscr)
1668
1669 # eventloop
1670 ch = None
1671 stdscr.clear()
1672 stdscr.refresh()
1673 while True:
1674 oldmode, unused = state.mode
1675 if oldmode == MODE_INIT:
1676 state.change_mode(MODE_RULES)
1677 e = state.event(ch)
1678
1679 if e == E_QUIT:
1680 return False
1681 if e == E_HISTEDIT:
1682 return state.rules
1683 else:
1684 if e == E_RESIZE:
1685 size = screen_size()
1686 if size != stdscr.getmaxyx():
1687 curses.resizeterm(*size)
1688
1689 sizes = state.layout()
1690 curmode, unused = state.mode
1691 if curmode != oldmode:
1692 state.page_height = sizes[b'main'][0]
1693 # Adjust the view to fit the current screen size.
1694 state.move_cursor(state.pos, state.pos)
1695
1696 # Pack the windows against the top, each pane spread across the
1697 # full width of the screen.
1698 y, x = (0, 0)
1699 helpwin, y, x = drawvertwin(sizes[b'help'], y, x)
1700 mainwin, y, x = drawvertwin(sizes[b'main'], y, x)
1701 commitwin, y, x = drawvertwin(sizes[b'commit'], y, x)
1702
1703 if e in (E_PAGEDOWN, E_PAGEUP, E_LINEDOWN, E_LINEUP):
1704 if e == E_PAGEDOWN:
1705 state.change_view(+1, b'page')
1706 elif e == E_PAGEUP:
1707 state.change_view(-1, b'page')
1708 elif e == E_LINEDOWN:
1709 state.change_view(+1, b'line')
1710 elif e == E_LINEUP:
1711 state.change_view(-1, b'line')
1712
1713 # start rendering
1714 commitwin.erase()
1715 helpwin.erase()
1716 mainwin.erase()
1717 if curmode == MODE_PATCH:
1718 state.render_patch(mainwin)
1719 elif curmode == MODE_HELP:
1720 state.render_string(mainwin, __doc__.strip().splitlines())
1721 else:
1722 state.render_rules(mainwin)
1723 state.render_commit(commitwin)
1724 state.render_help(helpwin)
1725 curses.doupdate()
1726 # done rendering
1727 ch = encoding.strtolocal(stdscr.getkey())
1728
1729
1730 def _chistedit(ui, repo, state, freeargs, opts):
1731 """interactively edit changeset history via a curses interface
1732
1733 Provides a ncurses interface to histedit. Press ? in chistedit mode
1734 to see an extensive help. Requires python-curses to be installed."""
1735
1736 if curses is None:
1737 raise error.Abort(_(b"Python curses library required"))
1738
1739 # disable color
1740 ui._colormode = None
1741
1742 try:
1743 keep = opts.get(b'keep')
1744 revs = opts.get(b'rev', [])[:]
1745 cmdutil.checkunfinished(repo)
1746 scmutil.bail_if_changed(repo)
1747
1748 revs.extend(freeargs)
1749 if not revs:
1750 defaultrev = destutil.desthistedit(ui, repo)
1751 if defaultrev is not None:
1752 revs.append(defaultrev)
1753 if len(revs) != 1:
1754 raise error.InputError(
1755 _(b'histedit requires exactly one ancestor revision')
1756 )
1757
1758 rr = list(repo.set(b'roots(%ld)', logcmdutil.revrange(repo, revs)))
1759 if len(rr) != 1:
1760 raise error.InputError(
1761 _(
1762 b'The specified revisions must have '
1763 b'exactly one common root'
1764 )
1765 )
1766 root = rr[0].node()
1767
1768 topmost = repo.dirstate.p1()
1769 revs = between(repo, root, topmost, keep)
1770 if not revs:
1771 raise error.InputError(
1772 _(b'%s is not an ancestor of working directory') % short(root)
1773 )
1774
1775 rules = []
1776 for i, r in enumerate(revs):
1777 rules.append(histeditrule(ui, repo[r], i))
1778 with util.with_lc_ctype():
1779 rc = curses.wrapper(functools.partial(_chisteditmain, repo, rules))
1780 if rc is False:
1781 ui.write(_(b"histedit aborted\n"))
1782 return 0
1783 if type(rc) is list:
1784 ui.status(_(b"performing changes\n"))
1785 rules = makecommands(rc)
1786 with repo.vfs(b'chistedit', b'w+') as fp:
1787 for r in rules:
1788 fp.write(r)
1789 opts[b'commands'] = fp.name
1790 return _texthistedit(ui, repo, state, freeargs, opts)
1791 except KeyboardInterrupt:
1792 pass
1793 return -1
1794
1795
1796 @command(
1797 b'histedit',
1798 [
1799 (
1800 b'',
1801 b'commands',
1802 b'',
1803 _(b'read history edits from the specified file'),
1804 _(b'FILE'),
1805 ),
1806 (b'c', b'continue', False, _(b'continue an edit already in progress')),
1807 (b'', b'edit-plan', False, _(b'edit remaining actions list')),
1808 (
1809 b'k',
1810 b'keep',
1811 False,
1812 _(b"don't strip old nodes after edit is complete"),
1813 ),
1814 (b'', b'abort', False, _(b'abort an edit in progress')),
1815 (b'o', b'outgoing', False, _(b'changesets not found in destination')),
1816 (
1817 b'f',
1818 b'force',
1819 False,
1820 _(b'force outgoing even for unrelated repositories'),
1821 ),
1822 (b'r', b'rev', [], _(b'first revision to be edited'), _(b'REV')),
1823 ]
1824 + cmdutil.formatteropts,
1825 _(b"[OPTIONS] ([ANCESTOR] | --outgoing [URL])"),
1826 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
1827 )
1828 def histedit(ui, repo, *freeargs, **opts):
1829 """interactively edit changeset history
1830
1831 This command lets you edit a linear series of changesets (up to
1832 and including the working directory, which should be clean).
1833 You can:
1834
1835 - `pick` to [re]order a changeset
1836
1837 - `drop` to omit changeset
1838
1839 - `mess` to reword the changeset commit message
1840
1841 - `fold` to combine it with the preceding changeset (using the later date)
1842
1843 - `roll` like fold, but discarding this commit's description and date
1844
1845 - `edit` to edit this changeset (preserving date)
1846
1847 - `base` to checkout changeset and apply further changesets from there
1848
1849 There are a number of ways to select the root changeset:
1850
1851 - Specify ANCESTOR directly
1852
1853 - Use --outgoing -- it will be the first linear changeset not
1854 included in destination. (See :hg:`help config.paths.default-push`)
1855
1856 - Otherwise, the value from the "histedit.defaultrev" config option
1857 is used as a revset to select the base revision when ANCESTOR is not
1858 specified. The first revision returned by the revset is used. By
1859 default, this selects the editable history that is unique to the
1860 ancestry of the working directory.
1861
1862 .. container:: verbose
1863
1864 If you use --outgoing, this command will abort if there are ambiguous
1865 outgoing revisions. For example, if there are multiple branches
1866 containing outgoing revisions.
1867
1868 Use "min(outgoing() and ::.)" or similar revset specification
1869 instead of --outgoing to specify edit target revision exactly in
1870 such ambiguous situation. See :hg:`help revsets` for detail about
1871 selecting revisions.
1872
1873 .. container:: verbose
1874
1875 Examples:
1876
1877 - A number of changes have been made.
1878 Revision 3 is no longer needed.
1879
1880 Start history editing from revision 3::
1881
1882 hg histedit -r 3
1883
1884 An editor opens, containing the list of revisions,
1885 with specific actions specified::
1886
1887 pick 5339bf82f0ca 3 Zworgle the foobar
1888 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1889 pick 0a9639fcda9d 5 Morgify the cromulancy
1890
1891 Additional information about the possible actions
1892 to take appears below the list of revisions.
1893
1894 To remove revision 3 from the history,
1895 its action (at the beginning of the relevant line)
1896 is changed to 'drop'::
1897
1898 drop 5339bf82f0ca 3 Zworgle the foobar
1899 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1900 pick 0a9639fcda9d 5 Morgify the cromulancy
1901
1902 - A number of changes have been made.
1903 Revision 2 and 4 need to be swapped.
1904
1905 Start history editing from revision 2::
1906
1907 hg histedit -r 2
1908
1909 An editor opens, containing the list of revisions,
1910 with specific actions specified::
1911
1912 pick 252a1af424ad 2 Blorb a morgwazzle
1913 pick 5339bf82f0ca 3 Zworgle the foobar
1914 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1915
1916 To swap revision 2 and 4, its lines are swapped
1917 in the editor::
1918
1919 pick 8ef592ce7cc4 4 Bedazzle the zerlog
1920 pick 5339bf82f0ca 3 Zworgle the foobar
1921 pick 252a1af424ad 2 Blorb a morgwazzle
1922
1923 Returns 0 on success, 1 if user intervention is required (not only
1924 for intentional "edit" command, but also for resolving unexpected
1925 conflicts).
1926 """
1927 opts = pycompat.byteskwargs(opts)
1928
1929 state = histeditstate(repo)
1930 with repo.wlock() as wlock, repo.lock() as lock:
1931 state.wlock = wlock
1932 state.lock = lock
1933 # kludge: _chistedit only works for starting an edit, not aborting
1934 # or continuing, so fall back to regular _texthistedit for those
1935 # operations.
1936 if ui.interface(b'histedit') == b'curses' and _getgoal(opts) == goalnew:
1937 return _chistedit(ui, repo, state, freeargs, opts)
1938 return _texthistedit(ui, repo, state, freeargs, opts)
1939
1940
1941 def _texthistedit(ui, repo, state, freeargs, opts):
1942 _histedit(ui, repo, state, freeargs, opts)
1943
1944
1945 goalcontinue = b'continue'
1946 goalabort = b'abort'
1947 goaleditplan = b'edit-plan'
1948 goalnew = b'new'
1949
1950
1951 def _getgoal(opts):
1952 if opts.get(b'continue'):
1953 return goalcontinue
1954 if opts.get(b'abort'):
1955 return goalabort
1956 if opts.get(b'edit_plan'):
1957 return goaleditplan
1958 return goalnew
1959
1960
1961 def _readfile(ui, path):
1962 if path == b'-':
1963 with ui.timeblockedsection(b'histedit'):
1964 return ui.fin.read()
1965 else:
1966 return util.readfile(path)
1967
1968
1969 def _validateargs(ui, repo, freeargs, opts, goal, rules, revs):
1970 # TODO only abort if we try to histedit mq patches, not just
1971 # blanket if mq patches are applied somewhere
1972 mq = getattr(repo, 'mq', None)
1973 if mq and mq.applied:
1974 raise error.StateError(_(b'source has mq patches applied'))
1975
1976 # basic argument incompatibility processing
1977 outg = opts.get(b'outgoing')
1978 editplan = opts.get(b'edit_plan')
1979 abort = opts.get(b'abort')
1980 force = opts.get(b'force')
1981 if force and not outg:
1982 raise error.InputError(_(b'--force only allowed with --outgoing'))
1983 if goal == b'continue':
1984 if any((outg, abort, revs, freeargs, rules, editplan)):
1985 raise error.InputError(_(b'no arguments allowed with --continue'))
1986 elif goal == b'abort':
1987 if any((outg, revs, freeargs, rules, editplan)):
1988 raise error.InputError(_(b'no arguments allowed with --abort'))
1989 elif goal == b'edit-plan':
1990 if any((outg, revs, freeargs)):
1991 raise error.InputError(
1992 _(b'only --commands argument allowed with --edit-plan')
1993 )
1994 else:
1995 if outg:
1996 if revs:
1997 raise error.InputError(
1998 _(b'no revisions allowed with --outgoing')
1999 )
2000 if len(freeargs) > 1:
2001 raise error.InputError(
2002 _(b'only one repo argument allowed with --outgoing')
2003 )
2004 else:
2005 revs.extend(freeargs)
2006 if len(revs) == 0:
2007 defaultrev = destutil.desthistedit(ui, repo)
2008 if defaultrev is not None:
2009 revs.append(defaultrev)
2010
2011 if len(revs) != 1:
2012 raise error.InputError(
2013 _(b'histedit requires exactly one ancestor revision')
2014 )
2015
2016
2017 def _histedit(ui, repo, state, freeargs, opts):
2018 fm = ui.formatter(b'histedit', opts)
2019 fm.startitem()
2020 goal = _getgoal(opts)
2021 revs = opts.get(b'rev', [])
2022 nobackup = not ui.configbool(b'rewrite', b'backup-bundle')
2023 rules = opts.get(b'commands', b'')
2024 state.keep = opts.get(b'keep', False)
2025
2026 _validateargs(ui, repo, freeargs, opts, goal, rules, revs)
2027
2028 hastags = False
2029 if revs:
2030 revs = logcmdutil.revrange(repo, revs)
2031 ctxs = [repo[rev] for rev in revs]
2032 for ctx in ctxs:
2033 tags = [tag for tag in ctx.tags() if tag != b'tip']
2034 if not hastags:
2035 hastags = len(tags)
2036 if hastags:
2037 if ui.promptchoice(
2038 _(
2039 b'warning: tags associated with the given'
2040 b' changeset will be lost after histedit.\n'
2041 b'do you want to continue (yN)? $$ &Yes $$ &No'
2042 ),
2043 default=1,
2044 ):
2045 raise error.CanceledError(_(b'histedit cancelled\n'))
2046 # rebuild state
2047 if goal == goalcontinue:
2048 state.read()
2049 state = bootstrapcontinue(ui, state, opts)
2050 elif goal == goaleditplan:
2051 _edithisteditplan(ui, repo, state, rules)
2052 return
2053 elif goal == goalabort:
2054 _aborthistedit(ui, repo, state, nobackup=nobackup)
2055 return
2056 else:
2057 # goal == goalnew
2058 _newhistedit(ui, repo, state, revs, freeargs, opts)
2059
2060 _continuehistedit(ui, repo, state)
2061 _finishhistedit(ui, repo, state, fm)
2062 fm.end()
2063
2064
2065 def _continuehistedit(ui, repo, state):
2066 """This function runs after either:
2067 - bootstrapcontinue (if the goal is 'continue')
2068 - _newhistedit (if the goal is 'new')
2069 """
2070 # preprocess rules so that we can hide inner folds from the user
2071 # and only show one editor
2072 actions = state.actions[:]
2073 for idx, (action, nextact) in enumerate(zip(actions, actions[1:] + [None])):
2074 if action.verb == b'fold' and nextact and nextact.verb == b'fold':
2075 state.actions[idx].__class__ = _multifold
2076
2077 # Force an initial state file write, so the user can run --abort/continue
2078 # even if there's an exception before the first transaction serialize.
2079 state.write()
2080
2081 tr = None
2082 # Don't use singletransaction by default since it rolls the entire
2083 # transaction back if an unexpected exception happens (like a
2084 # pretxncommit hook throws, or the user aborts the commit msg editor).
2085 if ui.configbool(b"histedit", b"singletransaction"):
2086 # Don't use a 'with' for the transaction, since actions may close
2087 # and reopen a transaction. For example, if the action executes an
2088 # external process it may choose to commit the transaction first.
2089 tr = repo.transaction(b'histedit')
2090 progress = ui.makeprogress(
2091 _(b"editing"), unit=_(b'changes'), total=len(state.actions)
2092 )
2093 with progress, util.acceptintervention(tr):
2094 while state.actions:
2095 state.write(tr=tr)
2096 actobj = state.actions[0]
2097 progress.increment(item=actobj.torule())
2098 ui.debug(
2099 b'histedit: processing %s %s\n' % (actobj.verb, actobj.torule())
2100 )
2101 parentctx, replacement_ = actobj.run()
2102 state.parentctxnode = parentctx.node()
2103 state.replacements.extend(replacement_)
2104 state.actions.pop(0)
2105
2106 state.write()
2107
2108
2109 def _finishhistedit(ui, repo, state, fm):
2110 """This action runs when histedit is finishing its session"""
2111 mergemod.update(repo[state.parentctxnode])
2112
2113 mapping, tmpnodes, created, ntm = processreplacement(state)
2114 if mapping:
2115 for prec, succs in mapping.items():
2116 if not succs:
2117 ui.debug(b'histedit: %s is dropped\n' % short(prec))
2118 else:
2119 ui.debug(
2120 b'histedit: %s is replaced by %s\n'
2121 % (short(prec), short(succs[0]))
2122 )
2123 if len(succs) > 1:
2124 m = b'histedit: %s'
2125 for n in succs[1:]:
2126 ui.debug(m % short(n))
2127
2128 if not state.keep:
2129 if mapping:
2130 movetopmostbookmarks(repo, state.topmost, ntm)
2131 # TODO update mq state
2132 else:
2133 mapping = {}
2134
2135 for n in tmpnodes:
2136 if n in repo:
2137 mapping[n] = ()
2138
2139 # remove entries about unknown nodes
2140 has_node = repo.unfiltered().changelog.index.has_node
2141 mapping = {
2142 k: v
2143 for k, v in mapping.items()
2144 if has_node(k) and all(has_node(n) for n in v)
2145 }
2146 cmdutil.cleanup_nodes(repo, mapping, b'histedit')
2147 hf = fm.hexfunc
2148 fl = fm.formatlist
2149 fd = fm.formatdict
2150 nodechanges = fd(
2151 {
2152 hf(oldn): fl([hf(n) for n in newn], name=b'node')
2153 for oldn, newn in mapping.items()
2154 },
2155 key=b"oldnode",
2156 value=b"newnodes",
2157 )
2158 fm.data(nodechanges=nodechanges)
2159
2160 state.clear()
2161 if os.path.exists(repo.sjoin(b'undo')):
2162 os.unlink(repo.sjoin(b'undo'))
2163 if repo.vfs.exists(b'histedit-last-edit.txt'):
2164 repo.vfs.unlink(b'histedit-last-edit.txt')
2165
2166
2167 def _aborthistedit(ui, repo, state, nobackup=False):
2168 try:
2169 state.read()
2170 __, leafs, tmpnodes, __ = processreplacement(state)
2171 ui.debug(b'restore wc to old parent %s\n' % short(state.topmost))
2172
2173 # Recover our old commits if necessary
2174 if not state.topmost in repo and state.backupfile:
2175 backupfile = repo.vfs.join(state.backupfile)
2176 f = scmutil.open_path(ui, backupfile)
2177 gen = exchange.readbundle(ui, f, backupfile)
2178 with repo.transaction(b'histedit.abort') as tr:
2179 bundle2.applybundle(
2180 repo,
2181 gen,
2182 tr,
2183 source=b'histedit',
2184 url=b'bundle:' + backupfile,
2185 )
2186
2187 os.remove(backupfile)
2188
2189 # check whether we should update away
2190 if repo.unfiltered().revs(
2191 b'parents() and (%n or %ln::)',
2192 state.parentctxnode,
2193 leafs | tmpnodes,
2194 ):
2195 up_impl.clean(repo, state.topmost, show_stats=True, quietempty=True)
2196 cleanupnode(ui, repo, tmpnodes, nobackup=nobackup)
2197 cleanupnode(ui, repo, leafs, nobackup=nobackup)
2198 except Exception:
2199 if state.inprogress():
2200 ui.warn(
2201 _(
2202 b'warning: encountered an exception during histedit '
2203 b'--abort; the repository may not have been completely '
2204 b'cleaned up\n'
2205 )
2206 )
2207 raise
2208 finally:
2209 state.clear()
2210
2211
2212 def hgaborthistedit(ui, repo):
2213 state = histeditstate(repo)
2214 nobackup = not ui.configbool(b'rewrite', b'backup-bundle')
2215 with repo.wlock() as wlock, repo.lock() as lock:
2216 state.wlock = wlock
2217 state.lock = lock
2218 _aborthistedit(ui, repo, state, nobackup=nobackup)
2219
2220
2221 def _edithisteditplan(ui, repo, state, rules):
2222 state.read()
2223 if not rules:
2224 comment = geteditcomment(
2225 ui, short(state.parentctxnode), short(state.topmost)
2226 )
2227 rules = ruleeditor(repo, ui, state.actions, comment)
2228 else:
2229 rules = _readfile(ui, rules)
2230 actions = parserules(rules, state)
2231 ctxs = [repo[act.node] for act in state.actions if act.node]
2232 warnverifyactions(ui, repo, actions, state, ctxs)
2233 state.actions = actions
2234 state.write()
2235
2236
2237 def _newhistedit(ui, repo, state, revs, freeargs, opts):
2238 outg = opts.get(b'outgoing')
2239 rules = opts.get(b'commands', b'')
2240 force = opts.get(b'force')
2241
2242 cmdutil.checkunfinished(repo)
2243 scmutil.bail_if_changed(repo)
2244
2245 topmost = repo.dirstate.p1()
2246 if outg:
2247 if freeargs:
2248 remote = freeargs[0]
2249 else:
2250 remote = None
2251 root = findoutgoing(ui, repo, remote, force, opts)
2252 else:
2253 rr = list(repo.set(b'roots(%ld)', logcmdutil.revrange(repo, revs)))
2254 if len(rr) != 1:
2255 raise error.InputError(
2256 _(
2257 b'The specified revisions must have '
2258 b'exactly one common root'
2259 )
2260 )
2261 root = rr[0].node()
2262
2263 revs = between(repo, root, topmost, state.keep)
2264 if not revs:
2265 raise error.InputError(
2266 _(b'%s is not an ancestor of working directory') % short(root)
2267 )
2268
2269 ctxs = [repo[r] for r in revs]
2270
2271 wctx = repo[None]
2272 # Please don't ask me why `ancestors` is this value. I figured it
2273 # out with print-debugging, not by actually understanding what the
2274 # merge code is doing. :(
2275 ancs = [repo[b'.']]
2276 # Sniff-test to make sure we won't collide with untracked files in
2277 # the working directory. If we don't do this, we can get a
2278 # collision after we've started histedit and backing out gets ugly
2279 # for everyone, especially the user.
2280 for c in [ctxs[0].p1()] + ctxs:
2281 try:
2282 mergemod.calculateupdates(
2283 repo,
2284 wctx,
2285 c,
2286 ancs,
2287 # These parameters were determined by print-debugging
2288 # what happens later on inside histedit.
2289 branchmerge=False,
2290 force=False,
2291 acceptremote=False,
2292 followcopies=False,
2293 )
2294 except error.Abort:
2295 raise error.StateError(
2296 _(
2297 b"untracked files in working directory conflict with files in %s"
2298 )
2299 % c
2300 )
2301
2302 if not rules:
2303 comment = geteditcomment(ui, short(root), short(topmost))
2304 actions = [pick(state, r) for r in revs]
2305 rules = ruleeditor(repo, ui, actions, comment)
2306 else:
2307 rules = _readfile(ui, rules)
2308 actions = parserules(rules, state)
2309 warnverifyactions(ui, repo, actions, state, ctxs)
2310
2311 parentctxnode = repo[root].p1().node()
2312
2313 state.parentctxnode = parentctxnode
2314 state.actions = actions
2315 state.topmost = topmost
2316 state.replacements = []
2317
2318 ui.log(
2319 b"histedit",
2320 b"%d actions to histedit\n",
2321 len(actions),
2322 histedit_num_actions=len(actions),
2323 )
2324
2325 # Create a backup so we can always abort completely.
2326 backupfile = None
2327 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2328 backupfile = repair.backupbundle(
2329 repo, [parentctxnode], [topmost], root, b'histedit'
2330 )
2331 state.backupfile = backupfile
2332
2333
2334 def _getsummary(ctx):
2335 return stringutil.firstline(ctx.description())
2336
2337
2338 def bootstrapcontinue(ui, state, opts):
2339 repo = state.repo
2340
2341 ms = mergestatemod.mergestate.read(repo)
2342 mergeutil.checkunresolved(ms)
2343
2344 if state.actions:
2345 actobj = state.actions.pop(0)
2346
2347 if _isdirtywc(repo):
2348 actobj.continuedirty()
2349 if _isdirtywc(repo):
2350 abortdirty()
2351
2352 parentctx, replacements = actobj.continueclean()
2353
2354 state.parentctxnode = parentctx.node()
2355 state.replacements.extend(replacements)
2356
2357 return state
2358
2359
2360 def hgcontinuehistedit(ui, repo):
2361 fm = ui.formatter(b'continue', {})
2362 fm.startitem()
2363
2364 state = histeditstate(repo)
2365 with repo.wlock() as wlock, repo.lock() as lock:
2366 state.wlock = wlock
2367 state.lock = lock
2368 state.read()
2369 state = bootstrapcontinue(ui, state, None)
2370 _continuehistedit(ui, repo, state)
2371 _finishhistedit(ui, repo, state, fm)
2372 fm.end()
2373
2374
2375 def between(repo, old, new, keep):
2376 """select and validate the set of revision to edit
2377
2378 When keep is false, the specified set can't have children."""
2379 revs = repo.revs(b'%n::%n', old, new)
2380 if revs and not keep:
2381 rewriteutil.precheck(repo, revs, b'edit')
2382 if repo.revs(b'(%ld) and merge()', revs):
2383 raise error.StateError(
2384 _(b'cannot edit history that contains merges')
2385 )
2386 return pycompat.maplist(repo.changelog.node, revs)
2387
2388
2389 def ruleeditor(repo, ui, actions, editcomment=b""):
2390 """open an editor to edit rules
2391
2392 rules are in the format [ [act, ctx], ...] like in state.rules
2393 """
2394 if repo.ui.configbool(b"experimental", b"histedit.autoverb"):
2395 newact = util.sortdict()
2396 for act in actions:
2397 ctx = repo[act.node]
2398 summary = _getsummary(ctx)
2399 fword = summary.split(b' ', 1)[0].lower()
2400 added = False
2401
2402 # if it doesn't end with the special character '!' just skip this
2403 if fword.endswith(b'!'):
2404 fword = fword[:-1]
2405 if fword in primaryactions | secondaryactions | tertiaryactions:
2406 act.verb = fword
2407 # get the target summary
2408 tsum = summary[len(fword) + 1 :].lstrip()
2409 # safe but slow: reverse iterate over the actions so we
2410 # don't clash on two commits having the same summary
2411 for na, l in reversed(list(newact.items())):
2412 actx = repo[na.node]
2413 asum = _getsummary(actx)
2414 if asum == tsum:
2415 added = True
2416 l.append(act)
2417 break
2418
2419 if not added:
2420 newact[act] = []
2421
2422 # copy over and flatten the new list
2423 actions = []
2424 for na, l in newact.items():
2425 actions.append(na)
2426 actions += l
2427
2428 rules = b'\n'.join([act.torule() for act in actions])
2429 rules += b'\n\n'
2430 rules += editcomment
2431 rules = ui.edit(
2432 rules,
2433 ui.username(),
2434 {b'prefix': b'histedit'},
2435 repopath=repo.path,
2436 action=b'histedit',
2437 )
2438
2439 # Save edit rules in .hg/histedit-last-edit.txt in case
2440 # the user needs to ask for help after something
2441 # surprising happens.
2442 with repo.vfs(b'histedit-last-edit.txt', b'wb') as f:
2443 f.write(rules)
2444
2445 return rules
2446
2447
2448 def parserules(rules, state):
2449 """Read the histedit rules string and return list of action objects"""
2450 rules = [
2451 l
2452 for l in (r.strip() for r in rules.splitlines())
2453 if l and not l.startswith(b'#')
2454 ]
2455 actions = []
2456 for r in rules:
2457 if b' ' not in r:
2458 raise error.ParseError(_(b'malformed line "%s"') % r)
2459 verb, rest = r.split(b' ', 1)
2460
2461 if verb not in actiontable:
2462 raise error.ParseError(_(b'unknown action "%s"') % verb)
2463
2464 action = actiontable[verb].fromrule(state, rest)
2465 actions.append(action)
2466 return actions
2467
2468
2469 def warnverifyactions(ui, repo, actions, state, ctxs):
2470 try:
2471 verifyactions(actions, state, ctxs)
2472 except error.ParseError:
2473 if repo.vfs.exists(b'histedit-last-edit.txt'):
2474 ui.warn(
2475 _(
2476 b'warning: histedit rules saved '
2477 b'to: .hg/histedit-last-edit.txt\n'
2478 )
2479 )
2480 raise
2481
2482
2483 def verifyactions(actions, state, ctxs):
2484 """Verify that there exists exactly one action per given changeset and
2485 other constraints.
2486
2487 Will abort if there are to many or too few rules, a malformed rule,
2488 or a rule on a changeset outside of the user-given range.
2489 """
2490 expected = {c.node() for c in ctxs}
2491 seen = set()
2492 prev = None
2493
2494 if actions and actions[0].verb in [b'roll', b'fold']:
2495 raise error.ParseError(
2496 _(b'first changeset cannot use verb "%s"') % actions[0].verb
2497 )
2498
2499 for action in actions:
2500 action.verify(prev, expected, seen)
2501 prev = action
2502 if action.node is not None:
2503 seen.add(action.node)
2504 missing = sorted(expected - seen) # sort to stabilize output
2505
2506 if state.repo.ui.configbool(b'histedit', b'dropmissing'):
2507 if len(actions) == 0:
2508 raise error.ParseError(
2509 _(b'no rules provided'),
2510 hint=_(b'use strip extension to remove commits'),
2511 )
2512
2513 drops = [drop(state, n) for n in missing]
2514 # put the in the beginning so they execute immediately and
2515 # don't show in the edit-plan in the future
2516 actions[:0] = drops
2517 elif missing:
2518 raise error.ParseError(
2519 _(b'missing rules for changeset %s') % short(missing[0]),
2520 hint=_(
2521 b'use "drop %s" to discard, see also: '
2522 b"'hg help -e histedit.config'"
2523 )
2524 % short(missing[0]),
2525 )
2526
2527
2528 def adjustreplacementsfrommarkers(repo, oldreplacements):
2529 """Adjust replacements from obsolescence markers
2530
2531 Replacements structure is originally generated based on
2532 histedit's state and does not account for changes that are
2533 not recorded there. This function fixes that by adding
2534 data read from obsolescence markers"""
2535 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
2536 return oldreplacements
2537
2538 unfi = repo.unfiltered()
2539 get_rev = unfi.changelog.index.get_rev
2540 obsstore = repo.obsstore
2541 newreplacements = list(oldreplacements)
2542 oldsuccs = [r[1] for r in oldreplacements]
2543 # successors that have already been added to succstocheck once
2544 seensuccs = set().union(
2545 *oldsuccs
2546 ) # create a set from an iterable of tuples
2547 succstocheck = list(seensuccs)
2548 while succstocheck:
2549 n = succstocheck.pop()
2550 missing = get_rev(n) is None
2551 markers = obsstore.successors.get(n, ())
2552 if missing and not markers:
2553 # dead end, mark it as such
2554 newreplacements.append((n, ()))
2555 for marker in markers:
2556 nsuccs = marker[1]
2557 newreplacements.append((n, nsuccs))
2558 for nsucc in nsuccs:
2559 if nsucc not in seensuccs:
2560 seensuccs.add(nsucc)
2561 succstocheck.append(nsucc)
2562
2563 return newreplacements
2564
2565
2566 def processreplacement(state):
2567 """process the list of replacements to return
2568
2569 1) the final mapping between original and created nodes
2570 2) the list of temporary node created by histedit
2571 3) the list of new commit created by histedit"""
2572 replacements = adjustreplacementsfrommarkers(state.repo, state.replacements)
2573 allsuccs = set()
2574 replaced = set()
2575 fullmapping = {}
2576 # initialize basic set
2577 # fullmapping records all operations recorded in replacement
2578 for rep in replacements:
2579 allsuccs.update(rep[1])
2580 replaced.add(rep[0])
2581 fullmapping.setdefault(rep[0], set()).update(rep[1])
2582 new = allsuccs - replaced
2583 tmpnodes = allsuccs & replaced
2584 # Reduce content fullmapping into direct relation between original nodes
2585 # and final node created during history edition
2586 # Dropped changeset are replaced by an empty list
2587 toproceed = set(fullmapping)
2588 final = {}
2589 while toproceed:
2590 for x in list(toproceed):
2591 succs = fullmapping[x]
2592 for s in list(succs):
2593 if s in toproceed:
2594 # non final node with unknown closure
2595 # We can't process this now
2596 break
2597 elif s in final:
2598 # non final node, replace with closure
2599 succs.remove(s)
2600 succs.update(final[s])
2601 else:
2602 final[x] = succs
2603 toproceed.remove(x)
2604 # remove tmpnodes from final mapping
2605 for n in tmpnodes:
2606 del final[n]
2607 # we expect all changes involved in final to exist in the repo
2608 # turn `final` into list (topologically sorted)
2609 get_rev = state.repo.changelog.index.get_rev
2610 for prec, succs in final.items():
2611 final[prec] = sorted(succs, key=get_rev)
2612
2613 # computed topmost element (necessary for bookmark)
2614 if new:
2615 newtopmost = sorted(new, key=state.repo.changelog.rev)[-1]
2616 elif not final:
2617 # Nothing rewritten at all. we won't need `newtopmost`
2618 # It is the same as `oldtopmost` and `processreplacement` know it
2619 newtopmost = None
2620 else:
2621 # every body died. The newtopmost is the parent of the root.
2622 r = state.repo.changelog.rev
2623 newtopmost = state.repo[sorted(final, key=r)[0]].p1().node()
2624
2625 return final, tmpnodes, new, newtopmost
2626
2627
2628 def movetopmostbookmarks(repo, oldtopmost, newtopmost):
2629 """Move bookmark from oldtopmost to newly created topmost
2630
2631 This is arguably a feature and we may only want that for the active
2632 bookmark. But the behavior is kept compatible with the old version for now.
2633 """
2634 if not oldtopmost or not newtopmost:
2635 return
2636 oldbmarks = repo.nodebookmarks(oldtopmost)
2637 if oldbmarks:
2638 with repo.lock(), repo.transaction(b'histedit') as tr:
2639 marks = repo._bookmarks
2640 changes = []
2641 for name in oldbmarks:
2642 changes.append((name, newtopmost))
2643 marks.applychanges(repo, tr, changes)
2644
2645
2646 def cleanupnode(ui, repo, nodes, nobackup=False):
2647 """strip a group of nodes from the repository
2648
2649 The set of node to strip may contains unknown nodes."""
2650 with repo.lock():
2651 # do not let filtering get in the way of the cleanse
2652 # we should probably get rid of obsolescence marker created during the
2653 # histedit, but we currently do not have such information.
2654 repo = repo.unfiltered()
2655 # Find all nodes that need to be stripped
2656 # (we use %lr instead of %ln to silently ignore unknown items)
2657 has_node = repo.changelog.index.has_node
2658 nodes = sorted(n for n in nodes if has_node(n))
2659 roots = [c.node() for c in repo.set(b"roots(%ln)", nodes)]
2660 if roots:
2661 backup = not nobackup
2662 repair.strip(ui, repo, roots, backup=backup)
2663
2664
2665 def stripwrapper(orig, ui, repo, nodelist, *args, **kwargs):
2666 if isinstance(nodelist, bytes):
2667 nodelist = [nodelist]
2668 state = histeditstate(repo)
2669 if state.inprogress():
2670 state.read()
2671 histedit_nodes = {
2672 action.node for action in state.actions if action.node
2673 }
2674 common_nodes = histedit_nodes & set(nodelist)
2675 if common_nodes:
2676 raise error.Abort(
2677 _(b"histedit in progress, can't strip %s")
2678 % b', '.join(short(x) for x in common_nodes)
2679 )
2680 return orig(ui, repo, nodelist, *args, **kwargs)
2681
2682
2683 extensions.wrapfunction(repair, 'strip', stripwrapper)
2684
2685
2686 def summaryhook(ui, repo):
2687 state = histeditstate(repo)
2688 if not state.inprogress():
2689 return
2690 state.read()
2691 if state.actions:
2692 # i18n: column positioning for "hg summary"
2693 ui.write(
2694 _(b'hist: %s (histedit --continue)\n')
2695 % (
2696 ui.label(_(b'%d remaining'), b'histedit.remaining')
2697 % len(state.actions)
2698 )
2699 )
2700
2701
2702 def extsetup(ui):
2703 cmdutil.summaryhooks.add(b'histedit', summaryhook)
2704 statemod.addunfinished(
2705 b'histedit',
2706 fname=b'histedit-state',
2707 allowcommit=True,
2708 continueflag=True,
2709 abortfunc=hgaborthistedit,
2710 continuefunc=hgcontinuehistedit,
2711 )