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,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: pforge-cli
3
+ Version: 0.1.0
4
+ Summary: Repository-neutral engineering workflow CLI for quality gates, commits, releases, and versioning.
5
+ Author: tks18
6
+ Author-email: tks18 <tksudharshan@gmail.com>
7
+ License-Expression: GPL-3.0-or-later
8
+ Requires-Dist: packaging>=24.0
9
+ Requires-Dist: pydantic>=2.7.0
10
+ Requires-Dist: rich>=13.0.0
11
+ Requires-Dist: tomlkit>=0.12.0
12
+ Requires-Dist: typer>=0.12.0
13
+ Requires-Python: >=3.13
14
+ Description-Content-Type: text/markdown
15
+
16
+ # Project Forge (`pforge` / `pforge-cli`)
17
+
18
+ Repository-neutral engineering workflow CLI for quality gates, conventional commits, releases, and versioning.
19
+
20
+ ## Overview
21
+
22
+ Project Forge standardizes common Python repository engineering workflows into a single standalone CLI without copying scripts from repository to repository:
23
+
24
+ - **Multi-engine Quality Gate**: Fast (<2s) and Full diagnostic checks across Ruff (lint & format), Mypy, Pyright, Pylint, and Pytest.
25
+ - **Native Standard-Version Replacement**: Pure Python SemVer bumper (`pforge bump`) calculating increments from Conventional Commits, updating project files, generating `CHANGELOG.md`, and tagging releases.
26
+ - **Conventional Commit Automation**: Grouped atomic commits with repository-neutral scope inference and interactive wizard (`pforge commit`).
27
+ - **Quality Hooks**: Project-neutral Git hooks (`pre-commit` and `pre-push`) calling `pforge quality`.
28
+ - **Changelog & GitHub Workflows**: Single-source changelog parsing, pull request creation with embedded quality tables, and GitHub release publication.
29
+ - **Publishing & Diagnostics**: Clean `uv build` and `uv publish` orchestration, and non-destructive `doctor` and `status` commands.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ # Using uv (recommended)
35
+ uv add --dev pforge-cli
36
+
37
+ # Using pip
38
+ pip install pforge-cli
39
+ ```
40
+
41
+ ## CLI Usage
42
+
43
+ ### Diagnostics & Status
44
+ ```bash
45
+ pforge status # High-level dashboard snapshot of repository state
46
+ pforge doctor # Diagnostic environment verification of tools and configs
47
+ ```
48
+
49
+ ### Quality Gate
50
+ ```bash
51
+ pforge quality --fast # Fast Tier (<2s): Ruff check, Ruff format check, Mypy
52
+ pforge quality --fast --fix # Auto-apply safe Ruff lint & format fixes
53
+ pforge quality # Full Tier: Ruff, Mypy, Pyright, Pylint, Pytest
54
+ pforge quality --export all # Export structured audit reports to outputs/ (CSV & JSON)
55
+ ```
56
+
57
+ ### Version Bumping & Changelog
58
+ ```bash
59
+ pforge bump --dry-run # Preview next version and changelog entry
60
+ pforge bump # Automatically detect bump type and update files
61
+ pforge bump --release-as minor # Explicitly bump minor (or patch, major)
62
+ pforge bump --prerelease rc # Bump with prerelease identifier
63
+ ```
64
+
65
+ ### Automated Conventional Commits
66
+ ```bash
67
+ pforge commit --preview # Preview grouped atomic conventional commits
68
+ pforge commit -i # Interactive commit wizard with diff inspection
69
+ pforge commit --run # Execute atomic commits immediately
70
+ ```
71
+
72
+ ### Git Quality Hooks
73
+ ```bash
74
+ pforge hooks install # Install pre-commit and pre-push quality hooks
75
+ pforge hooks status # Check installation and core.hooksPath status
76
+ pforge hooks uninstall # Clean hooks and unset core.hooksPath
77
+ ```
78
+
79
+ ### Pull Requests & Releases
80
+ ```bash
81
+ pforge pr preview # Preview PR title, notes, and Quality Gate table
82
+ pforge pr create # Create/update PR on GitHub via gh CLI
83
+ pforge release preview # Preview release notes for latest version
84
+ pforge release publish # Publish release to GitHub via gh CLI
85
+ ```
86
+
87
+ ### PyPI Publishing
88
+ ```bash
89
+ pforge publish --dry-run # Verify quality, clean dist/, build with uv build
90
+ pforge publish # Build packages and upload to PyPI using token
91
+ ```
92
+
93
+ ## Configuration (`pyproject.toml`)
94
+
95
+ Project Forge works with zero configuration for standard Python repositories. Custom settings can be optionally configured under `[tool.project-forge]`:
96
+
97
+ ```toml
98
+ [tool.project-forge]
99
+ source = ["src"]
100
+ tests = ["tests"]
101
+ changelog = "CHANGELOG.md"
102
+
103
+ [tool.project-forge.git]
104
+ development_branch = "dev"
105
+ default_branch = "main"
106
+
107
+ [tool.project-forge.quality]
108
+ fast = ["ruff-check", "ruff-format", "mypy"]
109
+ full = ["ruff-check", "ruff-format", "mypy", "pyright", "pytest"]
110
+
111
+ [tool.project-forge.commits]
112
+ header_max_length = 72
113
+
114
+ [tool.project-forge.bump]
115
+ tag_prefix = "v"
116
+ files = ["pyproject.toml", "src/**/__init__.py"]
117
+
118
+ [tool.project-forge.docs]
119
+ require_module_docstrings = true
120
+ require_package_ownership = false
121
+ ```
122
+
123
+ ## Development & Testing
124
+
125
+ ```bash
126
+ # Sync environment
127
+ uv sync
128
+
129
+ # Run test suite
130
+ uv run pytest tests/ -v
131
+
132
+ # Run linters and typecheckers
133
+ uv run ruff check .
134
+ uv run ruff format --check src/ tests/
135
+ uv run mypy src
136
+ uv run pyright
137
+ ```
138
+
139
+ ## License
140
+
141
+ GPL-3.0-or-later
142
+
@@ -0,0 +1,20 @@
1
+ project_forge/__init__.py,sha256=v5KcbQM4jx5E4_S9csbaeMVYNgFwibVd-KNLAvgzfrY,138
2
+ project_forge/bumper.py,sha256=HUGWaS5TfcLho0mYYtWiPpWp5oDypVLte-_XOG9y5NY,15100
3
+ project_forge/changelog.py,sha256=wilFBKWBKWjUZqWQ-7iC5pddbzu2UyhVCGe-nPOAZAM,5036
4
+ project_forge/cli.py,sha256=ftDFKB_cx54Jp2__48QymBbtkZyzYfztRe6vldg8JJ0,13194
5
+ project_forge/commits.py,sha256=9l-fftHxN1pjXzPJa6_yaL9T7wtW-hXL3p40TCLTWzA,21377
6
+ project_forge/config.py,sha256=EuAWISK5b7SZKQN0SmxFtAiPGZQkMzC-mwLSplDUIS8,3182
7
+ project_forge/doctor.py,sha256=4mcO5xS9ibbsMgsFMWSMXIGGNgL-i-Y9g7SGAzf9gPY,4405
8
+ project_forge/documentation.py,sha256=OqFhhd-_8pO_LcL5z18tobRmWprAQyJD-bs7kinzpAI,9591
9
+ project_forge/hooks.py,sha256=b13hYlMDcNtVNOeu2FssNHs-pY9CbMEpFNVffH99_D0,6129
10
+ project_forge/process.py,sha256=UBIVn4Nc-61SaTAxvwHuXUzNnFZqUqzMHZoHii33Xww,3818
11
+ project_forge/project.py,sha256=3MiDcosHM0-Pnc-rp5zy4q5V1fmdZ9yTvB8wEFKh4yA,3867
12
+ project_forge/publishing.py,sha256=D2sGQRhmbA5Byx-WoOJRfzHrxuUclG9rzlgVKMGzVts,4632
13
+ project_forge/pull_requests.py,sha256=-Py9RALK_by4o045iTjQ6U73UJmYOVi3hrszPKWtRQY,8724
14
+ project_forge/quality.py,sha256=DkCo_bVPDEV5rT9j1GhnqJUyL1ov3H9MVoWFu8yVxyo,15815
15
+ project_forge/releases.py,sha256=B_C8R06p8togR-rzKZecYCFv7eNgcEK54zY4D5H7ozk,5708
16
+ project_forge/status.py,sha256=zJgs8HHqxp67hosLN5XBt-eu0biXfSiftRktgib2mDc,2344
17
+ pforge_cli-0.1.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
18
+ pforge_cli-0.1.0.dist-info/entry_points.txt,sha256=NsYQj96e4-3nLPSQb-eguZSdpWGmkOeLzQ9PQVOnRlo,50
19
+ pforge_cli-0.1.0.dist-info/METADATA,sha256=pn4bOo9E9Z8j0nqIMNMeMVLRTmG_AxYYA5g9_8Vduv4,4746
20
+ pforge_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.9
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ pforge = project_forge.cli:app
3
+
@@ -0,0 +1,6 @@
1
+ """Project Forge (pforge) package initialization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["__version__"]
@@ -0,0 +1,514 @@
1
+ """Native Python standard-version replacement for version bumping and changelog generation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from dataclasses import dataclass
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+
11
+ import tomlkit
12
+ from packaging.version import InvalidVersion, Version
13
+
14
+ from project_forge.process import run_process
15
+
16
+
17
+ @dataclass
18
+ class ParsedCommit:
19
+ """Structured representation of a conventional commit."""
20
+
21
+ commit_hash: str
22
+ subject: str
23
+ body: str
24
+ commit_type: str = "chore"
25
+ scope: str = ""
26
+ description: str = ""
27
+ is_breaking: bool = False
28
+
29
+
30
+ # Map conventional commit types to section titles and icons
31
+ CATEGORY_MAP: dict[str, str] = {
32
+ "feat": "Features 🔥",
33
+ "fix": "Bug Fixes 🛠",
34
+ "perf": "Performance Improvements 🏎",
35
+ "refactor": "Code Refactoring 🖌",
36
+ "docs": "Documentation 📃",
37
+ "test": "Tests 🧪",
38
+ "build": "Build System 🏗",
39
+ "ci": "CI / Tooling 🛠",
40
+ "style": "Styling 🎨",
41
+ "revert": "Reverts ◀",
42
+ "chore": "Others 🔧",
43
+ }
44
+
45
+
46
+ def parse_conventional_commit(commit_hash: str, subject: str, body: str) -> ParsedCommit:
47
+ """Parse conventional commit header and body for type, scope, breaking changes.
48
+
49
+ Parameters
50
+ ----------
51
+ commit_hash : str
52
+ Git commit hash (short or full).
53
+ subject : str
54
+ First line of commit message.
55
+ body : str
56
+ Remaining lines of commit message.
57
+
58
+ Returns
59
+ -------
60
+ ParsedCommit
61
+ Parsed commit representation.
62
+ """
63
+ # Regex: ^(?P<type>[a-zA-Z]+)(?:\((?P<scope>[^)]+)\))?(?P<breaking>!)?:\s+(?P<desc>.+)$
64
+ pattern = re.compile(
65
+ r"^(?P<type>[a-zA-Z]+)(?:\((?P<scope>[^)]+)\))?(?P<breaking>!)?:\s+(?P<desc>.+)$"
66
+ )
67
+ match = pattern.match(subject.strip())
68
+
69
+ is_breaking = False
70
+ if "BREAKING CHANGE:" in body or "BREAKING-CHANGE:" in body:
71
+ is_breaking = True
72
+
73
+ if match:
74
+ c_type = match.group("type").lower()
75
+ scope = match.group("scope") or ""
76
+ breaking_mark = match.group("breaking")
77
+ if breaking_mark:
78
+ is_breaking = True
79
+ desc = match.group("desc").strip()
80
+ return ParsedCommit(
81
+ commit_hash=commit_hash,
82
+ subject=subject.strip(),
83
+ body=body.strip(),
84
+ commit_type=c_type,
85
+ scope=scope,
86
+ description=desc,
87
+ is_breaking=is_breaking,
88
+ )
89
+
90
+ # Fallback non-conventional commit
91
+ return ParsedCommit(
92
+ commit_hash=commit_hash,
93
+ subject=subject.strip(),
94
+ body=body.strip(),
95
+ commit_type="chore",
96
+ scope="",
97
+ description=subject.strip(),
98
+ is_breaking=is_breaking,
99
+ )
100
+
101
+
102
+ def get_commits_since_last_tag(
103
+ root_dir: Path,
104
+ tag_prefix: str = "v",
105
+ first_release: bool = False,
106
+ ) -> tuple[str | None, list[ParsedCommit]]:
107
+ """Get all commits since the last release tag.
108
+
109
+ Parameters
110
+ ----------
111
+ root_dir : Path
112
+ Repository root directory.
113
+ tag_prefix : str, optional
114
+ Tag prefix, by default "v".
115
+ first_release : bool, optional
116
+ If True, returns all commits from repository beginning.
117
+
118
+ Returns
119
+ -------
120
+ tuple[str | None, list[ParsedCommit]]
121
+ (latest_tag, list_of_parsed_commits)
122
+ """
123
+ latest_tag: str | None = None
124
+ if not first_release:
125
+ # Find latest tag matching pattern
126
+ tag_proc = run_process(
127
+ ["git", "describe", "--tags", "--abbrev=0", f"--match={tag_prefix}*"],
128
+ cwd=root_dir,
129
+ )
130
+ if tag_proc.passed and tag_proc.stdout.strip():
131
+ latest_tag = tag_proc.stdout.strip()
132
+ else:
133
+ # Try without prefix
134
+ tag_proc2 = run_process(
135
+ ["git", "describe", "--tags", "--abbrev=0"],
136
+ cwd=root_dir,
137
+ )
138
+ if tag_proc2.passed and tag_proc2.stdout.strip():
139
+ latest_tag = tag_proc2.stdout.strip()
140
+
141
+ # Log command with field separator (%x1f) and record separator (%x1e)
142
+ # %h: short hash, %s: subject, %b: body
143
+ log_range = f"{latest_tag}..HEAD" if latest_tag else "HEAD"
144
+ cmd = [
145
+ "git",
146
+ "log",
147
+ log_range,
148
+ "--format=%h%x1f%s%x1f%b%x1e",
149
+ ]
150
+ log_proc = run_process(cmd, cwd=root_dir)
151
+ if not log_proc.passed or not log_proc.stdout.strip():
152
+ return latest_tag, []
153
+
154
+ commits: list[ParsedCommit] = []
155
+ records = log_proc.stdout.split("\x1e")
156
+ for rec in records:
157
+ rec = rec.strip()
158
+ if not rec:
159
+ continue
160
+ parts = rec.split("\x1f")
161
+ h = parts[0].strip() if len(parts) > 0 else ""
162
+ s = parts[1].strip() if len(parts) > 1 else ""
163
+ b = parts[2].strip() if len(parts) > 2 else ""
164
+ if not s:
165
+ continue
166
+ # Skip release commits from appearing in changelog
167
+ if s.startswith("chore(release):") or s.startswith("release:"):
168
+ continue
169
+ commits.append(parse_conventional_commit(h, s, b))
170
+
171
+ return latest_tag, commits
172
+
173
+
174
+ def detect_semver_bump(commits: list[ParsedCommit]) -> str:
175
+ """Analyze conventional commits to determine SemVer increment.
176
+
177
+ Parameters
178
+ ----------
179
+ commits : list[ParsedCommit]
180
+ List of parsed commits since last release.
181
+
182
+ Returns
183
+ -------
184
+ str
185
+ 'major', 'minor', or 'patch'
186
+ """
187
+ if not commits:
188
+ return "patch"
189
+
190
+ has_breaking = any(c.is_breaking for c in commits)
191
+ if has_breaking:
192
+ return "major"
193
+
194
+ has_feat = any(c.commit_type == "feat" for c in commits)
195
+ if has_feat:
196
+ return "minor"
197
+
198
+ return "patch"
199
+
200
+
201
+ def calculate_next_version(
202
+ current_version: str,
203
+ bump_type: str,
204
+ prerelease: str | None = None,
205
+ ) -> str:
206
+ """Calculate the next SemVer version string.
207
+
208
+ Parameters
209
+ ----------
210
+ current_version : str
211
+ Current version (e.g. '0.1.0' or '1.2.3-beta.1').
212
+ bump_type : str
213
+ 'major', 'minor', 'patch', or an explicit version string ('1.0.0').
214
+ prerelease : str | None, optional
215
+ Optional prerelease tag (e.g. 'alpha', 'beta', 'rc').
216
+
217
+ Returns
218
+ -------
219
+ str
220
+ New incremented version string.
221
+ """
222
+ clean_curr = current_version.lstrip("v").strip()
223
+
224
+ # Check if bump_type is directly an explicit version string
225
+ try:
226
+ explicit_v = Version(bump_type)
227
+ return str(explicit_v)
228
+ except InvalidVersion:
229
+ pass
230
+
231
+ try:
232
+ v = Version(clean_curr)
233
+ major = v.major
234
+ minor = v.minor
235
+ micro = v.micro
236
+ except InvalidVersion:
237
+ # Fallback regex parsing
238
+ m = re.match(r"^(\d+)\.(\d+)\.(\d+)", clean_curr)
239
+ if m:
240
+ major, minor, micro = int(m.group(1)), int(m.group(2)), int(m.group(3))
241
+ else:
242
+ major, minor, micro = 0, 1, 0
243
+
244
+ bump = bump_type.lower()
245
+ if bump == "major":
246
+ major += 1
247
+ minor = 0
248
+ micro = 0
249
+ elif bump == "minor":
250
+ minor += 1
251
+ micro = 0
252
+ elif bump == "patch":
253
+ micro += 1
254
+
255
+ base_ver = f"{major}.{minor}.{micro}"
256
+ if prerelease:
257
+ return f"{base_ver}-{prerelease}.0"
258
+ return base_ver
259
+
260
+
261
+ def update_file_version(
262
+ filepath: Path,
263
+ new_version: str,
264
+ ) -> bool:
265
+ """Update version string in target file based on file type.
266
+
267
+ Parameters
268
+ ----------
269
+ filepath : Path
270
+ Path to file to update.
271
+ new_version : str
272
+ New SemVer version string.
273
+
274
+ Returns
275
+ -------
276
+ bool
277
+ True if updated successfully.
278
+ """
279
+ if not filepath.is_file():
280
+ return False
281
+
282
+ name = filepath.name.lower()
283
+
284
+ if name == "pyproject.toml":
285
+ content = filepath.read_text(encoding="utf-8")
286
+ doc = tomlkit.parse(content)
287
+ if "project" in doc and "version" in doc["project"]:
288
+ doc["project"]["version"] = new_version
289
+ filepath.write_text(tomlkit.dumps(doc), encoding="utf-8")
290
+ return True
291
+ # Fallback regex if tomlkit structure differs
292
+ subbed, count = re.subn(
293
+ r'^(version\s*=\s*")[^"]+(")',
294
+ rf"\g<1>{new_version}\g<2>",
295
+ content,
296
+ flags=re.MULTILINE,
297
+ )
298
+ if count > 0:
299
+ filepath.write_text(subbed, encoding="utf-8")
300
+ return True
301
+ return False
302
+
303
+ if name == "package.json":
304
+ try:
305
+ data = json.loads(filepath.read_text(encoding="utf-8"))
306
+ data["version"] = new_version
307
+ filepath.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
308
+ return True
309
+ except Exception:
310
+ return False
311
+
312
+ if name == "__init__.py":
313
+ content = filepath.read_text(encoding="utf-8")
314
+ subbed, count = re.subn(
315
+ r'(__version__\s*=\s*")[^"]+(")',
316
+ rf"\g<1>{new_version}\g<2>",
317
+ content,
318
+ )
319
+ if count > 0:
320
+ filepath.write_text(subbed, encoding="utf-8")
321
+ return True
322
+ # If __version__ not present, append it
323
+ if "__version__" not in content:
324
+ new_content = content.rstrip() + f'\n__version__ = "{new_version}"\n'
325
+ filepath.write_text(new_content, encoding="utf-8")
326
+ return True
327
+ return False
328
+
329
+ return False
330
+
331
+
332
+ def generate_changelog_section(
333
+ version: str,
334
+ date_str: str,
335
+ commits: list[ParsedCommit],
336
+ tag_prefix: str = "v",
337
+ ) -> str:
338
+ """Generate Markdown release notes section grouped by category.
339
+
340
+ Parameters
341
+ ----------
342
+ version : str
343
+ New release version (e.g. '0.2.0').
344
+ date_str : str
345
+ Date string (e.g. '2026-11-24').
346
+ commits : list[ParsedCommit]
347
+ List of parsed commits included in release.
348
+ tag_prefix : str, optional
349
+ Prefix for release tag.
350
+
351
+ Returns
352
+ -------
353
+ str
354
+ Formatted Markdown text for the section.
355
+ """
356
+ clean_ver = version.lstrip("v")
357
+ lines: list[str] = [
358
+ f"## [{clean_ver}] - {date_str}",
359
+ "",
360
+ ]
361
+
362
+ # Group commits by category
363
+ grouped: dict[str, list[ParsedCommit]] = {}
364
+ for c in commits:
365
+ grouped.setdefault(c.commit_type, []).append(c)
366
+
367
+ # Order categories according to CATEGORY_MAP
368
+ for c_type, title in CATEGORY_MAP.items():
369
+ type_commits = grouped.get(c_type, [])
370
+ if not type_commits:
371
+ continue
372
+
373
+ lines.append(f"### {title}")
374
+ for c in type_commits:
375
+ scope_prefix = f"**{c.scope}**: " if c.scope else ""
376
+ breaking_note = " **(BREAKING CHANGE)**" if c.is_breaking else ""
377
+ hash_suffix = f" ([{c.commit_hash}](commit/{c.commit_hash}))" if c.commit_hash else ""
378
+ lines.append(f"- {scope_prefix}{c.description}{breaking_note}{hash_suffix}")
379
+ lines.append("")
380
+
381
+ return "\n".join(lines).strip()
382
+
383
+
384
+ def prepend_to_changelog(changelog_path: Path, new_section: str) -> None:
385
+ """Insert new release section at the top of CHANGELOG.md under title.
386
+
387
+ Parameters
388
+ ----------
389
+ changelog_path : Path
390
+ Path to CHANGELOG.md.
391
+ new_section : str
392
+ Formatted markdown section to insert.
393
+ """
394
+ title = "# Changelog\n\nAll notable changes to this project will be documented in this file.\n"
395
+ if not changelog_path.exists():
396
+ changelog_path.write_text(f"{title}\n{new_section}\n", encoding="utf-8")
397
+ return
398
+
399
+ existing = changelog_path.read_text(encoding="utf-8")
400
+ # Check if starts with a markdown H1 title
401
+ title_match = re.match(r"^(#\s+[^\n]+\n+)", existing)
402
+ if title_match:
403
+ header = title_match.group(1)
404
+ rest = existing[title_match.end() :].lstrip()
405
+ updated = f"{header}\n{new_section}\n\n{rest}"
406
+ else:
407
+ updated = f"{title}\n{new_section}\n\n{existing.lstrip()}"
408
+
409
+ changelog_path.write_text(updated, encoding="utf-8")
410
+
411
+
412
+ def run_bump(
413
+ root_dir: Path,
414
+ release_as: str | None = None,
415
+ prerelease: str | None = None,
416
+ first_release: bool = False,
417
+ dry_run: bool = False,
418
+ no_commit: bool = False,
419
+ no_tag: bool = False,
420
+ tag_prefix: str = "v",
421
+ ) -> tuple[int, str]:
422
+ """Execute complete native SemVer bump and changelog generation.
423
+
424
+ Parameters
425
+ ----------
426
+ root_dir : Path
427
+ Project root directory.
428
+ release_as : str | None, optional
429
+ 'patch', 'minor', 'major', or specific version ('1.2.0').
430
+ prerelease : str | None, optional
431
+ Prerelease identifier ('alpha', 'beta', 'rc').
432
+ first_release : bool, optional
433
+ Whether this is the first release.
434
+ dry_run : bool, optional
435
+ Preview without writing files or making Git commits.
436
+ no_commit : bool, optional
437
+ Skip creating Git release commit.
438
+ no_tag : bool, optional
439
+ Skip creating Git release tag.
440
+ tag_prefix : str, optional
441
+ Tag prefix, by default 'v'.
442
+
443
+ Returns
444
+ -------
445
+ tuple[int, str]
446
+ (exit_code, new_version)
447
+ """
448
+ from project_forge.config import load_config
449
+ from project_forge.project import read_project_metadata
450
+
451
+ cfg = load_config(root_dir)
452
+ metadata = read_project_metadata(root_dir)
453
+ current_version = metadata.get("version", "0.1.0")
454
+
455
+ _last_tag, commits = get_commits_since_last_tag(
456
+ root_dir,
457
+ tag_prefix=tag_prefix,
458
+ first_release=first_release,
459
+ )
460
+
461
+ # Determine bump type
462
+ bump_type = release_as or detect_semver_bump(commits)
463
+ new_version = calculate_next_version(current_version, bump_type, prerelease)
464
+
465
+ today = datetime.now().strftime("%Y-%m-%d")
466
+ changelog_section = generate_changelog_section(
467
+ version=new_version,
468
+ date_str=today,
469
+ commits=commits,
470
+ tag_prefix=tag_prefix,
471
+ )
472
+
473
+ target_files: list[Path] = [
474
+ root_dir / "pyproject.toml",
475
+ ]
476
+ # Check for __init__.py files in src/
477
+ for init_file in (root_dir / "src").rglob("__init__.py"):
478
+ target_files.append(init_file)
479
+ if (root_dir / "package.json").exists():
480
+ target_files.append(root_dir / "package.json")
481
+
482
+ changelog_path = root_dir / cfg.bump.changelog_file
483
+
484
+ if dry_run:
485
+ return 0, new_version
486
+
487
+ # Update files
488
+ for f in target_files:
489
+ update_file_version(f, new_version)
490
+
491
+ # Prepend changelog
492
+ prepend_to_changelog(changelog_path, changelog_section)
493
+
494
+ # Git stage and commit
495
+ if not no_commit:
496
+ paths_to_stage = [str(f.relative_to(root_dir)) for f in target_files if f.exists()]
497
+ if changelog_path.exists():
498
+ paths_to_stage.append(str(changelog_path.relative_to(root_dir)))
499
+
500
+ run_process(["git", "add"] + paths_to_stage, cwd=root_dir)
501
+ commit_msg = f"chore(release): {tag_prefix}{new_version}"
502
+ commit_res = run_process(["git", "commit", "-m", commit_msg], cwd=root_dir)
503
+ if not commit_res.passed:
504
+ return 1, new_version
505
+
506
+ # Git tag
507
+ if not no_tag:
508
+ tag_name = f"{tag_prefix}{new_version}"
509
+ tag_msg = f"chore(release): {tag_name}"
510
+ tag_res = run_process(["git", "tag", "-a", tag_name, "-m", tag_msg], cwd=root_dir)
511
+ if not tag_res.passed:
512
+ return 1, new_version
513
+
514
+ return 0, new_version