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,184 @@
1
+ """Consolidated changelog parser, validator, and release notes extractor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+
10
+ @dataclass
11
+ class ReleaseNotes:
12
+ """Parsed release section from a CHANGELOG.md file."""
13
+
14
+ version: str
15
+ raw_version: str
16
+ title: str
17
+ date: str | None
18
+ body: str
19
+
20
+ @property
21
+ def clean_version(self) -> str:
22
+ """Version string with leading 'v' stripped."""
23
+ return self.version.lstrip("v")
24
+
25
+
26
+ def parse_changelog(changelog_path: Path) -> list[ReleaseNotes]:
27
+ """Parse CHANGELOG.md and extract all release sections.
28
+
29
+ Supports Markdown headers like:
30
+ - ## [1.2.0] - 2026-11-24
31
+ - ## [v1.2.0] (2026-11-24)
32
+ - ## 1.2.0
33
+ - ### [1.2.0]
34
+
35
+ Parameters
36
+ ----------
37
+ changelog_path : Path
38
+ Path to the changelog file.
39
+
40
+ Returns
41
+ -------
42
+ list[ReleaseNotes]
43
+ Ordered list of parsed releases (latest first).
44
+ """
45
+ if not changelog_path.is_file():
46
+ return []
47
+
48
+ content = changelog_path.read_text(encoding="utf-8", errors="replace")
49
+
50
+ # Match header line containing version
51
+ # e.g.: ## [1.2.3] or ## v1.2.3 or ### [1.2.3] - 2026-01-01
52
+ header_pattern = re.compile(
53
+ r"^#{2,3}\s+(?:\[(?P<ver_bracket>v?\d+\.\d+\.\d+[^\s\]]*)\]|(?P<ver_plain>v?\d+\.\d+\.\d+[^\s\(]*))"
54
+ r"(?:\s*[-–—]?\s*(?:\((?P<date_paren>[^)]+)\)|(?P<date_plain>\d{4}-\d{2}-\d{2})))?",
55
+ re.MULTILINE,
56
+ )
57
+
58
+ matches = list(header_pattern.finditer(content))
59
+ releases: list[ReleaseNotes] = []
60
+
61
+ for i, match in enumerate(matches):
62
+ raw_ver = (match.group("ver_bracket") or match.group("ver_plain") or "").strip()
63
+ version = raw_ver.lstrip("v")
64
+ date_str = match.group("date_paren") or match.group("date_plain")
65
+ if date_str:
66
+ date_str = date_str.strip()
67
+
68
+ start_idx = match.start()
69
+ end_idx = matches[i + 1].start() if i + 1 < len(matches) else len(content)
70
+
71
+ raw_body = content[start_idx:end_idx].strip()
72
+ # Normalize top-level header of section to ## if it was ###
73
+ body = "## " + raw_body[4:] if raw_body.startswith("### ") else raw_body
74
+
75
+ releases.append(
76
+ ReleaseNotes(
77
+ version=version,
78
+ raw_version=raw_ver,
79
+ title=f"Release - v{version}",
80
+ date=date_str,
81
+ body=body,
82
+ )
83
+ )
84
+
85
+ return releases
86
+
87
+
88
+ def get_latest_release(changelog_path: Path) -> ReleaseNotes | None:
89
+ """Return the most recent release entry in CHANGELOG.md.
90
+
91
+ Parameters
92
+ ----------
93
+ changelog_path : Path
94
+ Path to CHANGELOG.md.
95
+
96
+ Returns
97
+ -------
98
+ ReleaseNotes | None
99
+ The latest release notes, or None if changelog is empty/missing.
100
+ """
101
+ releases = parse_changelog(changelog_path)
102
+ return releases[0] if releases else None
103
+
104
+
105
+ def get_release_by_version(changelog_path: Path, version: str) -> ReleaseNotes | None:
106
+ """Retrieve specific release notes by target version.
107
+
108
+ Parameters
109
+ ----------
110
+ changelog_path : Path
111
+ Path to CHANGELOG.md.
112
+ version : str
113
+ Target version (e.g. '1.2.0' or 'v1.2.0').
114
+
115
+ Returns
116
+ -------
117
+ ReleaseNotes | None
118
+ Matching release notes, or None if not found.
119
+ """
120
+ clean_target = version.lstrip("v").strip()
121
+ releases = parse_changelog(changelog_path)
122
+ for rel in releases:
123
+ if rel.clean_version == clean_target:
124
+ return rel
125
+ return None
126
+
127
+
128
+ def validate_changelog(changelog_path: Path) -> tuple[bool, list[str]]:
129
+ """Validate CHANGELOG.md existence and formatting.
130
+
131
+ Parameters
132
+ ----------
133
+ changelog_path : Path
134
+ Path to CHANGELOG.md.
135
+
136
+ Returns
137
+ -------
138
+ tuple[bool, list[str]]
139
+ (is_valid, error_messages)
140
+ """
141
+ errors: list[str] = []
142
+ if not changelog_path.exists():
143
+ errors.append(f"Changelog file does not exist: {changelog_path}")
144
+ return False, errors
145
+
146
+ releases = parse_changelog(changelog_path)
147
+ if not releases:
148
+ errors.append(
149
+ "No valid SemVer release headers found in changelog (expected '## [X.Y.Z]' or '## X.Y.Z')."
150
+ )
151
+ return False, errors
152
+
153
+ return True, []
154
+
155
+
156
+ def resolve_git_tag(
157
+ version: str,
158
+ existing_tags: set[str],
159
+ tag_prefix: str = "v",
160
+ ) -> str | None:
161
+ """Match a version string against existing git tags.
162
+
163
+ Checks '{tag_prefix}{clean_ver}' first, then '{clean_ver}'.
164
+
165
+ Parameters
166
+ ----------
167
+ version : str
168
+ Version to match.
169
+ existing_tags : set[str]
170
+ Set of available git tags in repository.
171
+ tag_prefix : str, optional
172
+ Tag prefix (default 'v').
173
+
174
+ Returns
175
+ -------
176
+ str | None
177
+ The matching tag name in existing_tags, or None if not found.
178
+ """
179
+ clean_ver = version.lstrip("v").strip()
180
+ candidates = [f"{tag_prefix}{clean_ver}", clean_ver]
181
+ for cand in candidates:
182
+ if cand in existing_tags:
183
+ return cand
184
+ return None
project_forge/cli.py ADDED
@@ -0,0 +1,386 @@
1
+ """Top-level Typer CLI command router for Project Forge (pforge)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typer
6
+
7
+ from project_forge.bumper import run_bump
8
+ from project_forge.changelog import (
9
+ get_latest_release,
10
+ get_release_by_version,
11
+ validate_changelog,
12
+ )
13
+ from project_forge.commits import execute_commit_flow
14
+ from project_forge.config import load_config
15
+ from project_forge.doctor import run_doctor
16
+ from project_forge.documentation import run_documentation_audit
17
+ from project_forge.hooks import get_hooks_status, install_hooks, uninstall_hooks
18
+ from project_forge.project import find_project_root
19
+ from project_forge.publishing import run_publish_flow
20
+ from project_forge.pull_requests import run_pr_workflow
21
+ from project_forge.quality import run_quality_gate
22
+ from project_forge.releases import run_release_workflow
23
+ from project_forge.status import show_status
24
+
25
+ app = typer.Typer(
26
+ name="pforge",
27
+ help="Repository-neutral engineering workflow CLI for quality gates, commits, releases, and versioning.",
28
+ no_args_is_help=True,
29
+ )
30
+
31
+ hooks_app = typer.Typer(
32
+ name="hooks", help="Manage git pre-commit and pre-push quality hooks.", no_args_is_help=True
33
+ )
34
+ changelog_app = typer.Typer(
35
+ name="changelog", help="Inspect and validate CHANGELOG.md.", no_args_is_help=True
36
+ )
37
+ pr_app = typer.Typer(
38
+ name="pr", help="Preview and create GitHub pull requests.", no_args_is_help=True
39
+ )
40
+ release_app = typer.Typer(
41
+ name="release", help="Preview and publish GitHub releases.", no_args_is_help=True
42
+ )
43
+ docs_app = typer.Typer(name="docs", help="AST-level documentation auditor.", no_args_is_help=True)
44
+
45
+ app.add_typer(hooks_app)
46
+ app.add_typer(changelog_app)
47
+ app.add_typer(pr_app)
48
+ app.add_typer(release_app)
49
+ app.add_typer(docs_app)
50
+
51
+
52
+ @app.command()
53
+ def doctor() -> None:
54
+ """Run diagnostic checks on repository configuration and external toolchains."""
55
+ code = run_doctor()
56
+ raise typer.Exit(code)
57
+
58
+
59
+ @app.command()
60
+ def status() -> None:
61
+ """Display high-level snapshot dashboard of project status."""
62
+ code = show_status()
63
+ raise typer.Exit(code)
64
+
65
+
66
+ @app.command()
67
+ def bump(
68
+ release_as: str | None = typer.Option(
69
+ None,
70
+ "--release-as",
71
+ "-r",
72
+ help="Explicit release increment ('patch', 'minor', 'major', or version like '1.2.0').",
73
+ ),
74
+ prerelease: str | None = typer.Option(
75
+ None,
76
+ "--prerelease",
77
+ "-p",
78
+ help="Prerelease tag identifier ('alpha', 'beta', 'rc').",
79
+ ),
80
+ first_release: bool = typer.Option(
81
+ False,
82
+ "--first-release",
83
+ help="Generate first release from repository inception.",
84
+ ),
85
+ dry_run: bool = typer.Option(
86
+ False,
87
+ "--dry-run",
88
+ "-d",
89
+ help="Preview version calculation and changelog without writing files or making Git commits.",
90
+ ),
91
+ no_commit: bool = typer.Option(
92
+ False,
93
+ "--no-commit",
94
+ help="Do not create release commit.",
95
+ ),
96
+ no_tag: bool = typer.Option(
97
+ False,
98
+ "--no-tag",
99
+ help="Do not create annotated release tag.",
100
+ ),
101
+ ) -> None:
102
+ """Native Python SemVer version bumper and changelog generator."""
103
+ root_dir = find_project_root()
104
+ cfg = load_config(root_dir)
105
+ code, new_version = run_bump(
106
+ root_dir=root_dir,
107
+ release_as=release_as,
108
+ prerelease=prerelease,
109
+ first_release=first_release,
110
+ dry_run=dry_run,
111
+ no_commit=no_commit,
112
+ no_tag=no_tag,
113
+ tag_prefix=cfg.bump.tag_prefix,
114
+ )
115
+ if dry_run:
116
+ typer.echo(f"[DRY-RUN] Next calculated version: {new_version}")
117
+ else:
118
+ typer.echo(f"Successfully bumped version to v{new_version}")
119
+ raise typer.Exit(code)
120
+
121
+
122
+ @app.command()
123
+ def quality(
124
+ fast: bool = typer.Option(
125
+ False, "--fast", help="Run Tier 1 fast checks (<2s: Ruff Lint, Format, Mypy)."
126
+ ),
127
+ fix: bool = typer.Option(
128
+ False, "--fix", help="Automatically apply safe formatting and lint fixes."
129
+ ),
130
+ tier: str = typer.Option("full", "--tier", help="Quality tier: 'fast' or 'full'."),
131
+ export: str = typer.Option(
132
+ "cli", "--export", help="Output format: 'cli', 'csv', 'json', or 'all'."
133
+ ),
134
+ output_path: str | None = typer.Option(
135
+ None, "--output-path", help="Destination path for exported report file."
136
+ ),
137
+ quiet: bool = typer.Option(False, "--quiet", "-q", help="Suppress progress logs."),
138
+ ) -> None:
139
+ """Run unified multi-engine quality gate and diagnostics."""
140
+ chosen_tier = "fast" if fast else tier
141
+ code = run_quality_gate(
142
+ tier=chosen_tier,
143
+ export=export,
144
+ output_path=output_path,
145
+ auto_fix=fix,
146
+ quiet=quiet,
147
+ )
148
+ raise typer.Exit(code)
149
+
150
+
151
+ @app.command()
152
+ def commit(
153
+ preview: bool = typer.Option(
154
+ False, "--preview", "--dry-run", help="Preview atomic commit groups without committing."
155
+ ),
156
+ interactive: bool = typer.Option(
157
+ False, "--interactive", "-i", help="Interactive file/group commit wizard."
158
+ ),
159
+ run: bool = typer.Option(False, "--run", help="Execute commits immediately."),
160
+ map_path: str | None = typer.Option(
161
+ None, "--map", help="Path to custom Message-to-Paths overrides JSON."
162
+ ),
163
+ only_mapped: bool = typer.Option(
164
+ False, "--only-mapped", help="Only commit files explicitly mapped in overrides."
165
+ ),
166
+ no_verify: bool = typer.Option(
167
+ False, "--no-verify", "-n", help="Bypass git hooks during commit execution."
168
+ ),
169
+ skip_audit: bool = typer.Option(False, "--skip-audit", help="Skip upfront quality gate check."),
170
+ ) -> None:
171
+ """Automated conventional commits with scope inference and grouping."""
172
+ code = execute_commit_flow(
173
+ dry_run=preview,
174
+ interactive=interactive,
175
+ run=run,
176
+ map_path=map_path,
177
+ only_mapped=only_mapped,
178
+ no_verify=no_verify,
179
+ skip_audit=skip_audit,
180
+ )
181
+ raise typer.Exit(code)
182
+
183
+
184
+ @app.command()
185
+ def publish(
186
+ skip_quality: bool = typer.Option(
187
+ False, "--skip-quality", help="Skip pre-publish quality gate check."
188
+ ),
189
+ dry_run: bool = typer.Option(
190
+ False, "--dry-run", "-d", help="Build and check packages without uploading to PyPI."
191
+ ),
192
+ ) -> None:
193
+ """Build distribution packages and publish to PyPI using token from .env or environment."""
194
+ code = run_publish_flow(skip_quality=skip_quality, dry_run=dry_run)
195
+ raise typer.Exit(code)
196
+
197
+
198
+ # -----------------------------------------------------------------------------
199
+ # Hooks Subcommands
200
+ # -----------------------------------------------------------------------------
201
+
202
+
203
+ @hooks_app.command("install")
204
+ def hooks_install() -> None:
205
+ """Install git pre-commit and pre-push quality hooks."""
206
+ code = install_hooks()
207
+ if code == 0:
208
+ typer.echo("Git quality hooks installed successfully.")
209
+ raise typer.Exit(code)
210
+
211
+
212
+ @hooks_app.command("status")
213
+ def hooks_status_cmd() -> None:
214
+ """Check git hooks installation and configuration status."""
215
+ st = get_hooks_status()
216
+ typer.echo(f"Hooks Installed : {st['installed']}")
217
+ typer.echo(f"Git core.hooksPath : {st['core_hooks_path']}")
218
+ typer.echo(f"Tracked pre-commit : {st['tracked_pre_commit']}")
219
+ typer.echo(f"Tracked pre-push : {st['tracked_pre_push']}")
220
+
221
+
222
+ @hooks_app.command("uninstall")
223
+ def hooks_uninstall() -> None:
224
+ """Uninstall git hooks and unset git core.hooksPath."""
225
+ code = uninstall_hooks()
226
+ typer.echo("Git hooks uninstalled.")
227
+ raise typer.Exit(code)
228
+
229
+
230
+ # -----------------------------------------------------------------------------
231
+ # Changelog Subcommands
232
+ # -----------------------------------------------------------------------------
233
+
234
+
235
+ @changelog_app.command("validate")
236
+ def changelog_validate() -> None:
237
+ """Validate CHANGELOG.md file existence and formatting."""
238
+ root_dir = find_project_root()
239
+ cfg = load_config(root_dir)
240
+ valid, errors = validate_changelog(root_dir / cfg.changelog)
241
+ if valid:
242
+ typer.echo(f"Changelog '{cfg.changelog}' is valid.")
243
+ raise typer.Exit(0)
244
+ for err in errors:
245
+ typer.echo(f"Error: {err}", err=True)
246
+ raise typer.Exit(1)
247
+
248
+
249
+ @changelog_app.command("latest")
250
+ def changelog_latest() -> None:
251
+ """Display the latest release notes from CHANGELOG.md."""
252
+ root_dir = find_project_root()
253
+ cfg = load_config(root_dir)
254
+ rel = get_latest_release(root_dir / cfg.changelog)
255
+ if rel:
256
+ typer.echo(rel.body)
257
+ raise typer.Exit(0)
258
+ typer.echo("No releases found in changelog.", err=True)
259
+ raise typer.Exit(1)
260
+
261
+
262
+ @changelog_app.command("show")
263
+ def changelog_show(version: str = typer.Argument(..., help="Release version to display.")) -> None:
264
+ """Display release notes for a specific version."""
265
+ root_dir = find_project_root()
266
+ cfg = load_config(root_dir)
267
+ rel = get_release_by_version(root_dir / cfg.changelog, version)
268
+ if rel:
269
+ typer.echo(rel.body)
270
+ raise typer.Exit(0)
271
+ typer.echo(f"Version '{version}' not found in changelog.", err=True)
272
+ raise typer.Exit(1)
273
+
274
+
275
+ # -----------------------------------------------------------------------------
276
+ # PR Subcommands
277
+ # -----------------------------------------------------------------------------
278
+
279
+
280
+ @pr_app.command("preview")
281
+ def pr_preview(
282
+ head: str | None = typer.Option(None, "--head", help="Source branch."),
283
+ base: str | None = typer.Option(None, "--base", help="Target branch."),
284
+ version: str | None = typer.Option(
285
+ None, "--version", help="Version to extract from changelog."
286
+ ),
287
+ title: str | None = typer.Option(None, "--title", help="Custom PR title."),
288
+ draft: bool = typer.Option(False, "--draft", help="Preview as draft PR."),
289
+ re_audit: bool = typer.Option(False, "--re-audit", help="Force fresh quality gate execution."),
290
+ ) -> None:
291
+ """Preview PR title, changelog body, and Quality Gate certification table."""
292
+ code = run_pr_workflow(
293
+ head=head,
294
+ base=base,
295
+ version=version,
296
+ title=title,
297
+ draft=draft,
298
+ re_audit=re_audit,
299
+ dry_run=True,
300
+ )
301
+ raise typer.Exit(code)
302
+
303
+
304
+ @pr_app.command("create")
305
+ def pr_create(
306
+ head: str | None = typer.Option(None, "--head", help="Source branch."),
307
+ base: str | None = typer.Option(None, "--base", help="Target branch."),
308
+ version: str | None = typer.Option(
309
+ None, "--version", help="Version to extract from changelog."
310
+ ),
311
+ title: str | None = typer.Option(None, "--title", help="Custom PR title."),
312
+ draft: bool = typer.Option(False, "--draft", help="Open as draft PR."),
313
+ re_audit: bool = typer.Option(False, "--re-audit", help="Force fresh quality gate execution."),
314
+ ) -> None:
315
+ """Create or update GitHub PR with embedded Quality Gate certification."""
316
+ code = run_pr_workflow(
317
+ head=head,
318
+ base=base,
319
+ version=version,
320
+ title=title,
321
+ draft=draft,
322
+ re_audit=re_audit,
323
+ dry_run=False,
324
+ )
325
+ raise typer.Exit(code)
326
+
327
+
328
+ # -----------------------------------------------------------------------------
329
+ # Release Subcommands
330
+ # -----------------------------------------------------------------------------
331
+
332
+
333
+ @release_app.command("preview")
334
+ def release_preview(
335
+ latest: bool = typer.Option(True, "--latest", help="Preview latest changelog entry."),
336
+ version: str | None = typer.Option(None, "--version", help="Target specific version."),
337
+ all_releases: bool = typer.Option(False, "--all", help="Preview all changelog entries."),
338
+ ) -> None:
339
+ """Preview release notes from changelog."""
340
+ code = run_release_workflow(
341
+ publish=False,
342
+ latest=latest,
343
+ single_version=version,
344
+ preview_all=all_releases,
345
+ )
346
+ raise typer.Exit(code)
347
+
348
+
349
+ @release_app.command("publish")
350
+ def release_publish(
351
+ latest: bool = typer.Option(True, "--latest", help="Publish latest version."),
352
+ version: str | None = typer.Option(None, "--version", help="Target specific version."),
353
+ draft: bool = typer.Option(False, "--draft", help="Publish as draft release on GitHub."),
354
+ interactive: bool = typer.Option(
355
+ False, "--interactive", "-i", help="Prompt before publishing."
356
+ ),
357
+ ) -> None:
358
+ """Publish release to GitHub using gh CLI."""
359
+ code = run_release_workflow(
360
+ publish=True,
361
+ latest=latest,
362
+ single_version=version,
363
+ draft=draft,
364
+ interactive=interactive,
365
+ )
366
+ raise typer.Exit(code)
367
+
368
+
369
+ # -----------------------------------------------------------------------------
370
+ # Docs Subcommands
371
+ # -----------------------------------------------------------------------------
372
+
373
+
374
+ @docs_app.command("audit")
375
+ def docs_audit(
376
+ strict: bool = typer.Option(
377
+ False, "--strict", help="Include private methods and internal helpers."
378
+ ),
379
+ require_init: bool = typer.Option(
380
+ False, "--require-init", help="Require explicit __init__ docstring."
381
+ ),
382
+ as_json: bool = typer.Option(False, "--json", help="Output structured JSON instead of table."),
383
+ ) -> None:
384
+ """Run AST documentation auditor across configured source roots."""
385
+ code = run_documentation_audit(strict=strict, require_init=require_init, as_json=as_json)
386
+ raise typer.Exit(code)