##// END OF EJS Templates
rebase: add boolean config item rebase.store-source...
rebase: add boolean config item rebase.store-source This allows to use rebase without recording a rebase_source extra field. This is useful for example to build a mirror converted from another SCM (such as svn) by converting only new revisions, and then incrementally add them to the destination by pulling from the newly converted (unrelated) repo and rebasing the new revisions onto the last old already stored changeset. Without this patch the rebased changesets would always receive some rebase_source that would depend on the particular history of the conversion process, instead of only depending on the original source revisions. This is used to implement a hg mirror repo of SvarDOS (a partially nonfree but completely redistributable DOS distribution) in the scripts at https://hg.pushbx.org/ecm/svardos.scr/ In particular, cre.sh creates an svn mirror, upd.sh recreates an entire hg repo from the svn mirror (which takes too long to do in a regular job), and akt.sh uses hg convert with the config item convert.svn.startrev to incrementally convert only the two most recent revisions already found in the mirror destination plus any possible new revisions. If any are found, the temporary repo's changesets are pulled into the destination (as changesets from an unrelated repository). Then the changesets corresponding to the new revisions are rebased onto the prior final changeset. (Finally, the two remaining duplicates of the prior head and its parent are stripped from the destination repository.) Without this patch, the particular rebase_source extra field would depend on the order and times at which akt.sh was used, instead of only depending on the source repository. In other words, whatever sequence of upd.sh and akt.sh is used at whatever times, it is desired that the final output repositories always match each other exactly.

File last commit:

r49801:642e31cb default
r50343:cfff73ca default
Show More
fix.py
955 lines | 36.2 KiB | text/x-python | PythonLexer
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 # fix - rewrite file content in changesets and working copy
#
# Copyright 2018 Google LLC.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""rewrite file content in changesets or working copy (EXPERIMENTAL)
Provides a command that runs configured tools on the contents of modified files,
writing back any fixes to the working copy or replacing changesets.
Here is an example configuration that causes :hg:`fix` to apply automatic
formatting fixes to modified lines in C++ code::
[fix]
clang-format:command=clang-format --assume-filename={rootpath}
clang-format:linerange=--lines={first}:{last}
Danny Hooper
fix: rename :fileset subconfig to :pattern...
r40569 clang-format:pattern=set:**.cpp or **.hpp
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
The :command suboption forms the first part of the shell command that will be
used to fix a file. The content of the file is passed on standard input, and the
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568 fixed file content is expected on standard output. Any output on standard error
will be displayed as a warning. If the exit status is not zero, the file will
not be affected. A placeholder warning is displayed if there is a non-zero exit
status but no standard error output. Some values may be substituted into the
command::
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
{rootpath} The path of the file being fixed, relative to the repo root
{basename} The name of the file being fixed, without the directory path
If the :linerange suboption is set, the tool will only be run if there are
changed lines in a file. The value of this suboption is appended to the shell
command once for every range of changed lines in the file. Some values may be
substituted into the command::
{first} The 1-based line number of the first line in the modified range
{last} The 1-based line number of the last line in the modified range
Danny Hooper
fix: allow tools to use :linerange, but also run if a file is unchanged...
r43001 Deleted sections of a file will be ignored by :linerange, because there is no
corresponding line range in the version being fixed.
By default, tools that set :linerange will only be executed if there is at least
one changed line range. This is meant to prevent accidents like running a code
formatter in such a way that it unexpectedly reformats the whole file. If such a
tool needs to operate on unchanged files, it should set the :skipclean suboption
to false.
Danny Hooper
fix: rename :fileset subconfig to :pattern...
r40569 The :pattern suboption determines which files will be passed through each
Martin von Zweigbergk
fix: match patterns relative to root...
r43501 configured tool. See :hg:`help patterns` for possible values. However, all
patterns are relative to the repo root, even if that text says they are relative
to the current working directory. If there are file arguments to :hg:`fix`, the
intersection of these patterns is used.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
There is also a configurable limit for the maximum size of file that will be
processed by :hg:`fix`::
[fix]
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568 maxfilesize = 2MB
Normally, execution of configured tools will continue after a failure (indicated
by a non-zero exit status). It can also be configured to abort after the first
such failure, so that no files will be affected if any tool fails. This abort
will also cause :hg:`fix` to exit with a non-zero status::
[fix]
failure = abort
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Danny Hooper
fix: add suboption for configuring execution order of tools...
r40599 When multiple tools are configured to affect a file, they execute in an order
defined by the :priority suboption. The priority suboption has a default value
of zero for each tool. Tools are executed in order of descending priority. The
execution order of tools with equal priority is unspecified. For example, you
could use the 'sort' and 'head' utilities to keep only the 10 smallest numbers
in a text file by ensuring that 'sort' runs before 'head'::
[fix]
Danny Hooper
tests: use more portable flags in test-fix.t...
r41162 sort:command = sort -n
head:command = head -n 10
Danny Hooper
fix: add suboption for configuring execution order of tools...
r40599 sort:pattern = numbers.txt
head:pattern = numbers.txt
sort:priority = 2
head:priority = 1
To account for changes made by each tool, the line numbers used for incremental
formatting are recomputed before executing the next tool. So, each tool may see
different values for the arguments added by the :linerange suboption.
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372
Each fixer tool is allowed to return some metadata in addition to the fixed file
content. The metadata must be placed before the file content on stdout,
separated from the file content by a zero byte. The metadata is parsed as a JSON
value (so, it should be UTF-8 encoded and contain no zero bytes). A fixer tool
is expected to produce this metadata encoding if and only if the :metadata
suboption is true::
[fix]
tool:command = tool --prepend-json-metadata
tool:metadata = true
The metadata values are passed to hooks, which can be used to print summaries or
perform other post-fixing work. The supported hooks are::
"postfixfile"
Run once for each file in each revision where any fixer tools made changes
to the file content. Provides "$HG_REV" and "$HG_PATH" to identify the file,
and "$HG_METADATA" with a map of fixer names to metadata values from fixer
tools that affected the file. Fixer tools that didn't affect the file have a
timeless
fix: fix grammar/typos in hg help -e fix
r44500 value of None. Only fixer tools that executed are present in the metadata.
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372
"postfix"
Run once after all files and revisions have been handled. Provides
"$HG_REPLACEMENTS" with information about what revisions were created and
made obsolete. Provides a boolean "$HG_WDIRWRITTEN" to indicate whether any
files in the working copy were updated. Provides a list "$HG_METADATA"
mapping fixer tool names to lists of metadata values returned from
executions that modified a file. This aggregates the same metadata
previously passed to the "postfixfile" hook.
Danny Hooper
fix: run fixer tools in the repo root as cwd so they can use the working copy...
r42900
timeless
fix: fix grammar/typos in hg help -e fix
r44500 Fixer tools are run in the repository's root directory. This allows them to read
Danny Hooper
fix: run fixer tools in the repo root as cwd so they can use the working copy...
r42900 configuration files from the working copy, or even write to the working copy.
The working copy is not updated to match the revision being fixed. In fact,
several revisions may be fixed in parallel. Writes to the working copy are not
amended into the revision being fixed; fixer tools should always write fixed
file content back to stdout as documented above.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """
import collections
import itertools
import os
import re
import subprocess
from mercurial.i18n import _
Joerg Sonnenberger
fix: merge imports...
r47595 from mercurial.node import (
Martin von Zweigbergk
fix: rewrite writeworkingdir() to explicitly not work with merges...
r48566 nullid,
Joerg Sonnenberger
fix: merge imports...
r47595 nullrev,
wdirrev,
)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Martin von Zweigbergk
fix: make Fixer initialization more explicit for clarity...
r43493 from mercurial.utils import procutil
Matt Harbison
py3: convert arguments, cwd and env to native strings when spawning subprocess...
r39851
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 from mercurial import (
cmdutil,
context,
copies,
error,
Martin von Zweigbergk
errors: raise InputError on bad revset to revrange() iff provided by the user...
r48928 logcmdutil,
Martin von Zweigbergk
fix: match patterns relative to root...
r43501 match as matchmod,
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 mdiff,
merge,
Augie Fackler
mergestate: split out merge state handling code from main merge module...
r45383 mergestate as mergestatemod,
Augie Fackler
fix: port most of the way to python 3...
r37636 pycompat,
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 registrar,
Martin von Zweigbergk
fix: use rewriteutil.precheck() instead of reimplementing it...
r44388 rewriteutil,
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 scmutil,
util,
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554 worker,
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 )
# Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
# 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
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 testedwith = b'ships-with-hg-core'
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
cmdtable = {}
command = registrar.command(cmdtable)
configtable = {}
configitem = registrar.configitem(configtable)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 # Register the suboptions allowed for each configured fixer, and default values.
Danny Hooper
fix: add suboption for configuring execution order of tools...
r40599 FIXER_ATTRS = {
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'command': None,
b'linerange': None,
b'pattern': None,
b'priority': 0,
Martin von Zweigbergk
fix: make Fixer initialization more explicit for clarity...
r43493 b'metadata': False,
b'skipclean': True,
b'enabled': True,
Danny Hooper
fix: add suboption for configuring execution order of tools...
r40599 }
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Danny Hooper
fix: add suboption for configuring execution order of tools...
r40599 for key, default in FIXER_ATTRS.items():
Martin von Zweigbergk
fix: fix registration of config item defaults...
r43488 configitem(b'fix', b'.*:%s$' % key, default=default, generic=True)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
# A good default size allows most source code files to be fixed, but avoids
# letting fixer tools choke on huge inputs, which could be surprising to the
# user.
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 configitem(b'fix', b'maxfilesize', default=b'2MB')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568 # Allow fix commands to exit non-zero if an executed fixer tool exits non-zero.
# This helps users do shell scripts that stop when a fixer tool signals a
# problem.
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 configitem(b'fix', b'failure', default=b'continue')
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568 def checktoolfailureaction(ui, message, hint=None):
"""Abort with 'message' if fix.failure=abort"""
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 action = ui.config(b'fix', b'failure')
if action not in (b'continue', b'abort'):
Augie Fackler
formatting: blacken the codebase...
r43346 raise error.Abort(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b'unknown fix.failure action: %s') % (action,),
hint=_(b'use "continue" or "abort"'),
Augie Fackler
formatting: blacken the codebase...
r43346 )
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 if action == b'abort':
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568 raise error.Abort(message, hint=hint)
Augie Fackler
formatting: blacken the codebase...
r43346
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 allopt = (b'', b'all', False, _(b'fix all non-public non-obsolete revisions'))
Augie Fackler
formatting: blacken the codebase...
r43346 baseopt = (
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'',
b'base',
Augie Fackler
formatting: blacken the codebase...
r43346 [],
_(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'revisions to diff against (overrides automatic '
b'selection, and applies to every revision being '
b'fixed)'
Augie Fackler
formatting: blacken the codebase...
r43346 ),
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b'REV'),
Augie Fackler
formatting: blacken the codebase...
r43346 )
Martin von Zweigbergk
fix: mark -r as advanced...
r45065 revopt = (b'r', b'rev', [], _(b'revisions to fix (ADVANCED)'), _(b'REV'))
Martin von Zweigbergk
fix: add a -s option to format a revision and its descendants...
r45064 sourceopt = (
b's',
b'source',
[],
_(b'fix the specified revisions and their descendants'),
_(b'REV'),
)
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 wdiropt = (b'w', b'working-dir', False, _(b'fix the working directory'))
wholeopt = (b'', b'whole', False, _(b'always fix every line of a file'))
usage = _(b'[OPTION]... [FILE]...')
Danny Hooper
fix: pull out flag definitions to make them re-usable from extensions...
r38984
Augie Fackler
formatting: blacken the codebase...
r43346
@command(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'fix',
Martin von Zweigbergk
fix: add a -s option to format a revision and its descendants...
r45064 [allopt, baseopt, revopt, sourceopt, wdiropt, wholeopt],
Augie Fackler
formatting: blacken the codebase...
r43346 usage,
helpcategory=command.CATEGORY_FILE_CONTENTS,
)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def fix(ui, repo, *pats, **opts):
"""rewrite file content in changesets or working directory
Runs any configured tools to fix the content of files. Only affects files
with changes, unless file arguments are provided. Only affects changed lines
of files, unless the --whole flag is used. Some tools may always affect the
whole file regardless of --whole.
Martin von Zweigbergk
fix: update documentation to reflect preference for --source over --rev...
r45777 If --working-dir is used, files with uncommitted changes in the working copy
will be fixed. Note that no backup are made.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Martin von Zweigbergk
fix: update documentation to reflect preference for --source over --rev...
r45777 If revisions are specified with --source, those revisions and their
descendants will be checked, and they may be replaced with new revisions
that have fixed file content. By automatically including the descendants,
no merging, rebasing, or evolution will be required. If an ancestor of the
working copy is included, then the working copy itself will also be fixed,
and the working copy will be updated to the fixed parent.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
When determining what lines of each file to fix at each revision, the whole
set of revisions being fixed is considered, so that fixes to earlier
revisions are not forgotten in later ones. The --base flag can be used to
override this default behavior, though it is not usually desirable to do so.
"""
Augie Fackler
fix: port most of the way to python 3...
r37636 opts = pycompat.byteskwargs(opts)
Martin von Zweigbergk
fix: add a -s option to format a revision and its descendants...
r45064 cmdutil.check_at_most_one_arg(opts, b'all', b'source', b'rev')
cmdutil.check_incompatible_arguments(
opts, b'working_dir', [b'all', b'source']
)
Martin von Zweigbergk
fix: move handling of --all into getrevstofix() for consistency...
r45063
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 with repo.wlock(), repo.lock(), repo.transaction(b'fix'):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 revstofix = getrevstofix(ui, repo, opts)
basectxs = getbasectxs(repo, opts, revstofix)
Augie Fackler
formatting: blacken the codebase...
r43346 workqueue, numitems = getworkqueue(
ui, repo, pats, opts, revstofix, basectxs
)
Rodrigo Damazio Bovendorp
fix: obtain base paths before starting workers...
r45633 basepaths = getbasepaths(repo, opts, workqueue, basectxs)
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554 fixers = getfixers(ui)
Rodrigo Damazio Bovendorp
fix: prefetch file contents...
r45634 # Rather than letting each worker independently fetch the files
# (which also would add complications for shared/keepalive
# connections), prefetch them all first.
_prefetchfiles(repo, workqueue, basepaths)
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554 # There are no data dependencies between the workers fixing each file
# revision, so we can use all available parallelism.
def getfixes(items):
Danny Hooper
fix: reduce number of tool executions...
r48992 for srcrev, path, dstrevs in items:
ctx = repo[srcrev]
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554 olddata = ctx[path].data()
Augie Fackler
formatting: blacken the codebase...
r43346 metadata, newdata = fixfile(
Danny Hooper
fix: reduce number of tool executions...
r48992 ui,
repo,
opts,
fixers,
ctx,
path,
basepaths,
basectxs[srcrev],
Augie Fackler
formatting: blacken the codebase...
r43346 )
Danny Hooper
fix: reduce number of tool executions...
r48992 # We ungroup the work items now, because the code that consumes
# these results has to handle each dstrev separately, and in
# topological order. Because these are handled in topological
# order, it's important that we pass around references to
# "newdata" instead of copying it. Otherwise, we would be
# keeping more copies of file content in memory at a time than
# if we hadn't bothered to group/deduplicate the work items.
data = newdata if newdata != olddata else None
for dstrev in dstrevs:
yield (dstrev, path, metadata, data)
Augie Fackler
formatting: blacken the codebase...
r43346
results = worker.worker(
ui, 1.0, getfixes, tuple(), workqueue, threadsafe=False
)
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554
# We have to hold on to the data for each successor revision in memory
# until all its parents are committed. We ensure this by committing and
# freeing memory for the revisions in some topological order. This
# leaves a little bit of memory efficiency on the table, but also makes
# the tests deterministic. It might also be considered a feature since
# it makes the results more easily reproducible.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 filedata = collections.defaultdict(dict)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 aggregatemetadata = collections.defaultdict(list)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 replacements = {}
Danny Hooper
fix: correctly set wdirwritten given that the dict item is deleted...
r38985 wdirwritten = False
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554 commitorder = sorted(revstofix, reverse=True)
Augie Fackler
formatting: blacken the codebase...
r43346 with ui.makeprogress(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 topic=_(b'fixing'), unit=_(b'files'), total=sum(numitems.values())
Augie Fackler
formatting: blacken the codebase...
r43346 ) as progress:
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 for rev, path, filerevmetadata, newdata in results:
Danny Hooper
fix: add progress bar for number of file revisions processed...
r38555 progress.increment(item=path)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 for fixername, fixermetadata in filerevmetadata.items():
aggregatemetadata[fixername].append(fixermetadata)
Danny Hooper
fix: add progress bar for number of file revisions processed...
r38555 if newdata is not None:
filedata[rev][path] = newdata
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 hookargs = {
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'rev': rev,
b'path': path,
b'metadata': filerevmetadata,
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 }
Augie Fackler
formatting: blacken the codebase...
r43346 repo.hook(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'postfixfile',
Augie Fackler
formatting: blacken the codebase...
r43346 throw=False,
**pycompat.strkwargs(hookargs)
)
Danny Hooper
fix: add progress bar for number of file revisions processed...
r38555 numitems[rev] -= 1
# Apply the fixes for this and any other revisions that are
# ready and sitting at the front of the queue. Using a loop here
# prevents the queue from being blocked by the first revision to
# be ready out of order.
while commitorder and not numitems[commitorder[-1]]:
rev = commitorder.pop()
ctx = repo[rev]
if rev == wdirrev:
writeworkingdir(repo, ctx, filedata[rev], replacements)
Danny Hooper
fix: correctly set wdirwritten given that the dict item is deleted...
r38985 wdirwritten = bool(filedata[rev])
Danny Hooper
fix: add progress bar for number of file revisions processed...
r38555 else:
replacerev(ui, repo, ctx, filedata[rev], replacements)
del filedata[rev]
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Danny Hooper
fix: correctly set wdirwritten given that the dict item is deleted...
r38985 cleanup(repo, replacements, wdirwritten)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 hookargs = {
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'replacements': replacements,
b'wdirwritten': wdirwritten,
b'metadata': aggregatemetadata,
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 }
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 repo.hook(b'postfix', throw=True, **pycompat.strkwargs(hookargs))
Danny Hooper
fix: add a monkey-patchable point after all new revisions have been committed...
r38847
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: add a monkey-patchable point after all new revisions have been committed...
r38847 def cleanup(repo, replacements, wdirwritten):
"""Calls scmutil.cleanupnodes() with the given replacements.
"replacements" is a dict from nodeid to nodeid, with one key and one value
for every revision that was affected by fixing. This is slightly different
from cleanupnodes().
"wdirwritten" is a bool which tells whether the working copy was affected by
fixing, since it has no entry in "replacements".
Useful as a hook point for extending "hg fix" with output summarizing the
effects of the command, though we choose not to output anything here.
"""
Gregory Szorc
global: bulk replace simple pycompat.iteritems(x) with x.items()...
r49768 replacements = {prec: [succ] for prec, succ in replacements.items()}
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 scmutil.cleanupnodes(repo, replacements, b'fix', fixphase=True)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def getworkqueue(ui, repo, pats, opts, revstofix, basectxs):
Danny Hooper
fix: reduce number of tool executions...
r48992 """Constructs a list of files to fix and which revisions each fix applies to
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Danny Hooper
fix: reduce number of tool executions...
r48992 To avoid duplicating work, there is usually only one work item for each file
revision that might need to be fixed. There can be multiple work items per
file revision if the same file needs to be fixed in multiple changesets with
different baserevs. Each work item also contains a list of changesets where
the file's data should be replaced with the fixed data. The work items for
earlier changesets come earlier in the work queue, to improve pipelining by
allowing the first changeset to be replaced while fixes are still being
computed for later changesets.
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554
Danny Hooper
fix: reduce number of tool executions...
r48992 Also returned is a map from changesets to the count of work items that might
affect each changeset. This is used later to count when all of a changeset's
work items have been finished, without having to inspect the remaining work
queue in each worker subprocess.
The example work item (1, "foo/bar.txt", (1, 2, 3)) means that the data of
bar.txt should be read from revision 1, then fixed, and written back to
revisions 1, 2 and 3. Revision 1 is called the "srcrev" and the list of
revisions is called the "dstrevs". In practice the srcrev is always one of
the dstrevs, and we make that choice when constructing the work item so that
the choice can't be made inconsistently later on. The dstrevs should all
have the same file revision for the given path, so the choice of srcrev is
arbitrary. The wdirrev can be a dstrev and a srcrev.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """
Danny Hooper
fix: reduce number of tool executions...
r48992 dstrevmap = collections.defaultdict(list)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 numitems = collections.defaultdict(int)
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 maxfilesize = ui.configbytes(b'fix', b'maxfilesize')
Danny Hooper
fix: use a worker pool to parallelize running tools...
r38554 for rev in sorted(revstofix):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 fixctx = repo[rev]
match = scmutil.match(fixctx, pats, opts)
Augie Fackler
formatting: blacken the codebase...
r43346 for path in sorted(
pathstofix(ui, repo, pats, opts, match, basectxs[rev], fixctx)
):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 fctx = fixctx[path]
if fctx.islink():
continue
if fctx.size() > maxfilesize:
Augie Fackler
formatting: blacken the codebase...
r43346 ui.warn(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b'ignoring file larger than %s: %s\n')
Augie Fackler
formatting: blacken the codebase...
r43346 % (util.bytecount(maxfilesize), path)
)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 continue
Danny Hooper
fix: reduce number of tool executions...
r48992 baserevs = tuple(ctx.rev() for ctx in basectxs[rev])
dstrevmap[(fctx.filerev(), baserevs, path)].append(rev)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 numitems[rev] += 1
Danny Hooper
fix: reduce number of tool executions...
r48992 workqueue = [
(min(dstrevs), path, dstrevs)
Raphaël Gomès
fix: appease pyflakes and make unused variables more obvious...
r49059 for (_filerev, _baserevs, path), dstrevs in dstrevmap.items()
Danny Hooper
fix: reduce number of tool executions...
r48992 ]
# Move work items for earlier changesets to the front of the queue, so we
# might be able to replace those changesets (in topological order) while
# we're still processing later work items. Note the min() in the previous
# expression, which means we don't need a custom comparator here. The path
# is also important in the sort order to make the output order stable. There
# are some situations where this doesn't help much, but some situations
# where it lets us buffer O(1) files instead of O(n) files.
workqueue.sort()
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 return workqueue, numitems
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def getrevstofix(ui, repo, opts):
"""Returns the set of revision numbers that should be fixed"""
Martin von Zweigbergk
fix: move handling of --all into getrevstofix() for consistency...
r45063 if opts[b'all']:
revs = repo.revs(b'(not public() and not obsolete()) or wdir()')
Martin von Zweigbergk
fix: add a -s option to format a revision and its descendants...
r45064 elif opts[b'source']:
Martin von Zweigbergk
errors: raise InputError on bad revset to revrange() iff provided by the user...
r48928 source_revs = logcmdutil.revrange(repo, opts[b'source'])
Martin von Zweigbergk
fix: don't include obsolete descendants with -s...
r46411 revs = set(repo.revs(b'(%ld::) - obsolete()', source_revs))
Martin von Zweigbergk
fix: add a -s option to format a revision and its descendants...
r45064 if wdirrev in source_revs:
# `wdir()::` is currently empty, so manually add wdir
revs.add(wdirrev)
if repo[b'.'].rev() in revs:
revs.add(wdirrev)
Martin von Zweigbergk
fix: move handling of --all into getrevstofix() for consistency...
r45063 else:
Martin von Zweigbergk
errors: raise InputError on bad revset to revrange() iff provided by the user...
r48928 revs = set(logcmdutil.revrange(repo, opts[b'rev']))
Martin von Zweigbergk
fix: move handling of --all into getrevstofix() for consistency...
r45063 if opts.get(b'working_dir'):
revs.add(wdirrev)
Martin von Zweigbergk
fix: refactor getrevstofix() to define revisions first, then validate them...
r45049 # Allow fixing only wdir() even if there's an unfinished operation
if not (len(revs) == 1 and wdirrev in revs):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 cmdutil.checkunfinished(repo)
Martin von Zweigbergk
fix: use rewriteutil.precheck() instead of reimplementing it...
r44388 rewriteutil.precheck(repo, revs, b'fix')
Augie Fackler
cleanup: use mergestate.unresolvedcount() instead of bool(list(unresolved()))...
r47070 if (
wdirrev in revs
and mergestatemod.mergestate.read(repo).unresolvedcount()
Augie Fackler
mergestate: split out merge state handling code from main merge module...
r45383 ):
Martin von Zweigbergk
fix: refactor getrevstofix() to define revisions first, then validate them...
r45049 raise error.Abort(b'unresolved conflicts', hint=b"use 'hg resolve'")
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if not revs:
raise error.Abort(
Martin von Zweigbergk
fix: suggest --source instead of --rev on empty revset...
r46409 b'no changesets specified', hint=b'use --source or --working-dir'
Augie Fackler
formatting: blacken the codebase...
r43346 )
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 return revs
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def pathstofix(ui, repo, pats, opts, match, basectxs, fixctx):
"""Returns the set of files that should be fixed in a context
The result depends on the base contexts; we include any file that has
changed relative to any of the base contexts. Base contexts should be
ancestors of the context being fixed.
"""
files = set()
for basectx in basectxs:
Augie Fackler
formatting: blacken the codebase...
r43346 stat = basectx.status(
fixctx, match=match, listclean=bool(pats), listunknown=bool(pats)
)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 files.update(
Augie Fackler
formatting: blacken the codebase...
r43346 set(
itertools.chain(
stat.added, stat.modified, stat.clean, stat.unknown
)
)
)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 return files
Augie Fackler
formatting: blacken the codebase...
r43346
Rodrigo Damazio Bovendorp
fix: obtain base paths before starting workers...
r45633 def lineranges(opts, path, basepaths, basectxs, fixctx, content2):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """Returns the set of line ranges that should be fixed in a file
Of the form [(10, 20), (30, 40)].
This depends on the given base contexts; we must consider lines that have
changed versus any of the base contexts, and whether the file has been
renamed versus any of them.
Another way to understand this is that we exclude line ranges that are
common to the file in all base contexts.
"""
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 if opts.get(b'whole'):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 # Return a range containing all lines. Rely on the diff implementation's
# idea of how many lines are in the file, instead of reimplementing it.
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 return difflineranges(b'', content2)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
rangeslist = []
for basectx in basectxs:
Rodrigo Damazio Bovendorp
fix: obtain base paths before starting workers...
r45633 basepath = basepaths.get((basectx.rev(), fixctx.rev(), path), path)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if basepath in basectx:
content1 = basectx[basepath].data()
else:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 content1 = b''
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 rangeslist.extend(difflineranges(content1, content2))
return unionranges(rangeslist)
Augie Fackler
formatting: blacken the codebase...
r43346
Rodrigo Damazio Bovendorp
fix: obtain base paths before starting workers...
r45633 def getbasepaths(repo, opts, workqueue, basectxs):
if opts.get(b'whole'):
# Base paths will never be fetched for line range determination.
return {}
basepaths = {}
Danny Hooper
fix: reduce number of tool executions...
r48992 for srcrev, path, _dstrevs in workqueue:
fixctx = repo[srcrev]
for basectx in basectxs[srcrev]:
Rodrigo Damazio Bovendorp
fix: obtain base paths before starting workers...
r45633 basepath = copies.pathcopies(basectx, fixctx).get(path, path)
if basepath in basectx:
basepaths[(basectx.rev(), fixctx.rev(), path)] = basepath
return basepaths
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def unionranges(rangeslist):
"""Return the union of some closed intervals
>>> unionranges([])
[]
>>> unionranges([(1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (2, 100)])
[(1, 100)]
>>> unionranges([(1, 99), (1, 100)])
[(1, 100)]
>>> unionranges([(1, 100), (40, 60)])
[(1, 100)]
>>> unionranges([(1, 49), (50, 100)])
[(1, 100)]
>>> unionranges([(1, 48), (50, 100)])
[(1, 48), (50, 100)]
>>> unionranges([(1, 2), (3, 4), (5, 6)])
[(1, 6)]
"""
rangeslist = sorted(set(rangeslist))
unioned = []
if rangeslist:
unioned, rangeslist = [rangeslist[0]], rangeslist[1:]
for a, b in rangeslist:
c, d = unioned[-1]
if a > d + 1:
unioned.append((a, b))
else:
unioned[-1] = (c, max(b, d))
return unioned
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def difflineranges(content1, content2):
"""Return list of line number ranges in content2 that differ from content1.
Line numbers are 1-based. The numbers are the first and last line contained
in the range. Single-line ranges have the same line number for the first and
last line. Excludes any empty ranges that result from lines that are only
present in content1. Relies on mdiff's idea of where the line endings are in
the string.
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> from mercurial import pycompat
>>> lines = lambda s: b'\\n'.join([c for c in pycompat.iterbytestr(s)])
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 >>> difflineranges2 = lambda a, b: difflineranges(lines(a), lines(b))
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'', b'')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 []
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'a', b'')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 []
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'', b'A')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 [(1, 1)]
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'a', b'a')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 []
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'a', b'A')
[(1, 1)]
>>> difflineranges2(b'ab', b'')
[]
>>> difflineranges2(b'', b'AB')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 [(1, 2)]
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'abc', b'ac')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 []
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'ab', b'aCb')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 [(2, 2)]
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'abc', b'aBc')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 [(2, 2)]
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'ab', b'AB')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 [(1, 2)]
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'abcde', b'aBcDe')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 [(2, 2), (4, 4)]
Yuya Nishihara
py3: fix fix doctests to be bytes-safe
r37230 >>> difflineranges2(b'abcde', b'aBCDe')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 [(2, 4)]
"""
ranges = []
for lines, kind in mdiff.allblocks(content1, content2):
firstline, lastline = lines[2:4]
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 if kind == b'!' and firstline != lastline:
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 ranges.append((firstline + 1, lastline))
return ranges
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def getbasectxs(repo, opts, revstofix):
"""Returns a map of the base contexts for each revision
The base contexts determine which lines are considered modified when we
Danny Hooper
fix: add test case that shows why --whole with --base is useful...
r38609 attempt to fix just the modified lines in a file. It also determines which
files we attempt to fix, so it is important to compute this even when
--whole is used.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """
# The --base flag overrides the usual logic, and we give every revision
# exactly the set of baserevs that the user specified.
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 if opts.get(b'base'):
Martin von Zweigbergk
errors: raise InputError on bad revset to revrange() iff provided by the user...
r48928 baserevs = set(logcmdutil.revrange(repo, opts.get(b'base')))
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if not baserevs:
baserevs = {nullrev}
basectxs = {repo[rev] for rev in baserevs}
return {rev: basectxs for rev in revstofix}
# Proceed in topological order so that we can easily determine each
# revision's baserevs by looking at its parents and their baserevs.
basectxs = collections.defaultdict(set)
for rev in sorted(revstofix):
ctx = repo[rev]
for pctx in ctx.parents():
if pctx.rev() in basectxs:
basectxs[rev].update(basectxs[pctx.rev()])
else:
basectxs[rev].add(pctx)
return basectxs
Augie Fackler
formatting: blacken the codebase...
r43346
Rodrigo Damazio Bovendorp
fix: prefetch file contents...
r45634 def _prefetchfiles(repo, workqueue, basepaths):
toprefetch = set()
# Prefetch the files that will be fixed.
Danny Hooper
fix: reduce number of tool executions...
r48992 for srcrev, path, _dstrevs in workqueue:
if srcrev == wdirrev:
Rodrigo Damazio Bovendorp
fix: prefetch file contents...
r45634 continue
Danny Hooper
fix: reduce number of tool executions...
r48992 toprefetch.add((srcrev, path))
Rodrigo Damazio Bovendorp
fix: prefetch file contents...
r45634
# Prefetch the base contents for lineranges().
for (baserev, fixrev, path), basepath in basepaths.items():
toprefetch.add((baserev, basepath))
if toprefetch:
scmutil.prefetchfiles(
repo,
[
(rev, scmutil.matchfiles(repo, [path]))
for rev, path in toprefetch
],
)
Rodrigo Damazio Bovendorp
fix: obtain base paths before starting workers...
r45633 def fixfile(ui, repo, opts, fixers, fixctx, path, basepaths, basectxs):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """Run any configured fixers that should affect the file in this context
Returns the file content that results from applying the fixers in some order
starting with the file's content in the fixctx. Fixers that support line
ranges will affect lines that have changed relative to any of the basectxs
(i.e. they will only avoid lines that are common to all basectxs).
Danny Hooper
fix: determine fixer tool failure by exit code instead of stderr...
r39003
A fixer tool's stdout will become the file's new content if and only if it
Danny Hooper
fix: run fixer tools in the repo root as cwd so they can use the working copy...
r42900 exits with code zero. The fixer tool's working directory is the repository's
root.
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 metadata = {}
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 newdata = fixctx[path].data()
Gregory Szorc
global: bulk replace simple pycompat.iteritems(x) with x.items()...
r49768 for fixername, fixer in fixers.items():
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if fixer.affects(opts, fixctx, path):
Rodrigo Damazio Bovendorp
fix: obtain base paths before starting workers...
r45633 ranges = lineranges(
opts, path, basepaths, basectxs, fixctx, newdata
)
Danny Hooper
fix: pass line ranges as value instead of callback...
r43003 command = fixer.command(ui, path, ranges)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if command is None:
continue
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 ui.debug(b'subprocess: %s\n' % (command,))
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 proc = subprocess.Popen(
Matt Harbison
py3: remove a couple of superfluous calls to pycompat.rapply()...
r39868 procutil.tonativestr(command),
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 shell=True,
Matt Harbison
py3: convert cwd to native string when running `fix`...
r43463 cwd=procutil.tonativestr(repo.root),
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
Augie Fackler
formatting: blacken the codebase...
r43346 stderr=subprocess.PIPE,
)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 stdout, stderr = proc.communicate(newdata)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if stderr:
showstderr(ui, fixctx.rev(), fixername, stderr)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 newerdata = stdout
if fixer.shouldoutputmetadata():
try:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 metadatajson, newerdata = stdout.split(b'\0', 1)
Gregory Szorc
py3: define and use json.loads polyfill...
r43697 metadata[fixername] = pycompat.json_loads(metadatajson)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 except ValueError:
Augie Fackler
formatting: blacken the codebase...
r43346 ui.warn(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b'ignored invalid output from fixer tool: %s\n')
Augie Fackler
formatting: blacken the codebase...
r43346 % (fixername,)
)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 continue
else:
metadata[fixername] = None
Danny Hooper
fix: determine fixer tool failure by exit code instead of stderr...
r39003 if proc.returncode == 0:
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 newdata = newerdata
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568 else:
if not stderr:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 message = _(b'exited with status %d\n') % (proc.returncode,)
Danny Hooper
fix: add a config to abort when a fixer tool fails...
r40568 showstderr(ui, fixctx.rev(), fixername, message)
checktoolfailureaction(
Augie Fackler
formatting: blacken the codebase...
r43346 ui,
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b'no fixes will be applied'),
Augie Fackler
formatting: blacken the codebase...
r43346 hint=_(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 b'use --config fix.failure=continue to apply any '
b'successful fixes anyway'
Augie Fackler
formatting: blacken the codebase...
r43346 ),
)
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 return metadata, newdata
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def showstderr(ui, rev, fixername, stderr):
"""Writes the lines of the stderr string as warnings on the ui
Uses the revision number and fixername to give more context to each line of
the error message. Doesn't include file names, since those take up a lot of
space and would tend to be included in the error message if they were
relevant.
"""
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 for line in re.split(b'[\r\n]+', stderr):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if line:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 ui.warn(b'[')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if rev is None:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 ui.warn(_(b'wdir'), label=b'evolve.rev')
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 else:
Martin von Zweigbergk
fix: replace str() by b'%d' for formatting integer...
r43807 ui.warn(b'%d' % rev, label=b'evolve.rev')
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 ui.warn(b'] %s: %s\n' % (fixername, line))
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
def writeworkingdir(repo, ctx, filedata, replacements):
"""Write new content to the working copy and check out the new p1 if any
We check out a new revision if and only if we fixed something in both the
working directory and its parent revision. This avoids the need for a full
update/merge, and means that the working directory simply isn't affected
unless the --working-dir flag is given.
Directly updates the dirstate for the affected files.
"""
Gregory Szorc
global: bulk replace simple pycompat.iteritems(x) with x.items()...
r49768 for path, data in filedata.items():
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 fctx = ctx[path]
fctx.write(data, fctx.flags())
Martin von Zweigbergk
fix: rewrite writeworkingdir() to explicitly not work with merges...
r48566 oldp1 = repo.dirstate.p1()
newp1 = replacements.get(oldp1, oldp1)
if newp1 != oldp1:
Martin von Zweigbergk
fix: again allow formatting the working copy while merging...
r48730 assert repo.dirstate.p2() == nullid
Martin von Zweigbergk
fix: use scmutil.movedirstate() instead of reimplementing...
r48567 with repo.dirstate.parentchange():
scmutil.movedirstate(repo, repo[newp1])
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def replacerev(ui, repo, ctx, filedata, replacements):
"""Commit a new revision like the given one, but with file content changes
"ctx" is the original revision to be replaced by a modified one.
"filedata" is a dict that maps paths to their new file content. All other
paths will be recreated from the original revision without changes.
"filedata" may contain paths that didn't exist in the original revision;
they will be added.
"replacements" is a dict that maps a single node to a single node, and it is
updated to indicate the original revision is replaced by the newly created
one. No entry is added if the replacement's node already exists.
The new revision has the same parents as the old one, unless those parents
have already been replaced, in which case those replacements are the parents
of this new revision. Thus, if revisions are replaced in topological order,
there is no need to rebase them into the original topology later.
"""
p1rev, p2rev = repo.changelog.parentrevs(ctx.rev())
p1ctx, p2ctx = repo[p1rev], repo[p2rev]
newp1node = replacements.get(p1ctx.node(), p1ctx.node())
newp2node = replacements.get(p2ctx.node(), p2ctx.node())
Danny Hooper
fix: add extra field to fixed revisions to avoid creating obsolescence cycles...
r40604 # We don't want to create a revision that has no changes from the original,
# but we should if the original revision's parent has been replaced.
# Otherwise, we would produce an orphan that needs no actual human
# intervention to evolve. We can't rely on commit() to avoid creating the
# un-needed revision because the extra field added below produces a new hash
# regardless of file content changes.
Augie Fackler
formatting: blacken the codebase...
r43346 if (
not filedata
and p1ctx.node() not in replacements
and p2ctx.node() not in replacements
):
Danny Hooper
fix: add extra field to fixed revisions to avoid creating obsolescence cycles...
r40604 return
extra = ctx.extra().copy()
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 extra[b'fix_source'] = ctx.hex()
Danny Hooper
fix: add extra field to fixed revisions to avoid creating obsolescence cycles...
r40604
Kyle Lippincott
fix: fix handling of merge commits by using overlayworkingctx...
r44414 wctx = context.overlayworkingctx(repo)
Martin von Zweigbergk
graftcopies: remove `skip` and `repo` arguments...
r44551 wctx.setbase(repo[newp1node])
Martin von Zweigbergk
merge: introduce a revert_to() for that use-case...
r44744 merge.revert_to(ctx, wc=wctx)
Martin von Zweigbergk
graftcopies: remove `skip` and `repo` arguments...
r44551 copies.graftcopies(wctx, ctx, ctx.p1())
Kyle Lippincott
fix: fix handling of merge commits by using overlayworkingctx...
r44414
for path in filedata.keys():
fctx = ctx[path]
copysource = fctx.copysource()
wctx.write(path, filedata[path], flags=fctx.flags())
if copysource:
wctx.markcopied(path, copysource)
Matt Harbison
fix: update commit hash references in the new commits...
r46305 desc = rewriteutil.update_hash_refs(
repo,
ctx.description(),
{oldnode: [newnode] for oldnode, newnode in replacements.items()},
)
Kyle Lippincott
fix: fix handling of merge commits by using overlayworkingctx...
r44414 memctx = wctx.tomemctx(
Matt Harbison
fix: update commit hash references in the new commits...
r46305 text=desc,
Kyle Lippincott
fix: fix handling of merge commits by using overlayworkingctx...
r44414 branch=ctx.branch(),
extra=extra,
Martin von Zweigbergk
scmutil: make cleanupnodes optionally also fix the phase...
r38442 date=ctx.date(),
Kyle Lippincott
fix: fix handling of merge commits by using overlayworkingctx...
r44414 parents=(newp1node, newp2node),
user=ctx.user(),
Augie Fackler
formatting: blacken the codebase...
r43346 )
Kyle Lippincott
fix: fix handling of merge commits by using overlayworkingctx...
r44414
Martin von Zweigbergk
scmutil: make cleanupnodes optionally also fix the phase...
r38442 sucnode = memctx.commit()
prenode = ctx.node()
if prenode == sucnode:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 ui.debug(b'node %s already existed\n' % (ctx.hex()))
Martin von Zweigbergk
scmutil: make cleanupnodes optionally also fix the phase...
r38442 else:
replacements[ctx.node()] = sucnode
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Augie Fackler
formatting: blacken the codebase...
r43346
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def getfixers(ui):
"""Returns a map of configured fixer tools indexed by their names
Each value is a Fixer object with methods that implement the behavior of the
fixer's config suboptions. Does not validate the config values.
"""
Danny Hooper
fix: add suboption for configuring execution order of tools...
r40599 fixers = {}
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 for name in fixernames(ui):
Martin von Zweigbergk
fix: make Fixer initialization more explicit for clarity...
r43493 enabled = ui.configbool(b'fix', name + b':enabled')
command = ui.config(b'fix', name + b':command')
pattern = ui.config(b'fix', name + b':pattern')
linerange = ui.config(b'fix', name + b':linerange')
priority = ui.configint(b'fix', name + b':priority')
metadata = ui.configbool(b'fix', name + b':metadata')
skipclean = ui.configbool(b'fix', name + b':skipclean')
Danny Hooper
fix: ignore fixer tool configurations that are missing patterns...
r42882 # Don't use a fixer if it has no pattern configured. It would be
# dangerous to let it affect all files. It would be pointless to let it
# affect no files. There is no reasonable subset of files to use as the
# default.
Martin von Zweigbergk
fix: warn when a fixer doesn't have a configured command...
r43494 if command is None:
ui.warn(
_(b'fixer tool has no command configuration: %s\n') % (name,)
)
elif pattern is None:
Danny Hooper
fix: ignore fixer tool configurations that are missing patterns...
r42882 ui.warn(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 _(b'fixer tool has no pattern configuration: %s\n') % (name,)
Augie Fackler
formatting: blacken the codebase...
r43346 )
Martin von Zweigbergk
fix: make Fixer initialization more explicit for clarity...
r43493 elif not enabled:
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 ui.debug(b'ignoring disabled fixer tool: %s\n' % (name,))
Martin von Zweigbergk
fix: make Fixer initialization more explicit for clarity...
r43493 else:
fixers[name] = Fixer(
command, pattern, linerange, priority, metadata, skipclean
)
Danny Hooper
fix: add suboption for configuring execution order of tools...
r40599 return collections.OrderedDict(
Augie Fackler
formatting: blacken the codebase...
r43346 sorted(fixers.items(), key=lambda item: item[1]._priority, reverse=True)
)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
def fixernames(ui):
"""Returns the names of [fix] config options that have suboptions"""
names = set()
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 for k, v in ui.configitems(b'fix'):
if b':' in k:
names.add(k.split(b':', 1)[0])
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 return names
Augie Fackler
formatting: blacken the codebase...
r43346
Gregory Szorc
py3: use class X: instead of class X(object):...
r49801 class Fixer:
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """Wraps the raw config values for a fixer with methods"""
Martin von Zweigbergk
fix: make Fixer initialization more explicit for clarity...
r43493 def __init__(
self, command, pattern, linerange, priority, metadata, skipclean
):
self._command = command
self._pattern = pattern
self._linerange = linerange
self._priority = priority
self._metadata = metadata
self._skipclean = skipclean
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 def affects(self, opts, fixctx, path):
"""Should this fixer run on the file at the given path and context?"""
Martin von Zweigbergk
fix: match patterns relative to root...
r43501 repo = fixctx.repo()
matcher = matchmod.match(
repo.root, repo.root, [self._pattern], ctx=fixctx
)
return matcher(path)
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200
Danny Hooper
fix: allow fixer tools to return metadata in addition to the file content...
r42372 def shouldoutputmetadata(self):
"""Should the stdout of this fixer start with JSON and a null byte?"""
return self._metadata
Danny Hooper
fix: pass line ranges as value instead of callback...
r43003 def command(self, ui, path, ranges):
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 """A shell command to use to invoke this fixer on the given file/lines
May return None if there is no appropriate command to run for the given
parameters.
"""
Yuya Nishihara
fix: use templater to substitute values in command string...
r37792 expand = cmdutil.rendercommandtemplate
Augie Fackler
formatting: blacken the codebase...
r43346 parts = [
expand(
ui,
self._command,
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 {b'rootpath': path, b'basename': os.path.basename(path)},
Augie Fackler
formatting: blacken the codebase...
r43346 )
]
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 if self._linerange:
Danny Hooper
fix: allow tools to use :linerange, but also run if a file is unchanged...
r43001 if self._skipclean and not ranges:
Danny Hooper
fix: new extension for automatically modifying file contents...
r37200 # No line ranges to fix, so don't run the fixer.
return None
for first, last in ranges:
Augie Fackler
formatting: blacken the codebase...
r43346 parts.append(
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 expand(
ui, self._linerange, {b'first': first, b'last': last}
)
Augie Fackler
formatting: blacken the codebase...
r43346 )
Augie Fackler
formatting: byteify all mercurial/ and hgext/ string literals...
r43347 return b' '.join(parts)