Debian Codegraph @

hgext/fix.py

raw
1 # fix - rewrite file content in changesets and working copy
2 #
3 # Copyright 2018 Google LLC.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7 """rewrite file content in changesets or working copy (EXPERIMENTAL)
8
9 Provides a command that runs configured tools on the contents of modified files,
10 writing back any fixes to the working copy or replacing changesets.
11
12 Fixer tools are run in the repository's root directory. This allows them to read
13 configuration files from the working copy, or even write to the working copy.
14 The working copy is not updated to match the revision being fixed. In fact,
15 several revisions may be fixed in parallel. Writes to the working copy are not
16 amended into the revision being fixed; fixer tools MUST always read content to
17 be fixed from stdin, and write fixed file content back to stdout.
18
19 Here is an example configuration that causes :hg:`fix` to apply automatic
20 formatting fixes to modified lines in C++ code::
21
22 [fix]
23 clang-format:command=clang-format --assume-filename={rootpath}
24 clang-format:linerange=--lines={first}:{last}
25 clang-format:pattern=set:**.cpp or **.hpp
26
27 The :command suboption forms the first part of the shell command that will be
28 used to fix a file. The content of the file is passed on standard input, and the
29 fixed file content is expected on standard output. Any output on standard error
30 will be displayed as a warning. If the exit status is not zero, the file will
31 not be affected. A placeholder warning is displayed if there is a non-zero exit
32 status but no standard error output. Some values may be substituted into the
33 command::
34
35 {rootpath} The path of the file being fixed, relative to the repo root
36 {basename} The name of the file being fixed, without the directory path
37
38 If the :linerange suboption is set, the tool will only be run if there are
39 changed lines in a file. The value of this suboption is appended to the shell
40 command once for every range of changed lines in the file. Some values may be
41 substituted into the command::
42
43 {first} The 1-based line number of the first line in the modified range
44 {last} The 1-based line number of the last line in the modified range
45
46 Deleted sections of a file will be ignored by :linerange, because there is no
47 corresponding line range in the version being fixed.
48
49 By default, tools that set :linerange will only be executed if there is at least
50 one changed line range. This is meant to prevent accidents like running a code
51 formatter in such a way that it unexpectedly reformats the whole file. If such a
52 tool needs to operate on unchanged files, it should set the :skipclean suboption
53 to false.
54
55 The :pattern suboption determines which files will be passed through each
56 configured tool. See :hg:`help patterns` for possible values. However, all
57 patterns are relative to the repo root, even if that text says they are relative
58 to the current working directory. If there are file arguments to :hg:`fix`, the
59 intersection of these patterns is used.
60
61 There is also a configurable limit for the maximum size of file that will be
62 processed by :hg:`fix`::
63
64 [fix]
65 maxfilesize = 2MB
66
67 Normally, execution of configured tools will continue after a failure (indicated
68 by a non-zero exit status). It can also be configured to abort after the first
69 such failure, so that no files will be affected if any tool fails. This abort
70 will also cause :hg:`fix` to exit with a non-zero status::
71
72 [fix]
73 failure = abort
74
75 When multiple tools are configured to affect a file, they execute in an order
76 defined by the :priority suboption. The priority suboption has a default value
77 of zero for each tool. Tools are executed in order of descending priority. The
78 execution order of tools with equal priority is unspecified. For example, you
79 could use the 'sort' and 'head' utilities to keep only the 10 smallest numbers
80 in a text file by ensuring that 'sort' runs before 'head'::
81
82 [fix]
83 sort:command = sort -n
84 head:command = head -n 10
85 sort:pattern = numbers.txt
86 head:pattern = numbers.txt
87 sort:priority = 2
88 head:priority = 1
89
90 To account for changes made by each tool, the line numbers used for incremental
91 formatting are recomputed before executing the next tool. So, each tool may see
92 different values for the arguments added by the :linerange suboption.
93
94 Each fixer tool is allowed to return some metadata in addition to the fixed file
95 content. The metadata must be placed before the file content on stdout,
96 separated from the file content by a zero byte. The metadata is parsed as a JSON
97 value (so, it should be UTF-8 encoded and contain no zero bytes). A fixer tool
98 is expected to produce this metadata encoding if and only if the :metadata
99 suboption is true::
100
101 [fix]
102 tool:command = tool --prepend-json-metadata
103 tool:metadata = true
104
105 The metadata values are passed to hooks, which can be used to print summaries or
106 perform other post-fixing work. The supported hooks are::
107
108 "postfixfile"
109 Run once for each file in each revision where any fixer tools made changes
110 to the file content. Provides "$HG_REV" and "$HG_PATH" to identify the file,
111 and "$HG_METADATA" with a map of fixer names to metadata values from fixer
112 tools that affected the file. Fixer tools that didn't affect the file have a
113 value of None. Only fixer tools that executed are present in the metadata.
114
115 "postfix"
116 Run once after all files and revisions have been handled. Provides
117 "$HG_REPLACEMENTS" with information about what revisions were created and
118 made obsolete. Provides a boolean "$HG_WDIRWRITTEN" to indicate whether any
119 files in the working copy were updated. Provides a list "$HG_METADATA"
120 mapping fixer tool names to lists of metadata values returned from
121 executions that modified a file. This aggregates the same metadata
122 previously passed to the "postfixfile" hook.
123
124 You can specify a list of directories to search the tool command in using the
125 `fix.extra-bin-paths` configuration.
126 """
127
128 from __future__ import annotations
129
130 import collections
131 import itertools
132 import os
133 import re
134 import subprocess
135 import sys
136
137 from mercurial.i18n import _
138 from mercurial.node import (
139 nullid,
140 nullrev,
141 wdirrev,
142 )
143
144 from mercurial.utils import procutil
145
146 from mercurial import (
147 cmdutil,
148 context,
149 copies,
150 encoding,
151 error,
152 logcmdutil,
153 match as matchmod,
154 mdiff,
155 merge,
156 mergestate as mergestatemod,
157 pycompat,
158 registrar,
159 rewriteutil,
160 scmutil,
161 util,
162 worker,
163 )
164
165 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
166 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
167 # be specifying the version(s) of Mercurial they are tested with, or
168 # leave the attribute unspecified.
169 testedwith = b'ships-with-hg-core'
170
171 cmdtable = {}
172 command = registrar.command(cmdtable)
173
174 configtable = {}
175 configitem = registrar.configitem(configtable)
176
177 # Register the suboptions allowed for each configured fixer, and default values.
178 FIXER_ATTRS = {
179 b'command': None,
180 b'linerange': None,
181 b'pattern': None,
182 b'priority': 0,
183 b'metadata': False,
184 b'skipclean': True,
185 b'enabled': True,
186 }
187
188 for key, default in FIXER_ATTRS.items():
189 configitem(b'fix', b'.*:%s$' % key, default=default, generic=True)
190
191 # A good default size allows most source code files to be fixed, but avoids
192 # letting fixer tools choke on huge inputs, which could be surprising to the
193 # user.
194 configitem(b'fix', b'maxfilesize', default=b'2MB')
195
196 # Allow fix commands to exit non-zero if an executed fixer tool exits non-zero.
197 # This helps users do shell scripts that stop when a fixer tool signals a
198 # problem.
199 configitem(b'fix', b'failure', default=b'continue')
200
201 configitem(b'fix', b'extra-bin-paths', default=list)
202
203
204 def checktoolfailureaction(ui, message, hint=None):
205 """Abort with 'message' if fix.failure=abort"""
206 action = ui.config(b'fix', b'failure')
207 if action not in (b'continue', b'abort'):
208 raise error.Abort(
209 _(b'unknown fix.failure action: %s') % (action,),
210 hint=_(b'use "continue" or "abort"'),
211 )
212 if action == b'abort':
213 raise error.Abort(message, hint=hint)
214
215
216 allopt = (b'', b'all', False, _(b'fix all non-public non-obsolete revisions'))
217 baseopt = (
218 b'',
219 b'base',
220 [],
221 _(
222 b'revisions to diff against (overrides automatic '
223 b'selection, and applies to every revision being '
224 b'fixed)'
225 ),
226 _(b'REV'),
227 )
228 revopt = (b'r', b'rev', [], _(b'revisions to fix (ADVANCED)'), _(b'REV'))
229 sourceopt = (
230 b's',
231 b'source',
232 [],
233 _(b'fix the specified revisions and their descendants'),
234 _(b'REV'),
235 )
236 wdiropt = (b'w', b'working-dir', False, _(b'fix the working directory'))
237 wholeopt = (b'', b'whole', False, _(b'always fix every line of a file'))
238 usage = _(b'[OPTION]... [FILE]...')
239
240
241 @command(
242 b'fix',
243 [allopt, baseopt, revopt, sourceopt, wdiropt, wholeopt],
244 usage,
245 helpcategory=command.CATEGORY_FILE_CONTENTS,
246 )
247 def fix(ui, repo, *pats, **opts):
248 """rewrite file content in changesets or working directory
249
250 Runs any configured tools to fix the content of files. (See
251 :hg:`help -e fix` for details about configuring tools.) Only affects files
252 with changes, unless file arguments are provided. Only affects changed lines
253 of files, unless the --whole flag is used. Some tools may always affect the
254 whole file regardless of --whole.
255
256 If --working-dir is used, files with uncommitted changes in the working copy
257 will be fixed. Note that no backup are made.
258
259 If revisions are specified with --source, those revisions and their
260 descendants will be checked, and they may be replaced with new revisions
261 that have fixed file content. By automatically including the descendants,
262 no merging, rebasing, or evolution will be required. If an ancestor of the
263 working copy is included, then the working copy itself will also be fixed,
264 and the working copy will be updated to the fixed parent.
265
266 When determining what lines of each file to fix at each revision, the whole
267 set of revisions being fixed is considered, so that fixes to earlier
268 revisions are not forgotten in later ones. The --base flag can be used to
269 override this default behavior, though it is not usually desirable to do so.
270 """
271 opts = pycompat.byteskwargs(opts)
272 cmdutil.check_at_most_one_arg(opts, b'all', b'source', b'rev')
273 cmdutil.check_incompatible_arguments(
274 opts, b'working_dir', [b'all', b'source']
275 )
276
277 with repo.wlock(), repo.lock(), repo.transaction(b'fix'):
278 revstofix = getrevstofix(ui, repo, opts)
279 basectxs = getbasectxs(repo, opts, revstofix)
280 workqueue, numitems = getworkqueue(
281 ui, repo, pats, opts, revstofix, basectxs
282 )
283 basepaths = getbasepaths(repo, opts, workqueue, basectxs)
284 fixers = getfixers(ui)
285
286 # Rather than letting each worker independently fetch the files
287 # (which also would add complications for shared/keepalive
288 # connections), prefetch them all first.
289 _prefetchfiles(repo, workqueue, basepaths)
290
291 # There are no data dependencies between the workers fixing each file
292 # revision, so we can use all available parallelism.
293 def getfixes(items):
294 for srcrev, path, dstrevs in items:
295 ctx = repo[srcrev]
296 olddata = ctx[path].data()
297 metadata, newdata = fixfile(
298 ui,
299 repo,
300 opts,
301 fixers,
302 ctx,
303 path,
304 basepaths,
305 basectxs[srcrev],
306 )
307 # We ungroup the work items now, because the code that consumes
308 # these results has to handle each dstrev separately, and in
309 # topological order. Because these are handled in topological
310 # order, it's important that we pass around references to
311 # "newdata" instead of copying it. Otherwise, we would be
312 # keeping more copies of file content in memory at a time than
313 # if we hadn't bothered to group/deduplicate the work items.
314 data = newdata if newdata != olddata else None
315 for dstrev in dstrevs:
316 yield (dstrev, path, metadata, data)
317
318 results = worker.worker(
319 ui, 1.0, getfixes, tuple(), workqueue, threadsafe=False
320 )
321
322 # We have to hold on to the data for each successor revision in memory
323 # until all its parents are committed. We ensure this by committing and
324 # freeing memory for the revisions in some topological order. This
325 # leaves a little bit of memory efficiency on the table, but also makes
326 # the tests deterministic. It might also be considered a feature since
327 # it makes the results more easily reproducible.
328 filedata = collections.defaultdict(dict)
329 aggregatemetadata = collections.defaultdict(list)
330 replacements = {}
331 wdirwritten = False
332 commitorder = sorted(revstofix, reverse=True)
333 with ui.makeprogress(
334 topic=_(b'fixing'), unit=_(b'files'), total=sum(numitems.values())
335 ) as progress:
336 for rev, path, filerevmetadata, newdata in results:
337 progress.increment(item=path)
338 for fixername, fixermetadata in filerevmetadata.items():
339 aggregatemetadata[fixername].append(fixermetadata)
340 if newdata is not None:
341 filedata[rev][path] = newdata
342 hookargs = {
343 b'rev': rev,
344 b'path': path,
345 b'metadata': filerevmetadata,
346 }
347 repo.hook(
348 b'postfixfile',
349 throw=False,
350 **pycompat.strkwargs(hookargs),
351 )
352 numitems[rev] -= 1
353 # Apply the fixes for this and any other revisions that are
354 # ready and sitting at the front of the queue. Using a loop here
355 # prevents the queue from being blocked by the first revision to
356 # be ready out of order.
357 while commitorder and not numitems[commitorder[-1]]:
358 rev = commitorder.pop()
359 ctx = repo[rev]
360 if rev == wdirrev:
361 writeworkingdir(repo, ctx, filedata[rev], replacements)
362 wdirwritten = bool(filedata[rev])
363 else:
364 replacerev(ui, repo, ctx, filedata[rev], replacements)
365 del filedata[rev]
366
367 cleanup(repo, replacements, wdirwritten)
368 hookargs = {
369 b'replacements': replacements,
370 b'wdirwritten': wdirwritten,
371 b'metadata': aggregatemetadata,
372 }
373 repo.hook(b'postfix', throw=True, **pycompat.strkwargs(hookargs))
374
375
376 def cleanup(repo, replacements, wdirwritten):
377 """Calls cmdutil.cleanup_nodes() with the given replacements.
378
379 "replacements" is a dict from nodeid to nodeid, with one key and one value
380 for every revision that was affected by fixing. This is slightly different
381 from cleanupnodes().
382
383 "wdirwritten" is a bool which tells whether the working copy was affected by
384 fixing, since it has no entry in "replacements".
385
386 Useful as a hook point for extending "hg fix" with output summarizing the
387 effects of the command, though we choose not to output anything here.
388 """
389 replacements = {prec: [succ] for prec, succ in replacements.items()}
390 cmdutil.cleanup_nodes(repo, replacements, b'fix', fixphase=True)
391
392
393 def getworkqueue(ui, repo, pats, opts, revstofix, basectxs):
394 """Constructs a list of files to fix and which revisions each fix applies to
395
396 To avoid duplicating work, there is usually only one work item for each file
397 revision that might need to be fixed. There can be multiple work items per
398 file revision if the same file needs to be fixed in multiple changesets with
399 different baserevs. Each work item also contains a list of changesets where
400 the file's data should be replaced with the fixed data. The work items for
401 earlier changesets come earlier in the work queue, to improve pipelining by
402 allowing the first changeset to be replaced while fixes are still being
403 computed for later changesets.
404
405 Also returned is a map from changesets to the count of work items that might
406 affect each changeset. This is used later to count when all of a changeset's
407 work items have been finished, without having to inspect the remaining work
408 queue in each worker subprocess.
409
410 The example work item (1, "foo/bar.txt", (1, 2, 3)) means that the data of
411 bar.txt should be read from revision 1, then fixed, and written back to
412 revisions 1, 2 and 3. Revision 1 is called the "srcrev" and the list of
413 revisions is called the "dstrevs". In practice the srcrev is always one of
414 the dstrevs, and we make that choice when constructing the work item so that
415 the choice can't be made inconsistently later on. The dstrevs should all
416 have the same file revision for the given path, so the choice of srcrev is
417 arbitrary. The wdirrev can be a dstrev and a srcrev.
418 """
419 dstrevmap = collections.defaultdict(list)
420 numitems = collections.defaultdict(int)
421 maxfilesize = ui.configbytes(b'fix', b'maxfilesize')
422 for rev in sorted(revstofix):
423 fixctx = repo[rev]
424 match = scmutil.match(fixctx, pats, opts)
425 for path in sorted(
426 pathstofix(ui, repo, pats, opts, match, basectxs[rev], fixctx)
427 ):
428 fctx = fixctx[path]
429 if fctx.islink():
430 continue
431 if fctx.size() > maxfilesize:
432 ui.warn(
433 _(b'ignoring file larger than %s: %s\n')
434 % (util.bytecount(maxfilesize), path)
435 )
436 continue
437 baserevs = tuple(ctx.rev() for ctx in basectxs[rev])
438 dstrevmap[(fctx.filerev(), baserevs, path)].append(rev)
439 numitems[rev] += 1
440 workqueue = [
441 (min(dstrevs), path, dstrevs)
442 for (_filerev, _baserevs, path), dstrevs in dstrevmap.items()
443 ]
444 # Move work items for earlier changesets to the front of the queue, so we
445 # might be able to replace those changesets (in topological order) while
446 # we're still processing later work items. Note the min() in the previous
447 # expression, which means we don't need a custom comparator here. The path
448 # is also important in the sort order to make the output order stable. There
449 # are some situations where this doesn't help much, but some situations
450 # where it lets us buffer O(1) files instead of O(n) files.
451 workqueue.sort()
452 return workqueue, numitems
453
454
455 def getrevstofix(ui, repo, opts):
456 """Returns the set of revision numbers that should be fixed"""
457 if opts[b'all']:
458 revs = repo.revs(b'(not public() and not obsolete()) or wdir()')
459 elif opts[b'source']:
460 source_revs = logcmdutil.revrange(repo, opts[b'source'])
461 revs = set(repo.revs(b'(%ld::) - obsolete()', source_revs))
462 if wdirrev in source_revs:
463 # `wdir()::` is currently empty, so manually add wdir
464 revs.add(wdirrev)
465 if repo[b'.'].rev() in revs:
466 revs.add(wdirrev)
467 else:
468 revs = set(logcmdutil.revrange(repo, opts[b'rev']))
469 if opts.get(b'working_dir'):
470 revs.add(wdirrev)
471 # Allow fixing only wdir() even if there's an unfinished operation
472 if not (len(revs) == 1 and wdirrev in revs):
473 cmdutil.checkunfinished(repo)
474 rewriteutil.precheck(repo, revs, b'fix')
475 if (
476 wdirrev in revs
477 and mergestatemod.mergestate.read(repo).unresolvedcount()
478 ):
479 raise error.Abort(b'unresolved conflicts', hint=b"use 'hg resolve'")
480 if not revs:
481 raise error.Abort(
482 b'no changesets specified', hint=b'use --source or --working-dir'
483 )
484 return revs
485
486
487 def pathstofix(ui, repo, pats, opts, match, basectxs, fixctx):
488 """Returns the set of files that should be fixed in a context
489
490 The result depends on the base contexts; we include any file that has
491 changed relative to any of the base contexts. Base contexts should be
492 ancestors of the context being fixed.
493 """
494 files = set()
495 for basectx in basectxs:
496 stat = basectx.status(
497 fixctx, match=match, listclean=bool(pats), listunknown=bool(pats)
498 )
499 files.update(
500 set(
501 itertools.chain(
502 stat.added, stat.modified, stat.clean, stat.unknown
503 )
504 )
505 )
506 return files
507
508
509 def lineranges(opts, path, basepaths, basectxs, fixctx, content2):
510 """Returns the set of line ranges that should be fixed in a file
511
512 Of the form [(10, 20), (30, 40)].
513
514 This depends on the given base contexts; we must consider lines that have
515 changed versus any of the base contexts, and whether the file has been
516 renamed versus any of them.
517
518 Another way to understand this is that we exclude line ranges that are
519 common to the file in all base contexts.
520 """
521 if opts.get(b'whole'):
522 # Return a range containing all lines. Rely on the diff implementation's
523 # idea of how many lines are in the file, instead of reimplementing it.
524 return difflineranges(b'', content2)
525
526 rangeslist = []
527 for basectx in basectxs:
528 basepath = basepaths.get((basectx.rev(), fixctx.rev(), path), path)
529
530 if basepath in basectx:
531 content1 = basectx[basepath].data()
532 else:
533 content1 = b''
534 rangeslist.extend(difflineranges(content1, content2))
535 return unionranges(rangeslist)
536
537
538 def getbasepaths(repo, opts, workqueue, basectxs):
539 if opts.get(b'whole'):
540 # Base paths will never be fetched for line range determination.
541 return {}
542
543 basepaths = {}
544 for srcrev, path, _dstrevs in workqueue:
545 fixctx = repo[srcrev]
546 for basectx in basectxs[srcrev]:
547 basepath = copies.pathcopies(basectx, fixctx).get(path, path)
548 if basepath in basectx:
549 basepaths[(basectx.rev(), fixctx.rev(), path)] = basepath
550 return basepaths
551
552
553 def unionranges(rangeslist):
554 """Return the union of some closed intervals
555
556 >>> unionranges([])
557 []
558 >>> unionranges([(1, 100)])
559 [(1, 100)]
560 >>> unionranges([(1, 100), (1, 100)])
561 [(1, 100)]
562 >>> unionranges([(1, 100), (2, 100)])
563 [(1, 100)]
564 >>> unionranges([(1, 99), (1, 100)])
565 [(1, 100)]
566 >>> unionranges([(1, 100), (40, 60)])
567 [(1, 100)]
568 >>> unionranges([(1, 49), (50, 100)])
569 [(1, 100)]
570 >>> unionranges([(1, 48), (50, 100)])
571 [(1, 48), (50, 100)]
572 >>> unionranges([(1, 2), (3, 4), (5, 6)])
573 [(1, 6)]
574 """
575 rangeslist = sorted(set(rangeslist))
576 unioned = []
577 if rangeslist:
578 unioned, rangeslist = [rangeslist[0]], rangeslist[1:]
579 for a, b in rangeslist:
580 c, d = unioned[-1]
581 if a > d + 1:
582 unioned.append((a, b))
583 else:
584 unioned[-1] = (c, max(b, d))
585 return unioned
586
587
588 def difflineranges(content1, content2):
589 """Return list of line number ranges in content2 that differ from content1.
590
591 Line numbers are 1-based. The numbers are the first and last line contained
592 in the range. Single-line ranges have the same line number for the first and
593 last line. Excludes any empty ranges that result from lines that are only
594 present in content1. Relies on mdiff's idea of where the line endings are in
595 the string.
596
597 >>> from mercurial import pycompat
598 >>> lines = lambda s: b'\\n'.join([c for c in pycompat.iterbytestr(s)])
599 >>> difflineranges2 = lambda a, b: difflineranges(lines(a), lines(b))
600 >>> difflineranges2(b'', b'')
601 []
602 >>> difflineranges2(b'a', b'')
603 []
604 >>> difflineranges2(b'', b'A')
605 [(1, 1)]
606 >>> difflineranges2(b'a', b'a')
607 []
608 >>> difflineranges2(b'a', b'A')
609 [(1, 1)]
610 >>> difflineranges2(b'ab', b'')
611 []
612 >>> difflineranges2(b'', b'AB')
613 [(1, 2)]
614 >>> difflineranges2(b'abc', b'ac')
615 []
616 >>> difflineranges2(b'ab', b'aCb')
617 [(2, 2)]
618 >>> difflineranges2(b'abc', b'aBc')
619 [(2, 2)]
620 >>> difflineranges2(b'ab', b'AB')
621 [(1, 2)]
622 >>> difflineranges2(b'abcde', b'aBcDe')
623 [(2, 2), (4, 4)]
624 >>> difflineranges2(b'abcde', b'aBCDe')
625 [(2, 4)]
626 """
627 ranges = []
628 for lines, kind in mdiff.allblocks(content1, content2):
629 firstline, lastline = lines[2:4]
630 if kind == b'!' and firstline != lastline:
631 ranges.append((firstline + 1, lastline))
632 return ranges
633
634
635 def getbasectxs(repo, opts, revstofix):
636 """Returns a map of the base contexts for each revision
637
638 The base contexts determine which lines are considered modified when we
639 attempt to fix just the modified lines in a file. It also determines which
640 files we attempt to fix, so it is important to compute this even when
641 --whole is used.
642 """
643 # The --base flag overrides the usual logic, and we give every revision
644 # exactly the set of baserevs that the user specified.
645 if opts.get(b'base'):
646 baserevs = set(logcmdutil.revrange(repo, opts.get(b'base')))
647 if not baserevs:
648 baserevs = {nullrev}
649 basectxs = {repo[rev] for rev in baserevs}
650 return {rev: basectxs for rev in revstofix}
651
652 # Proceed in topological order so that we can easily determine each
653 # revision's baserevs by looking at its parents and their baserevs.
654 basectxs = collections.defaultdict(set)
655 for rev in sorted(revstofix):
656 ctx = repo[rev]
657 for pctx in ctx.parents():
658 if pctx.rev() in basectxs:
659 basectxs[rev].update(basectxs[pctx.rev()])
660 else:
661 basectxs[rev].add(pctx)
662 return basectxs
663
664
665 def _prefetchfiles(repo, workqueue, basepaths):
666 toprefetch = set()
667
668 # Prefetch the files that will be fixed.
669 for srcrev, path, _dstrevs in workqueue:
670 if srcrev == wdirrev:
671 continue
672 toprefetch.add((srcrev, path))
673
674 # Prefetch the base contents for lineranges().
675 for (baserev, fixrev, path), basepath in basepaths.items():
676 toprefetch.add((baserev, basepath))
677
678 if toprefetch:
679 scmutil.prefetchfiles(
680 repo,
681 [
682 (rev, scmutil.matchfiles(repo, [path]))
683 for rev, path in toprefetch
684 ],
685 )
686
687
688 def _augmented_env(wvfs, extra_paths):
689 if os.supports_bytes_environ:
690 env = encoding.environ.copy()
691 raw_path = env.get(b'PATH', b'')
692 extra_paths = [wvfs.join(i) for i in extra_paths]
693 path_items = extra_paths + raw_path.split(pycompat.ospathsep)
694 env[b'PATH'] = pycompat.ospathsep.join(path_items)
695 else:
696 path_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
697 extra_str = [p.decode(path_encoding, 'ignore') for p in extra_paths]
698 base = wvfs.base.decode(path_encoding, 'ignore')
699 extra_str = [os.path.join(base, i) for i in extra_str]
700
701 # use (os).xxx to bypass checkcode complains. We are doing this
702 # unicode access on purpose.
703 env = (os).environ.copy()
704 raw_path = env.get('PATH', '')
705 path_items = extra_str + raw_path.split((os).pathsep)
706 env['PATH'] = (os).pathsep.join(path_items)
707 return env
708
709
710 def fixfile(ui, repo, opts, fixers, fixctx, path, basepaths, basectxs):
711 """Run any configured fixers that should affect the file in this context
712
713 Returns the file content that results from applying the fixers in some order
714 starting with the file's content in the fixctx. Fixers that support line
715 ranges will affect lines that have changed relative to any of the basectxs
716 (i.e. they will only avoid lines that are common to all basectxs).
717
718 A fixer tool's stdout will become the file's new content if and only if it
719 exits with code zero. The fixer tool's working directory is the repository's
720 root.
721 """
722 metadata = {}
723 newdata = fixctx[path].data()
724
725 env = None
726 extra_paths = ui.configlist(b'fix', b'extra-bin-paths')
727 if extra_paths:
728 env = _augmented_env(repo.wvfs, extra_paths)
729 for fixername, fixer in fixers.items():
730 if fixer.affects(opts, fixctx, path):
731 ranges = lineranges(
732 opts, path, basepaths, basectxs, fixctx, newdata
733 )
734 command = fixer.command(ui, path, ranges)
735 if command is None:
736 continue
737 msg = b'fixing: %s - %s - %s\n'
738 msg %= (fixctx, fixername, path)
739 ui.debug(msg)
740 ui.debug(b'subprocess: %s\n' % (command,))
741 proc = subprocess.Popen(
742 procutil.tonativestr(command),
743 shell=True,
744 cwd=procutil.tonativestr(repo.root),
745 stdin=subprocess.PIPE,
746 stdout=subprocess.PIPE,
747 stderr=subprocess.PIPE,
748 env=env,
749 )
750 stdout, stderr = proc.communicate(newdata)
751 if stderr:
752 showstderr(ui, fixctx.rev(), fixername, stderr)
753 newerdata = stdout
754 if fixer.shouldoutputmetadata():
755 try:
756 metadatajson, newerdata = stdout.split(b'\0', 1)
757 metadata[fixername] = pycompat.json_loads(metadatajson)
758 except ValueError:
759 ui.warn(
760 _(b'ignored invalid output from fixer tool: %s\n')
761 % (fixername,)
762 )
763 continue
764 else:
765 metadata[fixername] = None
766 if proc.returncode == 0:
767 newdata = newerdata
768 else:
769 if not stderr:
770 message = _(b'exited with status %d\n') % (proc.returncode,)
771 showstderr(ui, fixctx.rev(), fixername, message)
772 checktoolfailureaction(
773 ui,
774 _(b'no fixes will be applied'),
775 hint=_(
776 b'use --config fix.failure=continue to apply any '
777 b'successful fixes anyway'
778 ),
779 )
780 return metadata, newdata
781
782
783 def showstderr(ui, rev, fixername, stderr):
784 """Writes the lines of the stderr string as warnings on the ui
785
786 Uses the revision number and fixername to give more context to each line of
787 the error message. Doesn't include file names, since those take up a lot of
788 space and would tend to be included in the error message if they were
789 relevant.
790 """
791 for line in re.split(b'[\r\n]+', stderr):
792 if line:
793 ui.warn(b'[')
794 if rev is None:
795 ui.warn(_(b'wdir'), label=b'evolve.rev')
796 else:
797 ui.warn(b'%d' % rev, label=b'evolve.rev')
798 ui.warn(b'] %s: %s\n' % (fixername, line))
799
800
801 def writeworkingdir(repo, ctx, filedata, replacements):
802 """Write new content to the working copy and check out the new p1 if any
803
804 We check out a new revision if and only if we fixed something in both the
805 working directory and its parent revision. This avoids the need for a full
806 update/merge, and means that the working directory simply isn't affected
807 unless the --working-dir flag is given.
808
809 Directly updates the dirstate for the affected files.
810 """
811 for path, data in filedata.items():
812 fctx = ctx[path]
813 fctx.write(data, fctx.flags())
814
815 oldp1 = repo.dirstate.p1()
816 newp1 = replacements.get(oldp1, oldp1)
817 if newp1 != oldp1:
818 assert repo.dirstate.p2() == nullid
819 with repo.dirstate.changing_parents(repo):
820 scmutil.movedirstate(repo, repo[newp1])
821
822
823 def replacerev(ui, repo, ctx, filedata, replacements):
824 """Commit a new revision like the given one, but with file content changes
825
826 "ctx" is the original revision to be replaced by a modified one.
827
828 "filedata" is a dict that maps paths to their new file content. All other
829 paths will be recreated from the original revision without changes.
830 "filedata" may contain paths that didn't exist in the original revision;
831 they will be added.
832
833 "replacements" is a dict that maps a single node to a single node, and it is
834 updated to indicate the original revision is replaced by the newly created
835 one. No entry is added if the replacement's node already exists.
836
837 The new revision has the same parents as the old one, unless those parents
838 have already been replaced, in which case those replacements are the parents
839 of this new revision. Thus, if revisions are replaced in topological order,
840 there is no need to rebase them into the original topology later.
841 """
842
843 p1rev, p2rev = repo.changelog.parentrevs(ctx.rev())
844 p1ctx, p2ctx = repo[p1rev], repo[p2rev]
845 newp1node = replacements.get(p1ctx.node(), p1ctx.node())
846 newp2node = replacements.get(p2ctx.node(), p2ctx.node())
847
848 # We don't want to create a revision that has no changes from the original,
849 # but we should if the original revision's parent has been replaced.
850 # Otherwise, we would produce an orphan that needs no actual human
851 # intervention to evolve. We can't rely on commit() to avoid creating the
852 # un-needed revision because the extra field added below produces a new hash
853 # regardless of file content changes.
854 if (
855 not filedata
856 and p1ctx.node() not in replacements
857 and p2ctx.node() not in replacements
858 ):
859 return
860
861 extra = ctx.extra().copy()
862 extra[b'fix_source'] = ctx.hex()
863
864 wctx = context.overlayworkingctx(repo)
865 wctx.setbase(repo[newp1node])
866 merge.revert_to(ctx, wc=wctx)
867 copies.graftcopies(wctx, ctx, ctx.p1())
868
869 for path in filedata.keys():
870 fctx = ctx[path]
871 copysource = fctx.copysource()
872 wctx.write(path, filedata[path], flags=fctx.flags())
873 if copysource:
874 wctx.markcopied(path, copysource)
875
876 desc = rewriteutil.update_hash_refs(
877 repo,
878 ctx.description(),
879 {oldnode: [newnode] for oldnode, newnode in replacements.items()},
880 )
881
882 memctx = wctx.tomemctx(
883 text=desc,
884 branch=ctx.branch(),
885 extra=extra,
886 date=ctx.date(),
887 parents=(newp1node, newp2node),
888 user=ctx.user(),
889 )
890
891 sucnode = memctx.commit()
892 prenode = ctx.node()
893 if prenode == sucnode:
894 ui.debug(b'node %s already existed\n' % (ctx.hex()))
895 else:
896 replacements[ctx.node()] = sucnode
897
898
899 def getfixers(ui):
900 """Returns a map of configured fixer tools indexed by their names
901
902 Each value is a Fixer object with methods that implement the behavior of the
903 fixer's config suboptions. Does not validate the config values.
904 """
905 fixers = {}
906 for name in fixernames(ui):
907 enabled = ui.configbool(b'fix', name + b':enabled')
908 command = ui.config(b'fix', name + b':command')
909 pattern = ui.config(b'fix', name + b':pattern')
910 linerange = ui.config(b'fix', name + b':linerange')
911 priority = ui.configint(b'fix', name + b':priority')
912 metadata = ui.configbool(b'fix', name + b':metadata')
913 skipclean = ui.configbool(b'fix', name + b':skipclean')
914 # Don't use a fixer if it has no pattern configured. It would be
915 # dangerous to let it affect all files. It would be pointless to let it
916 # affect no files. There is no reasonable subset of files to use as the
917 # default.
918 if command is None:
919 ui.warn(
920 _(b'fixer tool has no command configuration: %s\n') % (name,)
921 )
922 elif pattern is None:
923 ui.warn(
924 _(b'fixer tool has no pattern configuration: %s\n') % (name,)
925 )
926 elif not enabled:
927 ui.debug(b'ignoring disabled fixer tool: %s\n' % (name,))
928 else:
929 fixers[name] = Fixer(
930 command, pattern, linerange, priority, metadata, skipclean
931 )
932 return collections.OrderedDict(
933 sorted(fixers.items(), key=lambda item: item[1]._priority, reverse=True)
934 )
935
936
937 def fixernames(ui):
938 """Returns the names of [fix] config options that have suboptions"""
939 names = set()
940 for k, v in ui.configitems(b'fix'):
941 if b':' in k:
942 names.add(k.split(b':', 1)[0])
943 return names
944
945
946 class Fixer:
947 """Wraps the raw config values for a fixer with methods"""
948
949 def __init__(
950 self, command, pattern, linerange, priority, metadata, skipclean
951 ):
952 self._command = command
953 self._pattern = pattern
954 self._linerange = linerange
955 self._priority = priority
956 self._metadata = metadata
957 self._skipclean = skipclean
958
959 def affects(self, opts, fixctx, path):
960 """Should this fixer run on the file at the given path and context?"""
961 repo = fixctx.repo()
962 matcher = matchmod.match(
963 repo.root, repo.root, [self._pattern], ctx=fixctx
964 )
965 return matcher(path)
966
967 def shouldoutputmetadata(self):
968 """Should the stdout of this fixer start with JSON and a null byte?"""
969 return self._metadata
970
971 def command(self, ui, path, ranges):
972 """A shell command to use to invoke this fixer on the given file/lines
973
974 May return None if there is no appropriate command to run for the given
975 parameters.
976 """
977 expand = cmdutil.rendercommandtemplate
978 parts = [
979 expand(
980 ui,
981 self._command,
982 {b'rootpath': path, b'basename': os.path.basename(path)},
983 )
984 ]
985 if self._linerange:
986 if self._skipclean and not ranges:
987 # No line ranges to fix, so don't run the fixer.
988 return None
989 for first, last in ranges:
990 parts.append(
991 expand(
992 ui, self._linerange, {b'first': first, b'last': last}
993 )
994 )
995 return b' '.join(parts)