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,126 @@
1
+ """Unified subprocess execution runner for Project Forge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import time
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+
12
+ @dataclass
13
+ class ProcessResult:
14
+ """Result of an executed subprocess."""
15
+
16
+ command: list[str]
17
+ exit_code: int
18
+ stdout: str
19
+ stderr: str
20
+ duration_seconds: float
21
+
22
+ @property
23
+ def passed(self) -> bool:
24
+ """Return True if command returned zero exit code."""
25
+ return self.exit_code == 0
26
+
27
+ @property
28
+ def combined_output(self) -> str:
29
+ """Return combined stdout and stderr."""
30
+ out = self.stdout.strip()
31
+ err = self.stderr.strip()
32
+ if out and err:
33
+ return f"{out}\n{err}"
34
+ return out or err
35
+
36
+
37
+ def run_process(
38
+ command: list[str],
39
+ cwd: Path | str | None = None,
40
+ env: dict[str, str] | None = None,
41
+ capture_output: bool = True,
42
+ text: bool = True,
43
+ check: bool = False,
44
+ timeout: float | None = None,
45
+ ) -> ProcessResult:
46
+ """Execute a subprocess command with unified error and duration handling.
47
+
48
+ Parameters
49
+ ----------
50
+ command : list[str]
51
+ Command arguments list.
52
+ cwd : Path | str | None, optional
53
+ Working directory for the process, by default None.
54
+ env : dict[str, str] | None, optional
55
+ Environment variables dictionary, by default None (inherits os.environ).
56
+ capture_output : bool, optional
57
+ Whether to capture stdout and stderr, by default True.
58
+ text : bool, optional
59
+ Whether to decode output as string, by default True.
60
+ check : bool, optional
61
+ Whether to raise CalledProcessError on non-zero exit code, by default False.
62
+ timeout : float | None, optional
63
+ Command timeout in seconds, by default None.
64
+
65
+ Returns
66
+ -------
67
+ ProcessResult
68
+ Populated result object with execution metrics.
69
+ """
70
+ proc_env = os.environ.copy()
71
+ if env:
72
+ proc_env.update(env)
73
+
74
+ t0 = time.perf_counter()
75
+ try:
76
+ proc = subprocess.run(
77
+ command,
78
+ cwd=str(cwd) if cwd else None,
79
+ env=proc_env,
80
+ capture_output=capture_output,
81
+ text=text,
82
+ encoding="utf-8" if text else None,
83
+ errors="replace" if text else None,
84
+ check=check,
85
+ timeout=timeout,
86
+ )
87
+ duration = time.perf_counter() - t0
88
+ return ProcessResult(
89
+ command=command,
90
+ exit_code=proc.returncode,
91
+ stdout=proc.stdout or "" if text else "",
92
+ stderr=proc.stderr or "" if text else "",
93
+ duration_seconds=duration,
94
+ )
95
+ except subprocess.CalledProcessError as exc:
96
+ duration = time.perf_counter() - t0
97
+ return ProcessResult(
98
+ command=command,
99
+ exit_code=exc.returncode,
100
+ stdout=exc.stdout or "" if text else "",
101
+ stderr=exc.stderr or "" if text else "",
102
+ duration_seconds=duration,
103
+ )
104
+ except FileNotFoundError as exc:
105
+ duration = time.perf_counter() - t0
106
+ return ProcessResult(
107
+ command=command,
108
+ exit_code=127,
109
+ stdout="",
110
+ stderr=f"Executable not found: {command[0]} ({exc})",
111
+ duration_seconds=duration,
112
+ )
113
+ except subprocess.TimeoutExpired as exc:
114
+ duration = time.perf_counter() - t0
115
+ out_str = (
116
+ exc.stdout.decode("utf-8", errors="replace")
117
+ if isinstance(exc.stdout, bytes)
118
+ else (exc.stdout or "")
119
+ )
120
+ return ProcessResult(
121
+ command=command,
122
+ exit_code=124,
123
+ stdout=out_str if text else "",
124
+ stderr=f"Command timed out after {timeout} seconds",
125
+ duration_seconds=duration,
126
+ )
@@ -0,0 +1,148 @@
1
+ """Project and Git repository discovery helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from project_forge.process import run_process
10
+
11
+
12
+ def find_project_root(start_dir: Path | None = None) -> Path:
13
+ """Find the root directory of the project by checking parent directories.
14
+
15
+ Checks for pyproject.toml, .git, or CHANGELOG.md.
16
+
17
+ Parameters
18
+ ----------
19
+ start_dir : Path | None, optional
20
+ Starting path, by default current working directory.
21
+
22
+ Returns
23
+ -------
24
+ Path
25
+ Resolved project root path.
26
+ """
27
+ current = (start_dir or Path.cwd()).resolve()
28
+ for candidate in [current, *current.parents]:
29
+ if (candidate / "pyproject.toml").exists() or (candidate / ".git").exists():
30
+ return candidate
31
+ return current
32
+
33
+
34
+ def read_project_metadata(root_dir: Path) -> dict[str, str]:
35
+ """Read project name, version, and description from pyproject.toml.
36
+
37
+ Parameters
38
+ ----------
39
+ root_dir : Path
40
+ Project root directory containing pyproject.toml.
41
+
42
+ Returns
43
+ -------
44
+ dict[str, str]
45
+ Metadata dictionary containing name, version, description.
46
+ """
47
+ pyproject_path = root_dir / "pyproject.toml"
48
+ metadata = {
49
+ "name": root_dir.name,
50
+ "version": "0.1.0",
51
+ "description": "",
52
+ }
53
+ if not pyproject_path.exists():
54
+ return metadata
55
+
56
+ try:
57
+ content = pyproject_path.read_bytes()
58
+ data: dict[str, Any] = tomllib.loads(content.decode("utf-8"))
59
+ project_dict = data.get("project", {})
60
+ metadata["name"] = project_dict.get("name", root_dir.name)
61
+ metadata["version"] = project_dict.get("version", "0.1.0")
62
+ metadata["description"] = project_dict.get("description", "")
63
+ except Exception:
64
+ pass
65
+
66
+ return metadata
67
+
68
+
69
+ def get_git_branch(root_dir: Path) -> str:
70
+ """Get the current git branch name.
71
+
72
+ Parameters
73
+ ----------
74
+ root_dir : Path
75
+ Project root directory.
76
+
77
+ Returns
78
+ -------
79
+ str
80
+ Current branch name or 'HEAD' if detached/unknown.
81
+ """
82
+ res = run_process(["git", "branch", "--show-current"], cwd=root_dir)
83
+ branch = res.stdout.strip()
84
+ if not branch:
85
+ res_head = run_process(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=root_dir)
86
+ branch = res_head.stdout.strip()
87
+ return branch or "unknown"
88
+
89
+
90
+ def get_git_tags(root_dir: Path) -> set[str]:
91
+ """Get all git tags in the repository.
92
+
93
+ Parameters
94
+ ----------
95
+ root_dir : Path
96
+ Project root directory.
97
+
98
+ Returns
99
+ -------
100
+ set[str]
101
+ Set of tag strings.
102
+ """
103
+ res = run_process(["git", "tag"], cwd=root_dir)
104
+ if res.passed and res.stdout.strip():
105
+ return set(res.stdout.strip().splitlines())
106
+ return set()
107
+
108
+
109
+ def get_dirty_files(root_dir: Path) -> list[str]:
110
+ """Get list of uncommitted changed files from git status porcelain.
111
+
112
+ Parameters
113
+ ----------
114
+ root_dir : Path
115
+ Project root directory.
116
+
117
+ Returns
118
+ -------
119
+ list[str]
120
+ List of changed file paths.
121
+ """
122
+ res = run_process(["git", "status", "--porcelain"], cwd=root_dir)
123
+ if not res.passed or not res.stdout.strip():
124
+ return []
125
+ files: list[str] = []
126
+ for line in res.stdout.splitlines():
127
+ if len(line) > 3:
128
+ raw_path = line[3:].strip().strip('"')
129
+ if " -> " in raw_path:
130
+ _, raw_path = raw_path.split(" -> ", 1)
131
+ files.append(raw_path.strip().strip('"'))
132
+ return files
133
+
134
+
135
+ def is_git_clean(root_dir: Path) -> bool:
136
+ """Check if git working tree has no uncommitted changes.
137
+
138
+ Parameters
139
+ ----------
140
+ root_dir : Path
141
+ Project root directory.
142
+
143
+ Returns
144
+ -------
145
+ bool
146
+ True if clean, False otherwise.
147
+ """
148
+ return len(get_dirty_files(root_dir)) == 0
@@ -0,0 +1,134 @@
1
+ """PyPI package build and publishing orchestration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from rich.console import Console
9
+
10
+ from project_forge.process import run_process
11
+
12
+ console = Console()
13
+
14
+
15
+ def load_pypi_token(root_dir: Path) -> str | None:
16
+ """Safely load PyPI upload token from environment or .env file."""
17
+ token = os.environ.get("UV_PUBLISH_TOKEN") or os.environ.get("PYPI_TOKEN")
18
+ if token:
19
+ return token.strip()
20
+
21
+ env_path = root_dir / ".env"
22
+ if env_path.exists():
23
+ try:
24
+ for line in env_path.read_text(encoding="utf-8").splitlines():
25
+ stripped = line.strip()
26
+ if not stripped or stripped.startswith("#"):
27
+ continue
28
+ if "=" in stripped:
29
+ key, val = stripped.split("=", 1)
30
+ key = key.strip()
31
+ val = val.strip().strip("'\"")
32
+ if key in ("UV_PUBLISH_TOKEN", "PYPI_TOKEN", "POETRY_PYPI_TOKEN_PYPI"):
33
+ return val
34
+ except OSError:
35
+ pass
36
+
37
+ return None
38
+
39
+
40
+ def run_publish_flow(
41
+ root_dir: Path | None = None,
42
+ skip_quality: bool = False,
43
+ dry_run: bool = False,
44
+ ) -> int:
45
+ """Build distributions with uv build and publish them to PyPI.
46
+
47
+ Parameters
48
+ ----------
49
+ root_dir : Path | None, optional
50
+ Project root directory, by default None.
51
+ skip_quality : bool, optional
52
+ Skip pre-publish quality gate check, by default False.
53
+ dry_run : bool, optional
54
+ Build and check artifacts without uploading to PyPI, by default False.
55
+
56
+ Returns
57
+ -------
58
+ int
59
+ 0 on success, 1 on failure.
60
+ """
61
+ if root_dir is None:
62
+ from project_forge.project import find_project_root
63
+
64
+ root_dir = find_project_root()
65
+
66
+ # 1. Quality gate verification
67
+ if not skip_quality:
68
+ from project_forge.quality import run_quality_gate
69
+
70
+ console.print(
71
+ "[bold cyan]Step 1: Running Pre-Publish Quality Gate Verification...[/bold cyan]"
72
+ )
73
+ exit_code = run_quality_gate(tier="full", export="cli", root_dir=root_dir)
74
+ if exit_code != 0:
75
+ console.print("[bold red]Publish aborted: Quality Gate checks failed.[/bold red]")
76
+ return exit_code
77
+
78
+ # 2. Clean existing artifacts in dist/
79
+ dist_dir = root_dir / "dist"
80
+ if dist_dir.exists():
81
+ console.print("[dim]Cleaning existing distribution packages from dist/...[/dim]")
82
+ for pkg in list(dist_dir.glob("*.whl")) + list(dist_dir.glob("*.tar.gz")):
83
+ try:
84
+ pkg.unlink()
85
+ except OSError:
86
+ pass
87
+
88
+ # 3. Build distribution packages using uv build
89
+ console.print(
90
+ "\n[bold cyan]Step 2: Building distribution packages with 'uv build'...[/bold cyan]"
91
+ )
92
+ build_proc = run_process(["uv", "build"], cwd=root_dir)
93
+ if not build_proc.passed:
94
+ console.print(f"[bold red]✘ uv build failed:[/bold red] {build_proc.stderr}")
95
+ return build_proc.exit_code
96
+
97
+ built_packages = [str(p) for p in dist_dir.glob("*.whl")] + [
98
+ str(p) for p in dist_dir.glob("*.tar.gz")
99
+ ]
100
+ if not built_packages:
101
+ console.print("[bold red]✘ Error: No packages found in dist/ after uv build.[/bold red]")
102
+ return 1
103
+
104
+ console.print(f"[bold green]✔ Built {len(built_packages)} package artifact(s):[/bold green]")
105
+ for pkg_path in built_packages:
106
+ console.print(f" • {Path(pkg_path).name}")
107
+
108
+ if dry_run:
109
+ console.print(
110
+ "\n[yellow]DRY-RUN Mode: Packages built successfully. Skipping PyPI upload.[/yellow]"
111
+ )
112
+ return 0
113
+
114
+ # 4. Publish packages with uv publish
115
+ token = load_pypi_token(root_dir)
116
+ if not token:
117
+ console.print(
118
+ "\n[bold red]✘ PyPI Publish Error: No UV_PUBLISH_TOKEN or PYPI_TOKEN found in .env or environment.[/bold red]\n"
119
+ "[dim]Please add UV_PUBLISH_TOKEN=pypi-... to your .env file or environment.[/dim]"
120
+ )
121
+ return 1
122
+
123
+ console.print(
124
+ "\n[bold cyan]Step 3: Publishing distribution packages to PyPI with 'uv publish'...[/bold cyan]"
125
+ )
126
+ publish_env = {"UV_PUBLISH_TOKEN": token}
127
+ publish_cmd = ["uv", "publish"] + built_packages
128
+ pub_proc = run_process(publish_cmd, cwd=root_dir, env=publish_env)
129
+ if not pub_proc.passed:
130
+ console.print(f"[bold red]✘ uv publish failed:[/bold red] {pub_proc.stderr}")
131
+ return pub_proc.exit_code
132
+
133
+ console.print("[bold green]✔ Successfully published release packages to PyPI![/bold green]")
134
+ return 0
@@ -0,0 +1,259 @@
1
+ """Automated GitHub Pull Request Generator with Quality Gate Certification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import Any, cast
9
+
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+ from rich.syntax import Syntax
13
+
14
+ from project_forge.changelog import parse_changelog
15
+ from project_forge.process import run_process
16
+
17
+ console = Console()
18
+
19
+
20
+ def load_audit_report(root_dir: Path, force_run: bool = False) -> dict[str, Any]:
21
+ """Load latest audit report from outputs/audit_report.json, running audit if missing."""
22
+ report_file = root_dir / "outputs" / "audit_report.json"
23
+
24
+ if force_run or not report_file.exists():
25
+ from project_forge.quality import run_quality_gate
26
+
27
+ console.print("[dim]Generating fresh Quality Gate audit report (Full Tier)...[/dim]")
28
+ run_quality_gate(tier="full", export="all", quiet=True, root_dir=root_dir)
29
+
30
+ if report_file.exists():
31
+ try:
32
+ content = report_file.read_text(encoding="utf-8")
33
+ data = json.loads(content)
34
+ if isinstance(data, dict):
35
+ return cast(dict[str, Any], data)
36
+ except Exception as exc:
37
+ console.print(f"[yellow]Warning: Could not read audit report JSON: {exc}[/yellow]")
38
+
39
+ return {
40
+ "timestamp": "N/A",
41
+ "tier": "full",
42
+ "all_passed": True,
43
+ "total_duration_seconds": 0.0,
44
+ "total_issues": 0,
45
+ "engines": [],
46
+ }
47
+
48
+
49
+ def format_audit_markdown(audit_data: dict[str, Any], head_branch: str, base_branch: str) -> str:
50
+ """Format Quality Gate audit metrics into a GitHub Markdown table."""
51
+ engines = audit_data.get("engines", [])
52
+ all_passed = audit_data.get("all_passed", True)
53
+ total_duration = audit_data.get("total_duration_seconds", 0.0)
54
+ timestamp = audit_data.get("timestamp", "N/A")
55
+
56
+ lines: list[str] = [
57
+ "---",
58
+ "## 🛡️ Quality Gate Certification",
59
+ "",
60
+ "| Quality Engine | Tier | Duration | Issues | Status |",
61
+ "| :--- | :---: | :---: | :---: | :---: |",
62
+ ]
63
+
64
+ for eng in engines:
65
+ name = eng.get("name", "Unknown")
66
+ tier = eng.get("tier", "Full")
67
+ duration = eng.get("duration_seconds", 0.0)
68
+ issues = eng.get("issue_count", 0)
69
+ passed = eng.get("passed", True)
70
+ status_badge = "✅ PASS" if passed else "❌ FAIL"
71
+ lines.append(f"| {name} | {tier} | {duration:.2f}s | {issues} | {status_badge} |")
72
+
73
+ overall_badge = (
74
+ "🟢 **ALL QUALITY ENGINES PASSED**" if all_passed else "🔴 **QUALITY GATE ISSUES DETECTED**"
75
+ )
76
+
77
+ lines.extend(
78
+ [
79
+ "",
80
+ f"> **Gate Status:** {overall_badge} (Total: {total_duration:.2f}s) ",
81
+ f"> **Audit Timestamp:** `{timestamp}` ",
82
+ f"> **Branch Flow:** `{head_branch}` ➔ `{base_branch}` ",
83
+ ]
84
+ )
85
+
86
+ return "\n".join(lines)
87
+
88
+
89
+ def check_gh_cli() -> bool:
90
+ """Check if GitHub CLI (gh) is installed and authenticated."""
91
+ proc = run_process(["gh", "auth", "status"])
92
+ return proc.passed
93
+
94
+
95
+ def find_existing_pr(head: str, base: str, root_dir: Path) -> dict[str, Any] | None:
96
+ """Check if an open pull request already exists between head and base."""
97
+ cmd = [
98
+ "gh",
99
+ "pr",
100
+ "list",
101
+ "--head",
102
+ head,
103
+ "--base",
104
+ base,
105
+ "--state",
106
+ "open",
107
+ "--json",
108
+ "number,title,url,state",
109
+ ]
110
+ proc = run_process(cmd, cwd=root_dir)
111
+ if proc.passed and proc.stdout.strip():
112
+ try:
113
+ raw = json.loads(proc.stdout)
114
+ if isinstance(raw, list) and raw:
115
+ first = cast(dict[str, Any], raw[0])
116
+ return first
117
+ except Exception:
118
+ pass
119
+ return None
120
+
121
+
122
+ def run_pr_workflow(
123
+ root_dir: Path | None = None,
124
+ head: str | None = None,
125
+ base: str | None = None,
126
+ version: str | None = None,
127
+ title: str | None = None,
128
+ draft: bool = False,
129
+ re_audit: bool = False,
130
+ dry_run: bool = False,
131
+ ) -> int:
132
+ """Execute PR preview or creation workflow."""
133
+ if root_dir is None:
134
+ from project_forge.project import find_project_root
135
+
136
+ root_dir = find_project_root()
137
+
138
+ from project_forge.config import load_config
139
+ from project_forge.project import get_git_branch
140
+
141
+ cfg = load_config(root_dir)
142
+ head_branch = head or get_git_branch(root_dir)
143
+ base_branch = base or cfg.git.default_branch
144
+
145
+ changelog_path = root_dir / cfg.changelog
146
+ if not changelog_path.exists():
147
+ console.print(f"[bold red]Error: Changelog file not found at {changelog_path}[/bold red]")
148
+ return 1
149
+
150
+ releases = parse_changelog(changelog_path)
151
+ if not releases:
152
+ console.print("[bold red]Error: No releases parsed from changelog.[/bold red]")
153
+ return 1
154
+
155
+ if version:
156
+ clean_target = version.lstrip("v")
157
+ target_entry = next((r for r in releases if r.clean_version == clean_target), None)
158
+ if not target_entry:
159
+ console.print(
160
+ f"[bold red]Error: Version '{version}' not found in {changelog_path.name}[/bold red]"
161
+ )
162
+ return 1
163
+ else:
164
+ target_entry = releases[0]
165
+
166
+ pr_title = title or f"Release v{target_entry.clean_version}"
167
+ audit_data = load_audit_report(root_dir, force_run=re_audit)
168
+ audit_md = format_audit_markdown(audit_data, head_branch=head_branch, base_branch=base_branch)
169
+
170
+ pr_body = f"{target_entry.body}\n\n{audit_md}\n"
171
+
172
+ if dry_run:
173
+ console.print(
174
+ Panel(
175
+ f"[bold cyan]Base Branch:[/bold cyan] {base_branch}\n"
176
+ f"[bold cyan]Head Branch:[/bold cyan] {head_branch}\n"
177
+ f"[bold cyan]PR Title:[/bold cyan] {pr_title}\n"
178
+ f"[bold cyan]Mode:[/bold cyan] [yellow]DRY-RUN PREVIEW[/yellow]\n"
179
+ f"[dim]Draft PR:[/dim] {'Yes' if draft else 'No'}",
180
+ title="[bold yellow]Pull Request Preview[/bold yellow]",
181
+ border_style="yellow",
182
+ )
183
+ )
184
+ syntax = Syntax(pr_body, "markdown", theme="monokai", line_numbers=False)
185
+ console.print(Panel(syntax, title="Generated PR Body", border_style="cyan"))
186
+ console.print(
187
+ "[green]Dry run complete. Use create command to publish PR to GitHub.[/green]"
188
+ )
189
+ return 0
190
+
191
+ if not check_gh_cli():
192
+ console.print(
193
+ "[bold red]Error: GitHub CLI (gh) is not installed or authenticated.[/bold red]"
194
+ )
195
+ console.print("[dim]Run 'gh auth login' to authenticate with your GitHub account.[/dim]")
196
+ return 1
197
+
198
+ existing_pr = find_existing_pr(head=head_branch, base=base_branch, root_dir=root_dir)
199
+
200
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False, suffix=".md") as f:
201
+ f.write(pr_body)
202
+ temp_body_path = f.name
203
+
204
+ try:
205
+ if existing_pr:
206
+ pr_num = str(existing_pr.get("number", ""))
207
+ pr_url = str(existing_pr.get("url", ""))
208
+ console.print(
209
+ f"[bold cyan]Found open PR #{pr_num}. Updating title and description...[/bold cyan]"
210
+ )
211
+ cmd = [
212
+ "gh",
213
+ "pr",
214
+ "edit",
215
+ pr_num,
216
+ "--title",
217
+ pr_title,
218
+ "--body-file",
219
+ temp_body_path,
220
+ ]
221
+ res = run_process(cmd, cwd=root_dir)
222
+ if res.passed:
223
+ console.print(
224
+ f"[bold green]✔ Successfully updated PR #{pr_num}:[/bold green] {pr_url}"
225
+ )
226
+ return 0
227
+ console.print(f"[bold red]✘ Failed to update PR #{pr_num}:[/bold red] {res.stderr}")
228
+ return 1
229
+
230
+ console.print(
231
+ f"[bold cyan]Creating new pull request from '{head_branch}' into '{base_branch}'...[/bold cyan]"
232
+ )
233
+ cmd = [
234
+ "gh",
235
+ "pr",
236
+ "create",
237
+ "--head",
238
+ head_branch,
239
+ "--base",
240
+ base_branch,
241
+ "--title",
242
+ pr_title,
243
+ "--body-file",
244
+ temp_body_path,
245
+ ]
246
+ if draft:
247
+ cmd.append("--draft")
248
+
249
+ res = run_process(cmd, cwd=root_dir)
250
+ if res.passed:
251
+ new_url = res.stdout.strip()
252
+ console.print(
253
+ f"[bold green]✔ Successfully created Pull Request:[/bold green] {new_url}"
254
+ )
255
+ return 0
256
+ console.print(f"[bold red]✘ Failed to create pull request:[/bold red] {res.stderr}")
257
+ return 1
258
+ finally:
259
+ Path(temp_body_path).unlink(missing_ok=True)