xlsform-lint 0.1.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 (48) hide show
  1. xlsform_lint-0.1.0/LICENSE +202 -0
  2. xlsform_lint-0.1.0/PKG-INFO +17 -0
  3. xlsform_lint-0.1.0/README.md +95 -0
  4. xlsform_lint-0.1.0/pyproject.toml +37 -0
  5. xlsform_lint-0.1.0/setup.cfg +4 -0
  6. xlsform_lint-0.1.0/src/xlsform_lint/__init__.py +7 -0
  7. xlsform_lint-0.1.0/src/xlsform_lint/__main__.py +6 -0
  8. xlsform_lint-0.1.0/src/xlsform_lint/cli.py +58 -0
  9. xlsform_lint-0.1.0/src/xlsform_lint/config.py +175 -0
  10. xlsform_lint-0.1.0/src/xlsform_lint/diagnostics.py +177 -0
  11. xlsform_lint-0.1.0/src/xlsform_lint/engine.py +41 -0
  12. xlsform_lint-0.1.0/src/xlsform_lint/json_formatter.py +60 -0
  13. xlsform_lint-0.1.0/src/xlsform_lint/native_model.py +242 -0
  14. xlsform_lint-0.1.0/src/xlsform_lint/native_rules.py +257 -0
  15. xlsform_lint-0.1.0/src/xlsform_lint/policy.py +125 -0
  16. xlsform_lint-0.1.0/src/xlsform_lint/pre_commit.py +23 -0
  17. xlsform_lint-0.1.0/src/xlsform_lint/pyxform_adapter.py +273 -0
  18. xlsform_lint-0.1.0/src/xlsform_lint/sarif_formatter.py +85 -0
  19. xlsform_lint-0.1.0/src/xlsform_lint/source_reader.py +102 -0
  20. xlsform_lint-0.1.0/src/xlsform_lint/text_formatter.py +52 -0
  21. xlsform_lint-0.1.0/src/xlsform_lint/workbook_input.py +10 -0
  22. xlsform_lint-0.1.0/src/xlsform_lint.egg-info/PKG-INFO +17 -0
  23. xlsform_lint-0.1.0/src/xlsform_lint.egg-info/SOURCES.txt +46 -0
  24. xlsform_lint-0.1.0/src/xlsform_lint.egg-info/dependency_links.txt +1 -0
  25. xlsform_lint-0.1.0/src/xlsform_lint.egg-info/entry_points.txt +2 -0
  26. xlsform_lint-0.1.0/src/xlsform_lint.egg-info/requires.txt +8 -0
  27. xlsform_lint-0.1.0/src/xlsform_lint.egg-info/top_level.txt +1 -0
  28. xlsform_lint-0.1.0/tests/test_diagnostics.py +147 -0
  29. xlsform_lint-0.1.0/tests/test_executable_boundary.py +174 -0
  30. xlsform_lint-0.1.0/tests/test_exit_codes.py +38 -0
  31. xlsform_lint-0.1.0/tests/test_phase2_pyxform_rules.py +276 -0
  32. xlsform_lint-0.1.0/tests/test_phase3_cli.py +73 -0
  33. xlsform_lint-0.1.0/tests/test_phase3_native_rules.py +223 -0
  34. xlsform_lint-0.1.0/tests/test_phase4_cli.py +248 -0
  35. xlsform_lint-0.1.0/tests/test_phase4_config.py +112 -0
  36. xlsform_lint-0.1.0/tests/test_phase4_policy.py +115 -0
  37. xlsform_lint-0.1.0/tests/test_phase5_cli.py +189 -0
  38. xlsform_lint-0.1.0/tests/test_phase5_golden.py +45 -0
  39. xlsform_lint-0.1.0/tests/test_phase5_json.py +65 -0
  40. xlsform_lint-0.1.0/tests/test_phase5_sarif.py +59 -0
  41. xlsform_lint-0.1.0/tests/test_phase5_schema.py +60 -0
  42. xlsform_lint-0.1.0/tests/test_phase6_packaging.py +32 -0
  43. xlsform_lint-0.1.0/tests/test_phase6_precommit.py +43 -0
  44. xlsform_lint-0.1.0/tests/test_phase6_workflows.py +41 -0
  45. xlsform_lint-0.1.0/tests/test_phase7_contracts.py +117 -0
  46. xlsform_lint-0.1.0/tests/test_phase7_larger_forms.py +101 -0
  47. xlsform_lint-0.1.0/tests/test_px999_cli.py +88 -0
  48. xlsform_lint-0.1.0/tests/test_text_formatter.py +60 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: xlsform-lint
3
+ Version: 0.1.0
4
+ Summary: Ruff/ESLint-style developer linter for XLSForm
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/imshahinul/xlsform-lint
7
+ Project-URL: Issues, https://github.com/imshahinul/xlsform-lint/issues
8
+ Requires-Python: >=3.11
9
+ License-File: LICENSE
10
+ Requires-Dist: pyxform<4.6,>=4.5
11
+ Requires-Dist: openpyxl==3.1.5
12
+ Provides-Extra: dev
13
+ Requires-Dist: build<2,>=1; extra == "dev"
14
+ Requires-Dist: pytest>=8; extra == "dev"
15
+ Requires-Dist: jsonschema<5,>=4; extra == "dev"
16
+ Requires-Dist: pre-commit<5,>=3; extra == "dev"
17
+ Dynamic: license-file
@@ -0,0 +1,95 @@
1
+ # xlsform-lint
2
+
3
+ `xlsform-lint` is a developer-oriented, Ruff/ESLint-style linter for XLSForm.
4
+ It combines pyxform semantic validation with seven narrow native diagnostics and
5
+ supports deterministic text, JSON v1, and SARIF output. pyxform is the semantic
6
+ authority: this tool makes selected upstream failures easier to act on and adds
7
+ bounded authoring checks; it does not replace pyxform or XLSForm testing on the
8
+ target data-collection platform.
9
+
10
+ Version 0.1.0 is prepared for the first public release but is not yet published.
11
+ The project does not validate runtime XPath behavior, execute a form, load or
12
+ validate external CSV data, or claim to find everything outside pyxform's
13
+ validation.
14
+
15
+ ## Installation
16
+
17
+ Python 3.11 or newer is required. The package supports pyxform 4.5.x
18
+ (`pyxform>=4.5,<4.6`) and pins openpyxl 3.1.5.
19
+
20
+ For a local checkout or a built wheel:
21
+
22
+ ```bash
23
+ python -m pip install .
24
+ python -m pip install dist/xlsform_lint-0.1.0-py3-none-any.whl
25
+ ```
26
+
27
+ After the first public package release, the following will be the public
28
+ installation syntax. It is **future syntax only**; version 0.1.0 is prepared
29
+ locally but is not currently published on PyPI:
30
+
31
+ ```bash
32
+ python -m pip install xlsform-lint
33
+ ```
34
+
35
+ See [installation details](docs/installation.md).
36
+
37
+ ## Usage and output
38
+
39
+ Lint one workbook. Errors fail by default; warnings and information are shown
40
+ but do not fail:
41
+
42
+ ```bash
43
+ xlsform-lint FORM.xlsx
44
+ xlsform-lint FORM.xlsx --fail-on warning
45
+ xlsform-lint FORM.xlsx --format json
46
+ xlsform-lint FORM.xlsx --format sarif
47
+ ```
48
+
49
+ Text is intended for people. JSON follows the tracked
50
+ [JSON v1 schema](schemas/xlsform-lint-output-v1.schema.json). SARIF provides an
51
+ interchange format, although XLSX cells do not map naturally to source-code line
52
+ annotations.
53
+
54
+ ## Configuration and policy
55
+
56
+ Store policy in `.xlsform-lint.toml`. Discovery starts at the workbook's
57
+ directory and uses the nearest ancestor file; `--config PATH` selects one file
58
+ explicitly. Resolution order is built-ins, selected `default` or `strict`
59
+ profile, config, then explicit CLI settings.
60
+
61
+ ```toml
62
+ profile = "strict"
63
+
64
+ [lint]
65
+ fail_on = "warning"
66
+ format = "text"
67
+
68
+ [rules]
69
+ UX001 = "error"
70
+
71
+ [select]
72
+ include = ["PX", "CHO", "LBL", "I18N", "UX", "ORD"]
73
+ ignore = ["UX002"]
74
+ ```
75
+
76
+ `--select RULES` and `--ignore RULES` accept comma-separated exact IDs or the
77
+ prefixes `PX`, `CHO`, `LBL`, `I18N`, `UX`, and `ORD`. `--fail-on` accepts
78
+ `error`, `warning`, or `info`; `--profile` accepts `default` or `strict`.
79
+ See the complete [configuration reference](docs/configuration.md).
80
+
81
+ ## Integrations and reference
82
+
83
+ - [Rule catalog](docs/rules.md)
84
+ - [Configuration reference](docs/configuration.md)
85
+ - [Pre-commit](docs/pre-commit.md)
86
+ - [GitHub Actions](docs/github-actions.md)
87
+ - [Installation details](docs/installation.md)
88
+
89
+ The supported V1 public interface is the CLI. Python implementation modules are
90
+ internal unless explicitly exported and documented. The frozen architecture is
91
+ recorded in [`xlsform-lint-v1-blueprint.md`](xlsform-lint-v1-blueprint.md).
92
+
93
+ ## License
94
+
95
+ `xlsform-lint` is licensed under the [Apache License 2.0](LICENSE).
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "xlsform-lint"
7
+ version = "0.1.0"
8
+ description = "Ruff/ESLint-style developer linter for XLSForm"
9
+ requires-python = ">=3.11"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ dependencies = [
13
+ "pyxform>=4.5,<4.6",
14
+ "openpyxl==3.1.5",
15
+ ]
16
+
17
+ [project.urls]
18
+ Repository = "https://github.com/imshahinul/xlsform-lint"
19
+ Issues = "https://github.com/imshahinul/xlsform-lint/issues"
20
+
21
+ [project.scripts]
22
+ xlsform-lint = "xlsform_lint.cli:main"
23
+
24
+ [project.optional-dependencies]
25
+ dev = [
26
+ "build>=1,<2",
27
+ "pytest>=8",
28
+ "jsonschema>=4,<5",
29
+ "pre-commit>=3,<5",
30
+ ]
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.pytest.ini_options]
36
+ testpaths = ["tests"]
37
+ addopts = "-ra"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ """Package marker for xlsform-lint.
2
+
3
+ The supported V1 public interface is the command-line interface. Implementation
4
+ modules are internal unless they are explicitly exported and documented.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ """Module execution entry point."""
2
+
3
+ from .cli import main
4
+
5
+
6
+ raise SystemExit(main())
@@ -0,0 +1,58 @@
1
+ """Stable command-line interface with the Phase 4 policy layer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Sequence
8
+
9
+ from .config import ConfigError, load_config_for, parse_cli_selectors
10
+ from .engine import InputError, lint_workbook
11
+ from .json_formatter import format_json
12
+ from .policy import CliPolicyOptions, apply_policy, exit_code_for_policy, resolve_policy
13
+ from .sarif_formatter import format_sarif
14
+ from .text_formatter import format_diagnostics
15
+
16
+
17
+ def build_parser() -> argparse.ArgumentParser:
18
+ parser = argparse.ArgumentParser(prog="xlsform-lint")
19
+ parser.add_argument("workbook", help="path to one XLSForm .xlsx workbook")
20
+ parser.add_argument("--config", metavar="PATH", help="use this configuration file only")
21
+ parser.add_argument("--select", metavar="RULES", help="report only comma-separated rule IDs or prefixes")
22
+ parser.add_argument("--ignore", metavar="RULES", help="hide comma-separated rule IDs or prefixes")
23
+ parser.add_argument("--profile", choices=("default", "strict"), help="select a built-in policy profile")
24
+ parser.add_argument("--fail-on", choices=("error", "warning", "info"), help="minimum failing severity")
25
+ parser.add_argument("--format", choices=("text", "json", "sarif"), help="output format")
26
+ return parser
27
+
28
+
29
+ def main(argv: Sequence[str] | None = None) -> int:
30
+ """Render lint results and map expected and unexpected failures to exit codes."""
31
+
32
+ args = build_parser().parse_args(argv)
33
+ try:
34
+ config = load_config_for(args.workbook, args.config)
35
+ cli = CliPolicyOptions(
36
+ profile=args.profile,
37
+ fail_on=args.fail_on,
38
+ include=parse_cli_selectors(args.select, "--select") if args.select is not None else None,
39
+ ignore=parse_cli_selectors(args.ignore, "--ignore") if args.ignore is not None else None,
40
+ output_format=args.format,
41
+ )
42
+ policy = resolve_policy(config, cli)
43
+ raw_diagnostics = lint_workbook(args.workbook)
44
+ diagnostics = apply_policy(raw_diagnostics, policy)
45
+ except (ConfigError, InputError) as error:
46
+ print(f"xlsform-lint: error: {error}", file=sys.stderr)
47
+ return 2
48
+ except Exception:
49
+ print("xlsform-lint: internal error", file=sys.stderr)
50
+ return 3
51
+
52
+ formatters = {
53
+ "text": lambda: format_diagnostics(diagnostics),
54
+ "json": lambda: format_json(args.workbook, diagnostics),
55
+ "sarif": lambda: format_sarif(args.workbook, diagnostics),
56
+ }
57
+ sys.stdout.write(formatters[policy.output_format]())
58
+ return exit_code_for_policy(raw_diagnostics, diagnostics, policy)
@@ -0,0 +1,175 @@
1
+ """Deterministic Phase 4 TOML discovery, loading, and validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ import tomllib
8
+
9
+
10
+ CONFIG_FILENAME = ".xlsform-lint.toml"
11
+ PROFILE_NAMES = frozenset({"default", "strict"})
12
+ FAIL_ON_VALUES = frozenset({"error", "warning", "info"})
13
+ FORMAT_VALUES = frozenset({"text", "json", "sarif"})
14
+ NATIVE_SEVERITY_VALUES = frozenset({"error", "warning", "info", "off"})
15
+ SELECTOR_PREFIXES = frozenset({"PX", "CHO", "LBL", "I18N", "UX", "ORD"})
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class RuleMetadata:
20
+ """Policy-only metadata; semantic implementations remain elsewhere."""
21
+
22
+ default_severity: str
23
+ origin: str
24
+ severity_configurable: bool
25
+
26
+
27
+ RULE_CATALOG = {
28
+ **{
29
+ rule_id: RuleMetadata("error", "pyxform", False)
30
+ for rule_id in ("PX001", "PX002", "PX003", "PX004", "PX005", "PX006", "PX999")
31
+ },
32
+ **{
33
+ rule_id: RuleMetadata("warning", "native", True)
34
+ for rule_id in ("CHO001", "LBL001", "LBL002", "I18N001", "UX001", "ORD001")
35
+ },
36
+ "UX002": RuleMetadata("info", "native", True),
37
+ }
38
+ RULE_IDS = frozenset(RULE_CATALOG)
39
+ PX_RULE_IDS = frozenset(
40
+ rule_id for rule_id, metadata in RULE_CATALOG.items() if metadata.origin == "pyxform"
41
+ )
42
+ NATIVE_RULE_IDS = RULE_IDS - PX_RULE_IDS
43
+
44
+
45
+ class ConfigError(Exception):
46
+ """A predictable, user-facing configuration failure."""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ConfigSettings:
51
+ """Validated explicit values from one configuration file."""
52
+
53
+ profile: str | None = None
54
+ fail_on: str | None = None
55
+ rule_overrides: tuple[tuple[str, str], ...] = ()
56
+ include: tuple[str, ...] | None = None
57
+ ignore: tuple[str, ...] | None = None
58
+ output_format: str | None = None
59
+ path: Path | None = None
60
+
61
+
62
+ def discover_config(workbook: str | Path) -> Path | None:
63
+ """Return the nearest config in the workbook parent's ancestry."""
64
+
65
+ start = Path(workbook).expanduser().absolute().parent
66
+ for directory in (start, *start.parents):
67
+ candidate = directory / CONFIG_FILENAME
68
+ if candidate.is_file():
69
+ return candidate
70
+ return None
71
+
72
+
73
+ def _expect_keys(table: dict[str, object], allowed: set[str], context: str) -> None:
74
+ unknown = sorted(set(table) - allowed)
75
+ if unknown:
76
+ raise ConfigError(f"unknown {context} key: {unknown[0]}")
77
+
78
+
79
+ def _string(value: object, context: str, allowed: frozenset[str]) -> str:
80
+ if not isinstance(value, str) or value not in allowed:
81
+ choices = ", ".join(sorted(allowed))
82
+ raise ConfigError(f"{context} must be one of: {choices}")
83
+ return value
84
+
85
+
86
+ def validate_selectors(value: object, context: str) -> tuple[str, ...]:
87
+ """Validate config selectors without accepting coercion or glob syntax."""
88
+
89
+ if not isinstance(value, list):
90
+ raise ConfigError(f"{context} must be a list of selectors")
91
+ result: list[str] = []
92
+ for item in value:
93
+ if not isinstance(item, str):
94
+ raise ConfigError(f"{context} items must be strings")
95
+ selector = item.strip()
96
+ if not selector:
97
+ raise ConfigError(f"{context} contains an empty selector")
98
+ if selector not in RULE_IDS and selector not in SELECTOR_PREFIXES:
99
+ raise ConfigError(f"unknown selector in {context}: {selector}")
100
+ result.append(selector)
101
+ return tuple(result)
102
+
103
+
104
+ def parse_cli_selectors(value: str, option: str) -> tuple[str, ...]:
105
+ """Parse a comma-separated CLI selector value."""
106
+
107
+ tokens = value.split(",")
108
+ if any(not token.strip() for token in tokens):
109
+ raise ConfigError(f"{option} contains an empty selector")
110
+ return validate_selectors([token.strip() for token in tokens], option)
111
+
112
+
113
+ def load_config(path: Path) -> ConfigSettings:
114
+ """Load one TOML file and reject every unsupported field."""
115
+
116
+ if not path.exists():
117
+ raise ConfigError(f"configuration file does not exist: {path}")
118
+ if not path.is_file():
119
+ raise ConfigError(f"configuration path is not a file: {path}")
120
+ try:
121
+ with path.open("rb") as stream:
122
+ data = tomllib.load(stream)
123
+ except (OSError, tomllib.TOMLDecodeError) as error:
124
+ raise ConfigError(f"unable to load configuration {path}: {error}") from error
125
+
126
+ _expect_keys(data, {"profile", "lint", "rules", "select"}, "top-level")
127
+ profile = None
128
+ if "profile" in data:
129
+ profile = _string(data["profile"], "profile", PROFILE_NAMES)
130
+
131
+ lint = data.get("lint", {})
132
+ if not isinstance(lint, dict):
133
+ raise ConfigError("lint must be a table")
134
+ _expect_keys(lint, {"fail_on", "format"}, "lint")
135
+ fail_on = None
136
+ if "fail_on" in lint:
137
+ fail_on = _string(lint["fail_on"], "lint.fail_on", FAIL_ON_VALUES)
138
+ output_format = None
139
+ if "format" in lint:
140
+ output_format = _string(lint["format"], "lint.format", FORMAT_VALUES)
141
+
142
+ rules = data.get("rules", {})
143
+ if not isinstance(rules, dict):
144
+ raise ConfigError("rules must be a table")
145
+ overrides: list[tuple[str, str]] = []
146
+ for rule_id in sorted(rules):
147
+ if rule_id not in RULE_IDS:
148
+ raise ConfigError(f"unknown rule ID: {rule_id}")
149
+ if rule_id in PX_RULE_IDS:
150
+ raise ConfigError(f"PX rule severity is fixed at error: {rule_id}")
151
+ severity = _string(rules[rule_id], f"rules.{rule_id}", NATIVE_SEVERITY_VALUES)
152
+ overrides.append((rule_id, severity))
153
+
154
+ select = data.get("select", {})
155
+ if not isinstance(select, dict):
156
+ raise ConfigError("select must be a table")
157
+ _expect_keys(select, {"include", "ignore"}, "select")
158
+ include = validate_selectors(select["include"], "select.include") if "include" in select else None
159
+ ignore = validate_selectors(select["ignore"], "select.ignore") if "ignore" in select else None
160
+ return ConfigSettings(
161
+ profile=profile,
162
+ fail_on=fail_on,
163
+ rule_overrides=tuple(overrides),
164
+ include=include,
165
+ ignore=ignore,
166
+ output_format=output_format,
167
+ path=path,
168
+ )
169
+
170
+
171
+ def load_config_for(workbook: str | Path, explicit_path: str | Path | None) -> ConfigSettings:
172
+ """Use an explicit config only, otherwise discover by input ancestry."""
173
+
174
+ path = Path(explicit_path).expanduser() if explicit_path is not None else discover_config(workbook)
175
+ return ConfigSettings() if path is None else load_config(path)