##// END OF EJS Templates
fix: use rewriteutil.precheck() instead of reimplementing it...
Martin von Zweigbergk -
r44388:699d6be3 default
parent child Browse files
Show More
@@ -1,881 +1,867 b''
1 # fix - rewrite file content in changesets and working copy
1 # fix - rewrite file content in changesets and working copy
2 #
2 #
3 # Copyright 2018 Google LLC.
3 # Copyright 2018 Google LLC.
4 #
4 #
5 # This software may be used and distributed according to the terms of the
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.
6 # GNU General Public License version 2 or any later version.
7 """rewrite file content in changesets or working copy (EXPERIMENTAL)
7 """rewrite file content in changesets or working copy (EXPERIMENTAL)
8
8
9 Provides a command that runs configured tools on the contents of modified files,
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.
10 writing back any fixes to the working copy or replacing changesets.
11
11
12 Here is an example configuration that causes :hg:`fix` to apply automatic
12 Here is an example configuration that causes :hg:`fix` to apply automatic
13 formatting fixes to modified lines in C++ code::
13 formatting fixes to modified lines in C++ code::
14
14
15 [fix]
15 [fix]
16 clang-format:command=clang-format --assume-filename={rootpath}
16 clang-format:command=clang-format --assume-filename={rootpath}
17 clang-format:linerange=--lines={first}:{last}
17 clang-format:linerange=--lines={first}:{last}
18 clang-format:pattern=set:**.cpp or **.hpp
18 clang-format:pattern=set:**.cpp or **.hpp
19
19
20 The :command suboption forms the first part of the shell command that will be
20 The :command suboption forms the first part of the shell command that will be
21 used to fix a file. The content of the file is passed on standard input, and the
21 used to fix a file. The content of the file is passed on standard input, and the
22 fixed file content is expected on standard output. Any output on standard error
22 fixed file content is expected on standard output. Any output on standard error
23 will be displayed as a warning. If the exit status is not zero, the file will
23 will be displayed as a warning. If the exit status is not zero, the file will
24 not be affected. A placeholder warning is displayed if there is a non-zero exit
24 not be affected. A placeholder warning is displayed if there is a non-zero exit
25 status but no standard error output. Some values may be substituted into the
25 status but no standard error output. Some values may be substituted into the
26 command::
26 command::
27
27
28 {rootpath} The path of the file being fixed, relative to the repo root
28 {rootpath} The path of the file being fixed, relative to the repo root
29 {basename} The name of the file being fixed, without the directory path
29 {basename} The name of the file being fixed, without the directory path
30
30
31 If the :linerange suboption is set, the tool will only be run if there are
31 If the :linerange suboption is set, the tool will only be run if there are
32 changed lines in a file. The value of this suboption is appended to the shell
32 changed lines in a file. The value of this suboption is appended to the shell
33 command once for every range of changed lines in the file. Some values may be
33 command once for every range of changed lines in the file. Some values may be
34 substituted into the command::
34 substituted into the command::
35
35
36 {first} The 1-based line number of the first line in the modified range
36 {first} The 1-based line number of the first line in the modified range
37 {last} The 1-based line number of the last line in the modified range
37 {last} The 1-based line number of the last line in the modified range
38
38
39 Deleted sections of a file will be ignored by :linerange, because there is no
39 Deleted sections of a file will be ignored by :linerange, because there is no
40 corresponding line range in the version being fixed.
40 corresponding line range in the version being fixed.
41
41
42 By default, tools that set :linerange will only be executed if there is at least
42 By default, tools that set :linerange will only be executed if there is at least
43 one changed line range. This is meant to prevent accidents like running a code
43 one changed line range. This is meant to prevent accidents like running a code
44 formatter in such a way that it unexpectedly reformats the whole file. If such a
44 formatter in such a way that it unexpectedly reformats the whole file. If such a
45 tool needs to operate on unchanged files, it should set the :skipclean suboption
45 tool needs to operate on unchanged files, it should set the :skipclean suboption
46 to false.
46 to false.
47
47
48 The :pattern suboption determines which files will be passed through each
48 The :pattern suboption determines which files will be passed through each
49 configured tool. See :hg:`help patterns` for possible values. However, all
49 configured tool. See :hg:`help patterns` for possible values. However, all
50 patterns are relative to the repo root, even if that text says they are relative
50 patterns are relative to the repo root, even if that text says they are relative
51 to the current working directory. If there are file arguments to :hg:`fix`, the
51 to the current working directory. If there are file arguments to :hg:`fix`, the
52 intersection of these patterns is used.
52 intersection of these patterns is used.
53
53
54 There is also a configurable limit for the maximum size of file that will be
54 There is also a configurable limit for the maximum size of file that will be
55 processed by :hg:`fix`::
55 processed by :hg:`fix`::
56
56
57 [fix]
57 [fix]
58 maxfilesize = 2MB
58 maxfilesize = 2MB
59
59
60 Normally, execution of configured tools will continue after a failure (indicated
60 Normally, execution of configured tools will continue after a failure (indicated
61 by a non-zero exit status). It can also be configured to abort after the first
61 by a non-zero exit status). It can also be configured to abort after the first
62 such failure, so that no files will be affected if any tool fails. This abort
62 such failure, so that no files will be affected if any tool fails. This abort
63 will also cause :hg:`fix` to exit with a non-zero status::
63 will also cause :hg:`fix` to exit with a non-zero status::
64
64
65 [fix]
65 [fix]
66 failure = abort
66 failure = abort
67
67
68 When multiple tools are configured to affect a file, they execute in an order
68 When multiple tools are configured to affect a file, they execute in an order
69 defined by the :priority suboption. The priority suboption has a default value
69 defined by the :priority suboption. The priority suboption has a default value
70 of zero for each tool. Tools are executed in order of descending priority. The
70 of zero for each tool. Tools are executed in order of descending priority. The
71 execution order of tools with equal priority is unspecified. For example, you
71 execution order of tools with equal priority is unspecified. For example, you
72 could use the 'sort' and 'head' utilities to keep only the 10 smallest numbers
72 could use the 'sort' and 'head' utilities to keep only the 10 smallest numbers
73 in a text file by ensuring that 'sort' runs before 'head'::
73 in a text file by ensuring that 'sort' runs before 'head'::
74
74
75 [fix]
75 [fix]
76 sort:command = sort -n
76 sort:command = sort -n
77 head:command = head -n 10
77 head:command = head -n 10
78 sort:pattern = numbers.txt
78 sort:pattern = numbers.txt
79 head:pattern = numbers.txt
79 head:pattern = numbers.txt
80 sort:priority = 2
80 sort:priority = 2
81 head:priority = 1
81 head:priority = 1
82
82
83 To account for changes made by each tool, the line numbers used for incremental
83 To account for changes made by each tool, the line numbers used for incremental
84 formatting are recomputed before executing the next tool. So, each tool may see
84 formatting are recomputed before executing the next tool. So, each tool may see
85 different values for the arguments added by the :linerange suboption.
85 different values for the arguments added by the :linerange suboption.
86
86
87 Each fixer tool is allowed to return some metadata in addition to the fixed file
87 Each fixer tool is allowed to return some metadata in addition to the fixed file
88 content. The metadata must be placed before the file content on stdout,
88 content. The metadata must be placed before the file content on stdout,
89 separated from the file content by a zero byte. The metadata is parsed as a JSON
89 separated from the file content by a zero byte. The metadata is parsed as a JSON
90 value (so, it should be UTF-8 encoded and contain no zero bytes). A fixer tool
90 value (so, it should be UTF-8 encoded and contain no zero bytes). A fixer tool
91 is expected to produce this metadata encoding if and only if the :metadata
91 is expected to produce this metadata encoding if and only if the :metadata
92 suboption is true::
92 suboption is true::
93
93
94 [fix]
94 [fix]
95 tool:command = tool --prepend-json-metadata
95 tool:command = tool --prepend-json-metadata
96 tool:metadata = true
96 tool:metadata = true
97
97
98 The metadata values are passed to hooks, which can be used to print summaries or
98 The metadata values are passed to hooks, which can be used to print summaries or
99 perform other post-fixing work. The supported hooks are::
99 perform other post-fixing work. The supported hooks are::
100
100
101 "postfixfile"
101 "postfixfile"
102 Run once for each file in each revision where any fixer tools made changes
102 Run once for each file in each revision where any fixer tools made changes
103 to the file content. Provides "$HG_REV" and "$HG_PATH" to identify the file,
103 to the file content. Provides "$HG_REV" and "$HG_PATH" to identify the file,
104 and "$HG_METADATA" with a map of fixer names to metadata values from fixer
104 and "$HG_METADATA" with a map of fixer names to metadata values from fixer
105 tools that affected the file. Fixer tools that didn't affect the file have a
105 tools that affected the file. Fixer tools that didn't affect the file have a
106 valueof None. Only fixer tools that executed are present in the metadata.
106 valueof None. Only fixer tools that executed are present in the metadata.
107
107
108 "postfix"
108 "postfix"
109 Run once after all files and revisions have been handled. Provides
109 Run once after all files and revisions have been handled. Provides
110 "$HG_REPLACEMENTS" with information about what revisions were created and
110 "$HG_REPLACEMENTS" with information about what revisions were created and
111 made obsolete. Provides a boolean "$HG_WDIRWRITTEN" to indicate whether any
111 made obsolete. Provides a boolean "$HG_WDIRWRITTEN" to indicate whether any
112 files in the working copy were updated. Provides a list "$HG_METADATA"
112 files in the working copy were updated. Provides a list "$HG_METADATA"
113 mapping fixer tool names to lists of metadata values returned from
113 mapping fixer tool names to lists of metadata values returned from
114 executions that modified a file. This aggregates the same metadata
114 executions that modified a file. This aggregates the same metadata
115 previously passed to the "postfixfile" hook.
115 previously passed to the "postfixfile" hook.
116
116
117 Fixer tools are run the in repository's root directory. This allows them to read
117 Fixer tools are run the in repository's root directory. This allows them to read
118 configuration files from the working copy, or even write to the working copy.
118 configuration files from the working copy, or even write to the working copy.
119 The working copy is not updated to match the revision being fixed. In fact,
119 The working copy is not updated to match the revision being fixed. In fact,
120 several revisions may be fixed in parallel. Writes to the working copy are not
120 several revisions may be fixed in parallel. Writes to the working copy are not
121 amended into the revision being fixed; fixer tools should always write fixed
121 amended into the revision being fixed; fixer tools should always write fixed
122 file content back to stdout as documented above.
122 file content back to stdout as documented above.
123 """
123 """
124
124
125 from __future__ import absolute_import
125 from __future__ import absolute_import
126
126
127 import collections
127 import collections
128 import itertools
128 import itertools
129 import os
129 import os
130 import re
130 import re
131 import subprocess
131 import subprocess
132
132
133 from mercurial.i18n import _
133 from mercurial.i18n import _
134 from mercurial.node import nullrev
134 from mercurial.node import nullrev
135 from mercurial.node import wdirrev
135 from mercurial.node import wdirrev
136
136
137 from mercurial.utils import procutil
137 from mercurial.utils import procutil
138
138
139 from mercurial import (
139 from mercurial import (
140 cmdutil,
140 cmdutil,
141 context,
141 context,
142 copies,
142 copies,
143 error,
143 error,
144 match as matchmod,
144 match as matchmod,
145 mdiff,
145 mdiff,
146 merge,
146 merge,
147 obsolete,
148 pycompat,
147 pycompat,
149 registrar,
148 registrar,
149 rewriteutil,
150 scmutil,
150 scmutil,
151 util,
151 util,
152 worker,
152 worker,
153 )
153 )
154
154
155 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
155 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
156 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
156 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
157 # be specifying the version(s) of Mercurial they are tested with, or
157 # be specifying the version(s) of Mercurial they are tested with, or
158 # leave the attribute unspecified.
158 # leave the attribute unspecified.
159 testedwith = b'ships-with-hg-core'
159 testedwith = b'ships-with-hg-core'
160
160
161 cmdtable = {}
161 cmdtable = {}
162 command = registrar.command(cmdtable)
162 command = registrar.command(cmdtable)
163
163
164 configtable = {}
164 configtable = {}
165 configitem = registrar.configitem(configtable)
165 configitem = registrar.configitem(configtable)
166
166
167 # Register the suboptions allowed for each configured fixer, and default values.
167 # Register the suboptions allowed for each configured fixer, and default values.
168 FIXER_ATTRS = {
168 FIXER_ATTRS = {
169 b'command': None,
169 b'command': None,
170 b'linerange': None,
170 b'linerange': None,
171 b'pattern': None,
171 b'pattern': None,
172 b'priority': 0,
172 b'priority': 0,
173 b'metadata': False,
173 b'metadata': False,
174 b'skipclean': True,
174 b'skipclean': True,
175 b'enabled': True,
175 b'enabled': True,
176 }
176 }
177
177
178 for key, default in FIXER_ATTRS.items():
178 for key, default in FIXER_ATTRS.items():
179 configitem(b'fix', b'.*:%s$' % key, default=default, generic=True)
179 configitem(b'fix', b'.*:%s$' % key, default=default, generic=True)
180
180
181 # A good default size allows most source code files to be fixed, but avoids
181 # A good default size allows most source code files to be fixed, but avoids
182 # letting fixer tools choke on huge inputs, which could be surprising to the
182 # letting fixer tools choke on huge inputs, which could be surprising to the
183 # user.
183 # user.
184 configitem(b'fix', b'maxfilesize', default=b'2MB')
184 configitem(b'fix', b'maxfilesize', default=b'2MB')
185
185
186 # Allow fix commands to exit non-zero if an executed fixer tool exits non-zero.
186 # Allow fix commands to exit non-zero if an executed fixer tool exits non-zero.
187 # This helps users do shell scripts that stop when a fixer tool signals a
187 # This helps users do shell scripts that stop when a fixer tool signals a
188 # problem.
188 # problem.
189 configitem(b'fix', b'failure', default=b'continue')
189 configitem(b'fix', b'failure', default=b'continue')
190
190
191
191
192 def checktoolfailureaction(ui, message, hint=None):
192 def checktoolfailureaction(ui, message, hint=None):
193 """Abort with 'message' if fix.failure=abort"""
193 """Abort with 'message' if fix.failure=abort"""
194 action = ui.config(b'fix', b'failure')
194 action = ui.config(b'fix', b'failure')
195 if action not in (b'continue', b'abort'):
195 if action not in (b'continue', b'abort'):
196 raise error.Abort(
196 raise error.Abort(
197 _(b'unknown fix.failure action: %s') % (action,),
197 _(b'unknown fix.failure action: %s') % (action,),
198 hint=_(b'use "continue" or "abort"'),
198 hint=_(b'use "continue" or "abort"'),
199 )
199 )
200 if action == b'abort':
200 if action == b'abort':
201 raise error.Abort(message, hint=hint)
201 raise error.Abort(message, hint=hint)
202
202
203
203
204 allopt = (b'', b'all', False, _(b'fix all non-public non-obsolete revisions'))
204 allopt = (b'', b'all', False, _(b'fix all non-public non-obsolete revisions'))
205 baseopt = (
205 baseopt = (
206 b'',
206 b'',
207 b'base',
207 b'base',
208 [],
208 [],
209 _(
209 _(
210 b'revisions to diff against (overrides automatic '
210 b'revisions to diff against (overrides automatic '
211 b'selection, and applies to every revision being '
211 b'selection, and applies to every revision being '
212 b'fixed)'
212 b'fixed)'
213 ),
213 ),
214 _(b'REV'),
214 _(b'REV'),
215 )
215 )
216 revopt = (b'r', b'rev', [], _(b'revisions to fix'), _(b'REV'))
216 revopt = (b'r', b'rev', [], _(b'revisions to fix'), _(b'REV'))
217 wdiropt = (b'w', b'working-dir', False, _(b'fix the working directory'))
217 wdiropt = (b'w', b'working-dir', False, _(b'fix the working directory'))
218 wholeopt = (b'', b'whole', False, _(b'always fix every line of a file'))
218 wholeopt = (b'', b'whole', False, _(b'always fix every line of a file'))
219 usage = _(b'[OPTION]... [FILE]...')
219 usage = _(b'[OPTION]... [FILE]...')
220
220
221
221
222 @command(
222 @command(
223 b'fix',
223 b'fix',
224 [allopt, baseopt, revopt, wdiropt, wholeopt],
224 [allopt, baseopt, revopt, wdiropt, wholeopt],
225 usage,
225 usage,
226 helpcategory=command.CATEGORY_FILE_CONTENTS,
226 helpcategory=command.CATEGORY_FILE_CONTENTS,
227 )
227 )
228 def fix(ui, repo, *pats, **opts):
228 def fix(ui, repo, *pats, **opts):
229 """rewrite file content in changesets or working directory
229 """rewrite file content in changesets or working directory
230
230
231 Runs any configured tools to fix the content of files. Only affects files
231 Runs any configured tools to fix the content of files. Only affects files
232 with changes, unless file arguments are provided. Only affects changed lines
232 with changes, unless file arguments are provided. Only affects changed lines
233 of files, unless the --whole flag is used. Some tools may always affect the
233 of files, unless the --whole flag is used. Some tools may always affect the
234 whole file regardless of --whole.
234 whole file regardless of --whole.
235
235
236 If revisions are specified with --rev, those revisions will be checked, and
236 If revisions are specified with --rev, those revisions will be checked, and
237 they may be replaced with new revisions that have fixed file content. It is
237 they may be replaced with new revisions that have fixed file content. It is
238 desirable to specify all descendants of each specified revision, so that the
238 desirable to specify all descendants of each specified revision, so that the
239 fixes propagate to the descendants. If all descendants are fixed at the same
239 fixes propagate to the descendants. If all descendants are fixed at the same
240 time, no merging, rebasing, or evolution will be required.
240 time, no merging, rebasing, or evolution will be required.
241
241
242 If --working-dir is used, files with uncommitted changes in the working copy
242 If --working-dir is used, files with uncommitted changes in the working copy
243 will be fixed. If the checked-out revision is also fixed, the working
243 will be fixed. If the checked-out revision is also fixed, the working
244 directory will update to the replacement revision.
244 directory will update to the replacement revision.
245
245
246 When determining what lines of each file to fix at each revision, the whole
246 When determining what lines of each file to fix at each revision, the whole
247 set of revisions being fixed is considered, so that fixes to earlier
247 set of revisions being fixed is considered, so that fixes to earlier
248 revisions are not forgotten in later ones. The --base flag can be used to
248 revisions are not forgotten in later ones. The --base flag can be used to
249 override this default behavior, though it is not usually desirable to do so.
249 override this default behavior, though it is not usually desirable to do so.
250 """
250 """
251 opts = pycompat.byteskwargs(opts)
251 opts = pycompat.byteskwargs(opts)
252 cmdutil.check_at_most_one_arg(opts, b'all', b'rev')
252 cmdutil.check_at_most_one_arg(opts, b'all', b'rev')
253 if opts[b'all']:
253 if opts[b'all']:
254 opts[b'rev'] = [b'not public() and not obsolete()']
254 opts[b'rev'] = [b'not public() and not obsolete()']
255 opts[b'working_dir'] = True
255 opts[b'working_dir'] = True
256 with repo.wlock(), repo.lock(), repo.transaction(b'fix'):
256 with repo.wlock(), repo.lock(), repo.transaction(b'fix'):
257 revstofix = getrevstofix(ui, repo, opts)
257 revstofix = getrevstofix(ui, repo, opts)
258 basectxs = getbasectxs(repo, opts, revstofix)
258 basectxs = getbasectxs(repo, opts, revstofix)
259 workqueue, numitems = getworkqueue(
259 workqueue, numitems = getworkqueue(
260 ui, repo, pats, opts, revstofix, basectxs
260 ui, repo, pats, opts, revstofix, basectxs
261 )
261 )
262 fixers = getfixers(ui)
262 fixers = getfixers(ui)
263
263
264 # There are no data dependencies between the workers fixing each file
264 # There are no data dependencies between the workers fixing each file
265 # revision, so we can use all available parallelism.
265 # revision, so we can use all available parallelism.
266 def getfixes(items):
266 def getfixes(items):
267 for rev, path in items:
267 for rev, path in items:
268 ctx = repo[rev]
268 ctx = repo[rev]
269 olddata = ctx[path].data()
269 olddata = ctx[path].data()
270 metadata, newdata = fixfile(
270 metadata, newdata = fixfile(
271 ui, repo, opts, fixers, ctx, path, basectxs[rev]
271 ui, repo, opts, fixers, ctx, path, basectxs[rev]
272 )
272 )
273 # Don't waste memory/time passing unchanged content back, but
273 # Don't waste memory/time passing unchanged content back, but
274 # produce one result per item either way.
274 # produce one result per item either way.
275 yield (
275 yield (
276 rev,
276 rev,
277 path,
277 path,
278 metadata,
278 metadata,
279 newdata if newdata != olddata else None,
279 newdata if newdata != olddata else None,
280 )
280 )
281
281
282 results = worker.worker(
282 results = worker.worker(
283 ui, 1.0, getfixes, tuple(), workqueue, threadsafe=False
283 ui, 1.0, getfixes, tuple(), workqueue, threadsafe=False
284 )
284 )
285
285
286 # We have to hold on to the data for each successor revision in memory
286 # We have to hold on to the data for each successor revision in memory
287 # until all its parents are committed. We ensure this by committing and
287 # until all its parents are committed. We ensure this by committing and
288 # freeing memory for the revisions in some topological order. This
288 # freeing memory for the revisions in some topological order. This
289 # leaves a little bit of memory efficiency on the table, but also makes
289 # leaves a little bit of memory efficiency on the table, but also makes
290 # the tests deterministic. It might also be considered a feature since
290 # the tests deterministic. It might also be considered a feature since
291 # it makes the results more easily reproducible.
291 # it makes the results more easily reproducible.
292 filedata = collections.defaultdict(dict)
292 filedata = collections.defaultdict(dict)
293 aggregatemetadata = collections.defaultdict(list)
293 aggregatemetadata = collections.defaultdict(list)
294 replacements = {}
294 replacements = {}
295 wdirwritten = False
295 wdirwritten = False
296 commitorder = sorted(revstofix, reverse=True)
296 commitorder = sorted(revstofix, reverse=True)
297 with ui.makeprogress(
297 with ui.makeprogress(
298 topic=_(b'fixing'), unit=_(b'files'), total=sum(numitems.values())
298 topic=_(b'fixing'), unit=_(b'files'), total=sum(numitems.values())
299 ) as progress:
299 ) as progress:
300 for rev, path, filerevmetadata, newdata in results:
300 for rev, path, filerevmetadata, newdata in results:
301 progress.increment(item=path)
301 progress.increment(item=path)
302 for fixername, fixermetadata in filerevmetadata.items():
302 for fixername, fixermetadata in filerevmetadata.items():
303 aggregatemetadata[fixername].append(fixermetadata)
303 aggregatemetadata[fixername].append(fixermetadata)
304 if newdata is not None:
304 if newdata is not None:
305 filedata[rev][path] = newdata
305 filedata[rev][path] = newdata
306 hookargs = {
306 hookargs = {
307 b'rev': rev,
307 b'rev': rev,
308 b'path': path,
308 b'path': path,
309 b'metadata': filerevmetadata,
309 b'metadata': filerevmetadata,
310 }
310 }
311 repo.hook(
311 repo.hook(
312 b'postfixfile',
312 b'postfixfile',
313 throw=False,
313 throw=False,
314 **pycompat.strkwargs(hookargs)
314 **pycompat.strkwargs(hookargs)
315 )
315 )
316 numitems[rev] -= 1
316 numitems[rev] -= 1
317 # Apply the fixes for this and any other revisions that are
317 # Apply the fixes for this and any other revisions that are
318 # ready and sitting at the front of the queue. Using a loop here
318 # ready and sitting at the front of the queue. Using a loop here
319 # prevents the queue from being blocked by the first revision to
319 # prevents the queue from being blocked by the first revision to
320 # be ready out of order.
320 # be ready out of order.
321 while commitorder and not numitems[commitorder[-1]]:
321 while commitorder and not numitems[commitorder[-1]]:
322 rev = commitorder.pop()
322 rev = commitorder.pop()
323 ctx = repo[rev]
323 ctx = repo[rev]
324 if rev == wdirrev:
324 if rev == wdirrev:
325 writeworkingdir(repo, ctx, filedata[rev], replacements)
325 writeworkingdir(repo, ctx, filedata[rev], replacements)
326 wdirwritten = bool(filedata[rev])
326 wdirwritten = bool(filedata[rev])
327 else:
327 else:
328 replacerev(ui, repo, ctx, filedata[rev], replacements)
328 replacerev(ui, repo, ctx, filedata[rev], replacements)
329 del filedata[rev]
329 del filedata[rev]
330
330
331 cleanup(repo, replacements, wdirwritten)
331 cleanup(repo, replacements, wdirwritten)
332 hookargs = {
332 hookargs = {
333 b'replacements': replacements,
333 b'replacements': replacements,
334 b'wdirwritten': wdirwritten,
334 b'wdirwritten': wdirwritten,
335 b'metadata': aggregatemetadata,
335 b'metadata': aggregatemetadata,
336 }
336 }
337 repo.hook(b'postfix', throw=True, **pycompat.strkwargs(hookargs))
337 repo.hook(b'postfix', throw=True, **pycompat.strkwargs(hookargs))
338
338
339
339
340 def cleanup(repo, replacements, wdirwritten):
340 def cleanup(repo, replacements, wdirwritten):
341 """Calls scmutil.cleanupnodes() with the given replacements.
341 """Calls scmutil.cleanupnodes() with the given replacements.
342
342
343 "replacements" is a dict from nodeid to nodeid, with one key and one value
343 "replacements" is a dict from nodeid to nodeid, with one key and one value
344 for every revision that was affected by fixing. This is slightly different
344 for every revision that was affected by fixing. This is slightly different
345 from cleanupnodes().
345 from cleanupnodes().
346
346
347 "wdirwritten" is a bool which tells whether the working copy was affected by
347 "wdirwritten" is a bool which tells whether the working copy was affected by
348 fixing, since it has no entry in "replacements".
348 fixing, since it has no entry in "replacements".
349
349
350 Useful as a hook point for extending "hg fix" with output summarizing the
350 Useful as a hook point for extending "hg fix" with output summarizing the
351 effects of the command, though we choose not to output anything here.
351 effects of the command, though we choose not to output anything here.
352 """
352 """
353 replacements = {
353 replacements = {
354 prec: [succ] for prec, succ in pycompat.iteritems(replacements)
354 prec: [succ] for prec, succ in pycompat.iteritems(replacements)
355 }
355 }
356 scmutil.cleanupnodes(repo, replacements, b'fix', fixphase=True)
356 scmutil.cleanupnodes(repo, replacements, b'fix', fixphase=True)
357
357
358
358
359 def getworkqueue(ui, repo, pats, opts, revstofix, basectxs):
359 def getworkqueue(ui, repo, pats, opts, revstofix, basectxs):
360 """"Constructs the list of files to be fixed at specific revisions
360 """"Constructs the list of files to be fixed at specific revisions
361
361
362 It is up to the caller how to consume the work items, and the only
362 It is up to the caller how to consume the work items, and the only
363 dependence between them is that replacement revisions must be committed in
363 dependence between them is that replacement revisions must be committed in
364 topological order. Each work item represents a file in the working copy or
364 topological order. Each work item represents a file in the working copy or
365 in some revision that should be fixed and written back to the working copy
365 in some revision that should be fixed and written back to the working copy
366 or into a replacement revision.
366 or into a replacement revision.
367
367
368 Work items for the same revision are grouped together, so that a worker
368 Work items for the same revision are grouped together, so that a worker
369 pool starting with the first N items in parallel is likely to finish the
369 pool starting with the first N items in parallel is likely to finish the
370 first revision's work before other revisions. This can allow us to write
370 first revision's work before other revisions. This can allow us to write
371 the result to disk and reduce memory footprint. At time of writing, the
371 the result to disk and reduce memory footprint. At time of writing, the
372 partition strategy in worker.py seems favorable to this. We also sort the
372 partition strategy in worker.py seems favorable to this. We also sort the
373 items by ascending revision number to match the order in which we commit
373 items by ascending revision number to match the order in which we commit
374 the fixes later.
374 the fixes later.
375 """
375 """
376 workqueue = []
376 workqueue = []
377 numitems = collections.defaultdict(int)
377 numitems = collections.defaultdict(int)
378 maxfilesize = ui.configbytes(b'fix', b'maxfilesize')
378 maxfilesize = ui.configbytes(b'fix', b'maxfilesize')
379 for rev in sorted(revstofix):
379 for rev in sorted(revstofix):
380 fixctx = repo[rev]
380 fixctx = repo[rev]
381 match = scmutil.match(fixctx, pats, opts)
381 match = scmutil.match(fixctx, pats, opts)
382 for path in sorted(
382 for path in sorted(
383 pathstofix(ui, repo, pats, opts, match, basectxs[rev], fixctx)
383 pathstofix(ui, repo, pats, opts, match, basectxs[rev], fixctx)
384 ):
384 ):
385 fctx = fixctx[path]
385 fctx = fixctx[path]
386 if fctx.islink():
386 if fctx.islink():
387 continue
387 continue
388 if fctx.size() > maxfilesize:
388 if fctx.size() > maxfilesize:
389 ui.warn(
389 ui.warn(
390 _(b'ignoring file larger than %s: %s\n')
390 _(b'ignoring file larger than %s: %s\n')
391 % (util.bytecount(maxfilesize), path)
391 % (util.bytecount(maxfilesize), path)
392 )
392 )
393 continue
393 continue
394 workqueue.append((rev, path))
394 workqueue.append((rev, path))
395 numitems[rev] += 1
395 numitems[rev] += 1
396 return workqueue, numitems
396 return workqueue, numitems
397
397
398
398
399 def getrevstofix(ui, repo, opts):
399 def getrevstofix(ui, repo, opts):
400 """Returns the set of revision numbers that should be fixed"""
400 """Returns the set of revision numbers that should be fixed"""
401 revs = set(scmutil.revrange(repo, opts[b'rev']))
401 revs = set(scmutil.revrange(repo, opts[b'rev']))
402 for rev in revs:
402 for rev in revs:
403 checkfixablectx(ui, repo, repo[rev])
403 checkfixablectx(ui, repo, repo[rev])
404 if revs:
404 if revs:
405 cmdutil.checkunfinished(repo)
405 cmdutil.checkunfinished(repo)
406 checknodescendants(repo, revs)
406 rewriteutil.precheck(repo, revs, b'fix')
407 if opts.get(b'working_dir'):
407 if opts.get(b'working_dir'):
408 revs.add(wdirrev)
408 revs.add(wdirrev)
409 if list(merge.mergestate.read(repo).unresolved()):
409 if list(merge.mergestate.read(repo).unresolved()):
410 raise error.Abort(b'unresolved conflicts', hint=b"use 'hg resolve'")
410 raise error.Abort(b'unresolved conflicts', hint=b"use 'hg resolve'")
411 if not revs:
411 if not revs:
412 raise error.Abort(
412 raise error.Abort(
413 b'no changesets specified', hint=b'use --rev or --working-dir'
413 b'no changesets specified', hint=b'use --rev or --working-dir'
414 )
414 )
415 return revs
415 return revs
416
416
417
417
418 def checknodescendants(repo, revs):
419 if not obsolete.isenabled(repo, obsolete.allowunstableopt) and repo.revs(
420 b'(%ld::) - (%ld)', revs, revs
421 ):
422 raise error.Abort(
423 _(b'can only fix a changeset together with all its descendants')
424 )
425
426
427 def checkfixablectx(ui, repo, ctx):
418 def checkfixablectx(ui, repo, ctx):
428 """Aborts if the revision shouldn't be replaced with a fixed one."""
419 """Aborts if the revision shouldn't be replaced with a fixed one."""
429 if not ctx.mutable():
430 raise error.Abort(
431 b'can\'t fix immutable changeset %s'
432 % (scmutil.formatchangeid(ctx),)
433 )
434 if ctx.obsolete():
420 if ctx.obsolete():
435 # It would be better to actually check if the revision has a successor.
421 # It would be better to actually check if the revision has a successor.
436 allowdivergence = ui.configbool(
422 allowdivergence = ui.configbool(
437 b'experimental', b'evolution.allowdivergence'
423 b'experimental', b'evolution.allowdivergence'
438 )
424 )
439 if not allowdivergence:
425 if not allowdivergence:
440 raise error.Abort(
426 raise error.Abort(
441 b'fixing obsolete revision could cause divergence'
427 b'fixing obsolete revision could cause divergence'
442 )
428 )
443
429
444
430
445 def pathstofix(ui, repo, pats, opts, match, basectxs, fixctx):
431 def pathstofix(ui, repo, pats, opts, match, basectxs, fixctx):
446 """Returns the set of files that should be fixed in a context
432 """Returns the set of files that should be fixed in a context
447
433
448 The result depends on the base contexts; we include any file that has
434 The result depends on the base contexts; we include any file that has
449 changed relative to any of the base contexts. Base contexts should be
435 changed relative to any of the base contexts. Base contexts should be
450 ancestors of the context being fixed.
436 ancestors of the context being fixed.
451 """
437 """
452 files = set()
438 files = set()
453 for basectx in basectxs:
439 for basectx in basectxs:
454 stat = basectx.status(
440 stat = basectx.status(
455 fixctx, match=match, listclean=bool(pats), listunknown=bool(pats)
441 fixctx, match=match, listclean=bool(pats), listunknown=bool(pats)
456 )
442 )
457 files.update(
443 files.update(
458 set(
444 set(
459 itertools.chain(
445 itertools.chain(
460 stat.added, stat.modified, stat.clean, stat.unknown
446 stat.added, stat.modified, stat.clean, stat.unknown
461 )
447 )
462 )
448 )
463 )
449 )
464 return files
450 return files
465
451
466
452
467 def lineranges(opts, path, basectxs, fixctx, content2):
453 def lineranges(opts, path, basectxs, fixctx, content2):
468 """Returns the set of line ranges that should be fixed in a file
454 """Returns the set of line ranges that should be fixed in a file
469
455
470 Of the form [(10, 20), (30, 40)].
456 Of the form [(10, 20), (30, 40)].
471
457
472 This depends on the given base contexts; we must consider lines that have
458 This depends on the given base contexts; we must consider lines that have
473 changed versus any of the base contexts, and whether the file has been
459 changed versus any of the base contexts, and whether the file has been
474 renamed versus any of them.
460 renamed versus any of them.
475
461
476 Another way to understand this is that we exclude line ranges that are
462 Another way to understand this is that we exclude line ranges that are
477 common to the file in all base contexts.
463 common to the file in all base contexts.
478 """
464 """
479 if opts.get(b'whole'):
465 if opts.get(b'whole'):
480 # Return a range containing all lines. Rely on the diff implementation's
466 # Return a range containing all lines. Rely on the diff implementation's
481 # idea of how many lines are in the file, instead of reimplementing it.
467 # idea of how many lines are in the file, instead of reimplementing it.
482 return difflineranges(b'', content2)
468 return difflineranges(b'', content2)
483
469
484 rangeslist = []
470 rangeslist = []
485 for basectx in basectxs:
471 for basectx in basectxs:
486 basepath = copies.pathcopies(basectx, fixctx).get(path, path)
472 basepath = copies.pathcopies(basectx, fixctx).get(path, path)
487 if basepath in basectx:
473 if basepath in basectx:
488 content1 = basectx[basepath].data()
474 content1 = basectx[basepath].data()
489 else:
475 else:
490 content1 = b''
476 content1 = b''
491 rangeslist.extend(difflineranges(content1, content2))
477 rangeslist.extend(difflineranges(content1, content2))
492 return unionranges(rangeslist)
478 return unionranges(rangeslist)
493
479
494
480
495 def unionranges(rangeslist):
481 def unionranges(rangeslist):
496 """Return the union of some closed intervals
482 """Return the union of some closed intervals
497
483
498 >>> unionranges([])
484 >>> unionranges([])
499 []
485 []
500 >>> unionranges([(1, 100)])
486 >>> unionranges([(1, 100)])
501 [(1, 100)]
487 [(1, 100)]
502 >>> unionranges([(1, 100), (1, 100)])
488 >>> unionranges([(1, 100), (1, 100)])
503 [(1, 100)]
489 [(1, 100)]
504 >>> unionranges([(1, 100), (2, 100)])
490 >>> unionranges([(1, 100), (2, 100)])
505 [(1, 100)]
491 [(1, 100)]
506 >>> unionranges([(1, 99), (1, 100)])
492 >>> unionranges([(1, 99), (1, 100)])
507 [(1, 100)]
493 [(1, 100)]
508 >>> unionranges([(1, 100), (40, 60)])
494 >>> unionranges([(1, 100), (40, 60)])
509 [(1, 100)]
495 [(1, 100)]
510 >>> unionranges([(1, 49), (50, 100)])
496 >>> unionranges([(1, 49), (50, 100)])
511 [(1, 100)]
497 [(1, 100)]
512 >>> unionranges([(1, 48), (50, 100)])
498 >>> unionranges([(1, 48), (50, 100)])
513 [(1, 48), (50, 100)]
499 [(1, 48), (50, 100)]
514 >>> unionranges([(1, 2), (3, 4), (5, 6)])
500 >>> unionranges([(1, 2), (3, 4), (5, 6)])
515 [(1, 6)]
501 [(1, 6)]
516 """
502 """
517 rangeslist = sorted(set(rangeslist))
503 rangeslist = sorted(set(rangeslist))
518 unioned = []
504 unioned = []
519 if rangeslist:
505 if rangeslist:
520 unioned, rangeslist = [rangeslist[0]], rangeslist[1:]
506 unioned, rangeslist = [rangeslist[0]], rangeslist[1:]
521 for a, b in rangeslist:
507 for a, b in rangeslist:
522 c, d = unioned[-1]
508 c, d = unioned[-1]
523 if a > d + 1:
509 if a > d + 1:
524 unioned.append((a, b))
510 unioned.append((a, b))
525 else:
511 else:
526 unioned[-1] = (c, max(b, d))
512 unioned[-1] = (c, max(b, d))
527 return unioned
513 return unioned
528
514
529
515
530 def difflineranges(content1, content2):
516 def difflineranges(content1, content2):
531 """Return list of line number ranges in content2 that differ from content1.
517 """Return list of line number ranges in content2 that differ from content1.
532
518
533 Line numbers are 1-based. The numbers are the first and last line contained
519 Line numbers are 1-based. The numbers are the first and last line contained
534 in the range. Single-line ranges have the same line number for the first and
520 in the range. Single-line ranges have the same line number for the first and
535 last line. Excludes any empty ranges that result from lines that are only
521 last line. Excludes any empty ranges that result from lines that are only
536 present in content1. Relies on mdiff's idea of where the line endings are in
522 present in content1. Relies on mdiff's idea of where the line endings are in
537 the string.
523 the string.
538
524
539 >>> from mercurial import pycompat
525 >>> from mercurial import pycompat
540 >>> lines = lambda s: b'\\n'.join([c for c in pycompat.iterbytestr(s)])
526 >>> lines = lambda s: b'\\n'.join([c for c in pycompat.iterbytestr(s)])
541 >>> difflineranges2 = lambda a, b: difflineranges(lines(a), lines(b))
527 >>> difflineranges2 = lambda a, b: difflineranges(lines(a), lines(b))
542 >>> difflineranges2(b'', b'')
528 >>> difflineranges2(b'', b'')
543 []
529 []
544 >>> difflineranges2(b'a', b'')
530 >>> difflineranges2(b'a', b'')
545 []
531 []
546 >>> difflineranges2(b'', b'A')
532 >>> difflineranges2(b'', b'A')
547 [(1, 1)]
533 [(1, 1)]
548 >>> difflineranges2(b'a', b'a')
534 >>> difflineranges2(b'a', b'a')
549 []
535 []
550 >>> difflineranges2(b'a', b'A')
536 >>> difflineranges2(b'a', b'A')
551 [(1, 1)]
537 [(1, 1)]
552 >>> difflineranges2(b'ab', b'')
538 >>> difflineranges2(b'ab', b'')
553 []
539 []
554 >>> difflineranges2(b'', b'AB')
540 >>> difflineranges2(b'', b'AB')
555 [(1, 2)]
541 [(1, 2)]
556 >>> difflineranges2(b'abc', b'ac')
542 >>> difflineranges2(b'abc', b'ac')
557 []
543 []
558 >>> difflineranges2(b'ab', b'aCb')
544 >>> difflineranges2(b'ab', b'aCb')
559 [(2, 2)]
545 [(2, 2)]
560 >>> difflineranges2(b'abc', b'aBc')
546 >>> difflineranges2(b'abc', b'aBc')
561 [(2, 2)]
547 [(2, 2)]
562 >>> difflineranges2(b'ab', b'AB')
548 >>> difflineranges2(b'ab', b'AB')
563 [(1, 2)]
549 [(1, 2)]
564 >>> difflineranges2(b'abcde', b'aBcDe')
550 >>> difflineranges2(b'abcde', b'aBcDe')
565 [(2, 2), (4, 4)]
551 [(2, 2), (4, 4)]
566 >>> difflineranges2(b'abcde', b'aBCDe')
552 >>> difflineranges2(b'abcde', b'aBCDe')
567 [(2, 4)]
553 [(2, 4)]
568 """
554 """
569 ranges = []
555 ranges = []
570 for lines, kind in mdiff.allblocks(content1, content2):
556 for lines, kind in mdiff.allblocks(content1, content2):
571 firstline, lastline = lines[2:4]
557 firstline, lastline = lines[2:4]
572 if kind == b'!' and firstline != lastline:
558 if kind == b'!' and firstline != lastline:
573 ranges.append((firstline + 1, lastline))
559 ranges.append((firstline + 1, lastline))
574 return ranges
560 return ranges
575
561
576
562
577 def getbasectxs(repo, opts, revstofix):
563 def getbasectxs(repo, opts, revstofix):
578 """Returns a map of the base contexts for each revision
564 """Returns a map of the base contexts for each revision
579
565
580 The base contexts determine which lines are considered modified when we
566 The base contexts determine which lines are considered modified when we
581 attempt to fix just the modified lines in a file. It also determines which
567 attempt to fix just the modified lines in a file. It also determines which
582 files we attempt to fix, so it is important to compute this even when
568 files we attempt to fix, so it is important to compute this even when
583 --whole is used.
569 --whole is used.
584 """
570 """
585 # The --base flag overrides the usual logic, and we give every revision
571 # The --base flag overrides the usual logic, and we give every revision
586 # exactly the set of baserevs that the user specified.
572 # exactly the set of baserevs that the user specified.
587 if opts.get(b'base'):
573 if opts.get(b'base'):
588 baserevs = set(scmutil.revrange(repo, opts.get(b'base')))
574 baserevs = set(scmutil.revrange(repo, opts.get(b'base')))
589 if not baserevs:
575 if not baserevs:
590 baserevs = {nullrev}
576 baserevs = {nullrev}
591 basectxs = {repo[rev] for rev in baserevs}
577 basectxs = {repo[rev] for rev in baserevs}
592 return {rev: basectxs for rev in revstofix}
578 return {rev: basectxs for rev in revstofix}
593
579
594 # Proceed in topological order so that we can easily determine each
580 # Proceed in topological order so that we can easily determine each
595 # revision's baserevs by looking at its parents and their baserevs.
581 # revision's baserevs by looking at its parents and their baserevs.
596 basectxs = collections.defaultdict(set)
582 basectxs = collections.defaultdict(set)
597 for rev in sorted(revstofix):
583 for rev in sorted(revstofix):
598 ctx = repo[rev]
584 ctx = repo[rev]
599 for pctx in ctx.parents():
585 for pctx in ctx.parents():
600 if pctx.rev() in basectxs:
586 if pctx.rev() in basectxs:
601 basectxs[rev].update(basectxs[pctx.rev()])
587 basectxs[rev].update(basectxs[pctx.rev()])
602 else:
588 else:
603 basectxs[rev].add(pctx)
589 basectxs[rev].add(pctx)
604 return basectxs
590 return basectxs
605
591
606
592
607 def fixfile(ui, repo, opts, fixers, fixctx, path, basectxs):
593 def fixfile(ui, repo, opts, fixers, fixctx, path, basectxs):
608 """Run any configured fixers that should affect the file in this context
594 """Run any configured fixers that should affect the file in this context
609
595
610 Returns the file content that results from applying the fixers in some order
596 Returns the file content that results from applying the fixers in some order
611 starting with the file's content in the fixctx. Fixers that support line
597 starting with the file's content in the fixctx. Fixers that support line
612 ranges will affect lines that have changed relative to any of the basectxs
598 ranges will affect lines that have changed relative to any of the basectxs
613 (i.e. they will only avoid lines that are common to all basectxs).
599 (i.e. they will only avoid lines that are common to all basectxs).
614
600
615 A fixer tool's stdout will become the file's new content if and only if it
601 A fixer tool's stdout will become the file's new content if and only if it
616 exits with code zero. The fixer tool's working directory is the repository's
602 exits with code zero. The fixer tool's working directory is the repository's
617 root.
603 root.
618 """
604 """
619 metadata = {}
605 metadata = {}
620 newdata = fixctx[path].data()
606 newdata = fixctx[path].data()
621 for fixername, fixer in pycompat.iteritems(fixers):
607 for fixername, fixer in pycompat.iteritems(fixers):
622 if fixer.affects(opts, fixctx, path):
608 if fixer.affects(opts, fixctx, path):
623 ranges = lineranges(opts, path, basectxs, fixctx, newdata)
609 ranges = lineranges(opts, path, basectxs, fixctx, newdata)
624 command = fixer.command(ui, path, ranges)
610 command = fixer.command(ui, path, ranges)
625 if command is None:
611 if command is None:
626 continue
612 continue
627 ui.debug(b'subprocess: %s\n' % (command,))
613 ui.debug(b'subprocess: %s\n' % (command,))
628 proc = subprocess.Popen(
614 proc = subprocess.Popen(
629 procutil.tonativestr(command),
615 procutil.tonativestr(command),
630 shell=True,
616 shell=True,
631 cwd=procutil.tonativestr(repo.root),
617 cwd=procutil.tonativestr(repo.root),
632 stdin=subprocess.PIPE,
618 stdin=subprocess.PIPE,
633 stdout=subprocess.PIPE,
619 stdout=subprocess.PIPE,
634 stderr=subprocess.PIPE,
620 stderr=subprocess.PIPE,
635 )
621 )
636 stdout, stderr = proc.communicate(newdata)
622 stdout, stderr = proc.communicate(newdata)
637 if stderr:
623 if stderr:
638 showstderr(ui, fixctx.rev(), fixername, stderr)
624 showstderr(ui, fixctx.rev(), fixername, stderr)
639 newerdata = stdout
625 newerdata = stdout
640 if fixer.shouldoutputmetadata():
626 if fixer.shouldoutputmetadata():
641 try:
627 try:
642 metadatajson, newerdata = stdout.split(b'\0', 1)
628 metadatajson, newerdata = stdout.split(b'\0', 1)
643 metadata[fixername] = pycompat.json_loads(metadatajson)
629 metadata[fixername] = pycompat.json_loads(metadatajson)
644 except ValueError:
630 except ValueError:
645 ui.warn(
631 ui.warn(
646 _(b'ignored invalid output from fixer tool: %s\n')
632 _(b'ignored invalid output from fixer tool: %s\n')
647 % (fixername,)
633 % (fixername,)
648 )
634 )
649 continue
635 continue
650 else:
636 else:
651 metadata[fixername] = None
637 metadata[fixername] = None
652 if proc.returncode == 0:
638 if proc.returncode == 0:
653 newdata = newerdata
639 newdata = newerdata
654 else:
640 else:
655 if not stderr:
641 if not stderr:
656 message = _(b'exited with status %d\n') % (proc.returncode,)
642 message = _(b'exited with status %d\n') % (proc.returncode,)
657 showstderr(ui, fixctx.rev(), fixername, message)
643 showstderr(ui, fixctx.rev(), fixername, message)
658 checktoolfailureaction(
644 checktoolfailureaction(
659 ui,
645 ui,
660 _(b'no fixes will be applied'),
646 _(b'no fixes will be applied'),
661 hint=_(
647 hint=_(
662 b'use --config fix.failure=continue to apply any '
648 b'use --config fix.failure=continue to apply any '
663 b'successful fixes anyway'
649 b'successful fixes anyway'
664 ),
650 ),
665 )
651 )
666 return metadata, newdata
652 return metadata, newdata
667
653
668
654
669 def showstderr(ui, rev, fixername, stderr):
655 def showstderr(ui, rev, fixername, stderr):
670 """Writes the lines of the stderr string as warnings on the ui
656 """Writes the lines of the stderr string as warnings on the ui
671
657
672 Uses the revision number and fixername to give more context to each line of
658 Uses the revision number and fixername to give more context to each line of
673 the error message. Doesn't include file names, since those take up a lot of
659 the error message. Doesn't include file names, since those take up a lot of
674 space and would tend to be included in the error message if they were
660 space and would tend to be included in the error message if they were
675 relevant.
661 relevant.
676 """
662 """
677 for line in re.split(b'[\r\n]+', stderr):
663 for line in re.split(b'[\r\n]+', stderr):
678 if line:
664 if line:
679 ui.warn(b'[')
665 ui.warn(b'[')
680 if rev is None:
666 if rev is None:
681 ui.warn(_(b'wdir'), label=b'evolve.rev')
667 ui.warn(_(b'wdir'), label=b'evolve.rev')
682 else:
668 else:
683 ui.warn(b'%d' % rev, label=b'evolve.rev')
669 ui.warn(b'%d' % rev, label=b'evolve.rev')
684 ui.warn(b'] %s: %s\n' % (fixername, line))
670 ui.warn(b'] %s: %s\n' % (fixername, line))
685
671
686
672
687 def writeworkingdir(repo, ctx, filedata, replacements):
673 def writeworkingdir(repo, ctx, filedata, replacements):
688 """Write new content to the working copy and check out the new p1 if any
674 """Write new content to the working copy and check out the new p1 if any
689
675
690 We check out a new revision if and only if we fixed something in both the
676 We check out a new revision if and only if we fixed something in both the
691 working directory and its parent revision. This avoids the need for a full
677 working directory and its parent revision. This avoids the need for a full
692 update/merge, and means that the working directory simply isn't affected
678 update/merge, and means that the working directory simply isn't affected
693 unless the --working-dir flag is given.
679 unless the --working-dir flag is given.
694
680
695 Directly updates the dirstate for the affected files.
681 Directly updates the dirstate for the affected files.
696 """
682 """
697 for path, data in pycompat.iteritems(filedata):
683 for path, data in pycompat.iteritems(filedata):
698 fctx = ctx[path]
684 fctx = ctx[path]
699 fctx.write(data, fctx.flags())
685 fctx.write(data, fctx.flags())
700 if repo.dirstate[path] == b'n':
686 if repo.dirstate[path] == b'n':
701 repo.dirstate.normallookup(path)
687 repo.dirstate.normallookup(path)
702
688
703 oldparentnodes = repo.dirstate.parents()
689 oldparentnodes = repo.dirstate.parents()
704 newparentnodes = [replacements.get(n, n) for n in oldparentnodes]
690 newparentnodes = [replacements.get(n, n) for n in oldparentnodes]
705 if newparentnodes != oldparentnodes:
691 if newparentnodes != oldparentnodes:
706 repo.setparents(*newparentnodes)
692 repo.setparents(*newparentnodes)
707
693
708
694
709 def replacerev(ui, repo, ctx, filedata, replacements):
695 def replacerev(ui, repo, ctx, filedata, replacements):
710 """Commit a new revision like the given one, but with file content changes
696 """Commit a new revision like the given one, but with file content changes
711
697
712 "ctx" is the original revision to be replaced by a modified one.
698 "ctx" is the original revision to be replaced by a modified one.
713
699
714 "filedata" is a dict that maps paths to their new file content. All other
700 "filedata" is a dict that maps paths to their new file content. All other
715 paths will be recreated from the original revision without changes.
701 paths will be recreated from the original revision without changes.
716 "filedata" may contain paths that didn't exist in the original revision;
702 "filedata" may contain paths that didn't exist in the original revision;
717 they will be added.
703 they will be added.
718
704
719 "replacements" is a dict that maps a single node to a single node, and it is
705 "replacements" is a dict that maps a single node to a single node, and it is
720 updated to indicate the original revision is replaced by the newly created
706 updated to indicate the original revision is replaced by the newly created
721 one. No entry is added if the replacement's node already exists.
707 one. No entry is added if the replacement's node already exists.
722
708
723 The new revision has the same parents as the old one, unless those parents
709 The new revision has the same parents as the old one, unless those parents
724 have already been replaced, in which case those replacements are the parents
710 have already been replaced, in which case those replacements are the parents
725 of this new revision. Thus, if revisions are replaced in topological order,
711 of this new revision. Thus, if revisions are replaced in topological order,
726 there is no need to rebase them into the original topology later.
712 there is no need to rebase them into the original topology later.
727 """
713 """
728
714
729 p1rev, p2rev = repo.changelog.parentrevs(ctx.rev())
715 p1rev, p2rev = repo.changelog.parentrevs(ctx.rev())
730 p1ctx, p2ctx = repo[p1rev], repo[p2rev]
716 p1ctx, p2ctx = repo[p1rev], repo[p2rev]
731 newp1node = replacements.get(p1ctx.node(), p1ctx.node())
717 newp1node = replacements.get(p1ctx.node(), p1ctx.node())
732 newp2node = replacements.get(p2ctx.node(), p2ctx.node())
718 newp2node = replacements.get(p2ctx.node(), p2ctx.node())
733
719
734 # We don't want to create a revision that has no changes from the original,
720 # We don't want to create a revision that has no changes from the original,
735 # but we should if the original revision's parent has been replaced.
721 # but we should if the original revision's parent has been replaced.
736 # Otherwise, we would produce an orphan that needs no actual human
722 # Otherwise, we would produce an orphan that needs no actual human
737 # intervention to evolve. We can't rely on commit() to avoid creating the
723 # intervention to evolve. We can't rely on commit() to avoid creating the
738 # un-needed revision because the extra field added below produces a new hash
724 # un-needed revision because the extra field added below produces a new hash
739 # regardless of file content changes.
725 # regardless of file content changes.
740 if (
726 if (
741 not filedata
727 not filedata
742 and p1ctx.node() not in replacements
728 and p1ctx.node() not in replacements
743 and p2ctx.node() not in replacements
729 and p2ctx.node() not in replacements
744 ):
730 ):
745 return
731 return
746
732
747 def filectxfn(repo, memctx, path):
733 def filectxfn(repo, memctx, path):
748 if path not in ctx:
734 if path not in ctx:
749 return None
735 return None
750 fctx = ctx[path]
736 fctx = ctx[path]
751 copysource = fctx.copysource()
737 copysource = fctx.copysource()
752 return context.memfilectx(
738 return context.memfilectx(
753 repo,
739 repo,
754 memctx,
740 memctx,
755 path=fctx.path(),
741 path=fctx.path(),
756 data=filedata.get(path, fctx.data()),
742 data=filedata.get(path, fctx.data()),
757 islink=fctx.islink(),
743 islink=fctx.islink(),
758 isexec=fctx.isexec(),
744 isexec=fctx.isexec(),
759 copysource=copysource,
745 copysource=copysource,
760 )
746 )
761
747
762 extra = ctx.extra().copy()
748 extra = ctx.extra().copy()
763 extra[b'fix_source'] = ctx.hex()
749 extra[b'fix_source'] = ctx.hex()
764
750
765 memctx = context.memctx(
751 memctx = context.memctx(
766 repo,
752 repo,
767 parents=(newp1node, newp2node),
753 parents=(newp1node, newp2node),
768 text=ctx.description(),
754 text=ctx.description(),
769 files=set(ctx.files()) | set(filedata.keys()),
755 files=set(ctx.files()) | set(filedata.keys()),
770 filectxfn=filectxfn,
756 filectxfn=filectxfn,
771 user=ctx.user(),
757 user=ctx.user(),
772 date=ctx.date(),
758 date=ctx.date(),
773 extra=extra,
759 extra=extra,
774 branch=ctx.branch(),
760 branch=ctx.branch(),
775 editor=None,
761 editor=None,
776 )
762 )
777 sucnode = memctx.commit()
763 sucnode = memctx.commit()
778 prenode = ctx.node()
764 prenode = ctx.node()
779 if prenode == sucnode:
765 if prenode == sucnode:
780 ui.debug(b'node %s already existed\n' % (ctx.hex()))
766 ui.debug(b'node %s already existed\n' % (ctx.hex()))
781 else:
767 else:
782 replacements[ctx.node()] = sucnode
768 replacements[ctx.node()] = sucnode
783
769
784
770
785 def getfixers(ui):
771 def getfixers(ui):
786 """Returns a map of configured fixer tools indexed by their names
772 """Returns a map of configured fixer tools indexed by their names
787
773
788 Each value is a Fixer object with methods that implement the behavior of the
774 Each value is a Fixer object with methods that implement the behavior of the
789 fixer's config suboptions. Does not validate the config values.
775 fixer's config suboptions. Does not validate the config values.
790 """
776 """
791 fixers = {}
777 fixers = {}
792 for name in fixernames(ui):
778 for name in fixernames(ui):
793 enabled = ui.configbool(b'fix', name + b':enabled')
779 enabled = ui.configbool(b'fix', name + b':enabled')
794 command = ui.config(b'fix', name + b':command')
780 command = ui.config(b'fix', name + b':command')
795 pattern = ui.config(b'fix', name + b':pattern')
781 pattern = ui.config(b'fix', name + b':pattern')
796 linerange = ui.config(b'fix', name + b':linerange')
782 linerange = ui.config(b'fix', name + b':linerange')
797 priority = ui.configint(b'fix', name + b':priority')
783 priority = ui.configint(b'fix', name + b':priority')
798 metadata = ui.configbool(b'fix', name + b':metadata')
784 metadata = ui.configbool(b'fix', name + b':metadata')
799 skipclean = ui.configbool(b'fix', name + b':skipclean')
785 skipclean = ui.configbool(b'fix', name + b':skipclean')
800 # Don't use a fixer if it has no pattern configured. It would be
786 # Don't use a fixer if it has no pattern configured. It would be
801 # dangerous to let it affect all files. It would be pointless to let it
787 # dangerous to let it affect all files. It would be pointless to let it
802 # affect no files. There is no reasonable subset of files to use as the
788 # affect no files. There is no reasonable subset of files to use as the
803 # default.
789 # default.
804 if command is None:
790 if command is None:
805 ui.warn(
791 ui.warn(
806 _(b'fixer tool has no command configuration: %s\n') % (name,)
792 _(b'fixer tool has no command configuration: %s\n') % (name,)
807 )
793 )
808 elif pattern is None:
794 elif pattern is None:
809 ui.warn(
795 ui.warn(
810 _(b'fixer tool has no pattern configuration: %s\n') % (name,)
796 _(b'fixer tool has no pattern configuration: %s\n') % (name,)
811 )
797 )
812 elif not enabled:
798 elif not enabled:
813 ui.debug(b'ignoring disabled fixer tool: %s\n' % (name,))
799 ui.debug(b'ignoring disabled fixer tool: %s\n' % (name,))
814 else:
800 else:
815 fixers[name] = Fixer(
801 fixers[name] = Fixer(
816 command, pattern, linerange, priority, metadata, skipclean
802 command, pattern, linerange, priority, metadata, skipclean
817 )
803 )
818 return collections.OrderedDict(
804 return collections.OrderedDict(
819 sorted(fixers.items(), key=lambda item: item[1]._priority, reverse=True)
805 sorted(fixers.items(), key=lambda item: item[1]._priority, reverse=True)
820 )
806 )
821
807
822
808
823 def fixernames(ui):
809 def fixernames(ui):
824 """Returns the names of [fix] config options that have suboptions"""
810 """Returns the names of [fix] config options that have suboptions"""
825 names = set()
811 names = set()
826 for k, v in ui.configitems(b'fix'):
812 for k, v in ui.configitems(b'fix'):
827 if b':' in k:
813 if b':' in k:
828 names.add(k.split(b':', 1)[0])
814 names.add(k.split(b':', 1)[0])
829 return names
815 return names
830
816
831
817
832 class Fixer(object):
818 class Fixer(object):
833 """Wraps the raw config values for a fixer with methods"""
819 """Wraps the raw config values for a fixer with methods"""
834
820
835 def __init__(
821 def __init__(
836 self, command, pattern, linerange, priority, metadata, skipclean
822 self, command, pattern, linerange, priority, metadata, skipclean
837 ):
823 ):
838 self._command = command
824 self._command = command
839 self._pattern = pattern
825 self._pattern = pattern
840 self._linerange = linerange
826 self._linerange = linerange
841 self._priority = priority
827 self._priority = priority
842 self._metadata = metadata
828 self._metadata = metadata
843 self._skipclean = skipclean
829 self._skipclean = skipclean
844
830
845 def affects(self, opts, fixctx, path):
831 def affects(self, opts, fixctx, path):
846 """Should this fixer run on the file at the given path and context?"""
832 """Should this fixer run on the file at the given path and context?"""
847 repo = fixctx.repo()
833 repo = fixctx.repo()
848 matcher = matchmod.match(
834 matcher = matchmod.match(
849 repo.root, repo.root, [self._pattern], ctx=fixctx
835 repo.root, repo.root, [self._pattern], ctx=fixctx
850 )
836 )
851 return matcher(path)
837 return matcher(path)
852
838
853 def shouldoutputmetadata(self):
839 def shouldoutputmetadata(self):
854 """Should the stdout of this fixer start with JSON and a null byte?"""
840 """Should the stdout of this fixer start with JSON and a null byte?"""
855 return self._metadata
841 return self._metadata
856
842
857 def command(self, ui, path, ranges):
843 def command(self, ui, path, ranges):
858 """A shell command to use to invoke this fixer on the given file/lines
844 """A shell command to use to invoke this fixer on the given file/lines
859
845
860 May return None if there is no appropriate command to run for the given
846 May return None if there is no appropriate command to run for the given
861 parameters.
847 parameters.
862 """
848 """
863 expand = cmdutil.rendercommandtemplate
849 expand = cmdutil.rendercommandtemplate
864 parts = [
850 parts = [
865 expand(
851 expand(
866 ui,
852 ui,
867 self._command,
853 self._command,
868 {b'rootpath': path, b'basename': os.path.basename(path)},
854 {b'rootpath': path, b'basename': os.path.basename(path)},
869 )
855 )
870 ]
856 ]
871 if self._linerange:
857 if self._linerange:
872 if self._skipclean and not ranges:
858 if self._skipclean and not ranges:
873 # No line ranges to fix, so don't run the fixer.
859 # No line ranges to fix, so don't run the fixer.
874 return None
860 return None
875 for first, last in ranges:
861 for first, last in ranges:
876 parts.append(
862 parts.append(
877 expand(
863 expand(
878 ui, self._linerange, {b'first': first, b'last': last}
864 ui, self._linerange, {b'first': first, b'last': last}
879 )
865 )
880 )
866 )
881 return b' '.join(parts)
867 return b' '.join(parts)
@@ -1,1429 +1,1431 b''
1 A script that implements uppercasing of specific lines in a file. This
1 A script that implements uppercasing of specific lines in a file. This
2 approximates the behavior of code formatters well enough for our tests.
2 approximates the behavior of code formatters well enough for our tests.
3
3
4 $ UPPERCASEPY="$TESTTMP/uppercase.py"
4 $ UPPERCASEPY="$TESTTMP/uppercase.py"
5 $ cat > $UPPERCASEPY <<EOF
5 $ cat > $UPPERCASEPY <<EOF
6 > import sys
6 > import sys
7 > from mercurial.utils.procutil import setbinary
7 > from mercurial.utils.procutil import setbinary
8 > setbinary(sys.stdin)
8 > setbinary(sys.stdin)
9 > setbinary(sys.stdout)
9 > setbinary(sys.stdout)
10 > lines = set()
10 > lines = set()
11 > for arg in sys.argv[1:]:
11 > for arg in sys.argv[1:]:
12 > if arg == 'all':
12 > if arg == 'all':
13 > sys.stdout.write(sys.stdin.read().upper())
13 > sys.stdout.write(sys.stdin.read().upper())
14 > sys.exit(0)
14 > sys.exit(0)
15 > else:
15 > else:
16 > first, last = arg.split('-')
16 > first, last = arg.split('-')
17 > lines.update(range(int(first), int(last) + 1))
17 > lines.update(range(int(first), int(last) + 1))
18 > for i, line in enumerate(sys.stdin.readlines()):
18 > for i, line in enumerate(sys.stdin.readlines()):
19 > if i + 1 in lines:
19 > if i + 1 in lines:
20 > sys.stdout.write(line.upper())
20 > sys.stdout.write(line.upper())
21 > else:
21 > else:
22 > sys.stdout.write(line)
22 > sys.stdout.write(line)
23 > EOF
23 > EOF
24 $ TESTLINES="foo\nbar\nbaz\nqux\n"
24 $ TESTLINES="foo\nbar\nbaz\nqux\n"
25 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY
25 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY
26 foo
26 foo
27 bar
27 bar
28 baz
28 baz
29 qux
29 qux
30 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY all
30 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY all
31 FOO
31 FOO
32 BAR
32 BAR
33 BAZ
33 BAZ
34 QUX
34 QUX
35 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 1-1
35 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 1-1
36 FOO
36 FOO
37 bar
37 bar
38 baz
38 baz
39 qux
39 qux
40 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 1-2
40 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 1-2
41 FOO
41 FOO
42 BAR
42 BAR
43 baz
43 baz
44 qux
44 qux
45 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 2-3
45 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 2-3
46 foo
46 foo
47 BAR
47 BAR
48 BAZ
48 BAZ
49 qux
49 qux
50 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 2-2 4-4
50 $ printf $TESTLINES | "$PYTHON" $UPPERCASEPY 2-2 4-4
51 foo
51 foo
52 BAR
52 BAR
53 baz
53 baz
54 QUX
54 QUX
55
55
56 Set up the config with two simple fixers: one that fixes specific line ranges,
56 Set up the config with two simple fixers: one that fixes specific line ranges,
57 and one that always fixes the whole file. They both "fix" files by converting
57 and one that always fixes the whole file. They both "fix" files by converting
58 letters to uppercase. They use different file extensions, so each test case can
58 letters to uppercase. They use different file extensions, so each test case can
59 choose which behavior to use by naming files.
59 choose which behavior to use by naming files.
60
60
61 $ cat >> $HGRCPATH <<EOF
61 $ cat >> $HGRCPATH <<EOF
62 > [extensions]
62 > [extensions]
63 > fix =
63 > fix =
64 > [experimental]
64 > [experimental]
65 > evolution.createmarkers=True
65 > evolution.createmarkers=True
66 > evolution.allowunstable=True
66 > evolution.allowunstable=True
67 > [fix]
67 > [fix]
68 > uppercase-whole-file:command="$PYTHON" $UPPERCASEPY all
68 > uppercase-whole-file:command="$PYTHON" $UPPERCASEPY all
69 > uppercase-whole-file:pattern=set:**.whole
69 > uppercase-whole-file:pattern=set:**.whole
70 > uppercase-changed-lines:command="$PYTHON" $UPPERCASEPY
70 > uppercase-changed-lines:command="$PYTHON" $UPPERCASEPY
71 > uppercase-changed-lines:linerange={first}-{last}
71 > uppercase-changed-lines:linerange={first}-{last}
72 > uppercase-changed-lines:pattern=set:**.changed
72 > uppercase-changed-lines:pattern=set:**.changed
73 > EOF
73 > EOF
74
74
75 Help text for fix.
75 Help text for fix.
76
76
77 $ hg help fix
77 $ hg help fix
78 hg fix [OPTION]... [FILE]...
78 hg fix [OPTION]... [FILE]...
79
79
80 rewrite file content in changesets or working directory
80 rewrite file content in changesets or working directory
81
81
82 Runs any configured tools to fix the content of files. Only affects files
82 Runs any configured tools to fix the content of files. Only affects files
83 with changes, unless file arguments are provided. Only affects changed
83 with changes, unless file arguments are provided. Only affects changed
84 lines of files, unless the --whole flag is used. Some tools may always
84 lines of files, unless the --whole flag is used. Some tools may always
85 affect the whole file regardless of --whole.
85 affect the whole file regardless of --whole.
86
86
87 If revisions are specified with --rev, those revisions will be checked,
87 If revisions are specified with --rev, those revisions will be checked,
88 and they may be replaced with new revisions that have fixed file content.
88 and they may be replaced with new revisions that have fixed file content.
89 It is desirable to specify all descendants of each specified revision, so
89 It is desirable to specify all descendants of each specified revision, so
90 that the fixes propagate to the descendants. If all descendants are fixed
90 that the fixes propagate to the descendants. If all descendants are fixed
91 at the same time, no merging, rebasing, or evolution will be required.
91 at the same time, no merging, rebasing, or evolution will be required.
92
92
93 If --working-dir is used, files with uncommitted changes in the working
93 If --working-dir is used, files with uncommitted changes in the working
94 copy will be fixed. If the checked-out revision is also fixed, the working
94 copy will be fixed. If the checked-out revision is also fixed, the working
95 directory will update to the replacement revision.
95 directory will update to the replacement revision.
96
96
97 When determining what lines of each file to fix at each revision, the
97 When determining what lines of each file to fix at each revision, the
98 whole set of revisions being fixed is considered, so that fixes to earlier
98 whole set of revisions being fixed is considered, so that fixes to earlier
99 revisions are not forgotten in later ones. The --base flag can be used to
99 revisions are not forgotten in later ones. The --base flag can be used to
100 override this default behavior, though it is not usually desirable to do
100 override this default behavior, though it is not usually desirable to do
101 so.
101 so.
102
102
103 (use 'hg help -e fix' to show help for the fix extension)
103 (use 'hg help -e fix' to show help for the fix extension)
104
104
105 options ([+] can be repeated):
105 options ([+] can be repeated):
106
106
107 --all fix all non-public non-obsolete revisions
107 --all fix all non-public non-obsolete revisions
108 --base REV [+] revisions to diff against (overrides automatic selection,
108 --base REV [+] revisions to diff against (overrides automatic selection,
109 and applies to every revision being fixed)
109 and applies to every revision being fixed)
110 -r --rev REV [+] revisions to fix
110 -r --rev REV [+] revisions to fix
111 -w --working-dir fix the working directory
111 -w --working-dir fix the working directory
112 --whole always fix every line of a file
112 --whole always fix every line of a file
113
113
114 (some details hidden, use --verbose to show complete help)
114 (some details hidden, use --verbose to show complete help)
115
115
116 $ hg help -e fix
116 $ hg help -e fix
117 fix extension - rewrite file content in changesets or working copy
117 fix extension - rewrite file content in changesets or working copy
118 (EXPERIMENTAL)
118 (EXPERIMENTAL)
119
119
120 Provides a command that runs configured tools on the contents of modified
120 Provides a command that runs configured tools on the contents of modified
121 files, writing back any fixes to the working copy or replacing changesets.
121 files, writing back any fixes to the working copy or replacing changesets.
122
122
123 Here is an example configuration that causes 'hg fix' to apply automatic
123 Here is an example configuration that causes 'hg fix' to apply automatic
124 formatting fixes to modified lines in C++ code:
124 formatting fixes to modified lines in C++ code:
125
125
126 [fix]
126 [fix]
127 clang-format:command=clang-format --assume-filename={rootpath}
127 clang-format:command=clang-format --assume-filename={rootpath}
128 clang-format:linerange=--lines={first}:{last}
128 clang-format:linerange=--lines={first}:{last}
129 clang-format:pattern=set:**.cpp or **.hpp
129 clang-format:pattern=set:**.cpp or **.hpp
130
130
131 The :command suboption forms the first part of the shell command that will be
131 The :command suboption forms the first part of the shell command that will be
132 used to fix a file. The content of the file is passed on standard input, and
132 used to fix a file. The content of the file is passed on standard input, and
133 the fixed file content is expected on standard output. Any output on standard
133 the fixed file content is expected on standard output. Any output on standard
134 error will be displayed as a warning. If the exit status is not zero, the file
134 error will be displayed as a warning. If the exit status is not zero, the file
135 will not be affected. A placeholder warning is displayed if there is a non-
135 will not be affected. A placeholder warning is displayed if there is a non-
136 zero exit status but no standard error output. Some values may be substituted
136 zero exit status but no standard error output. Some values may be substituted
137 into the command:
137 into the command:
138
138
139 {rootpath} The path of the file being fixed, relative to the repo root
139 {rootpath} The path of the file being fixed, relative to the repo root
140 {basename} The name of the file being fixed, without the directory path
140 {basename} The name of the file being fixed, without the directory path
141
141
142 If the :linerange suboption is set, the tool will only be run if there are
142 If the :linerange suboption is set, the tool will only be run if there are
143 changed lines in a file. The value of this suboption is appended to the shell
143 changed lines in a file. The value of this suboption is appended to the shell
144 command once for every range of changed lines in the file. Some values may be
144 command once for every range of changed lines in the file. Some values may be
145 substituted into the command:
145 substituted into the command:
146
146
147 {first} The 1-based line number of the first line in the modified range
147 {first} The 1-based line number of the first line in the modified range
148 {last} The 1-based line number of the last line in the modified range
148 {last} The 1-based line number of the last line in the modified range
149
149
150 Deleted sections of a file will be ignored by :linerange, because there is no
150 Deleted sections of a file will be ignored by :linerange, because there is no
151 corresponding line range in the version being fixed.
151 corresponding line range in the version being fixed.
152
152
153 By default, tools that set :linerange will only be executed if there is at
153 By default, tools that set :linerange will only be executed if there is at
154 least one changed line range. This is meant to prevent accidents like running
154 least one changed line range. This is meant to prevent accidents like running
155 a code formatter in such a way that it unexpectedly reformats the whole file.
155 a code formatter in such a way that it unexpectedly reformats the whole file.
156 If such a tool needs to operate on unchanged files, it should set the
156 If such a tool needs to operate on unchanged files, it should set the
157 :skipclean suboption to false.
157 :skipclean suboption to false.
158
158
159 The :pattern suboption determines which files will be passed through each
159 The :pattern suboption determines which files will be passed through each
160 configured tool. See 'hg help patterns' for possible values. However, all
160 configured tool. See 'hg help patterns' for possible values. However, all
161 patterns are relative to the repo root, even if that text says they are
161 patterns are relative to the repo root, even if that text says they are
162 relative to the current working directory. If there are file arguments to 'hg
162 relative to the current working directory. If there are file arguments to 'hg
163 fix', the intersection of these patterns is used.
163 fix', the intersection of these patterns is used.
164
164
165 There is also a configurable limit for the maximum size of file that will be
165 There is also a configurable limit for the maximum size of file that will be
166 processed by 'hg fix':
166 processed by 'hg fix':
167
167
168 [fix]
168 [fix]
169 maxfilesize = 2MB
169 maxfilesize = 2MB
170
170
171 Normally, execution of configured tools will continue after a failure
171 Normally, execution of configured tools will continue after a failure
172 (indicated by a non-zero exit status). It can also be configured to abort
172 (indicated by a non-zero exit status). It can also be configured to abort
173 after the first such failure, so that no files will be affected if any tool
173 after the first such failure, so that no files will be affected if any tool
174 fails. This abort will also cause 'hg fix' to exit with a non-zero status:
174 fails. This abort will also cause 'hg fix' to exit with a non-zero status:
175
175
176 [fix]
176 [fix]
177 failure = abort
177 failure = abort
178
178
179 When multiple tools are configured to affect a file, they execute in an order
179 When multiple tools are configured to affect a file, they execute in an order
180 defined by the :priority suboption. The priority suboption has a default value
180 defined by the :priority suboption. The priority suboption has a default value
181 of zero for each tool. Tools are executed in order of descending priority. The
181 of zero for each tool. Tools are executed in order of descending priority. The
182 execution order of tools with equal priority is unspecified. For example, you
182 execution order of tools with equal priority is unspecified. For example, you
183 could use the 'sort' and 'head' utilities to keep only the 10 smallest numbers
183 could use the 'sort' and 'head' utilities to keep only the 10 smallest numbers
184 in a text file by ensuring that 'sort' runs before 'head':
184 in a text file by ensuring that 'sort' runs before 'head':
185
185
186 [fix]
186 [fix]
187 sort:command = sort -n
187 sort:command = sort -n
188 head:command = head -n 10
188 head:command = head -n 10
189 sort:pattern = numbers.txt
189 sort:pattern = numbers.txt
190 head:pattern = numbers.txt
190 head:pattern = numbers.txt
191 sort:priority = 2
191 sort:priority = 2
192 head:priority = 1
192 head:priority = 1
193
193
194 To account for changes made by each tool, the line numbers used for
194 To account for changes made by each tool, the line numbers used for
195 incremental formatting are recomputed before executing the next tool. So, each
195 incremental formatting are recomputed before executing the next tool. So, each
196 tool may see different values for the arguments added by the :linerange
196 tool may see different values for the arguments added by the :linerange
197 suboption.
197 suboption.
198
198
199 Each fixer tool is allowed to return some metadata in addition to the fixed
199 Each fixer tool is allowed to return some metadata in addition to the fixed
200 file content. The metadata must be placed before the file content on stdout,
200 file content. The metadata must be placed before the file content on stdout,
201 separated from the file content by a zero byte. The metadata is parsed as a
201 separated from the file content by a zero byte. The metadata is parsed as a
202 JSON value (so, it should be UTF-8 encoded and contain no zero bytes). A fixer
202 JSON value (so, it should be UTF-8 encoded and contain no zero bytes). A fixer
203 tool is expected to produce this metadata encoding if and only if the
203 tool is expected to produce this metadata encoding if and only if the
204 :metadata suboption is true:
204 :metadata suboption is true:
205
205
206 [fix]
206 [fix]
207 tool:command = tool --prepend-json-metadata
207 tool:command = tool --prepend-json-metadata
208 tool:metadata = true
208 tool:metadata = true
209
209
210 The metadata values are passed to hooks, which can be used to print summaries
210 The metadata values are passed to hooks, which can be used to print summaries
211 or perform other post-fixing work. The supported hooks are:
211 or perform other post-fixing work. The supported hooks are:
212
212
213 "postfixfile"
213 "postfixfile"
214 Run once for each file in each revision where any fixer tools made changes
214 Run once for each file in each revision where any fixer tools made changes
215 to the file content. Provides "$HG_REV" and "$HG_PATH" to identify the file,
215 to the file content. Provides "$HG_REV" and "$HG_PATH" to identify the file,
216 and "$HG_METADATA" with a map of fixer names to metadata values from fixer
216 and "$HG_METADATA" with a map of fixer names to metadata values from fixer
217 tools that affected the file. Fixer tools that didn't affect the file have a
217 tools that affected the file. Fixer tools that didn't affect the file have a
218 valueof None. Only fixer tools that executed are present in the metadata.
218 valueof None. Only fixer tools that executed are present in the metadata.
219
219
220 "postfix"
220 "postfix"
221 Run once after all files and revisions have been handled. Provides
221 Run once after all files and revisions have been handled. Provides
222 "$HG_REPLACEMENTS" with information about what revisions were created and
222 "$HG_REPLACEMENTS" with information about what revisions were created and
223 made obsolete. Provides a boolean "$HG_WDIRWRITTEN" to indicate whether any
223 made obsolete. Provides a boolean "$HG_WDIRWRITTEN" to indicate whether any
224 files in the working copy were updated. Provides a list "$HG_METADATA"
224 files in the working copy were updated. Provides a list "$HG_METADATA"
225 mapping fixer tool names to lists of metadata values returned from
225 mapping fixer tool names to lists of metadata values returned from
226 executions that modified a file. This aggregates the same metadata
226 executions that modified a file. This aggregates the same metadata
227 previously passed to the "postfixfile" hook.
227 previously passed to the "postfixfile" hook.
228
228
229 Fixer tools are run the in repository's root directory. This allows them to
229 Fixer tools are run the in repository's root directory. This allows them to
230 read configuration files from the working copy, or even write to the working
230 read configuration files from the working copy, or even write to the working
231 copy. The working copy is not updated to match the revision being fixed. In
231 copy. The working copy is not updated to match the revision being fixed. In
232 fact, several revisions may be fixed in parallel. Writes to the working copy
232 fact, several revisions may be fixed in parallel. Writes to the working copy
233 are not amended into the revision being fixed; fixer tools should always write
233 are not amended into the revision being fixed; fixer tools should always write
234 fixed file content back to stdout as documented above.
234 fixed file content back to stdout as documented above.
235
235
236 list of commands:
236 list of commands:
237
237
238 fix rewrite file content in changesets or working directory
238 fix rewrite file content in changesets or working directory
239
239
240 (use 'hg help -v -e fix' to show built-in aliases and global options)
240 (use 'hg help -v -e fix' to show built-in aliases and global options)
241
241
242 There is no default behavior in the absence of --rev and --working-dir.
242 There is no default behavior in the absence of --rev and --working-dir.
243
243
244 $ hg init badusage
244 $ hg init badusage
245 $ cd badusage
245 $ cd badusage
246
246
247 $ hg fix
247 $ hg fix
248 abort: no changesets specified
248 abort: no changesets specified
249 (use --rev or --working-dir)
249 (use --rev or --working-dir)
250 [255]
250 [255]
251 $ hg fix --whole
251 $ hg fix --whole
252 abort: no changesets specified
252 abort: no changesets specified
253 (use --rev or --working-dir)
253 (use --rev or --working-dir)
254 [255]
254 [255]
255 $ hg fix --base 0
255 $ hg fix --base 0
256 abort: no changesets specified
256 abort: no changesets specified
257 (use --rev or --working-dir)
257 (use --rev or --working-dir)
258 [255]
258 [255]
259
259
260 Fixing a public revision isn't allowed. It should abort early enough that
260 Fixing a public revision isn't allowed. It should abort early enough that
261 nothing happens, even to the working directory.
261 nothing happens, even to the working directory.
262
262
263 $ printf "hello\n" > hello.whole
263 $ printf "hello\n" > hello.whole
264 $ hg commit -Aqm "hello"
264 $ hg commit -Aqm "hello"
265 $ hg phase -r 0 --public
265 $ hg phase -r 0 --public
266 $ hg fix -r 0
266 $ hg fix -r 0
267 abort: can't fix immutable changeset 0:6470986d2e7b
267 abort: cannot fix public changesets
268 (see 'hg help phases' for details)
268 [255]
269 [255]
269 $ hg fix -r 0 --working-dir
270 $ hg fix -r 0 --working-dir
270 abort: can't fix immutable changeset 0:6470986d2e7b
271 abort: cannot fix public changesets
272 (see 'hg help phases' for details)
271 [255]
273 [255]
272 $ hg cat -r tip hello.whole
274 $ hg cat -r tip hello.whole
273 hello
275 hello
274 $ cat hello.whole
276 $ cat hello.whole
275 hello
277 hello
276
278
277 $ cd ..
279 $ cd ..
278
280
279 Fixing a clean working directory should do nothing. Even the --whole flag
281 Fixing a clean working directory should do nothing. Even the --whole flag
280 shouldn't cause any clean files to be fixed. Specifying a clean file explicitly
282 shouldn't cause any clean files to be fixed. Specifying a clean file explicitly
281 should only fix it if the fixer always fixes the whole file. The combination of
283 should only fix it if the fixer always fixes the whole file. The combination of
282 an explicit filename and --whole should format the entire file regardless.
284 an explicit filename and --whole should format the entire file regardless.
283
285
284 $ hg init fixcleanwdir
286 $ hg init fixcleanwdir
285 $ cd fixcleanwdir
287 $ cd fixcleanwdir
286
288
287 $ printf "hello\n" > hello.changed
289 $ printf "hello\n" > hello.changed
288 $ printf "world\n" > hello.whole
290 $ printf "world\n" > hello.whole
289 $ hg commit -Aqm "foo"
291 $ hg commit -Aqm "foo"
290 $ hg fix --working-dir
292 $ hg fix --working-dir
291 $ hg diff
293 $ hg diff
292 $ hg fix --working-dir --whole
294 $ hg fix --working-dir --whole
293 $ hg diff
295 $ hg diff
294 $ hg fix --working-dir *
296 $ hg fix --working-dir *
295 $ cat *
297 $ cat *
296 hello
298 hello
297 WORLD
299 WORLD
298 $ hg revert --all --no-backup
300 $ hg revert --all --no-backup
299 reverting hello.whole
301 reverting hello.whole
300 $ hg fix --working-dir * --whole
302 $ hg fix --working-dir * --whole
301 $ cat *
303 $ cat *
302 HELLO
304 HELLO
303 WORLD
305 WORLD
304
306
305 The same ideas apply to fixing a revision, so we create a revision that doesn't
307 The same ideas apply to fixing a revision, so we create a revision that doesn't
306 modify either of the files in question and try fixing it. This also tests that
308 modify either of the files in question and try fixing it. This also tests that
307 we ignore a file that doesn't match any configured fixer.
309 we ignore a file that doesn't match any configured fixer.
308
310
309 $ hg revert --all --no-backup
311 $ hg revert --all --no-backup
310 reverting hello.changed
312 reverting hello.changed
311 reverting hello.whole
313 reverting hello.whole
312 $ printf "unimportant\n" > some.file
314 $ printf "unimportant\n" > some.file
313 $ hg commit -Aqm "some other file"
315 $ hg commit -Aqm "some other file"
314
316
315 $ hg fix -r .
317 $ hg fix -r .
316 $ hg cat -r tip *
318 $ hg cat -r tip *
317 hello
319 hello
318 world
320 world
319 unimportant
321 unimportant
320 $ hg fix -r . --whole
322 $ hg fix -r . --whole
321 $ hg cat -r tip *
323 $ hg cat -r tip *
322 hello
324 hello
323 world
325 world
324 unimportant
326 unimportant
325 $ hg fix -r . *
327 $ hg fix -r . *
326 $ hg cat -r tip *
328 $ hg cat -r tip *
327 hello
329 hello
328 WORLD
330 WORLD
329 unimportant
331 unimportant
330 $ hg fix -r . * --whole --config experimental.evolution.allowdivergence=true
332 $ hg fix -r . * --whole --config experimental.evolution.allowdivergence=true
331 2 new content-divergent changesets
333 2 new content-divergent changesets
332 $ hg cat -r tip *
334 $ hg cat -r tip *
333 HELLO
335 HELLO
334 WORLD
336 WORLD
335 unimportant
337 unimportant
336
338
337 $ cd ..
339 $ cd ..
338
340
339 Fixing the working directory should still work if there are no revisions.
341 Fixing the working directory should still work if there are no revisions.
340
342
341 $ hg init norevisions
343 $ hg init norevisions
342 $ cd norevisions
344 $ cd norevisions
343
345
344 $ printf "something\n" > something.whole
346 $ printf "something\n" > something.whole
345 $ hg add
347 $ hg add
346 adding something.whole
348 adding something.whole
347 $ hg fix --working-dir
349 $ hg fix --working-dir
348 $ cat something.whole
350 $ cat something.whole
349 SOMETHING
351 SOMETHING
350
352
351 $ cd ..
353 $ cd ..
352
354
353 Test the effect of fixing the working directory for each possible status, with
355 Test the effect of fixing the working directory for each possible status, with
354 and without providing explicit file arguments.
356 and without providing explicit file arguments.
355
357
356 $ hg init implicitlyfixstatus
358 $ hg init implicitlyfixstatus
357 $ cd implicitlyfixstatus
359 $ cd implicitlyfixstatus
358
360
359 $ printf "modified\n" > modified.whole
361 $ printf "modified\n" > modified.whole
360 $ printf "removed\n" > removed.whole
362 $ printf "removed\n" > removed.whole
361 $ printf "deleted\n" > deleted.whole
363 $ printf "deleted\n" > deleted.whole
362 $ printf "clean\n" > clean.whole
364 $ printf "clean\n" > clean.whole
363 $ printf "ignored.whole" > .hgignore
365 $ printf "ignored.whole" > .hgignore
364 $ hg commit -Aqm "stuff"
366 $ hg commit -Aqm "stuff"
365
367
366 $ printf "modified!!!\n" > modified.whole
368 $ printf "modified!!!\n" > modified.whole
367 $ printf "unknown\n" > unknown.whole
369 $ printf "unknown\n" > unknown.whole
368 $ printf "ignored\n" > ignored.whole
370 $ printf "ignored\n" > ignored.whole
369 $ printf "added\n" > added.whole
371 $ printf "added\n" > added.whole
370 $ hg add added.whole
372 $ hg add added.whole
371 $ hg remove removed.whole
373 $ hg remove removed.whole
372 $ rm deleted.whole
374 $ rm deleted.whole
373
375
374 $ hg status --all
376 $ hg status --all
375 M modified.whole
377 M modified.whole
376 A added.whole
378 A added.whole
377 R removed.whole
379 R removed.whole
378 ! deleted.whole
380 ! deleted.whole
379 ? unknown.whole
381 ? unknown.whole
380 I ignored.whole
382 I ignored.whole
381 C .hgignore
383 C .hgignore
382 C clean.whole
384 C clean.whole
383
385
384 $ hg fix --working-dir
386 $ hg fix --working-dir
385
387
386 $ hg status --all
388 $ hg status --all
387 M modified.whole
389 M modified.whole
388 A added.whole
390 A added.whole
389 R removed.whole
391 R removed.whole
390 ! deleted.whole
392 ! deleted.whole
391 ? unknown.whole
393 ? unknown.whole
392 I ignored.whole
394 I ignored.whole
393 C .hgignore
395 C .hgignore
394 C clean.whole
396 C clean.whole
395
397
396 $ cat *.whole
398 $ cat *.whole
397 ADDED
399 ADDED
398 clean
400 clean
399 ignored
401 ignored
400 MODIFIED!!!
402 MODIFIED!!!
401 unknown
403 unknown
402
404
403 $ printf "modified!!!\n" > modified.whole
405 $ printf "modified!!!\n" > modified.whole
404 $ printf "added\n" > added.whole
406 $ printf "added\n" > added.whole
405
407
406 Listing the files explicitly causes untracked files to also be fixed, but
408 Listing the files explicitly causes untracked files to also be fixed, but
407 ignored files are still unaffected.
409 ignored files are still unaffected.
408
410
409 $ hg fix --working-dir *.whole
411 $ hg fix --working-dir *.whole
410
412
411 $ hg status --all
413 $ hg status --all
412 M clean.whole
414 M clean.whole
413 M modified.whole
415 M modified.whole
414 A added.whole
416 A added.whole
415 R removed.whole
417 R removed.whole
416 ! deleted.whole
418 ! deleted.whole
417 ? unknown.whole
419 ? unknown.whole
418 I ignored.whole
420 I ignored.whole
419 C .hgignore
421 C .hgignore
420
422
421 $ cat *.whole
423 $ cat *.whole
422 ADDED
424 ADDED
423 CLEAN
425 CLEAN
424 ignored
426 ignored
425 MODIFIED!!!
427 MODIFIED!!!
426 UNKNOWN
428 UNKNOWN
427
429
428 $ cd ..
430 $ cd ..
429
431
430 Test that incremental fixing works on files with additions, deletions, and
432 Test that incremental fixing works on files with additions, deletions, and
431 changes in multiple line ranges. Note that deletions do not generally cause
433 changes in multiple line ranges. Note that deletions do not generally cause
432 neighboring lines to be fixed, so we don't return a line range for purely
434 neighboring lines to be fixed, so we don't return a line range for purely
433 deleted sections. In the future we should support a :deletion config that
435 deleted sections. In the future we should support a :deletion config that
434 allows fixers to know where deletions are located.
436 allows fixers to know where deletions are located.
435
437
436 $ hg init incrementalfixedlines
438 $ hg init incrementalfixedlines
437 $ cd incrementalfixedlines
439 $ cd incrementalfixedlines
438
440
439 $ printf "a\nb\nc\nd\ne\nf\ng\n" > foo.txt
441 $ printf "a\nb\nc\nd\ne\nf\ng\n" > foo.txt
440 $ hg commit -Aqm "foo"
442 $ hg commit -Aqm "foo"
441 $ printf "zz\na\nc\ndd\nee\nff\nf\ngg\n" > foo.txt
443 $ printf "zz\na\nc\ndd\nee\nff\nf\ngg\n" > foo.txt
442
444
443 $ hg --config "fix.fail:command=echo" \
445 $ hg --config "fix.fail:command=echo" \
444 > --config "fix.fail:linerange={first}:{last}" \
446 > --config "fix.fail:linerange={first}:{last}" \
445 > --config "fix.fail:pattern=foo.txt" \
447 > --config "fix.fail:pattern=foo.txt" \
446 > fix --working-dir
448 > fix --working-dir
447 $ cat foo.txt
449 $ cat foo.txt
448 1:1 4:6 8:8
450 1:1 4:6 8:8
449
451
450 $ cd ..
452 $ cd ..
451
453
452 Test that --whole fixes all lines regardless of the diffs present.
454 Test that --whole fixes all lines regardless of the diffs present.
453
455
454 $ hg init wholeignoresdiffs
456 $ hg init wholeignoresdiffs
455 $ cd wholeignoresdiffs
457 $ cd wholeignoresdiffs
456
458
457 $ printf "a\nb\nc\nd\ne\nf\ng\n" > foo.changed
459 $ printf "a\nb\nc\nd\ne\nf\ng\n" > foo.changed
458 $ hg commit -Aqm "foo"
460 $ hg commit -Aqm "foo"
459 $ printf "zz\na\nc\ndd\nee\nff\nf\ngg\n" > foo.changed
461 $ printf "zz\na\nc\ndd\nee\nff\nf\ngg\n" > foo.changed
460
462
461 $ hg fix --working-dir
463 $ hg fix --working-dir
462 $ cat foo.changed
464 $ cat foo.changed
463 ZZ
465 ZZ
464 a
466 a
465 c
467 c
466 DD
468 DD
467 EE
469 EE
468 FF
470 FF
469 f
471 f
470 GG
472 GG
471
473
472 $ hg fix --working-dir --whole
474 $ hg fix --working-dir --whole
473 $ cat foo.changed
475 $ cat foo.changed
474 ZZ
476 ZZ
475 A
477 A
476 C
478 C
477 DD
479 DD
478 EE
480 EE
479 FF
481 FF
480 F
482 F
481 GG
483 GG
482
484
483 $ cd ..
485 $ cd ..
484
486
485 We should do nothing with symlinks, and their targets should be unaffected. Any
487 We should do nothing with symlinks, and their targets should be unaffected. Any
486 other behavior would be more complicated to implement and harder to document.
488 other behavior would be more complicated to implement and harder to document.
487
489
488 #if symlink
490 #if symlink
489 $ hg init dontmesswithsymlinks
491 $ hg init dontmesswithsymlinks
490 $ cd dontmesswithsymlinks
492 $ cd dontmesswithsymlinks
491
493
492 $ printf "hello\n" > hello.whole
494 $ printf "hello\n" > hello.whole
493 $ ln -s hello.whole hellolink
495 $ ln -s hello.whole hellolink
494 $ hg add
496 $ hg add
495 adding hello.whole
497 adding hello.whole
496 adding hellolink
498 adding hellolink
497 $ hg fix --working-dir hellolink
499 $ hg fix --working-dir hellolink
498 $ hg status
500 $ hg status
499 A hello.whole
501 A hello.whole
500 A hellolink
502 A hellolink
501
503
502 $ cd ..
504 $ cd ..
503 #endif
505 #endif
504
506
505 We should allow fixers to run on binary files, even though this doesn't sound
507 We should allow fixers to run on binary files, even though this doesn't sound
506 like a common use case. There's not much benefit to disallowing it, and users
508 like a common use case. There's not much benefit to disallowing it, and users
507 can add "and not binary()" to their filesets if needed. The Mercurial
509 can add "and not binary()" to their filesets if needed. The Mercurial
508 philosophy is generally to not handle binary files specially anyway.
510 philosophy is generally to not handle binary files specially anyway.
509
511
510 $ hg init cantouchbinaryfiles
512 $ hg init cantouchbinaryfiles
511 $ cd cantouchbinaryfiles
513 $ cd cantouchbinaryfiles
512
514
513 $ printf "hello\0\n" > hello.whole
515 $ printf "hello\0\n" > hello.whole
514 $ hg add
516 $ hg add
515 adding hello.whole
517 adding hello.whole
516 $ hg fix --working-dir 'set:binary()'
518 $ hg fix --working-dir 'set:binary()'
517 $ cat hello.whole
519 $ cat hello.whole
518 HELLO\x00 (esc)
520 HELLO\x00 (esc)
519
521
520 $ cd ..
522 $ cd ..
521
523
522 We have a config for the maximum size of file we will attempt to fix. This can
524 We have a config for the maximum size of file we will attempt to fix. This can
523 be helpful to avoid running unsuspecting fixer tools on huge inputs, which
525 be helpful to avoid running unsuspecting fixer tools on huge inputs, which
524 could happen by accident without a well considered configuration. A more
526 could happen by accident without a well considered configuration. A more
525 precise configuration could use the size() fileset function if one global limit
527 precise configuration could use the size() fileset function if one global limit
526 is undesired.
528 is undesired.
527
529
528 $ hg init maxfilesize
530 $ hg init maxfilesize
529 $ cd maxfilesize
531 $ cd maxfilesize
530
532
531 $ printf "this file is huge\n" > hello.whole
533 $ printf "this file is huge\n" > hello.whole
532 $ hg add
534 $ hg add
533 adding hello.whole
535 adding hello.whole
534 $ hg --config fix.maxfilesize=10 fix --working-dir
536 $ hg --config fix.maxfilesize=10 fix --working-dir
535 ignoring file larger than 10 bytes: hello.whole
537 ignoring file larger than 10 bytes: hello.whole
536 $ cat hello.whole
538 $ cat hello.whole
537 this file is huge
539 this file is huge
538
540
539 $ cd ..
541 $ cd ..
540
542
541 If we specify a file to fix, other files should be left alone, even if they
543 If we specify a file to fix, other files should be left alone, even if they
542 have changes.
544 have changes.
543
545
544 $ hg init fixonlywhatitellyouto
546 $ hg init fixonlywhatitellyouto
545 $ cd fixonlywhatitellyouto
547 $ cd fixonlywhatitellyouto
546
548
547 $ printf "fix me!\n" > fixme.whole
549 $ printf "fix me!\n" > fixme.whole
548 $ printf "not me.\n" > notme.whole
550 $ printf "not me.\n" > notme.whole
549 $ hg add
551 $ hg add
550 adding fixme.whole
552 adding fixme.whole
551 adding notme.whole
553 adding notme.whole
552 $ hg fix --working-dir fixme.whole
554 $ hg fix --working-dir fixme.whole
553 $ cat *.whole
555 $ cat *.whole
554 FIX ME!
556 FIX ME!
555 not me.
557 not me.
556
558
557 $ cd ..
559 $ cd ..
558
560
559 If we try to fix a missing file, we still fix other files.
561 If we try to fix a missing file, we still fix other files.
560
562
561 $ hg init fixmissingfile
563 $ hg init fixmissingfile
562 $ cd fixmissingfile
564 $ cd fixmissingfile
563
565
564 $ printf "fix me!\n" > foo.whole
566 $ printf "fix me!\n" > foo.whole
565 $ hg add
567 $ hg add
566 adding foo.whole
568 adding foo.whole
567 $ hg fix --working-dir foo.whole bar.whole
569 $ hg fix --working-dir foo.whole bar.whole
568 bar.whole: $ENOENT$
570 bar.whole: $ENOENT$
569 $ cat *.whole
571 $ cat *.whole
570 FIX ME!
572 FIX ME!
571
573
572 $ cd ..
574 $ cd ..
573
575
574 Specifying a directory name should fix all its files and subdirectories.
576 Specifying a directory name should fix all its files and subdirectories.
575
577
576 $ hg init fixdirectory
578 $ hg init fixdirectory
577 $ cd fixdirectory
579 $ cd fixdirectory
578
580
579 $ mkdir -p dir1/dir2
581 $ mkdir -p dir1/dir2
580 $ printf "foo\n" > foo.whole
582 $ printf "foo\n" > foo.whole
581 $ printf "bar\n" > dir1/bar.whole
583 $ printf "bar\n" > dir1/bar.whole
582 $ printf "baz\n" > dir1/dir2/baz.whole
584 $ printf "baz\n" > dir1/dir2/baz.whole
583 $ hg add
585 $ hg add
584 adding dir1/bar.whole
586 adding dir1/bar.whole
585 adding dir1/dir2/baz.whole
587 adding dir1/dir2/baz.whole
586 adding foo.whole
588 adding foo.whole
587 $ hg fix --working-dir dir1
589 $ hg fix --working-dir dir1
588 $ cat foo.whole dir1/bar.whole dir1/dir2/baz.whole
590 $ cat foo.whole dir1/bar.whole dir1/dir2/baz.whole
589 foo
591 foo
590 BAR
592 BAR
591 BAZ
593 BAZ
592
594
593 $ cd ..
595 $ cd ..
594
596
595 Fixing a file in the working directory that needs no fixes should not actually
597 Fixing a file in the working directory that needs no fixes should not actually
596 write back to the file, so for example the mtime shouldn't change.
598 write back to the file, so for example the mtime shouldn't change.
597
599
598 $ hg init donttouchunfixedfiles
600 $ hg init donttouchunfixedfiles
599 $ cd donttouchunfixedfiles
601 $ cd donttouchunfixedfiles
600
602
601 $ printf "NO FIX NEEDED\n" > foo.whole
603 $ printf "NO FIX NEEDED\n" > foo.whole
602 $ hg add
604 $ hg add
603 adding foo.whole
605 adding foo.whole
604 $ cp -p foo.whole foo.whole.orig
606 $ cp -p foo.whole foo.whole.orig
605 $ cp -p foo.whole.orig foo.whole
607 $ cp -p foo.whole.orig foo.whole
606 $ sleep 2 # mtime has a resolution of one or two seconds.
608 $ sleep 2 # mtime has a resolution of one or two seconds.
607 $ hg fix --working-dir
609 $ hg fix --working-dir
608 $ f foo.whole.orig --newer foo.whole
610 $ f foo.whole.orig --newer foo.whole
609 foo.whole.orig: newer than foo.whole
611 foo.whole.orig: newer than foo.whole
610
612
611 $ cd ..
613 $ cd ..
612
614
613 When a fixer prints to stderr, we don't assume that it has failed. We show the
615 When a fixer prints to stderr, we don't assume that it has failed. We show the
614 error messages to the user, and we still let the fixer affect the file it was
616 error messages to the user, and we still let the fixer affect the file it was
615 fixing if its exit code is zero. Some code formatters might emit error messages
617 fixing if its exit code is zero. Some code formatters might emit error messages
616 on stderr and nothing on stdout, which would cause us the clear the file,
618 on stderr and nothing on stdout, which would cause us the clear the file,
617 except that they also exit with a non-zero code. We show the user which fixer
619 except that they also exit with a non-zero code. We show the user which fixer
618 emitted the stderr, and which revision, but we assume that the fixer will print
620 emitted the stderr, and which revision, but we assume that the fixer will print
619 the filename if it is relevant (since the issue may be non-specific). There is
621 the filename if it is relevant (since the issue may be non-specific). There is
620 also a config to abort (without affecting any files whatsoever) if we see any
622 also a config to abort (without affecting any files whatsoever) if we see any
621 tool with a non-zero exit status.
623 tool with a non-zero exit status.
622
624
623 $ hg init showstderr
625 $ hg init showstderr
624 $ cd showstderr
626 $ cd showstderr
625
627
626 $ printf "hello\n" > hello.txt
628 $ printf "hello\n" > hello.txt
627 $ hg add
629 $ hg add
628 adding hello.txt
630 adding hello.txt
629 $ cat > $TESTTMP/work.sh <<'EOF'
631 $ cat > $TESTTMP/work.sh <<'EOF'
630 > printf 'HELLO\n'
632 > printf 'HELLO\n'
631 > printf "$@: some\nerror that didn't stop the tool" >&2
633 > printf "$@: some\nerror that didn't stop the tool" >&2
632 > exit 0 # success despite the stderr output
634 > exit 0 # success despite the stderr output
633 > EOF
635 > EOF
634 $ hg --config "fix.work:command=sh $TESTTMP/work.sh {rootpath}" \
636 $ hg --config "fix.work:command=sh $TESTTMP/work.sh {rootpath}" \
635 > --config "fix.work:pattern=hello.txt" \
637 > --config "fix.work:pattern=hello.txt" \
636 > fix --working-dir
638 > fix --working-dir
637 [wdir] work: hello.txt: some
639 [wdir] work: hello.txt: some
638 [wdir] work: error that didn't stop the tool
640 [wdir] work: error that didn't stop the tool
639 $ cat hello.txt
641 $ cat hello.txt
640 HELLO
642 HELLO
641
643
642 $ printf "goodbye\n" > hello.txt
644 $ printf "goodbye\n" > hello.txt
643 $ printf "foo\n" > foo.whole
645 $ printf "foo\n" > foo.whole
644 $ hg add
646 $ hg add
645 adding foo.whole
647 adding foo.whole
646 $ cat > $TESTTMP/fail.sh <<'EOF'
648 $ cat > $TESTTMP/fail.sh <<'EOF'
647 > printf 'GOODBYE\n'
649 > printf 'GOODBYE\n'
648 > printf "$@: some\nerror that did stop the tool\n" >&2
650 > printf "$@: some\nerror that did stop the tool\n" >&2
649 > exit 42 # success despite the stdout output
651 > exit 42 # success despite the stdout output
650 > EOF
652 > EOF
651 $ hg --config "fix.fail:command=sh $TESTTMP/fail.sh {rootpath}" \
653 $ hg --config "fix.fail:command=sh $TESTTMP/fail.sh {rootpath}" \
652 > --config "fix.fail:pattern=hello.txt" \
654 > --config "fix.fail:pattern=hello.txt" \
653 > --config "fix.failure=abort" \
655 > --config "fix.failure=abort" \
654 > fix --working-dir
656 > fix --working-dir
655 [wdir] fail: hello.txt: some
657 [wdir] fail: hello.txt: some
656 [wdir] fail: error that did stop the tool
658 [wdir] fail: error that did stop the tool
657 abort: no fixes will be applied
659 abort: no fixes will be applied
658 (use --config fix.failure=continue to apply any successful fixes anyway)
660 (use --config fix.failure=continue to apply any successful fixes anyway)
659 [255]
661 [255]
660 $ cat hello.txt
662 $ cat hello.txt
661 goodbye
663 goodbye
662 $ cat foo.whole
664 $ cat foo.whole
663 foo
665 foo
664
666
665 $ hg --config "fix.fail:command=sh $TESTTMP/fail.sh {rootpath}" \
667 $ hg --config "fix.fail:command=sh $TESTTMP/fail.sh {rootpath}" \
666 > --config "fix.fail:pattern=hello.txt" \
668 > --config "fix.fail:pattern=hello.txt" \
667 > fix --working-dir
669 > fix --working-dir
668 [wdir] fail: hello.txt: some
670 [wdir] fail: hello.txt: some
669 [wdir] fail: error that did stop the tool
671 [wdir] fail: error that did stop the tool
670 $ cat hello.txt
672 $ cat hello.txt
671 goodbye
673 goodbye
672 $ cat foo.whole
674 $ cat foo.whole
673 FOO
675 FOO
674
676
675 $ hg --config "fix.fail:command=exit 42" \
677 $ hg --config "fix.fail:command=exit 42" \
676 > --config "fix.fail:pattern=hello.txt" \
678 > --config "fix.fail:pattern=hello.txt" \
677 > fix --working-dir
679 > fix --working-dir
678 [wdir] fail: exited with status 42
680 [wdir] fail: exited with status 42
679
681
680 $ cd ..
682 $ cd ..
681
683
682 Fixing the working directory and its parent revision at the same time should
684 Fixing the working directory and its parent revision at the same time should
683 check out the replacement revision for the parent. This prevents any new
685 check out the replacement revision for the parent. This prevents any new
684 uncommitted changes from appearing. We test this for a clean working directory
686 uncommitted changes from appearing. We test this for a clean working directory
685 and a dirty one. In both cases, all lines/files changed since the grandparent
687 and a dirty one. In both cases, all lines/files changed since the grandparent
686 will be fixed. The grandparent is the "baserev" for both the parent and the
688 will be fixed. The grandparent is the "baserev" for both the parent and the
687 working copy.
689 working copy.
688
690
689 $ hg init fixdotandcleanwdir
691 $ hg init fixdotandcleanwdir
690 $ cd fixdotandcleanwdir
692 $ cd fixdotandcleanwdir
691
693
692 $ printf "hello\n" > hello.whole
694 $ printf "hello\n" > hello.whole
693 $ printf "world\n" > world.whole
695 $ printf "world\n" > world.whole
694 $ hg commit -Aqm "the parent commit"
696 $ hg commit -Aqm "the parent commit"
695
697
696 $ hg parents --template '{rev} {desc}\n'
698 $ hg parents --template '{rev} {desc}\n'
697 0 the parent commit
699 0 the parent commit
698 $ hg fix --working-dir -r .
700 $ hg fix --working-dir -r .
699 $ hg parents --template '{rev} {desc}\n'
701 $ hg parents --template '{rev} {desc}\n'
700 1 the parent commit
702 1 the parent commit
701 $ hg cat -r . *.whole
703 $ hg cat -r . *.whole
702 HELLO
704 HELLO
703 WORLD
705 WORLD
704 $ cat *.whole
706 $ cat *.whole
705 HELLO
707 HELLO
706 WORLD
708 WORLD
707 $ hg status
709 $ hg status
708
710
709 $ cd ..
711 $ cd ..
710
712
711 Same test with a dirty working copy.
713 Same test with a dirty working copy.
712
714
713 $ hg init fixdotanddirtywdir
715 $ hg init fixdotanddirtywdir
714 $ cd fixdotanddirtywdir
716 $ cd fixdotanddirtywdir
715
717
716 $ printf "hello\n" > hello.whole
718 $ printf "hello\n" > hello.whole
717 $ printf "world\n" > world.whole
719 $ printf "world\n" > world.whole
718 $ hg commit -Aqm "the parent commit"
720 $ hg commit -Aqm "the parent commit"
719
721
720 $ printf "hello,\n" > hello.whole
722 $ printf "hello,\n" > hello.whole
721 $ printf "world!\n" > world.whole
723 $ printf "world!\n" > world.whole
722
724
723 $ hg parents --template '{rev} {desc}\n'
725 $ hg parents --template '{rev} {desc}\n'
724 0 the parent commit
726 0 the parent commit
725 $ hg fix --working-dir -r .
727 $ hg fix --working-dir -r .
726 $ hg parents --template '{rev} {desc}\n'
728 $ hg parents --template '{rev} {desc}\n'
727 1 the parent commit
729 1 the parent commit
728 $ hg cat -r . *.whole
730 $ hg cat -r . *.whole
729 HELLO
731 HELLO
730 WORLD
732 WORLD
731 $ cat *.whole
733 $ cat *.whole
732 HELLO,
734 HELLO,
733 WORLD!
735 WORLD!
734 $ hg status
736 $ hg status
735 M hello.whole
737 M hello.whole
736 M world.whole
738 M world.whole
737
739
738 $ cd ..
740 $ cd ..
739
741
740 When we have a chain of commits that change mutually exclusive lines of code,
742 When we have a chain of commits that change mutually exclusive lines of code,
741 we should be able to do incremental fixing that causes each commit in the chain
743 we should be able to do incremental fixing that causes each commit in the chain
742 to include fixes made to the previous commits. This prevents children from
744 to include fixes made to the previous commits. This prevents children from
743 backing out the fixes made in their parents. A dirty working directory is
745 backing out the fixes made in their parents. A dirty working directory is
744 conceptually similar to another commit in the chain.
746 conceptually similar to another commit in the chain.
745
747
746 $ hg init incrementallyfixchain
748 $ hg init incrementallyfixchain
747 $ cd incrementallyfixchain
749 $ cd incrementallyfixchain
748
750
749 $ cat > file.changed <<EOF
751 $ cat > file.changed <<EOF
750 > first
752 > first
751 > second
753 > second
752 > third
754 > third
753 > fourth
755 > fourth
754 > fifth
756 > fifth
755 > EOF
757 > EOF
756 $ hg commit -Aqm "the common ancestor (the baserev)"
758 $ hg commit -Aqm "the common ancestor (the baserev)"
757 $ cat > file.changed <<EOF
759 $ cat > file.changed <<EOF
758 > first (changed)
760 > first (changed)
759 > second
761 > second
760 > third
762 > third
761 > fourth
763 > fourth
762 > fifth
764 > fifth
763 > EOF
765 > EOF
764 $ hg commit -Aqm "the first commit to fix"
766 $ hg commit -Aqm "the first commit to fix"
765 $ cat > file.changed <<EOF
767 $ cat > file.changed <<EOF
766 > first (changed)
768 > first (changed)
767 > second
769 > second
768 > third (changed)
770 > third (changed)
769 > fourth
771 > fourth
770 > fifth
772 > fifth
771 > EOF
773 > EOF
772 $ hg commit -Aqm "the second commit to fix"
774 $ hg commit -Aqm "the second commit to fix"
773 $ cat > file.changed <<EOF
775 $ cat > file.changed <<EOF
774 > first (changed)
776 > first (changed)
775 > second
777 > second
776 > third (changed)
778 > third (changed)
777 > fourth
779 > fourth
778 > fifth (changed)
780 > fifth (changed)
779 > EOF
781 > EOF
780
782
781 $ hg fix -r . -r '.^' --working-dir
783 $ hg fix -r . -r '.^' --working-dir
782
784
783 $ hg parents --template '{rev}\n'
785 $ hg parents --template '{rev}\n'
784 4
786 4
785 $ hg cat -r '.^^' file.changed
787 $ hg cat -r '.^^' file.changed
786 first
788 first
787 second
789 second
788 third
790 third
789 fourth
791 fourth
790 fifth
792 fifth
791 $ hg cat -r '.^' file.changed
793 $ hg cat -r '.^' file.changed
792 FIRST (CHANGED)
794 FIRST (CHANGED)
793 second
795 second
794 third
796 third
795 fourth
797 fourth
796 fifth
798 fifth
797 $ hg cat -r . file.changed
799 $ hg cat -r . file.changed
798 FIRST (CHANGED)
800 FIRST (CHANGED)
799 second
801 second
800 THIRD (CHANGED)
802 THIRD (CHANGED)
801 fourth
803 fourth
802 fifth
804 fifth
803 $ cat file.changed
805 $ cat file.changed
804 FIRST (CHANGED)
806 FIRST (CHANGED)
805 second
807 second
806 THIRD (CHANGED)
808 THIRD (CHANGED)
807 fourth
809 fourth
808 FIFTH (CHANGED)
810 FIFTH (CHANGED)
809
811
810 $ cd ..
812 $ cd ..
811
813
812 If we incrementally fix a merge commit, we should fix any lines that changed
814 If we incrementally fix a merge commit, we should fix any lines that changed
813 versus either parent. You could imagine only fixing the intersection or some
815 versus either parent. You could imagine only fixing the intersection or some
814 other subset, but this is necessary if either parent is being fixed. It
816 other subset, but this is necessary if either parent is being fixed. It
815 prevents us from forgetting fixes made in either parent.
817 prevents us from forgetting fixes made in either parent.
816
818
817 $ hg init incrementallyfixmergecommit
819 $ hg init incrementallyfixmergecommit
818 $ cd incrementallyfixmergecommit
820 $ cd incrementallyfixmergecommit
819
821
820 $ printf "a\nb\nc\n" > file.changed
822 $ printf "a\nb\nc\n" > file.changed
821 $ hg commit -Aqm "ancestor"
823 $ hg commit -Aqm "ancestor"
822
824
823 $ printf "aa\nb\nc\n" > file.changed
825 $ printf "aa\nb\nc\n" > file.changed
824 $ hg commit -m "change a"
826 $ hg commit -m "change a"
825
827
826 $ hg checkout '.^'
828 $ hg checkout '.^'
827 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
829 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
828 $ printf "a\nb\ncc\n" > file.changed
830 $ printf "a\nb\ncc\n" > file.changed
829 $ hg commit -m "change c"
831 $ hg commit -m "change c"
830 created new head
832 created new head
831
833
832 $ hg merge
834 $ hg merge
833 merging file.changed
835 merging file.changed
834 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
836 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
835 (branch merge, don't forget to commit)
837 (branch merge, don't forget to commit)
836 $ hg commit -m "merge"
838 $ hg commit -m "merge"
837 $ hg cat -r . file.changed
839 $ hg cat -r . file.changed
838 aa
840 aa
839 b
841 b
840 cc
842 cc
841
843
842 $ hg fix -r . --working-dir
844 $ hg fix -r . --working-dir
843 $ hg cat -r . file.changed
845 $ hg cat -r . file.changed
844 AA
846 AA
845 b
847 b
846 CC
848 CC
847
849
848 $ cd ..
850 $ cd ..
849
851
850 Abort fixing revisions if there is an unfinished operation. We don't want to
852 Abort fixing revisions if there is an unfinished operation. We don't want to
851 make things worse by editing files or stripping/obsoleting things. Also abort
853 make things worse by editing files or stripping/obsoleting things. Also abort
852 fixing the working directory if there are unresolved merge conflicts.
854 fixing the working directory if there are unresolved merge conflicts.
853
855
854 $ hg init abortunresolved
856 $ hg init abortunresolved
855 $ cd abortunresolved
857 $ cd abortunresolved
856
858
857 $ echo "foo1" > foo.whole
859 $ echo "foo1" > foo.whole
858 $ hg commit -Aqm "foo 1"
860 $ hg commit -Aqm "foo 1"
859
861
860 $ hg update null
862 $ hg update null
861 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
863 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
862 $ echo "foo2" > foo.whole
864 $ echo "foo2" > foo.whole
863 $ hg commit -Aqm "foo 2"
865 $ hg commit -Aqm "foo 2"
864
866
865 $ hg --config extensions.rebase= rebase -r 1 -d 0
867 $ hg --config extensions.rebase= rebase -r 1 -d 0
866 rebasing 1:c3b6dc0e177a "foo 2" (tip)
868 rebasing 1:c3b6dc0e177a "foo 2" (tip)
867 merging foo.whole
869 merging foo.whole
868 warning: conflicts while merging foo.whole! (edit, then use 'hg resolve --mark')
870 warning: conflicts while merging foo.whole! (edit, then use 'hg resolve --mark')
869 unresolved conflicts (see hg resolve, then hg rebase --continue)
871 unresolved conflicts (see hg resolve, then hg rebase --continue)
870 [1]
872 [1]
871
873
872 $ hg --config extensions.rebase= fix --working-dir
874 $ hg --config extensions.rebase= fix --working-dir
873 abort: unresolved conflicts
875 abort: unresolved conflicts
874 (use 'hg resolve')
876 (use 'hg resolve')
875 [255]
877 [255]
876
878
877 $ hg --config extensions.rebase= fix -r .
879 $ hg --config extensions.rebase= fix -r .
878 abort: rebase in progress
880 abort: rebase in progress
879 (use 'hg rebase --continue' or 'hg rebase --abort')
881 (use 'hg rebase --continue' or 'hg rebase --abort')
880 [255]
882 [255]
881
883
882 $ cd ..
884 $ cd ..
883
885
884 When fixing a file that was renamed, we should diff against the source of the
886 When fixing a file that was renamed, we should diff against the source of the
885 rename for incremental fixing and we should correctly reproduce the rename in
887 rename for incremental fixing and we should correctly reproduce the rename in
886 the replacement revision.
888 the replacement revision.
887
889
888 $ hg init fixrenamecommit
890 $ hg init fixrenamecommit
889 $ cd fixrenamecommit
891 $ cd fixrenamecommit
890
892
891 $ printf "a\nb\nc\n" > source.changed
893 $ printf "a\nb\nc\n" > source.changed
892 $ hg commit -Aqm "source revision"
894 $ hg commit -Aqm "source revision"
893 $ hg move source.changed dest.changed
895 $ hg move source.changed dest.changed
894 $ printf "a\nb\ncc\n" > dest.changed
896 $ printf "a\nb\ncc\n" > dest.changed
895 $ hg commit -m "dest revision"
897 $ hg commit -m "dest revision"
896
898
897 $ hg fix -r .
899 $ hg fix -r .
898 $ hg log -r tip --copies --template "{file_copies}\n"
900 $ hg log -r tip --copies --template "{file_copies}\n"
899 dest.changed (source.changed)
901 dest.changed (source.changed)
900 $ hg cat -r tip dest.changed
902 $ hg cat -r tip dest.changed
901 a
903 a
902 b
904 b
903 CC
905 CC
904
906
905 $ cd ..
907 $ cd ..
906
908
907 When fixing revisions that remove files we must ensure that the replacement
909 When fixing revisions that remove files we must ensure that the replacement
908 actually removes the file, whereas it could accidentally leave it unchanged or
910 actually removes the file, whereas it could accidentally leave it unchanged or
909 write an empty string to it.
911 write an empty string to it.
910
912
911 $ hg init fixremovedfile
913 $ hg init fixremovedfile
912 $ cd fixremovedfile
914 $ cd fixremovedfile
913
915
914 $ printf "foo\n" > foo.whole
916 $ printf "foo\n" > foo.whole
915 $ printf "bar\n" > bar.whole
917 $ printf "bar\n" > bar.whole
916 $ hg commit -Aqm "add files"
918 $ hg commit -Aqm "add files"
917 $ hg remove bar.whole
919 $ hg remove bar.whole
918 $ hg commit -m "remove file"
920 $ hg commit -m "remove file"
919 $ hg status --change .
921 $ hg status --change .
920 R bar.whole
922 R bar.whole
921 $ hg fix -r . foo.whole
923 $ hg fix -r . foo.whole
922 $ hg status --change tip
924 $ hg status --change tip
923 M foo.whole
925 M foo.whole
924 R bar.whole
926 R bar.whole
925
927
926 $ cd ..
928 $ cd ..
927
929
928 If fixing a revision finds no fixes to make, no replacement revision should be
930 If fixing a revision finds no fixes to make, no replacement revision should be
929 created.
931 created.
930
932
931 $ hg init nofixesneeded
933 $ hg init nofixesneeded
932 $ cd nofixesneeded
934 $ cd nofixesneeded
933
935
934 $ printf "FOO\n" > foo.whole
936 $ printf "FOO\n" > foo.whole
935 $ hg commit -Aqm "add file"
937 $ hg commit -Aqm "add file"
936 $ hg log --template '{rev}\n'
938 $ hg log --template '{rev}\n'
937 0
939 0
938 $ hg fix -r .
940 $ hg fix -r .
939 $ hg log --template '{rev}\n'
941 $ hg log --template '{rev}\n'
940 0
942 0
941
943
942 $ cd ..
944 $ cd ..
943
945
944 If fixing a commit reverts all the changes in the commit, we replace it with a
946 If fixing a commit reverts all the changes in the commit, we replace it with a
945 commit that changes no files.
947 commit that changes no files.
946
948
947 $ hg init nochangesleft
949 $ hg init nochangesleft
948 $ cd nochangesleft
950 $ cd nochangesleft
949
951
950 $ printf "FOO\n" > foo.whole
952 $ printf "FOO\n" > foo.whole
951 $ hg commit -Aqm "add file"
953 $ hg commit -Aqm "add file"
952 $ printf "foo\n" > foo.whole
954 $ printf "foo\n" > foo.whole
953 $ hg commit -m "edit file"
955 $ hg commit -m "edit file"
954 $ hg status --change .
956 $ hg status --change .
955 M foo.whole
957 M foo.whole
956 $ hg fix -r .
958 $ hg fix -r .
957 $ hg status --change tip
959 $ hg status --change tip
958
960
959 $ cd ..
961 $ cd ..
960
962
961 If we fix a parent and child revision together, the child revision must be
963 If we fix a parent and child revision together, the child revision must be
962 replaced if the parent is replaced, even if the diffs of the child needed no
964 replaced if the parent is replaced, even if the diffs of the child needed no
963 fixes. However, we're free to not replace revisions that need no fixes and have
965 fixes. However, we're free to not replace revisions that need no fixes and have
964 no ancestors that are replaced.
966 no ancestors that are replaced.
965
967
966 $ hg init mustreplacechild
968 $ hg init mustreplacechild
967 $ cd mustreplacechild
969 $ cd mustreplacechild
968
970
969 $ printf "FOO\n" > foo.whole
971 $ printf "FOO\n" > foo.whole
970 $ hg commit -Aqm "add foo"
972 $ hg commit -Aqm "add foo"
971 $ printf "foo\n" > foo.whole
973 $ printf "foo\n" > foo.whole
972 $ hg commit -m "edit foo"
974 $ hg commit -m "edit foo"
973 $ printf "BAR\n" > bar.whole
975 $ printf "BAR\n" > bar.whole
974 $ hg commit -Aqm "add bar"
976 $ hg commit -Aqm "add bar"
975
977
976 $ hg log --graph --template '{rev} {files}'
978 $ hg log --graph --template '{rev} {files}'
977 @ 2 bar.whole
979 @ 2 bar.whole
978 |
980 |
979 o 1 foo.whole
981 o 1 foo.whole
980 |
982 |
981 o 0 foo.whole
983 o 0 foo.whole
982
984
983 $ hg fix -r 0:2
985 $ hg fix -r 0:2
984 $ hg log --graph --template '{rev} {files}'
986 $ hg log --graph --template '{rev} {files}'
985 o 4 bar.whole
987 o 4 bar.whole
986 |
988 |
987 o 3
989 o 3
988 |
990 |
989 | @ 2 bar.whole
991 | @ 2 bar.whole
990 | |
992 | |
991 | x 1 foo.whole
993 | x 1 foo.whole
992 |/
994 |/
993 o 0 foo.whole
995 o 0 foo.whole
994
996
995
997
996 $ cd ..
998 $ cd ..
997
999
998 It's also possible that the child needs absolutely no changes, but we still
1000 It's also possible that the child needs absolutely no changes, but we still
999 need to replace it to update its parent. If we skipped replacing the child
1001 need to replace it to update its parent. If we skipped replacing the child
1000 because it had no file content changes, it would become an orphan for no good
1002 because it had no file content changes, it would become an orphan for no good
1001 reason.
1003 reason.
1002
1004
1003 $ hg init mustreplacechildevenifnop
1005 $ hg init mustreplacechildevenifnop
1004 $ cd mustreplacechildevenifnop
1006 $ cd mustreplacechildevenifnop
1005
1007
1006 $ printf "Foo\n" > foo.whole
1008 $ printf "Foo\n" > foo.whole
1007 $ hg commit -Aqm "add a bad foo"
1009 $ hg commit -Aqm "add a bad foo"
1008 $ printf "FOO\n" > foo.whole
1010 $ printf "FOO\n" > foo.whole
1009 $ hg commit -m "add a good foo"
1011 $ hg commit -m "add a good foo"
1010 $ hg fix -r . -r '.^'
1012 $ hg fix -r . -r '.^'
1011 $ hg log --graph --template '{rev} {desc}'
1013 $ hg log --graph --template '{rev} {desc}'
1012 o 3 add a good foo
1014 o 3 add a good foo
1013 |
1015 |
1014 o 2 add a bad foo
1016 o 2 add a bad foo
1015
1017
1016 @ 1 add a good foo
1018 @ 1 add a good foo
1017 |
1019 |
1018 x 0 add a bad foo
1020 x 0 add a bad foo
1019
1021
1020
1022
1021 $ cd ..
1023 $ cd ..
1022
1024
1023 Similar to the case above, the child revision may become empty as a result of
1025 Similar to the case above, the child revision may become empty as a result of
1024 fixing its parent. We should still create an empty replacement child.
1026 fixing its parent. We should still create an empty replacement child.
1025 TODO: determine how this should interact with ui.allowemptycommit given that
1027 TODO: determine how this should interact with ui.allowemptycommit given that
1026 the empty replacement could have children.
1028 the empty replacement could have children.
1027
1029
1028 $ hg init mustreplacechildevenifempty
1030 $ hg init mustreplacechildevenifempty
1029 $ cd mustreplacechildevenifempty
1031 $ cd mustreplacechildevenifempty
1030
1032
1031 $ printf "foo\n" > foo.whole
1033 $ printf "foo\n" > foo.whole
1032 $ hg commit -Aqm "add foo"
1034 $ hg commit -Aqm "add foo"
1033 $ printf "Foo\n" > foo.whole
1035 $ printf "Foo\n" > foo.whole
1034 $ hg commit -m "edit foo"
1036 $ hg commit -m "edit foo"
1035 $ hg fix -r . -r '.^'
1037 $ hg fix -r . -r '.^'
1036 $ hg log --graph --template '{rev} {desc}\n' --stat
1038 $ hg log --graph --template '{rev} {desc}\n' --stat
1037 o 3 edit foo
1039 o 3 edit foo
1038 |
1040 |
1039 o 2 add foo
1041 o 2 add foo
1040 foo.whole | 1 +
1042 foo.whole | 1 +
1041 1 files changed, 1 insertions(+), 0 deletions(-)
1043 1 files changed, 1 insertions(+), 0 deletions(-)
1042
1044
1043 @ 1 edit foo
1045 @ 1 edit foo
1044 | foo.whole | 2 +-
1046 | foo.whole | 2 +-
1045 | 1 files changed, 1 insertions(+), 1 deletions(-)
1047 | 1 files changed, 1 insertions(+), 1 deletions(-)
1046 |
1048 |
1047 x 0 add foo
1049 x 0 add foo
1048 foo.whole | 1 +
1050 foo.whole | 1 +
1049 1 files changed, 1 insertions(+), 0 deletions(-)
1051 1 files changed, 1 insertions(+), 0 deletions(-)
1050
1052
1051
1053
1052 $ cd ..
1054 $ cd ..
1053
1055
1054 Fixing a secret commit should replace it with another secret commit.
1056 Fixing a secret commit should replace it with another secret commit.
1055
1057
1056 $ hg init fixsecretcommit
1058 $ hg init fixsecretcommit
1057 $ cd fixsecretcommit
1059 $ cd fixsecretcommit
1058
1060
1059 $ printf "foo\n" > foo.whole
1061 $ printf "foo\n" > foo.whole
1060 $ hg commit -Aqm "add foo" --secret
1062 $ hg commit -Aqm "add foo" --secret
1061 $ hg fix -r .
1063 $ hg fix -r .
1062 $ hg log --template '{rev} {phase}\n'
1064 $ hg log --template '{rev} {phase}\n'
1063 1 secret
1065 1 secret
1064 0 secret
1066 0 secret
1065
1067
1066 $ cd ..
1068 $ cd ..
1067
1069
1068 We should also preserve phase when fixing a draft commit while the user has
1070 We should also preserve phase when fixing a draft commit while the user has
1069 their default set to secret.
1071 their default set to secret.
1070
1072
1071 $ hg init respectphasesnewcommit
1073 $ hg init respectphasesnewcommit
1072 $ cd respectphasesnewcommit
1074 $ cd respectphasesnewcommit
1073
1075
1074 $ printf "foo\n" > foo.whole
1076 $ printf "foo\n" > foo.whole
1075 $ hg commit -Aqm "add foo"
1077 $ hg commit -Aqm "add foo"
1076 $ hg --config phases.newcommit=secret fix -r .
1078 $ hg --config phases.newcommit=secret fix -r .
1077 $ hg log --template '{rev} {phase}\n'
1079 $ hg log --template '{rev} {phase}\n'
1078 1 draft
1080 1 draft
1079 0 draft
1081 0 draft
1080
1082
1081 $ cd ..
1083 $ cd ..
1082
1084
1083 Debug output should show what fixer commands are being subprocessed, which is
1085 Debug output should show what fixer commands are being subprocessed, which is
1084 useful for anyone trying to set up a new config.
1086 useful for anyone trying to set up a new config.
1085
1087
1086 $ hg init debugoutput
1088 $ hg init debugoutput
1087 $ cd debugoutput
1089 $ cd debugoutput
1088
1090
1089 $ printf "foo\nbar\nbaz\n" > foo.changed
1091 $ printf "foo\nbar\nbaz\n" > foo.changed
1090 $ hg commit -Aqm "foo"
1092 $ hg commit -Aqm "foo"
1091 $ printf "Foo\nbar\nBaz\n" > foo.changed
1093 $ printf "Foo\nbar\nBaz\n" > foo.changed
1092 $ hg --debug fix --working-dir
1094 $ hg --debug fix --working-dir
1093 subprocess: * $TESTTMP/uppercase.py 1-1 3-3 (glob)
1095 subprocess: * $TESTTMP/uppercase.py 1-1 3-3 (glob)
1094
1096
1095 $ cd ..
1097 $ cd ..
1096
1098
1097 Fixing an obsolete revision can cause divergence, so we abort unless the user
1099 Fixing an obsolete revision can cause divergence, so we abort unless the user
1098 configures to allow it. This is not yet smart enough to know whether there is a
1100 configures to allow it. This is not yet smart enough to know whether there is a
1099 successor, but even then it is not likely intentional or idiomatic to fix an
1101 successor, but even then it is not likely intentional or idiomatic to fix an
1100 obsolete revision.
1102 obsolete revision.
1101
1103
1102 $ hg init abortobsoleterev
1104 $ hg init abortobsoleterev
1103 $ cd abortobsoleterev
1105 $ cd abortobsoleterev
1104
1106
1105 $ printf "foo\n" > foo.changed
1107 $ printf "foo\n" > foo.changed
1106 $ hg commit -Aqm "foo"
1108 $ hg commit -Aqm "foo"
1107 $ hg debugobsolete `hg parents --template '{node}'`
1109 $ hg debugobsolete `hg parents --template '{node}'`
1108 1 new obsolescence markers
1110 1 new obsolescence markers
1109 obsoleted 1 changesets
1111 obsoleted 1 changesets
1110 $ hg --hidden fix -r 0
1112 $ hg --hidden fix -r 0
1111 abort: fixing obsolete revision could cause divergence
1113 abort: fixing obsolete revision could cause divergence
1112 [255]
1114 [255]
1113
1115
1114 $ hg --hidden fix -r 0 --config experimental.evolution.allowdivergence=true
1116 $ hg --hidden fix -r 0 --config experimental.evolution.allowdivergence=true
1115 $ hg cat -r tip foo.changed
1117 $ hg cat -r tip foo.changed
1116 FOO
1118 FOO
1117
1119
1118 $ cd ..
1120 $ cd ..
1119
1121
1120 Test all of the available substitution values for fixer commands.
1122 Test all of the available substitution values for fixer commands.
1121
1123
1122 $ hg init substitution
1124 $ hg init substitution
1123 $ cd substitution
1125 $ cd substitution
1124
1126
1125 $ mkdir foo
1127 $ mkdir foo
1126 $ printf "hello\ngoodbye\n" > foo/bar
1128 $ printf "hello\ngoodbye\n" > foo/bar
1127 $ hg add
1129 $ hg add
1128 adding foo/bar
1130 adding foo/bar
1129 $ hg --config "fix.fail:command=printf '%s\n' '{rootpath}' '{basename}'" \
1131 $ hg --config "fix.fail:command=printf '%s\n' '{rootpath}' '{basename}'" \
1130 > --config "fix.fail:linerange='{first}' '{last}'" \
1132 > --config "fix.fail:linerange='{first}' '{last}'" \
1131 > --config "fix.fail:pattern=foo/bar" \
1133 > --config "fix.fail:pattern=foo/bar" \
1132 > fix --working-dir
1134 > fix --working-dir
1133 $ cat foo/bar
1135 $ cat foo/bar
1134 foo/bar
1136 foo/bar
1135 bar
1137 bar
1136 1
1138 1
1137 2
1139 2
1138
1140
1139 $ cd ..
1141 $ cd ..
1140
1142
1141 The --base flag should allow picking the revisions to diff against for changed
1143 The --base flag should allow picking the revisions to diff against for changed
1142 files and incremental line formatting.
1144 files and incremental line formatting.
1143
1145
1144 $ hg init baseflag
1146 $ hg init baseflag
1145 $ cd baseflag
1147 $ cd baseflag
1146
1148
1147 $ printf "one\ntwo\n" > foo.changed
1149 $ printf "one\ntwo\n" > foo.changed
1148 $ printf "bar\n" > bar.changed
1150 $ printf "bar\n" > bar.changed
1149 $ hg commit -Aqm "first"
1151 $ hg commit -Aqm "first"
1150 $ printf "one\nTwo\n" > foo.changed
1152 $ printf "one\nTwo\n" > foo.changed
1151 $ hg commit -m "second"
1153 $ hg commit -m "second"
1152 $ hg fix -w --base .
1154 $ hg fix -w --base .
1153 $ hg status
1155 $ hg status
1154 $ hg fix -w --base null
1156 $ hg fix -w --base null
1155 $ cat foo.changed
1157 $ cat foo.changed
1156 ONE
1158 ONE
1157 TWO
1159 TWO
1158 $ cat bar.changed
1160 $ cat bar.changed
1159 BAR
1161 BAR
1160
1162
1161 $ cd ..
1163 $ cd ..
1162
1164
1163 If the user asks to fix the parent of another commit, they are asking to create
1165 If the user asks to fix the parent of another commit, they are asking to create
1164 an orphan. We must respect experimental.evolution.allowunstable.
1166 an orphan. We must respect experimental.evolution.allowunstable.
1165
1167
1166 $ hg init allowunstable
1168 $ hg init allowunstable
1167 $ cd allowunstable
1169 $ cd allowunstable
1168
1170
1169 $ printf "one\n" > foo.whole
1171 $ printf "one\n" > foo.whole
1170 $ hg commit -Aqm "first"
1172 $ hg commit -Aqm "first"
1171 $ printf "two\n" > foo.whole
1173 $ printf "two\n" > foo.whole
1172 $ hg commit -m "second"
1174 $ hg commit -m "second"
1173 $ hg --config experimental.evolution.allowunstable=False fix -r '.^'
1175 $ hg --config experimental.evolution.allowunstable=False fix -r '.^'
1174 abort: can only fix a changeset together with all its descendants
1176 abort: cannot fix changeset with children
1175 [255]
1177 [255]
1176 $ hg fix -r '.^'
1178 $ hg fix -r '.^'
1177 1 new orphan changesets
1179 1 new orphan changesets
1178 $ hg cat -r 2 foo.whole
1180 $ hg cat -r 2 foo.whole
1179 ONE
1181 ONE
1180
1182
1181 $ cd ..
1183 $ cd ..
1182
1184
1183 The --base flag affects the set of files being fixed. So while the --whole flag
1185 The --base flag affects the set of files being fixed. So while the --whole flag
1184 makes the base irrelevant for changed line ranges, it still changes the
1186 makes the base irrelevant for changed line ranges, it still changes the
1185 meaning and effect of the command. In this example, no files or lines are fixed
1187 meaning and effect of the command. In this example, no files or lines are fixed
1186 until we specify the base, but then we do fix unchanged lines.
1188 until we specify the base, but then we do fix unchanged lines.
1187
1189
1188 $ hg init basewhole
1190 $ hg init basewhole
1189 $ cd basewhole
1191 $ cd basewhole
1190 $ printf "foo1\n" > foo.changed
1192 $ printf "foo1\n" > foo.changed
1191 $ hg commit -Aqm "first"
1193 $ hg commit -Aqm "first"
1192 $ printf "foo2\n" >> foo.changed
1194 $ printf "foo2\n" >> foo.changed
1193 $ printf "bar\n" > bar.changed
1195 $ printf "bar\n" > bar.changed
1194 $ hg commit -Aqm "second"
1196 $ hg commit -Aqm "second"
1195
1197
1196 $ hg fix --working-dir --whole
1198 $ hg fix --working-dir --whole
1197 $ cat *.changed
1199 $ cat *.changed
1198 bar
1200 bar
1199 foo1
1201 foo1
1200 foo2
1202 foo2
1201
1203
1202 $ hg fix --working-dir --base 0 --whole
1204 $ hg fix --working-dir --base 0 --whole
1203 $ cat *.changed
1205 $ cat *.changed
1204 BAR
1206 BAR
1205 FOO1
1207 FOO1
1206 FOO2
1208 FOO2
1207
1209
1208 $ cd ..
1210 $ cd ..
1209
1211
1210 The execution order of tools can be controlled. This example doesn't work if
1212 The execution order of tools can be controlled. This example doesn't work if
1211 you sort after truncating, but the config defines the correct order while the
1213 you sort after truncating, but the config defines the correct order while the
1212 definitions are out of order (which might imply the incorrect order given the
1214 definitions are out of order (which might imply the incorrect order given the
1213 implementation of fix). The goal is to use multiple tools to select the lowest
1215 implementation of fix). The goal is to use multiple tools to select the lowest
1214 5 numbers in the file.
1216 5 numbers in the file.
1215
1217
1216 $ hg init priorityexample
1218 $ hg init priorityexample
1217 $ cd priorityexample
1219 $ cd priorityexample
1218
1220
1219 $ cat >> .hg/hgrc <<EOF
1221 $ cat >> .hg/hgrc <<EOF
1220 > [fix]
1222 > [fix]
1221 > head:command = head -n 5
1223 > head:command = head -n 5
1222 > head:pattern = numbers.txt
1224 > head:pattern = numbers.txt
1223 > head:priority = 1
1225 > head:priority = 1
1224 > sort:command = sort -n
1226 > sort:command = sort -n
1225 > sort:pattern = numbers.txt
1227 > sort:pattern = numbers.txt
1226 > sort:priority = 2
1228 > sort:priority = 2
1227 > EOF
1229 > EOF
1228
1230
1229 $ printf "8\n2\n3\n6\n7\n4\n9\n5\n1\n0\n" > numbers.txt
1231 $ printf "8\n2\n3\n6\n7\n4\n9\n5\n1\n0\n" > numbers.txt
1230 $ hg add -q
1232 $ hg add -q
1231 $ hg fix -w
1233 $ hg fix -w
1232 $ cat numbers.txt
1234 $ cat numbers.txt
1233 0
1235 0
1234 1
1236 1
1235 2
1237 2
1236 3
1238 3
1237 4
1239 4
1238
1240
1239 And of course we should be able to break this by reversing the execution order.
1241 And of course we should be able to break this by reversing the execution order.
1240 Test negative priorities while we're at it.
1242 Test negative priorities while we're at it.
1241
1243
1242 $ cat >> .hg/hgrc <<EOF
1244 $ cat >> .hg/hgrc <<EOF
1243 > [fix]
1245 > [fix]
1244 > head:priority = -1
1246 > head:priority = -1
1245 > sort:priority = -2
1247 > sort:priority = -2
1246 > EOF
1248 > EOF
1247 $ printf "8\n2\n3\n6\n7\n4\n9\n5\n1\n0\n" > numbers.txt
1249 $ printf "8\n2\n3\n6\n7\n4\n9\n5\n1\n0\n" > numbers.txt
1248 $ hg fix -w
1250 $ hg fix -w
1249 $ cat numbers.txt
1251 $ cat numbers.txt
1250 2
1252 2
1251 3
1253 3
1252 6
1254 6
1253 7
1255 7
1254 8
1256 8
1255
1257
1256 $ cd ..
1258 $ cd ..
1257
1259
1258 It's possible for repeated applications of a fixer tool to create cycles in the
1260 It's possible for repeated applications of a fixer tool to create cycles in the
1259 generated content of a file. For example, two users with different versions of
1261 generated content of a file. For example, two users with different versions of
1260 a code formatter might fight over the formatting when they run hg fix. In the
1262 a code formatter might fight over the formatting when they run hg fix. In the
1261 absence of other changes, this means we could produce commits with the same
1263 absence of other changes, this means we could produce commits with the same
1262 hash in subsequent runs of hg fix. This is a problem unless we support
1264 hash in subsequent runs of hg fix. This is a problem unless we support
1263 obsolescence cycles well. We avoid this by adding an extra field to the
1265 obsolescence cycles well. We avoid this by adding an extra field to the
1264 successor which forces it to have a new hash. That's why this test creates
1266 successor which forces it to have a new hash. That's why this test creates
1265 three revisions instead of two.
1267 three revisions instead of two.
1266
1268
1267 $ hg init cyclictool
1269 $ hg init cyclictool
1268 $ cd cyclictool
1270 $ cd cyclictool
1269
1271
1270 $ cat >> .hg/hgrc <<EOF
1272 $ cat >> .hg/hgrc <<EOF
1271 > [fix]
1273 > [fix]
1272 > swapletters:command = tr ab ba
1274 > swapletters:command = tr ab ba
1273 > swapletters:pattern = foo
1275 > swapletters:pattern = foo
1274 > EOF
1276 > EOF
1275
1277
1276 $ echo ab > foo
1278 $ echo ab > foo
1277 $ hg commit -Aqm foo
1279 $ hg commit -Aqm foo
1278
1280
1279 $ hg fix -r 0
1281 $ hg fix -r 0
1280 $ hg fix -r 1
1282 $ hg fix -r 1
1281
1283
1282 $ hg cat -r 0 foo --hidden
1284 $ hg cat -r 0 foo --hidden
1283 ab
1285 ab
1284 $ hg cat -r 1 foo --hidden
1286 $ hg cat -r 1 foo --hidden
1285 ba
1287 ba
1286 $ hg cat -r 2 foo
1288 $ hg cat -r 2 foo
1287 ab
1289 ab
1288
1290
1289 $ cd ..
1291 $ cd ..
1290
1292
1291 We run fixer tools in the repo root so they can look for config files or other
1293 We run fixer tools in the repo root so they can look for config files or other
1292 important things in the working directory. This does NOT mean we are
1294 important things in the working directory. This does NOT mean we are
1293 reconstructing a working copy of every revision being fixed; we're just giving
1295 reconstructing a working copy of every revision being fixed; we're just giving
1294 the tool knowledge of the repo's location in case it can do something
1296 the tool knowledge of the repo's location in case it can do something
1295 reasonable with that.
1297 reasonable with that.
1296
1298
1297 $ hg init subprocesscwd
1299 $ hg init subprocesscwd
1298 $ cd subprocesscwd
1300 $ cd subprocesscwd
1299
1301
1300 $ cat >> .hg/hgrc <<EOF
1302 $ cat >> .hg/hgrc <<EOF
1301 > [fix]
1303 > [fix]
1302 > printcwd:command = "$PYTHON" -c "import os; print(os.getcwd())"
1304 > printcwd:command = "$PYTHON" -c "import os; print(os.getcwd())"
1303 > printcwd:pattern = relpath:foo/bar
1305 > printcwd:pattern = relpath:foo/bar
1304 > EOF
1306 > EOF
1305
1307
1306 $ mkdir foo
1308 $ mkdir foo
1307 $ printf "bar\n" > foo/bar
1309 $ printf "bar\n" > foo/bar
1308 $ hg commit -Aqm blah
1310 $ hg commit -Aqm blah
1309
1311
1310 $ hg fix -w -r . foo/bar
1312 $ hg fix -w -r . foo/bar
1311 $ hg cat -r tip foo/bar
1313 $ hg cat -r tip foo/bar
1312 $TESTTMP/subprocesscwd
1314 $TESTTMP/subprocesscwd
1313 $ cat foo/bar
1315 $ cat foo/bar
1314 $TESTTMP/subprocesscwd
1316 $TESTTMP/subprocesscwd
1315
1317
1316 $ cd foo
1318 $ cd foo
1317
1319
1318 $ hg fix -w -r . bar
1320 $ hg fix -w -r . bar
1319 $ hg cat -r tip bar
1321 $ hg cat -r tip bar
1320 $TESTTMP/subprocesscwd
1322 $TESTTMP/subprocesscwd
1321 $ cat bar
1323 $ cat bar
1322 $TESTTMP/subprocesscwd
1324 $TESTTMP/subprocesscwd
1323 $ echo modified > bar
1325 $ echo modified > bar
1324 $ hg fix -w bar
1326 $ hg fix -w bar
1325 $ cat bar
1327 $ cat bar
1326 $TESTTMP/subprocesscwd
1328 $TESTTMP/subprocesscwd
1327
1329
1328 $ cd ../..
1330 $ cd ../..
1329
1331
1330 Tools configured without a pattern are ignored. It would be too dangerous to
1332 Tools configured without a pattern are ignored. It would be too dangerous to
1331 run them on all files, because this might happen while testing a configuration
1333 run them on all files, because this might happen while testing a configuration
1332 that also deletes all of the file content. There is no reasonable subset of the
1334 that also deletes all of the file content. There is no reasonable subset of the
1333 files to use as a default. Users should be explicit about what files are
1335 files to use as a default. Users should be explicit about what files are
1334 affected by a tool. This test also confirms that we don't crash when the
1336 affected by a tool. This test also confirms that we don't crash when the
1335 pattern config is missing, and that we only warn about it once.
1337 pattern config is missing, and that we only warn about it once.
1336
1338
1337 $ hg init nopatternconfigured
1339 $ hg init nopatternconfigured
1338 $ cd nopatternconfigured
1340 $ cd nopatternconfigured
1339
1341
1340 $ printf "foo" > foo
1342 $ printf "foo" > foo
1341 $ printf "bar" > bar
1343 $ printf "bar" > bar
1342 $ hg add -q
1344 $ hg add -q
1343 $ hg fix --debug --working-dir --config "fix.nopattern:command=echo fixed"
1345 $ hg fix --debug --working-dir --config "fix.nopattern:command=echo fixed"
1344 fixer tool has no pattern configuration: nopattern
1346 fixer tool has no pattern configuration: nopattern
1345 $ cat foo bar
1347 $ cat foo bar
1346 foobar (no-eol)
1348 foobar (no-eol)
1347 $ hg fix --debug --working-dir --config "fix.nocommand:pattern=foo.bar"
1349 $ hg fix --debug --working-dir --config "fix.nocommand:pattern=foo.bar"
1348 fixer tool has no command configuration: nocommand
1350 fixer tool has no command configuration: nocommand
1349
1351
1350 $ cd ..
1352 $ cd ..
1351
1353
1352 Tools can be disabled. Disabled tools do nothing but print a debug message.
1354 Tools can be disabled. Disabled tools do nothing but print a debug message.
1353
1355
1354 $ hg init disabled
1356 $ hg init disabled
1355 $ cd disabled
1357 $ cd disabled
1356
1358
1357 $ printf "foo\n" > foo
1359 $ printf "foo\n" > foo
1358 $ hg add -q
1360 $ hg add -q
1359 $ hg fix --debug --working-dir --config "fix.disabled:command=echo fixed" \
1361 $ hg fix --debug --working-dir --config "fix.disabled:command=echo fixed" \
1360 > --config "fix.disabled:pattern=foo" \
1362 > --config "fix.disabled:pattern=foo" \
1361 > --config "fix.disabled:enabled=false"
1363 > --config "fix.disabled:enabled=false"
1362 ignoring disabled fixer tool: disabled
1364 ignoring disabled fixer tool: disabled
1363 $ cat foo
1365 $ cat foo
1364 foo
1366 foo
1365
1367
1366 $ cd ..
1368 $ cd ..
1367
1369
1368 Test that we can configure a fixer to affect all files regardless of the cwd.
1370 Test that we can configure a fixer to affect all files regardless of the cwd.
1369 The way we invoke matching must not prohibit this.
1371 The way we invoke matching must not prohibit this.
1370
1372
1371 $ hg init affectallfiles
1373 $ hg init affectallfiles
1372 $ cd affectallfiles
1374 $ cd affectallfiles
1373
1375
1374 $ mkdir foo bar
1376 $ mkdir foo bar
1375 $ printf "foo" > foo/file
1377 $ printf "foo" > foo/file
1376 $ printf "bar" > bar/file
1378 $ printf "bar" > bar/file
1377 $ printf "baz" > baz_file
1379 $ printf "baz" > baz_file
1378 $ hg add -q
1380 $ hg add -q
1379
1381
1380 $ cd bar
1382 $ cd bar
1381 $ hg fix --working-dir --config "fix.cooltool:command=echo fixed" \
1383 $ hg fix --working-dir --config "fix.cooltool:command=echo fixed" \
1382 > --config "fix.cooltool:pattern=glob:**"
1384 > --config "fix.cooltool:pattern=glob:**"
1383 $ cd ..
1385 $ cd ..
1384
1386
1385 $ cat foo/file
1387 $ cat foo/file
1386 fixed
1388 fixed
1387 $ cat bar/file
1389 $ cat bar/file
1388 fixed
1390 fixed
1389 $ cat baz_file
1391 $ cat baz_file
1390 fixed
1392 fixed
1391
1393
1392 $ cd ..
1394 $ cd ..
1393
1395
1394 Tools should be able to run on unchanged files, even if they set :linerange.
1396 Tools should be able to run on unchanged files, even if they set :linerange.
1395 This includes a corner case where deleted chunks of a file are not considered
1397 This includes a corner case where deleted chunks of a file are not considered
1396 changes.
1398 changes.
1397
1399
1398 $ hg init skipclean
1400 $ hg init skipclean
1399 $ cd skipclean
1401 $ cd skipclean
1400
1402
1401 $ printf "a\nb\nc\n" > foo
1403 $ printf "a\nb\nc\n" > foo
1402 $ printf "a\nb\nc\n" > bar
1404 $ printf "a\nb\nc\n" > bar
1403 $ printf "a\nb\nc\n" > baz
1405 $ printf "a\nb\nc\n" > baz
1404 $ hg commit -Aqm "base"
1406 $ hg commit -Aqm "base"
1405
1407
1406 $ printf "a\nc\n" > foo
1408 $ printf "a\nc\n" > foo
1407 $ printf "a\nx\nc\n" > baz
1409 $ printf "a\nx\nc\n" > baz
1408
1410
1409 $ cat >> print.py <<EOF
1411 $ cat >> print.py <<EOF
1410 > import sys
1412 > import sys
1411 > for a in sys.argv[1:]:
1413 > for a in sys.argv[1:]:
1412 > print(a)
1414 > print(a)
1413 > EOF
1415 > EOF
1414
1416
1415 $ hg fix --working-dir foo bar baz \
1417 $ hg fix --working-dir foo bar baz \
1416 > --config "fix.changedlines:command=\"$PYTHON\" print.py \"Line ranges:\"" \
1418 > --config "fix.changedlines:command=\"$PYTHON\" print.py \"Line ranges:\"" \
1417 > --config 'fix.changedlines:linerange="{first} through {last}"' \
1419 > --config 'fix.changedlines:linerange="{first} through {last}"' \
1418 > --config 'fix.changedlines:pattern=glob:**' \
1420 > --config 'fix.changedlines:pattern=glob:**' \
1419 > --config 'fix.changedlines:skipclean=false'
1421 > --config 'fix.changedlines:skipclean=false'
1420
1422
1421 $ cat foo
1423 $ cat foo
1422 Line ranges:
1424 Line ranges:
1423 $ cat bar
1425 $ cat bar
1424 Line ranges:
1426 Line ranges:
1425 $ cat baz
1427 $ cat baz
1426 Line ranges:
1428 Line ranges:
1427 2 through 2
1429 2 through 2
1428
1430
1429 $ cd ..
1431 $ cd ..
General Comments 0
You need to be logged in to leave comments. Login now