commitwise 0.1.5__py3-none-any.whl → 0.2.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.
Files changed (37) hide show
  1. commitwise/__init__.py +1 -1
  2. commitwise/__main__.py +5 -0
  3. commitwise/cli.py +166 -41
  4. commitwise/config/__init__.py +6 -0
  5. commitwise/config/manager.py +131 -0
  6. commitwise/config/paths.py +18 -0
  7. commitwise/config/schema.py +66 -0
  8. commitwise/core/__init__.py +1 -0
  9. commitwise/core/diff.py +39 -0
  10. commitwise/core/generator.py +46 -0
  11. commitwise/core/git.py +92 -0
  12. commitwise/core/validation.py +35 -0
  13. commitwise/errors.py +135 -0
  14. commitwise/prompts/__init__.py +1 -0
  15. commitwise/prompts/commit_message.py +78 -0
  16. commitwise/providers/__init__.py +1 -0
  17. commitwise/providers/base.py +73 -0
  18. commitwise/providers/factory.py +38 -0
  19. commitwise/providers/ollama.py +90 -0
  20. commitwise/providers/openrouter.py +83 -0
  21. commitwise-0.2.0.dist-info/METADATA +190 -0
  22. commitwise-0.2.0.dist-info/RECORD +26 -0
  23. {commitwise-0.1.5.dist-info → commitwise-0.2.0.dist-info}/WHEEL +1 -1
  24. commitwise/ai/__init__.py +0 -0
  25. commitwise/ai/base.py +0 -60
  26. commitwise/ai/local_engine.py +0 -39
  27. commitwise/ai/openai_engine.py +0 -35
  28. commitwise/ai_source.py +0 -48
  29. commitwise/cli_utils.py +0 -87
  30. commitwise/config.py +0 -9
  31. commitwise/file_source.py +0 -25
  32. commitwise/git_utils.py +0 -80
  33. commitwise-0.1.5.dist-info/METADATA +0 -147
  34. commitwise-0.1.5.dist-info/RECORD +0 -17
  35. {commitwise-0.1.5.dist-info → commitwise-0.2.0.dist-info}/entry_points.txt +0 -0
  36. {commitwise-0.1.5.dist-info → commitwise-0.2.0.dist-info}/licenses/LICENSE +0 -0
  37. {commitwise-0.1.5.dist-info → commitwise-0.2.0.dist-info}/top_level.txt +0 -0
commitwise/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__='0.1.5'
1
+ __version__ = "0.2.0"
commitwise/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow running CommitWise with `python -m commitwise`."""
2
+
3
+ from commitwise.cli import main
4
+
5
+ raise SystemExit(main())
commitwise/cli.py CHANGED
@@ -1,59 +1,184 @@
1
+ """Command-line interface for CommitWise's safe, staged-diff workflow."""
2
+
3
+ import argparse
4
+ import json
1
5
  import sys
6
+ from typing import List, Optional
7
+
8
+ import pyperclip
2
9
 
3
10
  from commitwise import __version__
4
- from commitwise.cli_utils import (
5
- build_parser,
6
- )
7
- from commitwise.git_utils import (
8
- get_staged_diff,
9
- git_commit_with_message,
10
- confirm_commit,
11
+ from commitwise.config.manager import ConfigError, ConfigManager
12
+ from commitwise.core.diff import DiffAnalyzer
13
+ from commitwise.core.generator import CommitMessageGenerator, TRANSIENT_ERRORS
14
+ from commitwise.core.git import GitClient
15
+ from commitwise.errors import (
16
+ CommitWiseError,
17
+ DiffTooLargeError,
18
+ NoStagedChangesError,
11
19
  )
12
- from commitwise.file_source import read_commit_file
13
- from commitwise.ai_source import generate_ai_commit_message
20
+ from commitwise.providers.factory import create_provider
14
21
 
15
22
 
16
- def main() -> None:
17
- parser = build_parser()
18
- args = parser.parse_args()
23
+ def build_parser() -> argparse.ArgumentParser:
24
+ """Build the public CLI; provider selection is explicit and exclusive."""
25
+ parser = argparse.ArgumentParser(
26
+ prog="commitwise",
27
+ description="Commit your code Wisely ...",
28
+ )
29
+ parser.add_argument(
30
+ "--version", "-V", action="version",
31
+ version="commitwise {}".format(__version__),
32
+ )
33
+ provider_group = parser.add_mutually_exclusive_group()
34
+ provider_group.add_argument(
35
+ "--ai-local", action="store_true",
36
+ help="Generate suggestions with the local Ollama model.",
37
+ )
38
+ provider_group.add_argument(
39
+ "--ai-online", action="store_true",
40
+ help="Generate suggestions with OpenRouter.",
41
+ )
19
42
 
20
- # version flag
21
- if args.version:
22
- print(f"commitwise {__version__}")
23
- sys.exit(0)
43
+ commands = parser.add_subparsers(dest="command")
44
+ config_parser = commands.add_parser("config", help="Manage global configuration.")
45
+ config_commands = config_parser.add_subparsers(dest="config_command")
24
46
 
25
- # [X] both flags used
26
- if args.ai and args.file:
27
- parser.error("Use either --ai or --file, not both.")
47
+ config_commands.add_parser("show", help="Show global configuration (secrets masked).")
48
+ config_commands.add_parser("path", help="Show the global configuration file path.")
28
49
 
29
- # [X] no mode selected
30
- if not args.ai and not args.file:
31
- parser.print_help()
32
- sys.exit(0)
50
+ set_parser = config_commands.add_parser("set", help="Set one global configuration value.")
51
+ set_parser.add_argument("key", help="Dotted setting name, e.g. online.model.")
52
+ set_parser.add_argument("value", help="New setting value.")
53
+
54
+ return parser
55
+
56
+
57
+ def _show_no_staged_files(mode: str) -> None:
58
+ command = "commitwise --ai-online" if mode == "online" else "commitwise --ai-local"
59
+ print(
60
+ "No staged files found!\n\n"
61
+ "No files have been staged for commit.\n\n"
62
+ "Please stage your changes first:\n\n"
63
+ "git add <files>\n\n"
64
+ "Then run:\n\n"
65
+ "{}".format(command),
66
+ file=sys.stderr,
67
+ )
68
+
69
+
70
+ def _run_config(args: argparse.Namespace, manager: ConfigManager) -> int:
71
+ if args.config_command == "show":
72
+ print(json.dumps(manager.get_masked_config(), indent=2, sort_keys=True))
73
+ return 0
74
+ if args.config_command == "path":
75
+ print(str(manager.config_path))
76
+ return 0
77
+ if args.config_command == "set":
78
+ manager.set_value(args.key, args.value)
79
+ displayed = manager.get_masked_config()
80
+ section, name = args.key.split(".", 1)
81
+ print("{} = {}".format(args.key, json.dumps(displayed[section][name])))
82
+ return 0
83
+ print("Use 'commitwise config --help' to see configuration commands.")
84
+ return 0
85
+
86
+
87
+ def _run_generation(mode: str, manager: ConfigManager) -> int:
88
+ config = manager.load()
89
+ analysis = DiffAnalyzer(
90
+ GitClient(),
91
+ max_diff_size=config["general"]["max_diff_size"],
92
+ ).analyze()
93
+
94
+ print(
95
+ "Analyzing {} staged file(s) ({} bytes).".format(
96
+ len(analysis.files), analysis.size_bytes
97
+ )
98
+ )
99
+ if mode == "local":
100
+ print("Generating with Ollama; response is received incrementally.")
101
+ else:
102
+ print("Generating with OpenRouter.")
103
+
104
+ provider = create_provider(mode, config)
105
+ suggestions = CommitMessageGenerator(provider).generate(analysis.diff)
106
+
107
+ print("\nCommit message suggestions:\n")
108
+ for index, suggestion in enumerate(suggestions, start=1):
109
+ print("{}. {}".format(index, suggestion))
33
110
 
34
111
  try:
35
- # AI mode
36
- if args.ai:
37
- diff = get_staged_diff()
38
- message = generate_ai_commit_message(diff)
112
+ selected = input("\nSelect a suggestion to copy [1-3, q to quit]: ").strip()
113
+ except (EOFError, KeyboardInterrupt):
114
+ print("\nSelection cancelled.")
115
+ return 0
39
116
 
40
- if not confirm_commit(message):
41
- print("\n\nCommit aborted.")
42
- sys.exit(0)
117
+ if selected.lower() == "q":
118
+ print("No suggestion selected.")
119
+ return 0
120
+ if selected not in ("1", "2", "3"):
121
+ print("Invalid selection. No message was copied.", file=sys.stderr)
122
+ return 2
43
123
 
44
- git_commit_with_message(message)
45
- return
124
+ message = suggestions[int(selected) - 1]
125
+ try:
126
+ pyperclip.copy(message)
127
+ print("\nCopied to clipboard. Run this yourself when ready:")
128
+ except pyperclip.PyperclipException:
129
+ print("\nClipboard is unavailable. Copy the message manually:")
130
+ print(message)
131
+ return 0
132
+
133
+ print('git commit -m "{}"'.format(message.replace('"', '\\"')))
134
+ return 0
46
135
 
47
- # File mode
48
- if args.file:
49
- message = read_commit_file(args.file)
50
- git_commit_with_message(message)
51
- return
52
136
 
53
- except Exception as e:
54
- print(f"\n [X] Error: {e}", file=sys.stderr)
55
- sys.exit(1)
137
+ def main(argv: Optional[List[str]] = None) -> int:
138
+ """Run a CLI command and translate expected errors into useful messages."""
139
+ parser = build_parser()
140
+ args = parser.parse_args(argv)
141
+ manager = ConfigManager()
142
+
143
+ if args.command == "config":
144
+ try:
145
+ return _run_config(args, manager)
146
+ except (ConfigError, ValueError) as exc:
147
+ print("Error: {}".format(exc), file=sys.stderr)
148
+ return 1
149
+
150
+ mode = "local" if args.ai_local else "online" if args.ai_online else None
151
+ if mode is None:
152
+ parser.print_help()
153
+ return 0
154
+
155
+ try:
156
+ return _run_generation(mode, manager)
157
+ except NoStagedChangesError:
158
+ _show_no_staged_files(mode)
159
+ return 1
160
+ except DiffTooLargeError as exc:
161
+ print(
162
+ "Staged diff is too large ({} bytes; limit: {} bytes).\n"
163
+ "Split the changes into smaller commits and try again.".format(
164
+ exc.actual_size, exc.maximum_size
165
+ ),
166
+ file=sys.stderr,
167
+ )
168
+ return 1
169
+ except TRANSIENT_ERRORS as exc:
170
+ print(
171
+ "The AI provider failed after three attempts.\n{}".format(exc),
172
+ file=sys.stderr,
173
+ )
174
+ return 1
175
+ except (CommitWiseError, ConfigError) as exc:
176
+ print("Error: {}".format(exc), file=sys.stderr)
177
+ return 1
178
+ except KeyboardInterrupt:
179
+ print("\nCancelled.")
180
+ return 130
56
181
 
57
182
 
58
183
  if __name__ == "__main__":
59
- main()
184
+ raise SystemExit(main())
@@ -0,0 +1,6 @@
1
+ """Global configuration support for CommitWise."""
2
+
3
+ from commitwise.config.manager import ConfigManager
4
+ from commitwise.config.schema import DEFAULT_CONFIG
5
+
6
+ __all__ = ["ConfigManager", "DEFAULT_CONFIG"]
@@ -0,0 +1,131 @@
1
+ """Load, validate, update, and safely write global CommitWise config."""
2
+
3
+ import os
4
+ import tempfile
5
+ from copy import deepcopy
6
+ from pathlib import Path
7
+ from typing import Any, Dict, Optional
8
+
9
+ import tomlkit
10
+
11
+ from commitwise.config.paths import get_config_dir, get_config_path
12
+ from commitwise.config.schema import (
13
+ ALLOWED_SETTINGS,
14
+ default_config,
15
+ validate_config,
16
+ )
17
+
18
+
19
+ class ConfigError(Exception):
20
+ """Raised when CommitWise configuration cannot be read or updated."""
21
+
22
+
23
+ class ConfigManager:
24
+ """Manage the single per-user CommitWise TOML configuration."""
25
+
26
+ def __init__(
27
+ self,
28
+ config_path: Optional[Path] = None,
29
+ config_dir: Optional[Path] = None,
30
+ ) -> None:
31
+ self.config_path = Path(config_path) if config_path else get_config_path()
32
+ self.config_dir = (
33
+ Path(config_dir) if config_dir else self.config_path.parent
34
+ )
35
+
36
+ def load(self) -> Dict[str, Any]:
37
+ """Load the configuration, creating a default file on first use."""
38
+ if not self.config_path.exists():
39
+ config = default_config()
40
+ self.save(config)
41
+ return config
42
+
43
+ try:
44
+ with self.config_path.open("r", encoding="utf-8") as config_file:
45
+ parsed = tomlkit.parse(config_file.read())
46
+ config = self._to_plain_dict(parsed)
47
+ validate_config(config)
48
+ return config
49
+ except (OSError, ValueError, tomlkit.exceptions.ParseError) as exc:
50
+ raise ConfigError(
51
+ "Unable to load configuration at {}: {}".format(
52
+ self.config_path, exc
53
+ )
54
+ ) from exc
55
+
56
+ def save(self, config: Dict[str, Any]) -> None:
57
+ """Validate and atomically save a complete configuration."""
58
+ try:
59
+ validate_config(config)
60
+ document = tomlkit.document()
61
+ for section_name, values in config.items():
62
+ section = tomlkit.table()
63
+ for key, value in values.items():
64
+ section.add(key, value)
65
+ document.add(section_name, section)
66
+
67
+ self.config_dir.mkdir(parents=True, exist_ok=True)
68
+ file_descriptor, temporary_name = tempfile.mkstemp(
69
+ prefix=".commitwise-",
70
+ suffix=".toml.tmp",
71
+ dir=str(self.config_dir),
72
+ )
73
+ try:
74
+ with os.fdopen(file_descriptor, "w", encoding="utf-8", newline="\n") as temp_file:
75
+ temp_file.write(tomlkit.dumps(document))
76
+ temp_file.flush()
77
+ os.fsync(temp_file.fileno())
78
+ os.replace(temporary_name, str(self.config_path))
79
+ finally:
80
+ if os.path.exists(temporary_name):
81
+ os.unlink(temporary_name)
82
+ except (OSError, ValueError, TypeError) as exc:
83
+ raise ConfigError("Unable to save configuration: {}".format(exc)) from exc
84
+
85
+ def set_value(self, key: str, value: Any) -> Dict[str, Any]:
86
+ """Update one allowlisted dotted setting and persist the result."""
87
+ if key not in ALLOWED_SETTINGS:
88
+ raise ConfigError("Unknown configuration setting: {}".format(key))
89
+
90
+ expected_type = ALLOWED_SETTINGS[key]
91
+ if expected_type is int:
92
+ try:
93
+ if isinstance(value, bool):
94
+ raise ValueError
95
+ converted_value = int(value)
96
+ except (TypeError, ValueError) as exc:
97
+ raise ConfigError("{} must be an integer.".format(key)) from exc
98
+ else:
99
+ converted_value = str(value)
100
+
101
+ config = self.load()
102
+ section, name = key.split(".", 1)
103
+ config[section][name] = converted_value
104
+ try:
105
+ validate_config(config)
106
+ except ValueError as exc:
107
+ raise ConfigError(str(exc)) from exc
108
+ self.save(config)
109
+ return config
110
+
111
+ def get_masked_config(self) -> Dict[str, Any]:
112
+ """Return configuration safe for display; never reveal the API key."""
113
+ config = deepcopy(self.load())
114
+ api_key = config["online"].get("api_key", "")
115
+ if api_key:
116
+ config["online"]["api_key"] = "********"
117
+ return config
118
+
119
+ @staticmethod
120
+ def _to_plain_dict(parsed: Any) -> Dict[str, Any]:
121
+ """Convert TOMLKit tables into ordinary Python dictionaries."""
122
+ result: Dict[str, Any] = {}
123
+ for section_name, values in parsed.items():
124
+ if not hasattr(values, "items"):
125
+ result[section_name] = values
126
+ continue
127
+ result[section_name] = {
128
+ key: value.unwrap() if hasattr(value, "unwrap") else value
129
+ for key, value in values.items()
130
+ }
131
+ return result
@@ -0,0 +1,18 @@
1
+ """Resolve CommitWise's per-user configuration paths."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ from platformdirs import user_config_path
7
+
8
+ APP_NAME = "CommitWise" if os.name == "nt" else "commitwise"
9
+
10
+
11
+ def get_config_dir() -> Path:
12
+ """Return the roaming config directory on Windows and XDG config on Linux."""
13
+ return Path(user_config_path(APP_NAME, appauthor=False, roaming=True))
14
+
15
+
16
+ def get_config_path() -> Path:
17
+ """Return the path to the global TOML configuration file."""
18
+ return get_config_dir() / "config.toml"
@@ -0,0 +1,66 @@
1
+ """Default values and validation rules for global configuration."""
2
+
3
+ from copy import deepcopy
4
+ from typing import Any, Dict
5
+
6
+ DEFAULT_CONFIG: Dict[str, Any] = {
7
+ "general": {
8
+ # The limit is measured in UTF-8 bytes, not characters.
9
+ "max_diff_size": 50000,
10
+ },
11
+ "local": {
12
+ "base_url": "http://localhost:11434",
13
+ "model": "llama3.1",
14
+ "timeout": 120,
15
+ },
16
+ "online": {
17
+ "base_url": "https://openrouter.ai/api/v1",
18
+ "model": "",
19
+ "api_key": "",
20
+ "timeout": 60,
21
+ },
22
+ }
23
+
24
+ ALLOWED_SETTINGS = {
25
+ "general.max_diff_size": int,
26
+ "local.base_url": str,
27
+ "local.model": str,
28
+ "local.timeout": int,
29
+ "online.base_url": str,
30
+ "online.model": str,
31
+ "online.api_key": str,
32
+ "online.timeout": int,
33
+ }
34
+
35
+
36
+ def default_config() -> Dict[str, Any]:
37
+ """Return a fresh copy of the default configuration."""
38
+ return deepcopy(DEFAULT_CONFIG)
39
+
40
+
41
+ def validate_config(config: Dict[str, Any]) -> None:
42
+ """Validate known configuration sections and setting types."""
43
+ if not isinstance(config, dict):
44
+ raise ValueError("Configuration root must be a TOML table.")
45
+
46
+ for section in ("general", "local", "online"):
47
+ if section not in config or not isinstance(config[section], dict):
48
+ raise ValueError("Missing or invalid configuration section: {}".format(section))
49
+
50
+ for key, expected_type in ALLOWED_SETTINGS.items():
51
+ section, name = key.split(".", 1)
52
+ value = config[section].get(name)
53
+ if value is None:
54
+ raise ValueError("Missing configuration value: {}".format(key))
55
+ if expected_type is int:
56
+ if isinstance(value, bool) or not isinstance(value, int):
57
+ raise ValueError("{} must be an integer.".format(key))
58
+ if value <= 0:
59
+ raise ValueError("{} must be greater than zero.".format(key))
60
+ elif not isinstance(value, expected_type):
61
+ raise ValueError("{} must be a string.".format(key))
62
+
63
+ for key in ("local.base_url", "local.model", "online.base_url"):
64
+ section, name = key.split(".", 1)
65
+ if not config[section][name].strip():
66
+ raise ValueError("{} cannot be empty.".format(key))
@@ -0,0 +1 @@
1
+ """Core Git and generation logic for CommitWise."""
@@ -0,0 +1,39 @@
1
+ """Diff size enforcement and staged-change analysis."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Tuple
5
+
6
+ from commitwise.core.git import GitClient
7
+ from commitwise.errors import DiffTooLargeError
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class DiffAnalysis:
12
+ """Validated staged diff ready to be sent to an AI provider."""
13
+
14
+ files: Tuple[str, ...]
15
+ diff: str
16
+ size_bytes: int
17
+
18
+
19
+ class DiffAnalyzer:
20
+ """Collect staged changes and enforce the configured hard size limit."""
21
+
22
+ def __init__(self, git_client: GitClient, max_diff_size: int) -> None:
23
+ if isinstance(max_diff_size, bool) or not isinstance(max_diff_size, int) or max_diff_size <= 0:
24
+ raise ValueError("max_diff_size must be a positive integer.")
25
+ self.git_client = git_client
26
+ self.max_diff_size = max_diff_size
27
+
28
+ def analyze(self) -> DiffAnalysis:
29
+ staged = self.git_client.get_staged_changes()
30
+ size_bytes = len(staged.diff.encode("utf-8", errors="surrogateescape"))
31
+
32
+ if size_bytes > self.max_diff_size:
33
+ raise DiffTooLargeError(size_bytes, self.max_diff_size)
34
+
35
+ return DiffAnalysis(
36
+ files=staged.files,
37
+ diff=staged.diff,
38
+ size_bytes=size_bytes,
39
+ )
@@ -0,0 +1,46 @@
1
+ """Provider orchestration and bounded retry policy."""
2
+
3
+ import time
4
+ from typing import Callable, List, Optional
5
+
6
+ from commitwise.errors import (
7
+ AIProviderConnectionError,
8
+ AIProviderRateLimitError,
9
+ AIProviderTimeout,
10
+ AIProviderUnavailable,
11
+ )
12
+ from commitwise.providers.base import AIProvider
13
+
14
+ TRANSIENT_ERRORS = (
15
+ AIProviderConnectionError,
16
+ AIProviderRateLimitError,
17
+ AIProviderTimeout,
18
+ AIProviderUnavailable,
19
+ )
20
+
21
+
22
+ class CommitMessageGenerator:
23
+ """Call one explicitly selected provider and retry transient failures."""
24
+
25
+ def __init__(
26
+ self,
27
+ provider: AIProvider,
28
+ max_attempts: int = 3,
29
+ sleep: Optional[Callable[[float], None]] = None,
30
+ ) -> None:
31
+ if max_attempts < 1:
32
+ raise ValueError("max_attempts must be at least one.")
33
+ self.provider = provider
34
+ self.max_attempts = max_attempts
35
+ self.sleep = sleep or time.sleep
36
+
37
+ def generate(self, diff: str) -> List[str]:
38
+ """Return validated suggestions, retrying only transient provider errors."""
39
+ for attempt in range(1, self.max_attempts + 1):
40
+ try:
41
+ return self.provider.generate(diff)
42
+ except TRANSIENT_ERRORS:
43
+ if attempt >= self.max_attempts:
44
+ raise
45
+ self.sleep(float(attempt))
46
+ raise RuntimeError("Generation loop exited unexpectedly.")
commitwise/core/git.py ADDED
@@ -0,0 +1,92 @@
1
+ """Read-only Git access for CommitWise."""
2
+
3
+ import subprocess
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Optional, Tuple
7
+
8
+ from commitwise.errors import (
9
+ EmptyStagedDiffError,
10
+ GitCommandError,
11
+ NoStagedChangesError,
12
+ NotGitRepositoryError,
13
+ )
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class StagedChanges:
18
+ """Snapshot of the currently staged paths and patch."""
19
+
20
+ files: Tuple[str, ...]
21
+ diff: str
22
+
23
+
24
+ class GitClient:
25
+ """Read staged Git data without modifying the repository or index."""
26
+
27
+ def __init__(self, cwd: Optional[Path] = None) -> None:
28
+ self.cwd = Path(cwd) if cwd is not None else None
29
+
30
+ def _run_read_only(self, *args: str) -> str:
31
+ """Run one explicitly allowed read-only Git command."""
32
+ allowed_commands = {
33
+ ("rev-parse", "--show-toplevel"),
34
+ ("diff", "--cached", "--name-only", "-z"),
35
+ ("diff", "--cached", "--no-ext-diff", "--no-color", "--unified=3"),
36
+ }
37
+ if tuple(args) not in allowed_commands:
38
+ raise ValueError("Git command is not in the read-only allowlist.")
39
+
40
+ try:
41
+ result = subprocess.run(
42
+ ["git", *args],
43
+ cwd=str(self.cwd) if self.cwd else None,
44
+ stdout=subprocess.PIPE,
45
+ stderr=subprocess.PIPE,
46
+ encoding="utf-8",
47
+ errors="surrogateescape",
48
+ check=False,
49
+ )
50
+ except FileNotFoundError as exc:
51
+ raise GitCommandError(
52
+ "Git executable was not found. Install Git and ensure it is on PATH."
53
+ ) from exc
54
+ except OSError as exc:
55
+ raise GitCommandError("Unable to execute Git: {}".format(exc)) from exc
56
+
57
+ if result.returncode != 0:
58
+ message = result.stderr.strip() or "Git command failed."
59
+ if args == ("rev-parse", "--show-toplevel"):
60
+ raise NotGitRepositoryError(
61
+ "The current directory is not inside a Git repository."
62
+ )
63
+ raise GitCommandError(message)
64
+
65
+ return result.stdout
66
+
67
+ def repository_root(self) -> Path:
68
+ """Return the root directory of the current Git repository."""
69
+ root = self._run_read_only("rev-parse", "--show-toplevel").strip()
70
+ return Path(root)
71
+
72
+ def get_staged_changes(self) -> StagedChanges:
73
+ """Return staged paths and patch; never include unstaged changes."""
74
+ self.repository_root()
75
+ raw_paths = self._run_read_only(
76
+ "diff", "--cached", "--name-only", "-z"
77
+ )
78
+ files = tuple(path for path in raw_paths.split("\0") if path)
79
+ if not files:
80
+ raise NoStagedChangesError(
81
+ "No staged files found. Run git add <files> first."
82
+ )
83
+
84
+ diff = self._run_read_only(
85
+ "diff", "--cached", "--no-ext-diff", "--no-color", "--unified=3"
86
+ )
87
+ if not diff.strip():
88
+ raise EmptyStagedDiffError(
89
+ "Staged files were found, but the staged diff is empty."
90
+ )
91
+
92
+ return StagedChanges(files=files, diff=diff)
@@ -0,0 +1,35 @@
1
+ """Validation for structured AI output and Conventional Commit headers."""
2
+
3
+ import re
4
+ from typing import List
5
+
6
+ CONVENTIONAL_COMMIT_PATTERN = re.compile(
7
+ r"^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)"
8
+ r"(\([a-zA-Z0-9._/-]+\))?!?: \S.*$"
9
+ )
10
+
11
+
12
+ def validate_suggestions(suggestions: object) -> List[str]:
13
+ """Require exactly three distinct, single-line Conventional Commit messages."""
14
+ if not isinstance(suggestions, list) or len(suggestions) != 3:
15
+ raise ValueError("The AI must return exactly three suggestions.")
16
+
17
+ validated = []
18
+ for suggestion in suggestions:
19
+ if not isinstance(suggestion, str):
20
+ raise ValueError("Every suggestion must be a string.")
21
+ message = suggestion.strip()
22
+ if not message or "\n" in message or "\r" in message:
23
+ raise ValueError("Suggestions must be non-empty single-line messages.")
24
+ if not CONVENTIONAL_COMMIT_PATTERN.fullmatch(message):
25
+ raise ValueError(
26
+ "Invalid Conventional Commit message: {}".format(message)
27
+ )
28
+ validated.append(message)
29
+
30
+ # Case-only differences are not useful alternatives. Semantic similarity
31
+ # cannot be reliably determined with a deterministic syntax validator.
32
+ if len({message.casefold() for message in validated}) != 3:
33
+ raise ValueError("The AI must return three distinct suggestions.")
34
+
35
+ return validated