histedit.py
2347 lines
| 81.5 KiB
| text/x-python
|
PythonLexer
/ hgext / histedit.py
Augie Fackler
|
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. | ||||
Augie Fackler
|
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 | ||||
FUJIWARA Katsunori
|
r18322 | # Edit history between c561b4e977df and 7c2fd3b9020c | ||
Augie Fackler
|
r17131 | # | ||
Adrian Zgorzałek
|
r20503 | # Commits are listed from least to most recent | ||
# | ||||
Augie Fackler
|
r17131 | # Commands: | ||
# p, pick = use commit | ||||
# e, edit = use commit, but stop for amending | ||||
Matt Mackall
|
r20511 | # f, fold = use commit, but combine it with the one above | ||
Ben Schmidt
|
r31056 | # r, roll = like fold, but discard this commit's description and date | ||
Augie Fackler
|
r17131 | # d, drop = remove commit from history | ||
timeless@mozdev.org
|
r26100 | # m, mess = edit commit message without changing commit content | ||
Saurabh Singh
|
r34490 | # b, base = checkout changeset and apply further changesets from there | ||
Augie Fackler
|
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 | ||||
FUJIWARA Katsunori
|
r18322 | # Edit history between c561b4e977df and 7c2fd3b9020c | ||
Augie Fackler
|
r17131 | # | ||
Adrian Zgorzałek
|
r20503 | # Commits are listed from least to most recent | ||
# | ||||
Augie Fackler
|
r17131 | # Commands: | ||
# p, pick = use commit | ||||
# e, edit = use commit, but stop for amending | ||||
Matt Mackall
|
r20511 | # f, fold = use commit, but combine it with the one above | ||
Ben Schmidt
|
r31056 | # r, roll = like fold, but discard this commit's description and date | ||
Augie Fackler
|
r17131 | # d, drop = remove commit from history | ||
timeless@mozdev.org
|
r26100 | # m, mess = edit commit message without changing commit content | ||
Saurabh Singh
|
r34490 | # b, base = checkout changeset and apply further changesets from there | ||
Augie Fackler
|
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 | ||||
Augie Fackler
|
r17064 | |||
Ben Schmidt
|
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:: | ||||
Augie Fackler
|
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 | ||||
Ben Schmidt
|
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. | ||||
Augie Fackler
|
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. | ||||
FUJIWARA Katsunori
|
r18323 | If we clone the histedit-ed example repository above and add four more | ||
changes, such that we have the following history:: | ||||
Augie Fackler
|
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. | ||||
Mateusz Kwapich
|
r24199 | |||
Mateusz Kwapich
|
r27414 | Config | ||
------ | ||||
Mateusz Kwapich
|
r24199 | Histedit rule lines are truncated to 80 characters by default. You | ||
timeless@mozdev.org
|
r26171 | can customize this behavior by setting a different length in your | ||
FUJIWARA Katsunori
|
r24869 | configuration file:: | ||
Mateusz Kwapich
|
r24199 | |||
FUJIWARA Katsunori
|
r24869 | [histedit] | ||
linelen = 120 # truncate rule lines at 120 characters | ||||
Gregory Szorc
|
r27262 | |||
Augie Fackler
|
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. | ||||
Gregory Szorc
|
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() | ||||
Mateusz Kwapich
|
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 | ||||
FUJIWARA Katsunori
|
r27957 | the drop to be implicit for missing commits by adding:: | ||
Mateusz Kwapich
|
r27414 | |||
[histedit] | ||||
dropmissing = True | ||||
Durham Goode
|
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 | ||||
Augie Fackler
|
r17064 | """ | ||
Augie Fackler
|
r17131 | |||
Pulkit Goyal
|
r29126 | from __future__ import absolute_import | ||
Matt Harbison
|
r40688 | # chistedit dependencies that are not available everywhere | ||
try: | ||||
import fcntl | ||||
import termios | ||||
except ImportError: | ||||
fcntl = None | ||||
termios = None | ||||
Augie Fackler
|
r40638 | import functools | ||
Yuya Nishihara
|
r42883 | import locale | ||
Augie Fackler
|
r17064 | import os | ||
Augie Fackler
|
r40638 | import struct | ||
Yuya Nishihara
|
r29205 | |||
from mercurial.i18n import _ | ||||
Pulkit Goyal
|
r29126 | from mercurial import ( | ||
bundle2, | ||||
cmdutil, | ||||
context, | ||||
copies, | ||||
destutil, | ||||
discovery, | ||||
error, | ||||
exchange, | ||||
extensions, | ||||
hg, | ||||
Augie Fackler
|
r40638 | logcmdutil, | ||
Pulkit Goyal
|
r29126 | merge as mergemod, | ||
Siddharth Agarwal
|
r32057 | mergeutil, | ||
Pulkit Goyal
|
r29126 | node, | ||
obsolete, | ||||
Pulkit Goyal
|
r35000 | pycompat, | ||
Yuya Nishihara
|
r32337 | registrar, | ||
Pulkit Goyal
|
r29126 | repair, | ||
scmutil, | ||||
Pulkit Goyal
|
r38525 | state as statemod, | ||
Pulkit Goyal
|
r29126 | util, | ||
) | ||||
Yuya Nishihara
|
r37102 | from mercurial.utils import ( | ||
Taapas Agrawal
|
r41249 | dateutil, | ||
Yuya Nishihara
|
r37102 | stringutil, | ||
) | ||||
Augie Fackler
|
r17064 | |||
Pulkit Goyal
|
r29324 | pickle = util.pickle | ||
Adrian Buehlmann
|
r17147 | cmdtable = {} | ||
Yuya Nishihara
|
r32337 | command = registrar.command(cmdtable) | ||
Adrian Buehlmann
|
r17147 | |||
Boris Feld
|
r34472 | configtable = {} | ||
configitem = registrar.configitem(configtable) | ||||
Boris Feld
|
r34476 | configitem('experimental', 'histedit.autoverb', | ||
default=False, | ||||
) | ||||
Boris Feld
|
r34472 | configitem('histedit', 'defaultrev', | ||
Boris Feld
|
r37021 | default=None, | ||
Boris Feld
|
r34472 | ) | ||
Boris Feld
|
r34473 | configitem('histedit', 'dropmissing', | ||
default=False, | ||||
) | ||||
Boris Feld
|
r34474 | configitem('histedit', 'linelen', | ||
default=80, | ||||
) | ||||
Boris Feld
|
r34475 | configitem('histedit', 'singletransaction', | ||
default=False, | ||||
) | ||||
Augie Fackler
|
r40638 | configitem('ui', 'interface.histedit', | ||
default=None, | ||||
) | ||||
Augie Fackler
|
r41650 | configitem('histedit', 'summary-template', | ||
default='{rev} {desc|firstline}') | ||||
Boris Feld
|
r34472 | |||
Augie Fackler
|
r29841 | # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for | ||
Augie Fackler
|
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. | ||||
Augie Fackler
|
r29841 | testedwith = 'ships-with-hg-core' | ||
Augie Fackler
|
r17064 | |||
timeless
|
r27675 | actiontable = {} | ||
primaryactions = set() | ||||
secondaryactions = set() | ||||
tertiaryactions = set() | ||||
internalactions = set() | ||||
Mateusz Kwapich
|
r28592 | def geteditcomment(ui, first, last): | ||
timeless
|
r27673 | """ construct the editor comment | ||
The comment includes:: | ||||
- an intro | ||||
timeless
|
r27674 | - sorted primary commands | ||
- sorted short commands | ||||
timeless
|
r27675 | - sorted long commands | ||
Mateusz Kwapich
|
r28592 | - additional hints | ||
timeless
|
r27673 | |||
Commands are only included once. | ||||
""" | ||||
intro = _("""Edit history between %s and %s | ||||
Commits are listed from least to most recent | ||||
liscju
|
r28396 | You can reorder changesets by reordering the lines | ||
timeless
|
r27675 | Commands: | ||
FUJIWARA Katsunori
|
r17315 | """) | ||
timeless
|
r27675 | actions = [] | ||
def addverb(v): | ||||
a = actiontable[v] | ||||
lines = a.message.split("\n") | ||||
if len(a.verbs): | ||||
v = ', '.join(sorted(a.verbs, key=lambda v: len(v))) | ||||
actions.append(" %s = %s" % (v, lines[0])) | ||||
actions.extend([' %s' for l in lines[1:]]) | ||||
for v in ( | ||||
sorted(primaryactions) + | ||||
sorted(secondaryactions) + | ||||
sorted(tertiaryactions) | ||||
): | ||||
addverb(v) | ||||
actions.append('') | ||||
Augie Fackler
|
r17064 | |||
Mateusz Kwapich
|
r28592 | hints = [] | ||
if ui.configbool('histedit', 'dropmissing'): | ||||
hints.append("Deleting a changeset from the list " | ||||
"will DISCARD it from the edited history!") | ||||
lines = (intro % (first, last)).split('\n') + actions + hints | ||||
return ''.join(['# %s\n' % l if l else '#\n' for l in lines]) | ||||
timeless
|
r27673 | |||
David Soria Parra
|
r22976 | class histeditstate(object): | ||
Martin von Zweigbergk
|
r41200 | def __init__(self, repo): | ||
David Soria Parra
|
r22976 | self.repo = repo | ||
Martin von Zweigbergk
|
r41200 | self.actions = None | ||
self.keep = None | ||||
self.topmost = None | ||||
self.parentctxnode = None | ||||
self.lock = None | ||||
self.wlock = None | ||||
Durham Goode
|
r24757 | self.backupfile = None | ||
Pulkit Goyal
|
r38525 | self.stateobj = statemod.cmdstate(repo, 'histedit-state') | ||
Martin von Zweigbergk
|
r41200 | self.replacements = [] | ||
David Soria Parra
|
r22976 | |||
David Soria Parra
|
r22983 | def read(self): | ||
Augie Fackler
|
r22986 | """Load histedit state from disk and set fields appropriately.""" | ||
Pulkit Goyal
|
r38526 | if not self.stateobj.exists(): | ||
timeless
|
r28123 | cmdutil.wrongtooltocontinue(self.repo, _('histedit')) | ||
David Soria Parra
|
r22983 | |||
Pulkit Goyal
|
r38526 | data = self._read() | ||
Pulkit Goyal
|
r38524 | |||
self.parentctxnode = data['parentctxnode'] | ||||
actions = parserules(data['rules'], self) | ||||
self.actions = actions | ||||
self.keep = data['keep'] | ||||
self.topmost = data['topmost'] | ||||
self.replacements = data['replacements'] | ||||
self.backupfile = data['backupfile'] | ||||
Pulkit Goyal
|
r38526 | def _read(self): | ||
fp = self.repo.vfs.read('histedit-state') | ||||
Pulkit Goyal
|
r38524 | if fp.startswith('v1\n'): | ||
Bryan O'Sullivan
|
r27527 | data = self._load() | ||
parentctxnode, rules, keep, topmost, replacements, backupfile = data | ||||
else: | ||||
Pulkit Goyal
|
r38524 | data = pickle.loads(fp) | ||
Durham Goode
|
r24756 | parentctxnode, rules, keep, topmost, replacements = data | ||
Durham Goode
|
r24757 | backupfile = None | ||
Pulkit Goyal
|
r38524 | rules = "\n".join(["%s %s" % (verb, rest) for [verb, rest] in rules]) | ||
David Soria Parra
|
r22983 | |||
Pulkit Goyal
|
r38524 | return {'parentctxnode': parentctxnode, "rules": rules, "keep": keep, | ||
"topmost": topmost, "replacements": replacements, | ||||
"backupfile": backupfile} | ||||
David Soria Parra
|
r22983 | |||
Durham Goode
|
r31511 | def write(self, tr=None): | ||
if tr: | ||||
tr.addfilegenerator('histedit-state', ('histedit-state',), | ||||
self._write, location='plain') | ||||
else: | ||||
with self.repo.vfs("histedit-state", "w") as f: | ||||
self._write(f) | ||||
def _write(self, fp): | ||||
Durham Goode
|
r24756 | fp.write('v1\n') | ||
fp.write('%s\n' % node.hex(self.parentctxnode)) | ||||
fp.write('%s\n' % node.hex(self.topmost)) | ||||
Augie Fackler
|
r36185 | fp.write('%s\n' % ('True' if self.keep else 'False')) | ||
Mateusz Kwapich
|
r27208 | fp.write('%d\n' % len(self.actions)) | ||
for action in self.actions: | ||||
fp.write('%s\n' % action.tostate()) | ||||
Durham Goode
|
r24756 | fp.write('%d\n' % len(self.replacements)) | ||
for replacement in self.replacements: | ||||
fp.write('%s%s\n' % (node.hex(replacement[0]), ''.join(node.hex(r) | ||||
for r in replacement[1]))) | ||||
Durham Goode
|
r24958 | backupfile = self.backupfile | ||
if not backupfile: | ||||
backupfile = '' | ||||
fp.write('%s\n' % backupfile) | ||||
David Soria Parra
|
r22976 | |||
Durham Goode
|
r24756 | def _load(self): | ||
fp = self.repo.vfs('histedit-state', 'r') | ||||
lines = [l[:-1] for l in fp.readlines()] | ||||
index = 0 | ||||
lines[index] # version number | ||||
index += 1 | ||||
parentctxnode = node.bin(lines[index]) | ||||
index += 1 | ||||
topmost = node.bin(lines[index]) | ||||
index += 1 | ||||
keep = lines[index] == 'True' | ||||
index += 1 | ||||
# Rules | ||||
rules = [] | ||||
rulelen = int(lines[index]) | ||||
index += 1 | ||||
Gregory Szorc
|
r38806 | for i in pycompat.xrange(rulelen): | ||
Durham Goode
|
r24810 | ruleaction = lines[index] | ||
index += 1 | ||||
Durham Goode
|
r24756 | rule = lines[index] | ||
index += 1 | ||||
Durham Goode
|
r24810 | rules.append((ruleaction, rule)) | ||
Durham Goode
|
r24756 | |||
# Replacements | ||||
replacements = [] | ||||
replacementlen = int(lines[index]) | ||||
index += 1 | ||||
Gregory Szorc
|
r38806 | for i in pycompat.xrange(replacementlen): | ||
Durham Goode
|
r24756 | replacement = lines[index] | ||
original = node.bin(replacement[:40]) | ||||
succ = [node.bin(replacement[i:i + 40]) for i in | ||||
range(40, len(replacement), 40)] | ||||
replacements.append((original, succ)) | ||||
index += 1 | ||||
Durham Goode
|
r24757 | backupfile = lines[index] | ||
index += 1 | ||||
Durham Goode
|
r24756 | fp.close() | ||
Durham Goode
|
r24757 | return parentctxnode, rules, keep, topmost, replacements, backupfile | ||
Durham Goode
|
r24756 | |||
David Soria Parra
|
r22978 | def clear(self): | ||
Christian Delahousse
|
r26583 | if self.inprogress(): | ||
self.repo.vfs.unlink('histedit-state') | ||||
David Soria Parra
|
r22978 | |||
Christian Delahousse
|
r26582 | def inprogress(self): | ||
return self.repo.vfs.exists('histedit-state') | ||||
Mateusz Kwapich
|
r27200 | |||
Durham Goode
|
r24765 | class histeditaction(object): | ||
def __init__(self, state, node): | ||||
self.state = state | ||||
self.repo = state.repo | ||||
self.node = node | ||||
@classmethod | ||||
def fromrule(cls, state, rule): | ||||
"""Parses the given rule, returning an instance of the histeditaction. | ||||
""" | ||||
Sangeet Kumar Mishra
|
r37124 | ruleid = rule.strip().split(' ', 1)[0] | ||
# ruleid can be anything from rev numbers, hashes, "bookmarks" etc | ||||
# Check for validation of rule ids and get the rulehash | ||||
timeless
|
r27547 | try: | ||
Sangeet Kumar Mishra
|
r37124 | rev = node.bin(ruleid) | ||
Augie Fackler
|
r36256 | except TypeError: | ||
Sangeet Kumar Mishra
|
r37124 | try: | ||
_ctx = scmutil.revsingle(state.repo, ruleid) | ||||
rulehash = _ctx.hex() | ||||
rev = node.bin(rulehash) | ||||
except error.RepoLookupError: | ||||
Sangeet Kumar Mishra
|
r37285 | raise error.ParseError(_("invalid changeset %s") % ruleid) | ||
timeless
|
r27547 | return cls(state, rev) | ||
Mateusz Kwapich
|
r27202 | |||
Pierre-Yves David
|
r29879 | def verify(self, prev, expected, seen): | ||
Mateusz Kwapich
|
r27202 | """ Verifies semantic correctness of the rule""" | ||
repo = self.repo | ||||
ha = node.hex(self.node) | ||||
Martin von Zweigbergk
|
r37696 | self.node = scmutil.resolvehexnodeidprefix(repo, ha) | ||
Martin von Zweigbergk
|
r37524 | if self.node is None: | ||
raise error.ParseError(_('unknown changeset %s listed') % ha[:12]) | ||||
Martin von Zweigbergk
|
r37523 | self._verifynodeconstraints(prev, expected, seen) | ||
Pierre-Yves David
|
r29879 | |||
Pierre-Yves David
|
r29880 | def _verifynodeconstraints(self, prev, expected, seen): | ||
# by default command need a node in the edited list | ||||
if self.node not in expected: | ||||
raise error.ParseError(_('%s "%s" changeset was not a candidate') | ||||
% (self.verb, node.short(self.node)), | ||||
hint=_('only use listed changesets')) | ||||
# and only one command per node | ||||
if self.node in seen: | ||||
raise error.ParseError(_('duplicated command for changeset %s') % | ||||
node.short(self.node)) | ||||
Durham Goode
|
r24765 | |||
Sean Farley
|
r29466 | def torule(self): | ||
Mateusz Kwapich
|
r27203 | """build a histedit rule line for an action | ||
by default lines are in the form: | ||||
<hash> <rev> <summary> | ||||
""" | ||||
ctx = self.repo[self.node] | ||||
Augie Fackler
|
r41650 | ui = self.repo.ui | ||
summary = cmdutil.rendertemplate( | ||||
ctx, ui.config('histedit', 'summary-template')) or '' | ||||
summary = summary.splitlines()[0] | ||||
line = '%s %s %s' % (self.verb, ctx, summary) | ||||
Mateusz Kwapich
|
r27203 | # trim to 75 columns by default so it's not stupidly wide in my editor | ||
# (the 5 more are left for verb) | ||||
Boris Feld
|
r34474 | maxlen = self.repo.ui.configint('histedit', 'linelen') | ||
Mateusz Kwapich
|
r27203 | maxlen = max(maxlen, 22) # avoid truncating hash | ||
Yuya Nishihara
|
r37102 | return stringutil.ellipsis(line, maxlen) | ||
Mateusz Kwapich
|
r27203 | |||
Mateusz Kwapich
|
r27206 | def tostate(self): | ||
"""Print an action in format used by histedit state files | ||||
(the first line is a verb, the remainder is the second) | ||||
""" | ||||
return "%s\n%s" % (self.verb, node.hex(self.node)) | ||||
Durham Goode
|
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] | ||||
timeless
|
r28004 | repo.ui.pushbuffer(error=True, labeled=True) | ||
timeless
|
r27405 | hg.update(repo, self.state.parentctxnode, quietempty=True) | ||
Rodrigo Damazio Bovendorp
|
r42219 | repo.ui.popbuffer() | ||
Durham Goode
|
r24765 | stats = applychanges(repo.ui, repo, rulectx, {}) | ||
Boris Feld
|
r35391 | repo.dirstate.setbranch(rulectx.branch()) | ||
Gregory Szorc
|
r37143 | if stats.unresolvedcount: | ||
timeless
|
r27629 | raise error.InterventionRequired( | ||
_('Fix up the change (%s %s)') % | ||||
(self.verb, node.short(self.node)), | ||||
hint=_('hg histedit --continue to resume')) | ||||
Durham Goode
|
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) | ||||
Taapas Agrawal
|
r41249 | if repo.ui.configbool('rewrite', 'update-timestamp'): | ||
date = dateutil.makedate() | ||||
else: | ||||
date = rulectx.date() | ||||
Durham Goode
|
r24765 | commit(text=rulectx.description(), user=rulectx.user(), | ||
Taapas Agrawal
|
r41249 | date=date, extra=rulectx.extra(), editor=editor) | ||
Durham Goode
|
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.""" | ||||
ctx = self.repo['.'] | ||||
if ctx.node() == self.state.parentctxnode: | ||||
timeless
|
r28340 | self.repo.ui.warn(_('%s: skipping changeset (no changes)\n') % | ||
Durham Goode
|
r24765 | node.short(self.node)) | ||
return ctx, [(self.node, tuple())] | ||||
if ctx.node() == self.node: | ||||
# Nothing changed | ||||
return ctx, [] | ||||
return ctx, [(self.node, (ctx.node(),))] | ||||
Pierre-Yves David
|
r18436 | def commitfuncfor(repo, src): | ||
"""Build a commit function for the replacement of <src> | ||||
Mads Kiilerich
|
r18644 | This function ensure we apply the same treatment to all changesets. | ||
Pierre-Yves David
|
r18436 | |||
Pierre-Yves David
|
r18437 | - Add a 'histedit_source' entry in extra. | ||
Pierre-Yves David
|
r18436 | |||
Augie Fackler
|
r25450 | Note that fold has its own separated logic because its handling is a bit | ||
Pierre-Yves David
|
r18436 | different and not easily factored out of the fold method. | ||
""" | ||||
Pierre-Yves David
|
r18440 | phasemin = src.phase() | ||
Pierre-Yves David
|
r18436 | def commitfunc(**kwargs): | ||
Jun Wu
|
r31459 | overrides = {('phases', 'new-commit'): phasemin} | ||
with repo.ui.configoverride(overrides, 'histedit'): | ||||
Pulkit Goyal
|
r35000 | extra = kwargs.get(r'extra', {}).copy() | ||
Pierre-Yves David
|
r18440 | extra['histedit_source'] = src.hex() | ||
Pulkit Goyal
|
r35000 | kwargs[r'extra'] = extra | ||
Pierre-Yves David
|
r18440 | return repo.commit(**kwargs) | ||
Pierre-Yves David
|
r18436 | return commitfunc | ||
Pierre-Yves David
|
r17647 | def applychanges(ui, repo, ctx, opts): | ||
"""Merge changeset from ctx (only) in the current working directory""" | ||||
Martin von Zweigbergk
|
r41442 | wcpar = repo.dirstate.p1() | ||
Pierre-Yves David
|
r17647 | if ctx.p1().node() == wcpar: | ||
timeless@mozdev.org
|
r26171 | # edits are "in place" we do not need to make any merge, | ||
timeless
|
r27603 | # just applies changes on parent for editing | ||
Rodrigo Damazio Bovendorp
|
r42219 | ui.pushbuffer() | ||
Pierre-Yves David
|
r17647 | cmdutil.revert(ui, repo, ctx, (wcpar, node.nullid), all=True) | ||
Gregory Szorc
|
r37126 | stats = mergemod.updateresult(0, 0, 0, 0) | ||
Rodrigo Damazio Bovendorp
|
r42219 | ui.popbuffer() | ||
Pierre-Yves David
|
r17647 | else: | ||
try: | ||||
# ui.forcemerge is an internal variable, do not document | ||||
Mads Kiilerich
|
r20790 | repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), | ||
'histedit') | ||||
Matt Mackall
|
r22904 | stats = mergemod.graft(repo, ctx, ctx.p1(), ['local', 'histedit']) | ||
Pierre-Yves David
|
r17647 | finally: | ||
Mads Kiilerich
|
r20790 | repo.ui.setconfig('ui', 'forcemerge', '', 'histedit') | ||
Pierre-Yves David
|
r17647 | return stats | ||
Leah Xue
|
r17407 | |||
Gregory Szorc
|
r36421 | def collapse(repo, firstctx, lastctx, commitopts, skipprompt=False): | ||
Pierre-Yves David
|
r17644 | """collapse the set of revisions from first to last as new one. | ||
Expected commit options are: | ||||
- message | ||||
- date | ||||
- username | ||||
Mads Kiilerich
|
r17738 | Commit message is edited in all cases. | ||
Pierre-Yves David
|
r17644 | |||
This function works in memory.""" | ||||
Gregory Szorc
|
r36422 | ctxs = list(repo.set('%d::%d', firstctx.rev(), lastctx.rev())) | ||
Pierre-Yves David
|
r17644 | if not ctxs: | ||
return None | ||||
Augie Fackler
|
r25452 | for c in ctxs: | ||
if not c.mutable(): | ||||
timeless
|
r27545 | raise error.ParseError( | ||
Augie Fackler
|
r25452 | _("cannot fold into public change %s") % node.short(c.node())) | ||
Martin von Zweigbergk
|
r41442 | base = firstctx.p1() | ||
Pierre-Yves David
|
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) | ||||
Gregory Szorc
|
r36421 | copied = copies.pathcopies(base, lastctx) | ||
Pierre-Yves David
|
r17644 | |||
# prune files which were reverted by the updates | ||||
Gregory Szorc
|
r36421 | files = [f for f in files if not cmdutil.samefile(f, lastctx, base)] | ||
Pierre-Yves David
|
r17644 | # commit version of these files as defined by head | ||
Gregory Szorc
|
r36421 | headmf = lastctx.manifest() | ||
Pierre-Yves David
|
r17644 | def filectxfn(repo, ctx, path): | ||
if path in headmf: | ||||
Gregory Szorc
|
r36421 | fctx = lastctx[path] | ||
Pierre-Yves David
|
r17644 | flags = fctx.flags() | ||
Martin von Zweigbergk
|
r35401 | mctx = context.memfilectx(repo, ctx, | ||
Sean Farley
|
r21689 | fctx.path(), fctx.data(), | ||
Pierre-Yves David
|
r17644 | islink='l' in flags, | ||
isexec='x' in flags, | ||||
Martin von Zweigbergk
|
r42161 | copysource=copied.get(path)) | ||
Pierre-Yves David
|
r17644 | return mctx | ||
Mads Kiilerich
|
r22296 | return None | ||
Pierre-Yves David
|
r17644 | |||
if commitopts.get('message'): | ||||
message = commitopts['message'] | ||||
else: | ||||
Gregory Szorc
|
r36421 | message = firstctx.description() | ||
Pierre-Yves David
|
r17644 | user = commitopts.get('user') | ||
date = commitopts.get('date') | ||||
Pierre-Yves David
|
r18437 | extra = commitopts.get('extra') | ||
Pierre-Yves David
|
r17644 | |||
Gregory Szorc
|
r36421 | parents = (firstctx.p1().node(), firstctx.p2().node()) | ||
Mike Edgar
|
r22152 | editor = None | ||
Durham Goode
|
r24828 | if not skipprompt: | ||
Mike Edgar
|
r22152 | editor = cmdutil.getcommiteditor(edit=True, editform='histedit.fold') | ||
Pierre-Yves David
|
r17644 | new = context.memctx(repo, | ||
parents=parents, | ||||
text=message, | ||||
files=files, | ||||
filectxfn=filectxfn, | ||||
user=user, | ||||
date=date, | ||||
FUJIWARA Katsunori
|
r21239 | extra=extra, | ||
FUJIWARA Katsunori
|
r22002 | editor=editor) | ||
Pierre-Yves David
|
r17644 | return repo.commitctx(new) | ||
liscju
|
r26981 | def _isdirtywc(repo): | ||
return repo[None].dirty(missing=True) | ||||
Mateusz Kwapich
|
r27084 | def abortdirty(): | ||
raise error.Abort(_('working copy has pending changes'), | ||||
hint=_('amend, commit, or revert them and run histedit ' | ||||
'--continue, or abort with histedit --abort')) | ||||
timeless
|
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) | ||||
Mateusz Kwapich
|
r27201 | |||
timeless
|
r27675 | cls.verb = verb | ||
cls.verbs = verbs | ||||
cls.message = message | ||||
Mateusz Kwapich
|
r27201 | for verb in verbs: | ||
actiontable[verb] = cls | ||||
return cls | ||||
return wrap | ||||
timeless
|
r27675 | @action(['pick', 'p'], | ||
_('use commit'), | ||||
priority=True) | ||||
Durham Goode
|
r24767 | class pick(histeditaction): | ||
def run(self): | ||||
rulectx = self.repo[self.node] | ||||
Martin von Zweigbergk
|
r41442 | if rulectx.p1().node() == self.state.parentctxnode: | ||
Durham Goode
|
r24767 | self.repo.ui.debug('node %s unchanged\n' % node.short(self.node)) | ||
return rulectx, [] | ||||
Augie Fackler
|
r17064 | |||
Durham Goode
|
r24767 | return super(pick, self).run() | ||
Augie Fackler
|
r17064 | |||
timeless
|
r27675 | @action(['edit', 'e'], | ||
_('use commit, but stop for amending'), | ||||
priority=True) | ||||
Durham Goode
|
r24770 | class edit(histeditaction): | ||
def run(self): | ||||
repo = self.repo | ||||
rulectx = repo[self.node] | ||||
timeless
|
r27407 | hg.update(repo, self.state.parentctxnode, quietempty=True) | ||
Durham Goode
|
r24770 | applychanges(repo.ui, repo, rulectx, {}) | ||
raise error.InterventionRequired( | ||||
timeless
|
r27629 | _('Editing (%s), you may commit or record as needed now.') | ||
% node.short(self.node), | ||||
hint=_('hg histedit --continue to resume')) | ||||
Durham Goode
|
r24770 | |||
def commiteditor(self): | ||||
return cmdutil.getcommiteditor(edit=True, editform='histedit.edit') | ||||
Augie Fackler
|
r17064 | |||
timeless
|
r27675 | @action(['fold', 'f'], | ||
_('use commit, but combine it with the one above')) | ||||
Durham Goode
|
r24771 | class fold(histeditaction): | ||
Pierre-Yves David
|
r29879 | def verify(self, prev, expected, seen): | ||
timeless
|
r27542 | """ Verifies semantic correctness of the fold rule""" | ||
Pierre-Yves David
|
r29879 | super(fold, self).verify(prev, expected, seen) | ||
timeless
|
r27542 | repo = self.repo | ||
if not prev: | ||||
Martin von Zweigbergk
|
r41442 | c = repo[self.node].p1() | ||
timeless
|
r27542 | elif not prev.verb in ('pick', 'base'): | ||
return | ||||
else: | ||||
c = repo[prev.node] | ||||
if not c.mutable(): | ||||
timeless
|
r27545 | raise error.ParseError( | ||
timeless
|
r27542 | _("cannot fold into public change %s") % node.short(c.node())) | ||
Durham Goode
|
r24771 | def continuedirty(self): | ||
repo = self.repo | ||||
rulectx = repo[self.node] | ||||
commit = commitfuncfor(repo, rulectx) | ||||
commit(text='fold-temp-revision %s' % node.short(self.node), | ||||
user=rulectx.user(), date=rulectx.date(), | ||||
extra=rulectx.extra()) | ||||
def continueclean(self): | ||||
repo = self.repo | ||||
ctx = repo['.'] | ||||
rulectx = repo[self.node] | ||||
parentctxnode = self.state.parentctxnode | ||||
if ctx.node() == parentctxnode: | ||||
repo.ui.warn(_('%s: empty changeset\n') % | ||||
node.short(self.node)) | ||||
return ctx, [(self.node, (parentctxnode,))] | ||||
Mike Edgar
|
r22152 | |||
Durham Goode
|
r24771 | parentctx = repo[parentctxnode] | ||
Gregory Szorc
|
r36422 | newcommits = set(c.node() for c in repo.set('(%d::. - %d)', | ||
parentctx.rev(), | ||||
parentctx.rev())) | ||||
Durham Goode
|
r24771 | if not newcommits: | ||
repo.ui.warn(_('%s: cannot fold - working copy is not a ' | ||||
'descendant of previous commit %s\n') % | ||||
(node.short(self.node), node.short(parentctxnode))) | ||||
return ctx, [(self.node, (ctx.node(),))] | ||||
middlecommits = newcommits.copy() | ||||
middlecommits.discard(ctx.node()) | ||||
Durham Goode
|
r24773 | return self.finishfold(repo.ui, repo, parentctx, rulectx, ctx.node(), | ||
middlecommits) | ||||
Durham Goode
|
r24771 | |||
Durham Goode
|
r24773 | def skipprompt(self): | ||
Augie Fackler
|
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. | ||||
""" | ||||
Durham Goode
|
r24773 | return False | ||
Durham Goode
|
r24772 | |||
Augie Fackler
|
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 | ||||
Ben Schmidt
|
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 | ||||
Durham Goode
|
r24773 | def finishfold(self, ui, repo, ctx, oldctx, newnode, internalchanges): | ||
Martin von Zweigbergk
|
r41442 | parent = ctx.p1().node() | ||
Yuya Nishihara
|
r38527 | hg.updaterepo(repo, parent, overwrite=False) | ||
Durham Goode
|
r24772 | ### prepare new commit data | ||
Durham Goode
|
r24773 | commitopts = {} | ||
Durham Goode
|
r24772 | commitopts['user'] = ctx.user() | ||
# commit message | ||||
Augie Fackler
|
r26246 | if not self.mergedescs(): | ||
Durham Goode
|
r24772 | newmessage = ctx.description() | ||
else: | ||||
newmessage = '\n***\n'.join( | ||||
[ctx.description()] + | ||||
[repo[r].description() for r in internalchanges] + | ||||
[oldctx.description()]) + '\n' | ||||
commitopts['message'] = newmessage | ||||
# date | ||||
Ben Schmidt
|
r31056 | if self.firstdate(): | ||
commitopts['date'] = ctx.date() | ||||
else: | ||||
commitopts['date'] = max(ctx.date(), oldctx.date()) | ||||
Taapas Agrawal
|
r41249 | # if date is to be updated to current | ||
if ui.configbool('rewrite', 'update-timestamp'): | ||||
commitopts['date'] = dateutil.makedate() | ||||
Durham Goode
|
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. | ||||
extra['histedit_source'] = '%s,%s' % (ctx.hex(), oldctx.hex()) | ||||
commitopts['extra'] = extra | ||||
Jun Wu
|
r31459 | phasemin = max(ctx.phase(), oldctx.phase()) | ||
overrides = {('phases', 'new-commit'): phasemin} | ||||
with repo.ui.configoverride(overrides, 'histedit'): | ||||
Durham Goode
|
r24828 | n = collapse(repo, ctx, repo[newnode], commitopts, | ||
skipprompt=self.skipprompt()) | ||||
Durham Goode
|
r24772 | if n is None: | ||
return ctx, [] | ||||
Yuya Nishihara
|
r38527 | hg.updaterepo(repo, n, overwrite=False) | ||
Durham Goode
|
r24772 | replacements = [(oldctx.node(), (newnode,)), | ||
(ctx.node(), (n,)), | ||||
(newnode, (n,)), | ||||
] | ||||
for ich in internalchanges: | ||||
replacements.append((ich, (n,))) | ||||
return repo[n], replacements | ||||
Durham Goode
|
r24771 | |||
Saurabh Singh
|
r34490 | @action(['base', 'b'], | ||
_('checkout changeset and apply further changesets from there')) | ||||
Mateusz Kwapich
|
r27085 | class base(histeditaction): | ||
def run(self): | ||||
if self.repo['.'].node() != self.node: | ||||
Martin von Zweigbergk
|
r40402 | mergemod.update(self.repo, self.node, branchmerge=False, force=True) | ||
Mateusz Kwapich
|
r27085 | return self.continueclean() | ||
def continuedirty(self): | ||||
abortdirty() | ||||
def continueclean(self): | ||||
basectx = self.repo['.'] | ||||
return basectx, [] | ||||
Pierre-Yves David
|
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: | ||||
Augie Fackler
|
r29887 | msg = _('%s "%s" changeset was an edited list candidate') | ||
raise error.ParseError( | ||||
msg % (self.verb, node.short(self.node)), | ||||
hint=_('base must only use unlisted changesets')) | ||||
Pierre-Yves David
|
r29880 | |||
timeless
|
r27675 | @action(['_multifold'], | ||
_( | ||||
Augie Fackler
|
r26246 | """fold subclass used for when multiple folds happen in a row | ||
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. | ||||
timeless
|
r27675 | """), | ||
internal=True) | ||||
class _multifold(fold): | ||||
Augie Fackler
|
r26246 | def skipprompt(self): | ||
return True | ||||
timeless
|
r27675 | @action(["roll", "r"], | ||
Ben Schmidt
|
r31056 | _("like fold, but discard this commit's description and date")) | ||
Durham Goode
|
r24771 | class rollup(fold): | ||
Augie Fackler
|
r26246 | def mergedescs(self): | ||
return False | ||||
Durham Goode
|
r24773 | def skipprompt(self): | ||
return True | ||||
Augie Fackler
|
r17064 | |||
Ben Schmidt
|
r31056 | def firstdate(self): | ||
return True | ||||
timeless
|
r27675 | @action(["drop", "d"], | ||
_('remove commit from history')) | ||||
Durham Goode
|
r24768 | class drop(histeditaction): | ||
def run(self): | ||||
parentctx = self.repo[self.state.parentctxnode] | ||||
return parentctx, [(self.node, tuple())] | ||||
Augie Fackler
|
r17064 | |||
timeless
|
r27675 | @action(["mess", "m"], | ||
_('edit commit message without changing commit content'), | ||||
priority=True) | ||||
Durham Goode
|
r24769 | class message(histeditaction): | ||
def commiteditor(self): | ||||
return cmdutil.getcommiteditor(edit=True, editform='histedit.mess') | ||||
Augie Fackler
|
r17064 | |||
Pierre-Yves David
|
r26335 | def findoutgoing(ui, repo, remote=None, force=False, opts=None): | ||
Pierre-Yves David
|
r19021 | """utility function to find the first outgoing changeset | ||
timeless@mozdev.org
|
r26171 | Used by initialization code""" | ||
Pierre-Yves David
|
r26335 | if opts is None: | ||
opts = {} | ||||
Pierre-Yves David
|
r19021 | dest = ui.expandpath(remote or 'default-push', remote or 'default') | ||
Martin von Zweigbergk
|
r37278 | dest, branches = hg.parseurl(dest, None)[:2] | ||
Pierre-Yves David
|
r19021 | ui.status(_('comparing with %s\n') % util.hidepassword(dest)) | ||
Martin von Zweigbergk
|
r37278 | revs, checkout = hg.addbranchrevs(repo, repo, branches, None) | ||
Pierre-Yves David
|
r19021 | other = hg.peer(repo, opts, dest) | ||
if revs: | ||||
revs = [repo.lookup(rev) for rev in revs] | ||||
outgoing = discovery.findcommonoutgoing(repo, other, revs, force=force) | ||||
if not outgoing.missing: | ||||
Pierre-Yves David
|
r26587 | raise error.Abort(_('no outgoing ancestors')) | ||
FUJIWARA Katsunori
|
r19841 | roots = list(repo.revs("roots(%ln)", outgoing.missing)) | ||
Martin von Zweigbergk
|
r40065 | if len(roots) > 1: | ||
FUJIWARA Katsunori
|
r19841 | msg = _('there are ambiguous outgoing revisions') | ||
timeless
|
r29970 | hint = _("see 'hg help histedit' for more detail") | ||
Pierre-Yves David
|
r26587 | raise error.Abort(msg, hint=hint) | ||
Martin von Zweigbergk
|
r37330 | return repo[roots[0]].node() | ||
Pierre-Yves David
|
r19021 | |||
Augie Fackler
|
r40638 | # Curses Support | ||
try: | ||||
import curses | ||||
except ImportError: | ||||
curses = None | ||||
KEY_LIST = ['pick', 'edit', 'fold', 'drop', 'mess', 'roll'] | ||||
ACTION_LABELS = { | ||||
'fold': '^fold', | ||||
'roll': '^roll', | ||||
} | ||||
Jordi Gutiérrez Hermoso
|
r41851 | COLOR_HELP, COLOR_SELECTED, COLOR_OK, COLOR_WARN, COLOR_CURRENT = 1, 2, 3, 4, 5 | ||
Jordi Gutiérrez Hermoso
|
r42258 | COLOR_DIFF_ADD_LINE, COLOR_DIFF_DEL_LINE, COLOR_DIFF_OFFSET = 6, 7, 8 | ||
Augie Fackler
|
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 = { | ||||
'global': { | ||||
'h': 'next-action', | ||||
'KEY_RIGHT': 'next-action', | ||||
'l': 'prev-action', | ||||
'KEY_LEFT': 'prev-action', | ||||
'q': 'quit', | ||||
'c': 'histedit', | ||||
'C': 'histedit', | ||||
'v': 'showpatch', | ||||
'?': 'help', | ||||
}, | ||||
MODE_RULES: { | ||||
'd': 'action-drop', | ||||
'e': 'action-edit', | ||||
'f': 'action-fold', | ||||
'm': 'action-mess', | ||||
'p': 'action-pick', | ||||
'r': 'action-roll', | ||||
' ': 'select', | ||||
'j': 'down', | ||||
'k': 'up', | ||||
'KEY_DOWN': 'down', | ||||
'KEY_UP': 'up', | ||||
'J': 'move-down', | ||||
'K': 'move-up', | ||||
'KEY_NPAGE': 'move-down', | ||||
'KEY_PPAGE': 'move-up', | ||||
'0': 'goto', # Used for 0..9 | ||||
}, | ||||
MODE_PATCH: { | ||||
' ': 'page-down', | ||||
'KEY_NPAGE': 'page-down', | ||||
'KEY_PPAGE': 'page-up', | ||||
'j': 'line-down', | ||||
'k': 'line-up', | ||||
'KEY_DOWN': 'line-down', | ||||
'KEY_UP': 'line-up', | ||||
'J': 'down', | ||||
'K': 'up', | ||||
}, | ||||
MODE_HELP: { | ||||
}, | ||||
} | ||||
def screen_size(): | ||||
return struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, ' ')) | ||||
class histeditrule(object): | ||||
def __init__(self, ctx, pos, action='pick'): | ||||
self.ctx = ctx | ||||
self.action = action | ||||
self.origpos = pos | ||||
self.pos = pos | ||||
self.conflicts = [] | ||||
def __str__(self): | ||||
# Some actions ('fold' and 'roll') combine a patch with a previous one. | ||||
# Add a marker showing which patch they apply to, and also omit the | ||||
# description for 'roll' (since it will get discarded). Example display: | ||||
# | ||||
# #10 pick 316392:06a16c25c053 add option to skip tests | ||||
# #11 ^roll 316393:71313c964cc5 | ||||
# #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"). | ||||
action = ACTION_LABELS.get(self.action, self.action) | ||||
h = self.ctx.hex()[0:12] | ||||
r = self.ctx.rev() | ||||
desc = self.ctx.description().splitlines()[0].strip() | ||||
if self.action == 'roll': | ||||
desc = '' | ||||
return "#{0:<2} {1:<6} {2}:{3} {4}".format( | ||||
self.origpos, action, r, h, desc) | ||||
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 | ||||
# ============ EVENTS =============== | ||||
def movecursor(state, 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).''' | ||||
state['pos'] = newpos | ||||
mode, _ = state['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 = state['modes'][MODE_RULES] | ||||
if newpos < modestate['line_offset']: | ||||
modestate['line_offset'] = newpos | ||||
elif newpos > modestate['line_offset'] + state['page_height'] - 1: | ||||
modestate['line_offset'] = newpos - state['page_height'] + 1 | ||||
# Reset the patch view region to the top of the new patch. | ||||
state['modes'][MODE_PATCH]['line_offset'] = 0 | ||||
def changemode(state, mode): | ||||
curmode, _ = state['mode'] | ||||
state['mode'] = (mode, curmode) | ||||
feyu@google.com
|
r42419 | if mode == MODE_PATCH: | ||
state['modes'][MODE_PATCH]['patchcontents'] = patchcontents(state) | ||||
Augie Fackler
|
r40638 | |||
def makeselection(state, pos): | ||||
state['selected'] = pos | ||||
def swap(state, oldpos, newpos): | ||||
"""Swap two positions and calculate necessary conflicts in | ||||
O(|newpos-oldpos|) time""" | ||||
rules = state['rules'] | ||||
assert 0 <= oldpos < len(rules) and 0 <= newpos < len(rules) | ||||
rules[oldpos], rules[newpos] = rules[newpos], rules[oldpos] | ||||
# TODO: swap should not know about histeditrule's internals | ||||
rules[newpos].pos = newpos | ||||
rules[oldpos].pos = oldpos | ||||
start = min(oldpos, newpos) | ||||
end = max(oldpos, newpos) | ||||
for r in pycompat.xrange(start, end + 1): | ||||
rules[newpos].checkconflicts(rules[r]) | ||||
rules[oldpos].checkconflicts(rules[r]) | ||||
if state['selected']: | ||||
makeselection(state, newpos) | ||||
def changeaction(state, pos, action): | ||||
"""Change the action state on the given position to the new action""" | ||||
rules = state['rules'] | ||||
assert 0 <= pos < len(rules) | ||||
rules[pos].action = action | ||||
def cycleaction(state, pos, next=False): | ||||
"""Changes the action state the next or the previous action from | ||||
the action list""" | ||||
rules = state['rules'] | ||||
assert 0 <= pos < len(rules) | ||||
current = rules[pos].action | ||||
assert current in KEY_LIST | ||||
index = KEY_LIST.index(current) | ||||
if next: | ||||
index += 1 | ||||
else: | ||||
index -= 1 | ||||
changeaction(state, pos, KEY_LIST[index % len(KEY_LIST)]) | ||||
def changeview(state, 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, _ = state['mode'] | ||||
if mode != MODE_PATCH: | ||||
return | ||||
mode_state = state['modes'][mode] | ||||
feyu@google.com
|
r42419 | num_lines = len(mode_state['patchcontents']) | ||
Augie Fackler
|
r40638 | page_height = state['page_height'] | ||
unit = page_height if unit == 'page' else 1 | ||||
num_pages = 1 + (num_lines - 1) / page_height | ||||
max_offset = (num_pages - 1) * page_height | ||||
newline = mode_state['line_offset'] + delta * unit | ||||
mode_state['line_offset'] = max(0, min(max_offset, newline)) | ||||
def event(state, 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. | ||||
""" | ||||
selected = state['selected'] | ||||
oldpos = state['pos'] | ||||
rules = state['rules'] | ||||
if ch in (curses.KEY_RESIZE, "KEY_RESIZE"): | ||||
return E_RESIZE | ||||
lookup_ch = ch | ||||
if '0' <= ch <= '9': | ||||
lookup_ch = '0' | ||||
curmode, prevmode = state['mode'] | ||||
action = KEYTABLE[curmode].get(lookup_ch, KEYTABLE['global'].get(lookup_ch)) | ||||
if action is None: | ||||
return | ||||
if action in ('down', 'move-down'): | ||||
newpos = min(oldpos + 1, len(rules) - 1) | ||||
movecursor(state, oldpos, newpos) | ||||
if selected is not None or action == 'move-down': | ||||
swap(state, oldpos, newpos) | ||||
elif action in ('up', 'move-up'): | ||||
newpos = max(0, oldpos - 1) | ||||
movecursor(state, oldpos, newpos) | ||||
if selected is not None or action == 'move-up': | ||||
swap(state, oldpos, newpos) | ||||
elif action == 'next-action': | ||||
cycleaction(state, oldpos, next=True) | ||||
elif action == 'prev-action': | ||||
cycleaction(state, oldpos, next=False) | ||||
elif action == 'select': | ||||
selected = oldpos if selected is None else None | ||||
makeselection(state, selected) | ||||
elif action == 'goto' and int(ch) < len(rules) and len(rules) <= 10: | ||||
newrule = next((r for r in rules if r.origpos == int(ch))) | ||||
movecursor(state, oldpos, newrule.pos) | ||||
if selected is not None: | ||||
swap(state, oldpos, newrule.pos) | ||||
elif action.startswith('action-'): | ||||
changeaction(state, oldpos, action[7:]) | ||||
elif action == 'showpatch': | ||||
changemode(state, MODE_PATCH if curmode != MODE_PATCH else prevmode) | ||||
elif action == 'help': | ||||
changemode(state, MODE_HELP if curmode != MODE_HELP else prevmode) | ||||
elif action == 'quit': | ||||
return E_QUIT | ||||
elif action == 'histedit': | ||||
return E_HISTEDIT | ||||
elif action == 'page-down': | ||||
return E_PAGEDOWN | ||||
elif action == 'page-up': | ||||
return E_PAGEUP | ||||
elif action == 'line-down': | ||||
return E_LINEDOWN | ||||
elif action == 'line-up': | ||||
return E_LINEUP | ||||
def makecommands(rules): | ||||
"""Returns a list of commands consumable by histedit --commands based on | ||||
our list of rules""" | ||||
commands = [] | ||||
for rules in rules: | ||||
commands.append("{0} {1}\n".format(rules.action, rules.ctx)) | ||||
return commands | ||||
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 | ||||
line = ("{0:<%d}" % length).format(str(line).strip())[:length] | ||||
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) | ||||
Yu Feng
|
r42418 | def _trunc_head(line, n): | ||
if len(line) <= n: | ||||
return line | ||||
return '> ' + line[-(n - 2):] | ||||
def _trunc_tail(line, n): | ||||
if len(line) <= n: | ||||
return line | ||||
return line[:n - 2] + ' >' | ||||
Augie Fackler
|
r40638 | def patchcontents(state): | ||
repo = state['repo'] | ||||
rule = state['rules'][state['pos']] | ||||
displayer = logcmdutil.changesetdisplayer(repo.ui, repo, { | ||||
Jordi Gutiérrez Hermoso
|
r42239 | "patch": True, "template": "status" | ||
Augie Fackler
|
r40638 | }, buffered=True) | ||
Jordi Gutiérrez Hermoso
|
r42336 | overrides = {('ui', 'verbose'): True} | ||
with repo.ui.configoverride(overrides, source='histedit'): | ||||
displayer.show(rule.ctx) | ||||
displayer.close() | ||||
Augie Fackler
|
r40638 | return displayer.hunk[rule.ctx.rev()].splitlines() | ||
def _chisteditmain(repo, rules, stdscr): | ||||
Jordi Gutiérrez Hermoso
|
r42257 | try: | ||
curses.use_default_colors() | ||||
except curses.error: | ||||
pass | ||||
Augie Fackler
|
r40638 | # 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) | ||||
Jordi Gutiérrez Hermoso
|
r41851 | curses.init_pair(COLOR_CURRENT, curses.COLOR_WHITE, curses.COLOR_MAGENTA) | ||
Jordi Gutiérrez Hermoso
|
r42258 | 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) | ||||
Augie Fackler
|
r40638 | |||
# don't display the cursor | ||||
try: | ||||
curses.curs_set(0) | ||||
except curses.error: | ||||
pass | ||||
def rendercommit(win, state): | ||||
"""Renders the commit window that shows the log of the current selected | ||||
commit""" | ||||
pos = state['pos'] | ||||
rules = state['rules'] | ||||
rule = rules[pos] | ||||
ctx = rule.ctx | ||||
win.box() | ||||
maxy, maxx = win.getmaxyx() | ||||
length = maxx - 3 | ||||
line = "changeset: {0}:{1:<12}".format(ctx.rev(), ctx) | ||||
win.addstr(1, 1, line[:length]) | ||||
Akshit Jain
|
r41850 | line = "user: {0}".format(ctx.user()) | ||
Augie Fackler
|
r40638 | win.addstr(2, 1, line[:length]) | ||
bms = repo.nodebookmarks(ctx.node()) | ||||
line = "bookmark: {0}".format(' '.join(bms)) | ||||
win.addstr(3, 1, line[:length]) | ||||
Yu Feng
|
r42418 | line = "summary: {0}".format(ctx.description().splitlines()[0]) | ||
Augie Fackler
|
r40638 | win.addstr(4, 1, line[:length]) | ||
Yu Feng
|
r42418 | line = "files: " | ||
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: | ||||
win.addstr(y, fnx, _trunc_tail(','.join(files[i:]), fnmaxx)) | ||||
y = y + 1 | ||||
break | ||||
win.addstr(y, fnx, _trunc_head(line1, fnmaxx)) | ||||
y = y + 1 | ||||
Augie Fackler
|
r40638 | |||
conflicts = rule.conflicts | ||||
if len(conflicts) > 0: | ||||
conflictstr = ','.join(map(lambda r: str(r.ctx), conflicts)) | ||||
conflictstr = "changed files overlap with {0}".format(conflictstr) | ||||
else: | ||||
conflictstr = 'no overlap' | ||||
Yu Feng
|
r42418 | win.addstr(y, 1, conflictstr[:length]) | ||
Augie Fackler
|
r40638 | win.noutrefresh() | ||
def helplines(mode): | ||||
if mode == MODE_PATCH: | ||||
help = """\ | ||||
?: 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 = """\ | ||||
?: 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 | ||||
""" | ||||
return help.splitlines() | ||||
def renderhelp(win, state): | ||||
maxy, maxx = win.getmaxyx() | ||||
mode, _ = state['mode'] | ||||
for y, line in enumerate(helplines(mode)): | ||||
if y >= maxy: | ||||
break | ||||
addln(win, y, 0, line, curses.color_pair(COLOR_HELP)) | ||||
win.noutrefresh() | ||||
def renderrules(rulesscr, state): | ||||
rules = state['rules'] | ||||
pos = state['pos'] | ||||
selected = state['selected'] | ||||
start = state['modes'][MODE_RULES]['line_offset'] | ||||
conflicts = [r.ctx for r in rules if r.conflicts] | ||||
if len(conflicts) > 0: | ||||
line = "potential conflict in %s" % ','.join(map(str, conflicts)) | ||||
addln(rulesscr, -1, 0, line, curses.color_pair(COLOR_WARN)) | ||||
for y, rule in enumerate(rules[start:]): | ||||
if y >= state['page_height']: | ||||
break | ||||
if len(rule.conflicts) > 0: | ||||
rulesscr.addstr(y, 0, " ", curses.color_pair(COLOR_WARN)) | ||||
else: | ||||
rulesscr.addstr(y, 0, " ", curses.COLOR_BLACK) | ||||
if y + start == selected: | ||||
addln(rulesscr, y, 2, rule, curses.color_pair(COLOR_SELECTED)) | ||||
elif y + start == pos: | ||||
Jordi Gutiérrez Hermoso
|
r41851 | addln(rulesscr, y, 2, rule, | ||
curses.color_pair(COLOR_CURRENT) | curses.A_BOLD) | ||||
Augie Fackler
|
r40638 | else: | ||
addln(rulesscr, y, 2, rule) | ||||
rulesscr.noutrefresh() | ||||
Jordi Gutiérrez Hermoso
|
r42258 | def renderstring(win, state, output, diffcolors=False): | ||
Augie Fackler
|
r40638 | maxy, maxx = win.getmaxyx() | ||
length = min(maxy - 1, len(output)) | ||||
for y in range(0, length): | ||||
Jordi Gutiérrez Hermoso
|
r42258 | line = output[y] | ||
if diffcolors: | ||||
if line and line[0] == '+': | ||||
win.addstr( | ||||
y, 0, line, curses.color_pair(COLOR_DIFF_ADD_LINE)) | ||||
elif line and line[0] == '-': | ||||
win.addstr( | ||||
y, 0, line, curses.color_pair(COLOR_DIFF_DEL_LINE)) | ||||
elif line.startswith('@@ '): | ||||
win.addstr( | ||||
y, 0, line, curses.color_pair(COLOR_DIFF_OFFSET)) | ||||
else: | ||||
win.addstr(y, 0, line) | ||||
else: | ||||
win.addstr(y, 0, line) | ||||
Augie Fackler
|
r40638 | win.noutrefresh() | ||
def renderpatch(win, state): | ||||
start = state['modes'][MODE_PATCH]['line_offset'] | ||||
feyu@google.com
|
r42419 | content = state['modes'][MODE_PATCH]['patchcontents'] | ||
renderstring(win, state, content[start:], diffcolors=True) | ||||
Augie Fackler
|
r40638 | |||
def layout(mode): | ||||
maxy, maxx = stdscr.getmaxyx() | ||||
helplen = len(helplines(mode)) | ||||
return { | ||||
Yu Feng
|
r42418 | 'commit': (12, maxx), | ||
Augie Fackler
|
r40638 | 'help': (helplen, maxx), | ||
Yu Feng
|
r42418 | 'main': (maxy - helplen - 12, maxx), | ||
Augie Fackler
|
r40638 | } | ||
def drawvertwin(size, y, x): | ||||
win = curses.newwin(size[0], size[1], y, x) | ||||
y += size[0] | ||||
return win, y, x | ||||
state = { | ||||
'pos': 0, | ||||
'rules': rules, | ||||
'selected': None, | ||||
'mode': (MODE_INIT, MODE_INIT), | ||||
'page_height': None, | ||||
'modes': { | ||||
MODE_RULES: { | ||||
'line_offset': 0, | ||||
}, | ||||
MODE_PATCH: { | ||||
'line_offset': 0, | ||||
} | ||||
}, | ||||
'repo': repo, | ||||
} | ||||
# eventloop | ||||
ch = None | ||||
stdscr.clear() | ||||
stdscr.refresh() | ||||
while True: | ||||
try: | ||||
oldmode, _ = state['mode'] | ||||
if oldmode == MODE_INIT: | ||||
changemode(state, MODE_RULES) | ||||
e = event(state, ch) | ||||
if e == E_QUIT: | ||||
return False | ||||
if e == E_HISTEDIT: | ||||
return state['rules'] | ||||
else: | ||||
if e == E_RESIZE: | ||||
size = screen_size() | ||||
if size != stdscr.getmaxyx(): | ||||
curses.resizeterm(*size) | ||||
curmode, _ = state['mode'] | ||||
sizes = layout(curmode) | ||||
if curmode != oldmode: | ||||
state['page_height'] = sizes['main'][0] | ||||
# Adjust the view to fit the current screen size. | ||||
movecursor(state, state['pos'], state['pos']) | ||||
# 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['help'], y, x) | ||||
mainwin, y, x = drawvertwin(sizes['main'], y, x) | ||||
commitwin, y, x = drawvertwin(sizes['commit'], y, x) | ||||
if e in (E_PAGEDOWN, E_PAGEUP, E_LINEDOWN, E_LINEUP): | ||||
if e == E_PAGEDOWN: | ||||
changeview(state, +1, 'page') | ||||
elif e == E_PAGEUP: | ||||
changeview(state, -1, 'page') | ||||
elif e == E_LINEDOWN: | ||||
changeview(state, +1, 'line') | ||||
elif e == E_LINEUP: | ||||
changeview(state, -1, 'line') | ||||
# start rendering | ||||
commitwin.erase() | ||||
helpwin.erase() | ||||
mainwin.erase() | ||||
if curmode == MODE_PATCH: | ||||
renderpatch(mainwin, state) | ||||
elif curmode == MODE_HELP: | ||||
renderstring(mainwin, state, __doc__.strip().splitlines()) | ||||
else: | ||||
renderrules(mainwin, state) | ||||
rendercommit(commitwin, state) | ||||
renderhelp(helpwin, state) | ||||
curses.doupdate() | ||||
# done rendering | ||||
ch = stdscr.getkey() | ||||
except curses.error: | ||||
pass | ||||
def _chistedit(ui, repo, *freeargs, **opts): | ||||
"""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: | ||||
raise error.Abort(_("Python curses library required")) | ||||
# disable color | ||||
ui._colormode = None | ||||
try: | ||||
keep = opts.get('keep') | ||||
revs = opts.get('rev', [])[:] | ||||
cmdutil.checkunfinished(repo) | ||||
cmdutil.bailifchanged(repo) | ||||
if os.path.exists(os.path.join(repo.path, 'histedit-state')): | ||||
raise error.Abort(_('history edit already in progress, try ' | ||||
'--continue or --abort')) | ||||
revs.extend(freeargs) | ||||
if not revs: | ||||
defaultrev = destutil.desthistedit(ui, repo) | ||||
if defaultrev is not None: | ||||
revs.append(defaultrev) | ||||
if len(revs) != 1: | ||||
raise error.Abort( | ||||
_('histedit requires exactly one ancestor revision')) | ||||
rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs))) | ||||
if len(rr) != 1: | ||||
raise error.Abort(_('The specified revisions must have ' | ||||
'exactly one common root')) | ||||
root = rr[0].node() | ||||
Martin von Zweigbergk
|
r41444 | topmost = repo.dirstate.p1() | ||
Augie Fackler
|
r40638 | revs = between(repo, root, topmost, keep) | ||
if not revs: | ||||
raise error.Abort(_('%s is not an ancestor of working directory') % | ||||
node.short(root)) | ||||
ctxs = [] | ||||
for i, r in enumerate(revs): | ||||
ctxs.append(histeditrule(repo[r], i)) | ||||
Yuya Nishihara
|
r42883 | # Curses requires setting the locale or it will default to the C | ||
# locale. This sets the locale to the user's default system | ||||
# locale. | ||||
locale.setlocale(locale.LC_ALL, r'') | ||||
Augie Fackler
|
r40638 | rc = curses.wrapper(functools.partial(_chisteditmain, repo, ctxs)) | ||
curses.echo() | ||||
curses.endwin() | ||||
if rc is False: | ||||
Jordi Gutiérrez Hermoso
|
r41848 | ui.write(_("histedit aborted\n")) | ||
Augie Fackler
|
r40638 | return 0 | ||
if type(rc) is list: | ||||
Jordi Gutiérrez Hermoso
|
r42189 | ui.status(_("performing changes\n")) | ||
Augie Fackler
|
r40638 | rules = makecommands(rc) | ||
filename = repo.vfs.join('chistedit') | ||||
with open(filename, 'w+') as fp: | ||||
for r in rules: | ||||
fp.write(r) | ||||
opts['commands'] = filename | ||||
return _texthistedit(ui, repo, *freeargs, **opts) | ||||
except KeyboardInterrupt: | ||||
pass | ||||
return -1 | ||||
Adrian Buehlmann
|
r17147 | @command('histedit', | ||
[('', 'commands', '', | ||||
Anton Shestakov
|
r24232 | _('read history edits from the specified file'), _('FILE')), | ||
Adrian Buehlmann
|
r17147 | ('c', 'continue', False, _('continue an edit already in progress')), | ||
Mateusz Kwapich
|
r24142 | ('', 'edit-plan', False, _('edit remaining actions list')), | ||
Adrian Buehlmann
|
r17147 | ('k', 'keep', False, | ||
_("don't strip old nodes after edit is complete")), | ||||
('', 'abort', False, _('abort an edit in progress')), | ||||
('o', 'outgoing', False, _('changesets not found in destination')), | ||||
('f', 'force', False, | ||||
_('force outgoing even for unrelated repositories')), | ||||
Pulkit Goyal
|
r35124 | ('r', 'rev', [], _('first revision to be edited'), _('REV'))] + | ||
cmdutil.formatteropts, | ||||
rdamazio@google.com
|
r40329 | _("[OPTIONS] ([ANCESTOR] | --outgoing [URL])"), | ||
helpcategory=command.CATEGORY_CHANGE_MANAGEMENT) | ||||
Pierre-Yves David
|
r19020 | def histedit(ui, repo, *freeargs, **opts): | ||
Augie Fackler
|
r17131 | """interactively edit changeset history | ||
FUJIWARA Katsunori
|
r19621 | |||
timeless
|
r27713 | This command lets you edit a linear series of changesets (up to | ||
and including the working directory, which should be clean). | ||||
FUJIWARA Katsunori
|
r27956 | You can: | ||
timeless
|
r27713 | |||
- `pick` to [re]order a changeset | ||||
- `drop` to omit changeset | ||||
- `mess` to reword the changeset commit message | ||||
Ben Schmidt
|
r31055 | - `fold` to combine it with the preceding changeset (using the later date) | ||
timeless
|
r27713 | |||
Ben Schmidt
|
r31056 | - `roll` like fold, but discarding this commit's description and date | ||
timeless
|
r27713 | |||
Ben Schmidt
|
r31055 | - `edit` to edit this changeset (preserving date) | ||
FUJIWARA Katsunori
|
r19622 | |||
Saurabh Singh
|
r34490 | - `base` to checkout changeset and apply further changesets from there | ||
Wagner Bruna
|
r27972 | There are a number of ways to select the root changeset: | ||
timeless
|
r27714 | |||
- Specify ANCESTOR directly | ||||
Gregory Szorc
|
r27262 | |||
timeless
|
r27714 | - Use --outgoing -- it will be the first linear changeset not | ||
FUJIWARA Katsunori
|
r28077 | included in destination. (See :hg:`help config.paths.default-push`) | ||
timeless
|
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. | ||||
FUJIWARA Katsunori
|
r19842 | |||
timeless
|
r27630 | .. container:: verbose | ||
FUJIWARA Katsunori
|
r19842 | |||
timeless
|
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. | ||||
FUJIWARA Katsunori
|
r19972 | |||
Mathias De Maré
|
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 | ||||
FUJIWARA Katsunori
|
r19972 | Returns 0 on success, 1 if user intervention is required (not only | ||
for intentional "edit" command, but also for resolving unexpected | ||||
conflicts). | ||||
Augie Fackler
|
r17064 | """ | ||
Augie Fackler
|
r41211 | # kludge: _chistedit only works for starting an edit, not aborting | ||
# or continuing, so fall back to regular _texthistedit for those | ||||
# operations. | ||||
Augie Fackler
|
r41259 | if ui.interface('histedit') == 'curses' and _getgoal( | ||
pycompat.byteskwargs(opts)) == goalnew: | ||||
Augie Fackler
|
r40638 | return _chistedit(ui, repo, *freeargs, **opts) | ||
return _texthistedit(ui, repo, *freeargs, **opts) | ||||
def _texthistedit(ui, repo, *freeargs, **opts): | ||||
David Soria Parra
|
r22984 | state = histeditstate(repo) | ||
Martin von Zweigbergk
|
r41201 | with repo.wlock() as wlock, repo.lock() as lock: | ||
state.wlock = wlock | ||||
state.lock = lock | ||||
David Soria Parra
|
r22984 | _histedit(ui, repo, state, *freeargs, **opts) | ||
Siddharth Agarwal
|
r20071 | |||
Kostia Balytskyi
|
r28144 | goalcontinue = 'continue' | ||
goalabort = 'abort' | ||||
goaleditplan = 'edit-plan' | ||||
goalnew = 'new' | ||||
Kostia Balytskyi
|
r28134 | def _getgoal(opts): | ||
Augie Fackler
|
r41259 | if opts.get(b'continue'): | ||
Kostia Balytskyi
|
r28144 | return goalcontinue | ||
Augie Fackler
|
r41259 | if opts.get(b'abort'): | ||
Kostia Balytskyi
|
r28144 | return goalabort | ||
Augie Fackler
|
r41259 | if opts.get(b'edit_plan'): | ||
Kostia Balytskyi
|
r28144 | return goaleditplan | ||
return goalnew | ||||
Kostia Balytskyi
|
r28134 | |||
Yuya Nishihara
|
r30262 | def _readfile(ui, path): | ||
Jun Wu
|
r28550 | if path == '-': | ||
Simon Farnsworth
|
r30983 | with ui.timeblockedsection('histedit'): | ||
return ui.fin.read() | ||||
Jun Wu
|
r28550 | else: | ||
with open(path, 'rb') as f: | ||||
return f.read() | ||||
Kostia Balytskyi
|
r28134 | def _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs): | ||
timeless
|
r27169 | # TODO only abort if we try to histedit mq patches, not just | ||
Augie Fackler
|
r17064 | # blanket if mq patches are applied somewhere | ||
mq = getattr(repo, 'mq', None) | ||||
if mq and mq.applied: | ||||
Pierre-Yves David
|
r26587 | raise error.Abort(_('source has mq patches applied')) | ||
Augie Fackler
|
r17064 | |||
Pierre-Yves David
|
r19020 | # basic argument incompatibility processing | ||
outg = opts.get('outgoing') | ||||
Mateusz Kwapich
|
r24142 | editplan = opts.get('edit_plan') | ||
Pierre-Yves David
|
r19020 | abort = opts.get('abort') | ||
force = opts.get('force') | ||||
if force and not outg: | ||||
Pierre-Yves David
|
r26587 | raise error.Abort(_('--force only allowed with --outgoing')) | ||
Kostia Balytskyi
|
r28134 | if goal == 'continue': | ||
Augie Fackler
|
r25149 | if any((outg, abort, revs, freeargs, rules, editplan)): | ||
Pierre-Yves David
|
r26587 | raise error.Abort(_('no arguments allowed with --continue')) | ||
Kostia Balytskyi
|
r28134 | elif goal == 'abort': | ||
Augie Fackler
|
r25149 | if any((outg, revs, freeargs, rules, editplan)): | ||
Pierre-Yves David
|
r26587 | raise error.Abort(_('no arguments allowed with --abort')) | ||
Kostia Balytskyi
|
r28134 | elif goal == 'edit-plan': | ||
Augie Fackler
|
r25149 | if any((outg, revs, freeargs)): | ||
Pierre-Yves David
|
r26587 | raise error.Abort(_('only --commands argument allowed with ' | ||
Mateusz Kwapich
|
r24142 | '--edit-plan')) | ||
Pierre-Yves David
|
r19020 | else: | ||
Martin von Zweigbergk
|
r38822 | if state.inprogress(): | ||
Pierre-Yves David
|
r26587 | raise error.Abort(_('history edit already in progress, try ' | ||
Pierre-Yves David
|
r19020 | '--continue or --abort')) | ||
if outg: | ||||
if revs: | ||||
Pierre-Yves David
|
r26587 | raise error.Abort(_('no revisions allowed with --outgoing')) | ||
Pierre-Yves David
|
r19020 | if len(freeargs) > 1: | ||
Pierre-Yves David
|
r26587 | raise error.Abort( | ||
Pierre-Yves David
|
r19020 | _('only one repo argument allowed with --outgoing')) | ||
else: | ||||
Pierre-Yves David
|
r19021 | revs.extend(freeargs) | ||
Durham Goode
|
r24009 | if len(revs) == 0: | ||
Gregory Szorc
|
r27262 | defaultrev = destutil.desthistedit(ui, repo) | ||
if defaultrev is not None: | ||||
revs.append(defaultrev) | ||||
Pierre-Yves David
|
r19021 | if len(revs) != 1: | ||
Pierre-Yves David
|
r26587 | raise error.Abort( | ||
FUJIWARA Katsunori
|
r19621 | _('histedit requires exactly one ancestor revision')) | ||
Pierre-Yves David
|
r19020 | |||
Kostia Balytskyi
|
r28134 | def _histedit(ui, repo, state, *freeargs, **opts): | ||
Pulkit Goyal
|
r35000 | opts = pycompat.byteskwargs(opts) | ||
Pulkit Goyal
|
r35124 | fm = ui.formatter('histedit', opts) | ||
fm.startitem() | ||||
Kostia Balytskyi
|
r28134 | goal = _getgoal(opts) | ||
revs = opts.get('rev', []) | ||||
Yuya Nishihara
|
r41242 | nobackup = not ui.configbool('rewrite', 'backup-bundle') | ||
Kostia Balytskyi
|
r28134 | rules = opts.get('commands', '') | ||
state.keep = opts.get('keep', False) | ||||
Augie Fackler
|
r17064 | |||
Kostia Balytskyi
|
r28134 | _validateargs(ui, repo, state, freeargs, opts, goal, rules, revs) | ||
David Soria Parra
|
r22977 | |||
Navaneeth Suresh
|
r41136 | hastags = False | ||
if revs: | ||||
revs = scmutil.revrange(repo, revs) | ||||
ctxs = [repo[rev] for rev in revs] | ||||
for ctx in ctxs: | ||||
tags = [tag for tag in ctx.tags() if tag != 'tip'] | ||||
if not hastags: | ||||
hastags = len(tags) | ||||
if hastags: | ||||
Navaneeth Suresh
|
r41186 | if ui.promptchoice(_('warning: tags associated with the given' | ||
Yuya Nishihara
|
r41248 | ' changeset will be lost after histedit.\n' | ||
Yuya Nishihara
|
r41247 | 'do you want to continue (yN)? $$ &Yes $$ &No'), | ||
default=1): | ||||
Navaneeth Suresh
|
r41186 | raise error.Abort(_('histedit cancelled\n')) | ||
David Soria Parra
|
r22977 | # rebuild state | ||
Kostia Balytskyi
|
r28144 | if goal == goalcontinue: | ||
David Soria Parra
|
r22983 | state.read() | ||
David Soria Parra
|
r22980 | state = bootstrapcontinue(ui, state, opts) | ||
Kostia Balytskyi
|
r28144 | elif goal == goaleditplan: | ||
Kostia Balytskyi
|
r28154 | _edithisteditplan(ui, repo, state, rules) | ||
Mateusz Kwapich
|
r24142 | return | ||
Kostia Balytskyi
|
r28144 | elif goal == goalabort: | ||
Sushil khanchi
|
r38566 | _aborthistedit(ui, repo, state, nobackup=nobackup) | ||
Augie Fackler
|
r17064 | return | ||
else: | ||||
Kostia Balytskyi
|
r28144 | # goal == goalnew | ||
Kostia Balytskyi
|
r28154 | _newhistedit(ui, repo, state, revs, freeargs, opts) | ||
Durham Goode
|
r24757 | |||
Kostia Balytskyi
|
r28154 | _continuehistedit(ui, repo, state) | ||
Pulkit Goyal
|
r35124 | _finishhistedit(ui, repo, state, fm) | ||
fm.end() | ||||
Kostia Balytskyi
|
r28133 | |||
Kostia Balytskyi
|
r28154 | def _continuehistedit(ui, repo, state): | ||
"""This function runs after either: | ||||
Kostia Balytskyi
|
r28133 | - bootstrapcontinue (if the goal is 'continue') | ||
Kostia Balytskyi
|
r28154 | - _newhistedit (if the goal is 'new') | ||
Kostia Balytskyi
|
r28133 | """ | ||
Augie Fackler
|
r26246 | # preprocess rules so that we can hide inner folds from the user | ||
# and only show one editor | ||||
Mateusz Kwapich
|
r27207 | actions = state.actions[:] | ||
for idx, (action, nextact) in enumerate( | ||||
zip(actions, actions[1:] + [None])): | ||||
if action.verb == 'fold' and nextact and nextact.verb == 'fold': | ||||
state.actions[idx].__class__ = _multifold | ||||
Augie Fackler
|
r26246 | |||
Durham Goode
|
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() | ||||
Martin von Zweigbergk
|
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). | ||||
Boris Feld
|
r34475 | if ui.configbool("histedit", "singletransaction"): | ||
Martin von Zweigbergk
|
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. | ||||
tr = repo.transaction('histedit') | ||||
Martin von Zweigbergk
|
r38397 | progress = ui.makeprogress(_("editing"), unit=_('changes'), | ||
total=len(state.actions)) | ||||
with progress, util.acceptintervention(tr): | ||||
Durham Goode
|
r31513 | while state.actions: | ||
Martin von Zweigbergk
|
r33444 | state.write(tr=tr) | ||
Durham Goode
|
r31513 | actobj = state.actions[0] | ||
Martin von Zweigbergk
|
r38397 | progress.increment(item=actobj.torule()) | ||
Augie Fackler
|
r41925 | ui.debug('histedit: processing %s %s\n' % (actobj.verb, | ||
Durham Goode
|
r31513 | actobj.torule())) | ||
parentctx, replacement_ = actobj.run() | ||||
state.parentctxnode = parentctx.node() | ||||
state.replacements.extend(replacement_) | ||||
state.actions.pop(0) | ||||
Mateusz Kwapich
|
r24111 | state.write() | ||
Augie Fackler
|
r17064 | |||
Pulkit Goyal
|
r35124 | def _finishhistedit(ui, repo, state, fm): | ||
Kostia Balytskyi
|
r28153 | """This action runs when histedit is finishing its session""" | ||
Yuya Nishihara
|
r38527 | hg.updaterepo(repo, state.parentctxnode, overwrite=False) | ||
Augie Fackler
|
r17064 | |||
Augie Fackler
|
r22985 | mapping, tmpnodes, created, ntm = processreplacement(state) | ||
Pierre-Yves David
|
r17758 | if mapping: | ||
for prec, succs in mapping.iteritems(): | ||||
if not succs: | ||||
ui.debug('histedit: %s is dropped\n' % node.short(prec)) | ||||
else: | ||||
ui.debug('histedit: %s is replaced by %s\n' % ( | ||||
node.short(prec), node.short(succs[0]))) | ||||
if len(succs) > 1: | ||||
m = 'histedit: %s' | ||||
for n in succs[1:]: | ||||
ui.debug(m % node.short(n)) | ||||
Durham Goode
|
r25330 | if not state.keep: | ||
Pierre-Yves David
|
r17758 | if mapping: | ||
Jun Wu
|
r33351 | movetopmostbookmarks(repo, state.topmost, ntm) | ||
Pierre-Yves David
|
r17663 | # TODO update mq state | ||
Jun Wu
|
r33350 | else: | ||
mapping = {} | ||||
for n in tmpnodes: | ||||
Boris Feld
|
r39950 | if n in repo: | ||
mapping[n] = () | ||||
Jun Wu
|
r33350 | |||
Jun Wu
|
r33351 | # remove entries about unknown nodes | ||
nodemap = repo.unfiltered().changelog.nodemap | ||||
mapping = {k: v for k, v in mapping.items() | ||||
if k in nodemap and all(n in nodemap for n in v)} | ||||
scmutil.cleanupnodes(repo, mapping, 'histedit') | ||||
Pulkit Goyal
|
r35124 | hf = fm.hexfunc | ||
fl = fm.formatlist | ||||
fd = fm.formatdict | ||||
nodechanges = fd({hf(oldn): fl([hf(n) for n in newn], name='node') | ||||
for oldn, newn in mapping.iteritems()}, | ||||
key="oldnode", value="newnodes") | ||||
fm.data(nodechanges=nodechanges) | ||||
Pierre-Yves David
|
r25894 | |||
David Soria Parra
|
r22978 | state.clear() | ||
Augie Fackler
|
r17064 | if os.path.exists(repo.sjoin('undo')): | ||
os.unlink(repo.sjoin('undo')) | ||||
timeless
|
r27546 | if repo.vfs.exists('histedit-last-edit.txt'): | ||
repo.vfs.unlink('histedit-last-edit.txt') | ||||
Augie Fackler
|
r17064 | |||
Sushil khanchi
|
r38566 | def _aborthistedit(ui, repo, state, nobackup=False): | ||
Kostia Balytskyi
|
r28130 | try: | ||
state.read() | ||||
Kostia Balytskyi
|
r28179 | __, leafs, tmpnodes, __ = processreplacement(state) | ||
Kostia Balytskyi
|
r28130 | ui.debug('restore wc to old parent %s\n' | ||
% node.short(state.topmost)) | ||||
# Recover our old commits if necessary | ||||
if not state.topmost in repo and state.backupfile: | ||||
Pierre-Yves David
|
r31329 | backupfile = repo.vfs.join(state.backupfile) | ||
Kostia Balytskyi
|
r28130 | f = hg.openpath(ui, backupfile) | ||
gen = exchange.readbundle(ui, f, backupfile) | ||||
with repo.transaction('histedit.abort') as tr: | ||||
Martin von Zweigbergk
|
r33043 | bundle2.applybundle(repo, gen, tr, source='histedit', | ||
url='bundle:' + backupfile) | ||||
Kostia Balytskyi
|
r28130 | |||
os.remove(backupfile) | ||||
# check whether we should update away | ||||
if repo.unfiltered().revs('parents() and (%n or %ln::)', | ||||
state.parentctxnode, leafs | tmpnodes): | ||||
hg.clean(repo, state.topmost, show_stats=True, quietempty=True) | ||||
Sushil khanchi
|
r38566 | cleanupnode(ui, repo, tmpnodes, nobackup=nobackup) | ||
cleanupnode(ui, repo, leafs, nobackup=nobackup) | ||||
Kostia Balytskyi
|
r28130 | except Exception: | ||
if state.inprogress(): | ||||
ui.warn(_('warning: encountered an exception during histedit ' | ||||
'--abort; the repository may not have been completely ' | ||||
'cleaned up\n')) | ||||
raise | ||||
finally: | ||||
state.clear() | ||||
Taapas Agrawal
|
r42787 | def hgaborthistedit(ui, repo): | ||
state = histeditstate(repo) | ||||
nobackup = not ui.configbool('rewrite', 'backup-bundle') | ||||
with repo.wlock() as wlock, repo.lock() as lock: | ||||
state.wlock = wlock | ||||
state.lock = lock | ||||
_aborthistedit(ui, repo, state, nobackup=nobackup) | ||||
Kostia Balytskyi
|
r28154 | def _edithisteditplan(ui, repo, state, rules): | ||
Kostia Balytskyi
|
r28131 | state.read() | ||
if not rules: | ||||
Mateusz Kwapich
|
r28592 | comment = geteditcomment(ui, | ||
node.short(state.parentctxnode), | ||||
Kostia Balytskyi
|
r28131 | node.short(state.topmost)) | ||
rules = ruleeditor(repo, ui, state.actions, comment) | ||||
else: | ||||
Yuya Nishihara
|
r30262 | rules = _readfile(ui, rules) | ||
Kostia Balytskyi
|
r28131 | actions = parserules(rules, state) | ||
Augie Fackler
|
r41925 | ctxs = [repo[act.node] | ||
Pierre-Yves David
|
r29874 | for act in state.actions if act.node] | ||
Kostia Balytskyi
|
r28131 | warnverifyactions(ui, repo, actions, state, ctxs) | ||
state.actions = actions | ||||
state.write() | ||||
Kostia Balytskyi
|
r28154 | def _newhistedit(ui, repo, state, revs, freeargs, opts): | ||
Kostia Balytskyi
|
r28132 | outg = opts.get('outgoing') | ||
rules = opts.get('commands', '') | ||||
force = opts.get('force') | ||||
cmdutil.checkunfinished(repo) | ||||
cmdutil.bailifchanged(repo) | ||||
Martin von Zweigbergk
|
r41444 | topmost = repo.dirstate.p1() | ||
Kostia Balytskyi
|
r28132 | if outg: | ||
if freeargs: | ||||
remote = freeargs[0] | ||||
else: | ||||
remote = None | ||||
root = findoutgoing(ui, repo, remote, force, opts) | ||||
else: | ||||
rr = list(repo.set('roots(%ld)', scmutil.revrange(repo, revs))) | ||||
if len(rr) != 1: | ||||
raise error.Abort(_('The specified revisions must have ' | ||||
'exactly one common root')) | ||||
root = rr[0].node() | ||||
revs = between(repo, root, topmost, state.keep) | ||||
if not revs: | ||||
raise error.Abort(_('%s is not an ancestor of working directory') % | ||||
node.short(root)) | ||||
ctxs = [repo[r] for r in revs] | ||||
Augie Fackler
|
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. :( | ||||
ancs = [repo['.']] | ||||
# 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( | ||||
repo, wctx, c, ancs, | ||||
# These parameters were determined by print-debugging | ||||
# what happens later on inside histedit. | ||||
Martin von Zweigbergk
|
r43249 | branchmerge=False, force=False, acceptremote=False, | ||
followcopies=False) | ||||
Augie Fackler
|
r43247 | except error.Abort: | ||
raise error.Abort( | ||||
_("untracked files in working directory conflict with files in %s") % ( | ||||
c)) | ||||
Kostia Balytskyi
|
r28132 | if not rules: | ||
Mateusz Kwapich
|
r28592 | comment = geteditcomment(ui, node.short(root), node.short(topmost)) | ||
Kostia Balytskyi
|
r28132 | actions = [pick(state, r) for r in revs] | ||
rules = ruleeditor(repo, ui, actions, comment) | ||||
else: | ||||
Yuya Nishihara
|
r30262 | rules = _readfile(ui, rules) | ||
Kostia Balytskyi
|
r28132 | actions = parserules(rules, state) | ||
warnverifyactions(ui, repo, actions, state, ctxs) | ||||
Martin von Zweigbergk
|
r41442 | parentctxnode = repo[root].p1().node() | ||
Kostia Balytskyi
|
r28132 | |||
state.parentctxnode = parentctxnode | ||||
state.actions = actions | ||||
state.topmost = topmost | ||||
state.replacements = [] | ||||
Kyle Lippincott
|
r41225 | ui.log("histedit", "%d actions to histedit\n", len(actions), | ||
Phil Cohen
|
r35506 | histedit_num_actions=len(actions)) | ||
Kostia Balytskyi
|
r28132 | # Create a backup so we can always abort completely. | ||
backupfile = None | ||||
if not obsolete.isenabled(repo, obsolete.createmarkersopt): | ||||
Gregory Szorc
|
r37034 | backupfile = repair.backupbundle(repo, [parentctxnode], | ||
[topmost], root, 'histedit') | ||||
Kostia Balytskyi
|
r28132 | state.backupfile = backupfile | ||
Sean Farley
|
r29467 | def _getsummary(ctx): | ||
# a common pattern is to extract the summary but default to the empty | ||||
# string | ||||
summary = ctx.description() or '' | ||||
if summary: | ||||
summary = summary.splitlines()[0] | ||||
return summary | ||||
Durham Goode
|
r24774 | def bootstrapcontinue(ui, state, opts): | ||
repo = state.repo | ||||
Siddharth Agarwal
|
r32057 | |||
ms = mergemod.mergestate.read(repo) | ||||
mergeutil.checkunresolved(ms) | ||||
Mateusz Kwapich
|
r27207 | if state.actions: | ||
actobj = state.actions.pop(0) | ||||
Durham Goode
|
r24959 | |||
liscju
|
r26981 | if _isdirtywc(repo): | ||
Durham Goode
|
r24959 | actobj.continuedirty() | ||
liscju
|
r26981 | if _isdirtywc(repo): | ||
Mateusz Kwapich
|
r27084 | abortdirty() | ||
Durham Goode
|
r24766 | |||
Durham Goode
|
r24959 | parentctx, replacements = actobj.continueclean() | ||
Pierre-Yves David
|
r17666 | |||
Durham Goode
|
r24959 | state.parentctxnode = parentctx.node() | ||
state.replacements.extend(replacements) | ||||
David Soria Parra
|
r22980 | |||
return state | ||||
Pierre-Yves David
|
r17666 | |||
Pierre-Yves David
|
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.""" | ||||
Yuya Nishihara
|
r36431 | revs = repo.revs('%n::%n', old, new) | ||
if revs and not keep: | ||||
Durham Goode
|
r22952 | if (not obsolete.isenabled(repo, obsolete.allowunstableopt) and | ||
Gregory Szorc
|
r36427 | repo.revs('(%ld::) - (%ld)', revs, revs)): | ||
liscju
|
r28294 | raise error.Abort(_('can only histedit a changeset together ' | ||
'with all its descendants')) | ||||
Gregory Szorc
|
r36427 | if repo.revs('(%ld) and merge()', revs): | ||
Pierre-Yves David
|
r26587 | raise error.Abort(_('cannot edit history that contains merges')) | ||
Yuya Nishihara
|
r36431 | root = repo[revs.first()] # list is already sorted by repo.revs() | ||
Augie Fackler
|
r22416 | if not root.mutable(): | ||
Pierre-Yves David
|
r26587 | raise error.Abort(_('cannot edit public changeset: %s') % root, | ||
timeless
|
r29970 | hint=_("see 'hg help phases' for details")) | ||
Yuya Nishihara
|
r36431 | return pycompat.maplist(repo.changelog.node, revs) | ||
Pierre-Yves David
|
r17642 | |||
Mateusz Kwapich
|
r27204 | def ruleeditor(repo, ui, actions, editcomment=""): | ||
Mateusz Kwapich
|
r24140 | """open an editor to edit rules | ||
rules are in the format [ [act, ctx], ...] like in state.rules | ||||
""" | ||||
Sean Farley
|
r29465 | if repo.ui.configbool("experimental", "histedit.autoverb"): | ||
Sean Farley
|
r29470 | newact = util.sortdict() | ||
Sean Farley
|
r29465 | for act in actions: | ||
ctx = repo[act.node] | ||||
Sean Farley
|
r29469 | summary = _getsummary(ctx) | ||
Sean Farley
|
r29465 | fword = summary.split(' ', 1)[0].lower() | ||
Sean Farley
|
r29470 | added = False | ||
Sean Farley
|
r29465 | # if it doesn't end with the special character '!' just skip this | ||
if fword.endswith('!'): | ||||
fword = fword[:-1] | ||||
if fword in primaryactions | secondaryactions | tertiaryactions: | ||||
act.verb = fword | ||||
Sean Farley
|
r29470 | # get the target summary | ||
tsum = summary[len(fword) + 1:].lstrip() | ||||
# safe but slow: reverse iterate over the actions so we | ||||
# don't clash on two commits having the same summary | ||||
for na, l in reversed(list(newact.iteritems())): | ||||
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 = [] | ||||
for na, l in newact.iteritems(): | ||||
actions.append(na) | ||||
actions += l | ||||
Sean Farley
|
r29465 | |||
Sean Farley
|
r29466 | rules = '\n'.join([act.torule() for act in actions]) | ||
Mateusz Kwapich
|
r24140 | rules += '\n\n' | ||
rules += editcomment | ||||
Sean Farley
|
r30837 | rules = ui.edit(rules, ui.username(), {'prefix': 'histedit'}, | ||
Michael Bolin
|
r34030 | repopath=repo.path, action='histedit') | ||
Mateusz Kwapich
|
r24140 | |||
# Save edit rules in .hg/histedit-last-edit.txt in case | ||||
# the user needs to ask for help after something | ||||
# surprising happens. | ||||
Augie Fackler
|
r36186 | with repo.vfs('histedit-last-edit.txt', 'wb') as f: | ||
f.write(rules) | ||||
Mateusz Kwapich
|
r24140 | |||
return rules | ||||
Mateusz Kwapich
|
r27208 | def parserules(rules, state): | ||
"""Read the histedit rules string and return list of action objects """ | ||||
rules = [l for l in (r.strip() for r in rules.splitlines()) | ||||
if l and not l.startswith('#')] | ||||
actions = [] | ||||
Augie Fackler
|
r17064 | for r in rules: | ||
if ' ' not in r: | ||||
timeless
|
r27545 | raise error.ParseError(_('malformed line "%s"') % r) | ||
Mateusz Kwapich
|
r27082 | verb, rest = r.split(' ', 1) | ||
Mateusz Kwapich
|
r27208 | if verb not in actiontable: | ||
timeless
|
r27545 | raise error.ParseError(_('unknown action "%s"') % verb) | ||
Mateusz Kwapich
|
r27208 | |||
Mateusz Kwapich
|
r27082 | action = actiontable[verb].fromrule(state, rest) | ||
Mateusz Kwapich
|
r27208 | actions.append(action) | ||
return actions | ||||
timeless
|
r27543 | def warnverifyactions(ui, repo, actions, state, ctxs): | ||
try: | ||||
verifyactions(actions, state, ctxs) | ||||
timeless
|
r27545 | except error.ParseError: | ||
timeless
|
r27543 | if repo.vfs.exists('histedit-last-edit.txt'): | ||
ui.warn(_('warning: histedit rules saved ' | ||||
'to: .hg/histedit-last-edit.txt\n')) | ||||
raise | ||||
Mateusz Kwapich
|
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. | ||||
""" | ||||
Pierre-Yves David
|
r29878 | expected = set(c.node() for c in ctxs) | ||
Mateusz Kwapich
|
r27208 | seen = set() | ||
timeless
|
r27541 | prev = None | ||
André Klitzing
|
r33757 | |||
if actions and actions[0].verb in ['roll', 'fold']: | ||||
raise error.ParseError(_('first changeset cannot use verb "%s"') % | ||||
actions[0].verb) | ||||
Mateusz Kwapich
|
r27208 | for action in actions: | ||
Pierre-Yves David
|
r29879 | action.verify(prev, expected, seen) | ||
timeless
|
r27541 | prev = action | ||
Pierre-Yves David
|
r29876 | if action.node is not None: | ||
Pierre-Yves David
|
r29878 | seen.add(action.node) | ||
Pierre-Yves David
|
r19048 | missing = sorted(expected - seen) # sort to stabilize output | ||
Mateusz Kwapich
|
r27414 | |||
if state.repo.ui.configbool('histedit', 'dropmissing'): | ||||
Mateusz Kwapich
|
r28519 | if len(actions) == 0: | ||
raise error.ParseError(_('no rules provided'), | ||||
hint=_('use strip extension to remove commits')) | ||||
Pierre-Yves David
|
r29878 | drops = [drop(state, n) for n in missing] | ||
Mateusz Kwapich
|
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: | ||||
timeless
|
r27545 | raise error.ParseError(_('missing rules for changeset %s') % | ||
Pierre-Yves David
|
r29878 | node.short(missing[0]), | ||
Mateusz Kwapich
|
r27414 | hint=_('use "drop %s" to discard, see also: ' | ||
timeless
|
r29970 | "'hg help -e histedit.config'") | ||
Pierre-Yves David
|
r29878 | % node.short(missing[0])) | ||
Pierre-Yves David
|
r17663 | |||
Kostia Balytskyi
|
r28216 | def adjustreplacementsfrommarkers(repo, oldreplacements): | ||
Mads Kiilerich
|
r30332 | """Adjust replacements from obsolescence markers | ||
Kostia Balytskyi
|
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 | ||||
Mads Kiilerich
|
r30332 | data read from obsolescence markers""" | ||
Kostia Balytskyi
|
r28216 | if not obsolete.isenabled(repo, obsolete.createmarkersopt): | ||
return oldreplacements | ||||
unfi = repo.unfiltered() | ||||
Pierre-Yves David
|
r28224 | nm = unfi.changelog.nodemap | ||
obsstore = repo.obsstore | ||||
Kostia Balytskyi
|
r28216 | newreplacements = list(oldreplacements) | ||
oldsuccs = [r[1] for r in oldreplacements] | ||||
# successors that have already been added to succstocheck once | ||||
seensuccs = set().union(*oldsuccs) # create a set from an iterable of tuples | ||||
succstocheck = list(seensuccs) | ||||
while succstocheck: | ||||
n = succstocheck.pop() | ||||
Pierre-Yves David
|
r28224 | missing = nm.get(n) is None | ||
markers = obsstore.successors.get(n, ()) | ||||
if missing and not markers: | ||||
# dead end, mark it as such | ||||
Kostia Balytskyi
|
r28216 | newreplacements.append((n, ())) | ||
Pierre-Yves David
|
r28224 | for marker in markers: | ||
nsuccs = marker[1] | ||||
Kostia Balytskyi
|
r28216 | newreplacements.append((n, nsuccs)) | ||
for nsucc in nsuccs: | ||||
if nsucc not in seensuccs: | ||||
seensuccs.add(nsucc) | ||||
succstocheck.append(nsucc) | ||||
return newreplacements | ||||
Augie Fackler
|
r22985 | def processreplacement(state): | ||
Pierre-Yves David
|
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""" | ||||
Kostia Balytskyi
|
r28216 | replacements = adjustreplacementsfrommarkers(state.repo, state.replacements) | ||
Pierre-Yves David
|
r17758 | allsuccs = set() | ||
replaced = set() | ||||
fullmapping = {} | ||||
Augie Fackler
|
r26039 | # initialize basic set | ||
# fullmapping records all operations recorded in replacement | ||||
Pierre-Yves David
|
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 | ||||
Augie Fackler
|
r26039 | # Reduce content fullmapping into direct relation between original nodes | ||
Pierre-Yves David
|
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) | ||||
Augie Fackler
|
r22985 | nm = state.repo.changelog.nodemap | ||
Pierre-Yves David
|
r17758 | for prec, succs in final.items(): | ||
final[prec] = sorted(succs, key=nm.get) | ||||
Pierre-Yves David
|
r17663 | |||
Pierre-Yves David
|
r17758 | # computed topmost element (necessary for bookmark) | ||
if new: | ||||
Augie Fackler
|
r22985 | newtopmost = sorted(new, key=state.repo.changelog.rev)[-1] | ||
Pierre-Yves David
|
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. | ||||
Augie Fackler
|
r22985 | r = state.repo.changelog.rev | ||
newtopmost = state.repo[sorted(final, key=r)[0]].p1().node() | ||||
Pierre-Yves David
|
r17758 | |||
return final, tmpnodes, new, newtopmost | ||||
Pierre-Yves David
|
r17663 | |||
Jun Wu
|
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: | ||||
with repo.lock(), repo.transaction('histedit') as tr: | ||||
marks = repo._bookmarks | ||||
Boris Feld
|
r33486 | changes = [] | ||
Jun Wu
|
r33346 | for name in oldbmarks: | ||
Boris Feld
|
r33486 | changes.append((name, newtopmost)) | ||
marks.applychanges(repo, tr, changes) | ||||
Jun Wu
|
r33346 | |||
Sushil khanchi
|
r38566 | def cleanupnode(ui, repo, nodes, nobackup=False): | ||
Pierre-Yves David
|
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) | ||||
nm = repo.changelog.nodemap | ||||
nodes = sorted(n for n in nodes if n in nm) | ||||
roots = [c.node() for c in repo.set("roots(%ln)", nodes)] | ||||
Jun Wu
|
r33349 | if roots: | ||
Sushil khanchi
|
r38566 | backup = not nobackup | ||
repair.strip(ui, repo, roots, backup=backup) | ||||
Pierre-Yves David
|
r31637 | |||
Mateusz Kwapich
|
r24111 | def stripwrapper(orig, ui, repo, nodelist, *args, **kwargs): | ||
if isinstance(nodelist, str): | ||||
nodelist = [nodelist] | ||||
Martin von Zweigbergk
|
r38822 | state = histeditstate(repo) | ||
if state.inprogress(): | ||||
Mateusz Kwapich
|
r24111 | state.read() | ||
Martin von Zweigbergk
|
r32291 | histedit_nodes = {action.node for action | ||
in state.actions if action.node} | ||||
Martin von Zweigbergk
|
r30025 | common_nodes = histedit_nodes & set(nodelist) | ||
Mateusz Kwapich
|
r24111 | if common_nodes: | ||
Pierre-Yves David
|
r26587 | raise error.Abort(_("histedit in progress, can't strip %s") | ||
Matt Mackall
|
r24196 | % ', '.join(node.short(x) for x in common_nodes)) | ||
Mateusz Kwapich
|
r24111 | return orig(ui, repo, nodelist, *args, **kwargs) | ||
extensions.wrapfunction(repair, 'strip', stripwrapper) | ||||
Bryan O'Sullivan
|
r19215 | def summaryhook(ui, repo): | ||
Martin von Zweigbergk
|
r38822 | state = histeditstate(repo) | ||
if not state.inprogress(): | ||||
Bryan O'Sullivan
|
r19215 | return | ||
David Soria Parra
|
r22983 | state.read() | ||
Mateusz Kwapich
|
r27207 | if state.actions: | ||
Bryan O'Sullivan
|
r19215 | # i18n: column positioning for "hg summary" | ||
ui.write(_('hist: %s (histedit --continue)\n') % | ||||
(ui.label(_('%d remaining'), 'histedit.remaining') % | ||||
Mateusz Kwapich
|
r27207 | len(state.actions))) | ||
Bryan O'Sullivan
|
r19215 | |||
def extsetup(ui): | ||||
cmdutil.summaryhooks.add('histedit', summaryhook) | ||||
Taapas Agrawal
|
r42733 | statemod.addunfinished('histedit', fname='histedit-state', allowcommit=True, | ||
Taapas Agrawal
|
r42787 | continueflag=True, abortfunc=hgaborthistedit) | ||