pre-commit-bigfix 2.2.0__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/PKG-INFO +31 -7
  2. pre_commit_bigfix-2.2.0/pre_commit_bigfix.egg-info/PKG-INFO → pre_commit_bigfix-2.3.0/README.md +29 -37
  3. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/__init__.py +1 -1
  4. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_relevance_lint.py +214 -43
  5. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/run_all.py +2 -1
  6. pre_commit_bigfix-2.2.0/README.md → pre_commit_bigfix-2.3.0/pre_commit_bigfix.egg-info/PKG-INFO +61 -5
  7. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix.egg-info/requires.txt +1 -1
  8. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/setup.cfg +1 -1
  9. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_relevance_lint.py +246 -14
  10. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_hook_declarations.py +10 -0
  11. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_schema_guard.py +94 -0
  12. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/LICENSE +0 -0
  13. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/MANIFEST.in +0 -0
  14. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_actionscript_lint_schclass.py +0 -0
  15. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_actionscript_validate_prefetch.py +0 -0
  16. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_actionscript_validate_script.py +0 -0
  17. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_common.py +0 -0
  18. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_content_score_risk.py +0 -0
  19. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_conventions_check.py +0 -0
  20. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_relevance_convert_group.py +0 -0
  21. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_schema_validate.py +0 -0
  22. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/bes_siterepo_validate_layout.py +0 -0
  23. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/schclass.py +0 -0
  24. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/schclass_data/ExpandedActionScript.schclass +0 -0
  25. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/schclass_data/bigfix_overrides.schclass +0 -0
  26. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix/schclass_tokenizer.py +0 -0
  27. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix.egg-info/SOURCES.txt +0 -0
  28. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix.egg-info/dependency_links.txt +0 -0
  29. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix.egg-info/entry_points.txt +0 -0
  30. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pre_commit_bigfix.egg-info/top_level.txt +0 -0
  31. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/pyproject.toml +0 -0
  32. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/setup.py +0 -0
  33. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_actionscript_lint_schclass.py +0 -0
  34. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_actionscript_validate_prefetch.py +0 -0
  35. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_actionscript_validate_script.py +0 -0
  36. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_common.py +0 -0
  37. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_content_score_risk.py +0 -0
  38. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_conventions_check.py +0 -0
  39. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_relevance_convert_group.py +0 -0
  40. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_schema_validate.py +0 -0
  41. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_bes_siterepo_validate_layout.py +0 -0
  42. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_package_metadata.py +0 -0
  43. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_release_workflow.py +0 -0
  44. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_run_all.py +0 -0
  45. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_schclass.py +0 -0
  46. {pre_commit_bigfix-2.2.0 → pre_commit_bigfix-2.3.0}/tests/test_schclass_tokenizer.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pre-commit-bigfix
3
- Version: 2.2.0
3
+ Version: 2.3.0
4
4
  Summary: pre-commit hooks for BigFix content
5
5
  Home-page: https://github.com/jgstew/pre-commit-bigfix
6
6
  Author: JGStew
@@ -25,7 +25,7 @@ License-File: LICENSE
25
25
  Requires-Dist: bigfix_prefetch>=1.1.5
26
26
  Requires-Dist: lxml
27
27
  Requires-Dist: validate_bes_xml<3,>=2.4.1
28
- Requires-Dist: bigfix-relevance-analyzer<2,>=1.23.1; python_version >= "3.11"
28
+ Requires-Dist: bigfix-relevance-analyzer<2,>=1.26.0; python_version >= "3.11"
29
29
  Provides-Extra: test
30
30
  Requires-Dist: pytest; extra == "test"
31
31
  Dynamic: license-file
@@ -624,6 +624,7 @@ of the file.
624
624
  | `E612` | an ActionScript `{` with anything after it on its line and no `}` to close it there, which fails the action |
625
625
  | `E613` | a `<?Relevance` with no closing `?>`, so its relevance was not linted |
626
626
  | `E614` | a BES file that is not well-formed XML, so nothing in it was linted (**off by default**; `--enable E614`) |
627
+ | `E615` | an `--auto-fix` was not written because it would turn a BES.xsd-valid file invalid; fix by hand, or `--disable E615` to write it anyway |
627
628
  | `W600` | a name no inspector dump defines |
628
629
  | `W601` | a property written singular over an object that may be plural |
629
630
  | `W602` | a singular spelling mid-chain (under a `whose` filter, or where a plural is built from it), where the plural reads safer |
@@ -635,7 +636,7 @@ of the file.
635
636
 
636
637
  `W600` is a warning rather than an error because a repo running a newer client
637
638
  than the analyzer's dump snapshot legitimately uses names it has never heard
638
- of. `W601` is **disabled by default** in the hook declaration: across 1,108
639
+ of. `W601` is **disabled by default**: across 1,108
639
640
  `.bes` files of real content it fires 6,127 times, which drowns everything
640
641
  else. Switch it back on with `--enable W601`.
641
642
 
@@ -646,12 +647,35 @@ says the relevance that could be extracted is sound, not that the file parses.
646
647
  A file opts out of every check here with
647
648
  `<!-- pre-commit-skip: bes-relevance-lint -->` anywhere in it. There is no
648
649
  per-rule marker: `--disable` takes a code repo-wide, and a single file that
649
- legitimately needs relevance this complex is what `--max-score` is for. Files
650
- are never rewritten, but where the analyzer can work out a safe rewrite of a
651
- whole statement (today, the singular spellings behind `W602`) the fixed
652
- statement is printed once under its first finding as `suggested fix: ...`.
650
+ legitimately needs relevance this complex is what `--max-score` is for.
653
651
  E-codes fail the hook; pass `--strict` to also fail on warnings.
654
652
 
653
+ Where the analyzer can work out a safe rewrite of a statement (the singular
654
+ spellings behind `W602`, and the `unique value of` / singular-aggregate
655
+ rewrites behind `E611`), the fixed statement is printed once under its first
656
+ finding as `suggested fix: ...`. By default that is all: **unlike the sibling
657
+ hooks, this one never rewrites a file unless the repo opts in**, because a
658
+ relevance fix changes what a statement says, not just how it is formatted:
659
+
660
+ ```yaml
661
+ - id: bes-relevance-lint
662
+ args: [--auto-fix=yes]
663
+ ```
664
+
665
+ With `--auto-fix=yes`, each safe fix is written in place as the smallest
666
+ edit that makes it (`setting` gains an `s`; a wrap inserts
667
+ `unique value of `), so entities, CDATA and line endings around it are kept.
668
+ The analyzer refuses a fix it cannot prove safe - one that would add a finding
669
+ (a wrap that pushes a statement over `--max-score`, say), or one under a rule
670
+ you `--disable` - and refuses site by site, so a file can come back partly
671
+ fixed. Each written edit is reported as
672
+ `path:line: [W602] auto-fixed: setting -> settings (plural-preferred)`; a fix
673
+ that was not written keeps its `suggested fix:` line with
674
+ `(not auto-fixed: <reason>)`. A fix that would turn a BES.xsd-valid file
675
+ invalid is not written, and is reported as `E615`; files no schema applies to
676
+ (`.rel`, `.bsr`, ...) are written unchecked, as every sibling hook does. Any
677
+ auto-fix fails the hook so the change is reviewed and re-staged.
678
+
655
679
  This hook needs **Python 3.11 or newer** - the analyzer requires it, while the
656
680
  rest of this package still runs on 3.8. No specific interpreter is pinned, since
657
681
  `language_version` names an exact executable and pinning `python3.11` would
@@ -1,35 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: pre-commit-bigfix
3
- Version: 2.2.0
4
- Summary: pre-commit hooks for BigFix content
5
- Home-page: https://github.com/jgstew/pre-commit-bigfix
6
- Author: JGStew
7
- Author-email: noreply@jgstew.com
8
- Project-URL: Bug Tracker, https://github.com/jgstew/pre-commit-bigfix/issues
9
- Project-URL: Source, https://github.com/jgstew/pre-commit-bigfix
10
- Keywords: pre-commit hooks python bigfix bes
11
- Classifier: Programming Language :: Python :: 3
12
- Classifier: Programming Language :: Python :: 3 :: Only
13
- Classifier: Programming Language :: Python :: 3.8
14
- Classifier: Programming Language :: Python :: 3.9
15
- Classifier: Programming Language :: Python :: 3.10
16
- Classifier: Programming Language :: Python :: 3.11
17
- Classifier: Programming Language :: Python :: 3.12
18
- Classifier: License :: OSI Approved :: MIT License
19
- Classifier: Operating System :: OS Independent
20
- Classifier: Development Status :: 5 - Production/Stable
21
- Classifier: Intended Audience :: Developers
22
- Requires-Python: >=3.8
23
- Description-Content-Type: text/markdown
24
- License-File: LICENSE
25
- Requires-Dist: bigfix_prefetch>=1.1.5
26
- Requires-Dist: lxml
27
- Requires-Dist: validate_bes_xml<3,>=2.4.1
28
- Requires-Dist: bigfix-relevance-analyzer<2,>=1.23.1; python_version >= "3.11"
29
- Provides-Extra: test
30
- Requires-Dist: pytest; extra == "test"
31
- Dynamic: license-file
32
-
33
1
  # pre-commit-bigfix
34
2
 
35
3
  pre commit hooks for BigFix content
@@ -624,6 +592,7 @@ of the file.
624
592
  | `E612` | an ActionScript `{` with anything after it on its line and no `}` to close it there, which fails the action |
625
593
  | `E613` | a `<?Relevance` with no closing `?>`, so its relevance was not linted |
626
594
  | `E614` | a BES file that is not well-formed XML, so nothing in it was linted (**off by default**; `--enable E614`) |
595
+ | `E615` | an `--auto-fix` was not written because it would turn a BES.xsd-valid file invalid; fix by hand, or `--disable E615` to write it anyway |
627
596
  | `W600` | a name no inspector dump defines |
628
597
  | `W601` | a property written singular over an object that may be plural |
629
598
  | `W602` | a singular spelling mid-chain (under a `whose` filter, or where a plural is built from it), where the plural reads safer |
@@ -635,7 +604,7 @@ of the file.
635
604
 
636
605
  `W600` is a warning rather than an error because a repo running a newer client
637
606
  than the analyzer's dump snapshot legitimately uses names it has never heard
638
- of. `W601` is **disabled by default** in the hook declaration: across 1,108
607
+ of. `W601` is **disabled by default**: across 1,108
639
608
  `.bes` files of real content it fires 6,127 times, which drowns everything
640
609
  else. Switch it back on with `--enable W601`.
641
610
 
@@ -646,12 +615,35 @@ says the relevance that could be extracted is sound, not that the file parses.
646
615
  A file opts out of every check here with
647
616
  `<!-- pre-commit-skip: bes-relevance-lint -->` anywhere in it. There is no
648
617
  per-rule marker: `--disable` takes a code repo-wide, and a single file that
649
- legitimately needs relevance this complex is what `--max-score` is for. Files
650
- are never rewritten, but where the analyzer can work out a safe rewrite of a
651
- whole statement (today, the singular spellings behind `W602`) the fixed
652
- statement is printed once under its first finding as `suggested fix: ...`.
618
+ legitimately needs relevance this complex is what `--max-score` is for.
653
619
  E-codes fail the hook; pass `--strict` to also fail on warnings.
654
620
 
621
+ Where the analyzer can work out a safe rewrite of a statement (the singular
622
+ spellings behind `W602`, and the `unique value of` / singular-aggregate
623
+ rewrites behind `E611`), the fixed statement is printed once under its first
624
+ finding as `suggested fix: ...`. By default that is all: **unlike the sibling
625
+ hooks, this one never rewrites a file unless the repo opts in**, because a
626
+ relevance fix changes what a statement says, not just how it is formatted:
627
+
628
+ ```yaml
629
+ - id: bes-relevance-lint
630
+ args: [--auto-fix=yes]
631
+ ```
632
+
633
+ With `--auto-fix=yes`, each safe fix is written in place as the smallest
634
+ edit that makes it (`setting` gains an `s`; a wrap inserts
635
+ `unique value of `), so entities, CDATA and line endings around it are kept.
636
+ The analyzer refuses a fix it cannot prove safe - one that would add a finding
637
+ (a wrap that pushes a statement over `--max-score`, say), or one under a rule
638
+ you `--disable` - and refuses site by site, so a file can come back partly
639
+ fixed. Each written edit is reported as
640
+ `path:line: [W602] auto-fixed: setting -> settings (plural-preferred)`; a fix
641
+ that was not written keeps its `suggested fix:` line with
642
+ `(not auto-fixed: <reason>)`. A fix that would turn a BES.xsd-valid file
643
+ invalid is not written, and is reported as `E615`; files no schema applies to
644
+ (`.rel`, `.bsr`, ...) are written unchecked, as every sibling hook does. Any
645
+ auto-fix fails the hook so the change is reviewed and re-staged.
646
+
655
647
  This hook needs **Python 3.11 or newer** - the analyzer requires it, while the
656
648
  rest of this package still runs on 3.8. No specific interpreter is pinned, since
657
649
  `language_version` names an exact executable and pinning `python3.11` would
@@ -1,3 +1,3 @@
1
1
  """To support running this directly as a python module."""
2
2
 
3
- __version__ = "2.2.0"
3
+ __version__ = "2.3.0"
@@ -44,13 +44,15 @@ Checks:
44
44
  E614 a BES file that is not well-formed XML, so nothing in it was linted.
45
45
  Off by default -- bes-schema-validate owns file validity -- and
46
46
  switched back on with --enable E614
47
+ E615 an --auto-fix was not written, because it would turn a BES.xsd-valid
48
+ file invalid; fix by hand, or --disable E615 to write it anyway
47
49
  W600 a name no inspector dump defines. A warning rather than an error
48
50
  because a repo running a newer client than the analyzer's snapshot
49
51
  legitimately uses names it has never heard of
50
52
  W601 a property written singular over an object that may be plural.
51
- Disabled by default in .pre-commit-hooks.yaml: it fires ~6 times per
52
- file across real content, which drowns everything else. Enable it
53
- deliberately with --enable W601
53
+ Disabled by default: it fires ~6 times per file across real content,
54
+ which drowns everything else. Enable it deliberately with
55
+ --enable W601
54
56
  W602 a singular spelling mid-chain -- under a `whose` filter, or where a
55
57
  plural is built from it -- where the plural reads safer
56
58
  W603 two version-looking strings compared as strings, not as versions
@@ -84,38 +86,62 @@ anywhere in it, the same marker the sibling hooks honor. There is no per-rule
84
86
  marker: --disable takes the code repo-wide, and a single file that legitimately
85
87
  needs relevance this complex is what --max-score is for.
86
88
 
87
- There is no auto-fix: files are never rewritten. Where the analyzer can work
88
- out a safe rewrite of a whole statement (today, the singular spellings behind
89
- W602 and the `unique value of` / singular-aggregate rewrites behind E611), the fixed statement is printed once under that statement's first
90
- finding as `suggested fix: ...`, for a human to copy in. Everything else needs
91
- a human to decide what the relevance was meant to say.
89
+ Where the analyzer can work out a safe rewrite of a statement (the singular
90
+ spellings behind W602, and the `unique value of` / singular-aggregate rewrites
91
+ behind E611), the fixed statement is printed once under that statement's first
92
+ finding as `suggested fix: ...`. Everything else needs a human to decide what
93
+ the relevance was meant to say.
94
+
95
+ --auto-fix=yes writes those fixes in place. It defaults to no in every mode,
96
+ files given or auto-discovering -- unlike the sibling hooks, because a
97
+ relevance fix changes what a statement says, not just how it is formatted, so
98
+ a repo opts in with `args: [--auto-fix=yes]`. The analyzer plans each file
99
+ (plan_fix): every fix is written as the smallest edit that makes it, and
100
+ one it cannot prove safe -- one that would add a finding, or one under a rule
101
+ --disable turned off -- is refused, site by site, so a file can come back
102
+ partly fixed. The plan is written (write_fix) unless it would turn a
103
+ BES.xsd-valid file invalid, which is reported as E615 with the original
104
+ findings; a file no schema applies to (.rel, .bsr, ...) is written unchecked.
105
+ Each written edit prints `path:line: [CODE] auto-fixed: old -> new (rule)`; a
106
+ fix not written keeps its `suggested fix:` line, with `(not auto-fixed:
107
+ <reason>)`. An auto-fixed file fails the hook so the change is reviewed and
108
+ re-staged.
92
109
 
93
110
  Usage:
94
- bes-relevance-lint [--strict] [--disable E604] [--enable W601] [FILES...]
111
+ bes-relevance-lint [--strict] [--auto-fix=yes|no] [--disable E604]
112
+ [--enable W601] [FILES...]
95
113
 
96
114
  Exit status:
97
- 0 no E-code findings (and, without --strict, no warnings either), or the
98
- interpreter is older than 3.11, where the analyzer cannot be installed
99
- and the hook skips with a notice rather than failing a build that has
100
- no way to go green
101
- 1 an E-code fired, a warning fired under --strict, or the analyzer is
102
- missing on a 3.11+ interpreter, where it should have been installed
115
+ 0 no E-code findings and nothing auto-fixed (and, without --strict, no
116
+ warnings either), or the interpreter is older than 3.11, where the
117
+ analyzer cannot be installed and the hook skips with a notice rather
118
+ than failing a build that has no way to go green
119
+ 1 an E-code fired, a file was auto-fixed, a warning fired under
120
+ --strict, or the analyzer is missing on a 3.11+ interpreter, where it
121
+ should have been installed
103
122
  """
104
123
 
105
124
  import argparse
125
+ import itertools
126
+ import re
106
127
  import sys
107
128
 
129
+ from pre_commit_bigfix import bes_common
130
+
108
131
  try:
109
132
  from bigfix_relevance_analyzer import (
110
133
  LintConfig,
111
134
  Severity,
112
135
  lint_directory,
113
136
  lint_paths,
137
+ plan_fix,
138
+ write_fix,
114
139
  )
115
140
 
116
141
  IMPORT_ERROR = None
117
142
  except ImportError as exc: # pragma: no cover - exercised only on an old Python
118
143
  LintConfig = lint_directory = lint_paths = Severity = None
144
+ plan_fix = write_fix = None
119
145
  IMPORT_ERROR = exc
120
146
 
121
147
  __all__ = ["main"]
@@ -155,7 +181,12 @@ CODES = {
155
181
  "unterminated-code-fence": "W607",
156
182
  }
157
183
 
158
- KNOWN_CODES = frozenset(CODES.values())
184
+ # The hook's own code, not an analyzer rule: an --auto-fix the analyzer
185
+ # planned that was not written because it would turn a BES.xsd-valid file
186
+ # invalid -- the guard every rewriting sibling hook has under its own code.
187
+ GUARD_CODE = "E615"
188
+
189
+ KNOWN_CODES = frozenset(CODES.values()) | {GUARD_CODE}
159
190
 
160
191
  # The reverse direction, for --disable/--enable: a repo names an E-code, the
161
192
  # analyzer's LintConfig wants its own.
@@ -163,8 +194,12 @@ ANALYZER_CODES = {code: name for name, code in CODES.items()}
163
194
 
164
195
  # Off unless a repo names them in --enable. E614 is a BES file that is not
165
196
  # well-formed XML: bes-schema-validate already reports that, and this hook must
166
- # not duplicate its findings, so unparsable XML stays skipped here.
167
- DEFAULT_DISABLED = frozenset({"E614"})
197
+ # not duplicate its findings, so unparsable XML stays skipped here. W601 fires
198
+ # ~6 times per file across real content, which drowns everything else. It is
199
+ # off here rather than as `args: [--disable, W601]` in .pre-commit-hooks.yaml
200
+ # because a repo's `args:` replaces the manifest's: one writing
201
+ # `args: [--auto-fix=yes]` would have silently switched it back on.
202
+ DEFAULT_DISABLED = frozenset({"E614", "W601"})
168
203
 
169
204
 
170
205
  MIN_ANALYZER_PYTHON = (3, 11)
@@ -209,13 +244,14 @@ def _split_codes(raw):
209
244
  def _severities(disabled, enabled):
210
245
  """Per-code overrides for LintConfig, in the analyzer's own vocabulary."""
211
246
  severities = {}
212
- for code in disabled:
247
+ # GUARD_CODE is the hook's own, with no analyzer rule behind it
248
+ for code in disabled & set(ANALYZER_CODES):
213
249
  severities[ANALYZER_CODES[code]] = Severity.IGNORE
214
- for code in enabled:
250
+ for code in enabled & set(ANALYZER_CODES):
215
251
  # Restore the analyzer's own default rather than forcing a severity:
216
- # --enable exists to undo a default --disable from the hook
217
- # declaration, not to promote a warning into an error. --strict is
218
- # what does that, for every warning at once.
252
+ # --enable exists to undo one of this hook's DEFAULT_DISABLED, not to
253
+ # promote a warning into an error. --strict is what does that, for
254
+ # every warning at once.
219
255
  severities.pop(ANALYZER_CODES[code], None)
220
256
  return severities
221
257
 
@@ -238,11 +274,36 @@ def _opted_out(path):
238
274
  return False
239
275
 
240
276
 
241
- def _report(findings):
277
+ def _drop_opted_out(findings):
278
+ """`findings` without those from files carrying the skip marker.
279
+
280
+ For files the analyzer found itself -- auto-discovering, or walking a
281
+ folder named on the command line -- so the marker holds for them too.
282
+ Each file is read once, however many findings it has.
283
+ """
284
+ opted_out = {}
285
+ kept = []
286
+ for finding in findings:
287
+ if finding.path not in opted_out:
288
+ opted_out[finding.path] = _opted_out(finding.path)
289
+ if not opted_out[finding.path]:
290
+ kept.append(finding)
291
+ return kept
292
+
293
+
294
+ def _fix_key(path, line, original):
295
+ """What ties a statement's findings to its fix: (path, site line, text)."""
296
+ return (str(path), line, original)
297
+
298
+
299
+ def _report(findings, not_fixed=None):
242
300
  """Print each finding in this repo's format.
243
301
 
244
- Returns (errors, warnings).
302
+ `not_fixed` maps a statement's _fix_key to why --auto-fix did not write
303
+ its fix, which is added to its `suggested fix:` line. Returns (errors,
304
+ warnings).
245
305
  """
306
+ not_fixed = not_fixed or {}
246
307
  errors = warnings = 0
247
308
  # Every fixable finding from one statement carries the same whole-statement
248
309
  # rewrite, so print it once per statement rather than once per finding.
@@ -255,10 +316,12 @@ def _report(findings):
255
316
  fix = getattr(finding, "autofix", None)
256
317
  if fix is not None:
257
318
  site_line = finding.site.line if finding.site is not None else None
258
- key = (str(finding.path), site_line, fix.original)
319
+ key = _fix_key(finding.path, site_line, fix.original)
259
320
  if key not in suggested:
260
321
  suggested.add(key)
261
- print(f" suggested fix: {fix.fixed}")
322
+ reason = not_fixed.get(key)
323
+ tail = f" (not auto-fixed: {reason})" if reason else ""
324
+ print(f" suggested fix: {fix.fixed}{tail}")
262
325
  if finding.severity is Severity.WARNING:
263
326
  warnings += 1
264
327
  else:
@@ -266,6 +329,86 @@ def _report(findings):
266
329
  return errors, warnings
267
330
 
268
331
 
332
+ _LINE_BREAK = re.compile(r"\r\n|\r|\n")
333
+
334
+
335
+ def _auto_fix(path, findings, config, guard):
336
+ """Write the analyzer's safe fixes into one file, unless BES.xsd forbids it.
337
+
338
+ `findings` are the file's lint findings; a file none of them offers a fix
339
+ for is not read again. Otherwise the analyzer plans every fix (plan_fix,
340
+ which writes nothing and refuses what is unsafe, site by site), and the
341
+ plan is written (write_fix) unless, with `guard`, it would turn a
342
+ schema-valid file invalid. Returns (findings, fixed, refused, not_fixed):
343
+ the findings to report, which are the fixed file's when it was written;
344
+ `fixed` and `refused` as (line, code, message) for bes_common.report; and
345
+ `not_fixed`, each unwritten fix's reason by _fix_key.
346
+ """
347
+ if not any(getattr(finding, "autofix", None) for finding in findings):
348
+ return findings, [], [], {}
349
+ plan = plan_fix(path, config)
350
+ applied, unapplied, findings = plan.applied, plan.unapplied, plan.findings
351
+ refused = []
352
+ not_fixed = {}
353
+ if plan.changed:
354
+ # [] for a file no schema applies to (.rel, .bsr, ...), and for one
355
+ # that was not schema-valid to begin with: both are written unchecked.
356
+ errors = (
357
+ bes_common.schema_regression(plan.original, plan.fixed, str(path))
358
+ if guard
359
+ else []
360
+ )
361
+ if errors:
362
+ codes = ", ".join(
363
+ sorted(
364
+ {CODES[edit.rule] for fix in applied for edit in fix.autofix.edits}
365
+ )
366
+ )
367
+ refused.append(
368
+ (
369
+ 1,
370
+ GUARD_CODE,
371
+ (
372
+ f"auto-fix ({codes}) not written: it would make the file fail "
373
+ f"BES.xsd validation ({errors[0]}); fix by hand, or --disable "
374
+ f"{GUARD_CODE} to write it anyway"
375
+ ),
376
+ )
377
+ )
378
+ for fix in applied:
379
+ key = _fix_key(fix.path, fix.line, fix.autofix.original)
380
+ not_fixed[key] = f"it would fail BES.xsd validation ({GUARD_CODE})"
381
+ applied, findings = (), plan.original_findings
382
+ else:
383
+ result = write_fix(plan)
384
+ applied, unapplied, findings = (
385
+ result.applied,
386
+ result.unapplied,
387
+ result.findings,
388
+ )
389
+ for fix in unapplied:
390
+ not_fixed.setdefault(
391
+ _fix_key(fix.path, fix.line, fix.autofix.original), fix.reason
392
+ )
393
+ # One line per edit, not per statement: a statement can hold several
394
+ # fixes, each under its own rule (a respelling and a `unique value of`).
395
+ # Each is reported on its own line, as its finding was: a site's `line` is
396
+ # where the statement starts, and its text keeps its line breaks.
397
+ fixed = [
398
+ (
399
+ fix.line + len(_LINE_BREAK.findall(fix.autofix.original, 0, edit.start)),
400
+ CODES[edit.rule],
401
+ (
402
+ f"{fix.autofix.original[edit.start : edit.end]} -> {edit.replacement} "
403
+ f"({edit.rule})"
404
+ ),
405
+ )
406
+ for fix in applied
407
+ for edit in fix.autofix.edits
408
+ ]
409
+ return findings, fixed, refused, not_fixed
410
+
411
+
269
412
  def main(argv=None):
270
413
  """Execution starts here.
271
414
 
@@ -282,6 +425,15 @@ def main(argv=None):
282
425
  action="store_true",
283
426
  help="treat warnings as failures (non-zero exit); default: advisory",
284
427
  )
428
+ parser.add_argument(
429
+ "--auto-fix",
430
+ choices=["yes", "no"],
431
+ default="no",
432
+ help=(
433
+ "write the analyzer's safe fixes into the files in place (default: "
434
+ "no, in every mode -- unlike the sibling hooks, a repo opts in)"
435
+ ),
436
+ )
285
437
  parser.add_argument(
286
438
  "--disable",
287
439
  default="",
@@ -293,8 +445,8 @@ def main(argv=None):
293
445
  default="",
294
446
  metavar="CODES",
295
447
  help=(
296
- "comma-separated check IDs to switch back on, undoing a --disable "
297
- "this hook declares by default, e.g. --enable W601"
448
+ "comma-separated check IDs to switch back on, undoing one this "
449
+ "hook disables by default, e.g. --enable W601"
298
450
  ),
299
451
  )
300
452
  parser.add_argument(
@@ -374,28 +526,47 @@ def main(argv=None):
374
526
 
375
527
  config = LintConfig(**config_kwargs)
376
528
 
529
+ # Filter after the walk rather than before it: the analyzer owns
530
+ # discovery, and re-walking here to drop opted-out files first would mean
531
+ # two definitions of what counts as a file to check. A named file is still
532
+ # dropped before it is linted, which is all pre-commit ever passes.
377
533
  if args.files:
378
- findings = lint_paths(
379
- [path for path in args.files if not _opted_out(path)], config
534
+ findings = _drop_opted_out(
535
+ lint_paths([path for path in args.files if not _opted_out(path)], config)
380
536
  )
381
537
  else:
382
- # Filter after the walk rather than before it: the analyzer owns
383
- # discovery, and re-walking here to drop opted-out files first would
384
- # mean two definitions of what counts as a file to check.
385
- findings = [
386
- finding
387
- for finding in lint_directory(".", config, max_depth=args.max_depth)
388
- if not _opted_out(finding.path)
389
- ]
390
-
391
- error_count, warning_count = _report(findings)
538
+ findings = _drop_opted_out(
539
+ lint_directory(".", config, max_depth=args.max_depth)
540
+ )
392
541
 
542
+ if args.auto_fix != "yes":
543
+ error_count, warning_count = _report(findings)
544
+ fix_count = 0
545
+ else:
546
+ error_count = warning_count = fix_count = 0
547
+ guard = GUARD_CODE not in disabled
548
+ # The analyzer reports each file's findings together, in path order.
549
+ # A path named twice comes back as two runs, or one when adjacent:
550
+ # either way it is planned again from what is on disk, so a fix is
551
+ # written once.
552
+ for path, linted in itertools.groupby(findings, key=lambda f: f.path):
553
+ reported, fixed, refused, not_fixed = _auto_fix(
554
+ path, list(linted), config, guard
555
+ )
556
+ issues, _warnings, fixes = bes_common.report([(path, refused, fixed)])
557
+ errors, warnings = _report(reported, not_fixed)
558
+ error_count += issues + errors
559
+ warning_count += warnings
560
+ fix_count += fixes
561
+
562
+ if fix_count:
563
+ print(f"\nauto-fixed {fix_count} issue(s); review and re-stage the changes.")
393
564
  if warning_count:
394
565
  print(f"{warning_count} warning(s).")
395
566
  if error_count:
396
567
  print(f"{error_count} issue(s).")
397
- # E-codes always fail; warnings fail only under --strict
398
- return 1 if (error_count or (warning_count and args.strict)) else 0
568
+ # E-codes and any fix always fail; warnings fail only under --strict
569
+ return 1 if (error_count or fix_count or (warning_count and args.strict)) else 0
399
570
 
400
571
 
401
572
  if __name__ == "__main__":
@@ -109,7 +109,8 @@ HOOKS = (
109
109
  "bes-relevance-lint",
110
110
  "bes_relevance_lint",
111
111
  r"\.(bes|bes\.xml|ojo|besrpt|beswrpt|webreport|bsr|rel)$",
112
- args=("--disable", "W601"),
112
+ # --auto-fix is already off by default; say so anyway
113
+ read_only=("--auto-fix=no",),
113
114
  ),
114
115
  Hook(
115
116
  "bes-relevance-convert-group",
@@ -1,3 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: pre-commit-bigfix
3
+ Version: 2.3.0
4
+ Summary: pre-commit hooks for BigFix content
5
+ Home-page: https://github.com/jgstew/pre-commit-bigfix
6
+ Author: JGStew
7
+ Author-email: noreply@jgstew.com
8
+ Project-URL: Bug Tracker, https://github.com/jgstew/pre-commit-bigfix/issues
9
+ Project-URL: Source, https://github.com/jgstew/pre-commit-bigfix
10
+ Keywords: pre-commit hooks python bigfix bes
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Development Status :: 5 - Production/Stable
21
+ Classifier: Intended Audience :: Developers
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: bigfix_prefetch>=1.1.5
26
+ Requires-Dist: lxml
27
+ Requires-Dist: validate_bes_xml<3,>=2.4.1
28
+ Requires-Dist: bigfix-relevance-analyzer<2,>=1.26.0; python_version >= "3.11"
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest; extra == "test"
31
+ Dynamic: license-file
32
+
1
33
  # pre-commit-bigfix
2
34
 
3
35
  pre commit hooks for BigFix content
@@ -592,6 +624,7 @@ of the file.
592
624
  | `E612` | an ActionScript `{` with anything after it on its line and no `}` to close it there, which fails the action |
593
625
  | `E613` | a `<?Relevance` with no closing `?>`, so its relevance was not linted |
594
626
  | `E614` | a BES file that is not well-formed XML, so nothing in it was linted (**off by default**; `--enable E614`) |
627
+ | `E615` | an `--auto-fix` was not written because it would turn a BES.xsd-valid file invalid; fix by hand, or `--disable E615` to write it anyway |
595
628
  | `W600` | a name no inspector dump defines |
596
629
  | `W601` | a property written singular over an object that may be plural |
597
630
  | `W602` | a singular spelling mid-chain (under a `whose` filter, or where a plural is built from it), where the plural reads safer |
@@ -603,7 +636,7 @@ of the file.
603
636
 
604
637
  `W600` is a warning rather than an error because a repo running a newer client
605
638
  than the analyzer's dump snapshot legitimately uses names it has never heard
606
- of. `W601` is **disabled by default** in the hook declaration: across 1,108
639
+ of. `W601` is **disabled by default**: across 1,108
607
640
  `.bes` files of real content it fires 6,127 times, which drowns everything
608
641
  else. Switch it back on with `--enable W601`.
609
642
 
@@ -614,12 +647,35 @@ says the relevance that could be extracted is sound, not that the file parses.
614
647
  A file opts out of every check here with
615
648
  `<!-- pre-commit-skip: bes-relevance-lint -->` anywhere in it. There is no
616
649
  per-rule marker: `--disable` takes a code repo-wide, and a single file that
617
- legitimately needs relevance this complex is what `--max-score` is for. Files
618
- are never rewritten, but where the analyzer can work out a safe rewrite of a
619
- whole statement (today, the singular spellings behind `W602`) the fixed
620
- statement is printed once under its first finding as `suggested fix: ...`.
650
+ legitimately needs relevance this complex is what `--max-score` is for.
621
651
  E-codes fail the hook; pass `--strict` to also fail on warnings.
622
652
 
653
+ Where the analyzer can work out a safe rewrite of a statement (the singular
654
+ spellings behind `W602`, and the `unique value of` / singular-aggregate
655
+ rewrites behind `E611`), the fixed statement is printed once under its first
656
+ finding as `suggested fix: ...`. By default that is all: **unlike the sibling
657
+ hooks, this one never rewrites a file unless the repo opts in**, because a
658
+ relevance fix changes what a statement says, not just how it is formatted:
659
+
660
+ ```yaml
661
+ - id: bes-relevance-lint
662
+ args: [--auto-fix=yes]
663
+ ```
664
+
665
+ With `--auto-fix=yes`, each safe fix is written in place as the smallest
666
+ edit that makes it (`setting` gains an `s`; a wrap inserts
667
+ `unique value of `), so entities, CDATA and line endings around it are kept.
668
+ The analyzer refuses a fix it cannot prove safe - one that would add a finding
669
+ (a wrap that pushes a statement over `--max-score`, say), or one under a rule
670
+ you `--disable` - and refuses site by site, so a file can come back partly
671
+ fixed. Each written edit is reported as
672
+ `path:line: [W602] auto-fixed: setting -> settings (plural-preferred)`; a fix
673
+ that was not written keeps its `suggested fix:` line with
674
+ `(not auto-fixed: <reason>)`. A fix that would turn a BES.xsd-valid file
675
+ invalid is not written, and is reported as `E615`; files no schema applies to
676
+ (`.rel`, `.bsr`, ...) are written unchecked, as every sibling hook does. Any
677
+ auto-fix fails the hook so the change is reviewed and re-staged.
678
+
623
679
  This hook needs **Python 3.11 or newer** - the analyzer requires it, while the
624
680
  rest of this package still runs on 3.8. No specific interpreter is pinned, since
625
681
  `language_version` names an exact executable and pinning `python3.11` would
@@ -3,7 +3,7 @@ lxml
3
3
  validate_bes_xml<3,>=2.4.1
4
4
 
5
5
  [:python_version >= "3.11"]
6
- bigfix-relevance-analyzer<2,>=1.23.1
6
+ bigfix-relevance-analyzer<2,>=1.26.0
7
7
 
8
8
  [test]
9
9
  pytest
@@ -34,7 +34,7 @@ install_requires =
34
34
  bigfix_prefetch >= 1.1.5
35
35
  lxml
36
36
  validate_bes_xml >= 2.4.1, < 3
37
- bigfix-relevance-analyzer >= 1.23.1, < 2; python_version >= "3.11"
37
+ bigfix-relevance-analyzer >= 1.26.0, < 2; python_version >= "3.11"
38
38
 
39
39
  [options.package_data]
40
40
  pre_commit_bigfix = schclass_data/*.schclass
@@ -94,7 +94,8 @@ def test_every_analyzer_rule_is_mapped():
94
94
 
95
95
 
96
96
  def test_codes_are_unique():
97
- assert len(linter.KNOWN_CODES) == len(linter.CODES)
97
+ assert len(set(linter.CODES.values())) == len(linter.CODES)
98
+ assert linter.GUARD_CODE not in linter.CODES.values()
98
99
 
99
100
 
100
101
  @pytest.mark.parametrize(
@@ -125,7 +126,9 @@ def test_codes_are_unique():
125
126
  ],
126
127
  )
127
128
  def test_each_code_fires(tmp_path, capsys, relevance, code):
128
- _, out = run(tmp_path, relevance, capsys=capsys)
129
+ # --enable is a no-op for a code that is on by default, and switches W601
130
+ # back on, which DEFAULT_DISABLED turns off
131
+ _, out = run(tmp_path, relevance, "--enable", code, capsys=capsys)
129
132
  assert code in codes_in(out)
130
133
 
131
134
 
@@ -169,19 +172,14 @@ def test_disable_silences_a_code(tmp_path, capsys):
169
172
  assert status == 0
170
173
 
171
174
 
172
- def test_enable_undoes_a_declared_disable(tmp_path, capsys):
173
- """The hook declaration ships `--disable W601`; a repo that wants the rule
174
- appends `--enable W601` rather than having to restate the whole list.
175
+ def test_enable_undoes_a_default_disable(tmp_path, capsys):
176
+ """W601 is off in the hook's code (DEFAULT_DISABLED), not in the manifest's
177
+ `args`, so `--enable W601` alone switches it back on.
175
178
  """
176
- _, out = run(
177
- tmp_path,
178
- 'exists (name of files "x") whose (it = "y")',
179
- "--disable",
180
- "W601",
181
- "--enable",
182
- "W601",
183
- capsys=capsys,
184
- )
179
+ relevance = 'exists (name of files "x") whose (it = "y")'
180
+ _, out = run(tmp_path, relevance, capsys=capsys)
181
+ assert "W601" not in codes_in(out)
182
+ _, out = run(tmp_path, relevance, "--enable", "W601", capsys=capsys)
185
183
  assert codes_in(out) == ["W601"]
186
184
 
187
185
 
@@ -463,3 +461,237 @@ def test_a_suggested_fix_is_printed_once_per_statement(tmp_path, capsys):
463
461
  def test_an_unfixable_finding_prints_no_suggestion(tmp_path, capsys):
464
462
  _, out = run(tmp_path, "exists bogusinspectorname", capsys=capsys)
465
463
  assert not any("suggested fix:" in line for line in out)
464
+
465
+
466
+ # --- --auto-fix (bigfix-relevance-analyzer#115 Part B) -----------------------
467
+
468
+ SETTING = 'exists values of setting "x" of client'
469
+ SETTINGS = 'exists values of settings "x" of client'
470
+
471
+ # Two fences, each its own site: a respelling that adds nothing (line 4), and
472
+ # a `unique value of` wrap that raises the score from 12 to 20 (line 8). With
473
+ # --max-score 15 between the two, the wrap is refused and the respelling is
474
+ # still written: a file can come back partly fixed.
475
+ TWO_FENCES = (
476
+ "# x\n\n```relevance\n"
477
+ 'exists values of setting "x" of client\n'
478
+ "```\n\n```relevance\n"
479
+ 'pathnames of files "x" | "y"\n'
480
+ "```\n"
481
+ )
482
+
483
+ FOOTER = "auto-fixed {} issue(s); review and re-stage the changes."
484
+
485
+
486
+ def test_the_default_never_writes_and_prints_what_it_always_did(tmp_path, capsys):
487
+ """Opt-in: without the flag, the file is untouched and the output is
488
+ exactly the suggestion-only report, `suggested fix:` included.
489
+ """
490
+ path = write(tmp_path, bes(SETTING))
491
+ before = (tmp_path / "x.bes").read_bytes()
492
+ status = linter.main([path])
493
+ out = capsys.readouterr().out.splitlines()
494
+ assert (tmp_path / "x.bes").read_bytes() == before
495
+ assert status == 0
496
+ # the analyzer owns the message's wording; everything around it is pinned
497
+ assert out[0].startswith(f"{path}:5: [W602] warning: ")
498
+ assert out[0].endswith(" (plural-preferred)")
499
+ assert out[1:] == [f" suggested fix: {SETTINGS}", "1 warning(s)."]
500
+
501
+
502
+ def test_auto_fix_no_is_the_default_spelled_out(tmp_path, capsys):
503
+ path = write(tmp_path, bes(SETTING))
504
+ before = (tmp_path / "x.bes").read_bytes()
505
+ assert linter.main(["--auto-fix=no", path]) == 0
506
+ assert (tmp_path / "x.bes").read_bytes() == before
507
+ assert "auto-fixed" not in capsys.readouterr().out
508
+
509
+
510
+ def test_auto_fix_yes_writes_the_fix_and_fails_for_review(tmp_path, capsys):
511
+ path = write(tmp_path, bes(SETTING))
512
+ status = linter.main(["--auto-fix=yes", path])
513
+ out = capsys.readouterr().out.splitlines()
514
+ assert (tmp_path / "x.bes").read_text(encoding="utf-8") == bes(SETTINGS)
515
+ assert status == 1
516
+ assert out == [
517
+ f"{path}:5: [W602] auto-fixed: setting -> settings (plural-preferred)",
518
+ "",
519
+ FOOTER.format(1),
520
+ ]
521
+
522
+
523
+ def test_auto_fix_prints_one_line_per_edit_coded_by_its_rule(tmp_path, capsys):
524
+ """A wrap is an E611 edit: the code comes from the edit's own rule, and the
525
+ findings left after the fix are reported as usual.
526
+ """
527
+ path = write(tmp_path, bes('exists ("a" &amp; names of files "x")'))
528
+ status = linter.main(["--auto-fix=yes", path])
529
+ out = capsys.readouterr().out.splitlines()
530
+ assert status == 1
531
+ assert out[0] == (
532
+ f'{path}:5: [E611] auto-fixed: names of files "x" -> '
533
+ 'unique value of names of files "x" (singular-required)'
534
+ )
535
+ assert "unique value of names of files" in (tmp_path / "x.bes").read_text(
536
+ encoding="utf-8"
537
+ )
538
+ assert "E611" not in codes_in(out[1:])
539
+
540
+
541
+ def test_a_partly_fixed_file_keeps_the_refused_suggestion(tmp_path, capsys):
542
+ """Refusals can be per site: the respelling is written, and the wrap that
543
+ would add a complexity finding stays a suggestion with its reason.
544
+ """
545
+ path = write(tmp_path, TWO_FENCES, name="x.md")
546
+ status = linter.main(["--auto-fix=yes", "--max-score", "15", path])
547
+ out = capsys.readouterr().out.splitlines()
548
+ assert (tmp_path / "x.md").read_text(encoding="utf-8") == TWO_FENCES.replace(
549
+ "setting ", "settings "
550
+ )
551
+ assert status == 1
552
+ assert (
553
+ out[0] == f"{path}:4: [W602] auto-fixed: setting -> settings (plural-preferred)"
554
+ )
555
+ assert (
556
+ ' suggested fix: unique value of pathnames of files "x" | "y" '
557
+ "(not auto-fixed: the fix would add a complexity finding)"
558
+ ) in out
559
+ assert FOOTER.format(1) in out
560
+
561
+
562
+ def test_auto_fix_when_discovering_defaults_to_no(tmp_path, monkeypatch, capsys):
563
+ write(tmp_path, bes(SETTING))
564
+ before = (tmp_path / "x.bes").read_bytes()
565
+ monkeypatch.chdir(tmp_path)
566
+ assert linter.main([]) == 0
567
+ assert (tmp_path / "x.bes").read_bytes() == before
568
+ assert "suggested fix:" in capsys.readouterr().out
569
+
570
+
571
+ def test_auto_fix_yes_fixes_the_walked_files(tmp_path, monkeypatch, capsys):
572
+ write(tmp_path, bes(SETTING))
573
+ write(tmp_path, bes("it"), name="broken.bes") # findings, nothing to fix
574
+ monkeypatch.chdir(tmp_path)
575
+ status = linter.main(["--auto-fix=yes"])
576
+ out = capsys.readouterr().out
577
+ assert (tmp_path / "x.bes").read_text(encoding="utf-8") == bes(SETTINGS)
578
+ assert "x.bes:5: [W602] auto-fixed: setting -> settings" in out
579
+ assert "broken.bes:5: [E602]" in out
580
+ assert status == 1
581
+
582
+
583
+ def test_auto_fix_does_not_switch_w601_back_on(tmp_path, capsys):
584
+ """W601 is off in code, not in the manifest's `args`, so a repo writing
585
+ `args: [--auto-fix=yes]` (which replaces the manifest's) does not get it.
586
+ """
587
+ _, out = run(
588
+ tmp_path,
589
+ 'exists (name of files "x") whose (it = "y")',
590
+ "--auto-fix=yes",
591
+ capsys=capsys,
592
+ )
593
+ assert "W601" not in codes_in(out)
594
+
595
+
596
+ def test_disabling_a_rule_disables_its_fix(tmp_path, capsys):
597
+ path = write(tmp_path, bes(SETTING))
598
+ before = (tmp_path / "x.bes").read_bytes()
599
+ status = linter.main(["--auto-fix=yes", "--disable", "W602", path])
600
+ out = capsys.readouterr().out
601
+ assert (tmp_path / "x.bes").read_bytes() == before
602
+ assert "auto-fixed" not in out
603
+ assert status == 0
604
+
605
+
606
+ def test_an_opted_out_file_is_never_written(tmp_path, capsys):
607
+ path = write(tmp_path, bes(SETTING, marker=linter.SKIP_MARKER))
608
+ before = (tmp_path / "x.bes").read_bytes()
609
+ assert linter.main(["--auto-fix=yes", path]) == 0
610
+ assert (tmp_path / "x.bes").read_bytes() == before
611
+ assert capsys.readouterr().out == ""
612
+
613
+
614
+ def test_a_rel_fix_is_written_with_no_schema_to_check(tmp_path, capsys):
615
+ """No schema applies to a .rel, so schema_regression is [] and it is written,
616
+ like every sibling hook's non-BES writes.
617
+ """
618
+ path = write(tmp_path, SETTING + "\n", name="x.rel")
619
+ status = linter.main(["--auto-fix=yes", path])
620
+ out = capsys.readouterr().out
621
+ assert (tmp_path / "x.rel").read_text(encoding="utf-8") == SETTINGS + "\n"
622
+ assert "[E615]" not in out
623
+ assert status == 1
624
+
625
+
626
+ def test_every_fixable_rule_is_mapped():
627
+ """Each auto-fixed line is coded from CODES[edit.rule], so a rule the fixer
628
+ can emit and this hook does not map would raise mid-report.
629
+
630
+ TextEdit.rule
631
+ is the analyzer's checker-code-to-rule table, with anything unlisted
632
+ reported as type-error.
633
+ """
634
+ from bigfix_relevance_analyzer import lint
635
+ from bigfix_relevance_analyzer.autofix import TextEdit
636
+
637
+ # private, so read defensively: an analyzer refactor that renames it must
638
+ # not fail this hook's build, only narrow this check to the fallback
639
+ check_rules = getattr(lint, "_CHECK_RULES", {})
640
+ for code in [*check_rules, "an-unlisted-code"]:
641
+ assert TextEdit(0, 0, "", code).rule in linter.CODES
642
+
643
+
644
+ # --- review of #57 -----------------------------------------------------------
645
+
646
+
647
+ def test_an_opted_out_file_inside_a_named_folder_is_never_written(tmp_path, capsys):
648
+ """A named folder is walked by the analyzer, so the marker must be checked
649
+ per file found, not only per path given.
650
+ """
651
+ folder = tmp_path / "d"
652
+ folder.mkdir()
653
+ write(folder, bes(SETTING, marker=linter.SKIP_MARKER), name="skip.bes")
654
+ write(folder, bes(SETTING), name="fix.bes")
655
+ before = (folder / "skip.bes").read_bytes()
656
+ linter.main(["--auto-fix=yes", str(folder)])
657
+ out = capsys.readouterr().out
658
+ assert (folder / "skip.bes").read_bytes() == before
659
+ assert "skip.bes" not in out
660
+ assert (folder / "fix.bes").read_text(encoding="utf-8") == bes(SETTINGS)
661
+
662
+
663
+ def test_an_auto_fixed_line_is_the_line_the_edit_is_on(tmp_path, capsys):
664
+ """A statement can span lines; the auto-fixed line is the edit's own line,
665
+ the same one its finding is reported at, not the statement's first.
666
+ """
667
+ text = '# x\n\n```relevance\nexists values of\nsetting "x" of client\n```\n'
668
+ path = write(tmp_path, text, name="m.md")
669
+ linter.main([path])
670
+ finding = capsys.readouterr().out.splitlines()[0]
671
+ assert finding.startswith(f"{path}:5: [W602] ")
672
+ linter.main(["--auto-fix=yes", path])
673
+ out = capsys.readouterr().out.splitlines()
674
+ assert (
675
+ out[0] == f"{path}:5: [W602] auto-fixed: setting -> settings (plural-preferred)"
676
+ )
677
+
678
+
679
+ def test_auto_fix_yes_over_several_named_files(tmp_path, capsys):
680
+ """Each file is planned on its own; one with nothing to fix is reported as
681
+ lint reports it, between the fixed ones.
682
+ """
683
+ first = write(tmp_path, bes(SETTING), name="a.bes")
684
+ broken = write(tmp_path, bes("it"), name="b.bes")
685
+ last = write(tmp_path, SETTING + "\n", name="c.rel")
686
+ status = linter.main(["--auto-fix=yes", first, broken, last])
687
+ out = capsys.readouterr().out.splitlines()
688
+ assert status == 1
689
+ assert (
690
+ out[0]
691
+ == f"{first}:5: [W602] auto-fixed: setting -> settings (plural-preferred)"
692
+ )
693
+ assert out[1].startswith(f"{broken}:5: [E602] ")
694
+ assert (
695
+ out[2] == f"{last}:1: [W602] auto-fixed: setting -> settings (plural-preferred)"
696
+ )
697
+ assert FOOTER.format(2) in out
@@ -136,3 +136,13 @@ def test_bes_siterepo_validate_layout_checks_the_whole_repo():
136
136
  assert console_scripts()["bes-siterepo-validate-layout"] == (
137
137
  "pre_commit_bigfix.bes_siterepo_validate_layout:main"
138
138
  )
139
+
140
+
141
+ def test_bes_relevance_lint_declares_no_args():
142
+ """A repo's `args:` replaces the manifest's rather than appending, so any
143
+ default here would be silently dropped by `args: [--auto-fix=yes]`.
144
+
145
+ W601
146
+ is off in the hook's code instead (bigfix-relevance-analyzer#115).
147
+ """
148
+ assert "args" not in load_hooks()["bes-relevance-lint"]
@@ -20,6 +20,7 @@ from pre_commit_bigfix import bes_actionscript_validate_prefetch as prefetch
20
20
  from pre_commit_bigfix import bes_actionscript_validate_script as script
21
21
  from pre_commit_bigfix import bes_conventions_check as conventions
22
22
  from pre_commit_bigfix import bes_relevance_convert_group as convert_group
23
+ from pre_commit_bigfix import bes_relevance_lint as relevance_lint
23
24
 
24
25
  pytest.importorskip("validate_bes_xml")
25
26
 
@@ -113,6 +114,7 @@ def test_disabling_the_guard_lets_the_fix_through(
113
114
  (prefetch, "E404"),
114
115
  (script, "E526"),
115
116
  (convert_group, "E704"),
117
+ (relevance_lint, "E615"),
116
118
  ],
117
119
  )
118
120
  def test_guard_code_is_known_and_documented(hook, guard):
@@ -190,3 +192,95 @@ def test_passes_after_one_that_makes_the_file_valid_are_checked():
190
192
  assert [code for _l, code, _m in guard.fixed] == ["W1"]
191
193
  assert [code for _l, code, _m in guard.refused] == ["E999"]
192
194
  assert "W2" in guard.refused[0][2]
195
+
196
+
197
+ # --- bes-relevance-lint: the analyzer plans, the guard decides (#115 Part B) --
198
+ #
199
+ # The hook has no check_file and no text-to-text fixer for CASES to swap: it
200
+ # calls the analyzer's plan_fix (a module global) and writes the plan with
201
+ # write_fix. So these three mirror the CASES tests by swapping the planner for
202
+ # one that bends the real plan's fixed bytes.
203
+
204
+ SETTING = 'exists values of setting "x" of client'
205
+
206
+
207
+ def copy_fixable_example(tmp_path):
208
+ """Example-test.bes (schema-valid) with one W602-fixable <Relevance>."""
209
+ path = tmp_path / "example-test.bes"
210
+ text = EXAMPLE.read_text(encoding="utf-8")
211
+ path.write_text(
212
+ text.replace(
213
+ "<Relevance>False</Relevance>", f"<Relevance>{SETTING}</Relevance>"
214
+ ),
215
+ encoding="utf-8",
216
+ )
217
+ return path
218
+
219
+
220
+ def bent_planner(monkeypatch, transform):
221
+ """Swap relevance_lint.plan_fix for the real one with `transform` applied
222
+ to what it would write.
223
+ """
224
+ import dataclasses
225
+
226
+ real = relevance_lint.plan_fix
227
+
228
+ def planner(path, config):
229
+ plan = real(path, config)
230
+ fixed = transform(plan.fixed.decode("utf-8")).encode("utf-8")
231
+ return dataclasses.replace(plan, fixed=fixed)
232
+
233
+ monkeypatch.setattr(relevance_lint, "plan_fix", planner)
234
+
235
+
236
+ @pytest.fixture
237
+ def analyzer():
238
+ pytest.importorskip(
239
+ "bigfix_relevance_analyzer",
240
+ reason="bes-relevance-lint's analyzer needs Python 3.11+",
241
+ )
242
+
243
+
244
+ def test_relevance_lint_breaking_fix_is_not_written(
245
+ analyzer, tmp_path, monkeypatch, capsys
246
+ ):
247
+ path = copy_fixable_example(tmp_path)
248
+ original = path.read_bytes()
249
+ bent_planner(monkeypatch, breaking)
250
+ status = relevance_lint.main(["--auto-fix=yes", str(path)])
251
+ out = capsys.readouterr().out
252
+ assert path.read_bytes() == original
253
+ assert status == 1
254
+ assert "auto-fixed" not in out.replace("not auto-fixed", "")
255
+ guard_lines = [line for line in out.splitlines() if "[E615]" in line]
256
+ assert len(guard_lines) == 1
257
+ assert "BES.xsd" in guard_lines[0]
258
+ assert "W602" in guard_lines[0] # names the fix that was held back
259
+ # the original findings are reported, with the fix left as a suggestion
260
+ assert "[W602] warning:" in out
261
+ assert "(not auto-fixed: " in out
262
+
263
+
264
+ def test_relevance_lint_schema_valid_fix_is_written(
265
+ analyzer, tmp_path, monkeypatch, capsys
266
+ ):
267
+ path = copy_fixable_example(tmp_path)
268
+ bent_planner(monkeypatch, harmless)
269
+ status = relevance_lint.main(["--auto-fix=yes", str(path)])
270
+ out = capsys.readouterr().out
271
+ written = path.read_bytes()
272
+ assert b"<!-- touched -->" in written
273
+ assert b"settings" in written
274
+ assert "[W602] auto-fixed: setting -> settings" in out
275
+ assert "[E615]" not in out
276
+ assert status == 1
277
+
278
+
279
+ def test_relevance_lint_disabling_the_guard_lets_the_fix_through(
280
+ analyzer, tmp_path, monkeypatch, capsys
281
+ ):
282
+ path = copy_fixable_example(tmp_path)
283
+ bent_planner(monkeypatch, breaking)
284
+ relevance_lint.main(["--auto-fix=yes", "--disable", "E615", str(path)])
285
+ assert b"<Title>again</Title>" in path.read_bytes()
286
+ assert "[E615]" not in capsys.readouterr().out