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.
- polycheck/__init__.py +19 -0
- polycheck/cli.py +791 -0
- polycheck/config.py +123 -0
- polycheck/detect.py +151 -0
- polycheck/finding.py +131 -0
- polycheck/initializer.py +333 -0
- polycheck/languages/__init__.py +10 -0
- polycheck/mcp_server.py +994 -0
- polycheck/py.typed +0 -0
- polycheck/registry.py +119 -0
- polycheck/reporters/__init__.py +33 -0
- polycheck/reporters/json_reporter.py +58 -0
- polycheck/reporters/markdown_reporter.py +141 -0
- polycheck/reporters/sarif_reporter.py +114 -0
- polycheck/runner.py +279 -0
- polycheck/session.py +134 -0
- polycheck/tools/__init__.py +10 -0
- polycheck/tools/actionlint.py +66 -0
- polycheck/tools/base.py +449 -0
- polycheck/tools/depcheck.py +96 -0
- polycheck/tools/deptry.py +83 -0
- polycheck/tools/eslint.py +89 -0
- polycheck/tools/gitleaks.py +78 -0
- polycheck/tools/hadolint.py +75 -0
- polycheck/tools/knip.py +84 -0
- polycheck/tools/mypy.py +85 -0
- polycheck/tools/npm_audit.py +74 -0
- polycheck/tools/pip_audit.py +132 -0
- polycheck/tools/ruff.py +80 -0
- polycheck/tools/semgrep.py +80 -0
- polycheck/tools/shellcheck.py +80 -0
- polycheck/tools/sonarless.py +238 -0
- polycheck/tools/tsc.py +77 -0
- polycheck/tools/vulture.py +82 -0
- polycheck/verify.py +288 -0
- polycheck/workflows/__init__.py +76 -0
- polycheck-0.2.0.dist-info/METADATA +614 -0
- polycheck-0.2.0.dist-info/RECORD +42 -0
- polycheck-0.2.0.dist-info/WHEEL +5 -0
- polycheck-0.2.0.dist-info/entry_points.txt +2 -0
- polycheck-0.2.0.dist-info/licenses/LICENSE +21 -0
- polycheck-0.2.0.dist-info/top_level.txt +1 -0
polycheck/tools/base.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""Tool plugin abstract base class.
|
|
2
|
+
|
|
3
|
+
A tool is a wrapper around an external analyzer (ruff, eslint, gitleaks,
|
|
4
|
+
etc.). To add a new tool, subclass ``Tool`` and implement:
|
|
5
|
+
|
|
6
|
+
* ``name`` — short slug, e.g. "ruff"
|
|
7
|
+
* ``category`` — Finding.Category value
|
|
8
|
+
* ``languages`` — list of language slugs this tool applies to, or
|
|
9
|
+
``["*"]`` if it applies to any repo
|
|
10
|
+
* ``is_applicable()`` — does this tool make sense for the repo? E.g.
|
|
11
|
+
"is there a package.json?"
|
|
12
|
+
* ``run()`` — execute the tool, return ``list[Finding]``
|
|
13
|
+
|
|
14
|
+
Optionally override:
|
|
15
|
+
|
|
16
|
+
* ``install_hint()`` — one-line shell command to install the tool
|
|
17
|
+
* ``version()`` — installed version string, or None
|
|
18
|
+
* ``fix_command()`` — exact shell command to apply auto-fixes
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import abc
|
|
23
|
+
import os
|
|
24
|
+
import platform
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
import tarfile
|
|
28
|
+
import tempfile
|
|
29
|
+
import zipfile
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
import requests
|
|
34
|
+
|
|
35
|
+
from ..finding import Category, Finding
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Tool(abc.ABC):
|
|
39
|
+
"""Base class for analyzer wrappers."""
|
|
40
|
+
|
|
41
|
+
#: Short identifier. Used in Finding.tool, in CLI output, in the
|
|
42
|
+
#: ``.polycheck.yml`` enable/disable config.
|
|
43
|
+
name: str = ""
|
|
44
|
+
|
|
45
|
+
#: Top-level category. Tools producing different findings should
|
|
46
|
+
#: declare multiple subclasses.
|
|
47
|
+
category: Category = Category.OTHER
|
|
48
|
+
|
|
49
|
+
#: Languages this tool applies to. ``["python"]`` or
|
|
50
|
+
#: ``["javascript", "typescript"]`` or ``["*"]`` for any.
|
|
51
|
+
languages: list[str] = []
|
|
52
|
+
|
|
53
|
+
#: Whether the tool is multi-language (e.g. semgrep, gitleaks).
|
|
54
|
+
#: When True, the tool runs on every repo regardless of language.
|
|
55
|
+
universal: bool = False
|
|
56
|
+
|
|
57
|
+
#: How to install the tool. One of:
|
|
58
|
+
#: * ``"pipx:<package>"`` — ``pipx install <package>``
|
|
59
|
+
#: * ``"pip:<package>"`` — ``pip install --user <package>``
|
|
60
|
+
#: * ``"npm:<package>"`` — ``npm install -g <package>``
|
|
61
|
+
#: * ``"brew:<formula>"`` — ``brew install <formula>``
|
|
62
|
+
#: * ``"apt:<package>"`` — ``apt install <package>``
|
|
63
|
+
#: * ``"github:<owner>/<repo>"`` — download from GitHub releases
|
|
64
|
+
#: * ``None`` — no automatic install available
|
|
65
|
+
installer: str | None = None
|
|
66
|
+
|
|
67
|
+
@abc.abstractmethod
|
|
68
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
69
|
+
"""Return True if the tool makes sense to run on ``repo``.
|
|
70
|
+
|
|
71
|
+
Examples:
|
|
72
|
+
* ruff returns True iff ``pyproject.toml`` or ``*.py`` exists.
|
|
73
|
+
* eslint returns True iff ``package.json`` exists.
|
|
74
|
+
* gitleaks always returns True (universal).
|
|
75
|
+
"""
|
|
76
|
+
...
|
|
77
|
+
|
|
78
|
+
@abc.abstractmethod
|
|
79
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
80
|
+
"""Execute the tool and return normalized findings.
|
|
81
|
+
|
|
82
|
+
Implementations should:
|
|
83
|
+
* Locate the binary via ``shutil.which(self.binary)``; if absent
|
|
84
|
+
return an empty list (runner will report it as not installed).
|
|
85
|
+
* Set a sane timeout (default 300s in Runner).
|
|
86
|
+
* Parse the tool's native output (JSON where possible) and
|
|
87
|
+
convert each entry to a ``Finding`` with consistent severity.
|
|
88
|
+
"""
|
|
89
|
+
...
|
|
90
|
+
|
|
91
|
+
# ----- Optional hooks -----
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def binary(self) -> str:
|
|
95
|
+
"""The on-disk binary name to look up via shutil.which. Default
|
|
96
|
+
is the tool's ``name`` attribute. Override if the executable
|
|
97
|
+
differs (e.g. ``node_modules/.bin/eslint``)."""
|
|
98
|
+
return self.name
|
|
99
|
+
|
|
100
|
+
def is_installed(self) -> bool:
|
|
101
|
+
"""True if the underlying binary exists in PATH."""
|
|
102
|
+
return shutil.which(self.binary) is not None
|
|
103
|
+
|
|
104
|
+
def install_hint(self) -> str:
|
|
105
|
+
"""One-line shell command to install the tool. Shown to the user
|
|
106
|
+
via ``polycheck list-tools`` / ``polycheck doctor`` when the
|
|
107
|
+
tool is missing."""
|
|
108
|
+
cmd = build_install_command(self.installer, self.name)
|
|
109
|
+
if cmd is not None:
|
|
110
|
+
return cmd
|
|
111
|
+
if self.installer and self.installer.startswith("github-release:"):
|
|
112
|
+
return f"auto-install {self.name} from the latest GitHub release"
|
|
113
|
+
# For GitHub releases, show the releases page
|
|
114
|
+
if self.installer and self.installer.startswith("github:"):
|
|
115
|
+
repo_path = self.installer[len("github:"):]
|
|
116
|
+
return f"download from https://github.com/{repo_path}/releases"
|
|
117
|
+
return f"install {self.name} manually (no automatic installer available)"
|
|
118
|
+
|
|
119
|
+
def can_auto_install(self) -> bool:
|
|
120
|
+
"""Return True if the base installer can install this tool."""
|
|
121
|
+
if self.installer and self.installer.startswith("github-release:"):
|
|
122
|
+
return _github_release_supported(self.installer)
|
|
123
|
+
return build_install_command(self.installer, self.name) is not None
|
|
124
|
+
|
|
125
|
+
def install(self) -> tuple[bool, str]:
|
|
126
|
+
"""Attempt to install the tool. Returns ``(success, message)``.
|
|
127
|
+
|
|
128
|
+
Uses the ``installer`` class attribute. Falls back to printing
|
|
129
|
+
the install hint if no installer is registered. We avoid
|
|
130
|
+
``shell=True`` and split the command ourselves with
|
|
131
|
+
:func:`shlex.split` so we don't introduce a shell-injection
|
|
132
|
+
surface (and so semgrep's ``subprocess-shell-true`` doesn't
|
|
133
|
+
fire on this very file).
|
|
134
|
+
"""
|
|
135
|
+
if self.is_installed():
|
|
136
|
+
return True, f"{self.name} is already installed"
|
|
137
|
+
if not self.can_auto_install():
|
|
138
|
+
# Check if this is a github: installer to give better message
|
|
139
|
+
if self.installer and self.installer.startswith("github:"):
|
|
140
|
+
repo_path = self.installer[len("github:"):]
|
|
141
|
+
return False, (
|
|
142
|
+
f"no automatic installer for {self.name}; "
|
|
143
|
+
f"download from https://github.com/{repo_path}/releases"
|
|
144
|
+
)
|
|
145
|
+
return False, f"no automatic installer for {self.name}; see {self.install_hint()}"
|
|
146
|
+
if self.installer and self.installer.startswith("github-release:"):
|
|
147
|
+
return _install_github_release(self.installer, self.binary)
|
|
148
|
+
cmd = build_install_command(self.installer, self.name)
|
|
149
|
+
if cmd is None:
|
|
150
|
+
return False, f"no automatic installer for {self.name}; see {self.install_hint()}"
|
|
151
|
+
# Check if required package manager is available
|
|
152
|
+
if not self._check_package_manager(cmd):
|
|
153
|
+
return False, f"required package manager not found for {self.name}"
|
|
154
|
+
# shlex.split honours quotes, so "brew install hadolint" stays
|
|
155
|
+
# as two argv entries and a quoted install is preserved.
|
|
156
|
+
import shlex
|
|
157
|
+
argv = shlex.split(cmd)
|
|
158
|
+
try:
|
|
159
|
+
out = subprocess.run(
|
|
160
|
+
argv, capture_output=True, text=True, timeout=300
|
|
161
|
+
)
|
|
162
|
+
if out.returncode != 0:
|
|
163
|
+
return False, f"`{cmd}` failed: {(out.stderr or out.stdout).strip()[:200]}"
|
|
164
|
+
except subprocess.TimeoutExpired:
|
|
165
|
+
return False, f"`{cmd}` timed out after 300s"
|
|
166
|
+
except OSError as e:
|
|
167
|
+
return False, f"`{cmd}` could not run: {e}"
|
|
168
|
+
# Verify it actually got installed.
|
|
169
|
+
if self.is_installed():
|
|
170
|
+
return True, f"installed {self.name}"
|
|
171
|
+
return False, f"`{cmd}` returned 0 but `{self.binary}` is still not on PATH"
|
|
172
|
+
|
|
173
|
+
def _check_package_manager(self, cmd: str) -> bool:
|
|
174
|
+
"""Check if the required package manager is available."""
|
|
175
|
+
if "brew " in cmd:
|
|
176
|
+
return shutil.which("brew") is not None
|
|
177
|
+
if "npm " in cmd:
|
|
178
|
+
return shutil.which("npm") is not None
|
|
179
|
+
if "pipx " in cmd:
|
|
180
|
+
return shutil.which("pipx") is not None
|
|
181
|
+
if "apt " in cmd:
|
|
182
|
+
return shutil.which("apt") is not None
|
|
183
|
+
return True
|
|
184
|
+
|
|
185
|
+
def version(self) -> str | None:
|
|
186
|
+
"""Return the installed tool's version string, or None if it
|
|
187
|
+
can't be determined without running a heavyweight command.
|
|
188
|
+
|
|
189
|
+
We try ``--version`` first; on failure we try ``version``.
|
|
190
|
+
Anything else (Go tools that print usage, etc.) returns None
|
|
191
|
+
silently — the doctor command just shows ``?``.
|
|
192
|
+
"""
|
|
193
|
+
if not self.is_installed():
|
|
194
|
+
return None
|
|
195
|
+
for flag in ("--version", "version"):
|
|
196
|
+
try:
|
|
197
|
+
out = subprocess.run(
|
|
198
|
+
[self.binary, flag],
|
|
199
|
+
capture_output=True,
|
|
200
|
+
text=True,
|
|
201
|
+
timeout=10,
|
|
202
|
+
)
|
|
203
|
+
except (subprocess.TimeoutExpired, OSError, FileNotFoundError):
|
|
204
|
+
continue
|
|
205
|
+
if out.returncode == 0 and (out.stdout or out.stderr).strip():
|
|
206
|
+
return (out.stdout or out.stderr).strip().split("\n")[0]
|
|
207
|
+
return None
|
|
208
|
+
|
|
209
|
+
def fix_command(self, repo: Path) -> str | None:
|
|
210
|
+
"""The exact shell command to run to apply auto-fixes for this
|
|
211
|
+
tool, or None if the tool has no auto-fix mode."""
|
|
212
|
+
return None
|
|
213
|
+
|
|
214
|
+
def __repr__(self) -> str:
|
|
215
|
+
return f"<{type(self).__name__} name={self.name!r} langs={self.languages}>"
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _github_release_supported(installer: str) -> bool:
|
|
219
|
+
"""Return True if an OS/arch asset is known for this GitHub release."""
|
|
220
|
+
repo = installer.removeprefix("github-release:")
|
|
221
|
+
return _github_release_asset(repo, "0.0.0", platform.system(), platform.machine()) is not None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _install_github_release(installer: str, binary: str) -> tuple[bool, str]:
|
|
225
|
+
"""Install a binary from the latest GitHub release for the current OS/arch."""
|
|
226
|
+
repo = installer.removeprefix("github-release:")
|
|
227
|
+
version, assets, fetch_error = _latest_github_release_assets(repo)
|
|
228
|
+
if version is None:
|
|
229
|
+
return False, f"could not fetch latest release for {repo}: {fetch_error}"
|
|
230
|
+
|
|
231
|
+
asset_name = _github_release_asset(repo, version, platform.system(), platform.machine())
|
|
232
|
+
if asset_name is None:
|
|
233
|
+
return False, f"no release asset for {repo} on {platform.system()} {platform.machine()}"
|
|
234
|
+
|
|
235
|
+
asset_url = next(
|
|
236
|
+
(asset.get("browser_download_url") for asset in assets if asset.get("name") == asset_name),
|
|
237
|
+
None,
|
|
238
|
+
)
|
|
239
|
+
if not asset_url:
|
|
240
|
+
return False, f"release asset not found for {repo}: {asset_name}"
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
target = _download_and_install_asset(asset_url, binary)
|
|
244
|
+
except (OSError, tarfile.TarError, zipfile.BadZipFile, KeyError) as exc:
|
|
245
|
+
return False, f"failed to install {binary} from {repo}: {exc}"
|
|
246
|
+
|
|
247
|
+
path_note = ""
|
|
248
|
+
if str(target.parent) not in os.environ.get("PATH", "").split(os.pathsep):
|
|
249
|
+
path_note = f" Add {target.parent} to PATH."
|
|
250
|
+
return True, f"installed {binary} to {target}.{path_note}"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _latest_github_release_assets(
|
|
254
|
+
repo: str,
|
|
255
|
+
) -> tuple[str | None, list[dict[str, Any]], str]:
|
|
256
|
+
"""Fetch the latest release tag and asset metadata from GitHub.
|
|
257
|
+
|
|
258
|
+
Returns ``(tag, assets, error)``; ``tag`` is None when the fetch
|
|
259
|
+
failed and ``error`` carries the reason.
|
|
260
|
+
"""
|
|
261
|
+
url = f"https://api.github.com/repos/{repo}/releases/latest"
|
|
262
|
+
headers = {
|
|
263
|
+
"Accept": "application/vnd.github+json",
|
|
264
|
+
"User-Agent": "polycheck",
|
|
265
|
+
}
|
|
266
|
+
try:
|
|
267
|
+
response = requests.get(url, headers=headers, timeout=30)
|
|
268
|
+
except requests.RequestException as exc:
|
|
269
|
+
return None, [], str(exc)
|
|
270
|
+
if response.status_code != 200:
|
|
271
|
+
return None, [], f"HTTP {response.status_code}: {response.text[:200]}"
|
|
272
|
+
try:
|
|
273
|
+
data = response.json()
|
|
274
|
+
except ValueError as exc:
|
|
275
|
+
return None, [], str(exc)
|
|
276
|
+
tag = data.get("tag_name") or data.get("name")
|
|
277
|
+
if not tag:
|
|
278
|
+
return None, [], "release missing tag_name"
|
|
279
|
+
assets = data.get("assets", [])
|
|
280
|
+
if not isinstance(assets, list):
|
|
281
|
+
return None, [], "release assets missing"
|
|
282
|
+
return tag.lstrip("v"), assets, ""
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _download_and_install_asset(asset_url: str, binary: str) -> Path:
|
|
286
|
+
"""Download a release asset, extract the binary, and install it."""
|
|
287
|
+
asset_name = Path(asset_url).name
|
|
288
|
+
suffix = "".join(Path(asset_name).suffixes)
|
|
289
|
+
with tempfile.TemporaryDirectory(prefix="polycheck-github-release-") as tmp_name:
|
|
290
|
+
tmp = Path(tmp_name)
|
|
291
|
+
archive = tmp / asset_name
|
|
292
|
+
_download_file(asset_url, archive)
|
|
293
|
+
|
|
294
|
+
if suffix and (suffix.endswith(".zip") or suffix.endswith((".tar.gz", ".tgz", ".tar.xz"))):
|
|
295
|
+
extract_dir = tmp / "extract"
|
|
296
|
+
extract_dir.mkdir()
|
|
297
|
+
if suffix.endswith(".zip"):
|
|
298
|
+
with zipfile.ZipFile(archive) as zf:
|
|
299
|
+
zf.extractall(extract_dir)
|
|
300
|
+
else:
|
|
301
|
+
with tarfile.open(archive, "r:*") as tf:
|
|
302
|
+
tf.extractall(extract_dir)
|
|
303
|
+
source = _find_extracted_binary(extract_dir, binary)
|
|
304
|
+
else:
|
|
305
|
+
source = archive
|
|
306
|
+
target_dir = _writable_install_dir()
|
|
307
|
+
target_dir.mkdir(parents=True, exist_ok=True)
|
|
308
|
+
target_name = f"{binary}.exe" if platform.system() == "windows" else binary
|
|
309
|
+
target = target_dir / target_name
|
|
310
|
+
target.write_bytes(source.read_bytes())
|
|
311
|
+
target.chmod(0o755)
|
|
312
|
+
return target
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _download_file(url: str, path: Path) -> None:
|
|
316
|
+
"""Download a file using requests with a streaming response."""
|
|
317
|
+
with requests.get(url, stream=True, timeout=60) as response:
|
|
318
|
+
response.raise_for_status()
|
|
319
|
+
with path.open("wb") as fh:
|
|
320
|
+
for chunk in response.iter_content(chunk_size=1024 * 1024):
|
|
321
|
+
if chunk:
|
|
322
|
+
fh.write(chunk)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _find_extracted_binary(root: Path, binary: str) -> Path:
|
|
326
|
+
"""Find the extracted binary file inside an archive."""
|
|
327
|
+
names = {binary, f"{binary}.exe"}
|
|
328
|
+
matches = [path for path in root.rglob("*") if path.is_file() and path.name in names]
|
|
329
|
+
if matches:
|
|
330
|
+
return sorted(matches, key=lambda p: len(p.parts))[0]
|
|
331
|
+
raise FileNotFoundError(f"could not find {binary} in extracted archive")
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _writable_install_dir() -> Path:
|
|
335
|
+
"""Return a writable directory that is likely on PATH."""
|
|
336
|
+
for raw in os.environ.get("PATH", "").split(os.pathsep):
|
|
337
|
+
if not raw:
|
|
338
|
+
continue
|
|
339
|
+
path = Path(raw)
|
|
340
|
+
if path.exists() and os.access(path, os.W_OK):
|
|
341
|
+
return path
|
|
342
|
+
return Path.home() / ".local" / "bin"
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _github_release_asset(
|
|
346
|
+
repo: str,
|
|
347
|
+
version: str,
|
|
348
|
+
system: str,
|
|
349
|
+
machine: str,
|
|
350
|
+
) -> str | None:
|
|
351
|
+
"""Return the expected GitHub release asset name for a repo/platform."""
|
|
352
|
+
system = system.lower()
|
|
353
|
+
arch = _normalize_arch(machine)
|
|
354
|
+
if repo == "gitleaks/gitleaks":
|
|
355
|
+
return _gitleaks_asset(version, system, arch)
|
|
356
|
+
if repo == "rhysd/actionlint":
|
|
357
|
+
return _actionlint_asset(version, system, arch)
|
|
358
|
+
if repo == "hadolint/hadolint":
|
|
359
|
+
return _hadolint_asset(version, system, arch)
|
|
360
|
+
if repo == "koalaman/shellcheck":
|
|
361
|
+
return _shellcheck_asset(version, system, arch)
|
|
362
|
+
return None
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _normalize_arch(machine: str) -> str:
|
|
366
|
+
"""Normalize Python platform.machine() values."""
|
|
367
|
+
machine = machine.lower()
|
|
368
|
+
if machine in {"x86_64", "amd64"}:
|
|
369
|
+
return "x64"
|
|
370
|
+
if machine in {"aarch64", "arm64"}:
|
|
371
|
+
return "arm64"
|
|
372
|
+
return machine
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _gitleaks_asset(version: str, system: str, arch: str) -> str | None:
|
|
376
|
+
if system == "windows":
|
|
377
|
+
return f"gitleaks_{version}_windows_x64.zip" if arch == "x64" else None
|
|
378
|
+
if system in {"linux", "darwin"}:
|
|
379
|
+
suffix = "x64" if arch == "x64" else "arm64" if arch == "arm64" else None
|
|
380
|
+
if suffix:
|
|
381
|
+
return f"gitleaks_{version}_{system}_{suffix}.tar.gz"
|
|
382
|
+
return None
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _actionlint_asset(version: str, system: str, arch: str) -> str | None:
|
|
386
|
+
if system == "windows":
|
|
387
|
+
return f"actionlint_{version}_windows_amd64.zip" if arch == "x64" else None
|
|
388
|
+
if system in {"linux", "darwin"}:
|
|
389
|
+
suffix = "amd64" if arch == "x64" else "arm64" if arch == "arm64" else None
|
|
390
|
+
if suffix:
|
|
391
|
+
return f"actionlint_{version}_{system}_{suffix}.tar.gz"
|
|
392
|
+
return None
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _hadolint_asset(version: str, system: str, arch: str) -> str | None:
|
|
396
|
+
suffix = "x86_64" if arch == "x64" else "arm64" if arch == "arm64" else None
|
|
397
|
+
if not suffix:
|
|
398
|
+
return None
|
|
399
|
+
if system == "windows":
|
|
400
|
+
return f"hadolint-windows-{suffix}.exe"
|
|
401
|
+
if system == "darwin":
|
|
402
|
+
return f"hadolint-macos-{suffix}"
|
|
403
|
+
if system == "linux":
|
|
404
|
+
return f"hadolint-linux-{suffix}"
|
|
405
|
+
return None
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _shellcheck_asset(version: str, system: str, arch: str) -> str | None:
|
|
409
|
+
if system == "windows":
|
|
410
|
+
return f"shellcheck-v{version}.zip" if arch == "x64" else None
|
|
411
|
+
if system == "darwin":
|
|
412
|
+
suffix = "x86_64" if arch == "x64" else "aarch64" if arch == "arm64" else None
|
|
413
|
+
if suffix:
|
|
414
|
+
return f"shellcheck-v{version}.darwin.{suffix}.tar.xz"
|
|
415
|
+
if system == "linux":
|
|
416
|
+
suffix = "x86_64" if arch == "x64" else "aarch64" if arch == "arm64" else None
|
|
417
|
+
if suffix:
|
|
418
|
+
return f"shellcheck-v{version}.linux.{suffix}.tar.xz"
|
|
419
|
+
return None
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
# Map from ``installer`` strings to one-line shell commands.
|
|
423
|
+
_INSTALLERS = {
|
|
424
|
+
"pipx": "pipx install {pkg}",
|
|
425
|
+
"pip": "pip install --user {pkg}",
|
|
426
|
+
"npm": "npm install -g {pkg}",
|
|
427
|
+
"brew": "brew install {pkg}",
|
|
428
|
+
"apt": "sudo apt install {pkg}",
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def build_install_command(installer: str | None, name: str) -> str | None:
|
|
433
|
+
"""Render an installer string into a concrete shell command.
|
|
434
|
+
|
|
435
|
+
Returns None if the installer kind is unknown or no installer is
|
|
436
|
+
set. ``github:<owner>/<repo>`` returns None because the right
|
|
437
|
+
tarball URL depends on the OS + arch; the user is shown the
|
|
438
|
+
project page instead.
|
|
439
|
+
"""
|
|
440
|
+
if not installer:
|
|
441
|
+
return None
|
|
442
|
+
if installer.startswith("github:"):
|
|
443
|
+
# Can't auto-install from GitHub releases — show manual instructions
|
|
444
|
+
return None
|
|
445
|
+
kind, _, pkg = installer.partition(":")
|
|
446
|
+
template = _INSTALLERS.get(kind)
|
|
447
|
+
if template is None:
|
|
448
|
+
return None
|
|
449
|
+
return template.format(pkg=pkg or name)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""depcheck — find unused / missing JS/TS dependencies.
|
|
2
|
+
|
|
3
|
+
Parses depcheck's plain text output. Each finding is one line of the
|
|
4
|
+
form::
|
|
5
|
+
|
|
6
|
+
Missing: package-name
|
|
7
|
+
Unused: another-package
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from ..finding import Category, Finding, Severity
|
|
17
|
+
from .base import Tool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class DepcheckTool(Tool):
|
|
21
|
+
name = "depcheck"
|
|
22
|
+
category = Category.DEPS
|
|
23
|
+
languages = ["javascript", "typescript"]
|
|
24
|
+
installer = "npm:depcheck"
|
|
25
|
+
|
|
26
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
27
|
+
return (repo / "package.json").exists()
|
|
28
|
+
|
|
29
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
30
|
+
if shutil.which("depcheck") is None and shutil.which("npx") is None:
|
|
31
|
+
return []
|
|
32
|
+
# depcheck's JSON output is unstable across versions, so we
|
|
33
|
+
# use text. -q makes it print only findings. Prefer the local
|
|
34
|
+
# binary; npx needs the module name as its first argument.
|
|
35
|
+
if shutil.which("depcheck"):
|
|
36
|
+
cmd = ["depcheck", ".", "-q", "--no-dev"]
|
|
37
|
+
else:
|
|
38
|
+
cmd = ["npx", "depcheck", ".", "-q", "--no-dev"]
|
|
39
|
+
out = subprocess.run(
|
|
40
|
+
cmd, cwd=repo, capture_output=True, text=True, timeout=300
|
|
41
|
+
)
|
|
42
|
+
return self._parse(out.stdout + "\n" + out.stderr)
|
|
43
|
+
|
|
44
|
+
@staticmethod
|
|
45
|
+
def _parse(text: str) -> list[Finding]:
|
|
46
|
+
findings: list[Finding] = []
|
|
47
|
+
# Current depcheck prints headings ("Unused dependencies",
|
|
48
|
+
# "Missing dependencies") followed by "* package" bullets.
|
|
49
|
+
current: str | None = None
|
|
50
|
+
for raw in text.splitlines():
|
|
51
|
+
line = raw.strip()
|
|
52
|
+
if line.startswith("Missing dependenc"):
|
|
53
|
+
current = "Missing"
|
|
54
|
+
continue
|
|
55
|
+
if line.startswith(("Unused dependenc", "Unused devDependenc")):
|
|
56
|
+
current = "Unused"
|
|
57
|
+
continue
|
|
58
|
+
m = re.match(r"^\*\s*(.+)$", line)
|
|
59
|
+
if current and m:
|
|
60
|
+
kind, pkg = current, m.group(1).strip()
|
|
61
|
+
severity = Severity.MEDIUM if kind == "Missing" else Severity.LOW
|
|
62
|
+
findings.append(
|
|
63
|
+
Finding(
|
|
64
|
+
tool="depcheck",
|
|
65
|
+
rule=f"depcheck-{kind.lower()}",
|
|
66
|
+
severity=severity,
|
|
67
|
+
category=Category.DEPS,
|
|
68
|
+
message=f"{kind} dependency: {pkg}",
|
|
69
|
+
file=pkg,
|
|
70
|
+
line=0,
|
|
71
|
+
column=0,
|
|
72
|
+
fixable=False,
|
|
73
|
+
raw={"line": line},
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
continue
|
|
77
|
+
# Legacy one-line format: "Missing: pkg" / "Unused: pkg".
|
|
78
|
+
m = re.match(r"^(Missing|Unused):\s*(.+)$", line)
|
|
79
|
+
if m:
|
|
80
|
+
kind, pkg = m.group(1), m.group(2)
|
|
81
|
+
severity = Severity.MEDIUM if kind == "Missing" else Severity.LOW
|
|
82
|
+
findings.append(
|
|
83
|
+
Finding(
|
|
84
|
+
tool="depcheck",
|
|
85
|
+
rule=f"depcheck-{kind.lower()}",
|
|
86
|
+
severity=severity,
|
|
87
|
+
category=Category.DEPS,
|
|
88
|
+
message=f"{kind} dependency: {pkg}",
|
|
89
|
+
file=pkg,
|
|
90
|
+
line=0,
|
|
91
|
+
column=0,
|
|
92
|
+
fixable=False,
|
|
93
|
+
raw={"line": line},
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
return findings
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""deptry — find unused / missing Python dependencies.
|
|
2
|
+
|
|
3
|
+
deptry's text output is one line per finding. We parse it.
|
|
4
|
+
|
|
5
|
+
DEP001: imported but missing from the dependency definitions
|
|
6
|
+
DEP002: defined as a dependency but not used in the codebase
|
|
7
|
+
DEP003: imported but declared as a dev dependency
|
|
8
|
+
DEP004: imported but declared as an optional dependency
|
|
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
|
+
# File-level findings (e.g. DEP002) print "file: DEPxxx 'name' ...";
|
|
21
|
+
# code-level findings (e.g. DEP001) print "file:line:col: DEPxxx ...".
|
|
22
|
+
# Line and column are therefore optional groups.
|
|
23
|
+
_DEPTRY_LINE = re.compile(
|
|
24
|
+
r"^(?P<file>[^:]+):"
|
|
25
|
+
r"(?:(?P<line>\d+):(?:(?P<col>\d+):)?)?"
|
|
26
|
+
r"\s*(?P<code>DEP\d+)\s*"
|
|
27
|
+
r"'(?P<name>[^']+)'\s*(?P<rest>.+)$"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class DeptryTool(Tool):
|
|
32
|
+
name = "deptry"
|
|
33
|
+
category = Category.DEPS
|
|
34
|
+
languages = ["python"]
|
|
35
|
+
installer = "pipx:deptry"
|
|
36
|
+
|
|
37
|
+
def is_applicable(self, repo: Path) -> bool:
|
|
38
|
+
return (repo / "pyproject.toml").exists()
|
|
39
|
+
|
|
40
|
+
def run(self, repo: Path) -> list[Finding]:
|
|
41
|
+
if shutil.which("deptry") is None:
|
|
42
|
+
return []
|
|
43
|
+
out = subprocess.run(
|
|
44
|
+
["deptry", "."], cwd=repo, capture_output=True, text=True, timeout=300
|
|
45
|
+
)
|
|
46
|
+
# deptry exits non-zero when findings exist and prints them to
|
|
47
|
+
# stderr (stdout carries progress notes only).
|
|
48
|
+
return self._parse(out.stdout + "\n" + out.stderr)
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def _parse(text: str) -> list[Finding]:
|
|
52
|
+
# deptry emits ANSI color codes by default; strip them.
|
|
53
|
+
import re as _re
|
|
54
|
+
ansi = _re.compile(r"\x1b\[[0-9;]*m")
|
|
55
|
+
findings: list[Finding] = []
|
|
56
|
+
for raw in text.splitlines():
|
|
57
|
+
clean = ansi.sub("", raw).strip()
|
|
58
|
+
m = _DEPTRY_LINE.match(clean)
|
|
59
|
+
if not m:
|
|
60
|
+
continue
|
|
61
|
+
severity = {
|
|
62
|
+
"DEP001": Severity.MEDIUM, # missing
|
|
63
|
+
"DEP002": Severity.LOW, # unused
|
|
64
|
+
"DEP003": Severity.LOW, # dev-only
|
|
65
|
+
"DEP004": Severity.LOW, # optional-only
|
|
66
|
+
}.get(m.group("code"), Severity.MEDIUM)
|
|
67
|
+
line_text = m.group("line")
|
|
68
|
+
col_text = m.group("col")
|
|
69
|
+
findings.append(
|
|
70
|
+
Finding(
|
|
71
|
+
tool="deptry",
|
|
72
|
+
rule=m.group("code"),
|
|
73
|
+
severity=severity,
|
|
74
|
+
category=Category.DEPS,
|
|
75
|
+
message=f"{m.group('name')}: {m.group('rest').strip()}",
|
|
76
|
+
file=m.group("file"),
|
|
77
|
+
line=int(line_text) if line_text else None,
|
|
78
|
+
column=int(col_text) if col_text else None,
|
|
79
|
+
fixable=False,
|
|
80
|
+
raw={"line": clean},
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
return findings
|