polycheck 0.2.0__py3-none-any.whl

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 (42) hide show
  1. polycheck/__init__.py +19 -0
  2. polycheck/cli.py +791 -0
  3. polycheck/config.py +123 -0
  4. polycheck/detect.py +151 -0
  5. polycheck/finding.py +131 -0
  6. polycheck/initializer.py +333 -0
  7. polycheck/languages/__init__.py +10 -0
  8. polycheck/mcp_server.py +994 -0
  9. polycheck/py.typed +0 -0
  10. polycheck/registry.py +119 -0
  11. polycheck/reporters/__init__.py +33 -0
  12. polycheck/reporters/json_reporter.py +58 -0
  13. polycheck/reporters/markdown_reporter.py +141 -0
  14. polycheck/reporters/sarif_reporter.py +114 -0
  15. polycheck/runner.py +279 -0
  16. polycheck/session.py +134 -0
  17. polycheck/tools/__init__.py +10 -0
  18. polycheck/tools/actionlint.py +66 -0
  19. polycheck/tools/base.py +449 -0
  20. polycheck/tools/depcheck.py +96 -0
  21. polycheck/tools/deptry.py +83 -0
  22. polycheck/tools/eslint.py +89 -0
  23. polycheck/tools/gitleaks.py +78 -0
  24. polycheck/tools/hadolint.py +75 -0
  25. polycheck/tools/knip.py +84 -0
  26. polycheck/tools/mypy.py +85 -0
  27. polycheck/tools/npm_audit.py +74 -0
  28. polycheck/tools/pip_audit.py +132 -0
  29. polycheck/tools/ruff.py +80 -0
  30. polycheck/tools/semgrep.py +80 -0
  31. polycheck/tools/shellcheck.py +80 -0
  32. polycheck/tools/sonarless.py +238 -0
  33. polycheck/tools/tsc.py +77 -0
  34. polycheck/tools/vulture.py +82 -0
  35. polycheck/verify.py +288 -0
  36. polycheck/workflows/__init__.py +76 -0
  37. polycheck-0.2.0.dist-info/METADATA +614 -0
  38. polycheck-0.2.0.dist-info/RECORD +42 -0
  39. polycheck-0.2.0.dist-info/WHEEL +5 -0
  40. polycheck-0.2.0.dist-info/entry_points.txt +2 -0
  41. polycheck-0.2.0.dist-info/licenses/LICENSE +21 -0
  42. polycheck-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,80 @@
1
+ """ruff — fast Python linter + formatter (lint mode for findings).
2
+
3
+ ruff emits JSON when given ``--output-format=json``. Each item has
4
+ ``code`` (rule id), ``message``, ``location.row``/``column``, and
5
+ ``filename``. Most rules are auto-fixable via ``ruff check --fix``.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import subprocess
11
+ from pathlib import Path
12
+
13
+ from ..finding import Category, Finding, Severity
14
+ from .base import Tool
15
+
16
+ # Bug-shaped rules that survive the default MEDIUM severity filter:
17
+ # F821 undefined name and F811 redefinition break at runtime.
18
+ _HIGH_RULES = {"F821", "F811"}
19
+ # Comparison/exception handling mistakes (== None, bare except, lambda
20
+ # assignment, ambiguous names): real bug shapes, but often intentional.
21
+ _MEDIUM_RULES = {"E711", "E712", "E713", "E714", "E722", "E731", "E741"}
22
+
23
+
24
+ def _severity_for(code: str) -> Severity:
25
+ if code in _HIGH_RULES:
26
+ return Severity.HIGH
27
+ if code in _MEDIUM_RULES:
28
+ return Severity.MEDIUM
29
+ if code.startswith("N"):
30
+ return Severity.INFO # pep8-naming is style
31
+ return Severity.LOW
32
+
33
+
34
+ class RuffTool(Tool):
35
+ name = "ruff"
36
+ category = Category.LINT
37
+ languages = ["python"]
38
+ installer = "pipx:ruff"
39
+
40
+ def is_applicable(self, repo: Path) -> bool:
41
+ return any(repo.glob("**/*.py")) or (repo / "pyproject.toml").exists()
42
+
43
+ def run(self, repo: Path) -> list[Finding]:
44
+ cmd = ["ruff", "check", "--output-format=json", "--no-fix", "."]
45
+ out = subprocess.run(
46
+ cmd, cwd=repo, capture_output=True, text=True, timeout=300
47
+ )
48
+ # ruff returns non-zero when findings exist; that's normal.
49
+ if not out.stdout.strip():
50
+ return []
51
+ try:
52
+ items = json.loads(out.stdout)
53
+ except json.JSONDecodeError:
54
+ return []
55
+
56
+ findings: list[Finding] = []
57
+ for item in items:
58
+ loc = item.get("location", {})
59
+ findings.append(
60
+ Finding(
61
+ tool=self.name,
62
+ rule=item.get("code", "?"),
63
+ severity=_severity_for(item.get("code", "")),
64
+ category=self.category,
65
+ message=item.get("message", ""),
66
+ file=item.get("filename"),
67
+ line=loc.get("row"),
68
+ column=loc.get("column"),
69
+ fixable=item.get("fix") is not None,
70
+ fix_command="ruff check --fix ." if any(
71
+ it.get("fix") for it in items
72
+ ) else None,
73
+ doc_url=f"https://docs.astral.sh/ruff/rules/{item.get('code', '').lower()}",
74
+ raw=item,
75
+ )
76
+ )
77
+ return findings
78
+
79
+ def fix_command(self, repo: Path) -> str | None:
80
+ return "ruff check --fix ."
@@ -0,0 +1,80 @@
1
+ """semgrep — multi-language pattern-based static analyzer.
2
+
3
+ semgrep's JSON output (``--json``) is an envelope with ``results`` and
4
+ ``errors`` arrays. We take results only; errors are reported via the
5
+ ToolResult.error channel.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import shutil
11
+ import subprocess
12
+ from pathlib import Path
13
+
14
+ from ..finding import Category, Finding, Severity
15
+ from .base import Tool
16
+
17
+ _SEVERITY_MAP = {
18
+ "INFO": Severity.INFO,
19
+ "WARNING": Severity.MEDIUM,
20
+ "ERROR": Severity.HIGH,
21
+ }
22
+
23
+
24
+ class SemgrepTool(Tool):
25
+ name = "semgrep"
26
+ category = Category.SECURITY
27
+ languages = [
28
+ "python", "javascript", "typescript", "go", "rust", "java",
29
+ "ruby", "php", "csharp", "kotlin", "swift", "scala",
30
+ ]
31
+ installer = "pipx:semgrep"
32
+
33
+ def is_applicable(self, repo: Path) -> bool:
34
+ # semgrep is applicable everywhere there's source code.
35
+ return any(repo.glob("**/*.*"))
36
+
37
+ def run(self, repo: Path) -> list[Finding]:
38
+ if shutil.which("semgrep") is None:
39
+ return []
40
+ # The "auto" config covers most common patterns without
41
+ # requiring users to download the full ruleset.
42
+ cmd = [
43
+ "semgrep", "scan",
44
+ "--config=auto",
45
+ "--json",
46
+ "--quiet",
47
+ "--error", # exit non-zero on findings so we can ignore the code
48
+ "--no-rewrite-rule-ids",
49
+ ]
50
+ out = subprocess.run(
51
+ cmd, cwd=repo, capture_output=True, text=True, timeout=600
52
+ )
53
+ if not out.stdout.strip():
54
+ return []
55
+ try:
56
+ data = json.loads(out.stdout)
57
+ except json.JSONDecodeError:
58
+ return []
59
+
60
+ findings: list[Finding] = []
61
+ for r in data.get("results", []):
62
+ extra = r.get("extra", {})
63
+ severity = _SEVERITY_MAP.get(extra.get("severity", "WARNING"), Severity.MEDIUM)
64
+ findings.append(
65
+ Finding(
66
+ tool=self.name,
67
+ rule=r.get("check_id", "?").rsplit(".", 1)[-1],
68
+ severity=severity,
69
+ category=Category.SECURITY,
70
+ message=extra.get("message", "").splitlines()[0] if extra.get("message") else "",
71
+ file=r.get("path"),
72
+ line=extra.get("start", {}).get("line"),
73
+ column=extra.get("start", {}).get("col"),
74
+ fixable=bool(extra.get("fix")),
75
+ fix_command=None,
76
+ doc_url=r.get("check_id"),
77
+ raw=r,
78
+ )
79
+ )
80
+ return findings
@@ -0,0 +1,80 @@
1
+ """shellcheck — shell script linter (works for bash, sh, dash, ksh).
2
+
3
+ shellcheck's default output is the GNU-style
4
+ ``file:line:column: severity: message [code]`` format.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ from pathlib import Path
12
+
13
+ from ..finding import Category, Finding, Severity
14
+ from .base import Tool
15
+
16
+ _SHELLCHECK_LINE = re.compile(
17
+ r"^(?P<file>[^:]+):(?P<line>\d+):(?P<col>\d+):\s*"
18
+ r"(?P<severity>error|warning|note|info|style):\s*"
19
+ r"(?P<message>.*?)(?:\s*\[(?P<code>SC\d+)\])?\s*$"
20
+ )
21
+
22
+
23
+ class ShellcheckTool(Tool):
24
+ name = "shellcheck"
25
+ category = Category.LINT
26
+ languages = ["shell"]
27
+ installer = "github-release:koalaman/shellcheck"
28
+
29
+ def is_applicable(self, repo: Path) -> bool:
30
+ return any(repo.glob("**/*.sh")) or any(repo.glob("**/bin/*"))
31
+
32
+ def run(self, repo: Path) -> list[Finding]:
33
+ if shutil.which("shellcheck") is None:
34
+ return []
35
+ # shellcheck takes file arguments, not a directory. Collect the
36
+ # shell scripts we know about; nothing to check means no findings.
37
+ files = sorted(
38
+ str(p.relative_to(repo))
39
+ for p in repo.glob("**/*.sh")
40
+ if p.is_file()
41
+ )
42
+ if not files:
43
+ return []
44
+ # Use -f gcc for parseable one-line findings.
45
+ cmd = ["shellcheck", "-f", "gcc", "--severity=style", *files]
46
+ out = subprocess.run(
47
+ cmd, cwd=repo, capture_output=True, text=True, timeout=300
48
+ )
49
+ return self._parse(out.stdout + "\n" + out.stderr)
50
+
51
+ @staticmethod
52
+ def _parse(text: str) -> list[Finding]:
53
+ findings: list[Finding] = []
54
+ for raw in text.splitlines():
55
+ m = _SHELLCHECK_LINE.match(raw.strip())
56
+ if not m:
57
+ continue
58
+ severity = {
59
+ "error": Severity.HIGH,
60
+ "warning": Severity.MEDIUM,
61
+ "note": Severity.LOW,
62
+ "info": Severity.LOW,
63
+ "style": Severity.INFO,
64
+ }.get(m.group("severity"), Severity.LOW)
65
+ findings.append(
66
+ Finding(
67
+ tool="shellcheck",
68
+ rule=m.group("code") or m.group("severity"),
69
+ severity=severity,
70
+ category=Category.LINT,
71
+ message=m.group("message").strip(),
72
+ file=m.group("file"),
73
+ line=int(m.group("line")),
74
+ column=int(m.group("col")),
75
+ fixable=False,
76
+ doc_url=f"https://www.shellcheck.net/wiki/{m.group('code') or ''}",
77
+ raw={"line": raw},
78
+ )
79
+ )
80
+ return findings
@@ -0,0 +1,238 @@
1
+ """sonarless — SonarQube analysis via Docker (no server setup required).
2
+
3
+ Runs a local SonarQube instance in Docker, scans the repo, and queries
4
+ the SonarQube API for per-file issues. Covers 30+ languages (bugs,
5
+ vulnerabilities, code smells, security hotspots).
6
+
7
+ Requires Docker to be installed. Skips silently if Docker is absent.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import shutil
14
+ import subprocess
15
+ from pathlib import Path
16
+
17
+ from ..finding import Category, Finding, Severity
18
+ from .base import Tool
19
+
20
+ # SonarQube severity → polycheck severity
21
+ _SEVERITY_MAP = {
22
+ "BLOCKER": Severity.CRITICAL,
23
+ "CRITICAL": Severity.HIGH,
24
+ "MAJOR": Severity.MEDIUM,
25
+ "MINOR": Severity.LOW,
26
+ "INFO": Severity.INFO,
27
+ }
28
+
29
+ # SonarQube issue type → polycheck category
30
+ _TYPE_MAP = {
31
+ "BUG": Category.SECURITY,
32
+ "VULNERABILITY": Category.SECURITY,
33
+ "SECURITY_HOTSPOT": Category.SECURITY,
34
+ "CODE_SMELL": Category.LINT,
35
+ }
36
+
37
+ # SonarQube issue type → human-readable label for the rule field
38
+ _TYPE_LABEL = {
39
+ "BUG": "sonar:bug",
40
+ "VULNERABILITY": "sonar:vulnerability",
41
+ "SECURITY_HOTSPOT": "sonar:hotspot",
42
+ "CODE_SMELL": "sonar:smell",
43
+ }
44
+
45
+ SONAR_PORT = 9234
46
+ SONAR_USER = "admin"
47
+ SONAR_PASS = "Son@rless123"
48
+ SONARLESS_INSTALL_URL = "https://raw.githubusercontent.com/gitricko/sonarless/main/install.sh"
49
+
50
+
51
+ class SonarlessTool(Tool):
52
+ name = "sonarless"
53
+ category = Category.SECURITY
54
+ languages = ["*"]
55
+ universal = True
56
+ installer = "github:gitricko/sonarless"
57
+
58
+ def is_applicable(self, repo: Path) -> bool:
59
+ # Always applicable — SonarQube covers every language.
60
+ # But skip if Docker is not available.
61
+ if not _docker_available():
62
+ return False
63
+ return True
64
+
65
+ def is_installed(self) -> bool:
66
+ """Check if sonarless CLI is available."""
67
+ return shutil.which("sonarless") is not None
68
+
69
+ def install_hint(self) -> str:
70
+ return f"curl -sSL {SONARLESS_INSTALL_URL} | bash"
71
+
72
+ def can_auto_install(self) -> bool:
73
+ return _docker_available() and shutil.which("curl") is not None
74
+
75
+ def install(self) -> tuple[bool, str]:
76
+ """Install sonarless when Docker is available."""
77
+ if self.is_installed():
78
+ return True, "sonarless is already installed"
79
+ if not _docker_available():
80
+ return False, (
81
+ "Docker is required for sonarless. Ask your LLM coding "
82
+ "assistant to help install Docker for this OS, then rerun polycheck."
83
+ )
84
+ if shutil.which("curl") is None:
85
+ return False, "curl is required to install sonarless"
86
+
87
+ cmd = f"curl -sSL {SONARLESS_INSTALL_URL} | bash"
88
+ try:
89
+ result = subprocess.run(
90
+ ["bash", "-lc", cmd],
91
+ capture_output=True,
92
+ text=True,
93
+ timeout=300,
94
+ )
95
+ except subprocess.TimeoutExpired:
96
+ return False, "sonarless install timed out after 300s"
97
+ except OSError as e:
98
+ return False, f"sonarless install could not run: {e}"
99
+
100
+ if result.returncode != 0:
101
+ output = (result.stderr or result.stdout).strip()[:300]
102
+ return False, f"sonarless install failed: {output}"
103
+ if self.is_installed():
104
+ return True, "installed sonarless"
105
+ local_install = Path.home() / ".sonarless" / "sonarless"
106
+ if not local_install.exists():
107
+ local_install = Path.home() / ".sonarless" / "makefile.sh"
108
+ if local_install.exists():
109
+ target_dir = _writable_install_dir()
110
+ target_dir.mkdir(parents=True, exist_ok=True)
111
+ target = target_dir / "sonarless"
112
+ if local_install.name == "makefile.sh":
113
+ target.write_text(
114
+ "#!/usr/bin/env bash\n"
115
+ f"exec bash {local_install} \"$@\"\n",
116
+ encoding="utf-8",
117
+ )
118
+ target.chmod(0o755)
119
+ else:
120
+ shutil.copy2(local_install, target)
121
+ target.chmod(0o755)
122
+ if self.is_installed():
123
+ return True, f"installed sonarless to {target}"
124
+ return False, (
125
+ "sonarless install finished, but sonarless was not found on PATH. "
126
+ "Add ~/.sonarless to PATH or create the wrapper script from the README."
127
+ )
128
+
129
+ def run(self, repo: Path) -> list[Finding]:
130
+ # 1. Run sonarless scan
131
+ try:
132
+ result = subprocess.run(
133
+ ["sonarless", "scan"],
134
+ cwd=repo,
135
+ capture_output=True,
136
+ text=True,
137
+ timeout=600,
138
+ )
139
+ if result.returncode != 0:
140
+ # scan failed — return empty, runner will report it
141
+ return []
142
+ except (subprocess.TimeoutExpired, FileNotFoundError):
143
+ return []
144
+
145
+ # 2. Query SonarQube API for individual issues
146
+ project_name = repo.name
147
+ findings = self._query_issues(project_name)
148
+ return findings
149
+
150
+ def _query_issues(self, project_name: str) -> list[Finding]:
151
+ """Query the SonarQube REST API for per-file issues."""
152
+ import requests
153
+ from requests.auth import HTTPBasicAuth
154
+
155
+ url = f"http://localhost:{SONAR_PORT}/api/issues/search" # nosemgrep
156
+ params = {"componentKeys": project_name, "resolved": "false", "ps": "500"}
157
+
158
+ try:
159
+ resp = requests.get(url, params=params, auth=HTTPBasicAuth(SONAR_USER, SONAR_PASS), timeout=30)
160
+ resp.raise_for_status()
161
+ data = resp.json()
162
+ except (requests.RequestException, json.JSONDecodeError):
163
+ return []
164
+
165
+ issues = data.get("issues", [])
166
+ findings: list[Finding] = []
167
+
168
+ for issue in issues:
169
+ findings.append(self._parse_issue(issue))
170
+
171
+ return findings
172
+
173
+ def _parse_issue(self, issue: dict) -> Finding:
174
+ """Parse a single SonarQube issue into a Finding."""
175
+ severity_str = issue.get("severity", "INFO")
176
+ severity = _SEVERITY_MAP.get(severity_str, Severity.INFO)
177
+ issue_type = issue.get("type", "CODE_SMELL")
178
+ category = _TYPE_MAP.get(issue_type, Category.LINT)
179
+
180
+ component = issue.get("component", "")
181
+ file_path = component.split(":", 1)[1] if ":" in component else component
182
+
183
+ line = issue.get("line")
184
+ if line is not None:
185
+ try:
186
+ line = int(line)
187
+ except (ValueError, TypeError):
188
+ line = None
189
+
190
+ rule_key = issue.get("rule", "")
191
+ type_label = _TYPE_LABEL.get(issue_type, "sonar:issue")
192
+ rule = f"{type_label}:{rule_key}" if rule_key else type_label
193
+
194
+ message = issue.get("message", "").strip().split("\n")[0]
195
+
196
+ return Finding(
197
+ tool=self.name,
198
+ rule=rule,
199
+ severity=severity,
200
+ category=category,
201
+ message=message,
202
+ file=file_path,
203
+ line=line,
204
+ fixable=False,
205
+ doc_url=f"https://rules.sonarsource.com/{issue_type.lower()}/RSPEC-{rule_key.split(':')[0]}/" if rule_key else None,
206
+ raw=issue,
207
+ )
208
+
209
+ def fix_command(self, repo: Path) -> str | None:
210
+ return None # SonarQube issues require manual fixes
211
+
212
+
213
+ def _docker_available() -> bool:
214
+ """Check if Docker is installed and accessible."""
215
+ if shutil.which("docker") is None:
216
+ return False
217
+ try:
218
+ result = subprocess.run(
219
+ ["docker", "info"],
220
+ capture_output=True,
221
+ timeout=5,
222
+ )
223
+ return result.returncode == 0
224
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
225
+ return False
226
+
227
+
228
+ def _writable_install_dir() -> Path:
229
+ """Return a writable directory that is likely on PATH."""
230
+ candidates = [str(Path.home() / ".local" / "bin")]
231
+ candidates.extend(str(Path(os.environ.get("PATH", ""))).split(os.pathsep))
232
+ for raw in candidates:
233
+ if not raw:
234
+ continue
235
+ path = Path(raw)
236
+ if path.exists() and os.access(path, os.W_OK):
237
+ return path
238
+ return Path.home() / ".local" / "bin"
polycheck/tools/tsc.py ADDED
@@ -0,0 +1,77 @@
1
+ """tsc — TypeScript compiler (type checking only).
2
+
3
+ We run ``tsc --noEmit`` to get the well-known text output:
4
+
5
+ path/to/file.ts(12,5): error TS2322: Type 'string' is not assignable to type 'number'.
6
+
7
+ The (line,col) format in parens differs from mypy's, so it gets its
8
+ own parser.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ from pathlib import Path
16
+
17
+ from ..finding import Category, Finding, Severity
18
+ from .base import Tool
19
+
20
+ _TSC_LINE = re.compile(
21
+ r"^(?P<file>[^:(][^:]*?)\((?P<line>\d+),(?P<col>\d+)\):\s*"
22
+ r"(?P<severity>error|warning|info)\s+(?P<code>TS\d+):\s*"
23
+ r"(?P<message>.*)$"
24
+ )
25
+
26
+
27
+ class TscTool(Tool):
28
+ name = "tsc"
29
+ category = Category.TYPE
30
+ languages = ["javascript", "typescript"]
31
+ installer = "npm:typescript"
32
+
33
+ def is_applicable(self, repo: Path) -> bool:
34
+ return (repo / "tsconfig.json").exists()
35
+
36
+ def run(self, repo: Path) -> list[Finding]:
37
+ if shutil.which("tsc") is None and shutil.which("npx") is None:
38
+ return []
39
+ # Prefer the local binary if it exists; fall back to npx (which
40
+ # needs the module name as its first argument).
41
+ if shutil.which("tsc"):
42
+ cmd = ["tsc", "--noEmit", "--pretty", "false"]
43
+ else:
44
+ cmd = ["npx", "tsc", "--noEmit", "--pretty", "false"]
45
+ out = subprocess.run(
46
+ cmd, cwd=repo, capture_output=True, text=True, timeout=300
47
+ )
48
+ text = out.stdout + "\n" + out.stderr
49
+ return self._parse(text)
50
+
51
+ @staticmethod
52
+ def _parse(text: str) -> list[Finding]:
53
+ findings: list[Finding] = []
54
+ for raw in text.splitlines():
55
+ m = _TSC_LINE.match(raw.strip())
56
+ if not m:
57
+ continue
58
+ severity = {
59
+ "error": Severity.HIGH,
60
+ "warning": Severity.MEDIUM,
61
+ "info": Severity.INFO,
62
+ }.get(m.group("severity"), Severity.MEDIUM)
63
+ findings.append(
64
+ Finding(
65
+ tool="tsc",
66
+ rule=m.group("code"),
67
+ severity=severity,
68
+ category=Category.TYPE,
69
+ message=m.group("message"),
70
+ file=m.group("file"),
71
+ line=int(m.group("line")),
72
+ column=int(m.group("col")),
73
+ fixable=False,
74
+ raw={"line": raw},
75
+ )
76
+ )
77
+ return findings
@@ -0,0 +1,82 @@
1
+ """vulture — find dead Python code.
2
+
3
+ vulture has no JSON output; the default text format is
4
+ ``file:line: unused function 'name' (60% confidence)``.
5
+
6
+ Note: vulture has a *high* false-positive rate on Python protocol
7
+ methods (``__getattr__``, ``__dir__``, ``forward`` in nn.Module
8
+ subclasses) and on cross-file call sites in ``tests/``. The whitelist
9
+ file ``.vulture-whitelist.py`` at the repo root (when present) is
10
+ passed to vulture to silence those.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ from pathlib import Path
18
+
19
+ from ..finding import Category, Finding, Severity
20
+ from .base import Tool
21
+
22
+ _VULTURE_LINE = re.compile(
23
+ r"^(?P<file>[^:]+):(?P<line>\d+):\s*"
24
+ r"unused (?P<kind>\w+)\s+'(?P<name>[^']+)'\s*"
25
+ r"\((?P<confidence>\d+)%\s*confidence\)\s*$"
26
+ )
27
+
28
+
29
+ class VultureTool(Tool):
30
+ name = "vulture"
31
+ category = Category.DEAD_CODE
32
+ languages = ["python"]
33
+ installer = "pipx:vulture"
34
+
35
+ def is_applicable(self, repo: Path) -> bool:
36
+ return any(repo.glob("**/*.py"))
37
+
38
+ def run(self, repo: Path) -> list[Finding]:
39
+ # vulture has a JSON output too, but the text format is easier
40
+ # to read in the report. We use the text format.
41
+ if shutil.which("vulture") is None:
42
+ return []
43
+
44
+ cmd = ["vulture", "."]
45
+ # If the user has a whitelist at the repo root, pass it too.
46
+ for name in (".vulture-whitelist.py", "vulture_whitelist.py"):
47
+ wl = repo / name
48
+ if wl.exists():
49
+ cmd.append(str(wl.relative_to(repo)))
50
+
51
+ out = subprocess.run(
52
+ cmd, cwd=repo, capture_output=True, text=True, timeout=300
53
+ )
54
+ # vulture exits with the *number of findings* (capped), so 0 means
55
+ # clean, >=1 means findings exist — the exit code carries no error
56
+ # signal. Parse stdout whenever there is any.
57
+ if not out.stdout.strip():
58
+ return []
59
+ return self._parse(out.stdout)
60
+
61
+ @staticmethod
62
+ def _parse(text: str) -> list[Finding]:
63
+ findings: list[Finding] = []
64
+ for raw in text.splitlines():
65
+ m = _VULTURE_LINE.match(raw.strip())
66
+ if not m:
67
+ continue
68
+ findings.append(
69
+ Finding(
70
+ tool="vulture",
71
+ rule=f"unused-{m.group('kind')}",
72
+ severity=Severity.LOW,
73
+ category=Category.DEAD_CODE,
74
+ message=f"Unused {m.group('kind')} '{m.group('name')}'",
75
+ file=m.group("file"),
76
+ line=int(m.group("line")),
77
+ column=None,
78
+ fixable=False,
79
+ raw={"line": raw, "confidence": int(m.group("confidence"))},
80
+ )
81
+ )
82
+ return findings