pforge-cli 0.1.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,477 @@
1
+ """Unified Quality Gate & Multi-Engine Diagnostics Orchestration Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import json
7
+ import re
8
+ import time
9
+ from collections.abc import Callable
10
+ from dataclasses import asdict, dataclass, field
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from rich.console import Console
16
+ from rich.panel import Panel
17
+ from rich.table import Table
18
+
19
+ from project_forge.process import run_process
20
+
21
+ console = Console()
22
+
23
+
24
+ @dataclass
25
+ class DiagnosticIssue:
26
+ """Normalized diagnostic issue from any static analysis engine."""
27
+
28
+ engine: str
29
+ file: str
30
+ line: int
31
+ column: int
32
+ code: str
33
+ severity: str
34
+ message: str
35
+
36
+
37
+ def _empty_issues() -> list[DiagnosticIssue]:
38
+ return []
39
+
40
+
41
+ @dataclass
42
+ class EngineResult:
43
+ """Result summary of a single diagnostic engine run."""
44
+
45
+ name: str
46
+ tier: str
47
+ command: list[str]
48
+ duration_seconds: float
49
+ exit_code: int
50
+ passed: bool
51
+ issues: list[DiagnosticIssue] = field(default_factory=_empty_issues)
52
+ raw_output: str = ""
53
+
54
+
55
+ # -----------------------------------------------------------------------------
56
+ # Diagnostic Output Parsers
57
+ # -----------------------------------------------------------------------------
58
+
59
+
60
+ def parse_ruff_output(output: str) -> list[DiagnosticIssue]:
61
+ """Parse Ruff diagnostic output."""
62
+ issues: list[DiagnosticIssue] = []
63
+ # Match: path/file.py:line:col: CODE Message
64
+ pattern = re.compile(r"^([^:]+):(\d+):(\d+):\s+([A-Z0-9]+)\s+(.*)$", re.MULTILINE)
65
+ for match in pattern.finditer(output):
66
+ fpath, line, col, code, msg = match.groups()
67
+ issues.append(
68
+ DiagnosticIssue(
69
+ engine="Ruff",
70
+ file=fpath.strip(),
71
+ line=int(line),
72
+ column=int(col),
73
+ code=code.strip(),
74
+ severity="Error" if code.startswith(("E", "F")) else "Warning",
75
+ message=msg.strip(),
76
+ )
77
+ )
78
+ return issues
79
+
80
+
81
+ def parse_mypy_output(output: str) -> list[DiagnosticIssue]:
82
+ """Parse Mypy diagnostic output."""
83
+ issues: list[DiagnosticIssue] = []
84
+ # Match: path/file.py:line: error: Message [code]
85
+ pattern = re.compile(
86
+ r"^([^:]+):(\d+):\s+(error|warning|note):\s+(.*?)(?:\s+\[([a-z-]+)\])?$", re.MULTILINE
87
+ )
88
+ for match in pattern.finditer(output):
89
+ fpath, line, sev, msg, code = match.groups()
90
+ issues.append(
91
+ DiagnosticIssue(
92
+ engine="Mypy",
93
+ file=fpath.strip(),
94
+ line=int(line),
95
+ column=0,
96
+ code=(code or sev).strip(),
97
+ severity=sev.capitalize(),
98
+ message=msg.strip(),
99
+ )
100
+ )
101
+ return issues
102
+
103
+
104
+ def parse_pyright_output(output: str) -> list[DiagnosticIssue]:
105
+ """Parse Pyright diagnostic output."""
106
+ issues: list[DiagnosticIssue] = []
107
+ # Match: path/file.py:line:col - error: Message (code)
108
+ pattern = re.compile(
109
+ r"^\s*([^:\n]+):(\d+):(\d+)\s+-\s+(error|warning|info):\s+(.*?)(?:\s+\(([a-zA-Z0-9]+)\))?$",
110
+ re.MULTILINE,
111
+ )
112
+ for match in pattern.finditer(output):
113
+ fpath, line, col, sev, msg, code = match.groups()
114
+ issues.append(
115
+ DiagnosticIssue(
116
+ engine="Pyright",
117
+ file=fpath.strip(),
118
+ line=int(line),
119
+ column=int(col),
120
+ code=(code or sev).strip(),
121
+ severity=sev.capitalize(),
122
+ message=msg.strip(),
123
+ )
124
+ )
125
+ return issues
126
+
127
+
128
+ def parse_pylint_output(output: str) -> list[DiagnosticIssue]:
129
+ """Parse Pylint diagnostic output."""
130
+ issues: list[DiagnosticIssue] = []
131
+ # Match: path/file.py:line:col: C0123: Message (symbol)
132
+ pattern = re.compile(
133
+ r"^([^:]+):(\d+):(\d+):\s+([CRWEF]\d+):\s+(.*?)(?:\s+\(([a-z-]+)\))?$", re.MULTILINE
134
+ )
135
+ for match in pattern.finditer(output):
136
+ fpath, line, col, code, msg, symbol = match.groups()
137
+ sev_map = {"E": "Error", "F": "Fatal", "W": "Warning", "R": "Refactor", "C": "Convention"}
138
+ sev = sev_map.get(code[0], "Warning")
139
+ issues.append(
140
+ DiagnosticIssue(
141
+ engine="Pylint",
142
+ file=fpath.strip(),
143
+ line=int(line),
144
+ column=int(col),
145
+ code=symbol or code,
146
+ severity=sev,
147
+ message=msg.strip(),
148
+ )
149
+ )
150
+ return issues
151
+
152
+
153
+ def parse_generic_failures(output: str, engine_name: str = "Generic") -> list[DiagnosticIssue]:
154
+ """Parse generic failure messages from tool output."""
155
+ issues: list[DiagnosticIssue] = []
156
+ for line in output.splitlines():
157
+ if "FAILED " in line or "error:" in line.lower():
158
+ issues.append(
159
+ DiagnosticIssue(
160
+ engine=engine_name,
161
+ file="general",
162
+ line=0,
163
+ column=0,
164
+ code="FAIL",
165
+ severity="Error",
166
+ message=line.strip(),
167
+ )
168
+ )
169
+ return issues
170
+
171
+
172
+ # -----------------------------------------------------------------------------
173
+ # Engine Execution Runner
174
+ # -----------------------------------------------------------------------------
175
+
176
+
177
+ def _run_engine(
178
+ name: str,
179
+ tier: str,
180
+ command: list[str],
181
+ parser_fn: Callable[[str], list[DiagnosticIssue]] | None,
182
+ cwd: Path,
183
+ ) -> EngineResult:
184
+ """Execute a single diagnostic engine command and capture metrics."""
185
+ res = run_process(command, cwd=cwd)
186
+ raw = res.combined_output
187
+
188
+ issues: list[DiagnosticIssue] = []
189
+ if not res.passed:
190
+ if parser_fn:
191
+ issues = parser_fn(raw)
192
+ else:
193
+ issues = parse_generic_failures(raw, engine_name=name)
194
+
195
+ return EngineResult(
196
+ name=name,
197
+ tier=tier,
198
+ command=command,
199
+ duration_seconds=res.duration_seconds,
200
+ exit_code=res.exit_code,
201
+ passed=res.passed,
202
+ issues=issues,
203
+ raw_output=raw,
204
+ )
205
+
206
+
207
+ # -----------------------------------------------------------------------------
208
+ # Quality Gate Orchestrator
209
+ # -----------------------------------------------------------------------------
210
+
211
+
212
+ def run_quality_gate(
213
+ tier: str = "full",
214
+ export: str = "cli",
215
+ output_path: str | None = None,
216
+ auto_fix: bool = False,
217
+ quiet: bool = False,
218
+ root_dir: Path | None = None,
219
+ ) -> int:
220
+ """Run all configured quality engines based on tier and report results.
221
+
222
+ Parameters
223
+ ----------
224
+ tier : str, optional
225
+ 'fast' or 'full', by default 'full'.
226
+ export : str, optional
227
+ 'cli', 'csv', 'json', or 'all', by default 'cli'.
228
+ output_path : str | None, optional
229
+ Explicit output file destination, by default None.
230
+ auto_fix : bool, optional
231
+ Whether to run ruff format and ruff check --fix before testing, by default False.
232
+ quiet : bool, optional
233
+ Suppress progress logs, by default False.
234
+ root_dir : Path | None, optional
235
+ Project root directory, by default None (auto-discovered).
236
+
237
+ Returns
238
+ -------
239
+ int
240
+ 0 if all engines passed, 1 on failure.
241
+ """
242
+ if root_dir is None:
243
+ from project_forge.project import find_project_root
244
+
245
+ root_dir = find_project_root()
246
+
247
+ from project_forge.config import load_config
248
+ from project_forge.project import read_project_metadata
249
+
250
+ cfg = load_config(root_dir)
251
+ metadata = read_project_metadata(root_dir)
252
+ project_name = metadata.get("name", root_dir.name)
253
+
254
+ if not quiet:
255
+ console.print(
256
+ Panel(
257
+ f"[bold cyan]Local-First Quality Gate & Diagnostics[/bold cyan]\n"
258
+ f"[dim]Project:[/dim] {project_name} | [dim]Tier:[/dim] [bold]{tier.upper()}[/bold] | "
259
+ f"[dim]Export:[/dim] [bold]{export.upper()}[/bold]",
260
+ border_style="cyan",
261
+ )
262
+ )
263
+
264
+ if auto_fix:
265
+ if not quiet:
266
+ console.print("[yellow]>> Running auto-fix (Ruff lint & format)...[/yellow]")
267
+ run_process(["uv", "run", "ruff", "check", "--fix", "."], cwd=root_dir)
268
+ run_process(["uv", "run", "ruff", "format", "."], cwd=root_dir)
269
+
270
+ # Engine specifications catalog
271
+ # Map engine IDs to (Display Name, Default Tier, Command, Parser)
272
+ engine_catalog: dict[str, tuple[str, str, list[str], Any]] = {
273
+ "ruff-check": (
274
+ "Ruff Check",
275
+ "Fast",
276
+ ["uv", "run", "ruff", "check", "."],
277
+ parse_ruff_output,
278
+ ),
279
+ "ruff-format": (
280
+ "Ruff Format",
281
+ "Fast",
282
+ ["uv", "run", "ruff", "format", "--check", "."],
283
+ parse_generic_failures,
284
+ ),
285
+ "mypy": (
286
+ "Mypy Typecheck",
287
+ "Fast",
288
+ ["uv", "run", "mypy", "src"],
289
+ parse_mypy_output,
290
+ ),
291
+ "pyright": (
292
+ "Pyright Typecheck",
293
+ "Full",
294
+ ["uv", "run", "pyright"],
295
+ parse_pyright_output,
296
+ ),
297
+ "pylint": (
298
+ "Pylint Deep Analysis",
299
+ "Full",
300
+ ["uv", "run", "pylint", "src"],
301
+ parse_pylint_output,
302
+ ),
303
+ "pytest": (
304
+ "Pytest Suite",
305
+ "Full",
306
+ ["uv", "run", "pytest", "tests/", "-q"],
307
+ parse_generic_failures,
308
+ ),
309
+ }
310
+
311
+ # Resolve configured engine list for requested tier
312
+ selected_engine_ids = cfg.quality.fast if tier == "fast" else cfg.quality.full
313
+
314
+ # Filter catalog
315
+ engine_specs: list[tuple[str, str, list[str], Any]] = []
316
+ for eng_id in selected_engine_ids:
317
+ if eng_id in engine_catalog:
318
+ disp_name, eng_tier, cmd, parser_fn = engine_catalog[eng_id]
319
+ engine_specs.append((disp_name, eng_tier, cmd, parser_fn))
320
+
321
+ results: list[EngineResult] = []
322
+ total_start = time.perf_counter()
323
+
324
+ for name, eng_tier, cmd, parser_fn in engine_specs:
325
+ if not quiet:
326
+ console.print(f"[dim]Running {name}...[/dim]", end="\r")
327
+ res = _run_engine(name, eng_tier, cmd, parser_fn, cwd=root_dir)
328
+ results.append(res)
329
+ status_label = (
330
+ "[bold green]✓ PASS[/bold green]" if res.passed else "[bold red]✗ FAIL[/bold red]"
331
+ )
332
+ if not quiet:
333
+ console.print(f" {status_label} {name:<24} ({res.duration_seconds:.2f}s)")
334
+
335
+ total_duration = time.perf_counter() - total_start
336
+ all_passed = all(r.passed for r in results)
337
+
338
+ # 1. Render CLI Table
339
+ table = Table(title="\nQuality Gate Audit Summary", header_style="bold magenta")
340
+ table.add_column("Engine", style="bold")
341
+ table.add_column("Tier", justify="center")
342
+ table.add_column("Duration", justify="right")
343
+ table.add_column("Issues", justify="right")
344
+ table.add_column("Status", justify="center")
345
+
346
+ total_issues = 0
347
+ all_issues_list: list[DiagnosticIssue] = []
348
+
349
+ for r in results:
350
+ total_issues += len(r.issues)
351
+ all_issues_list.extend(r.issues)
352
+ status_str = "[bold green]PASS[/bold green]" if r.passed else "[bold red]FAIL[/bold red]"
353
+ issues_str = "[green]0[/green]" if len(r.issues) == 0 else f"[red]{len(r.issues)}[/red]"
354
+ table.add_row(r.name, r.tier, f"{r.duration_seconds:.2f}s", issues_str, status_str)
355
+
356
+ if not quiet:
357
+ console.print(table)
358
+
359
+ # 2. Render Failure Diagnostics if any
360
+ if not all_passed and not quiet:
361
+ console.print("\n[bold red]── Diagnostics / Failures Detected ──[/bold red]")
362
+ for r in results:
363
+ if not r.passed:
364
+ console.print(f"\n[bold yellow]Engine:[/bold yellow] [bold red]{r.name}[/bold red]")
365
+ if r.issues:
366
+ for iss in r.issues[:15]:
367
+ console.print(
368
+ f" [cyan]{iss.file}:{iss.line}[/cyan] [bold]{iss.code}[/bold] ({iss.severity}): {iss.message}"
369
+ )
370
+ if len(r.issues) > 15:
371
+ console.print(f" [dim]... and {len(r.issues) - 15} more issues[/dim]")
372
+ else:
373
+ lines = r.raw_output.splitlines()[-10:]
374
+ console.print(" " + "\n ".join(lines))
375
+
376
+ # 3. Handle CSV / JSON Exports
377
+ outputs_dir = root_dir / "outputs"
378
+ outputs_dir.mkdir(parents=True, exist_ok=True)
379
+ timestamp_str = datetime.now().isoformat()
380
+
381
+ if export in ("csv", "all"):
382
+ csv_file = (
383
+ Path(output_path)
384
+ if output_path and export == "csv"
385
+ else outputs_dir / "audit_report.csv"
386
+ )
387
+ with open(csv_file, mode="w", newline="", encoding="utf-8") as f:
388
+ writer = csv.writer(f)
389
+ writer.writerow(
390
+ [
391
+ "Timestamp",
392
+ "Engine",
393
+ "Tier",
394
+ "File",
395
+ "Line",
396
+ "Column",
397
+ "Code",
398
+ "Severity",
399
+ "Message",
400
+ ]
401
+ )
402
+ if all_issues_list:
403
+ for iss in all_issues_list:
404
+ writer.writerow(
405
+ [
406
+ timestamp_str,
407
+ iss.engine,
408
+ tier,
409
+ iss.file,
410
+ iss.line,
411
+ iss.column,
412
+ iss.code,
413
+ iss.severity,
414
+ iss.message,
415
+ ]
416
+ )
417
+ else:
418
+ writer.writerow(
419
+ [
420
+ timestamp_str,
421
+ "ALL_ENGINES",
422
+ tier,
423
+ "None",
424
+ 0,
425
+ 0,
426
+ "CLEAN",
427
+ "Info",
428
+ "All checks passed cleanly",
429
+ ]
430
+ )
431
+ if not quiet:
432
+ console.print(
433
+ f"\n[bold green]✓ Structured CSV audit report written to:[/bold green] {csv_file}"
434
+ )
435
+
436
+ if export in ("json", "all"):
437
+ json_file = (
438
+ Path(output_path)
439
+ if output_path and export == "json"
440
+ else outputs_dir / "audit_report.json"
441
+ )
442
+ payload = {
443
+ "timestamp": timestamp_str,
444
+ "project": project_name,
445
+ "tier": tier,
446
+ "all_passed": all_passed,
447
+ "total_duration_seconds": round(total_duration, 2),
448
+ "total_issues": total_issues,
449
+ "engines": [
450
+ {
451
+ "name": r.name,
452
+ "tier": r.tier,
453
+ "passed": r.passed,
454
+ "duration_seconds": round(r.duration_seconds, 2),
455
+ "exit_code": r.exit_code,
456
+ "issue_count": len(r.issues),
457
+ "issues": [asdict(iss) for iss in r.issues],
458
+ }
459
+ for r in results
460
+ ],
461
+ }
462
+ with open(json_file, mode="w", encoding="utf-8") as f:
463
+ json.dump(payload, f, indent=2)
464
+ if not quiet:
465
+ console.print(
466
+ f"[bold green]✓ Structured JSON audit report written to:[/bold green] {json_file}"
467
+ )
468
+
469
+ # Summary Footer
470
+ if not quiet:
471
+ summary_color = "bold green" if all_passed else "bold red"
472
+ status_text = "ALL QUALITY ENGINES PASSED" if all_passed else "QUALITY GATE FAILED"
473
+ console.print(
474
+ f"\n[{summary_color}]══ {status_text} (Total: {total_duration:.2f}s) ══[/{summary_color}]\n"
475
+ )
476
+
477
+ return 0 if all_passed else 1
@@ -0,0 +1,173 @@
1
+ """GitHub Release preview and publication manager."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ from pathlib import Path
7
+
8
+ from rich.console import Console
9
+
10
+ from project_forge.changelog import ReleaseNotes, parse_changelog, resolve_git_tag
11
+ from project_forge.process import run_process
12
+
13
+ console = Console()
14
+
15
+
16
+ def print_release_preview(tag: str, title: str, body: str, index: int, total: int) -> None:
17
+ """Print formatted release preview to terminal."""
18
+ separator = "=" * 80
19
+ console.print(f"\n{separator}")
20
+ console.print(f"[{index}/{total}] PREVIEW: {tag}")
21
+ console.print(separator)
22
+ console.print(f"• Target Git Tag : [cyan]{tag}[/cyan]")
23
+ console.print(f"• Release Title : [bold]{title}[/bold]")
24
+ console.print("• Release Content :\n")
25
+ console.print(body)
26
+ console.print(f"{separator}\n")
27
+
28
+
29
+ def publish_github_release(
30
+ root_dir: Path,
31
+ tag: str,
32
+ title: str,
33
+ body: str,
34
+ is_draft: bool = False,
35
+ ) -> bool:
36
+ """Publish a release to GitHub using gh CLI."""
37
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False, suffix=".md") as f:
38
+ f.write(body)
39
+ temp_notes = f.name
40
+
41
+ cmd = [
42
+ "gh",
43
+ "release",
44
+ "create",
45
+ tag,
46
+ "--title",
47
+ title,
48
+ "--notes-file",
49
+ temp_notes,
50
+ ]
51
+ if is_draft:
52
+ cmd.append("--draft")
53
+
54
+ try:
55
+ res = run_process(cmd, cwd=root_dir)
56
+ if res.passed:
57
+ console.print(
58
+ f"[bold green]✔ Successfully released {tag}{' (as draft)' if is_draft else ''}[/bold green]"
59
+ )
60
+ return True
61
+ console.print(f"[bold red]✘ Failed to create release for {tag}:[/bold red] {res.stderr}")
62
+ return False
63
+ finally:
64
+ Path(temp_notes).unlink(missing_ok=True)
65
+
66
+
67
+ def run_release_workflow(
68
+ root_dir: Path | None = None,
69
+ publish: bool = False,
70
+ latest: bool = False,
71
+ single_version: str | None = None,
72
+ draft: bool = False,
73
+ preview_all: bool = False,
74
+ interactive: bool = False,
75
+ ) -> int:
76
+ """Execute GitHub release preview or publishing workflow."""
77
+ if root_dir is None:
78
+ from project_forge.project import find_project_root
79
+
80
+ root_dir = find_project_root()
81
+
82
+ from project_forge.config import load_config
83
+ from project_forge.project import get_git_tags
84
+
85
+ cfg = load_config(root_dir)
86
+ changelog_path = root_dir / cfg.changelog
87
+
88
+ if not changelog_path.exists():
89
+ console.print(f"[bold red]Error: Changelog not found at {changelog_path}[/bold red]")
90
+ return 1
91
+
92
+ releases = parse_changelog(changelog_path)
93
+ if not releases:
94
+ console.print("[bold red]Error: No releases parsed from changelog.[/bold red]")
95
+ return 1
96
+
97
+ existing_tags = get_git_tags(root_dir)
98
+
99
+ # 1. Preview All
100
+ if preview_all:
101
+ for idx, rel in enumerate(releases, 1):
102
+ tag = resolve_git_tag(rel.version, existing_tags) or f"{rel.version} (TAG NOT IN GIT)"
103
+ print_release_preview(tag, rel.title, rel.body, idx, len(releases))
104
+ return 0
105
+
106
+ # 2. Preview Latest / Single
107
+ if not publish:
108
+ target_entry = releases[0]
109
+ if single_version:
110
+ clean_ver = single_version.lstrip("v")
111
+ found = next((r for r in releases if r.clean_version == clean_ver), None)
112
+ if not found:
113
+ console.print(
114
+ f"[bold red]Error: Version '{single_version}' not found in changelog.[/bold red]"
115
+ )
116
+ return 1
117
+ target_entry = found
118
+
119
+ tag = (
120
+ resolve_git_tag(target_entry.version, existing_tags)
121
+ or f"{target_entry.version} (TAG NOT IN GIT)"
122
+ )
123
+ print_release_preview(tag, target_entry.title, target_entry.body, 1, 1)
124
+ console.print("[dim]Use 'pforge release publish' to publish this release to GitHub.[/dim]")
125
+ return 0
126
+
127
+ # 3. Target determination for publishing
128
+ target_releases = releases
129
+ if latest:
130
+ target_releases = [releases[0]]
131
+ elif single_version:
132
+ clean_ver = single_version.lstrip("v")
133
+ target_releases = [r for r in releases if r.clean_version == clean_ver]
134
+ if not target_releases:
135
+ console.print(
136
+ f"[bold red]Error: Version '{single_version}' not found in changelog.[/bold red]"
137
+ )
138
+ return 1
139
+
140
+ valid_releases: list[tuple[str, ReleaseNotes]] = []
141
+ for rel in target_releases:
142
+ matched_tag = resolve_git_tag(rel.version, existing_tags)
143
+ if matched_tag is not None:
144
+ valid_releases.append((matched_tag, rel))
145
+ else:
146
+ console.print(
147
+ f"[yellow]Warning: Git tag for version '{rel.version}' not found. Skipping.[/yellow]"
148
+ )
149
+
150
+ if not valid_releases:
151
+ console.print("[yellow]No matching Git tags found to release.[/yellow]")
152
+ return 0
153
+
154
+ # Publication Execution
155
+ for idx, (tag, rel_item) in enumerate(valid_releases, 1):
156
+ if interactive:
157
+ print_release_preview(tag, rel_item.title, rel_item.body, idx, len(valid_releases))
158
+ choice = input(f"Publish release for tag '{tag}'? [y/n/q/all]: ").strip().lower()
159
+ if choice == "q":
160
+ break
161
+ if choice == "n":
162
+ continue
163
+ if choice == "all":
164
+ interactive = False
165
+
166
+ console.print(
167
+ f"Publishing release [{idx}/{len(valid_releases)}] -> Tag '{tag}', Title '{rel_item.title}'..."
168
+ )
169
+ ok = publish_github_release(root_dir, tag, rel_item.title, rel_item.body, is_draft=draft)
170
+ if not ok:
171
+ return 1
172
+
173
+ return 0