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,594 @@
1
+ """Automated Conventional Commit tooling with repository-neutral scope inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+ from typing import cast
9
+
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+ from rich.prompt import Prompt
13
+ from rich.syntax import Syntax
14
+ from rich.table import Table
15
+
16
+ from project_forge.process import run_process
17
+
18
+ console = Console()
19
+
20
+
21
+ @dataclass
22
+ class ChangedFile:
23
+ """Represents an uncommitted file change in the repository."""
24
+
25
+ status: str
26
+ filepath: str
27
+ orig_path: str | None = None
28
+
29
+ @property
30
+ def display_path(self) -> str:
31
+ """Formatted path for user presentation and logs."""
32
+ if self.orig_path:
33
+ return f"{self.orig_path} -> {self.filepath}"
34
+ return self.filepath
35
+
36
+
37
+ @dataclass
38
+ class CommitGroup:
39
+ """Represents a cohesive group of files committed atomically together."""
40
+
41
+ message: str
42
+ files: list[ChangedFile] = field(default_factory=lambda: cast(list[ChangedFile], []))
43
+
44
+ @property
45
+ def display_summary(self) -> str:
46
+ """Formatted summary of files in this commit group."""
47
+ if not self.files:
48
+ return "(no files)"
49
+ if len(self.files) == 1:
50
+ return self.files[0].display_path
51
+ paths = [f.filepath.replace("\\", "/") for f in self.files]
52
+ sample = ", ".join(Path(p).name for p in paths[:3])
53
+ suffix = f", ... (+{len(paths) - 3} more)" if len(paths) > 3 else ""
54
+ return f"{len(self.files)} files ({sample}{suffix})"
55
+
56
+
57
+ def format_commit_header(type_scope: str, desc: str, max_length: int = 72) -> str:
58
+ """Format and guarantee commit header is strictly within max_length characters."""
59
+ prefix = f"{type_scope}: "
60
+ max_desc_len = max_length - len(prefix)
61
+ if len(desc) > max_desc_len:
62
+ desc = desc[:max_desc_len].rstrip()
63
+ return f"{prefix}{desc}"
64
+
65
+
66
+ def infer_scope(
67
+ filepath: str,
68
+ source_roots: list[str] | None = None,
69
+ scope_overrides: dict[str, str] | None = None,
70
+ ) -> str:
71
+ """Infer a conventional commit scope based on directory path and configured source roots.
72
+
73
+ Parameters
74
+ ----------
75
+ filepath : str
76
+ Relative file path.
77
+ source_roots : list[str] | None, optional
78
+ Configured source root directories (e.g. ['src']).
79
+ scope_overrides : dict[str, str] | None, optional
80
+ Custom scope overrides mapping.
81
+
82
+ Returns
83
+ -------
84
+ str
85
+ Inferred scope string.
86
+ """
87
+ norm = filepath.replace("\\", "/")
88
+ if scope_overrides and norm in scope_overrides:
89
+ return scope_overrides[norm]
90
+
91
+ roots = source_roots or ["src"]
92
+ for src_root in roots:
93
+ norm_src = src_root.rstrip("/") + "/"
94
+ if norm.startswith(norm_src):
95
+ rel = norm[len(norm_src) :]
96
+ parts = rel.split("/")
97
+ if len(parts) >= 2:
98
+ # e.g. project_forge/cli.py -> cli
99
+ # or project_forge/domain/entity.py -> domain
100
+ second_part = parts[1]
101
+ stem = Path(second_part).stem
102
+ return stem[:15].rstrip("_")
103
+ return Path(parts[0]).stem[:15].rstrip("_")
104
+
105
+ if norm.startswith("tests/"):
106
+ stem = Path(norm).stem.replace("test_", "").rstrip("_")
107
+ return stem[:15].rstrip("_")
108
+ if norm.startswith(".githooks/"):
109
+ return "hooks"
110
+ if norm.startswith(".github/"):
111
+ return "ci"
112
+ if norm.startswith(".plan/"):
113
+ return "planning"
114
+ if norm.endswith(".md"):
115
+ return Path(norm).stem[:15].rstrip("_")
116
+
117
+ return Path(norm).stem[:15].rstrip("_")
118
+
119
+
120
+ def infer_commit_message(
121
+ file_item: ChangedFile,
122
+ source_roots: list[str] | None = None,
123
+ scope_overrides: dict[str, str] | None = None,
124
+ max_length: int = 72,
125
+ ) -> str:
126
+ """Infer a Conventional Commit message based on path heuristics."""
127
+ norm = file_item.filepath.replace("\\", "/")
128
+ scope = infer_scope(norm, source_roots, scope_overrides)
129
+
130
+ # Deletions
131
+ if file_item.status == "D":
132
+ if norm.endswith("__init__.py"):
133
+ pkg_parts = norm.split("/")
134
+ pkg_name = pkg_parts[-2] if len(pkg_parts) >= 2 else "root"
135
+ return format_commit_header(
136
+ f"refactor({pkg_name[:15].rstrip('_')})", "remove package facade", max_length
137
+ )
138
+ stem = Path(norm).stem
139
+ return format_commit_header(f"refactor({scope})", f"remove deprecated {stem}", max_length)
140
+
141
+ # Renames
142
+ if file_item.status == "R" and file_item.orig_path:
143
+ norm_orig = file_item.orig_path.replace("\\", "/")
144
+ stem = Path(norm).stem
145
+ orig_stem = Path(norm_orig).stem
146
+ if orig_stem == stem:
147
+ dest_parts = norm.split("/")
148
+ dest_folder = dest_parts[-2] if len(dest_parts) >= 2 else "root"
149
+ return format_commit_header(
150
+ f"refactor({scope})", f"relocate {stem} to {dest_folder}", max_length
151
+ )
152
+ return format_commit_header(
153
+ f"refactor({scope})", f"rename {orig_stem} to {stem}", max_length
154
+ )
155
+
156
+ # Package __init__.py exports
157
+ if norm.endswith("__init__.py"):
158
+ pkg_parts = norm.split("/")
159
+ pkg_name = pkg_parts[-2] if len(pkg_parts) >= 2 else "root"
160
+ return format_commit_header(
161
+ f"refactor({pkg_name[:15].rstrip('_')})", "update package exports", max_length
162
+ )
163
+
164
+ # Tests
165
+ if norm.startswith("tests/"):
166
+ return format_commit_header(f"test({scope})", "update test suite", max_length)
167
+
168
+ # CI & Tooling
169
+ if norm.startswith(".github/"):
170
+ return format_commit_header("ci(github)", "update workflow configuration", max_length)
171
+ if norm.startswith(".githooks/"):
172
+ return format_commit_header("ci(hooks)", "update git hook", max_length)
173
+ if norm in {
174
+ "ruff.toml",
175
+ "mypy.ini",
176
+ "pyrightconfig.json",
177
+ "pyrefly.toml",
178
+ "uv.toml",
179
+ ".pylintrc",
180
+ "poe_tasks.toml",
181
+ }:
182
+ tool_name = Path(norm).stem.lstrip(".").split(".")[0].rstrip("_")
183
+ return format_commit_header(f"ci({tool_name})", "update tool configuration", max_length)
184
+ if norm in {"pyproject.toml", "package.json", "uv.lock"}:
185
+ tool_name = Path(norm).stem.rstrip("_")
186
+ return format_commit_header(
187
+ f"chore({tool_name})", "update project configuration", max_length
188
+ )
189
+
190
+ # Source code
191
+ roots = source_roots or ["src"]
192
+ for src_root in roots:
193
+ if norm.startswith(src_root.rstrip("/") + "/"):
194
+ stem = Path(norm).stem
195
+ action = "add" if file_item.status in ("?", "??", "A") else "update"
196
+ return format_commit_header(f"refactor({scope})", f"{action} {stem}", max_length)
197
+
198
+ # Documentation
199
+ if norm.startswith(".plan/") or norm.startswith(".planning/"):
200
+ return format_commit_header("docs(planning)", "update plan and progress", max_length)
201
+ if norm.endswith(".md"):
202
+ stem = Path(norm).stem[:15].rstrip("_")
203
+ return format_commit_header(f"docs({stem})", "update documentation", max_length)
204
+
205
+ # Generic fallback
206
+ stem = Path(norm).stem.rstrip("_")
207
+ action = "add" if file_item.status in ("?", "??", "A") else "update"
208
+ return format_commit_header("chore", f"{action} {stem}", max_length)
209
+
210
+
211
+ def load_custom_overrides(root_dir: Path, cli_map_path: str | None = None) -> dict[str, list[str]]:
212
+ """Load Message-to-Paths commit override mappings from JSON."""
213
+ candidates: list[Path] = []
214
+ if cli_map_path:
215
+ candidates.append(Path(cli_map_path))
216
+ candidates.append(root_dir / ".commit_overrides.json")
217
+ candidates.append(root_dir / ".commit_map.json")
218
+
219
+ for p in candidates:
220
+ if p.is_file():
221
+ try:
222
+ content = p.read_text(encoding="utf-8")
223
+ raw_data: object = json.loads(content)
224
+ if isinstance(raw_data, dict):
225
+ raw_dict = cast(dict[object, object], raw_data)
226
+ result: dict[str, list[str]] = {}
227
+ for k, v in raw_dict.items():
228
+ msg_or_path = str(k).strip()
229
+ if isinstance(v, list):
230
+ raw_list = cast(list[object], v)
231
+ result[msg_or_path] = [
232
+ str(item).replace("\\", "/").strip() for item in raw_list
233
+ ]
234
+ elif isinstance(v, str):
235
+ path = msg_or_path.replace("\\", "/").strip()
236
+ result.setdefault(str(v).strip(), []).append(path)
237
+ return result
238
+ except Exception:
239
+ pass
240
+ return {}
241
+
242
+
243
+ def get_changed_files(root_dir: Path) -> list[ChangedFile]:
244
+ """Query git status for all uncommitted changes using temporary staging for renames."""
245
+ # 1. Temporarily stage everything to trigger git rename heuristics
246
+ run_process(["git", "add", "-A"], cwd=root_dir)
247
+
248
+ # 2. Query porcelain status with renames
249
+ proc = run_process(["git", "status", "-s", "-uall", "--find-renames"], cwd=root_dir)
250
+
251
+ # 3. Immediately unstage everything so index is clean
252
+ run_process(["git", "restore", "--staged", "."], cwd=root_dir)
253
+
254
+ if not proc.passed or not proc.stdout.strip():
255
+ return []
256
+
257
+ results: list[ChangedFile] = []
258
+ for line in proc.stdout.splitlines():
259
+ line = line.strip()
260
+ if not line:
261
+ continue
262
+ status_part = line[:2].strip()
263
+ file_part = line[2:].strip().strip('"')
264
+
265
+ if " -> " in file_part:
266
+ orig, target = file_part.split(" -> ", 1)
267
+ results.append(
268
+ ChangedFile(
269
+ status="R",
270
+ filepath=target.strip().strip('"'),
271
+ orig_path=orig.strip().strip('"'),
272
+ )
273
+ )
274
+ else:
275
+ results.append(
276
+ ChangedFile(
277
+ status=status_part,
278
+ filepath=file_part,
279
+ )
280
+ )
281
+ return results
282
+
283
+
284
+ def build_commit_groups(
285
+ files: list[ChangedFile],
286
+ overrides: dict[str, list[str]],
287
+ source_roots: list[str] | None = None,
288
+ scope_overrides: dict[str, str] | None = None,
289
+ only_mapped: bool = False,
290
+ max_length: int = 72,
291
+ ) -> list[CommitGroup]:
292
+ """Group uncommitted files into atomic CommitGroup objects."""
293
+ file_by_path: dict[str, ChangedFile] = {}
294
+ for f in files:
295
+ norm_target = f.filepath.replace("\\", "/")
296
+ file_by_path[norm_target] = f
297
+ if f.orig_path:
298
+ norm_orig = f.orig_path.replace("\\", "/")
299
+ file_by_path[norm_orig] = f
300
+
301
+ groups: list[CommitGroup] = []
302
+ accounted_filepaths: set[str] = set()
303
+
304
+ # 1. Groups explicitly defined in overrides
305
+ for msg, path_list in overrides.items():
306
+ group_files: list[ChangedFile] = []
307
+ for p in path_list:
308
+ norm_p = p.replace("\\", "/")
309
+ if norm_p in file_by_path:
310
+ f_obj = file_by_path[norm_p]
311
+ if f_obj.filepath not in accounted_filepaths:
312
+ group_files.append(f_obj)
313
+ accounted_filepaths.add(f_obj.filepath)
314
+
315
+ if group_files:
316
+ groups.append(CommitGroup(message=msg, files=group_files))
317
+
318
+ # 2. Inferred groups for remaining files
319
+ inferred_groups: dict[str, list[ChangedFile]] = {}
320
+ for f in files:
321
+ if f.filepath not in accounted_filepaths:
322
+ if only_mapped:
323
+ continue
324
+ inf_msg = infer_commit_message(
325
+ f, source_roots=source_roots, scope_overrides=scope_overrides, max_length=max_length
326
+ )
327
+ inferred_groups.setdefault(inf_msg, []).append(f)
328
+
329
+ for inf_msg, inf_files in inferred_groups.items():
330
+ groups.append(CommitGroup(message=inf_msg, files=inf_files))
331
+
332
+ return groups
333
+
334
+
335
+ def show_group_diff(group: CommitGroup, root_dir: Path) -> None:
336
+ """Display diff summary for all files in a commit group."""
337
+ paths_to_diff: list[str] = []
338
+ for f in group.files:
339
+ if f.status == "R" and f.orig_path:
340
+ paths_to_diff.append(f.orig_path.replace("\\", "/"))
341
+ paths_to_diff.append(f.filepath.replace("\\", "/"))
342
+
343
+ proc = run_process(["git", "diff", "HEAD", "--"] + paths_to_diff, cwd=root_dir)
344
+ diff_text = proc.stdout
345
+ if not diff_text.strip():
346
+ diff_text = "(No diff detected or binary content)"
347
+
348
+ syntax = Syntax(diff_text[:4000], "diff", theme="monokai", line_numbers=True)
349
+ console.print(Panel(syntax, title=f"Group Diff: {group.message}", border_style="cyan"))
350
+
351
+
352
+ def prompt_interactive_group(
353
+ group: CommitGroup, index: int, total: int, root_dir: Path
354
+ ) -> str | None:
355
+ """Interactive wizard to approve, customize, or skip a commit group."""
356
+ while True:
357
+ file_lines = "\n".join(f" • [{f.status}] {f.display_path}" for f in group.files[:8])
358
+ if len(group.files) > 8:
359
+ file_lines += f"\n • ... (+{len(group.files) - 8} more files)"
360
+
361
+ console.print(
362
+ Panel(
363
+ f"[bold cyan]Commit Group [{index}/{total}]:[/bold cyan]\n"
364
+ f"[dim]Files ({len(group.files)}):[/dim]\n{file_lines}\n\n"
365
+ f"[dim]Proposed Message:[/dim] [bold green]{group.message}[/bold green] [dim]({len(group.message)}/72 chars)[/dim]",
366
+ title="[bold yellow]Commitlint Group Wizard[/bold yellow]",
367
+ border_style="yellow",
368
+ )
369
+ )
370
+
371
+ console.print("[bold]Choices:[/bold]")
372
+ console.print(" [bold cyan]1[/bold cyan] -> Accept proposed message")
373
+ console.print(" [bold cyan]2[/bold cyan] -> Enter custom commit message")
374
+ console.print(" [bold cyan]3[/bold cyan] -> View group diff")
375
+ console.print(" [bold cyan]4[/bold cyan] -> Skip this group")
376
+ console.print(" [bold red]q[/bold red] -> Quit / Abort\n")
377
+
378
+ choice = Prompt.ask(
379
+ "[bold]Select option[/bold]", choices=["1", "2", "3", "4", "q"], default="1"
380
+ )
381
+
382
+ if choice == "1":
383
+ return group.message
384
+
385
+ if choice == "2":
386
+ while True:
387
+ custom_msg = Prompt.ask("Enter full commit message").strip()
388
+ if not custom_msg:
389
+ console.print("[red]Commit message cannot be empty.[/red]")
390
+ continue
391
+ if len(custom_msg) > 72:
392
+ console.print(
393
+ f"[red]Message exceeds 72 characters ({len(custom_msg)} chars).[/red]"
394
+ )
395
+ continue
396
+ return custom_msg
397
+
398
+ if choice == "3":
399
+ show_group_diff(group, root_dir=root_dir)
400
+ continue
401
+
402
+ if choice == "4":
403
+ console.print(f"[dim]Skipped group '{group.message}'[/dim]")
404
+ return None
405
+
406
+ if choice.lower() == "q":
407
+ console.print("[red]Aborted by user.[/red]")
408
+ return "__ABORT__"
409
+
410
+
411
+ def run_git_commit_group(
412
+ group: CommitGroup,
413
+ root_dir: Path,
414
+ dry_run: bool = False,
415
+ no_verify: bool = False,
416
+ ) -> bool:
417
+ """Stage all files in a group and create a single atomic git commit."""
418
+ if len(group.message) > 72:
419
+ console.print(
420
+ f"[bold red]ERROR:[/bold red] Commit message exceeds 72 characters: '{group.message}'"
421
+ )
422
+ return False
423
+
424
+ paths_to_stage: list[str] = []
425
+ for f in group.files:
426
+ if f.status == "R" and f.orig_path:
427
+ paths_to_stage.append(f.orig_path.replace("\\", "/"))
428
+ paths_to_stage.append(f.filepath.replace("\\", "/"))
429
+
430
+ if dry_run:
431
+ verify_flag = " --no-verify" if no_verify else ""
432
+ console.print(
433
+ f"[dim][DRY-RUN][/dim] git add -A -- {' '.join(paths_to_stage[:3])}{' ...' if len(paths_to_stage) > 3 else ''}"
434
+ )
435
+ console.print(
436
+ f'[dim][DRY-RUN][/dim] git commit -m "{group.message}"{verify_flag} [dim]({len(group.files)} files)[/dim]'
437
+ )
438
+ return True
439
+
440
+ # 1. Clean staging index
441
+ run_process(["git", "restore", "--staged", "."], cwd=root_dir)
442
+
443
+ # 2. Stage files
444
+ add_proc = run_process(["git", "add", "-A", "--"] + paths_to_stage, cwd=root_dir)
445
+ if not add_proc.passed:
446
+ console.print(
447
+ Panel(
448
+ add_proc.combined_output,
449
+ title="[bold red]git add FAILED[/bold red]",
450
+ border_style="red",
451
+ )
452
+ )
453
+ return False
454
+
455
+ # 3. Check staged changes
456
+ staged_proc = run_process(["git", "diff", "--cached", "--name-only"], cwd=root_dir)
457
+ if not staged_proc.stdout.strip():
458
+ console.print(
459
+ f"[yellow]Skipping group '{group.message}': no staged changes detected.[/yellow]"
460
+ )
461
+ return True
462
+
463
+ # 4. Commit
464
+ cmd = ["git", "commit", "-m", group.message]
465
+ if no_verify:
466
+ cmd.append("--no-verify")
467
+
468
+ commit_proc = run_process(cmd, cwd=root_dir)
469
+ if not commit_proc.passed:
470
+ console.print(
471
+ Panel(
472
+ commit_proc.combined_output,
473
+ title=f"[bold red]FAILED commit: {group.message}[/bold red]",
474
+ border_style="red",
475
+ )
476
+ )
477
+ run_process(["git", "restore", "--staged", "."], cwd=root_dir)
478
+ return False
479
+
480
+ console.print(
481
+ f'[bold green][OK][/bold green] Committed ({len(group.files)} files): "[cyan]{group.message}[/cyan]"'
482
+ )
483
+ return True
484
+
485
+
486
+ def execute_commit_flow(
487
+ root_dir: Path | None = None,
488
+ dry_run: bool = False,
489
+ interactive: bool = False,
490
+ run: bool = False,
491
+ map_path: str | None = None,
492
+ only_mapped: bool = False,
493
+ no_verify: bool = False,
494
+ skip_audit: bool = False,
495
+ ) -> int:
496
+ """Execute complete automated grouped Conventional Commits flow."""
497
+ if root_dir is None:
498
+ from project_forge.project import find_project_root
499
+
500
+ root_dir = find_project_root()
501
+
502
+ from project_forge.config import load_config
503
+
504
+ cfg = load_config(root_dir)
505
+ custom_overrides = load_custom_overrides(root_dir, map_path)
506
+
507
+ is_dry_run = dry_run or (not interactive and not run)
508
+
509
+ files = get_changed_files(root_dir)
510
+ if not files:
511
+ console.print("[green]Working tree is completely clean. Nothing to commit.[/green]")
512
+ return 0
513
+
514
+ groups = build_commit_groups(
515
+ files,
516
+ custom_overrides,
517
+ source_roots=cfg.source,
518
+ scope_overrides=cfg.commits.scope_overrides,
519
+ only_mapped=only_mapped,
520
+ max_length=cfg.commits.header_max_length,
521
+ )
522
+ if not groups:
523
+ console.print("[yellow]No changed files match the requested commit criteria.[/yellow]")
524
+ return 0
525
+
526
+ mode_label = (
527
+ "INTERACTIVE COMMIT WIZARD"
528
+ if interactive
529
+ else ("DRY-RUN PREVIEW" if is_dry_run else "EXECUTING GROUPED COMMITS")
530
+ )
531
+ total_files_in_groups = sum(len(g.files) for g in groups)
532
+ console.print(
533
+ f"\n--- [bold cyan]{mode_label}[/bold cyan] ({len(groups)} groups, {total_files_in_groups} files) ---\n"
534
+ )
535
+
536
+ table = Table(title="Planned Commit Groups", show_header=True, header_style="bold magenta")
537
+ table.add_column("#", style="dim", width=4)
538
+ table.add_column("Files", justify="right", style="cyan", width=6)
539
+ table.add_column("Commit Message", style="bold green")
540
+ table.add_column("Scope Summary", style="white")
541
+
542
+ for i, g in enumerate(groups, 1):
543
+ table.add_row(str(i), str(len(g.files)), g.message, g.display_summary)
544
+ console.print(table)
545
+ console.print("")
546
+
547
+ if is_dry_run:
548
+ console.print("[dim]To execute commits, run: pforge commit --run[/dim]")
549
+ console.print("[dim]Or run interactively: pforge commit -i[/dim]")
550
+ return 0
551
+
552
+ # Upfront quality gate
553
+ bypass_hooks = no_verify
554
+ if not skip_audit and not no_verify:
555
+ from project_forge.quality import run_quality_gate
556
+
557
+ console.print("\n[bold cyan]Running Upfront Fast Quality Gate Verification...[/bold cyan]")
558
+ exit_code = run_quality_gate(tier="fast", export="cli", root_dir=root_dir)
559
+ if exit_code != 0:
560
+ console.print("[bold red]Upfront Quality Gate Failed — Commits Aborted.[/bold red]")
561
+ return 1
562
+ console.print("[bold green]✓ Upfront Quality Gate Passed Cleanly![/bold green]\n")
563
+ bypass_hooks = True
564
+
565
+ success_count = 0
566
+ fail_count = 0
567
+ skipped_count = 0
568
+
569
+ try:
570
+ for idx, group in enumerate(groups, 1):
571
+ if interactive:
572
+ chosen_msg = prompt_interactive_group(group, idx, len(groups), root_dir=root_dir)
573
+ if chosen_msg == "__ABORT__":
574
+ break
575
+ if chosen_msg is None:
576
+ skipped_count += 1
577
+ continue
578
+ group.message = chosen_msg
579
+
580
+ ok = run_git_commit_group(
581
+ group, root_dir=root_dir, dry_run=False, no_verify=bypass_hooks
582
+ )
583
+ if ok:
584
+ success_count += 1
585
+ else:
586
+ fail_count += 1
587
+ break
588
+ finally:
589
+ run_process(["git", "restore", "--staged", "."], cwd=root_dir)
590
+
591
+ console.print(
592
+ f"\n[bold]Summary:[/bold] {success_count} groups committed, {fail_count} failed, {skipped_count} skipped."
593
+ )
594
+ return 0 if fail_count == 0 else 1
@@ -0,0 +1,101 @@
1
+ """Configuration schema and loader for Project Forge."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from pydantic import BaseModel, Field
10
+
11
+
12
+ class GitConfig(BaseModel):
13
+ """Git branch configuration."""
14
+
15
+ development_branch: str = "dev"
16
+ default_branch: str = "main"
17
+
18
+
19
+ class QualityConfig(BaseModel):
20
+ """Quality gate engines and tiers configuration."""
21
+
22
+ fast: list[str] = Field(default_factory=lambda: ["ruff-check", "ruff-format", "mypy"])
23
+ full: list[str] = Field(
24
+ default_factory=lambda: ["ruff-check", "ruff-format", "mypy", "pyright", "pytest"]
25
+ )
26
+ extra_paths: list[str] = Field(default_factory=list)
27
+
28
+
29
+ class CommitsConfig(BaseModel):
30
+ """Conventional commit behavior configuration."""
31
+
32
+ header_max_length: int = 72
33
+ overrides_file: str = ".commit_overrides.json"
34
+ scope_overrides: dict[str, str] = Field(default_factory=dict)
35
+
36
+
37
+ class DocsConfig(BaseModel):
38
+ """Documentation auditor policies."""
39
+
40
+ require_module_docstrings: bool = True
41
+ require_package_ownership: bool = False
42
+ require_init_docs: bool = False
43
+ include_private: bool = False
44
+
45
+
46
+ class BumpConfig(BaseModel):
47
+ """Version bumper and changelog generator configuration."""
48
+
49
+ tag_prefix: str = "v"
50
+ files: list[str] = Field(default_factory=lambda: ["pyproject.toml", "src/**/__init__.py"])
51
+ commit_all: bool = True
52
+ changelog_file: str = "CHANGELOG.md"
53
+
54
+
55
+ class ProjectForgeConfig(BaseModel):
56
+ """Top-level configuration loaded from [tool.project-forge]."""
57
+
58
+ source: list[str] = Field(default_factory=lambda: ["src"])
59
+ tests: list[str] = Field(default_factory=lambda: ["tests"])
60
+ changelog: str = "CHANGELOG.md"
61
+ git: GitConfig = Field(default_factory=GitConfig)
62
+ quality: QualityConfig = Field(default_factory=QualityConfig)
63
+ commits: CommitsConfig = Field(default_factory=CommitsConfig)
64
+ docs: DocsConfig = Field(default_factory=DocsConfig)
65
+ bump: BumpConfig = Field(default_factory=BumpConfig)
66
+
67
+
68
+ def load_config(root_dir: Path | None = None) -> ProjectForgeConfig:
69
+ """Load configuration from pyproject.toml [tool.project-forge] section.
70
+
71
+ If pyproject.toml does not exist or has no [tool.project-forge] section,
72
+ safe defaults are returned.
73
+
74
+ Parameters
75
+ ----------
76
+ root_dir : Path | None, optional
77
+ Project root directory, by default None (searched from cwd).
78
+
79
+ Returns
80
+ -------
81
+ ProjectForgeConfig
82
+ Loaded and validated configuration model.
83
+ """
84
+ if root_dir is None:
85
+ from project_forge.project import find_project_root
86
+
87
+ root_dir = find_project_root()
88
+
89
+ pyproject_file = root_dir / "pyproject.toml"
90
+ if not pyproject_file.is_file():
91
+ return ProjectForgeConfig()
92
+
93
+ try:
94
+ content = pyproject_file.read_bytes()
95
+ data: dict[str, Any] = tomllib.loads(content.decode("utf-8"))
96
+ tool_section = data.get("tool", {}).get("project-forge", {})
97
+ return ProjectForgeConfig.model_validate(tool_section)
98
+ except Exception as exc:
99
+ raise ValueError(
100
+ f"Failed to parse [tool.project-forge] in {pyproject_file}: {exc}"
101
+ ) from exc