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,132 @@
1
+ """Diagnostic environment inspector validating repository tooling and state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from pathlib import Path
7
+
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+
11
+ from project_forge.changelog import validate_changelog
12
+ from project_forge.config import load_config
13
+ from project_forge.hooks import get_hooks_status
14
+ from project_forge.process import run_process
15
+ from project_forge.project import find_project_root, get_git_branch, read_project_metadata
16
+
17
+ console = Console()
18
+
19
+
20
+ def run_doctor(root_dir: Path | None = None) -> int:
21
+ """Perform read-only diagnostic checks across the repository and tools."""
22
+ if root_dir is None:
23
+ root_dir = find_project_root()
24
+
25
+ cfg = load_config(root_dir)
26
+ metadata = read_project_metadata(root_dir)
27
+
28
+ table = Table(title="Project Forge Doctor Diagnostics", header_style="bold magenta")
29
+ table.add_column("Category", style="cyan")
30
+ table.add_column("Component", style="bold")
31
+ table.add_column("Status", justify="center")
32
+ table.add_column("Details")
33
+
34
+ all_ok = True
35
+
36
+ # 1. Project & Repository
37
+ has_git = (root_dir / ".git").is_dir()
38
+ table.add_row(
39
+ "Repository",
40
+ "Git Repository",
41
+ "[bold green]PASS[/bold green]" if has_git else "[bold red]FAIL[/bold red]",
42
+ f"Root: {root_dir}",
43
+ )
44
+ if not has_git:
45
+ all_ok = False
46
+
47
+ branch = get_git_branch(root_dir)
48
+ table.add_row(
49
+ "Repository",
50
+ "Current Branch",
51
+ "[bold green]PASS[/bold green]"
52
+ if branch != "unknown"
53
+ else "[bold yellow]WARN[/bold yellow]",
54
+ branch,
55
+ )
56
+
57
+ pyproject_exists = (root_dir / "pyproject.toml").is_file()
58
+ table.add_row(
59
+ "Configuration",
60
+ "pyproject.toml",
61
+ "[bold green]PASS[/bold green]" if pyproject_exists else "[bold red]FAIL[/bold red]",
62
+ f"{metadata.get('name')} v{metadata.get('version')}",
63
+ )
64
+ if not pyproject_exists:
65
+ all_ok = False
66
+
67
+ # Configured paths
68
+ for p_str in cfg.source:
69
+ exists = (root_dir / p_str).exists()
70
+ table.add_row(
71
+ "Configuration",
72
+ f"Source path: {p_str}",
73
+ "[bold green]PASS[/bold green]" if exists else "[bold red]FAIL[/bold red]",
74
+ str((root_dir / p_str).resolve()),
75
+ )
76
+ if not exists:
77
+ all_ok = False
78
+
79
+ for p_str in cfg.tests:
80
+ exists = (root_dir / p_str).exists()
81
+ table.add_row(
82
+ "Configuration",
83
+ f"Test path: {p_str}",
84
+ "[bold green]PASS[/bold green]" if exists else "[bold yellow]WARN[/bold yellow]",
85
+ str((root_dir / p_str).resolve()),
86
+ )
87
+
88
+ # 2. External Executables
89
+ tools_to_check = ["git", "uv", "gh", "ruff", "mypy", "pyright", "pytest"]
90
+ for tool in tools_to_check:
91
+ found = shutil.which(tool) is not None
92
+ if not found:
93
+ # Check if available via uv run
94
+ proc = run_process(["uv", "run", tool, "--version"], cwd=root_dir)
95
+ found = proc.passed
96
+
97
+ status_str = "[bold green]PASS[/bold green]" if found else "[bold yellow]WARN[/bold yellow]"
98
+ details_str = "Available" if found else "Not found in PATH or venv"
99
+ table.add_row("External Tools", tool, status_str, details_str)
100
+
101
+ # GitHub CLI Auth Check
102
+ gh_auth = run_process(["gh", "auth", "status"], cwd=root_dir)
103
+ table.add_row(
104
+ "GitHub CLI",
105
+ "gh auth status",
106
+ "[bold green]PASS[/bold green]" if gh_auth.passed else "[bold yellow]WARN[/bold yellow]",
107
+ "Authenticated" if gh_auth.passed else "Not logged in (run 'gh auth login')",
108
+ )
109
+
110
+ # Changelog check
111
+ changelog_file = root_dir / cfg.changelog
112
+ cl_valid, cl_errs = validate_changelog(changelog_file)
113
+ table.add_row(
114
+ "Changelog",
115
+ cfg.changelog,
116
+ "[bold green]PASS[/bold green]" if cl_valid else "[bold yellow]WARN[/bold yellow]",
117
+ "Valid release format" if cl_valid else (cl_errs[0] if cl_errs else "Missing"),
118
+ )
119
+
120
+ # Hooks check
121
+ hooks_status = get_hooks_status(root_dir)
122
+ table.add_row(
123
+ "Git Hooks",
124
+ "Quality Hooks",
125
+ "[bold green]PASS[/bold green]"
126
+ if hooks_status["installed"]
127
+ else "[bold yellow]WARN[/bold yellow]",
128
+ f"core.hooksPath: {hooks_status['core_hooks_path']}",
129
+ )
130
+
131
+ console.print(table)
132
+ return 0 if all_ok else 1
@@ -0,0 +1,280 @@
1
+ """AST-level documentation auditor and compliance verification gate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import json
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from rich.console import Console
12
+
13
+ console = Console()
14
+
15
+
16
+ @dataclass
17
+ class DocViolation:
18
+ """Documenting a specific missing or non-compliant docstring."""
19
+
20
+ file: str
21
+ line: int
22
+ entity_type: str
23
+ entity_name: str
24
+ rule: str
25
+ message: str
26
+
27
+ def to_dict(self) -> dict[str, Any]:
28
+ """Convert violation to dictionary."""
29
+ return {
30
+ "file": self.file,
31
+ "line": self.line,
32
+ "entity_type": self.entity_type,
33
+ "entity_name": self.entity_name,
34
+ "rule": self.rule,
35
+ "message": self.message,
36
+ }
37
+
38
+
39
+ def _is_property(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
40
+ """Check if function node is decorated as property."""
41
+ for dec in node.decorator_list:
42
+ if isinstance(dec, ast.Name) and dec.id == "property":
43
+ return True
44
+ if isinstance(dec, ast.Attribute) and dec.attr in ("setter", "deleter"):
45
+ return True
46
+ return False
47
+
48
+
49
+ class DocumentationAuditor:
50
+ """AST inspector checking docstrings across Python files."""
51
+
52
+ def __init__(
53
+ self,
54
+ base_dir: Path,
55
+ include_private: bool = False,
56
+ require_init_docs: bool = False,
57
+ require_package_ownership: bool = False,
58
+ ) -> None:
59
+ self.base_dir = base_dir
60
+ self.include_private = include_private
61
+ self.require_init_docs = require_init_docs
62
+ self.require_package_ownership = require_package_ownership
63
+ self.violations: list[DocViolation] = []
64
+
65
+ def audit_file(self, file_path: Path) -> None:
66
+ """Audit single Python file AST for docstring compliance."""
67
+ try:
68
+ rel_path = str(file_path.relative_to(self.base_dir))
69
+ except ValueError:
70
+ rel_path = str(file_path)
71
+
72
+ try:
73
+ content = file_path.read_text(encoding="utf-8")
74
+ tree = ast.parse(content, filename=str(file_path))
75
+ except Exception as exc:
76
+ self.violations.append(
77
+ DocViolation(
78
+ file=rel_path,
79
+ line=1,
80
+ entity_type="Module",
81
+ entity_name=file_path.name,
82
+ rule="PARSE_ERROR",
83
+ message=f"Failed to parse AST: {exc}",
84
+ )
85
+ )
86
+ return
87
+
88
+ # 1. Module Docstring Check
89
+ module_doc = ast.get_docstring(tree)
90
+ if not module_doc or not module_doc.strip():
91
+ self.violations.append(
92
+ DocViolation(
93
+ file=rel_path,
94
+ line=1,
95
+ entity_type="Module",
96
+ entity_name=file_path.name,
97
+ rule="MISSING_MODULE_DOCSTRING",
98
+ message="Module is missing a top-level docstring.",
99
+ )
100
+ )
101
+ elif file_path.name == "__init__.py" and self.require_package_ownership:
102
+ if "Owns" not in module_doc or "Does not own" not in module_doc:
103
+ self.violations.append(
104
+ DocViolation(
105
+ file=rel_path,
106
+ line=1,
107
+ entity_type="Package",
108
+ entity_name=file_path.parent.name,
109
+ rule="MISSING_OWNERSHIP_CONTRACT",
110
+ message="__init__.py missing 'Owns' and/or 'Does not own' boundary contract.",
111
+ )
112
+ )
113
+
114
+ # 2. Walk AST for Classes, Functions, Methods, Properties
115
+ for node in tree.body:
116
+ if isinstance(node, ast.ClassDef):
117
+ self._audit_class(node, rel_path)
118
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
119
+ self._audit_function(node, rel_path, is_method=False)
120
+
121
+ def _audit_class(self, node: ast.ClassDef, file_path: str) -> None:
122
+ if (
123
+ not self.include_private
124
+ and node.name.startswith("_")
125
+ and not node.name.startswith("__")
126
+ ):
127
+ return
128
+
129
+ cls_doc = ast.get_docstring(node)
130
+ if not cls_doc or not cls_doc.strip():
131
+ self.violations.append(
132
+ DocViolation(
133
+ file=file_path,
134
+ line=node.lineno,
135
+ entity_type="Class",
136
+ entity_name=node.name,
137
+ rule="MISSING_CLASS_DOCSTRING",
138
+ message=f"Class '{node.name}' is missing a docstring.",
139
+ )
140
+ )
141
+
142
+ for item in node.body:
143
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
144
+ is_prop = _is_property(item)
145
+ self._audit_function(
146
+ item,
147
+ file_path,
148
+ is_method=True,
149
+ is_property=is_prop,
150
+ parent_class=node.name,
151
+ parent_class_doc=cls_doc,
152
+ )
153
+ elif isinstance(item, ast.ClassDef):
154
+ self._audit_class(item, file_path)
155
+
156
+ def _audit_function(
157
+ self,
158
+ node: ast.FunctionDef | ast.AsyncFunctionDef,
159
+ file_path: str,
160
+ is_method: bool = False,
161
+ is_property: bool = False,
162
+ parent_class: str = "",
163
+ parent_class_doc: str | None = None,
164
+ ) -> None:
165
+ entity_type = "Property" if is_property else ("Method" if is_method else "Function")
166
+ full_name = f"{parent_class}.{node.name}" if parent_class else node.name
167
+
168
+ is_private = node.name.startswith("_") and not (
169
+ node.name.startswith("__") and node.name.endswith("__")
170
+ )
171
+ if not self.include_private and is_private:
172
+ return
173
+
174
+ doc = ast.get_docstring(node)
175
+
176
+ # Special handling for __init__
177
+ if is_method and node.name == "__init__":
178
+ if doc and doc.strip():
179
+ return
180
+ if not self.require_init_docs and parent_class_doc and parent_class_doc.strip():
181
+ return
182
+ self.violations.append(
183
+ DocViolation(
184
+ file=file_path,
185
+ line=node.lineno,
186
+ entity_type="Method",
187
+ entity_name=full_name,
188
+ rule="MISSING_INIT_DOCSTRING",
189
+ message=f"Constructor '{full_name}' lacks docstring and parent class lacks parameters documentation.",
190
+ )
191
+ )
192
+ return
193
+
194
+ if not doc or not doc.strip():
195
+ self.violations.append(
196
+ DocViolation(
197
+ file=file_path,
198
+ line=node.lineno,
199
+ entity_type=entity_type,
200
+ entity_name=full_name,
201
+ rule=f"MISSING_{entity_type.upper()}_DOCSTRING",
202
+ message=f"{entity_type} '{full_name}' is missing a docstring.",
203
+ )
204
+ )
205
+
206
+
207
+ def run_documentation_audit(
208
+ root_dir: Path | None = None,
209
+ strict: bool = False,
210
+ require_init: bool = False,
211
+ as_json: bool = False,
212
+ ) -> int:
213
+ """Run AST documentation auditor across configured source roots."""
214
+ if root_dir is None:
215
+ from project_forge.project import find_project_root
216
+
217
+ root_dir = find_project_root()
218
+
219
+ from project_forge.config import load_config
220
+
221
+ cfg = load_config(root_dir)
222
+
223
+ auditor = DocumentationAuditor(
224
+ base_dir=root_dir,
225
+ include_private=strict or cfg.docs.include_private,
226
+ require_init_docs=require_init or cfg.docs.require_init_docs,
227
+ require_package_ownership=cfg.docs.require_package_ownership,
228
+ )
229
+
230
+ for src_path_str in cfg.source:
231
+ src_path = root_dir / src_path_str
232
+ if src_path.is_dir():
233
+ for py_file in sorted(src_path.rglob("*.py")):
234
+ auditor.audit_file(py_file)
235
+ elif src_path.is_file() and src_path.suffix == ".py":
236
+ auditor.audit_file(src_path)
237
+
238
+ violations = auditor.violations
239
+
240
+ if as_json:
241
+ print(json.dumps([v.to_dict() for v in violations], indent=2))
242
+ return 1 if violations else 0
243
+
244
+ mode_label: list[str] = []
245
+ if strict:
246
+ mode_label.append("STRICT")
247
+ else:
248
+ mode_label.append("PUBLIC INTERFACES")
249
+ if require_init:
250
+ mode_label.append("REQUIRE __INIT__")
251
+
252
+ console.print("=" * 80)
253
+ console.print(
254
+ f"AST Documentation Auditor | Scope: {cfg.source} | Mode: {', '.join(mode_label)}"
255
+ )
256
+ console.print("=" * 80)
257
+
258
+ if not violations:
259
+ console.print(
260
+ "[bold green][PASS] ALL ENTITIES 100% DOCUMENTED! Zero violations found.[/bold green]"
261
+ )
262
+ console.print("=" * 80)
263
+ return 0
264
+
265
+ console.print(f"[bold yellow]Found {len(violations)} documentation violations:[/bold yellow]\n")
266
+ by_type: dict[str, int] = {}
267
+ for v in violations:
268
+ by_type[v.entity_type] = by_type.get(v.entity_type, 0) + 1
269
+ console.print(
270
+ f" [{v.entity_type:8s}] [cyan]{v.file}:{v.line}[/cyan] -> [bold]{v.entity_name}[/bold]"
271
+ )
272
+ console.print(f" [dim]Rule: {v.rule} | {v.message}[/dim]")
273
+
274
+ console.print("\nSummary by Entity Type:")
275
+ for etype, count in sorted(by_type.items()):
276
+ console.print(f" - {etype}: {count}")
277
+
278
+ console.print(f"\n[bold red]Total violations: {len(violations)}[/bold red]")
279
+ console.print("=" * 80)
280
+ return 1
project_forge/hooks.py ADDED
@@ -0,0 +1,198 @@
1
+ """Git quality hooks installer, uninstaller, and status inspector."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import stat
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from project_forge.process import run_process
11
+
12
+
13
+ def _make_executable(target: Path) -> None:
14
+ """Set executable permission on POSIX systems."""
15
+ try:
16
+ current_mode = os.stat(target).st_mode
17
+ os.chmod(target, current_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
18
+ except OSError:
19
+ pass
20
+
21
+
22
+ def generate_pre_commit_script(project_name: str) -> str:
23
+ """Generate project-neutral pre-commit shell script."""
24
+ return f"""#!/usr/bin/env sh
25
+ # {project_name} - Pre-Commit Quality Gate (Fast Tier)
26
+ # Managed by Project Forge (pforge)
27
+ echo "[Quality Gate] Running Pre-Commit Fast Verification..."
28
+
29
+ uv run pforge quality --fast
30
+ EXIT_CODE=$?
31
+
32
+ if [ $EXIT_CODE -ne 0 ]; then
33
+ echo ""
34
+ echo "[Quality Gate] [FAIL] Pre-commit checks failed."
35
+ echo "[Quality Gate] Fix issues or run 'uv run pforge quality --fast --fix' to auto-fix formatting."
36
+ exit $EXIT_CODE
37
+ fi
38
+
39
+ echo "[Quality Gate] [PASS] Pre-commit checks passed cleanly."
40
+ exit 0
41
+ """
42
+
43
+
44
+ def generate_pre_push_script(project_name: str) -> str:
45
+ """Generate project-neutral pre-push shell script."""
46
+ return f"""#!/usr/bin/env sh
47
+ # {project_name} - Pre-Push Quality Gate (Full Tier)
48
+ # Managed by Project Forge (pforge)
49
+ echo "[Quality Gate] Running Pre-Push Full Verification Suite..."
50
+
51
+ uv run pforge quality
52
+ EXIT_CODE=$?
53
+
54
+ if [ $EXIT_CODE -ne 0 ]; then
55
+ echo ""
56
+ echo "[Quality Gate] [FAIL] Pre-push verification failed."
57
+ echo "[Quality Gate] Push aborted. Ensure all quality checks pass before pushing."
58
+ exit $EXIT_CODE
59
+ fi
60
+
61
+ echo "[Quality Gate] [PASS] Full verification suite passed cleanly. Proceeding with push."
62
+ exit 0
63
+ """
64
+
65
+
66
+ def install_hooks(root_dir: Path | None = None) -> int:
67
+ """Install git pre-commit and pre-push hooks.
68
+
69
+ Configures Git's core.hooksPath to point to .githooks, and installs fallbacks into .git/hooks.
70
+
71
+ Parameters
72
+ ----------
73
+ root_dir : Path | None, optional
74
+ Project root directory, by default None.
75
+
76
+ Returns
77
+ -------
78
+ int
79
+ 0 on success, 1 on failure.
80
+ """
81
+ if root_dir is None:
82
+ from project_forge.project import find_project_root
83
+
84
+ root_dir = find_project_root()
85
+
86
+ from project_forge.project import read_project_metadata
87
+
88
+ metadata = read_project_metadata(root_dir)
89
+ project_name = metadata.get("name", root_dir.name)
90
+
91
+ tracked_dir = root_dir / ".githooks"
92
+ tracked_dir.mkdir(parents=True, exist_ok=True)
93
+
94
+ pre_commit_content = generate_pre_commit_script(project_name)
95
+ pre_push_content = generate_pre_push_script(project_name)
96
+
97
+ # 1. Write tracked hooks
98
+ tracked_pre_commit = tracked_dir / "pre-commit"
99
+ tracked_pre_push = tracked_dir / "pre-push"
100
+
101
+ tracked_pre_commit.write_text(pre_commit_content, encoding="utf-8", newline="\n")
102
+ _make_executable(tracked_pre_commit)
103
+
104
+ tracked_pre_push.write_text(pre_push_content, encoding="utf-8", newline="\n")
105
+ _make_executable(tracked_pre_push)
106
+
107
+ # 2. Configure git core.hooksPath
108
+ git_dir = root_dir / ".git"
109
+ if git_dir.exists():
110
+ proc = run_process(["git", "config", "core.hooksPath", ".githooks"], cwd=root_dir)
111
+ if not proc.passed:
112
+ print(f"Warning: Failed to configure git core.hooksPath: {proc.stderr}")
113
+
114
+ # 3. Fallback write directly to .git/hooks if folder exists
115
+ git_hooks_dir = git_dir / "hooks"
116
+ if git_hooks_dir.is_dir():
117
+ git_pre_commit = git_hooks_dir / "pre-commit"
118
+ git_pre_push = git_hooks_dir / "pre-push"
119
+ git_pre_commit.write_text(pre_commit_content, encoding="utf-8", newline="\n")
120
+ _make_executable(git_pre_commit)
121
+ git_pre_push.write_text(pre_push_content, encoding="utf-8", newline="\n")
122
+ _make_executable(git_pre_push)
123
+
124
+ return 0
125
+
126
+
127
+ def uninstall_hooks(root_dir: Path | None = None) -> int:
128
+ """Uninstall git hooks and reset git core.hooksPath.
129
+
130
+ Parameters
131
+ ----------
132
+ root_dir : Path | None, optional
133
+ Project root directory, by default None.
134
+
135
+ Returns
136
+ -------
137
+ int
138
+ 0 on success.
139
+ """
140
+ if root_dir is None:
141
+ from project_forge.project import find_project_root
142
+
143
+ root_dir = find_project_root()
144
+
145
+ # Reset core.hooksPath
146
+ run_process(["git", "config", "--unset", "core.hooksPath"], cwd=root_dir)
147
+
148
+ # Remove files from .githooks if present
149
+ tracked_dir = root_dir / ".githooks"
150
+ if tracked_dir.is_dir():
151
+ for hook_file in tracked_dir.glob("*"):
152
+ if hook_file.is_file():
153
+ hook_file.unlink(missing_ok=True)
154
+
155
+ return 0
156
+
157
+
158
+ def get_hooks_status(root_dir: Path | None = None) -> dict[str, Any]:
159
+ """Inspect Git hooks installation and configuration state.
160
+
161
+ Parameters
162
+ ----------
163
+ root_dir : Path | None, optional
164
+ Project root directory, by default None.
165
+
166
+ Returns
167
+ -------
168
+ dict[str, Any]
169
+ Dictionary with hooks configuration status.
170
+ """
171
+ if root_dir is None:
172
+ from project_forge.project import find_project_root
173
+
174
+ root_dir = find_project_root()
175
+
176
+ proc = run_process(["git", "config", "--get", "core.hooksPath"], cwd=root_dir)
177
+ hooks_path = proc.stdout.strip() if proc.passed else ""
178
+
179
+ tracked_dir = root_dir / ".githooks"
180
+ pre_commit_tracked = (tracked_dir / "pre-commit").exists()
181
+ pre_push_tracked = (tracked_dir / "pre-push").exists()
182
+
183
+ git_hooks_dir = root_dir / ".git" / "hooks"
184
+ pre_commit_git = (git_hooks_dir / "pre-commit").exists()
185
+ pre_push_git = (git_hooks_dir / "pre-push").exists()
186
+
187
+ installed = bool(hooks_path == ".githooks" and pre_commit_tracked and pre_push_tracked) or bool(
188
+ pre_commit_git and pre_push_git
189
+ )
190
+
191
+ return {
192
+ "installed": installed,
193
+ "core_hooks_path": hooks_path or "(not set)",
194
+ "tracked_pre_commit": pre_commit_tracked,
195
+ "tracked_pre_push": pre_push_tracked,
196
+ "git_hooks_pre_commit": pre_commit_git,
197
+ "git_hooks_pre_push": pre_push_git,
198
+ }