histedit.py
2682 lines
| 85.6 KiB
| text/x-python
|
PythonLexer
/ hgext / histedit.py
|
r17064 | # histedit.py - interactive history editing for mercurial | ||
# | ||||
# Copyright 2009 Augie Fackler <raf@durin42.com> | ||||
# | ||||
# This software may be used and distributed according to the terms of the | ||||
# GNU General Public License version 2 or any later version. | ||||
|
r17131 | """interactive history editing | ||
With this extension installed, Mercurial gains one new command: histedit. Usage | ||||
is as follows, assuming the following history:: | ||||
@ 3[tip] 7c2fd3b9020c 2009-04-27 18:04 -0500 durin42 | ||||
| Add delta | ||||
| | ||||
o 2 030b686bedc4 2009-04-27 18:04 -0500 durin42 | ||||
| Add gamma | ||||
| | ||||
o 1 c561b4e977df 2009-04-27 18:04 -0500 durin42 | ||||
| Add beta | ||||
| | ||||
o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42 | ||||
Add alpha | ||||
If you were to run ``hg histedit c561b4e977df``, you would see the following | ||||
file open in your editor:: | ||||
pick c561b4e977df Add beta | ||||
pick 030b686bedc4 Add gamma | ||||
pick 7c2fd3b9020c Add delta | ||||
|
r18322 | # Edit history between c561b4e977df and 7c2fd3b9020c | ||
|
r17131 | # | ||
|
r20503 | # Commits are listed from least to most recent | ||
# | ||||
|
r17131 | # Commands: | ||
# p, pick = use commit | ||||
|
r46720 | # e, edit = use commit, but allow edits before making new commit | ||
|
r20511 | # f, fold = use commit, but combine it with the one above | ||
|
r31056 | # r, roll = like fold, but discard this commit's description and date | ||
|
r17131 | # d, drop = remove commit from history | ||
|
r26100 | # m, mess = edit commit message without changing commit content | ||
|
r34490 | # b, base = checkout changeset and apply further changesets from there | ||
|
r17131 | # | ||
In this file, lines beginning with ``#`` are ignored. You must specify a rule | ||||
for each revision in your history. For example, if you had meant to add gamma | ||||
before beta, and then wanted to add delta in the same revision as beta, you | ||||
would reorganize the file to look like this:: | ||||
pick 030b686bedc4 Add gamma | ||||
pick c561b4e977df Add beta | ||||
fold 7c2fd3b9020c Add delta | ||||
|
r18322 | # Edit history between c561b4e977df and 7c2fd3b9020c | ||
|
r17131 | # | ||
|
r20503 | # Commits are listed from least to most recent | ||
# | ||||
|
r17131 | # Commands: | ||
# p, pick = use commit | ||||
|
r46720 | # e, edit = use commit, but allow edits before making new commit | ||
|
r20511 | # f, fold = use commit, but combine it with the one above | ||
|
r31056 | # r, roll = like fold, but discard this commit's description and date | ||
|
r17131 | # d, drop = remove commit from history | ||
|
r26100 | # m, mess = edit commit message without changing commit content | ||
|
r34490 | # b, base = checkout changeset and apply further changesets from there | ||
|
r17131 | # | ||
At which point you close the editor and ``histedit`` starts working. When you | ||||
specify a ``fold`` operation, ``histedit`` will open an editor when it folds | ||||
those revisions together, offering you a chance to clean up the commit message:: | ||||
Add beta | ||||
*** | ||||
Add delta | ||||
|
r17064 | |||
|
r31055 | Edit the commit message to your liking, then close the editor. The date used | ||
for the commit will be the later of the two commits' dates. For this example, | ||||
let's assume that the commit message was changed to ``Add beta and delta.`` | ||||
After histedit has run and had a chance to remove any old or temporary | ||||
revisions it needed, the history looks like this:: | ||||
|
r17131 | |||
@ 2[tip] 989b4d060121 2009-04-27 18:04 -0500 durin42 | ||||
| Add beta and delta. | ||||
| | ||||
o 1 081603921c3f 2009-04-27 18:04 -0500 durin42 | ||||
| Add gamma | ||||
| | ||||
o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42 | ||||
Add alpha | ||||
Note that ``histedit`` does *not* remove any revisions (even its own temporary | ||||
ones) until after it has completed all the editing operations, so it will | ||||
probably perform several strip operations when it's done. For the above example, | ||||
it had to run strip twice. Strip can be slow depending on a variety of factors, | ||||
so you might need to be a little patient. You can choose to keep the original | ||||
revisions by passing the ``--keep`` flag. | ||||
The ``edit`` operation will drop you back to a command prompt, | ||||
allowing you to edit files freely, or even use ``hg record`` to commit | ||||
some changes as a separate commit. When you're done, any remaining | ||||
uncommitted changes will be committed as well. When done, run ``hg | ||||
|
r31055 | histedit --continue`` to finish this step. If there are uncommitted | ||
changes, you'll be prompted for a new commit message, but the default | ||||
commit message will be the original message for the ``edit`` ed | ||||
revision, and the date of the original commit will be preserved. | ||||
|
r17131 | |||
The ``message`` operation will give you a chance to revise a commit | ||||
message without changing the contents. It's a shortcut for doing | ||||
``edit`` immediately followed by `hg histedit --continue``. | ||||
If ``histedit`` encounters a conflict when moving a revision (while | ||||
handling ``pick`` or ``fold``), it'll stop in a similar manner to | ||||
``edit`` with the difference that it won't prompt you for a commit | ||||
message when done. If you decide at this point that you don't like how | ||||
much work it will be to rearrange history, or that you made a mistake, | ||||
you can use ``hg histedit --abort`` to abandon the new changes you | ||||
have made and return to the state before you attempted to edit your | ||||
history. | ||||
|
r18323 | If we clone the histedit-ed example repository above and add four more | ||
changes, such that we have the following history:: | ||||
|
r17131 | |||
@ 6[tip] 038383181893 2009-04-27 18:04 -0500 stefan | ||||
| Add theta | ||||
| | ||||
o 5 140988835471 2009-04-27 18:04 -0500 stefan | ||||
| Add eta | ||||
| | ||||
o 4 122930637314 2009-04-27 18:04 -0500 stefan | ||||
| Add zeta | ||||
| | ||||
o 3 836302820282 2009-04-27 18:04 -0500 stefan | ||||
| Add epsilon | ||||
| | ||||
o 2 989b4d060121 2009-04-27 18:04 -0500 durin42 | ||||
| Add beta and delta. | ||||
| | ||||
o 1 081603921c3f 2009-04-27 18:04 -0500 durin42 | ||||
| Add gamma | ||||
| | ||||
o 0 d8d2fcd0e319 2009-04-27 18:04 -0500 durin42 | ||||
Add alpha | ||||
If you run ``hg histedit --outgoing`` on the clone then it is the same | ||||
as running ``hg histedit 836302820282``. If you need plan to push to a | ||||
repository that Mercurial does not detect to be related to the source | ||||
repo, you can add a ``--force`` option. | ||||
|
r24199 | |||
|
r27414 | Config | ||
------ | ||||
|
r24199 | Histedit rule lines are truncated to 80 characters by default. You | ||
|
r26171 | can customize this behavior by setting a different length in your | ||
|
r24869 | configuration file:: | ||
|
r24199 | |||
|
r24869 | [histedit] | ||
linelen = 120 # truncate rule lines at 120 characters | ||||
|
r27262 | |||
|
r41650 | The summary of a change can be customized as well:: | ||
[histedit] | ||||
summary-template = '{rev} {bookmarks} {desc|firstline}' | ||||
The customized summary should be kept short enough that rule lines | ||||
will fit in the configured line length. See above if that requires | ||||
customization. | ||||
|
r27262 | ``hg histedit`` attempts to automatically choose an appropriate base | ||
revision to use. To change which base revision is used, define a | ||||
revset in your configuration file:: | ||||
[histedit] | ||||
defaultrev = only(.) & draft() | ||||
|
r27414 | |||
By default each edited revision needs to be present in histedit commands. | ||||
To remove revision you need to use ``drop`` operation. You can configure | ||||
|
r27957 | the drop to be implicit for missing commits by adding:: | ||
|
r27414 | |||
[histedit] | ||||
dropmissing = True | ||||
|
r31513 | By default, histedit will close the transaction after each action. For | ||
performance purposes, you can configure histedit to use a single transaction | ||||
across the entire histedit. WARNING: This setting introduces a significant risk | ||||
of losing the work you've done in a histedit if the histedit aborts | ||||
unexpectedly:: | ||||
[histedit] | ||||
singletransaction = True | ||||
|
r17064 | """ | ||
|
r17131 | |||
|
r29126 | |||
|
r40688 | # chistedit dependencies that are not available everywhere | ||
try: | ||||
import fcntl | ||||
import termios | ||||
except ImportError: | ||||
fcntl = None | ||||
termios = None | ||||
|
r50143 | import binascii | ||
|
r40638 | import functools | ||
|
r17064 | import os | ||
|
r49725 | import pickle | ||
|
r40638 | import struct | ||
|
r29205 | |||
from mercurial.i18n import _ | ||||
|
r43359 | from mercurial.pycompat import ( | ||
getattr, | ||||
open, | ||||
) | ||||
|
r46729 | from mercurial.node import ( | ||
bin, | ||||
hex, | ||||
short, | ||||
) | ||||
|
r29126 | from mercurial import ( | ||
bundle2, | ||||
cmdutil, | ||||
context, | ||||
copies, | ||||
destutil, | ||||
discovery, | ||||
|
r43685 | encoding, | ||
|
r29126 | error, | ||
exchange, | ||||
extensions, | ||||
hg, | ||||
|
r40638 | logcmdutil, | ||
|
r29126 | merge as mergemod, | ||
|
r45383 | mergestate as mergestatemod, | ||
|
r32057 | mergeutil, | ||
|
r29126 | obsolete, | ||
|
r35000 | pycompat, | ||
|
r32337 | registrar, | ||
|
r29126 | repair, | ||
|
r44385 | rewriteutil, | ||
|
r29126 | scmutil, | ||
|
r38525 | state as statemod, | ||
|
r29126 | util, | ||
) | ||||
|
r37102 | from mercurial.utils import ( | ||
|
r41249 | dateutil, | ||
|
r37102 | stringutil, | ||
r47669 | urlutil, | |||
|
r37102 | ) | ||
|
r17064 | |||
|
r17147 | cmdtable = {} | ||
|
r32337 | command = registrar.command(cmdtable) | ||
|
r17147 | |||
|
r34472 | configtable = {} | ||
configitem = registrar.configitem(configtable) | ||||
|
r43346 | configitem( | ||
|
r46554 | b'experimental', | ||
b'histedit.autoverb', | ||||
default=False, | ||||
|
r34476 | ) | ||
|
r43346 | configitem( | ||
|
r46554 | b'histedit', | ||
b'defaultrev', | ||||
default=None, | ||||
|
r34472 | ) | ||
|
r43346 | configitem( | ||
|
r46554 | b'histedit', | ||
b'dropmissing', | ||||
default=False, | ||||
|
r34473 | ) | ||
|
r43346 | configitem( | ||
|
r46554 | b'histedit', | ||
b'linelen', | ||||
default=80, | ||||
|
r34475 | ) | ||
|
r43346 | configitem( | ||
|
r46554 | b'histedit', | ||
b'singletransaction', | ||||
default=False, | ||||
|
r40638 | ) | ||
|
r43346 | configitem( | ||
|
r46554 | b'ui', | ||
b'interface.histedit', | ||||
default=None, | ||||
|
r43346 | ) | ||
|
r43347 | configitem(b'histedit', b'summary-template', default=b'{rev} {desc|firstline}') | ||
|
r49047 | # TODO: Teach the text-based histedit interface to respect this config option | ||
# before we make it non-experimental. | ||||
configitem( | ||||
b'histedit', b'later-commits-first', default=False, experimental=True | ||||
) | ||||
|
r34472 | |||
|
r29841 | # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for | ||
|
r25186 | # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should | ||
# be specifying the version(s) of Mercurial they are tested with, or | ||||
# leave the attribute unspecified. | ||||
|
r43347 | testedwith = b'ships-with-hg-core' | ||
|
r17064 | |||
|
r27675 | actiontable = {} | ||
primaryactions = set() | ||||
secondaryactions = set() | ||||
tertiaryactions = set() | ||||
internalactions = set() | ||||
|
r43346 | |||
|
r28592 | def geteditcomment(ui, first, last): | ||
|
r46554 | """construct the editor comment | ||
|
r27673 | The comment includes:: | ||
- an intro | ||||
|
r27674 | - sorted primary commands | ||
- sorted short commands | ||||
|
r27675 | - sorted long commands | ||
|
r28592 | - additional hints | ||
|
r27673 | |||
Commands are only included once. | ||||
""" | ||||
|
r43346 | intro = _( | ||
|
r45149 | b"""Edit history between %s and %s | ||
|
r27673 | |||
Commits are listed from least to most recent | ||||
|
r28396 | You can reorder changesets by reordering the lines | ||
|
r27675 | Commands: | ||
|
r43346 | """ | ||
) | ||||
|
r27675 | actions = [] | ||
|
r43346 | |||
|
r27675 | def addverb(v): | ||
a = actiontable[v] | ||||
|
r43347 | lines = a.message.split(b"\n") | ||
|
r27675 | if len(a.verbs): | ||
|
r43347 | v = b', '.join(sorted(a.verbs, key=lambda v: len(v))) | ||
actions.append(b" %s = %s" % (v, lines[0])) | ||||
|
r44447 | actions.extend([b' %s'] * (len(lines) - 1)) | ||
|
r27675 | |||
for v in ( | ||||
|
r43346 | sorted(primaryactions) | ||
+ sorted(secondaryactions) | ||||
+ sorted(tertiaryactions) | ||||
): | ||||
|
r27675 | addverb(v) | ||
|
r43347 | actions.append(b'') | ||
|
r17064 | |||
|
r28592 | hints = [] | ||
|
r43347 | if ui.configbool(b'histedit', b'dropmissing'): | ||
|
r43346 | hints.append( | ||
|
r43347 | b"Deleting a changeset from the list " | ||
b"will DISCARD it from the edited history!" | ||||
|
r43346 | ) | ||
|
r28592 | |||
|
r43347 | lines = (intro % (first, last)).split(b'\n') + actions + hints | ||
return b''.join([b'# %s\n' % l if l else b'#\n' for l in lines]) | ||||
|
r27673 | |||
|
r43346 | |||
|
r49801 | class histeditstate: | ||
|
r41200 | def __init__(self, repo): | ||
|
r22976 | self.repo = repo | ||
|
r41200 | self.actions = None | ||
self.keep = None | ||||
self.topmost = None | ||||
self.parentctxnode = None | ||||
self.lock = None | ||||
self.wlock = None | ||||
|
r24757 | self.backupfile = None | ||
|
r43347 | self.stateobj = statemod.cmdstate(repo, b'histedit-state') | ||
|
r41200 | self.replacements = [] | ||
|
r22976 | |||
|
r22983 | def read(self): | ||
|
r22986 | """Load histedit state from disk and set fields appropriately.""" | ||
|
r38526 | if not self.stateobj.exists(): | ||
|
r43347 | cmdutil.wrongtooltocontinue(self.repo, _(b'histedit')) | ||
|
r22983 | |||
|
r38526 | data = self._read() | ||
|
r38524 | |||
|
r43347 | self.parentctxnode = data[b'parentctxnode'] | ||
actions = parserules(data[b'rules'], self) | ||||
|
r38524 | self.actions = actions | ||
|
r43347 | self.keep = data[b'keep'] | ||
self.topmost = data[b'topmost'] | ||||
self.replacements = data[b'replacements'] | ||||
self.backupfile = data[b'backupfile'] | ||||
|
r38524 | |||
|
r38526 | def _read(self): | ||
|
r43347 | fp = self.repo.vfs.read(b'histedit-state') | ||
if fp.startswith(b'v1\n'): | ||||
|
r27527 | data = self._load() | ||
parentctxnode, rules, keep, topmost, replacements, backupfile = data | ||||
else: | ||||
|
r38524 | data = pickle.loads(fp) | ||
|
r24756 | parentctxnode, rules, keep, topmost, replacements = data | ||
|
r24757 | backupfile = None | ||
|
r43347 | rules = b"\n".join([b"%s %s" % (verb, rest) for [verb, rest] in rules]) | ||
|
r22983 | |||
|
r43346 | return { | ||
|
r43347 | b'parentctxnode': parentctxnode, | ||
b"rules": rules, | ||||
b"keep": keep, | ||||
b"topmost": topmost, | ||||
b"replacements": replacements, | ||||
b"backupfile": backupfile, | ||||
|
r43346 | } | ||
|
r22983 | |||
|
r31511 | def write(self, tr=None): | ||
if tr: | ||||
|
r43346 | tr.addfilegenerator( | ||
|
r43347 | b'histedit-state', | ||
(b'histedit-state',), | ||||
|
r43346 | self._write, | ||
|
r43347 | location=b'plain', | ||
|
r43346 | ) | ||
|
r31511 | else: | ||
|
r43347 | with self.repo.vfs(b"histedit-state", b"w") as f: | ||
|
r31511 | self._write(f) | ||
def _write(self, fp): | ||||
|
r43347 | fp.write(b'v1\n') | ||
|
r46729 | fp.write(b'%s\n' % hex(self.parentctxnode)) | ||
fp.write(b'%s\n' % hex(self.topmost)) | ||||
|
r43347 | fp.write(b'%s\n' % (b'True' if self.keep else b'False')) | ||
fp.write(b'%d\n' % len(self.actions)) | ||||
|
r27208 | for action in self.actions: | ||
|
r43347 | fp.write(b'%s\n' % action.tostate()) | ||
fp.write(b'%d\n' % len(self.replacements)) | ||||
|
r24756 | for replacement in self.replacements: | ||
|
r43346 | fp.write( | ||
|
r43347 | b'%s%s\n' | ||
|
r43346 | % ( | ||
|
r46729 | hex(replacement[0]), | ||
b''.join(hex(r) for r in replacement[1]), | ||||
|
r43346 | ) | ||
) | ||||
|
r24958 | backupfile = self.backupfile | ||
if not backupfile: | ||||
|
r43347 | backupfile = b'' | ||
fp.write(b'%s\n' % backupfile) | ||||
|
r22976 | |||
|
r24756 | def _load(self): | ||
|
r43347 | fp = self.repo.vfs(b'histedit-state', b'r') | ||
|
r24756 | lines = [l[:-1] for l in fp.readlines()] | ||
index = 0 | ||||
|
r43346 | lines[index] # version number | ||
|
r24756 | index += 1 | ||
|
r46729 | parentctxnode = bin(lines[index]) | ||
|
r24756 | index += 1 | ||
|
r46729 | topmost = bin(lines[index]) | ||
|
r24756 | index += 1 | ||
|
r43347 | keep = lines[index] == b'True' | ||
|
r24756 | index += 1 | ||
# Rules | ||||
rules = [] | ||||
rulelen = int(lines[index]) | ||||
index += 1 | ||||
|
r50179 | for i in range(rulelen): | ||
|
r24810 | ruleaction = lines[index] | ||
index += 1 | ||||
|
r24756 | rule = lines[index] | ||
index += 1 | ||||
|
r24810 | rules.append((ruleaction, rule)) | ||
|
r24756 | |||
# Replacements | ||||
replacements = [] | ||||
replacementlen = int(lines[index]) | ||||
index += 1 | ||||
|
r50179 | for i in range(replacementlen): | ||
|
r24756 | replacement = lines[index] | ||
|
r46729 | original = bin(replacement[:40]) | ||
|
r43346 | succ = [ | ||
|
r46729 | bin(replacement[i : i + 40]) | ||
|
r43346 | for i in range(40, len(replacement), 40) | ||
] | ||||
|
r24756 | replacements.append((original, succ)) | ||
index += 1 | ||||
|
r24757 | backupfile = lines[index] | ||
index += 1 | ||||
|
r24756 | fp.close() | ||
|
r24757 | return parentctxnode, rules, keep, topmost, replacements, backupfile | ||
|
r24756 | |||
|
r22978 | def clear(self): | ||
|
r26583 | if self.inprogress(): | ||
|
r43347 | self.repo.vfs.unlink(b'histedit-state') | ||
|
r22978 | |||
|
r26582 | def inprogress(self): | ||
|
r43347 | return self.repo.vfs.exists(b'histedit-state') | ||
|
r26582 | |||
|
r27200 | |||
|
r49801 | class histeditaction: | ||
|
r24765 | def __init__(self, state, node): | ||
self.state = state | ||||
self.repo = state.repo | ||||
self.node = node | ||||
@classmethod | ||||
def fromrule(cls, state, rule): | ||||
|
r46554 | """Parses the given rule, returning an instance of the histeditaction.""" | ||
|
r43347 | ruleid = rule.strip().split(b' ', 1)[0] | ||
|
r37124 | # ruleid can be anything from rev numbers, hashes, "bookmarks" etc | ||
# Check for validation of rule ids and get the rulehash | ||||
|
r27547 | try: | ||
|
r46729 | rev = bin(ruleid) | ||
|
r50143 | except binascii.Error: | ||
|
r37124 | try: | ||
_ctx = scmutil.revsingle(state.repo, ruleid) | ||||
rulehash = _ctx.hex() | ||||
|
r46729 | rev = bin(rulehash) | ||
|
r37124 | except error.RepoLookupError: | ||
|
r43347 | raise error.ParseError(_(b"invalid changeset %s") % ruleid) | ||
|
r27547 | return cls(state, rev) | ||
|
r27202 | |||
|
r29879 | def verify(self, prev, expected, seen): | ||
|
r47856 | """Verifies semantic correctness of the rule""" | ||
|
r27202 | repo = self.repo | ||
|
r46729 | ha = hex(self.node) | ||
|
r37696 | self.node = scmutil.resolvehexnodeidprefix(repo, ha) | ||
|
r37524 | if self.node is None: | ||
|
r43347 | raise error.ParseError(_(b'unknown changeset %s listed') % ha[:12]) | ||
|
r37523 | self._verifynodeconstraints(prev, expected, seen) | ||
|
r29879 | |||
|
r29880 | def _verifynodeconstraints(self, prev, expected, seen): | ||
# by default command need a node in the edited list | ||||
if self.node not in expected: | ||||
|
r43346 | raise error.ParseError( | ||
|
r43347 | _(b'%s "%s" changeset was not a candidate') | ||
|
r46729 | % (self.verb, short(self.node)), | ||
|
r43347 | hint=_(b'only use listed changesets'), | ||
|
r43346 | ) | ||
|
r29880 | # and only one command per node | ||
if self.node in seen: | ||||
|
r43346 | raise error.ParseError( | ||
|
r46729 | _(b'duplicated command for changeset %s') % short(self.node) | ||
|
r43346 | ) | ||
|
r24765 | |||
|
r29466 | def torule(self): | ||
|
r27203 | """build a histedit rule line for an action | ||
by default lines are in the form: | ||||
<hash> <rev> <summary> | ||||
""" | ||||
ctx = self.repo[self.node] | ||||
|
r41650 | ui = self.repo.ui | ||
|
r46462 | # We don't want color codes in the commit message template, so | ||
# disable the label() template function while we render it. | ||||
with ui.configoverride( | ||||
{(b'templatealias', b'label(l,x)'): b"x"}, b'histedit' | ||||
): | ||||
|
r46461 | summary = cmdutil.rendertemplate( | ||
ctx, ui.config(b'histedit', b'summary-template') | ||||
) | ||||
|
r49886 | line = b'%s %s %s' % (self.verb, ctx, stringutil.firstline(summary)) | ||
|
r27203 | # trim to 75 columns by default so it's not stupidly wide in my editor | ||
# (the 5 more are left for verb) | ||||
|
r43347 | maxlen = self.repo.ui.configint(b'histedit', b'linelen') | ||
|
r43346 | maxlen = max(maxlen, 22) # avoid truncating hash | ||
|
r37102 | return stringutil.ellipsis(line, maxlen) | ||
|
r27203 | |||
|
r27206 | def tostate(self): | ||
"""Print an action in format used by histedit state files | ||||
|
r46554 | (the first line is a verb, the remainder is the second) | ||
|
r27206 | """ | ||
|
r46729 | return b"%s\n%s" % (self.verb, hex(self.node)) | ||
|
r27206 | |||
|
r24765 | def run(self): | ||
"""Runs the action. The default behavior is simply apply the action's | ||||
rulectx onto the current parentctx.""" | ||||
self.applychange() | ||||
self.continuedirty() | ||||
return self.continueclean() | ||||
def applychange(self): | ||||
"""Applies the changes from this action's rulectx onto the current | ||||
parentctx, but does not commit them.""" | ||||
repo = self.repo | ||||
rulectx = repo[self.node] | ||||
|
r48230 | with repo.ui.silent(): | ||
hg.update(repo, self.state.parentctxnode, quietempty=True) | ||||
|
r24765 | stats = applychanges(repo.ui, repo, rulectx, {}) | ||
r51152 | repo.dirstate.setbranch(rulectx.branch(), repo.currenttransaction()) | |||
|
r37143 | if stats.unresolvedcount: | ||
|
r27629 | raise error.InterventionRequired( | ||
|
r46729 | _(b'Fix up the change (%s %s)') % (self.verb, short(self.node)), | ||
|
r43347 | hint=_(b'hg histedit --continue to resume'), | ||
|
r43346 | ) | ||
|
r24765 | |||
def continuedirty(self): | ||||
"""Continues the action when changes have been applied to the working | ||||
copy. The default behavior is to commit the dirty changes.""" | ||||
repo = self.repo | ||||
rulectx = repo[self.node] | ||||
editor = self.commiteditor() | ||||
commit = commitfuncfor(repo, rulectx) | ||||
|
r43347 | if repo.ui.configbool(b'rewrite', b'update-timestamp'): | ||
|
r41249 | date = dateutil.makedate() | ||
else: | ||||
date = rulectx.date() | ||||
|
r43346 | commit( | ||
text=rulectx.description(), | ||||
user=rulectx.user(), | ||||
date=date, | ||||
extra=rulectx.extra(), | ||||
editor=editor, | ||||
) | ||||
|
r24765 | |||
def commiteditor(self): | ||||
"""The editor to be used to edit the commit message.""" | ||||
return False | ||||
def continueclean(self): | ||||
"""Continues the action when the working copy is clean. The default | ||||
behavior is to accept the current commit as the new version of the | ||||
rulectx.""" | ||||
|
r43347 | ctx = self.repo[b'.'] | ||
|
r24765 | if ctx.node() == self.state.parentctxnode: | ||
|
r43346 | self.repo.ui.warn( | ||
|
r46729 | _(b'%s: skipping changeset (no changes)\n') % short(self.node) | ||
|
r43346 | ) | ||
|
r24765 | return ctx, [(self.node, tuple())] | ||
if ctx.node() == self.node: | ||||
# Nothing changed | ||||
return ctx, [] | ||||
return ctx, [(self.node, (ctx.node(),))] | ||||
|
r43346 | |||
|
r18436 | def commitfuncfor(repo, src): | ||
"""Build a commit function for the replacement of <src> | ||||
|
r18644 | This function ensure we apply the same treatment to all changesets. | ||
|
r18436 | |||
|
r18437 | - Add a 'histedit_source' entry in extra. | ||
|
r18436 | |||
|
r25450 | Note that fold has its own separated logic because its handling is a bit | ||
|
r18436 | different and not easily factored out of the fold method. | ||
""" | ||||
|
r18440 | phasemin = src.phase() | ||
|
r43346 | |||
|
r18436 | def commitfunc(**kwargs): | ||
|
r43347 | overrides = {(b'phases', b'new-commit'): phasemin} | ||
with repo.ui.configoverride(overrides, b'histedit'): | ||||
|
r43906 | extra = kwargs.get('extra', {}).copy() | ||
|
r43347 | extra[b'histedit_source'] = src.hex() | ||
|
r43906 | kwargs['extra'] = extra | ||
|
r18440 | return repo.commit(**kwargs) | ||
|
r43346 | |||
|
r18436 | return commitfunc | ||
|
r43346 | |||
|
r17647 | def applychanges(ui, repo, ctx, opts): | ||
"""Merge changeset from ctx (only) in the current working directory""" | ||||
|
r45935 | if ctx.p1().node() == repo.dirstate.p1(): | ||
|
r26171 | # edits are "in place" we do not need to make any merge, | ||
|
r27603 | # just applies changes on parent for editing | ||
|
r48230 | with ui.silent(): | ||
cmdutil.revert(ui, repo, ctx, all=True) | ||||
stats = mergemod.updateresult(0, 0, 0, 0) | ||||
|
r17647 | else: | ||
try: | ||||
# ui.forcemerge is an internal variable, do not document | ||||
|
r43346 | repo.ui.setconfig( | ||
|
r43347 | b'ui', b'forcemerge', opts.get(b'tool', b''), b'histedit' | ||
|
r43346 | ) | ||
|
r49437 | stats = mergemod.graft( | ||
repo, | ||||
ctx, | ||||
labels=[ | ||||
b'already edited', | ||||
b'current change', | ||||
b'parent of current change', | ||||
], | ||||
) | ||||
|
r17647 | finally: | ||
|
r43347 | repo.ui.setconfig(b'ui', b'forcemerge', b'', b'histedit') | ||
|
r17647 | return stats | ||
|
r17407 | |||
|
r43346 | |||
|
r36421 | def collapse(repo, firstctx, lastctx, commitopts, skipprompt=False): | ||
|
r17644 | """collapse the set of revisions from first to last as new one. | ||
Expected commit options are: | ||||
- message | ||||
- date | ||||
- username | ||||
|
r17738 | Commit message is edited in all cases. | ||
|
r17644 | |||
This function works in memory.""" | ||||
|
r43347 | ctxs = list(repo.set(b'%d::%d', firstctx.rev(), lastctx.rev())) | ||
|
r17644 | if not ctxs: | ||
return None | ||||
|
r25452 | for c in ctxs: | ||
if not c.mutable(): | ||||
|
r27545 | raise error.ParseError( | ||
|
r46729 | _(b"cannot fold into public change %s") % short(c.node()) | ||
|
r43346 | ) | ||
|
r41442 | base = firstctx.p1() | ||
|
r17644 | |||
# commit a new version of the old changeset, including the update | ||||
# collect all files which might be affected | ||||
files = set() | ||||
for ctx in ctxs: | ||||
files.update(ctx.files()) | ||||
# Recompute copies (avoid recording a -> b -> a) | ||||
|
r36421 | copied = copies.pathcopies(base, lastctx) | ||
|
r17644 | |||
# prune files which were reverted by the updates | ||||
|
r36421 | files = [f for f in files if not cmdutil.samefile(f, lastctx, base)] | ||
|
r17644 | # commit version of these files as defined by head | ||
|
r36421 | headmf = lastctx.manifest() | ||
|
r43346 | |||
|
r17644 | def filectxfn(repo, ctx, path): | ||
if path in headmf: | ||||
|
r36421 | fctx = lastctx[path] | ||
|
r17644 | flags = fctx.flags() | ||
|
r43346 | mctx = context.memfilectx( | ||
repo, | ||||
ctx, | ||||
fctx.path(), | ||||
fctx.data(), | ||||
|
r43347 | islink=b'l' in flags, | ||
isexec=b'x' in flags, | ||||
|
r43346 | copysource=copied.get(path), | ||
) | ||||
|
r17644 | return mctx | ||
|
r22296 | return None | ||
|
r17644 | |||
|
r43347 | if commitopts.get(b'message'): | ||
message = commitopts[b'message'] | ||||
|
r17644 | else: | ||
|
r36421 | message = firstctx.description() | ||
|
r43347 | user = commitopts.get(b'user') | ||
date = commitopts.get(b'date') | ||||
extra = commitopts.get(b'extra') | ||||
|
r17644 | |||
|
r36421 | parents = (firstctx.p1().node(), firstctx.p2().node()) | ||
|
r22152 | editor = None | ||
|
r24828 | if not skipprompt: | ||
|
r43347 | editor = cmdutil.getcommiteditor(edit=True, editform=b'histedit.fold') | ||
|
r43346 | new = context.memctx( | ||
repo, | ||||
parents=parents, | ||||
text=message, | ||||
files=files, | ||||
filectxfn=filectxfn, | ||||
user=user, | ||||
date=date, | ||||
extra=extra, | ||||
editor=editor, | ||||
) | ||||
|
r17644 | return repo.commitctx(new) | ||
|
r43346 | |||
|
r26981 | def _isdirtywc(repo): | ||
return repo[None].dirty(missing=True) | ||||
|
r43346 | |||
|
r27084 | def abortdirty(): | ||
|
r48868 | raise error.StateError( | ||
|
r43347 | _(b'working copy has pending changes'), | ||
|
r43346 | hint=_( | ||
|
r43347 | b'amend, commit, or revert them and run histedit ' | ||
b'--continue, or abort with histedit --abort' | ||||
|
r43346 | ), | ||
) | ||||
|
r27084 | |||
|
r27675 | def action(verbs, message, priority=False, internal=False): | ||
def wrap(cls): | ||||
assert not priority or not internal | ||||
verb = verbs[0] | ||||
if priority: | ||||
primaryactions.add(verb) | ||||
elif internal: | ||||
internalactions.add(verb) | ||||
elif len(verbs) > 1: | ||||
secondaryactions.add(verb) | ||||
else: | ||||
tertiaryactions.add(verb) | ||||
|
r27201 | |||
|
r27675 | cls.verb = verb | ||
cls.verbs = verbs | ||||
cls.message = message | ||||
|
r27201 | for verb in verbs: | ||
actiontable[verb] = cls | ||||
return cls | ||||
|
r43346 | |||
|
r27201 | return wrap | ||
|
r43346 | |||
|
r43347 | @action([b'pick', b'p'], _(b'use commit'), priority=True) | ||
|
r24767 | class pick(histeditaction): | ||
def run(self): | ||||
rulectx = self.repo[self.node] | ||||
|
r41442 | if rulectx.p1().node() == self.state.parentctxnode: | ||
|
r46729 | self.repo.ui.debug(b'node %s unchanged\n' % short(self.node)) | ||
|
r24767 | return rulectx, [] | ||
|
r17064 | |||
|
r24767 | return super(pick, self).run() | ||
|
r17064 | |||
|
r43346 | |||
|
r46729 | @action( | ||
[b'edit', b'e'], | ||||
_(b'use commit, but allow edits before making new commit'), | ||||
priority=True, | ||||
) | ||||
|
r24770 | class edit(histeditaction): | ||
def run(self): | ||||
repo = self.repo | ||||
rulectx = repo[self.node] | ||||
|
r27407 | hg.update(repo, self.state.parentctxnode, quietempty=True) | ||
|
r24770 | applychanges(repo.ui, repo, rulectx, {}) | ||
|
r46719 | hint = _(b'to edit %s, `hg histedit --continue` after making changes') | ||
|
r24770 | raise error.InterventionRequired( | ||
|
r46719 | _(b'Editing (%s), commit as needed now to split the change') | ||
|
r46729 | % short(self.node), | ||
hint=hint % short(self.node), | ||||
|
r43346 | ) | ||
|
r24770 | |||
def commiteditor(self): | ||||
|
r43347 | return cmdutil.getcommiteditor(edit=True, editform=b'histedit.edit') | ||
@action([b'fold', b'f'], _(b'use commit, but combine it with the one above')) | ||||
|
r24771 | class fold(histeditaction): | ||
|
r29879 | def verify(self, prev, expected, seen): | ||
|
r47856 | """Verifies semantic correctness of the fold rule""" | ||
|
r29879 | super(fold, self).verify(prev, expected, seen) | ||
|
r27542 | repo = self.repo | ||
if not prev: | ||||
|
r41442 | c = repo[self.node].p1() | ||
|
r43347 | elif not prev.verb in (b'pick', b'base'): | ||
|
r27542 | return | ||
else: | ||||
c = repo[prev.node] | ||||
if not c.mutable(): | ||||
|
r27545 | raise error.ParseError( | ||
|
r46729 | _(b"cannot fold into public change %s") % short(c.node()) | ||
|
r43346 | ) | ||
|
r27542 | |||
|
r24771 | def continuedirty(self): | ||
repo = self.repo | ||||
rulectx = repo[self.node] | ||||
commit = commitfuncfor(repo, rulectx) | ||||
|
r43346 | commit( | ||
|
r46729 | text=b'fold-temp-revision %s' % short(self.node), | ||
|
r43346 | user=rulectx.user(), | ||
date=rulectx.date(), | ||||
extra=rulectx.extra(), | ||||
) | ||||
|
r24771 | |||
def continueclean(self): | ||||
repo = self.repo | ||||
|
r43347 | ctx = repo[b'.'] | ||
|
r24771 | rulectx = repo[self.node] | ||
parentctxnode = self.state.parentctxnode | ||||
if ctx.node() == parentctxnode: | ||||
|
r46729 | repo.ui.warn(_(b'%s: empty changeset\n') % short(self.node)) | ||
|
r24771 | return ctx, [(self.node, (parentctxnode,))] | ||
|
r22152 | |||
|
r24771 | parentctx = repo[parentctxnode] | ||
|
r44937 | newcommits = { | ||
|
r43346 | c.node() | ||
|
r43347 | for c in repo.set(b'(%d::. - %d)', parentctx.rev(), parentctx.rev()) | ||
|
r44937 | } | ||
|
r24771 | if not newcommits: | ||
|
r43346 | repo.ui.warn( | ||
_( | ||||
|
r43347 | b'%s: cannot fold - working copy is not a ' | ||
b'descendant of previous commit %s\n' | ||||
|
r43346 | ) | ||
|
r46729 | % (short(self.node), short(parentctxnode)) | ||
|
r43346 | ) | ||
|
r24771 | return ctx, [(self.node, (ctx.node(),))] | ||
middlecommits = newcommits.copy() | ||||
middlecommits.discard(ctx.node()) | ||||
|
r43346 | return self.finishfold( | ||
repo.ui, repo, parentctx, rulectx, ctx.node(), middlecommits | ||||
) | ||||
|
r24771 | |||
|
r24773 | def skipprompt(self): | ||
|
r26246 | """Returns true if the rule should skip the message editor. | ||
For example, 'fold' wants to show an editor, but 'rollup' | ||||
doesn't want to. | ||||
""" | ||||
|
r24773 | return False | ||
|
r24772 | |||
|
r26246 | def mergedescs(self): | ||
"""Returns true if the rule should merge messages of multiple changes. | ||||
This exists mainly so that 'rollup' rules can be a subclass of | ||||
'fold'. | ||||
""" | ||||
return True | ||||
|
r31056 | def firstdate(self): | ||
"""Returns true if the rule should preserve the date of the first | ||||
change. | ||||
This exists mainly so that 'rollup' rules can be a subclass of | ||||
'fold'. | ||||
""" | ||||
return False | ||||
|
r24773 | def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges): | ||
|
r46151 | mergemod.update(ctx.p1()) | ||
|
r24772 | ### prepare new commit data | ||
|
r24773 | commitopts = {} | ||
|
r43347 | commitopts[b'user'] = ctx.user() | ||
|
r24772 | # commit message | ||
|
r26246 | if not self.mergedescs(): | ||
|
r24772 | newmessage = ctx.description() | ||
else: | ||||
|
r43346 | newmessage = ( | ||
|
r43347 | b'\n***\n'.join( | ||
|
r43346 | [ctx.description()] | ||
+ [repo[r].description() for r in internalchanges] | ||||
+ [oldctx.description()] | ||||
) | ||||
|
r43347 | + b'\n' | ||
|
r43346 | ) | ||
|
r43347 | commitopts[b'message'] = newmessage | ||
|
r24772 | # date | ||
|
r31056 | if self.firstdate(): | ||
|
r43347 | commitopts[b'date'] = ctx.date() | ||
|
r31056 | else: | ||
|
r43347 | commitopts[b'date'] = max(ctx.date(), oldctx.date()) | ||
|
r41249 | # if date is to be updated to current | ||
|
r43347 | if ui.configbool(b'rewrite', b'update-timestamp'): | ||
commitopts[b'date'] = dateutil.makedate() | ||||
|
r41249 | |||
|
r24772 | extra = ctx.extra().copy() | ||
# histedit_source | ||||
# note: ctx is likely a temporary commit but that the best we can do | ||||
# here. This is sufficient to solve issue3681 anyway. | ||||
|
r43347 | extra[b'histedit_source'] = b'%s,%s' % (ctx.hex(), oldctx.hex()) | ||
commitopts[b'extra'] = extra | ||||
|
r31459 | phasemin = max(ctx.phase(), oldctx.phase()) | ||
|
r43347 | overrides = {(b'phases', b'new-commit'): phasemin} | ||
with repo.ui.configoverride(overrides, b'histedit'): | ||||
|
r43346 | n = collapse( | ||
repo, | ||||
ctx, | ||||
repo[newnode], | ||||
commitopts, | ||||
skipprompt=self.skipprompt(), | ||||
) | ||||
|
r24772 | if n is None: | ||
return ctx, [] | ||||
|
r46151 | mergemod.update(repo[n]) | ||
|
r43346 | replacements = [ | ||
(oldctx.node(), (newnode,)), | ||||
(ctx.node(), (n,)), | ||||
(newnode, (n,)), | ||||
] | ||||
|
r24772 | for ich in internalchanges: | ||
replacements.append((ich, (n,))) | ||||
return repo[n], replacements | ||||
|
r24771 | |||
|
r43346 | |||
@action( | ||||
|
r43347 | [b'base', b'b'], | ||
_(b'checkout changeset and apply further changesets from there'), | ||||
|
r43346 | ) | ||
|
r27085 | class base(histeditaction): | ||
def run(self): | ||||
|
r43347 | if self.repo[b'.'].node() != self.node: | ||
|
r44743 | mergemod.clean_update(self.repo[self.node]) | ||
|
r27085 | return self.continueclean() | ||
def continuedirty(self): | ||||
abortdirty() | ||||
def continueclean(self): | ||||
|
r43347 | basectx = self.repo[b'.'] | ||
|
r27085 | return basectx, [] | ||
|
r29880 | def _verifynodeconstraints(self, prev, expected, seen): | ||
# base can only be use with a node not in the edited set | ||||
if self.node in expected: | ||||
|
r43347 | msg = _(b'%s "%s" changeset was an edited list candidate') | ||
|
r29887 | raise error.ParseError( | ||
|
r46729 | msg % (self.verb, short(self.node)), | ||
|
r43347 | hint=_(b'base must only use unlisted changesets'), | ||
|
r43346 | ) | ||
@action( | ||||
|
r43347 | [b'_multifold'], | ||
|
r43346 | _( | ||
|
r50786 | b"""fold subclass used for when multiple folds happen in a row | ||
|
r26246 | |||
We only want to fire the editor for the folded message once when | ||||
(say) four changes are folded down into a single change. This is | ||||
similar to rollup, but we should preserve both messages so that | ||||
when the last fold operation runs we can show the user all the | ||||
commit messages in their editor. | ||||
|
r43346 | """ | ||
), | ||||
internal=True, | ||||
) | ||||
|
r27675 | class _multifold(fold): | ||
|
r26246 | def skipprompt(self): | ||
return True | ||||
|
r43346 | |||
@action( | ||||
|
r43347 | [b"roll", b"r"], | ||
_(b"like fold, but discard this commit's description and date"), | ||||
|
r43346 | ) | ||
|
r24771 | class rollup(fold): | ||
|
r26246 | def mergedescs(self): | ||
return False | ||||
|
r24773 | def skipprompt(self): | ||
return True | ||||
|
r17064 | |||
|
r31056 | def firstdate(self): | ||
return True | ||||
|
r43346 | |||
|
r43347 | @action([b"drop", b"d"], _(b'remove commit from history')) | ||
|
r24768 | class drop(histeditaction): | ||
def run(self): | ||||
parentctx = self.repo[self.state.parentctxnode] | ||||
return parentctx, [(self.node, tuple())] | ||||
|
r17064 | |||
|
r43346 | |||
@action( | ||||
|
r43347 | [b"mess", b"m"], | ||
_(b'edit commit message without changing commit content'), | ||||
|
r43346 | priority=True, | ||
) | ||||
|
r24769 | class message(histeditaction): | ||
def commiteditor(self): | ||||
|
r43347 | return cmdutil.getcommiteditor(edit=True, editform=b'histedit.mess') | ||
|
r17064 | |||
|
r43346 | |||
|
r26335 | def findoutgoing(ui, repo, remote=None, force=False, opts=None): | ||
|
r19021 | """utility function to find the first outgoing changeset | ||
|
r26171 | Used by initialization code""" | ||
|
r26335 | if opts is None: | ||
opts = {} | ||||
r47703 | path = urlutil.get_unique_push_path(b'histedit', repo, ui, remote) | |||
r50607 | ||||
ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(path.loc)) | ||||
|
r19021 | |||
r47703 | revs, checkout = hg.addbranchrevs(repo, repo, (path.branch, []), None) | |||
r50607 | other = hg.peer(repo, opts, path) | |||
|
r19021 | |||
if revs: | ||||
revs = [repo.lookup(rev) for rev in revs] | ||||
outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force) | ||||
if not outgoing.missing: | ||||
|
r48868 | raise error.StateError(_(b'no outgoing ancestors')) | ||
|
r43347 | roots = list(repo.revs(b"roots(%ln)", outgoing.missing)) | ||
|
r40065 | if len(roots) > 1: | ||
|
r43347 | msg = _(b'there are ambiguous outgoing revisions') | ||
hint = _(b"see 'hg help histedit' for more detail") | ||||
|
r48868 | raise error.StateError(msg, hint=hint) | ||
|
r37330 | return repo[roots[0]].node() | ||
|
r19021 | |||
|
r43346 | |||
|
r40638 | # Curses Support | ||
try: | ||||
import curses | ||||
except ImportError: | ||||
curses = None | ||||
|
r43347 | KEY_LIST = [b'pick', b'edit', b'fold', b'drop', b'mess', b'roll'] | ||
|
r40638 | ACTION_LABELS = { | ||
|
r43347 | b'fold': b'^fold', | ||
b'roll': b'^roll', | ||||
|
r40638 | } | ||
|
r43346 | COLOR_HELP, COLOR_SELECTED, COLOR_OK, COLOR_WARN, COLOR_CURRENT = 1, 2, 3, 4, 5 | ||
|
r42258 | COLOR_DIFF_ADD_LINE, COLOR_DIFF_DEL_LINE, COLOR_DIFF_OFFSET = 6, 7, 8 | ||
|
r44062 | COLOR_ROLL, COLOR_ROLL_CURRENT, COLOR_ROLL_SELECTED = 9, 10, 11 | ||
|
r40638 | |||
E_QUIT, E_HISTEDIT = 1, 2 | ||||
E_PAGEDOWN, E_PAGEUP, E_LINEUP, E_LINEDOWN, E_RESIZE = 3, 4, 5, 6, 7 | ||||
MODE_INIT, MODE_PATCH, MODE_RULES, MODE_HELP = 0, 1, 2, 3 | ||||
KEYTABLE = { | ||||
|
r43347 | b'global': { | ||
b'h': b'next-action', | ||||
b'KEY_RIGHT': b'next-action', | ||||
b'l': b'prev-action', | ||||
b'KEY_LEFT': b'prev-action', | ||||
b'q': b'quit', | ||||
b'c': b'histedit', | ||||
b'C': b'histedit', | ||||
b'v': b'showpatch', | ||||
b'?': b'help', | ||||
|
r40638 | }, | ||
MODE_RULES: { | ||||
|
r43347 | b'd': b'action-drop', | ||
b'e': b'action-edit', | ||||
b'f': b'action-fold', | ||||
b'm': b'action-mess', | ||||
b'p': b'action-pick', | ||||
b'r': b'action-roll', | ||||
b' ': b'select', | ||||
b'j': b'down', | ||||
b'k': b'up', | ||||
b'KEY_DOWN': b'down', | ||||
b'KEY_UP': b'up', | ||||
b'J': b'move-down', | ||||
b'K': b'move-up', | ||||
b'KEY_NPAGE': b'move-down', | ||||
b'KEY_PPAGE': b'move-up', | ||||
b'0': b'goto', # Used for 0..9 | ||||
|
r40638 | }, | ||
MODE_PATCH: { | ||||
|
r43347 | b' ': b'page-down', | ||
b'KEY_NPAGE': b'page-down', | ||||
b'KEY_PPAGE': b'page-up', | ||||
b'j': b'line-down', | ||||
b'k': b'line-up', | ||||
b'KEY_DOWN': b'line-down', | ||||
b'KEY_UP': b'line-up', | ||||
b'J': b'down', | ||||
b'K': b'up', | ||||
|
r40638 | }, | ||
|
r43346 | MODE_HELP: {}, | ||
|
r40638 | } | ||
|
r43346 | |||
|
r40638 | def screen_size(): | ||
|
r43347 | return struct.unpack(b'hh', fcntl.ioctl(1, termios.TIOCGWINSZ, b' ')) | ||
|
r40638 | |||
|
r43346 | |||
|
r49801 | class histeditrule: | ||
|
r45057 | def __init__(self, ui, ctx, pos, action=b'pick'): | ||
self.ui = ui | ||||
|
r40638 | self.ctx = ctx | ||
self.action = action | ||||
self.origpos = pos | ||||
self.pos = pos | ||||
self.conflicts = [] | ||||
|
r43685 | def __bytes__(self): | ||
|
r44061 | # Example display of several histeditrules: | ||
|
r40638 | # | ||
# #10 pick 316392:06a16c25c053 add option to skip tests | ||||
|
r44061 | # #11 ^roll 316393:71313c964cc5 <RED>oops a fixup commit</RED> | ||
|
r40638 | # #12 pick 316394:ab31f3973b0d include mfbt for mozilla-config.h | ||
# #13 ^fold 316395:14ce5803f4c3 fix warnings | ||||
# | ||||
# The carets point to the changeset being folded into ("roll this | ||||
# changeset into the changeset above"). | ||||
|
r44061 | return b'%s%s' % (self.prefix, self.desc) | ||
__str__ = encoding.strmethod(__bytes__) | ||||
@property | ||||
def prefix(self): | ||||
# Some actions ('fold' and 'roll') combine a patch with a | ||||
# previous one. Add a marker showing which patch they apply | ||||
# to. | ||||
|
r40638 | action = ACTION_LABELS.get(self.action, self.action) | ||
|
r44061 | |||
|
r40638 | h = self.ctx.hex()[0:12] | ||
r = self.ctx.rev() | ||||
|
r44061 | |||
return b"#%s %s %d:%s " % ( | ||||
|
r43685 | (b'%d' % self.origpos).ljust(2), | ||
action.ljust(6), | ||||
r, | ||||
h, | ||||
|
r43346 | ) | ||
|
r40638 | |||
|
r46022 | @util.propertycache | ||
|
r44061 | def desc(self): | ||
|
r46376 | summary = cmdutil.rendertemplate( | ||
self.ctx, self.ui.config(b'histedit', b'summary-template') | ||||
|
r45057 | ) | ||
if summary: | ||||
return summary | ||||
|
r44061 | # This is split off from the prefix property so that we can | ||
# separately make the description for 'roll' red (since it | ||||
# will get discarded). | ||||
|
r49886 | return stringutil.firstline(self.ctx.description()) | ||
|
r43685 | |||
|
r40638 | def checkconflicts(self, other): | ||
if other.pos > self.pos and other.origpos <= self.origpos: | ||||
if set(other.ctx.files()) & set(self.ctx.files()) != set(): | ||||
self.conflicts.append(other) | ||||
return self.conflicts | ||||
if other in self.conflicts: | ||||
self.conflicts.remove(other) | ||||
return self.conflicts | ||||
|
r43346 | |||
|
r40638 | def makecommands(rules): | ||
"""Returns a list of commands consumable by histedit --commands based on | ||||
our list of rules""" | ||||
commands = [] | ||||
for rules in rules: | ||||
|
r43688 | commands.append(b'%s %s\n' % (rules.action, rules.ctx)) | ||
|
r40638 | return commands | ||
|
r43346 | |||
|
r40638 | def addln(win, y, x, line, color=None): | ||
"""Add a line to the given window left padding but 100% filled with | ||||
whitespace characters, so that the color appears on the whole line""" | ||||
maxy, maxx = win.getmaxyx() | ||||
length = maxx - 1 - x | ||||
|
r43685 | line = bytes(line).ljust(length)[:length] | ||
|
r40638 | if y < 0: | ||
y = maxy + y | ||||
if x < 0: | ||||
x = maxx + x | ||||
if color: | ||||
win.addstr(y, x, line, color) | ||||
else: | ||||
win.addstr(y, x, line) | ||||
|
r43346 | |||
|
r42418 | def _trunc_head(line, n): | ||
if len(line) <= n: | ||||
return line | ||||
|
r43347 | return b'> ' + line[-(n - 2) :] | ||
|
r43346 | |||
|
r42418 | def _trunc_tail(line, n): | ||
if len(line) <= n: | ||||
return line | ||||
|
r43347 | return line[: n - 2] + b' >' | ||
|
r43346 | |||
|
r42418 | |||
|
r49801 | class _chistedit_state: | ||
|
r49014 | def __init__( | ||
self, | ||||
repo, | ||||
rules, | ||||
|
r49016 | stdscr, | ||
|
r49014 | ): | ||
self.repo = repo | ||||
self.rules = rules | ||||
|
r49016 | self.stdscr = stdscr | ||
|
r49047 | self.later_on_top = repo.ui.configbool( | ||
b'histedit', b'later-commits-first' | ||||
) | ||||
# The current item in display order, initialized to point to the top | ||||
# of the screen. | ||||
|
r49014 | self.pos = 0 | ||
self.selected = None | ||||
self.mode = (MODE_INIT, MODE_INIT) | ||||
self.page_height = None | ||||
self.modes = { | ||||
MODE_RULES: { | ||||
b'line_offset': 0, | ||||
}, | ||||
MODE_PATCH: { | ||||
b'line_offset': 0, | ||||
}, | ||||
} | ||||
|
r49015 | def render_commit(self, win): | ||
|
r40638 | """Renders the commit window that shows the log of the current selected | ||
commit""" | ||||
|
r49047 | rule = self.rules[self.display_pos_to_rule_pos(self.pos)] | ||
|
r40638 | |||
ctx = rule.ctx | ||||
win.box() | ||||
maxy, maxx = win.getmaxyx() | ||||
length = maxx - 3 | ||||
|
r43693 | line = b"changeset: %d:%s" % (ctx.rev(), ctx.hex()[:12]) | ||
|
r40638 | win.addstr(1, 1, line[:length]) | ||
|
r43685 | line = b"user: %s" % ctx.user() | ||
|
r40638 | win.addstr(2, 1, line[:length]) | ||
|
r49015 | bms = self.repo.nodebookmarks(ctx.node()) | ||
|
r43685 | line = b"bookmark: %s" % b' '.join(bms) | ||
|
r40638 | win.addstr(3, 1, line[:length]) | ||
|
r49886 | line = b"summary: %s" % stringutil.firstline(ctx.description()) | ||
|
r40638 | win.addstr(4, 1, line[:length]) | ||
|
r43347 | line = b"files: " | ||
|
r42418 | win.addstr(5, 1, line) | ||
fnx = 1 + len(line) | ||||
fnmaxx = length - fnx + 1 | ||||
y = 5 | ||||
fnmaxn = maxy - (1 + y) - 1 | ||||
files = ctx.files() | ||||
for i, line1 in enumerate(files): | ||||
if len(files) > fnmaxn and i == fnmaxn - 1: | ||||
|
r43347 | win.addstr(y, fnx, _trunc_tail(b','.join(files[i:]), fnmaxx)) | ||
|
r42418 | y = y + 1 | ||
break | ||||
win.addstr(y, fnx, _trunc_head(line1, fnmaxx)) | ||||
y = y + 1 | ||||
|
r40638 | |||
conflicts = rule.conflicts | ||||
if len(conflicts) > 0: | ||||
|
r43693 | conflictstr = b','.join(map(lambda r: r.ctx.hex()[:12], conflicts)) | ||
|
r43685 | conflictstr = b"changed files overlap with %s" % conflictstr | ||
|
r40638 | else: | ||
|
r43347 | conflictstr = b'no overlap' | ||
|
r40638 | |||
|
r42418 | win.addstr(y, 1, conflictstr[:length]) | ||
|
r40638 | win.noutrefresh() | ||
|
r49016 | def helplines(self): | ||
if self.mode[0] == MODE_PATCH: | ||||
help = b"""\ | ||||
?: help, k/up: line up, j/down: line down, v: stop viewing patch | ||||
pgup: prev page, space/pgdn: next page, c: commit, q: abort | ||||
""" | ||||
else: | ||||
help = b"""\ | ||||
?: help, k/up: move up, j/down: move down, space: select, v: view patch | ||||
d: drop, e: edit, f: fold, m: mess, p: pick, r: roll | ||||
pgup/K: move patch up, pgdn/J: move patch down, c: commit, q: abort | ||||
""" | ||||
|
r49194 | if self.later_on_top: | ||
help += b"Newer commits are shown above older commits.\n" | ||||
else: | ||||
help += b"Older commits are shown above newer commits.\n" | ||||
|
r49016 | return help.splitlines() | ||
def render_help(self, win): | ||||
maxy, maxx = win.getmaxyx() | ||||
for y, line in enumerate(self.helplines()): | ||||
if y >= maxy: | ||||
break | ||||
addln(win, y, 0, line, curses.color_pair(COLOR_HELP)) | ||||
win.noutrefresh() | ||||
def layout(self): | ||||
maxy, maxx = self.stdscr.getmaxyx() | ||||
helplen = len(self.helplines()) | ||||
mainlen = maxy - helplen - 12 | ||||
if mainlen < 1: | ||||
raise error.Abort( | ||||
_(b"terminal dimensions %d by %d too small for curses histedit") | ||||
% (maxy, maxx), | ||||
hint=_( | ||||
b"enlarge your terminal or use --config ui.interface=text" | ||||
), | ||||
) | ||||
return { | ||||
b'commit': (12, maxx), | ||||
b'help': (helplen, maxx), | ||||
b'main': (mainlen, maxx), | ||||
} | ||||
|
r49047 | def display_pos_to_rule_pos(self, display_pos): | ||
"""Converts a position in display order to rule order. | ||||
The `display_pos` is the order from the top in display order, not | ||||
considering which items are currently visible on the screen. Thus, | ||||
`display_pos=0` is the item at the top (possibly after scrolling to | ||||
the top) | ||||
""" | ||||
if self.later_on_top: | ||||
return len(self.rules) - 1 - display_pos | ||||
else: | ||||
return display_pos | ||||
|
r49017 | def render_rules(self, rulesscr): | ||
start = self.modes[MODE_RULES][b'line_offset'] | ||||
|
r40638 | |||
|
r49028 | conflicts = [r.ctx for r in self.rules if r.conflicts] | ||
|
r40638 | if len(conflicts) > 0: | ||
|
r43687 | line = b"potential conflict in %s" % b','.join( | ||
map(pycompat.bytestr, conflicts) | ||||
) | ||||
|
r40638 | addln(rulesscr, -1, 0, line, curses.color_pair(COLOR_WARN)) | ||
|
r49047 | for display_pos in range(start, len(self.rules)): | ||
y = display_pos - start | ||||
if y < 0 or y >= self.page_height: | ||||
continue | ||||
rule_pos = self.display_pos_to_rule_pos(display_pos) | ||||
rule = self.rules[rule_pos] | ||||
|
r40638 | if len(rule.conflicts) > 0: | ||
|
r43347 | rulesscr.addstr(y, 0, b" ", curses.color_pair(COLOR_WARN)) | ||
|
r40638 | else: | ||
|
r43347 | rulesscr.addstr(y, 0, b" ", curses.COLOR_BLACK) | ||
|
r44063 | |||
|
r49047 | if display_pos == self.selected: | ||
|
r44063 | rollcolor = COLOR_ROLL_SELECTED | ||
|
r40638 | addln(rulesscr, y, 2, rule, curses.color_pair(COLOR_SELECTED)) | ||
|
r49047 | elif display_pos == self.pos: | ||
|
r44063 | rollcolor = COLOR_ROLL_CURRENT | ||
|
r43346 | addln( | ||
rulesscr, | ||||
y, | ||||
2, | ||||
rule, | ||||
curses.color_pair(COLOR_CURRENT) | curses.A_BOLD, | ||||
) | ||||
|
r40638 | else: | ||
|
r44063 | rollcolor = COLOR_ROLL | ||
|
r40638 | addln(rulesscr, y, 2, rule) | ||
|
r44063 | |||
if rule.action == b'roll': | ||||
rulesscr.addstr( | ||||
y, | ||||
2 + len(rule.prefix), | ||||
rule.desc, | ||||
curses.color_pair(rollcolor), | ||||
) | ||||
|
r40638 | rulesscr.noutrefresh() | ||
|
r49018 | def render_string(self, win, output, diffcolors=False): | ||
maxy, maxx = win.getmaxyx() | ||||
length = min(maxy - 1, len(output)) | ||||
for y in range(0, length): | ||||
line = output[y] | ||||
if diffcolors: | ||||
|
r51227 | if line.startswith(b'+'): | ||
|
r49018 | win.addstr( | ||
y, 0, line, curses.color_pair(COLOR_DIFF_ADD_LINE) | ||||
) | ||||
|
r51227 | elif line.startswith(b'-'): | ||
|
r49018 | win.addstr( | ||
y, 0, line, curses.color_pair(COLOR_DIFF_DEL_LINE) | ||||
) | ||||
elif line.startswith(b'@@ '): | ||||
win.addstr(y, 0, line, curses.color_pair(COLOR_DIFF_OFFSET)) | ||||
else: | ||||
win.addstr(y, 0, line) | ||||
else: | ||||
win.addstr(y, 0, line) | ||||
win.noutrefresh() | ||||
def render_patch(self, win): | ||||
start = self.modes[MODE_PATCH][b'line_offset'] | ||||
content = self.modes[MODE_PATCH][b'patchcontents'] | ||||
self.render_string(win, content[start:], diffcolors=True) | ||||
|
r49019 | def event(self, ch): | ||
"""Change state based on the current character input | ||||
This takes the current state and based on the current character input from | ||||
the user we change the state. | ||||
""" | ||||
oldpos = self.pos | ||||
if ch in (curses.KEY_RESIZE, b"KEY_RESIZE"): | ||||
return E_RESIZE | ||||
lookup_ch = ch | ||||
if ch is not None and b'0' <= ch <= b'9': | ||||
lookup_ch = b'0' | ||||
curmode, prevmode = self.mode | ||||
action = KEYTABLE[curmode].get( | ||||
lookup_ch, KEYTABLE[b'global'].get(lookup_ch) | ||||
) | ||||
if action is None: | ||||
return | ||||
if action in (b'down', b'move-down'): | ||||
|
r49028 | newpos = min(oldpos + 1, len(self.rules) - 1) | ||
|
r49021 | self.move_cursor(oldpos, newpos) | ||
|
r49028 | if self.selected is not None or action == b'move-down': | ||
|
r49024 | self.swap(oldpos, newpos) | ||
|
r49019 | elif action in (b'up', b'move-up'): | ||
newpos = max(0, oldpos - 1) | ||||
|
r49021 | self.move_cursor(oldpos, newpos) | ||
|
r49028 | if self.selected is not None or action == b'move-up': | ||
|
r49024 | self.swap(oldpos, newpos) | ||
|
r49019 | elif action == b'next-action': | ||
|
r49026 | self.cycle_action(oldpos, next=True) | ||
|
r49019 | elif action == b'prev-action': | ||
|
r49026 | self.cycle_action(oldpos, next=False) | ||
|
r49019 | elif action == b'select': | ||
|
r49028 | self.selected = oldpos if self.selected is None else None | ||
self.make_selection(self.selected) | ||||
elif action == b'goto' and int(ch) < len(self.rules) <= 10: | ||||
newrule = next((r for r in self.rules if r.origpos == int(ch))) | ||||
|
r49021 | self.move_cursor(oldpos, newrule.pos) | ||
|
r49028 | if self.selected is not None: | ||
|
r49024 | self.swap(oldpos, newrule.pos) | ||
|
r49019 | elif action.startswith(b'action-'): | ||
|
r49025 | self.change_action(oldpos, action[7:]) | ||
|
r49019 | elif action == b'showpatch': | ||
|
r49022 | self.change_mode(MODE_PATCH if curmode != MODE_PATCH else prevmode) | ||
|
r49019 | elif action == b'help': | ||
|
r49022 | self.change_mode(MODE_HELP if curmode != MODE_HELP else prevmode) | ||
|
r49019 | elif action == b'quit': | ||
return E_QUIT | ||||
elif action == b'histedit': | ||||
return E_HISTEDIT | ||||
elif action == b'page-down': | ||||
return E_PAGEDOWN | ||||
elif action == b'page-up': | ||||
return E_PAGEUP | ||||
elif action == b'line-down': | ||||
return E_LINEDOWN | ||||
elif action == b'line-up': | ||||
return E_LINEUP | ||||
|
r49020 | def patch_contents(self): | ||
repo = self.repo | ||||
|
r49047 | rule = self.rules[self.display_pos_to_rule_pos(self.pos)] | ||
|
r49020 | displayer = logcmdutil.changesetdisplayer( | ||
repo.ui, | ||||
repo, | ||||
{b"patch": True, b"template": b"status"}, | ||||
buffered=True, | ||||
) | ||||
overrides = {(b'ui', b'verbose'): True} | ||||
with repo.ui.configoverride(overrides, source=b'histedit'): | ||||
displayer.show(rule.ctx) | ||||
displayer.close() | ||||
return displayer.hunk[rule.ctx.rev()].splitlines() | ||||
|
r49021 | def move_cursor(self, oldpos, newpos): | ||
"""Change the rule/changeset that the cursor is pointing to, regardless of | ||||
current mode (you can switch between patches from the view patch window).""" | ||||
self.pos = newpos | ||||
mode, _ = self.mode | ||||
if mode == MODE_RULES: | ||||
# Scroll through the list by updating the view for MODE_RULES, so that | ||||
# even if we are not currently viewing the rules, switching back will | ||||
# result in the cursor's rule being visible. | ||||
modestate = self.modes[MODE_RULES] | ||||
if newpos < modestate[b'line_offset']: | ||||
modestate[b'line_offset'] = newpos | ||||
elif newpos > modestate[b'line_offset'] + self.page_height - 1: | ||||
modestate[b'line_offset'] = newpos - self.page_height + 1 | ||||
# Reset the patch view region to the top of the new patch. | ||||
self.modes[MODE_PATCH][b'line_offset'] = 0 | ||||
|
r49022 | def change_mode(self, mode): | ||
curmode, _ = self.mode | ||||
self.mode = (mode, curmode) | ||||
if mode == MODE_PATCH: | ||||
self.modes[MODE_PATCH][b'patchcontents'] = self.patch_contents() | ||||
|
r49023 | def make_selection(self, pos): | ||
self.selected = pos | ||||
|
r49024 | def swap(self, oldpos, newpos): | ||
"""Swap two positions and calculate necessary conflicts in | ||||
O(|newpos-oldpos|) time""" | ||||
|
r49047 | old_rule_pos = self.display_pos_to_rule_pos(oldpos) | ||
new_rule_pos = self.display_pos_to_rule_pos(newpos) | ||||
|
r49024 | |||
rules = self.rules | ||||
|
r49047 | assert 0 <= old_rule_pos < len(rules) and 0 <= new_rule_pos < len(rules) | ||
rules[old_rule_pos], rules[new_rule_pos] = ( | ||||
rules[new_rule_pos], | ||||
rules[old_rule_pos], | ||||
) | ||||
|
r49024 | |||
# TODO: swap should not know about histeditrule's internals | ||||
|
r49047 | rules[new_rule_pos].pos = new_rule_pos | ||
rules[old_rule_pos].pos = old_rule_pos | ||||
start = min(old_rule_pos, new_rule_pos) | ||||
end = max(old_rule_pos, new_rule_pos) | ||||
|
r50179 | for r in range(start, end + 1): | ||
|
r49047 | rules[new_rule_pos].checkconflicts(rules[r]) | ||
rules[old_rule_pos].checkconflicts(rules[r]) | ||||
|
r49024 | |||
if self.selected: | ||||
self.make_selection(newpos) | ||||
|
r49025 | def change_action(self, pos, action): | ||
"""Change the action state on the given position to the new action""" | ||||
|
r49028 | assert 0 <= pos < len(self.rules) | ||
self.rules[pos].action = action | ||||
|
r49025 | |||
|
r49026 | def cycle_action(self, pos, next=False): | ||
"""Changes the action state the next or the previous action from | ||||
the action list""" | ||||
|
r49028 | assert 0 <= pos < len(self.rules) | ||
current = self.rules[pos].action | ||||
|
r49026 | |||
assert current in KEY_LIST | ||||
index = KEY_LIST.index(current) | ||||
if next: | ||||
index += 1 | ||||
else: | ||||
index -= 1 | ||||
self.change_action(pos, KEY_LIST[index % len(KEY_LIST)]) | ||||
|
r49027 | def change_view(self, delta, unit): | ||
"""Change the region of whatever is being viewed (a patch or the list of | ||||
changesets). 'delta' is an amount (+/- 1) and 'unit' is 'page' or 'line'.""" | ||||
mode, _ = self.mode | ||||
if mode != MODE_PATCH: | ||||
return | ||||
mode_state = self.modes[mode] | ||||
num_lines = len(mode_state[b'patchcontents']) | ||||
page_height = self.page_height | ||||
unit = page_height if unit == b'page' else 1 | ||||
num_pages = 1 + (num_lines - 1) // page_height | ||||
max_offset = (num_pages - 1) * page_height | ||||
newline = mode_state[b'line_offset'] + delta * unit | ||||
mode_state[b'line_offset'] = max(0, min(max_offset, newline)) | ||||
|
r49017 | |||
def _chisteditmain(repo, rules, stdscr): | ||||
try: | ||||
curses.use_default_colors() | ||||
except curses.error: | ||||
pass | ||||
# initialize color pattern | ||||
curses.init_pair(COLOR_HELP, curses.COLOR_WHITE, curses.COLOR_BLUE) | ||||
curses.init_pair(COLOR_SELECTED, curses.COLOR_BLACK, curses.COLOR_WHITE) | ||||
curses.init_pair(COLOR_WARN, curses.COLOR_BLACK, curses.COLOR_YELLOW) | ||||
curses.init_pair(COLOR_OK, curses.COLOR_BLACK, curses.COLOR_GREEN) | ||||
curses.init_pair(COLOR_CURRENT, curses.COLOR_WHITE, curses.COLOR_MAGENTA) | ||||
curses.init_pair(COLOR_DIFF_ADD_LINE, curses.COLOR_GREEN, -1) | ||||
curses.init_pair(COLOR_DIFF_DEL_LINE, curses.COLOR_RED, -1) | ||||
curses.init_pair(COLOR_DIFF_OFFSET, curses.COLOR_MAGENTA, -1) | ||||
curses.init_pair(COLOR_ROLL, curses.COLOR_RED, -1) | ||||
curses.init_pair( | ||||
COLOR_ROLL_CURRENT, curses.COLOR_BLACK, curses.COLOR_MAGENTA | ||||
) | ||||
curses.init_pair(COLOR_ROLL_SELECTED, curses.COLOR_RED, curses.COLOR_WHITE) | ||||
# don't display the cursor | ||||
try: | ||||
curses.curs_set(0) | ||||
except curses.error: | ||||
pass | ||||
|
r40638 | def drawvertwin(size, y, x): | ||
win = curses.newwin(size[0], size[1], y, x) | ||||
y += size[0] | ||||
return win, y, x | ||||
|
r49016 | state = _chistedit_state(repo, rules, stdscr) | ||
|
r40638 | |||
# eventloop | ||||
ch = None | ||||
stdscr.clear() | ||||
stdscr.refresh() | ||||
while True: | ||||
|
r49014 | oldmode, unused = state.mode | ||
|
r47125 | if oldmode == MODE_INIT: | ||
|
r49022 | state.change_mode(MODE_RULES) | ||
|
r49019 | e = state.event(ch) | ||
|
r47125 | |||
if e == E_QUIT: | ||||
return False | ||||
if e == E_HISTEDIT: | ||||
|
r49014 | return state.rules | ||
|
r47125 | else: | ||
if e == E_RESIZE: | ||||
size = screen_size() | ||||
if size != stdscr.getmaxyx(): | ||||
curses.resizeterm(*size) | ||||
|
r49016 | sizes = state.layout() | ||
|
r49014 | curmode, unused = state.mode | ||
|
r47125 | if curmode != oldmode: | ||
|
r49014 | state.page_height = sizes[b'main'][0] | ||
|
r47125 | # Adjust the view to fit the current screen size. | ||
|
r49021 | state.move_cursor(state.pos, state.pos) | ||
|
r47125 | |||
# Pack the windows against the top, each pane spread across the | ||||
# full width of the screen. | ||||
y, x = (0, 0) | ||||
helpwin, y, x = drawvertwin(sizes[b'help'], y, x) | ||||
mainwin, y, x = drawvertwin(sizes[b'main'], y, x) | ||||
commitwin, y, x = drawvertwin(sizes[b'commit'], y, x) | ||||
if e in (E_PAGEDOWN, E_PAGEUP, E_LINEDOWN, E_LINEUP): | ||||
if e == E_PAGEDOWN: | ||||
|
r49027 | state.change_view(+1, b'page') | ||
|
r47125 | elif e == E_PAGEUP: | ||
|
r49027 | state.change_view(-1, b'page') | ||
|
r47125 | elif e == E_LINEDOWN: | ||
|
r49027 | state.change_view(+1, b'line') | ||
|
r47125 | elif e == E_LINEUP: | ||
|
r49027 | state.change_view(-1, b'line') | ||
|
r47125 | |||
# start rendering | ||||
commitwin.erase() | ||||
helpwin.erase() | ||||
mainwin.erase() | ||||
if curmode == MODE_PATCH: | ||||
|
r49018 | state.render_patch(mainwin) | ||
|
r47125 | elif curmode == MODE_HELP: | ||
|
r49018 | state.render_string(mainwin, __doc__.strip().splitlines()) | ||
|
r40638 | else: | ||
|
r49017 | state.render_rules(mainwin) | ||
|
r49015 | state.render_commit(commitwin) | ||
|
r49016 | state.render_help(helpwin) | ||
|
r47125 | curses.doupdate() | ||
# done rendering | ||||
ch = encoding.strtolocal(stdscr.getkey()) | ||||
|
r40638 | |||
|
r43346 | |||
|
r44892 | def _chistedit(ui, repo, freeargs, opts): | ||
|
r40638 | """interactively edit changeset history via a curses interface | ||
Provides a ncurses interface to histedit. Press ? in chistedit mode | ||||
to see an extensive help. Requires python-curses to be installed.""" | ||||
if curses is None: | ||||
|
r43347 | raise error.Abort(_(b"Python curses library required")) | ||
|
r40638 | |||
# disable color | ||||
ui._colormode = None | ||||
try: | ||||
|
r43347 | keep = opts.get(b'keep') | ||
revs = opts.get(b'rev', [])[:] | ||||
|
r40638 | cmdutil.checkunfinished(repo) | ||
cmdutil.bailifchanged(repo) | ||||
revs.extend(freeargs) | ||||
if not revs: | ||||
defaultrev = destutil.desthistedit(ui, repo) | ||||
if defaultrev is not None: | ||||
revs.append(defaultrev) | ||||
if len(revs) != 1: | ||||
|
r48868 | raise error.InputError( | ||
|
r43347 | _(b'histedit requires exactly one ancestor revision') | ||
|
r43346 | ) | ||
|
r40638 | |||
|
r48928 | rr = list(repo.set(b'roots(%ld)', logcmdutil.revrange(repo, revs))) | ||
|
r40638 | if len(rr) != 1: | ||
|
r48868 | raise error.InputError( | ||
|
r43346 | _( | ||
|
r43347 | b'The specified revisions must have ' | ||
b'exactly one common root' | ||||
|
r43346 | ) | ||
) | ||||
|
r40638 | root = rr[0].node() | ||
|
r41444 | topmost = repo.dirstate.p1() | ||
|
r40638 | revs = between(repo, root, topmost, keep) | ||
if not revs: | ||||
|
r48868 | raise error.InputError( | ||
|
r46729 | _(b'%s is not an ancestor of working directory') % short(root) | ||
|
r43346 | ) | ||
|
r40638 | |||
|
r49029 | rules = [] | ||
|
r40638 | for i, r in enumerate(revs): | ||
|
r49029 | rules.append(histeditrule(ui, repo[r], i)) | ||
|
r45550 | with util.with_lc_ctype(): | ||
|
r49029 | rc = curses.wrapper(functools.partial(_chisteditmain, repo, rules)) | ||
|
r40638 | curses.echo() | ||
curses.endwin() | ||||
if rc is False: | ||||
|
r43347 | ui.write(_(b"histedit aborted\n")) | ||
|
r40638 | return 0 | ||
if type(rc) is list: | ||||
|
r43347 | ui.status(_(b"performing changes\n")) | ||
|
r40638 | rules = makecommands(rc) | ||
|
r43689 | with repo.vfs(b'chistedit', b'w+') as fp: | ||
|
r40638 | for r in rules: | ||
fp.write(r) | ||||
|
r44892 | opts[b'commands'] = fp.name | ||
return _texthistedit(ui, repo, freeargs, opts) | ||||
|
r40638 | except KeyboardInterrupt: | ||
pass | ||||
return -1 | ||||
|
r43346 | |||
@command( | ||||
|
r43347 | b'histedit', | ||
|
r43346 | [ | ||
( | ||||
|
r43347 | b'', | ||
b'commands', | ||||
b'', | ||||
_(b'read history edits from the specified file'), | ||||
_(b'FILE'), | ||||
|
r43346 | ), | ||
|
r43347 | (b'c', b'continue', False, _(b'continue an edit already in progress')), | ||
(b'', b'edit-plan', False, _(b'edit remaining actions list')), | ||||
|
r43346 | ( | ||
|
r43347 | b'k', | ||
b'keep', | ||||
|
r43346 | False, | ||
|
r43347 | _(b"don't strip old nodes after edit is complete"), | ||
|
r43346 | ), | ||
|
r43347 | (b'', b'abort', False, _(b'abort an edit in progress')), | ||
(b'o', b'outgoing', False, _(b'changesets not found in destination')), | ||||
( | ||||
b'f', | ||||
b'force', | ||||
False, | ||||
_(b'force outgoing even for unrelated repositories'), | ||||
), | ||||
(b'r', b'rev', [], _(b'first revision to be edited'), _(b'REV')), | ||||
|
r43346 | ] | ||
+ cmdutil.formatteropts, | ||||
|
r43347 | _(b"[OPTIONS] ([ANCESTOR] | --outgoing [URL])"), | ||
|
r43346 | helpcategory=command.CATEGORY_CHANGE_MANAGEMENT, | ||
) | ||||
|
r19020 | def histedit(ui, repo, *freeargs, **opts): | ||
|
r17131 | """interactively edit changeset history | ||
|
r19621 | |||
|
r27713 | This command lets you edit a linear series of changesets (up to | ||
and including the working directory, which should be clean). | ||||
|
r27956 | You can: | ||
|
r27713 | |||
- `pick` to [re]order a changeset | ||||
- `drop` to omit changeset | ||||
- `mess` to reword the changeset commit message | ||||
|
r31055 | - `fold` to combine it with the preceding changeset (using the later date) | ||
|
r27713 | |||
|
r31056 | - `roll` like fold, but discarding this commit's description and date | ||
|
r27713 | |||
|
r31055 | - `edit` to edit this changeset (preserving date) | ||
|
r19622 | |||
|
r34490 | - `base` to checkout changeset and apply further changesets from there | ||
|
r27972 | There are a number of ways to select the root changeset: | ||
|
r27714 | |||
- Specify ANCESTOR directly | ||||
|
r27262 | |||
|
r27714 | - Use --outgoing -- it will be the first linear changeset not | ||
|
r28077 | included in destination. (See :hg:`help config.paths.default-push`) | ||
|
r27714 | |||
- Otherwise, the value from the "histedit.defaultrev" config option | ||||
is used as a revset to select the base revision when ANCESTOR is not | ||||
specified. The first revision returned by the revset is used. By | ||||
default, this selects the editable history that is unique to the | ||||
ancestry of the working directory. | ||||
|
r19842 | |||
|
r27630 | .. container:: verbose | ||
|
r19842 | |||
|
r27630 | If you use --outgoing, this command will abort if there are ambiguous | ||
outgoing revisions. For example, if there are multiple branches | ||||
containing outgoing revisions. | ||||
Use "min(outgoing() and ::.)" or similar revset specification | ||||
instead of --outgoing to specify edit target revision exactly in | ||||
such ambiguous situation. See :hg:`help revsets` for detail about | ||||
selecting revisions. | ||||
|
r19972 | |||
|
r27145 | .. container:: verbose | ||
Examples: | ||||
- A number of changes have been made. | ||||
Revision 3 is no longer needed. | ||||
Start history editing from revision 3:: | ||||
hg histedit -r 3 | ||||
An editor opens, containing the list of revisions, | ||||
with specific actions specified:: | ||||
pick 5339bf82f0ca 3 Zworgle the foobar | ||||
pick 8ef592ce7cc4 4 Bedazzle the zerlog | ||||
pick 0a9639fcda9d 5 Morgify the cromulancy | ||||
Additional information about the possible actions | ||||
to take appears below the list of revisions. | ||||
To remove revision 3 from the history, | ||||
its action (at the beginning of the relevant line) | ||||
is changed to 'drop':: | ||||
drop 5339bf82f0ca 3 Zworgle the foobar | ||||
pick 8ef592ce7cc4 4 Bedazzle the zerlog | ||||
pick 0a9639fcda9d 5 Morgify the cromulancy | ||||
- A number of changes have been made. | ||||
Revision 2 and 4 need to be swapped. | ||||
Start history editing from revision 2:: | ||||
hg histedit -r 2 | ||||
An editor opens, containing the list of revisions, | ||||
with specific actions specified:: | ||||
pick 252a1af424ad 2 Blorb a morgwazzle | ||||
pick 5339bf82f0ca 3 Zworgle the foobar | ||||
pick 8ef592ce7cc4 4 Bedazzle the zerlog | ||||
To swap revision 2 and 4, its lines are swapped | ||||
in the editor:: | ||||
pick 8ef592ce7cc4 4 Bedazzle the zerlog | ||||
pick 5339bf82f0ca 3 Zworgle the foobar | ||||
pick 252a1af424ad 2 Blorb a morgwazzle | ||||
|
r19972 | Returns 0 on success, 1 if user intervention is required (not only | ||
for intentional "edit" command, but also for resolving unexpected | ||||
conflicts). | ||||
|
r17064 | """ | ||
|
r44892 | opts = pycompat.byteskwargs(opts) | ||
|
r41211 | # kludge: _chistedit only works for starting an edit, not aborting | ||
# or continuing, so fall back to regular _texthistedit for those | ||||
# operations. | ||||
|
r44925 | if ui.interface(b'histedit') == b'curses' and _getgoal(opts) == goalnew: | ||
|
r44892 | return _chistedit(ui, repo, freeargs, opts) | ||
return _texthistedit(ui, repo, freeargs, opts) | ||||
def _texthistedit(ui, repo, freeargs, opts): | ||||
|
r22984 | state = histeditstate(repo) | ||
|
r41201 | with repo.wlock() as wlock, repo.lock() as lock: | ||
state.wlock = wlock | ||||
state.lock = lock | ||||
|
r44892 | _histedit(ui, repo, state, freeargs, opts) | ||
|
r20071 | |||
|
r43346 | |||
|
r43347 | goalcontinue = b'continue' | ||
goalabort = b'abort' | ||||
goaleditplan = b'edit-plan' | ||||
goalnew = b'new' | ||||
|
r28144 | |||
|
r43346 | |||
|
r28134 | def _getgoal(opts): | ||
|
r41259 | if opts.get(b'continue'): | ||
|
r28144 | return goalcontinue | ||
|
r41259 | if opts.get(b'abort'): | ||
|
r28144 | return goalabort | ||
|
r41259 | if opts.get(b'edit_plan'): | ||
|
r28144 | return goaleditplan | ||
return goalnew | ||||
|
r28134 | |||
|
r43346 | |||
|
r30262 | def _readfile(ui, path): | ||
|
r43347 | if path == b'-': | ||
with ui.timeblockedsection(b'histedit'): | ||||
|
r30983 | return ui.fin.read() | ||
|
r28550 | else: | ||
|
r43347 | with open(path, b'rb') as f: | ||
|
r28550 | return f.read() | ||
|
r43346 | |||
|
r48867 | def _validateargs(ui, repo, freeargs, opts, goal, rules, revs): | ||
|
r27169 | # TODO only abort if we try to histedit mq patches, not just | ||
|
r17064 | # blanket if mq patches are applied somewhere | ||
mq = getattr(repo, 'mq', None) | ||||
if mq and mq.applied: | ||||
|
r48868 | raise error.StateError(_(b'source has mq patches applied')) | ||
|
r17064 | |||
|
r19020 | # basic argument incompatibility processing | ||
|
r43347 | outg = opts.get(b'outgoing') | ||
editplan = opts.get(b'edit_plan') | ||||
abort = opts.get(b'abort') | ||||
force = opts.get(b'force') | ||||
|
r19020 | if force and not outg: | ||
|
r48868 | raise error.InputError(_(b'--force only allowed with --outgoing')) | ||
|
r43347 | if goal == b'continue': | ||
|
r25149 | if any((outg, abort, revs, freeargs, rules, editplan)): | ||
|
r48868 | raise error.InputError(_(b'no arguments allowed with --continue')) | ||
|
r43347 | elif goal == b'abort': | ||
|
r25149 | if any((outg, revs, freeargs, rules, editplan)): | ||
|
r48868 | raise error.InputError(_(b'no arguments allowed with --abort')) | ||
|
r43347 | elif goal == b'edit-plan': | ||
|
r25149 | if any((outg, revs, freeargs)): | ||
|
r48868 | raise error.InputError( | ||
|
r43387 | _(b'only --commands argument allowed with --edit-plan') | ||
|
r43346 | ) | ||
|
r19020 | else: | ||
if outg: | ||||
if revs: | ||||
|
r48868 | raise error.InputError( | ||
_(b'no revisions allowed with --outgoing') | ||||
) | ||||
|
r19020 | if len(freeargs) > 1: | ||
|
r48868 | raise error.InputError( | ||
|
r43347 | _(b'only one repo argument allowed with --outgoing') | ||
|
r43346 | ) | ||
|
r19020 | else: | ||
|
r19021 | revs.extend(freeargs) | ||
|
r24009 | if len(revs) == 0: | ||
|
r27262 | defaultrev = destutil.desthistedit(ui, repo) | ||
if defaultrev is not None: | ||||
revs.append(defaultrev) | ||||
|
r19021 | if len(revs) != 1: | ||
|
r48868 | raise error.InputError( | ||
|
r43347 | _(b'histedit requires exactly one ancestor revision') | ||
|
r43346 | ) | ||
|
r19020 | |||
|
r44892 | def _histedit(ui, repo, state, freeargs, opts): | ||
|
r43347 | fm = ui.formatter(b'histedit', opts) | ||
|
r35124 | fm.startitem() | ||
|
r28134 | goal = _getgoal(opts) | ||
|
r43347 | revs = opts.get(b'rev', []) | ||
nobackup = not ui.configbool(b'rewrite', b'backup-bundle') | ||||
rules = opts.get(b'commands', b'') | ||||
state.keep = opts.get(b'keep', False) | ||||
|
r17064 | |||
|
r48867 | _validateargs(ui, repo, freeargs, opts, goal, rules, revs) | ||
|
r22977 | |||
|
r41136 | hastags = False | ||
if revs: | ||||
|
r48928 | revs = logcmdutil.revrange(repo, revs) | ||
|
r41136 | ctxs = [repo[rev] for rev in revs] | ||
for ctx in ctxs: | ||||
|
r43347 | tags = [tag for tag in ctx.tags() if tag != b'tip'] | ||
|
r41136 | if not hastags: | ||
hastags = len(tags) | ||||
if hastags: | ||||
|
r43346 | if ui.promptchoice( | ||
_( | ||||
|
r43347 | b'warning: tags associated with the given' | ||
b' changeset will be lost after histedit.\n' | ||||
b'do you want to continue (yN)? $$ &Yes $$ &No' | ||||
|
r43346 | ), | ||
default=1, | ||||
): | ||||
|
r48868 | raise error.CanceledError(_(b'histedit cancelled\n')) | ||
|
r22977 | # rebuild state | ||
|
r28144 | if goal == goalcontinue: | ||
|
r22983 | state.read() | ||
|
r22980 | state = bootstrapcontinue(ui, state, opts) | ||
|
r28144 | elif goal == goaleditplan: | ||
|
r28154 | _edithisteditplan(ui, repo, state, rules) | ||
|
r24142 | return | ||
|
r28144 | elif goal == goalabort: | ||
|
r38566 | _aborthistedit(ui, repo, state, nobackup=nobackup) | ||
|
r17064 | return | ||
else: | ||||
|
r28144 | # goal == goalnew | ||
|
r28154 | _newhistedit(ui, repo, state, revs, freeargs, opts) | ||
|
r24757 | |||
|
r28154 | _continuehistedit(ui, repo, state) | ||
|
r35124 | _finishhistedit(ui, repo, state, fm) | ||
fm.end() | ||||
|
r28133 | |||
|
r43346 | |||
|
r28154 | def _continuehistedit(ui, repo, state): | ||
"""This function runs after either: | ||||
|
r28133 | - bootstrapcontinue (if the goal is 'continue') | ||
|
r28154 | - _newhistedit (if the goal is 'new') | ||
|
r28133 | """ | ||
|
r26246 | # preprocess rules so that we can hide inner folds from the user | ||
# and only show one editor | ||||
|
r27207 | actions = state.actions[:] | ||
|
r43346 | for idx, (action, nextact) in enumerate(zip(actions, actions[1:] + [None])): | ||
|
r43347 | if action.verb == b'fold' and nextact and nextact.verb == b'fold': | ||
|
r27207 | state.actions[idx].__class__ = _multifold | ||
|
r26246 | |||
|
r31513 | # Force an initial state file write, so the user can run --abort/continue | ||
# even if there's an exception before the first transaction serialize. | ||||
state.write() | ||||
|
r33445 | |||
tr = None | ||||
# Don't use singletransaction by default since it rolls the entire | ||||
# transaction back if an unexpected exception happens (like a | ||||
# pretxncommit hook throws, or the user aborts the commit msg editor). | ||||
|
r43347 | if ui.configbool(b"histedit", b"singletransaction"): | ||
|
r33445 | # Don't use a 'with' for the transaction, since actions may close | ||
# and reopen a transaction. For example, if the action executes an | ||||
# external process it may choose to commit the transaction first. | ||||
|
r43347 | tr = repo.transaction(b'histedit') | ||
|
r43346 | progress = ui.makeprogress( | ||
|
r43347 | _(b"editing"), unit=_(b'changes'), total=len(state.actions) | ||
|
r43346 | ) | ||
|
r38397 | with progress, util.acceptintervention(tr): | ||
|
r31513 | while state.actions: | ||
|
r33444 | state.write(tr=tr) | ||
|
r31513 | actobj = state.actions[0] | ||
|
r38397 | progress.increment(item=actobj.torule()) | ||
|
r43346 | ui.debug( | ||
|
r43347 | b'histedit: processing %s %s\n' % (actobj.verb, actobj.torule()) | ||
|
r43346 | ) | ||
|
r31513 | parentctx, replacement_ = actobj.run() | ||
state.parentctxnode = parentctx.node() | ||||
state.replacements.extend(replacement_) | ||||
state.actions.pop(0) | ||||
|
r24111 | state.write() | ||
|
r17064 | |||
|
r43346 | |||
|
r35124 | def _finishhistedit(ui, repo, state, fm): | ||
|
r28153 | """This action runs when histedit is finishing its session""" | ||
|
r46151 | mergemod.update(repo[state.parentctxnode]) | ||
|
r17064 | |||
|
r22985 | mapping, tmpnodes, created, ntm = processreplacement(state) | ||
|
r17758 | if mapping: | ||
|
r49768 | for prec, succs in mapping.items(): | ||
|
r17758 | if not succs: | ||
|
r46729 | ui.debug(b'histedit: %s is dropped\n' % short(prec)) | ||
|
r17758 | else: | ||
|
r43346 | ui.debug( | ||
|
r43347 | b'histedit: %s is replaced by %s\n' | ||
|
r46729 | % (short(prec), short(succs[0])) | ||
|
r43346 | ) | ||
|
r17758 | if len(succs) > 1: | ||
|
r43347 | m = b'histedit: %s' | ||
|
r17758 | for n in succs[1:]: | ||
|
r46729 | ui.debug(m % short(n)) | ||
|
r17758 | |||
|
r25330 | if not state.keep: | ||
|
r17758 | if mapping: | ||
|
r33351 | movetopmostbookmarks(repo, state.topmost, ntm) | ||
|
r17663 | # TODO update mq state | ||
|
r33350 | else: | ||
mapping = {} | ||||
for n in tmpnodes: | ||||
|
r39950 | if n in repo: | ||
mapping[n] = () | ||||
|
r33350 | |||
|
r33351 | # remove entries about unknown nodes | ||
r43947 | has_node = repo.unfiltered().changelog.index.has_node | |||
|
r43346 | mapping = { | ||
k: v | ||||
for k, v in mapping.items() | ||||
r43947 | if has_node(k) and all(has_node(n) for n in v) | |||
|
r43346 | } | ||
|
r43347 | scmutil.cleanupnodes(repo, mapping, b'histedit') | ||
|
r35124 | hf = fm.hexfunc | ||
fl = fm.formatlist | ||||
fd = fm.formatdict | ||||
|
r43346 | nodechanges = fd( | ||
{ | ||||
|
r43347 | hf(oldn): fl([hf(n) for n in newn], name=b'node') | ||
|
r49768 | for oldn, newn in mapping.items() | ||
|
r43346 | }, | ||
|
r43347 | key=b"oldnode", | ||
value=b"newnodes", | ||||
|
r43346 | ) | ||
|
r35124 | fm.data(nodechanges=nodechanges) | ||
|
r25894 | |||
|
r22978 | state.clear() | ||
|
r43347 | if os.path.exists(repo.sjoin(b'undo')): | ||
os.unlink(repo.sjoin(b'undo')) | ||||
if repo.vfs.exists(b'histedit-last-edit.txt'): | ||||
repo.vfs.unlink(b'histedit-last-edit.txt') | ||||
|
r17064 | |||
|
r43346 | |||
|
r38566 | def _aborthistedit(ui, repo, state, nobackup=False): | ||
|
r28130 | try: | ||
state.read() | ||||
|
r28179 | __, leafs, tmpnodes, __ = processreplacement(state) | ||
|
r46729 | ui.debug(b'restore wc to old parent %s\n' % short(state.topmost)) | ||
|
r28130 | |||
# Recover our old commits if necessary | ||||
if not state.topmost in repo and state.backupfile: | ||||
|
r31329 | backupfile = repo.vfs.join(state.backupfile) | ||
|
r28130 | f = hg.openpath(ui, backupfile) | ||
gen = exchange.readbundle(ui, f, backupfile) | ||||
|
r43347 | with repo.transaction(b'histedit.abort') as tr: | ||
|
r43346 | bundle2.applybundle( | ||
|
r43347 | repo, | ||
gen, | ||||
tr, | ||||
source=b'histedit', | ||||
url=b'bundle:' + backupfile, | ||||
|
r43346 | ) | ||
|
r28130 | |||
os.remove(backupfile) | ||||
# check whether we should update away | ||||
|
r43346 | if repo.unfiltered().revs( | ||
|
r43347 | b'parents() and (%n or %ln::)', | ||
|
r43346 | state.parentctxnode, | ||
leafs | tmpnodes, | ||||
): | ||||
|
r28130 | hg.clean(repo, state.topmost, show_stats=True, quietempty=True) | ||
|
r38566 | cleanupnode(ui, repo, tmpnodes, nobackup=nobackup) | ||
cleanupnode(ui, repo, leafs, nobackup=nobackup) | ||||
|
r28130 | except Exception: | ||
if state.inprogress(): | ||||
|
r43346 | ui.warn( | ||
_( | ||||
|
r43347 | b'warning: encountered an exception during histedit ' | ||
b'--abort; the repository may not have been completely ' | ||||
b'cleaned up\n' | ||||
|
r43346 | ) | ||
) | ||||
|
r28130 | raise | ||
finally: | ||||
|
r43346 | state.clear() | ||
|
r28130 | |||
|
r42787 | def hgaborthistedit(ui, repo): | ||
state = histeditstate(repo) | ||||
|
r43347 | nobackup = not ui.configbool(b'rewrite', b'backup-bundle') | ||
|
r42787 | with repo.wlock() as wlock, repo.lock() as lock: | ||
state.wlock = wlock | ||||
state.lock = lock | ||||
_aborthistedit(ui, repo, state, nobackup=nobackup) | ||||
|
r43346 | |||
|
r28154 | def _edithisteditplan(ui, repo, state, rules): | ||
|
r28131 | state.read() | ||
if not rules: | ||||
|
r43346 | comment = geteditcomment( | ||
|
r46729 | ui, short(state.parentctxnode), short(state.topmost) | ||
|
r43346 | ) | ||
|
r28131 | rules = ruleeditor(repo, ui, state.actions, comment) | ||
else: | ||||
|
r30262 | rules = _readfile(ui, rules) | ||
|
r28131 | actions = parserules(rules, state) | ||
|
r43346 | ctxs = [repo[act.node] for act in state.actions if act.node] | ||
|
r28131 | warnverifyactions(ui, repo, actions, state, ctxs) | ||
state.actions = actions | ||||
state.write() | ||||
|
r43346 | |||
|
r28154 | def _newhistedit(ui, repo, state, revs, freeargs, opts): | ||
|
r43347 | outg = opts.get(b'outgoing') | ||
rules = opts.get(b'commands', b'') | ||||
force = opts.get(b'force') | ||||
|
r28132 | |||
cmdutil.checkunfinished(repo) | ||||
cmdutil.bailifchanged(repo) | ||||
|
r41444 | topmost = repo.dirstate.p1() | ||
|
r28132 | if outg: | ||
if freeargs: | ||||
remote = freeargs[0] | ||||
else: | ||||
remote = None | ||||
root = findoutgoing(ui, repo, remote, force, opts) | ||||
else: | ||||
|
r48928 | rr = list(repo.set(b'roots(%ld)', logcmdutil.revrange(repo, revs))) | ||
|
r28132 | if len(rr) != 1: | ||
|
r48868 | raise error.InputError( | ||
|
r43346 | _( | ||
|
r43347 | b'The specified revisions must have ' | ||
b'exactly one common root' | ||||
|
r43346 | ) | ||
) | ||||
|
r28132 | root = rr[0].node() | ||
revs = between(repo, root, topmost, state.keep) | ||||
if not revs: | ||||
|
r48868 | raise error.InputError( | ||
|
r46729 | _(b'%s is not an ancestor of working directory') % short(root) | ||
|
r43346 | ) | ||
|
r28132 | |||
ctxs = [repo[r] for r in revs] | ||||
|
r43247 | |||
wctx = repo[None] | ||||
# Please don't ask me why `ancestors` is this value. I figured it | ||||
# out with print-debugging, not by actually understanding what the | ||||
# merge code is doing. :( | ||||
|
r43347 | ancs = [repo[b'.']] | ||
|
r43247 | # Sniff-test to make sure we won't collide with untracked files in | ||
# the working directory. If we don't do this, we can get a | ||||
# collision after we've started histedit and backing out gets ugly | ||||
# for everyone, especially the user. | ||||
for c in [ctxs[0].p1()] + ctxs: | ||||
try: | ||||
mergemod.calculateupdates( | ||||
|
r43346 | repo, | ||
wctx, | ||||
c, | ||||
ancs, | ||||
|
r43247 | # These parameters were determined by print-debugging | ||
# what happens later on inside histedit. | ||||
|
r43346 | branchmerge=False, | ||
force=False, | ||||
acceptremote=False, | ||||
followcopies=False, | ||||
) | ||||
|
r43247 | except error.Abort: | ||
|
r48868 | raise error.StateError( | ||
|
r43346 | _( | ||
|
r43347 | b"untracked files in working directory conflict with files in %s" | ||
|
r43346 | ) | ||
% c | ||||
) | ||||
|
r43247 | |||
|
r28132 | if not rules: | ||
|
r46729 | comment = geteditcomment(ui, short(root), short(topmost)) | ||
|
r28132 | actions = [pick(state, r) for r in revs] | ||
rules = ruleeditor(repo, ui, actions, comment) | ||||
else: | ||||
|
r30262 | rules = _readfile(ui, rules) | ||
|
r28132 | actions = parserules(rules, state) | ||
warnverifyactions(ui, repo, actions, state, ctxs) | ||||
|
r41442 | parentctxnode = repo[root].p1().node() | ||
|
r28132 | |||
state.parentctxnode = parentctxnode | ||||
state.actions = actions | ||||
state.topmost = topmost | ||||
state.replacements = [] | ||||
|
r43346 | ui.log( | ||
|
r43347 | b"histedit", | ||
b"%d actions to histedit\n", | ||||
|
r43346 | len(actions), | ||
histedit_num_actions=len(actions), | ||||
) | ||||
|
r35506 | |||
|
r28132 | # Create a backup so we can always abort completely. | ||
backupfile = None | ||||
if not obsolete.isenabled(repo, obsolete.createmarkersopt): | ||||
|
r43346 | backupfile = repair.backupbundle( | ||
|
r43347 | repo, [parentctxnode], [topmost], root, b'histedit' | ||
|
r43346 | ) | ||
|
r28132 | state.backupfile = backupfile | ||
|
r43346 | |||
|
r29467 | def _getsummary(ctx): | ||
|
r49887 | return stringutil.firstline(ctx.description()) | ||
|
r29467 | |||
|
r43346 | |||
|
r24774 | def bootstrapcontinue(ui, state, opts): | ||
repo = state.repo | ||||
|
r32057 | |||
|
r45383 | ms = mergestatemod.mergestate.read(repo) | ||
|
r32057 | mergeutil.checkunresolved(ms) | ||
|
r27207 | if state.actions: | ||
actobj = state.actions.pop(0) | ||||
|
r24959 | |||
|
r26981 | if _isdirtywc(repo): | ||
|
r24959 | actobj.continuedirty() | ||
|
r26981 | if _isdirtywc(repo): | ||
|
r27084 | abortdirty() | ||
|
r24766 | |||
|
r24959 | parentctx, replacements = actobj.continueclean() | ||
|
r17666 | |||
|
r24959 | state.parentctxnode = parentctx.node() | ||
state.replacements.extend(replacements) | ||||
|
r22980 | |||
return state | ||||
|
r17666 | |||
|
r43346 | |||
|
r17642 | def between(repo, old, new, keep): | ||
"""select and validate the set of revision to edit | ||||
When keep is false, the specified set can't have children.""" | ||||
|
r43347 | revs = repo.revs(b'%n::%n', old, new) | ||
|
r36431 | if revs and not keep: | ||
|
r44385 | rewriteutil.precheck(repo, revs, b'edit') | ||
|
r43347 | if repo.revs(b'(%ld) and merge()', revs): | ||
|
r48868 | raise error.StateError( | ||
_(b'cannot edit history that contains merges') | ||||
) | ||||
|
r36431 | return pycompat.maplist(repo.changelog.node, revs) | ||
|
r17642 | |||
|
r43346 | |||
|
r43347 | def ruleeditor(repo, ui, actions, editcomment=b""): | ||
|
r24140 | """open an editor to edit rules | ||
rules are in the format [ [act, ctx], ...] like in state.rules | ||||
""" | ||||
|
r43347 | if repo.ui.configbool(b"experimental", b"histedit.autoverb"): | ||
|
r29470 | newact = util.sortdict() | ||
|
r29465 | for act in actions: | ||
ctx = repo[act.node] | ||||
|
r29469 | summary = _getsummary(ctx) | ||
|
r43347 | fword = summary.split(b' ', 1)[0].lower() | ||
|
r29470 | added = False | ||
|
r29465 | # if it doesn't end with the special character '!' just skip this | ||
|
r43347 | if fword.endswith(b'!'): | ||
|
r29465 | fword = fword[:-1] | ||
if fword in primaryactions | secondaryactions | tertiaryactions: | ||||
act.verb = fword | ||||
|
r29470 | # get the target summary | ||
|
r43346 | tsum = summary[len(fword) + 1 :].lstrip() | ||
|
r29470 | # safe but slow: reverse iterate over the actions so we | ||
# don't clash on two commits having the same summary | ||||
|
r49768 | for na, l in reversed(list(newact.items())): | ||
|
r29470 | actx = repo[na.node] | ||
asum = _getsummary(actx) | ||||
if asum == tsum: | ||||
added = True | ||||
l.append(act) | ||||
break | ||||
if not added: | ||||
newact[act] = [] | ||||
# copy over and flatten the new list | ||||
actions = [] | ||||
|
r49768 | for na, l in newact.items(): | ||
|
r29470 | actions.append(na) | ||
actions += l | ||||
|
r29465 | |||
|
r43347 | rules = b'\n'.join([act.torule() for act in actions]) | ||
rules += b'\n\n' | ||||
|
r24140 | rules += editcomment | ||
|
r43346 | rules = ui.edit( | ||
rules, | ||||
ui.username(), | ||||
|
r43347 | {b'prefix': b'histedit'}, | ||
|
r43346 | repopath=repo.path, | ||
|
r43347 | action=b'histedit', | ||
|
r43346 | ) | ||
|
r24140 | |||
# Save edit rules in .hg/histedit-last-edit.txt in case | ||||
# the user needs to ask for help after something | ||||
# surprising happens. | ||||
|
r43347 | with repo.vfs(b'histedit-last-edit.txt', b'wb') as f: | ||
|
r36186 | f.write(rules) | ||
|
r24140 | |||
return rules | ||||
|
r43346 | |||
|
r27208 | def parserules(rules, state): | ||
|
r47856 | """Read the histedit rules string and return list of action objects""" | ||
|
r43346 | rules = [ | ||
l | ||||
for l in (r.strip() for r in rules.splitlines()) | ||||
|
r43347 | if l and not l.startswith(b'#') | ||
|
r43346 | ] | ||
|
r27208 | actions = [] | ||
|
r17064 | for r in rules: | ||
|
r43347 | if b' ' not in r: | ||
raise error.ParseError(_(b'malformed line "%s"') % r) | ||||
verb, rest = r.split(b' ', 1) | ||||
|
r27082 | |||
|
r27208 | if verb not in actiontable: | ||
|
r43347 | raise error.ParseError(_(b'unknown action "%s"') % verb) | ||
|
r27208 | |||
|
r27082 | action = actiontable[verb].fromrule(state, rest) | ||
|
r27208 | actions.append(action) | ||
return actions | ||||
|
r43346 | |||
|
r27543 | def warnverifyactions(ui, repo, actions, state, ctxs): | ||
try: | ||||
verifyactions(actions, state, ctxs) | ||||
|
r27545 | except error.ParseError: | ||
|
r43347 | if repo.vfs.exists(b'histedit-last-edit.txt'): | ||
|
r43346 | ui.warn( | ||
_( | ||||
|
r43347 | b'warning: histedit rules saved ' | ||
b'to: .hg/histedit-last-edit.txt\n' | ||||
|
r43346 | ) | ||
) | ||||
|
r27543 | raise | ||
|
r43346 | |||
|
r27208 | def verifyactions(actions, state, ctxs): | ||
"""Verify that there exists exactly one action per given changeset and | ||||
other constraints. | ||||
Will abort if there are to many or too few rules, a malformed rule, | ||||
or a rule on a changeset outside of the user-given range. | ||||
""" | ||||
|
r44937 | expected = {c.node() for c in ctxs} | ||
|
r27208 | seen = set() | ||
|
r27541 | prev = None | ||
|
r33757 | |||
|
r43347 | if actions and actions[0].verb in [b'roll', b'fold']: | ||
|
r43346 | raise error.ParseError( | ||
|
r43347 | _(b'first changeset cannot use verb "%s"') % actions[0].verb | ||
|
r43346 | ) | ||
|
r33757 | |||
|
r27208 | for action in actions: | ||
|
r29879 | action.verify(prev, expected, seen) | ||
|
r27541 | prev = action | ||
|
r29876 | if action.node is not None: | ||
|
r29878 | seen.add(action.node) | ||
|
r19048 | missing = sorted(expected - seen) # sort to stabilize output | ||
|
r27414 | |||
|
r43347 | if state.repo.ui.configbool(b'histedit', b'dropmissing'): | ||
|
r28519 | if len(actions) == 0: | ||
|
r43346 | raise error.ParseError( | ||
|
r43347 | _(b'no rules provided'), | ||
hint=_(b'use strip extension to remove commits'), | ||||
|
r43346 | ) | ||
|
r28519 | |||
|
r29878 | drops = [drop(state, n) for n in missing] | ||
|
r27414 | # put the in the beginning so they execute immediately and | ||
# don't show in the edit-plan in the future | ||||
actions[:0] = drops | ||||
elif missing: | ||||
|
r43346 | raise error.ParseError( | ||
|
r46729 | _(b'missing rules for changeset %s') % short(missing[0]), | ||
|
r43346 | hint=_( | ||
|
r43347 | b'use "drop %s" to discard, see also: ' | ||
b"'hg help -e histedit.config'" | ||||
|
r43346 | ) | ||
|
r46729 | % short(missing[0]), | ||
|
r43346 | ) | ||
|
r17663 | |||
|
r28216 | def adjustreplacementsfrommarkers(repo, oldreplacements): | ||
|
r30332 | """Adjust replacements from obsolescence markers | ||
|
r28216 | |||
Replacements structure is originally generated based on | ||||
histedit's state and does not account for changes that are | ||||
not recorded there. This function fixes that by adding | ||||
|
r30332 | data read from obsolescence markers""" | ||
|
r28216 | if not obsolete.isenabled(repo, obsolete.createmarkersopt): | ||
return oldreplacements | ||||
unfi = repo.unfiltered() | ||||
r43968 | get_rev = unfi.changelog.index.get_rev | |||
|
r28224 | obsstore = repo.obsstore | ||
|
r28216 | newreplacements = list(oldreplacements) | ||
oldsuccs = [r[1] for r in oldreplacements] | ||||
# successors that have already been added to succstocheck once | ||||
|
r43346 | seensuccs = set().union( | ||
*oldsuccs | ||||
) # create a set from an iterable of tuples | ||||
|
r28216 | succstocheck = list(seensuccs) | ||
while succstocheck: | ||||
n = succstocheck.pop() | ||||
r43968 | missing = get_rev(n) is None | |||
|
r28224 | markers = obsstore.successors.get(n, ()) | ||
if missing and not markers: | ||||
# dead end, mark it as such | ||||
|
r28216 | newreplacements.append((n, ())) | ||
|
r28224 | for marker in markers: | ||
nsuccs = marker[1] | ||||
|
r28216 | newreplacements.append((n, nsuccs)) | ||
for nsucc in nsuccs: | ||||
if nsucc not in seensuccs: | ||||
seensuccs.add(nsucc) | ||||
succstocheck.append(nsucc) | ||||
return newreplacements | ||||
|
r43346 | |||
|
r22985 | def processreplacement(state): | ||
|
r17758 | """process the list of replacements to return | ||
1) the final mapping between original and created nodes | ||||
2) the list of temporary node created by histedit | ||||
3) the list of new commit created by histedit""" | ||||
|
r28216 | replacements = adjustreplacementsfrommarkers(state.repo, state.replacements) | ||
|
r17758 | allsuccs = set() | ||
replaced = set() | ||||
fullmapping = {} | ||||
|
r26039 | # initialize basic set | ||
# fullmapping records all operations recorded in replacement | ||||
|
r17758 | for rep in replacements: | ||
allsuccs.update(rep[1]) | ||||
replaced.add(rep[0]) | ||||
fullmapping.setdefault(rep[0], set()).update(rep[1]) | ||||
new = allsuccs - replaced | ||||
tmpnodes = allsuccs & replaced | ||||
|
r26039 | # Reduce content fullmapping into direct relation between original nodes | ||
|
r17758 | # and final node created during history edition | ||
# Dropped changeset are replaced by an empty list | ||||
toproceed = set(fullmapping) | ||||
final = {} | ||||
while toproceed: | ||||
for x in list(toproceed): | ||||
succs = fullmapping[x] | ||||
for s in list(succs): | ||||
if s in toproceed: | ||||
# non final node with unknown closure | ||||
# We can't process this now | ||||
break | ||||
elif s in final: | ||||
# non final node, replace with closure | ||||
succs.remove(s) | ||||
succs.update(final[s]) | ||||
else: | ||||
final[x] = succs | ||||
toproceed.remove(x) | ||||
# remove tmpnodes from final mapping | ||||
for n in tmpnodes: | ||||
del final[n] | ||||
# we expect all changes involved in final to exist in the repo | ||||
# turn `final` into list (topologically sorted) | ||||
r43969 | get_rev = state.repo.changelog.index.get_rev | |||
|
r17758 | for prec, succs in final.items(): | ||
r43969 | final[prec] = sorted(succs, key=get_rev) | |||
|
r17663 | |||
|
r17758 | # computed topmost element (necessary for bookmark) | ||
if new: | ||||
|
r22985 | newtopmost = sorted(new, key=state.repo.changelog.rev)[-1] | ||
|
r17758 | elif not final: | ||
# Nothing rewritten at all. we won't need `newtopmost` | ||||
# It is the same as `oldtopmost` and `processreplacement` know it | ||||
newtopmost = None | ||||
else: | ||||
# every body died. The newtopmost is the parent of the root. | ||||
|
r22985 | r = state.repo.changelog.rev | ||
newtopmost = state.repo[sorted(final, key=r)[0]].p1().node() | ||||
|
r17758 | |||
return final, tmpnodes, new, newtopmost | ||||
|
r17663 | |||
|
r43346 | |||
|
r33346 | def movetopmostbookmarks(repo, oldtopmost, newtopmost): | ||
"""Move bookmark from oldtopmost to newly created topmost | ||||
This is arguably a feature and we may only want that for the active | ||||
bookmark. But the behavior is kept compatible with the old version for now. | ||||
""" | ||||
if not oldtopmost or not newtopmost: | ||||
return | ||||
oldbmarks = repo.nodebookmarks(oldtopmost) | ||||
if oldbmarks: | ||||
|
r43347 | with repo.lock(), repo.transaction(b'histedit') as tr: | ||
|
r33346 | marks = repo._bookmarks | ||
|
r33486 | changes = [] | ||
|
r33346 | for name in oldbmarks: | ||
|
r33486 | changes.append((name, newtopmost)) | ||
marks.applychanges(repo, tr, changes) | ||||
|
r33346 | |||
|
r43346 | |||
|
r38566 | def cleanupnode(ui, repo, nodes, nobackup=False): | ||
|
r31637 | """strip a group of nodes from the repository | ||
The set of node to strip may contains unknown nodes.""" | ||||
with repo.lock(): | ||||
# do not let filtering get in the way of the cleanse | ||||
# we should probably get rid of obsolescence marker created during the | ||||
# histedit, but we currently do not have such information. | ||||
repo = repo.unfiltered() | ||||
# Find all nodes that need to be stripped | ||||
# (we use %lr instead of %ln to silently ignore unknown items) | ||||
r43948 | has_node = repo.changelog.index.has_node | |||
nodes = sorted(n for n in nodes if has_node(n)) | ||||
|
r43347 | roots = [c.node() for c in repo.set(b"roots(%ln)", nodes)] | ||
|
r33349 | if roots: | ||
|
r38566 | backup = not nobackup | ||
repair.strip(ui, repo, roots, backup=backup) | ||||
|
r31637 | |||
|
r43346 | |||
|
r24111 | def stripwrapper(orig, ui, repo, nodelist, *args, **kwargs): | ||
|
r44182 | if isinstance(nodelist, bytes): | ||
|
r24111 | nodelist = [nodelist] | ||
|
r38822 | state = histeditstate(repo) | ||
if state.inprogress(): | ||||
|
r24111 | state.read() | ||
|
r43346 | histedit_nodes = { | ||
action.node for action in state.actions if action.node | ||||
} | ||||
|
r30025 | common_nodes = histedit_nodes & set(nodelist) | ||
|
r24111 | if common_nodes: | ||
|
r43346 | raise error.Abort( | ||
|
r43347 | _(b"histedit in progress, can't strip %s") | ||
|
r46729 | % b', '.join(short(x) for x in common_nodes) | ||
|
r43346 | ) | ||
|
r24111 | return orig(ui, repo, nodelist, *args, **kwargs) | ||
|
r43346 | |||
r51674 | extensions.wrapfunction(repair, 'strip', stripwrapper) | |||
|
r24111 | |||
|
r43346 | |||
|
r19215 | def summaryhook(ui, repo): | ||
|
r38822 | state = histeditstate(repo) | ||
if not state.inprogress(): | ||||
|
r19215 | return | ||
|
r22983 | state.read() | ||
|
r27207 | if state.actions: | ||
|
r19215 | # i18n: column positioning for "hg summary" | ||
|
r43346 | ui.write( | ||
|
r43347 | _(b'hist: %s (histedit --continue)\n') | ||
|
r43346 | % ( | ||
|
r43347 | ui.label(_(b'%d remaining'), b'histedit.remaining') | ||
|
r43346 | % len(state.actions) | ||
) | ||||
) | ||||
|
r19215 | |||
def extsetup(ui): | ||||
|
r43347 | cmdutil.summaryhooks.add(b'histedit', summaryhook) | ||
|
r43346 | statemod.addunfinished( | ||
|
r43347 | b'histedit', | ||
fname=b'histedit-state', | ||||
|
r43346 | allowcommit=True, | ||
continueflag=True, | ||||
abortfunc=hgaborthistedit, | ||||
) | ||||