patchlint 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 (47) hide show
  1. patchlint-0.1.0/.gitignore +8 -0
  2. patchlint-0.1.0/CHANGELOG.md +26 -0
  3. patchlint-0.1.0/LICENSE +21 -0
  4. patchlint-0.1.0/PKG-INFO +150 -0
  5. patchlint-0.1.0/README.md +117 -0
  6. patchlint-0.1.0/pyproject.toml +64 -0
  7. patchlint-0.1.0/src/patchlint/__init__.py +3 -0
  8. patchlint-0.1.0/src/patchlint/cli.py +111 -0
  9. patchlint-0.1.0/src/patchlint/config.py +120 -0
  10. patchlint-0.1.0/src/patchlint/core/__init__.py +0 -0
  11. patchlint-0.1.0/src/patchlint/core/model.py +74 -0
  12. patchlint-0.1.0/src/patchlint/core/registry.py +48 -0
  13. patchlint-0.1.0/src/patchlint/core/runner.py +96 -0
  14. patchlint-0.1.0/src/patchlint/parsers/__init__.py +0 -0
  15. patchlint-0.1.0/src/patchlint/parsers/dockerfile.py +32 -0
  16. patchlint-0.1.0/src/patchlint/parsers/github_actions.py +78 -0
  17. patchlint-0.1.0/src/patchlint/rules/__init__.py +0 -0
  18. patchlint-0.1.0/src/patchlint/rules/dockerfile/DL001_root_user.py +31 -0
  19. patchlint-0.1.0/src/patchlint/rules/dockerfile/DL002_unpinned_base_image.py +39 -0
  20. patchlint-0.1.0/src/patchlint/rules/dockerfile/__init__.py +0 -0
  21. patchlint-0.1.0/src/patchlint/rules/github_actions/GA001_unpinned_action.py +44 -0
  22. patchlint-0.1.0/src/patchlint/rules/github_actions/GA002_script_injection.py +57 -0
  23. patchlint-0.1.0/src/patchlint/rules/github_actions/GA003_missing_permissions.py +39 -0
  24. patchlint-0.1.0/src/patchlint/rules/github_actions/GA004_pull_request_target_checkout.py +74 -0
  25. patchlint-0.1.0/src/patchlint/rules/github_actions/GA008_secrets_inherit.py +45 -0
  26. patchlint-0.1.0/src/patchlint/rules/github_actions/__init__.py +0 -0
  27. patchlint-0.1.0/src/patchlint/sarif.py +93 -0
  28. patchlint-0.1.0/src/patchlint/scaffold.py +88 -0
  29. patchlint-0.1.0/tests/fixtures/DL001/bad/Dockerfile +3 -0
  30. patchlint-0.1.0/tests/fixtures/DL001/good/Dockerfile +5 -0
  31. patchlint-0.1.0/tests/fixtures/DL002/bad/Dockerfile +2 -0
  32. patchlint-0.1.0/tests/fixtures/DL002/good/Dockerfile +3 -0
  33. patchlint-0.1.0/tests/fixtures/GA001/bad/workflow.yml +7 -0
  34. patchlint-0.1.0/tests/fixtures/GA001/good/workflow.yml +10 -0
  35. patchlint-0.1.0/tests/fixtures/GA002/bad/workflow.yml +8 -0
  36. patchlint-0.1.0/tests/fixtures/GA002/good/workflow.yml +11 -0
  37. patchlint-0.1.0/tests/fixtures/GA003/bad/workflow.yml +7 -0
  38. patchlint-0.1.0/tests/fixtures/GA003/good/workflow.yml +8 -0
  39. patchlint-0.1.0/tests/fixtures/GA004/bad/workflow.yml +10 -0
  40. patchlint-0.1.0/tests/fixtures/GA004/good/workflow.yml +10 -0
  41. patchlint-0.1.0/tests/fixtures/GA008/bad/workflow.yml +7 -0
  42. patchlint-0.1.0/tests/fixtures/GA008/good/workflow.yml +11 -0
  43. patchlint-0.1.0/tests/test_config.py +109 -0
  44. patchlint-0.1.0/tests/test_github_actions.py +66 -0
  45. patchlint-0.1.0/tests/test_parser_cli.py +33 -0
  46. patchlint-0.1.0/tests/test_rules.py +39 -0
  47. patchlint-0.1.0/tests/test_sarif.py +77 -0
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ .venv/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .mypy_cache/
8
+ .ruff_cache/
@@ -0,0 +1,26 @@
1
+ # Changelog
2
+
3
+ All notable changes are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0] - 2026-11-25
8
+
9
+ First public release.
10
+
11
+ ### Added
12
+ - Scans **Dockerfiles** and **GitHub Actions workflows**; every finding explains why it matters and how to fix it.
13
+ - Rules:
14
+ - `DL001` container runs as root
15
+ - `DL002` base image not pinned
16
+ - `GA001` action not pinned to a commit SHA
17
+ - `GA002` untrusted input in a `run:` script (script injection)
18
+ - `GA003` no top-level `permissions:` block (thanks @ljw1558)
19
+ - `GA004` `pull_request_target` workflow checks out the pull request's code (thanks @ljw1558)
20
+ - `GA008` `secrets: inherit` to a reusable workflow in another repository (thanks @SVR1339)
21
+ - Output as text, JSON or SARIF 2.1.0 (`--format sarif`) for GitHub code scanning; `-o FILE` and `--exit-zero`.
22
+ - Configuration in `.patchlint.toml` or `[tool.patchlint]`: `disable`, `exclude` and per-rule `[severity]`, with strict validation.
23
+ - `patchlint new-rule` scaffold for contributors; fixture-driven tests need no test code per rule.
24
+
25
+ [Unreleased]: https://github.com/RubahAnomali/patchlint/compare/v0.1.0...HEAD
26
+ [0.1.0]: https://github.com/RubahAnomali/patchlint/releases/tag/v0.1.0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 patchlint contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.5
2
+ Name: patchlint
3
+ Version: 0.1.0
4
+ Summary: A beginner-friendly security linter for Dockerfiles and GitHub Actions workflows. Every finding explains why and how to fix it.
5
+ Project-URL: Homepage, https://github.com/RubahAnomali/patchlint
6
+ Project-URL: Issues, https://github.com/RubahAnomali/patchlint/issues
7
+ Project-URL: Changelog, https://github.com/RubahAnomali/patchlint/blob/main/CHANGELOG.md
8
+ Author: RubahAnomali
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: devsecops,dockerfile,github-actions,linter,sarif,security
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: Software Development :: Quality Assurance
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: pyyaml>=6.0
26
+ Requires-Dist: tomli>=2.0; python_version < '3.11'
27
+ Provides-Extra: dev
28
+ Requires-Dist: mypy>=1.10; extra == 'dev'
29
+ Requires-Dist: pytest>=8; extra == 'dev'
30
+ Requires-Dist: ruff>=0.5; extra == 'dev'
31
+ Requires-Dist: types-pyyaml; extra == 'dev'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # patchlint
35
+
36
+ A small, beginner-friendly security linter for config files. Every finding tells you **why** it matters and **how to fix it**.
37
+
38
+ > Status: early (v0.1 in progress). Supports **Dockerfiles** and **GitHub Actions workflows**; docker-compose is on the [roadmap](ROADMAP.md).
39
+
40
+ | Files | Found by a directory scan | Rule prefix |
41
+ |---|---|---|
42
+ | Dockerfiles | `Dockerfile`, `Dockerfile.*`, `*.dockerfile` | `DL` |
43
+ | GitHub Actions workflows | `.github/workflows/*.yml` / `*.yaml` | `GA` |
44
+
45
+ ## Install and try
46
+
47
+ ```bash
48
+ pip install patchlint # once published; for now: pip install -e ".[dev]"
49
+ patchlint scan .
50
+ patchlint list-rules
51
+ patchlint explain DL001
52
+ ```
53
+
54
+ Example output:
55
+
56
+ ```
57
+ Dockerfile:1: [DL001/high] Final stage runs as root (no non-root USER set).
58
+ fix: Add `USER <non-root-user>` after installing packages.
59
+ .github/workflows/triage.yml:8: [GA002/high] `github.event.issue.title` is attacker-controlled and is pasted into the script.
60
+ fix: Move it to `env:` and use the variable, quoted, in the script.
61
+ ```
62
+
63
+ Exit code is `1` when findings exist, so it works in CI.
64
+
65
+ | Option | What it does |
66
+ |---|---|
67
+ | `--format json` | Machine-readable list of findings |
68
+ | `--format sarif` | [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html), for GitHub code scanning and IDEs |
69
+ | `-o FILE` | Write the report to a file instead of the terminal |
70
+ | `--exit-zero` | Exit `0` even with findings (useful before uploading a report) |
71
+ | `--rule ID` | Only run this rule (repeatable); overrides `disable` in the config |
72
+ | `--config FILE` / `--no-config` | Use a specific config file, or ignore config files |
73
+
74
+ ## Configuration
75
+
76
+ Put a `.patchlint.toml` in the folder you scan (or a `[tool.patchlint]` table in `pyproject.toml`):
77
+
78
+ ```toml
79
+ disable = ["DL002"] # turn rules off
80
+ exclude = ["tests/fixtures/*"] # skip paths (globs relative to the scanned folder; * also matches /)
81
+
82
+ [severity] # change a rule's severity: low, medium or high
83
+ GA001 = "high"
84
+ ```
85
+
86
+ Unknown keys, rule ids or severities stop the scan with an error that says what to fix, so typos never silently disable checks.
87
+
88
+ ## Show findings in GitHub's Security tab
89
+
90
+ Upload SARIF to GitHub code scanning, and findings appear as alerts on the right lines, including in pull requests. Add `.github/workflows/patchlint.yml`:
91
+
92
+ ```yaml
93
+ name: patchlint
94
+ on:
95
+ push:
96
+ branches: [main]
97
+ pull_request:
98
+ permissions:
99
+ contents: read
100
+ jobs:
101
+ scan:
102
+ runs-on: ubuntu-latest
103
+ permissions:
104
+ contents: read
105
+ security-events: write # needed to upload SARIF
106
+ steps:
107
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
108
+ with:
109
+ persist-credentials: false
110
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
111
+ with:
112
+ python-version: "3.12"
113
+ - run: pip install patchlint
114
+ - run: patchlint scan . --format sarif -o patchlint.sarif --exit-zero
115
+ - uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
116
+ with:
117
+ sarif_file: patchlint.sarif
118
+ ```
119
+
120
+ Code scanning is free for public repositories. The actions are pinned to commit SHAs, which is what rule GA001 asks for.
121
+
122
+ ## Contribute in 30 minutes
123
+
124
+ Each rule is one small file. Pick an issue labelled
125
+ [`good first issue`](../../labels/good%20first%20issue), then:
126
+
127
+ ```bash
128
+ pip install -e ".[dev]"
129
+ patchlint new-rule DL003 add_instead_of_copy # Dockerfile rule + fixtures
130
+ patchlint new-rule GA003 missing_permissions # GitHub Actions rule + fixtures
131
+ # edit the rule, edit the two fixtures, then:
132
+ pytest
133
+ ```
134
+
135
+ Full walkthrough: [CONTRIBUTING.md](CONTRIBUTING.md).
136
+
137
+ ## Project layout
138
+
139
+ ```
140
+ src/patchlint/
141
+ rules/dockerfile/ one file per Dockerfile rule (DL001_root_user.py ...)
142
+ rules/github_actions/ one file per workflow rule (GA001_unpinned_action.py ...)
143
+ parsers/ file-format parsers
144
+ core/ rule registry, runner, data types
145
+ tests/fixtures/<ID>/{bad,good}/ one file in each; every rule needs both
146
+ ```
147
+
148
+ ## License
149
+
150
+ MIT, see [LICENSE](LICENSE). Report vulnerabilities privately: see [SECURITY.md](SECURITY.md).
@@ -0,0 +1,117 @@
1
+ # patchlint
2
+
3
+ A small, beginner-friendly security linter for config files. Every finding tells you **why** it matters and **how to fix it**.
4
+
5
+ > Status: early (v0.1 in progress). Supports **Dockerfiles** and **GitHub Actions workflows**; docker-compose is on the [roadmap](ROADMAP.md).
6
+
7
+ | Files | Found by a directory scan | Rule prefix |
8
+ |---|---|---|
9
+ | Dockerfiles | `Dockerfile`, `Dockerfile.*`, `*.dockerfile` | `DL` |
10
+ | GitHub Actions workflows | `.github/workflows/*.yml` / `*.yaml` | `GA` |
11
+
12
+ ## Install and try
13
+
14
+ ```bash
15
+ pip install patchlint # once published; for now: pip install -e ".[dev]"
16
+ patchlint scan .
17
+ patchlint list-rules
18
+ patchlint explain DL001
19
+ ```
20
+
21
+ Example output:
22
+
23
+ ```
24
+ Dockerfile:1: [DL001/high] Final stage runs as root (no non-root USER set).
25
+ fix: Add `USER <non-root-user>` after installing packages.
26
+ .github/workflows/triage.yml:8: [GA002/high] `github.event.issue.title` is attacker-controlled and is pasted into the script.
27
+ fix: Move it to `env:` and use the variable, quoted, in the script.
28
+ ```
29
+
30
+ Exit code is `1` when findings exist, so it works in CI.
31
+
32
+ | Option | What it does |
33
+ |---|---|
34
+ | `--format json` | Machine-readable list of findings |
35
+ | `--format sarif` | [SARIF 2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html), for GitHub code scanning and IDEs |
36
+ | `-o FILE` | Write the report to a file instead of the terminal |
37
+ | `--exit-zero` | Exit `0` even with findings (useful before uploading a report) |
38
+ | `--rule ID` | Only run this rule (repeatable); overrides `disable` in the config |
39
+ | `--config FILE` / `--no-config` | Use a specific config file, or ignore config files |
40
+
41
+ ## Configuration
42
+
43
+ Put a `.patchlint.toml` in the folder you scan (or a `[tool.patchlint]` table in `pyproject.toml`):
44
+
45
+ ```toml
46
+ disable = ["DL002"] # turn rules off
47
+ exclude = ["tests/fixtures/*"] # skip paths (globs relative to the scanned folder; * also matches /)
48
+
49
+ [severity] # change a rule's severity: low, medium or high
50
+ GA001 = "high"
51
+ ```
52
+
53
+ Unknown keys, rule ids or severities stop the scan with an error that says what to fix, so typos never silently disable checks.
54
+
55
+ ## Show findings in GitHub's Security tab
56
+
57
+ Upload SARIF to GitHub code scanning, and findings appear as alerts on the right lines, including in pull requests. Add `.github/workflows/patchlint.yml`:
58
+
59
+ ```yaml
60
+ name: patchlint
61
+ on:
62
+ push:
63
+ branches: [main]
64
+ pull_request:
65
+ permissions:
66
+ contents: read
67
+ jobs:
68
+ scan:
69
+ runs-on: ubuntu-latest
70
+ permissions:
71
+ contents: read
72
+ security-events: write # needed to upload SARIF
73
+ steps:
74
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
75
+ with:
76
+ persist-credentials: false
77
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
78
+ with:
79
+ python-version: "3.12"
80
+ - run: pip install patchlint
81
+ - run: patchlint scan . --format sarif -o patchlint.sarif --exit-zero
82
+ - uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
83
+ with:
84
+ sarif_file: patchlint.sarif
85
+ ```
86
+
87
+ Code scanning is free for public repositories. The actions are pinned to commit SHAs, which is what rule GA001 asks for.
88
+
89
+ ## Contribute in 30 minutes
90
+
91
+ Each rule is one small file. Pick an issue labelled
92
+ [`good first issue`](../../labels/good%20first%20issue), then:
93
+
94
+ ```bash
95
+ pip install -e ".[dev]"
96
+ patchlint new-rule DL003 add_instead_of_copy # Dockerfile rule + fixtures
97
+ patchlint new-rule GA003 missing_permissions # GitHub Actions rule + fixtures
98
+ # edit the rule, edit the two fixtures, then:
99
+ pytest
100
+ ```
101
+
102
+ Full walkthrough: [CONTRIBUTING.md](CONTRIBUTING.md).
103
+
104
+ ## Project layout
105
+
106
+ ```
107
+ src/patchlint/
108
+ rules/dockerfile/ one file per Dockerfile rule (DL001_root_user.py ...)
109
+ rules/github_actions/ one file per workflow rule (GA001_unpinned_action.py ...)
110
+ parsers/ file-format parsers
111
+ core/ rule registry, runner, data types
112
+ tests/fixtures/<ID>/{bad,good}/ one file in each; every rule needs both
113
+ ```
114
+
115
+ ## License
116
+
117
+ MIT, see [LICENSE](LICENSE). Report vulnerabilities privately: see [SECURITY.md](SECURITY.md).
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "patchlint"
7
+ dynamic = ["version"]
8
+ description = "A beginner-friendly security linter for Dockerfiles and GitHub Actions workflows. Every finding explains why and how to fix it."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "RubahAnomali" }]
14
+ keywords = ["security", "linter", "dockerfile", "github-actions", "sarif", "devsecops"]
15
+ dependencies = ["pyyaml>=6.0", "tomli>=2.0; python_version < '3.11'"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Environment :: Console",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Security",
28
+ "Topic :: Software Development :: Quality Assurance",
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/RubahAnomali/patchlint"
33
+ Issues = "https://github.com/RubahAnomali/patchlint/issues"
34
+ Changelog = "https://github.com/RubahAnomali/patchlint/blob/main/CHANGELOG.md"
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["pytest>=8", "ruff>=0.5", "mypy>=1.10", "types-PyYAML"]
38
+
39
+ [project.scripts]
40
+ patchlint = "patchlint.cli:main"
41
+
42
+ [tool.hatch.version]
43
+ path = "src/patchlint/__init__.py"
44
+
45
+ [tool.hatch.build.targets.wheel]
46
+ packages = ["src/patchlint"]
47
+
48
+ # Only these go into the source package on PyPI (keeps local, untracked files out).
49
+ [tool.hatch.build.targets.sdist]
50
+ only-include = ["src", "tests", "README.md", "LICENSE", "CHANGELOG.md", "pyproject.toml"]
51
+
52
+ [tool.pytest.ini_options]
53
+ testpaths = ["tests"]
54
+
55
+ [tool.ruff]
56
+ line-length = 100
57
+ src = ["src", "tests"]
58
+
59
+ [tool.ruff.lint]
60
+ select = ["E", "F", "I", "B", "UP"]
61
+
62
+ [tool.mypy]
63
+ strict = true
64
+ files = ["src"]
@@ -0,0 +1,3 @@
1
+ """patchlint: a beginner-friendly security linter for config files."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,111 @@
1
+ """Command-line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from dataclasses import asdict
9
+ from pathlib import Path
10
+
11
+ from patchlint import __version__
12
+ from patchlint.config import Config, ConfigError, find_config, load_config
13
+ from patchlint.core.registry import load_rules
14
+ from patchlint.core.runner import scan
15
+ from patchlint.sarif import to_sarif
16
+ from patchlint.scaffold import new_rule
17
+
18
+
19
+ def main(argv: list[str] | None = None) -> int:
20
+ p = argparse.ArgumentParser(prog="patchlint", description=__doc__)
21
+ p.add_argument("--version", action="version", version=__version__)
22
+ sub = p.add_subparsers(dest="cmd", required=True)
23
+
24
+ s = sub.add_parser("scan", help="scan a file or directory")
25
+ s.add_argument("path", type=Path, nargs="?", default=Path("."))
26
+ s.add_argument("--format", choices=["text", "json", "sarif"], default="text")
27
+ s.add_argument("--rule", action="append", help="only run this rule id (repeatable)")
28
+ s.add_argument("-o", "--output", type=Path, help="write results to this file, not stdout")
29
+ cfg = s.add_mutually_exclusive_group()
30
+ cfg.add_argument(
31
+ "--config", type=Path, help="config file (default: .patchlint.toml or pyproject.toml)"
32
+ )
33
+ cfg.add_argument("--no-config", action="store_true", help="ignore any config file")
34
+ s.add_argument(
35
+ "--exit-zero",
36
+ action="store_true",
37
+ help="exit 0 even when there are findings (e.g. before uploading SARIF)",
38
+ )
39
+
40
+ sub.add_parser("list-rules", help="list all rules")
41
+
42
+ e = sub.add_parser("explain", help="show why a rule exists and how to fix it")
43
+ e.add_argument("rule_id")
44
+
45
+ n = sub.add_parser("new-rule", help="scaffold a new rule and its fixtures")
46
+ n.add_argument("rule_id", help="e.g. DL003")
47
+ n.add_argument("name", help="lower_snake_case, e.g. add_instead_of_copy")
48
+
49
+ args = p.parse_args(argv)
50
+
51
+ if args.cmd == "list-rules":
52
+ for r in load_rules().values():
53
+ print(f"{r.id} {r.severity:<6} {r.title}")
54
+ return 0
55
+
56
+ if args.cmd == "explain":
57
+ found = load_rules().get(args.rule_id.upper())
58
+ if found is None:
59
+ print(f"unknown rule {args.rule_id}", file=sys.stderr)
60
+ return 2
61
+ cwe = f" (CWE-{found.cwe})" if found.cwe else ""
62
+ print(f"{found.id}: {found.title}{cwe}\nSeverity: {found.severity}\n\n{found.doc}")
63
+ return 0
64
+
65
+ if args.cmd == "new-rule":
66
+ try:
67
+ created = new_rule(args.rule_id.upper(), args.name, Path.cwd())
68
+ except (ValueError, FileExistsError) as exc:
69
+ print(f"error: {exc}", file=sys.stderr)
70
+ return 2
71
+ for path in created:
72
+ print(f"created {path}")
73
+ return 0
74
+
75
+ rules = load_rules()
76
+ if args.rule:
77
+ unknown = sorted({r.upper() for r in args.rule} - set(rules))
78
+ if unknown:
79
+ print(f"error: unknown rule id(s): {unknown}", file=sys.stderr)
80
+ return 2
81
+ config = Config()
82
+ if not args.no_config:
83
+ config_path = args.config or find_config(args.path)
84
+ if config_path is not None:
85
+ try:
86
+ config = load_config(config_path, rules)
87
+ except (ConfigError, OSError) as exc:
88
+ print(f"error: {exc}", file=sys.stderr)
89
+ return 2
90
+ only = [r.upper() for r in args.rule] if args.rule else None
91
+ findings = scan(args.path, only, config)
92
+ if args.format == "json":
93
+ report = json.dumps([asdict(f) for f in findings], indent=2)
94
+ elif args.format == "sarif":
95
+ report = json.dumps(to_sarif(findings, rules), indent=2)
96
+ else:
97
+ lines = [
98
+ f"{f.path}:{f.line}: [{f.rule_id}/{f.severity}] {f.message}\n fix: {f.fix}"
99
+ for f in findings
100
+ ]
101
+ report = "\n".join([*lines, f"\n{len(findings)} finding(s)"])
102
+ if args.output:
103
+ args.output.write_text(report + "\n", encoding="utf-8")
104
+ print(f"wrote {len(findings)} finding(s) to {args.output}", file=sys.stderr)
105
+ else:
106
+ print(report)
107
+ return 1 if findings and not args.exit_zero else 0
108
+
109
+
110
+ if __name__ == "__main__":
111
+ raise SystemExit(main())
@@ -0,0 +1,120 @@
1
+ """Project configuration: `.patchlint.toml`, or `[tool.patchlint]` in `pyproject.toml`.
2
+
3
+ Example `.patchlint.toml`:
4
+
5
+ disable = ["DL002"] # rules to turn off
6
+ exclude = ["tests/fixtures/*"] # paths to skip (globs, relative to the scanned folder)
7
+
8
+ [severity] # change a rule's severity
9
+ GA001 = "high"
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import sys
15
+ from collections.abc import Collection, Mapping
16
+ from dataclasses import dataclass, field
17
+ from fnmatch import fnmatch
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from patchlint.core.model import SEVERITIES
22
+
23
+ if sys.version_info >= (3, 11):
24
+ import tomllib
25
+ else: # pragma: no cover - exercised on Python 3.10 only
26
+ import tomli as tomllib
27
+
28
+ CONFIG_FILE = ".patchlint.toml"
29
+ KNOWN_KEYS = {"disable", "exclude", "severity"}
30
+
31
+
32
+ class ConfigError(ValueError):
33
+ """The configuration file is invalid. The message says what to fix."""
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Config:
38
+ disable: frozenset[str] = frozenset()
39
+ exclude: tuple[str, ...] = ()
40
+ severity: Mapping[str, str] = field(default_factory=dict)
41
+ source: Path | None = None
42
+
43
+ def is_excluded(self, path: Path, root: Path) -> bool:
44
+ """True if `path` matches an exclude glob. `*` also matches `/`."""
45
+ try:
46
+ rel = path.resolve().relative_to(root.resolve()).as_posix()
47
+ except ValueError:
48
+ rel = path.as_posix()
49
+ return any(fnmatch(rel, pattern) for pattern in self.exclude)
50
+
51
+
52
+ def find_config(start: Path) -> Path | None:
53
+ """Look for `.patchlint.toml`, then a `pyproject.toml` with `[tool.patchlint]`,
54
+ in the scanned folder (or the scanned file's folder)."""
55
+ folder = start if start.is_dir() else start.parent
56
+ candidate = folder / CONFIG_FILE
57
+ if candidate.is_file():
58
+ return candidate
59
+ pyproject = folder / "pyproject.toml"
60
+ if pyproject.is_file():
61
+ try:
62
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
63
+ except tomllib.TOMLDecodeError:
64
+ return None # a broken pyproject.toml is not our problem to report
65
+ if isinstance(data.get("tool"), dict) and "patchlint" in data["tool"]:
66
+ return pyproject
67
+ return None
68
+
69
+
70
+ def load_config(path: Path, known_rules: Collection[str]) -> Config:
71
+ """Read and validate a config file."""
72
+ try:
73
+ data: dict[str, Any] = tomllib.loads(path.read_text(encoding="utf-8"))
74
+ except tomllib.TOMLDecodeError as exc:
75
+ raise ConfigError(f"{path}: invalid TOML ({exc})") from exc
76
+ if path.name == "pyproject.toml":
77
+ data = data.get("tool", {}).get("patchlint", {})
78
+ if not isinstance(data, dict):
79
+ raise ConfigError(f"{path}: [tool.patchlint] must be a table")
80
+ return parse_config(data, known_rules, path)
81
+
82
+
83
+ def parse_config(
84
+ data: Mapping[str, Any], known_rules: Collection[str], source: Path | None = None
85
+ ) -> Config:
86
+ where = str(source) if source else "config"
87
+ unknown = set(data) - KNOWN_KEYS
88
+ if unknown:
89
+ raise ConfigError(
90
+ f"{where}: unknown key(s) {sorted(unknown)}; allowed: {sorted(KNOWN_KEYS)}"
91
+ )
92
+
93
+ def rule_list(key: str) -> list[str]:
94
+ value = data.get(key, [])
95
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
96
+ raise ConfigError(f"{where}: `{key}` must be a list of strings")
97
+ return value
98
+
99
+ disable = [r.upper() for r in rule_list("disable")]
100
+ bad = sorted(set(disable) - set(known_rules))
101
+ if bad:
102
+ raise ConfigError(f"{where}: unknown rule id(s) in `disable`: {bad}")
103
+
104
+ exclude = rule_list("exclude")
105
+
106
+ severity_raw = data.get("severity", {})
107
+ if not isinstance(severity_raw, dict):
108
+ raise ConfigError(f"{where}: `[severity]` must be a table like `GA001 = \"high\"`")
109
+ severity: dict[str, str] = {}
110
+ for rule_id, level in severity_raw.items():
111
+ rule_id = rule_id.upper()
112
+ if rule_id not in known_rules:
113
+ raise ConfigError(f"{where}: unknown rule id in `[severity]`: {rule_id}")
114
+ if level not in SEVERITIES:
115
+ raise ConfigError(
116
+ f"{where}: severity for {rule_id} must be one of {list(SEVERITIES)}, got {level!r}"
117
+ )
118
+ severity[rule_id] = level
119
+
120
+ return Config(frozenset(disable), tuple(exclude), severity, source)
File without changes