patchops-guard 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.
@@ -0,0 +1,229 @@
1
+ """`patchops repair ...` — trigger + poll AI Repair jobs."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from enum import Enum
6
+ from pathlib import Path
7
+
8
+ import typer
9
+ from rich.console import Console
10
+
11
+ from patchops_cli import config as cfg_mod
12
+ from patchops_cli.client import APIError, PatchOpsCLIClient
13
+ from patchops_cli.formatters.json_fmt import write_json_output
14
+ from patchops_cli.formatters.table import (
15
+ render_repair_status,
16
+ render_repairs_table,
17
+ )
18
+ from patchops_cli.utils.errors import EXIT_USAGE, fail
19
+
20
+ app = typer.Typer(help="Trigger and monitor AI Repair jobs.")
21
+
22
+
23
+ class _Format(str, Enum):
24
+ json = "json"
25
+ table = "table"
26
+
27
+
28
+ class _JobStatus(str, Enum):
29
+ pending = "pending"
30
+ running = "running"
31
+ completed = "completed"
32
+ failed = "failed"
33
+
34
+
35
+ def _client() -> PatchOpsCLIClient:
36
+ cfg = cfg_mod.load()
37
+ if not cfg.is_authenticated():
38
+ raise fail(
39
+ "not authenticated — run `patchops auth login` first", exit_code=EXIT_USAGE
40
+ )
41
+ return PatchOpsCLIClient(cfg, timeout=60.0)
42
+
43
+
44
+ @app.command("start")
45
+ def start_repair(
46
+ finding_id: str = typer.Argument(..., help="Finding UUID to repair."),
47
+ fmt: _Format = typer.Option(_Format.table, "--format"),
48
+ output: Path | None = typer.Option(None, "--output"),
49
+ wait: bool = typer.Option(
50
+ False, "--wait", help="Block until the repair finishes (polls every 5 s)."
51
+ ),
52
+ timeout: int = typer.Option(
53
+ 900, "--timeout", help="Max seconds to wait when --wait is given.",
54
+ ),
55
+ ) -> None:
56
+ """Enqueue an AI repair job for ``finding_id``."""
57
+ try:
58
+ with _client() as client:
59
+ data = client.repair_start(finding_id)
60
+ job_id = data.get("job_id") or data.get("id")
61
+ if wait and job_id:
62
+ data = _wait_for(client, str(job_id), timeout=timeout)
63
+ except APIError as exc:
64
+ raise fail(f"repair start failed ({exc.status}): {exc.message}")
65
+
66
+ if fmt is _Format.json:
67
+ write_json_output(data, output)
68
+ else:
69
+ if output is not None:
70
+ write_json_output(data, output)
71
+ render_repair_status(data)
72
+
73
+
74
+ @app.command("status")
75
+ def status_repair(
76
+ job_id: str = typer.Argument(..., help="Job UUID returned by `repair start`."),
77
+ fmt: _Format = typer.Option(_Format.table, "--format"),
78
+ output: Path | None = typer.Option(None, "--output"),
79
+ wait: bool = typer.Option(
80
+ False, "--wait", help="Block until the repair finishes.",
81
+ ),
82
+ timeout: int = typer.Option(900, "--timeout"),
83
+ ) -> None:
84
+ """Fetch the current status of a repair job."""
85
+ try:
86
+ with _client() as client:
87
+ data = (
88
+ _wait_for(client, job_id, timeout=timeout)
89
+ if wait
90
+ else client.repair_status(job_id)
91
+ )
92
+ except APIError as exc:
93
+ raise fail(f"repair status failed ({exc.status}): {exc.message}")
94
+
95
+ if fmt is _Format.json:
96
+ write_json_output(data, output)
97
+ else:
98
+ if output is not None:
99
+ write_json_output(data, output)
100
+ render_repair_status(data)
101
+
102
+
103
+ @app.command("list")
104
+ def list_repairs(
105
+ status: _JobStatus | None = typer.Option(None, "--status"),
106
+ limit: int = typer.Option(50, "--limit", min=1, max=200),
107
+ fmt: _Format = typer.Option(_Format.table, "--format"),
108
+ output: Path | None = typer.Option(None, "--output"),
109
+ ) -> None:
110
+ """List recent AI repair jobs."""
111
+ try:
112
+ with _client() as client:
113
+ data = client.repair_list(
114
+ status=status.value if status else None, limit=limit
115
+ )
116
+ except APIError as exc:
117
+ raise fail(f"repair list failed ({exc.status}): {exc.message}")
118
+
119
+ items = data.get("data") or []
120
+ if fmt is _Format.json:
121
+ write_json_output(data, output)
122
+ else:
123
+ if output is not None:
124
+ write_json_output(data, output)
125
+ render_repairs_table(items)
126
+
127
+
128
+ def _wait_for(
129
+ client: PatchOpsCLIClient, job_id: str, *, timeout: int
130
+ ) -> dict:
131
+ console = Console()
132
+ deadline = time.time() + timeout
133
+ last_status = ""
134
+ while True:
135
+ data = client.repair_status(job_id)
136
+ current = str(data.get("status") or "")
137
+ if current != last_status:
138
+ console.print(f"[dim]status:[/dim] {current}")
139
+ last_status = current
140
+ if current in {"completed", "failed", "merged", "pr_created"}:
141
+ return data
142
+ if time.time() >= deadline:
143
+ console.print("[yellow]timed out waiting for repair.[/yellow]")
144
+ return data
145
+ time.sleep(5)
146
+
147
+
148
+ # ─────────────────────────── Quick Repair UX ───────────────────────────
149
+ # AI Repair 1.0's App-less + post-hoc PR flow. Backed by the
150
+ # /quick-repair/finding/{id}/patch.diff and /create-pr endpoints.
151
+
152
+
153
+ @app.command("download")
154
+ def download_patch(
155
+ finding_id: str = typer.Argument(..., help="QuickRepairFinding ID."),
156
+ output: Path = typer.Option(
157
+ Path("patchguard.diff"), "--output", "-o",
158
+ help="Where to save the .diff file.",
159
+ ),
160
+ ) -> None:
161
+ """Download the verified .diff produced by AI Repair 1.0.
162
+
163
+ Works without a repository connection — Stage 1-4 of the repair pipeline
164
+ (context → generate → sandbox → re-scan) produces a verified patch
165
+ that you can apply locally with ``git apply``.
166
+ """
167
+ try:
168
+ with _client() as client:
169
+ text = client.quick_repair_patch_download(finding_id)
170
+ except APIError as exc:
171
+ raise fail(
172
+ f"download failed ({exc.status}): {exc.message}",
173
+ )
174
+ output.write_text(text if isinstance(text, str) else str(text))
175
+ typer.secho(f"Wrote patch to {output}", fg="green")
176
+ typer.echo(f"Apply with: git apply {output}")
177
+
178
+
179
+ _PLATFORM_NAMES = {"github": "GitHub", "gitlab": "GitLab", "bitbucket": "Bitbucket"}
180
+
181
+
182
+ @app.command("create-pr")
183
+ def create_pr_for_finding(
184
+ finding_id: str = typer.Argument(..., help="QuickRepairFinding ID."),
185
+ fmt: _Format = typer.Option(_Format.table, "--format"),
186
+ output: Path | None = typer.Option(None, "--output"),
187
+ ) -> None:
188
+ """Promote a stored AI Repair 1.0 patch to a real pull/merge request.
189
+
190
+ Needs a working connection to the repository's platform (GitHub App
191
+ installed, or GitLab/Bitbucket connected). Otherwise the API returns 412
192
+ with the platform and where to fix it.
193
+ """
194
+ try:
195
+ with _client() as client:
196
+ data = client.quick_repair_create_pr(finding_id)
197
+ except APIError as exc:
198
+ if exc.status == 412:
199
+ detail = exc.detail if isinstance(exc.detail, dict) else {}
200
+ err = detail.get("detail") if isinstance(detail, dict) else None
201
+ err = err if isinstance(err, dict) else {}
202
+ install_url = err.get("install_url")
203
+ platform = str(err.get("platform") or "github")
204
+ # PLAN-047: GitLab·Bitbucket 저장소는 앱 설치가 아니라 다시 연결 (서버가 플랫폼을 알려 준다)
205
+ typer.secho(
206
+ "GitHub App not installed." if platform == "github"
207
+ else f"{_PLATFORM_NAMES.get(platform, platform)} connection is not usable — reconnect it in Settings → Integrations.",
208
+ fg="red",
209
+ )
210
+ if install_url:
211
+ typer.echo(f"Install: https://patchguard.ai{install_url}")
212
+ raise typer.Exit(code=2)
213
+ raise fail(
214
+ f"create-pr failed ({exc.status}): {exc.message}",
215
+ )
216
+
217
+ if fmt is _Format.json:
218
+ write_json_output(data, output)
219
+ else:
220
+ status = data.get("status") or "unknown"
221
+ pr_url = data.get("pr_url")
222
+ typer.echo(f"Status: {status}")
223
+ if pr_url:
224
+ typer.secho(f"PR: {pr_url}", fg="green")
225
+ else:
226
+ typer.echo("PR creation enqueued — poll `repair status` for the URL.")
227
+
228
+
229
+ __all__ = ["app"]
@@ -0,0 +1,127 @@
1
+ """``patchops repo-scan`` — Repo Scan Flash 1.4 / Deep 1.4.
2
+
3
+ Two tiers exposed via ``--tier``:
4
+ * ``quick`` (default) — Repo Scan Flash 1.4: fast, broad, daily-driver,
5
+ ideal for PR auto-checks and CI gating.
6
+ * ``deep`` — Repo Scan Deep 1.4: Flash + Pro cascade for
7
+ Java/Spring large repos, pre-release final audit, compliance.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from enum import Enum
12
+ from pathlib import Path
13
+
14
+ import typer
15
+
16
+ from patchops_cli import config as cfg_mod
17
+ from patchops_cli.client import APIError, PatchOpsCLIClient
18
+ from patchops_cli.formatters.json_fmt import write_json_output
19
+ from patchops_cli.utils.errors import EXIT_USAGE, fail
20
+
21
+ app = typer.Typer(
22
+ help="Repo Scan Flash 1.4 (quick) / Deep 1.4 (deep cascade).",
23
+ )
24
+
25
+
26
+ class _Tier(str, Enum):
27
+ quick = "quick"
28
+ deep = "deep"
29
+
30
+
31
+ class _Fmt(str, Enum):
32
+ table = "table"
33
+ json = "json"
34
+
35
+
36
+ def _client() -> PatchOpsCLIClient:
37
+ cfg = cfg_mod.load()
38
+ return PatchOpsCLIClient(cfg)
39
+
40
+
41
+ @app.command("run")
42
+ def repo_scan_run(
43
+ repo_path: Path = typer.Argument(
44
+ ..., exists=True, file_okay=False, dir_okay=True,
45
+ help="Local repo path (server-reachable).",
46
+ ),
47
+ tier: _Tier = typer.Option(
48
+ _Tier.quick, "--tier", "-t",
49
+ help="Scan tier — quick (Flash 1.4) or deep (Deep 1.4 cascade).",
50
+ ),
51
+ fmt: _Fmt = typer.Option(_Fmt.table, "--format", "-f"),
52
+ plan: str = typer.Option(
53
+ "", "--plan",
54
+ help="pro/business → real LLM. Auto-set to 'pro' on --tier=deep.",
55
+ ),
56
+ fail_on: str | None = typer.Option(
57
+ None, "--fail-on-severity",
58
+ help="Exit non-zero if any finding at or above this severity "
59
+ "(low|medium|high|critical).",
60
+ ),
61
+ ) -> None:
62
+ """Run Repo Scan against a local repository.
63
+
64
+ ``--tier=quick`` (default) → Flash 1.4 — fast, broad recall,
65
+ daily-driver. Ideal for PR auto-checks and CI gating.
66
+
67
+ ``--tier=deep`` → Deep 1.4 — Flash + Pro cascade. Adds heavy stages
68
+ (MRVA / property-based gen). Recommended for Java/Spring large repos,
69
+ pre-release audits, SOC2 / EU CRA compliance scans.
70
+ """
71
+ client = _client()
72
+ try:
73
+ data = client.repo_scan(
74
+ str(repo_path.absolute()),
75
+ tier=tier.value,
76
+ plan=plan,
77
+ )
78
+ except APIError as exc:
79
+ raise fail(
80
+ f"repo-scan failed ({exc.status}): {exc.message}",
81
+ exit_code=EXIT_USAGE,
82
+ )
83
+
84
+ if fmt is _Fmt.json:
85
+ write_json_output(data)
86
+ else:
87
+ engine = "Repo Scan Flash 1.4" if tier is _Tier.quick else "Repo Scan Deep 1.4"
88
+ typer.echo(f"Engine: {engine}")
89
+ typer.echo(f"Repo: {repo_path}")
90
+ typer.echo(f"Layer 1 findings: {data.get('layer1_total', 0)}")
91
+ typer.echo(f"Layer 2 anti-pattern: {data.get('layer2_anti_pattern_count', 0)}")
92
+ typer.echo(f"Layer 2 git arch: {data.get('layer2_git_arch_variants', 0)}")
93
+ typer.echo(f"Layer 3 variant hits: {data.get('layer3_variant_hits', 0)}")
94
+ if tier is _Tier.deep:
95
+ typer.echo(f"Stage E MRVA: {data.get('stage_e_mrva_hits', 0)}")
96
+ typer.echo(f"Stage F findings: {len(data.get('stage_f_findings', []) or [])}")
97
+ typer.echo(f"Stage G toxic combos: {data.get('stage_g_toxic_combinations', 0)}")
98
+ typer.echo(f"Differential hits: {data.get('stage_g_differential_hits', 0)}")
99
+ budget = data.get("budget", {}) or {}
100
+ if budget.get("allow_real_llm"):
101
+ typer.secho(
102
+ f"Real LLM active ({budget.get('remaining_cents', 0)}¢ remaining)",
103
+ fg="green",
104
+ )
105
+
106
+ if fail_on:
107
+ rank = {"low": 0, "medium": 1, "high": 2, "critical": 3}
108
+ if fail_on not in rank:
109
+ raise fail(
110
+ f"--fail-on-severity must be one of: {list(rank)}",
111
+ exit_code=EXIT_USAGE,
112
+ )
113
+ # Collect severities from stage_f_findings if present
114
+ severities: list[str] = []
115
+ for f in (data.get("stage_f_findings") or []):
116
+ sev = (f.get("severity") or "").lower()
117
+ if sev in rank:
118
+ severities.append(sev)
119
+ worst = max(severities, default=None, key=lambda s: rank[s])
120
+ if worst and rank[worst] >= rank[fail_on]:
121
+ typer.secho(
122
+ f"Threshold met: {worst} >= {fail_on}", fg="red",
123
+ )
124
+ raise typer.Exit(code=3)
125
+
126
+
127
+ __all__ = ["app"]
@@ -0,0 +1,339 @@
1
+ """`patchops sbom ...` — generate + upload CycloneDX.
2
+
3
+ The generator is a pure-Python lockfile parser for the major ecosystems,
4
+ emitting a minimal but valid CycloneDX 1.6 JSON document. It does not
5
+ depend on the backend package so the CLI is installable without the
6
+ server-side deps.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import uuid
13
+ import xml.etree.ElementTree as ET
14
+ from dataclasses import dataclass
15
+ from datetime import UTC, datetime
16
+ from pathlib import Path
17
+
18
+ import typer
19
+ from rich.console import Console
20
+
21
+ from patchops_cli import config as cfg_mod
22
+ from patchops_cli.client import APIError, PatchOpsCLIClient
23
+ from patchops_cli.formatters.json_fmt import write_json_output
24
+ from patchops_cli.utils.errors import EXIT_USAGE, fail
25
+
26
+ app = typer.Typer(help="Build and upload Software Bill of Materials (SBOM).")
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class _Pkg:
31
+ name: str
32
+ version: str
33
+ ecosystem: str
34
+ purl: str
35
+
36
+
37
+ def _purl(ecosystem: str, name: str, version: str) -> str:
38
+ ecosystem = ecosystem.lower()
39
+ return f"pkg:{ecosystem}/{name}@{version}"
40
+
41
+
42
+ # ----------------------------------------------------------------- parsers
43
+
44
+
45
+ def _parse_package_lock(content: str) -> list[_Pkg]:
46
+ data = json.loads(content)
47
+ out: list[_Pkg] = []
48
+ # npm v2/v3 lockfile layout
49
+ packages = data.get("packages") or {}
50
+ if packages:
51
+ for key, entry in packages.items():
52
+ if not key:
53
+ continue
54
+ name = entry.get("name") or key.split("node_modules/")[-1]
55
+ version = entry.get("version")
56
+ if not name or not version:
57
+ continue
58
+ out.append(_Pkg(name, version, "npm", _purl("npm", name, version)))
59
+ return out
60
+ # npm v1 dependencies
61
+ for name, entry in (data.get("dependencies") or {}).items():
62
+ version = entry.get("version")
63
+ if version:
64
+ out.append(_Pkg(name, version, "npm", _purl("npm", name, version)))
65
+ return out
66
+
67
+
68
+ def _parse_requirements(content: str) -> list[_Pkg]:
69
+ out: list[_Pkg] = []
70
+ for raw in content.splitlines():
71
+ line = raw.strip()
72
+ if not line or line.startswith("#"):
73
+ continue
74
+ m = re.match(
75
+ r"^([A-Za-z0-9_.\-]+)\s*==\s*([A-Za-z0-9._\-+]+)",
76
+ line,
77
+ )
78
+ if not m:
79
+ continue
80
+ name, version = m.group(1), m.group(2)
81
+ out.append(_Pkg(name, version, "pypi", _purl("pypi", name, version)))
82
+ return out
83
+
84
+
85
+ def _parse_pipfile_lock(content: str) -> list[_Pkg]:
86
+ data = json.loads(content)
87
+ out: list[_Pkg] = []
88
+ for section in ("default", "develop"):
89
+ for name, entry in (data.get(section) or {}).items():
90
+ version = (entry.get("version") or "").lstrip("=")
91
+ if version:
92
+ out.append(_Pkg(name, version, "pypi", _purl("pypi", name, version)))
93
+ return out
94
+
95
+
96
+ def _parse_pom_xml(content: str) -> list[_Pkg]:
97
+ out: list[_Pkg] = []
98
+ try:
99
+ root = ET.fromstring(content)
100
+ except ET.ParseError:
101
+ return []
102
+ ns = {"m": "http://maven.apache.org/POM/4.0.0"}
103
+ deps = root.findall(".//m:dependency", ns) or root.findall(".//dependency")
104
+ for dep in deps:
105
+ g = dep.findtext("m:groupId", default="", namespaces=ns) or dep.findtext(
106
+ "groupId", default=""
107
+ )
108
+ a = dep.findtext("m:artifactId", default="", namespaces=ns) or dep.findtext(
109
+ "artifactId", default=""
110
+ )
111
+ v = dep.findtext("m:version", default="", namespaces=ns) or dep.findtext(
112
+ "version", default=""
113
+ )
114
+ if g and a and v:
115
+ name = f"{g}:{a}"
116
+ out.append(_Pkg(name, v, "maven", f"pkg:maven/{g}/{a}@{v}"))
117
+ return out
118
+
119
+
120
+ def _parse_go_mod(content: str) -> list[_Pkg]:
121
+ out: list[_Pkg] = []
122
+ in_block = False
123
+ for raw in content.splitlines():
124
+ line = raw.strip()
125
+ if line.startswith("require ("):
126
+ in_block = True
127
+ continue
128
+ if in_block and line == ")":
129
+ in_block = False
130
+ continue
131
+ if line.startswith("require ") and not in_block:
132
+ parts = line[len("require "):].split()
133
+ if len(parts) >= 2:
134
+ out.append(_Pkg(parts[0], parts[1], "go", _purl("golang", parts[0], parts[1])))
135
+ continue
136
+ if in_block:
137
+ parts = line.split()
138
+ if len(parts) >= 2 and not parts[0].startswith("//"):
139
+ out.append(_Pkg(parts[0], parts[1], "go", _purl("golang", parts[0], parts[1])))
140
+ return out
141
+
142
+
143
+ def _parse_gemfile_lock(content: str) -> list[_Pkg]:
144
+ out: list[_Pkg] = []
145
+ in_specs = False
146
+ for raw in content.splitlines():
147
+ line = raw.rstrip()
148
+ if line.strip() == "specs:":
149
+ in_specs = True
150
+ continue
151
+ if in_specs:
152
+ if not line.startswith(" ") or line.startswith(" "):
153
+ if line.strip() and not line.startswith(" "):
154
+ in_specs = False
155
+ continue
156
+ m = re.match(r"^ ([A-Za-z0-9_\-]+)\s+\(([^)]+)\)", line)
157
+ if m:
158
+ name, version = m.group(1), m.group(2)
159
+ out.append(
160
+ _Pkg(name, version, "rubygems", _purl("gem", name, version))
161
+ )
162
+ return out
163
+
164
+
165
+ def _parse_cargo_lock(content: str) -> list[_Pkg]:
166
+ # Minimal TOML-ish parse — avoid adding a tomllib dep path at runtime.
167
+ out: list[_Pkg] = []
168
+ name: str | None = None
169
+ version: str | None = None
170
+ for raw in content.splitlines():
171
+ line = raw.strip()
172
+ if line == "[[package]]":
173
+ if name and version:
174
+ out.append(_Pkg(name, version, "cargo", _purl("cargo", name, version)))
175
+ name = None
176
+ version = None
177
+ continue
178
+ m = re.match(r'^name\s*=\s*"([^"]+)"$', line)
179
+ if m:
180
+ name = m.group(1)
181
+ continue
182
+ m = re.match(r'^version\s*=\s*"([^"]+)"$', line)
183
+ if m:
184
+ version = m.group(1)
185
+ if name and version:
186
+ out.append(_Pkg(name, version, "cargo", _purl("cargo", name, version)))
187
+ return out
188
+
189
+
190
+ def _parse_composer_lock(content: str) -> list[_Pkg]:
191
+ data = json.loads(content)
192
+ out: list[_Pkg] = []
193
+ for section in ("packages", "packages-dev"):
194
+ for pkg in data.get(section) or []:
195
+ name = pkg.get("name")
196
+ version = (pkg.get("version") or "").lstrip("v")
197
+ if name and version:
198
+ out.append(
199
+ _Pkg(name, version, "composer", _purl("composer", name, version))
200
+ )
201
+ return out
202
+
203
+
204
+ _PARSERS: dict[str, object] = {
205
+ "package-lock.json": _parse_package_lock,
206
+ "package.json": _parse_package_lock,
207
+ "requirements.txt": _parse_requirements,
208
+ "pipfile.lock": _parse_pipfile_lock,
209
+ "pom.xml": _parse_pom_xml,
210
+ "go.mod": _parse_go_mod,
211
+ "gemfile.lock": _parse_gemfile_lock,
212
+ "cargo.lock": _parse_cargo_lock,
213
+ "composer.lock": _parse_composer_lock,
214
+ }
215
+
216
+
217
+ def _detect_parser(path: Path):
218
+ name = path.name.lower()
219
+ parser = _PARSERS.get(name)
220
+ if parser is not None:
221
+ return parser
222
+ # Fallback matchers — pip-tools emits ``requirements.lock`` /
223
+ # ``requirements.in`` / ``requirements-dev.txt``, which all follow the
224
+ # same ``name==version`` grammar as requirements.txt. Accept them.
225
+ if name.startswith("requirements") and (
226
+ name.endswith(".txt") or name.endswith(".lock") or name.endswith(".in")
227
+ ):
228
+ return _parse_requirements
229
+ return None
230
+
231
+
232
+ def _build_cyclonedx(packages: list[_Pkg], *, source: Path) -> dict:
233
+ return {
234
+ "bomFormat": "CycloneDX",
235
+ "specVersion": "1.6",
236
+ "serialNumber": f"urn:uuid:{uuid.uuid4()}",
237
+ "version": 1,
238
+ "metadata": {
239
+ "timestamp": datetime.now(tz=UTC).isoformat(),
240
+ "tools": [
241
+ {
242
+ "vendor": "PatchOps Guard",
243
+ "name": "patchops-cli",
244
+ "version": _tool_version(),
245
+ }
246
+ ],
247
+ "component": {
248
+ "type": "application",
249
+ "name": source.stem or "root",
250
+ "version": "0.0.0",
251
+ },
252
+ },
253
+ "components": [
254
+ {
255
+ "type": "library",
256
+ "bom-ref": pkg.purl,
257
+ "name": pkg.name,
258
+ "version": pkg.version,
259
+ "purl": pkg.purl,
260
+ }
261
+ for pkg in packages
262
+ ],
263
+ }
264
+
265
+
266
+ def _tool_version() -> str:
267
+ try:
268
+ from patchops_cli import __version__
269
+
270
+ return __version__
271
+ except Exception:
272
+ return "0.0.0"
273
+
274
+
275
+ # ----------------------------------------------------------------- commands
276
+
277
+
278
+ @app.command("generate")
279
+ def generate(
280
+ path: Path = typer.Argument(
281
+ ..., exists=True, file_okay=True, dir_okay=False, readable=True,
282
+ help="Lockfile to read.",
283
+ ),
284
+ output: Path | None = typer.Option(
285
+ None, "--output", help="Write SBOM to a file instead of stdout."
286
+ ),
287
+ ) -> None:
288
+ """Generate a CycloneDX 1.6 SBOM from a lockfile."""
289
+ parser = _detect_parser(path)
290
+ if parser is None:
291
+ raise fail(
292
+ f"unsupported lockfile: {path.name}. "
293
+ "Supported: package-lock.json, requirements.txt, Pipfile.lock, "
294
+ "pom.xml, go.mod, Gemfile.lock, Cargo.lock, composer.lock.",
295
+ exit_code=EXIT_USAGE,
296
+ )
297
+ content = path.read_text(encoding="utf-8", errors="replace")
298
+ try:
299
+ packages = parser(content) # type: ignore[operator]
300
+ except Exception as exc:
301
+ raise fail(f"failed to parse {path.name}: {exc}")
302
+ if not packages:
303
+ raise fail(f"no packages found in {path.name}")
304
+
305
+ doc = _build_cyclonedx(packages, source=path)
306
+ write_json_output(doc, output)
307
+ if output is not None:
308
+ Console().print(
309
+ f"[green]Wrote {len(packages)} components to {output}[/green]"
310
+ )
311
+
312
+
313
+ @app.command("upload")
314
+ def upload(
315
+ path: Path = typer.Argument(
316
+ ..., exists=True, file_okay=True, dir_okay=False, readable=True,
317
+ help="CycloneDX or SPDX SBOM file to upload.",
318
+ ),
319
+ output: Path | None = typer.Option(None, "--output"),
320
+ ) -> None:
321
+ """Upload an SBOM and run OSV matching."""
322
+ cfg = cfg_mod.load()
323
+ # Scan SBOM endpoint accepts guests (with rate limit).
324
+ try:
325
+ with PatchOpsCLIClient(cfg, timeout=120.0) as client:
326
+ data = client.sbom_upload(path)
327
+ except APIError as exc:
328
+ raise fail(f"sbom upload failed ({exc.status}): {exc.message}")
329
+
330
+ write_json_output(data, output)
331
+ if output is None:
332
+ Console().print(
333
+ f"[bold]Packages:[/bold] total={data.get('packages_total', 0)} "
334
+ f"vulnerable={data.get('packages_vulnerable', 0)} "
335
+ f"cves={data.get('cves_total', 0)}"
336
+ )
337
+
338
+
339
+ __all__ = ["app"]