commitron 1.0.0rc4__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.
- commitron/__init__.py +1 -0
- commitron/__main__.py +3 -0
- commitron/ai.py +407 -0
- commitron/cli.py +617 -0
- commitron/config.py +289 -0
- commitron/credentials.py +124 -0
- commitron/git_ops.py +175 -0
- commitron/providers.py +337 -0
- commitron/safety.py +28 -0
- commitron-1.0.0rc4.dist-info/METADATA +393 -0
- commitron-1.0.0rc4.dist-info/RECORD +15 -0
- commitron-1.0.0rc4.dist-info/WHEEL +5 -0
- commitron-1.0.0rc4.dist-info/entry_points.txt +3 -0
- commitron-1.0.0rc4.dist-info/licenses/LICENSE +21 -0
- commitron-1.0.0rc4.dist-info/top_level.txt +1 -0
commitron/config.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""User configuration with environment-variable overrides and no stored API keys."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from urllib.parse import urlsplit
|
|
10
|
+
from typing import Any, Dict
|
|
11
|
+
|
|
12
|
+
from .providers import PROVIDERS
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
DEFAULTS: Dict[str, str] = {
|
|
16
|
+
"provider": "gemini",
|
|
17
|
+
"model": "",
|
|
18
|
+
"base_url": "",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def config_path() -> Path:
|
|
23
|
+
"""Return the platform-appropriate per-user config path."""
|
|
24
|
+
if os.name == "nt":
|
|
25
|
+
root = Path(os.environ.get("APPDATA") or (Path.home() / "AppData" / "Roaming"))
|
|
26
|
+
elif sys_platform() == "darwin":
|
|
27
|
+
root = Path.home() / "Library" / "Application Support"
|
|
28
|
+
else:
|
|
29
|
+
root = Path(os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config"))
|
|
30
|
+
return root / "commitron" / "config.json"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def sys_platform() -> str:
|
|
34
|
+
# Kept as a function to make path selection straightforward to test.
|
|
35
|
+
import sys
|
|
36
|
+
return sys.platform
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load_config() -> Dict[str, str]:
|
|
40
|
+
path = config_path()
|
|
41
|
+
data: Dict[str, Any] = {}
|
|
42
|
+
if path.exists():
|
|
43
|
+
try:
|
|
44
|
+
loaded = json.loads(path.read_text(encoding="utf-8"))
|
|
45
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
46
|
+
raise ValueError("Cannot read Commitron config at {}: {}".format(path, exc)) from exc
|
|
47
|
+
if not isinstance(loaded, dict):
|
|
48
|
+
raise ValueError("Commitron config must contain a JSON object.")
|
|
49
|
+
data = loaded
|
|
50
|
+
config = dict(DEFAULTS)
|
|
51
|
+
for key in DEFAULTS:
|
|
52
|
+
value = data.get(key)
|
|
53
|
+
if value is not None:
|
|
54
|
+
if not isinstance(value, str):
|
|
55
|
+
raise ValueError("Config value '{}' must be a string.".format(key))
|
|
56
|
+
config[key] = value.strip()
|
|
57
|
+
env_map = {
|
|
58
|
+
"provider": "COMMITRON_PROVIDER",
|
|
59
|
+
"model": "COMMITRON_MODEL",
|
|
60
|
+
"base_url": "COMMITRON_BASE_URL",
|
|
61
|
+
}
|
|
62
|
+
for key, env_name in env_map.items():
|
|
63
|
+
if os.environ.get(env_name, "").strip():
|
|
64
|
+
config[key] = os.environ[env_name].strip()
|
|
65
|
+
provider = config["provider"].lower()
|
|
66
|
+
if provider not in PROVIDERS:
|
|
67
|
+
raise ValueError("Unsupported provider '{}'. Supported: {}."
|
|
68
|
+
.format(provider, ", ".join(sorted(PROVIDERS))))
|
|
69
|
+
config["provider"] = provider
|
|
70
|
+
_validate_base_url(config["base_url"])
|
|
71
|
+
return config
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def save_config(updates: Dict[str, str]) -> Path:
|
|
75
|
+
unknown = set(updates) - set(DEFAULTS)
|
|
76
|
+
if unknown:
|
|
77
|
+
raise ValueError("Unsupported config key(s): {}".format(", ".join(sorted(unknown))))
|
|
78
|
+
current = dict(DEFAULTS)
|
|
79
|
+
path = config_path()
|
|
80
|
+
if path.exists():
|
|
81
|
+
current.update(load_file(path))
|
|
82
|
+
for key, value in updates.items():
|
|
83
|
+
if not isinstance(value, str):
|
|
84
|
+
raise ValueError("Config values must be strings.")
|
|
85
|
+
current[key] = value.strip()
|
|
86
|
+
provider = current["provider"].lower()
|
|
87
|
+
if provider not in PROVIDERS:
|
|
88
|
+
raise ValueError("Unsupported provider '{}'. Supported: {}."
|
|
89
|
+
.format(provider, ", ".join(sorted(PROVIDERS))))
|
|
90
|
+
current["provider"] = provider
|
|
91
|
+
_validate_base_url(current["base_url"])
|
|
92
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
93
|
+
fd, temp_name = tempfile.mkstemp(prefix="config-", suffix=".tmp", dir=str(path.parent))
|
|
94
|
+
try:
|
|
95
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
96
|
+
json.dump(current, handle, indent=2)
|
|
97
|
+
handle.write("\n")
|
|
98
|
+
if os.name != "nt":
|
|
99
|
+
try:
|
|
100
|
+
os.chmod(temp_name, 0o600)
|
|
101
|
+
except OSError:
|
|
102
|
+
pass
|
|
103
|
+
os.replace(temp_name, path)
|
|
104
|
+
finally:
|
|
105
|
+
if os.path.exists(temp_name):
|
|
106
|
+
os.unlink(temp_name)
|
|
107
|
+
return path
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def load_file(path: Path) -> Dict[str, str]:
|
|
111
|
+
"""Read known settings without silently discarding malformed values."""
|
|
112
|
+
try:
|
|
113
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
114
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
115
|
+
raise ValueError("Cannot read Commitron config at {}: {}".format(path, exc)) from exc
|
|
116
|
+
if not isinstance(data, dict):
|
|
117
|
+
raise ValueError("Commitron config must contain a JSON object.")
|
|
118
|
+
settings: Dict[str, str] = {}
|
|
119
|
+
for key in DEFAULTS:
|
|
120
|
+
if key not in data or data[key] is None:
|
|
121
|
+
continue
|
|
122
|
+
if not isinstance(data[key], str):
|
|
123
|
+
raise ValueError("Config value '{}' must be a string.".format(key))
|
|
124
|
+
settings[key] = data[key]
|
|
125
|
+
return settings
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _validate_base_url(value: str) -> None:
|
|
129
|
+
if not value:
|
|
130
|
+
return
|
|
131
|
+
parsed = urlsplit(value)
|
|
132
|
+
if any(char.isspace() or ord(char) < 32 or ord(char) == 127 for char in value):
|
|
133
|
+
raise ValueError("base_url cannot contain whitespace or control characters.")
|
|
134
|
+
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
|
135
|
+
raise ValueError("base_url must be an absolute http:// or https:// URL.")
|
|
136
|
+
if parsed.query or parsed.fragment:
|
|
137
|
+
raise ValueError("base_url cannot contain a query string or fragment.")
|
|
138
|
+
try:
|
|
139
|
+
parsed.port # Force validation of malformed or out-of-range ports.
|
|
140
|
+
except ValueError as exc:
|
|
141
|
+
raise ValueError("base_url contains an invalid port.") from exc
|
|
142
|
+
if parsed.username or parsed.password:
|
|
143
|
+
raise ValueError("Do not put credentials in base_url; use the provider's environment variable.")
|
|
144
|
+
local_hosts = {"localhost", "127.0.0.1", "::1"}
|
|
145
|
+
if parsed.scheme == "http" and parsed.hostname not in local_hosts:
|
|
146
|
+
raise ValueError("Non-local base_url must use HTTPS to protect API credentials.")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
PROJECT_CONFIG_NAME = ".commitron.json"
|
|
150
|
+
MAX_CONVENTION_CHARS = 1000
|
|
151
|
+
|
|
152
|
+
def load_project_convention(repo_root: Path) -> str:
|
|
153
|
+
"""Load repository-local commit guidance, if configured."""
|
|
154
|
+
path = Path(repo_root) / PROJECT_CONFIG_NAME
|
|
155
|
+
if path.is_symlink():
|
|
156
|
+
raise ValueError("Refusing to read a symlinked project config file.")
|
|
157
|
+
if not path.exists():
|
|
158
|
+
return ""
|
|
159
|
+
try:
|
|
160
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
161
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
162
|
+
raise ValueError("Cannot read project Commitron config at {}: {}".format(path, exc)) from exc
|
|
163
|
+
if not isinstance(data, dict):
|
|
164
|
+
raise ValueError("Project Commitron config must contain a JSON object.")
|
|
165
|
+
convention = data.get("commit_convention", "")
|
|
166
|
+
if not isinstance(convention, str):
|
|
167
|
+
raise ValueError("Project commit_convention must be a string.")
|
|
168
|
+
convention = convention.strip()
|
|
169
|
+
if len(convention) > MAX_CONVENTION_CHARS:
|
|
170
|
+
raise ValueError("Project commit convention cannot exceed {} characters.".format(MAX_CONVENTION_CHARS))
|
|
171
|
+
return convention
|
|
172
|
+
|
|
173
|
+
def save_project_convention(repo_root: Path, convention: str) -> Path:
|
|
174
|
+
"""Atomically save repository-local commit guidance in .commitron.json."""
|
|
175
|
+
if not isinstance(convention, str):
|
|
176
|
+
raise ValueError("Project commit convention must be a string.")
|
|
177
|
+
convention = convention.strip()
|
|
178
|
+
if len(convention) > MAX_CONVENTION_CHARS:
|
|
179
|
+
raise ValueError("Project commit convention cannot exceed {} characters.".format(MAX_CONVENTION_CHARS))
|
|
180
|
+
path = Path(repo_root) / PROJECT_CONFIG_NAME
|
|
181
|
+
if path.is_symlink():
|
|
182
|
+
raise ValueError("Refusing to overwrite a symlinked project config file.")
|
|
183
|
+
existing = {}
|
|
184
|
+
if path.exists():
|
|
185
|
+
try:
|
|
186
|
+
existing = json.loads(path.read_text(encoding="utf-8"))
|
|
187
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
188
|
+
raise ValueError("Cannot update project Commitron config at {}: {}".format(path, exc)) from exc
|
|
189
|
+
if not isinstance(existing, dict):
|
|
190
|
+
raise ValueError("Project Commitron config must contain a JSON object.")
|
|
191
|
+
if convention:
|
|
192
|
+
existing["commit_convention"] = convention
|
|
193
|
+
else:
|
|
194
|
+
existing.pop("commit_convention", None)
|
|
195
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
196
|
+
fd, temp_name = tempfile.mkstemp(prefix="commitron-", suffix=".tmp", dir=str(path.parent))
|
|
197
|
+
try:
|
|
198
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
199
|
+
json.dump(existing, handle, indent=2, ensure_ascii=False)
|
|
200
|
+
handle.write("\n")
|
|
201
|
+
if os.name != "nt":
|
|
202
|
+
try:
|
|
203
|
+
os.chmod(temp_name, 0o600)
|
|
204
|
+
except OSError:
|
|
205
|
+
pass
|
|
206
|
+
os.replace(temp_name, path)
|
|
207
|
+
finally:
|
|
208
|
+
if os.path.exists(temp_name):
|
|
209
|
+
os.unlink(temp_name)
|
|
210
|
+
return path
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
PROFILE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$")
|
|
214
|
+
|
|
215
|
+
def profiles_path() -> Path:
|
|
216
|
+
"""Return the per-user profile store next to the main config file."""
|
|
217
|
+
return config_path().with_name("profiles.json")
|
|
218
|
+
|
|
219
|
+
def _read_profiles() -> Dict[str, Dict[str, str]]:
|
|
220
|
+
path = profiles_path()
|
|
221
|
+
if not path.exists():
|
|
222
|
+
return {}
|
|
223
|
+
try:
|
|
224
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
225
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
226
|
+
raise ValueError("Cannot read Commitron profiles at {}: {}".format(path, exc)) from exc
|
|
227
|
+
if not isinstance(raw, dict):
|
|
228
|
+
raise ValueError("Commitron profiles must contain a JSON object.")
|
|
229
|
+
profiles: Dict[str, Dict[str, str]] = {}
|
|
230
|
+
for name, values in raw.items():
|
|
231
|
+
if not isinstance(name, str) or not PROFILE_NAME_RE.fullmatch(name):
|
|
232
|
+
raise ValueError("Invalid profile name in {}.".format(path))
|
|
233
|
+
if not isinstance(values, dict) or set(values) - set(DEFAULTS):
|
|
234
|
+
raise ValueError("Profile '{}' contains unsupported settings.".format(name))
|
|
235
|
+
if any(not isinstance(v, str) for v in values.values()):
|
|
236
|
+
raise ValueError("Profile '{}' settings must be strings.".format(name))
|
|
237
|
+
profiles[name] = {key: values.get(key, DEFAULTS[key]) for key in DEFAULTS}
|
|
238
|
+
provider = profiles[name]["provider"].lower()
|
|
239
|
+
if provider not in PROVIDERS:
|
|
240
|
+
raise ValueError("Profile '{}' has an unsupported provider. Supported: {}.".format(name, ", ".join(sorted(PROVIDERS))))
|
|
241
|
+
profiles[name]["provider"] = provider
|
|
242
|
+
_validate_base_url(profiles[name]["base_url"])
|
|
243
|
+
return profiles
|
|
244
|
+
|
|
245
|
+
def list_profiles() -> Dict[str, Dict[str, str]]:
|
|
246
|
+
"""Return validated named provider profiles."""
|
|
247
|
+
return _read_profiles()
|
|
248
|
+
|
|
249
|
+
def save_profile(name: str) -> Path:
|
|
250
|
+
"""Save current effective provider settings under a non-secret profile name."""
|
|
251
|
+
if not isinstance(name, str) or not PROFILE_NAME_RE.fullmatch(name):
|
|
252
|
+
raise ValueError("Profile name must be 1–32 letters, numbers, '_' or '-', and start with a letter or number.")
|
|
253
|
+
current = load_config()
|
|
254
|
+
profiles = _read_profiles()
|
|
255
|
+
profiles[name] = {key: current[key] for key in DEFAULTS}
|
|
256
|
+
return _write_profiles(profiles)
|
|
257
|
+
|
|
258
|
+
def use_profile(name: str) -> Path:
|
|
259
|
+
"""Apply a saved profile to the active config; environment overrides still take precedence."""
|
|
260
|
+
profiles = _read_profiles()
|
|
261
|
+
if name not in profiles:
|
|
262
|
+
raise ValueError("No profile named '{}'. Use 'commitron config profile list'.".format(name))
|
|
263
|
+
return save_config(profiles[name])
|
|
264
|
+
|
|
265
|
+
def delete_profile(name: str) -> Path:
|
|
266
|
+
profiles = _read_profiles()
|
|
267
|
+
if name not in profiles:
|
|
268
|
+
raise ValueError("No profile named '{}'.".format(name))
|
|
269
|
+
del profiles[name]
|
|
270
|
+
return _write_profiles(profiles)
|
|
271
|
+
|
|
272
|
+
def _write_profiles(profiles: Dict[str, Dict[str, str]]) -> Path:
|
|
273
|
+
path = profiles_path()
|
|
274
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
275
|
+
fd, temp_name = tempfile.mkstemp(prefix="profiles-", suffix=".tmp", dir=str(path.parent))
|
|
276
|
+
try:
|
|
277
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
278
|
+
json.dump(profiles, handle, indent=2, sort_keys=True)
|
|
279
|
+
handle.write("\n")
|
|
280
|
+
if os.name != "nt":
|
|
281
|
+
try:
|
|
282
|
+
os.chmod(temp_name, 0o600)
|
|
283
|
+
except OSError:
|
|
284
|
+
pass
|
|
285
|
+
os.replace(temp_name, path)
|
|
286
|
+
finally:
|
|
287
|
+
if os.path.exists(temp_name):
|
|
288
|
+
os.unlink(temp_name)
|
|
289
|
+
return path
|
commitron/credentials.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Optional OS-backed credential storage; environment variables take precedence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import importlib
|
|
5
|
+
import os
|
|
6
|
+
import unicodedata
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
SERVICE_NAME = "commitron"
|
|
11
|
+
PROVIDER_ENV = {
|
|
12
|
+
"gemini": "GEMINI_API_KEY",
|
|
13
|
+
"openai": "OPENAI_API_KEY",
|
|
14
|
+
"anthropic": "ANTHROPIC_API_KEY",
|
|
15
|
+
"groq": "GROQ_API_KEY",
|
|
16
|
+
"deepseek": "DEEPSEEK_API_KEY",
|
|
17
|
+
"openrouter": "OPENROUTER_API_KEY",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CredentialError(RuntimeError):
|
|
22
|
+
"""Raised when secure credential storage is unavailable or fails."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _keyring_module():
|
|
26
|
+
try:
|
|
27
|
+
module = importlib.import_module("keyring")
|
|
28
|
+
except ImportError as exc:
|
|
29
|
+
raise CredentialError(
|
|
30
|
+
"Secure credential storage is optional. Install it with: "
|
|
31
|
+
"python -m pip install 'commitron[secure-store]'"
|
|
32
|
+
) from exc
|
|
33
|
+
try:
|
|
34
|
+
backend = module.get_keyring()
|
|
35
|
+
backend_name = (backend.__class__.__module__ + "." + backend.__class__.__name__).lower()
|
|
36
|
+
priority = float(getattr(backend, "priority", 0))
|
|
37
|
+
except Exception as exc:
|
|
38
|
+
raise CredentialError("Could not inspect the operating-system credential backend.") from exc
|
|
39
|
+
if priority <= 0 or any(token in backend_name for token in ("plaintext", "fail", "null", "chainer")):
|
|
40
|
+
raise CredentialError(
|
|
41
|
+
"No supported secure OS credential backend is active. Configure the system keychain "
|
|
42
|
+
"or use the provider's environment variable instead."
|
|
43
|
+
)
|
|
44
|
+
return module
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _validated_value(value: object) -> str:
|
|
48
|
+
"""Validate opaque API-key text before it reaches an HTTP header or keychain."""
|
|
49
|
+
if not isinstance(value, str):
|
|
50
|
+
raise CredentialError("Credential must be text.")
|
|
51
|
+
cleaned = value.strip()
|
|
52
|
+
if not cleaned:
|
|
53
|
+
raise CredentialError("Credential cannot be empty.")
|
|
54
|
+
if len(cleaned) > 4096:
|
|
55
|
+
raise CredentialError("Credential is unexpectedly long (maximum 4096 characters).")
|
|
56
|
+
if any(unicodedata.category(char) == "Cc" for char in cleaned):
|
|
57
|
+
raise CredentialError("Credential cannot contain control characters or line breaks.")
|
|
58
|
+
return cleaned
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def get_credential(provider: str) -> Optional[str]:
|
|
62
|
+
"""Return environment credential first, then an optional OS keychain value."""
|
|
63
|
+
if provider == "ollama":
|
|
64
|
+
return None
|
|
65
|
+
env_name = PROVIDER_ENV.get(provider)
|
|
66
|
+
if not env_name:
|
|
67
|
+
raise CredentialError("Unsupported credential provider.")
|
|
68
|
+
value = os.environ.get(env_name, "")
|
|
69
|
+
if value.strip():
|
|
70
|
+
return _validated_value(value)
|
|
71
|
+
try:
|
|
72
|
+
module = _keyring_module()
|
|
73
|
+
saved = module.get_password(SERVICE_NAME, provider)
|
|
74
|
+
except CredentialError:
|
|
75
|
+
# A missing optional keyring must not break environment-only workflows.
|
|
76
|
+
return None
|
|
77
|
+
except Exception as exc:
|
|
78
|
+
raise CredentialError("Could not read the saved credential from the OS keychain.") from exc
|
|
79
|
+
return _validated_value(saved) if saved is not None else None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def set_credential(provider: str, value: str) -> None:
|
|
83
|
+
if provider not in PROVIDER_ENV:
|
|
84
|
+
raise CredentialError(
|
|
85
|
+
"Cannot store credentials for '{}'. Commitron supports API-key storage for "
|
|
86
|
+
"Gemini, OpenAI, Anthropic, Groq, DeepSeek, and OpenRouter.".format(provider)
|
|
87
|
+
)
|
|
88
|
+
cleaned = _validated_value(value)
|
|
89
|
+
module = _keyring_module()
|
|
90
|
+
try:
|
|
91
|
+
module.set_password(SERVICE_NAME, provider, cleaned)
|
|
92
|
+
except Exception as exc:
|
|
93
|
+
raise CredentialError("Could not save the credential to the OS keychain.") from exc
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def delete_credential(provider: str) -> bool:
|
|
97
|
+
if provider not in PROVIDER_ENV:
|
|
98
|
+
raise CredentialError(
|
|
99
|
+
"Cannot delete credentials for '{}'. Supported: Gemini, OpenAI, Anthropic, "
|
|
100
|
+
"Groq, DeepSeek, OpenRouter.".format(provider)
|
|
101
|
+
)
|
|
102
|
+
module = _keyring_module()
|
|
103
|
+
try:
|
|
104
|
+
module.delete_password(SERVICE_NAME, provider)
|
|
105
|
+
return True
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
raise CredentialError("Could not delete the credential from the OS keychain.") from exc
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def credential_status(provider: str) -> str:
|
|
111
|
+
env_name = PROVIDER_ENV.get(provider)
|
|
112
|
+
if provider == "ollama":
|
|
113
|
+
return "not required (local provider)"
|
|
114
|
+
if not env_name:
|
|
115
|
+
raise CredentialError("Unsupported credential provider.")
|
|
116
|
+
if os.environ.get(env_name, "").strip():
|
|
117
|
+
return "environment variable configured"
|
|
118
|
+
try:
|
|
119
|
+
module = _keyring_module()
|
|
120
|
+
return "saved in OS keychain" if module.get_password(SERVICE_NAME, provider) else "not configured"
|
|
121
|
+
except CredentialError:
|
|
122
|
+
return "not configured (install secure-store extra for keychain support)"
|
|
123
|
+
except Exception:
|
|
124
|
+
return "keychain unavailable"
|
commitron/git_ops.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Git operations. All subprocess calls use argument arrays (never a shell)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import subprocess
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import List
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class GitError(RuntimeError):
|
|
10
|
+
"""Raised when a Git command fails."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class GitResult:
|
|
15
|
+
stdout: str
|
|
16
|
+
stderr: str
|
|
17
|
+
returncode: int
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def run_git(*args: str, check: bool = True) -> GitResult:
|
|
21
|
+
try:
|
|
22
|
+
proc = subprocess.run(
|
|
23
|
+
["git", *args], capture_output=True, text=True,
|
|
24
|
+
encoding="utf-8", errors="replace", timeout=30, check=False,
|
|
25
|
+
)
|
|
26
|
+
except FileNotFoundError as exc:
|
|
27
|
+
raise GitError("Git executable was not found. Install Git and ensure it is on PATH.") from exc
|
|
28
|
+
except subprocess.TimeoutExpired as exc:
|
|
29
|
+
raise GitError("Git command timed out after 30 seconds.") from exc
|
|
30
|
+
result = GitResult(proc.stdout, proc.stderr, proc.returncode)
|
|
31
|
+
if check and proc.returncode:
|
|
32
|
+
detail = proc.stderr.strip() or proc.stdout.strip() or "Unknown Git error"
|
|
33
|
+
raise GitError(detail)
|
|
34
|
+
return result
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def ensure_repo() -> None:
|
|
38
|
+
run_git("rev-parse", "--is-inside-work-tree")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def staged_diff() -> str:
|
|
42
|
+
return run_git("diff", "--cached", "--no-ext-diff", "--no-color").stdout
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def unstaged_diff() -> str:
|
|
46
|
+
return run_git("diff", "--no-ext-diff", "--no-color").stdout
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def diff_stat(staged: bool = True) -> str:
|
|
50
|
+
args = ["diff"]
|
|
51
|
+
if staged:
|
|
52
|
+
args.append("--cached")
|
|
53
|
+
args.extend(["--stat", "--no-ext-diff"])
|
|
54
|
+
return run_git(*args).stdout
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def files_changed(staged: bool = True) -> List[str]:
|
|
58
|
+
args = ["diff"]
|
|
59
|
+
if staged:
|
|
60
|
+
args.append("--cached")
|
|
61
|
+
args.extend(["--name-only", "-z"])
|
|
62
|
+
output = run_git(*args).stdout
|
|
63
|
+
return [name for name in output.split("\0") if name]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def status_porcelain() -> str:
|
|
67
|
+
return run_git("status", "--short", "--branch").stdout
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def current_branch() -> str:
|
|
71
|
+
result = run_git("branch", "--show-current", check=False)
|
|
72
|
+
if result.returncode:
|
|
73
|
+
raise GitError(result.stderr.strip() or "Could not determine current branch")
|
|
74
|
+
return result.stdout.strip() or "(detached HEAD)"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def history(limit: int = 10) -> str:
|
|
78
|
+
return run_git("log", f"-{limit}", "--date=short", "--pretty=format:%h %ad %s").stdout
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def branches() -> str:
|
|
82
|
+
return run_git("branch", "--list", "--no-color").stdout
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def create_branch(name: str) -> None:
|
|
86
|
+
validate_branch_name(name)
|
|
87
|
+
run_git("switch", "-c", name)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def switch_branch(name: str) -> None:
|
|
91
|
+
validate_branch_name(name)
|
|
92
|
+
run_git("switch", name)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def commit(message: str) -> GitResult:
|
|
96
|
+
if not message.strip():
|
|
97
|
+
raise GitError("Commit message cannot be empty")
|
|
98
|
+
return run_git("commit", "-m", message, check=False)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def changed_files() -> List[str]:
|
|
102
|
+
output = run_git("diff", "--cached", "--name-only", "-z").stdout
|
|
103
|
+
return [name for name in output.split("\0") if name]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def repository_root() -> str:
|
|
107
|
+
"""Return the absolute root directory of the current Git repository."""
|
|
108
|
+
result = run_git("rev-parse", "--show-toplevel")
|
|
109
|
+
root = result.stdout.strip()
|
|
110
|
+
if not root:
|
|
111
|
+
raise GitError("Could not determine the Git repository root.")
|
|
112
|
+
return root
|
|
113
|
+
|
|
114
|
+
def validate_branch_name(name: str) -> None:
|
|
115
|
+
"""Raise GitError when a proposed branch name is not valid for Git."""
|
|
116
|
+
if not name or name.startswith("-") or any(ord(char) < 32 or ord(char) == 127 for char in name):
|
|
117
|
+
raise GitError("Invalid branch name returned by the AI provider.")
|
|
118
|
+
result = run_git("check-ref-format", "--branch", name, check=False)
|
|
119
|
+
if result.returncode:
|
|
120
|
+
raise GitError("AI suggested an invalid Git branch name: {}".format(name))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def history_entries(limit: int = 20) -> List[dict]:
|
|
124
|
+
"""Return structured recent commit metadata without invoking a shell."""
|
|
125
|
+
if not 1 <= limit <= 100:
|
|
126
|
+
raise GitError("History limit must be between 1 and 100.")
|
|
127
|
+
fmt = "%H%x00%ad%x00%s%x00%b%x1e"
|
|
128
|
+
output = run_git(
|
|
129
|
+
"log", "-{}".format(limit), "--date=short", "--no-show-signature",
|
|
130
|
+
"--pretty=format:" + fmt,
|
|
131
|
+
).stdout
|
|
132
|
+
entries = []
|
|
133
|
+
for record in output.split("\x1e"):
|
|
134
|
+
record = record.strip("\r\n")
|
|
135
|
+
if not record:
|
|
136
|
+
continue
|
|
137
|
+
fields = record.split("\x00", 3)
|
|
138
|
+
if len(fields) != 4:
|
|
139
|
+
raise GitError("Git returned an unexpected history record format.")
|
|
140
|
+
commit_hash, date, subject, body = fields
|
|
141
|
+
entries.append({
|
|
142
|
+
"hash": commit_hash.strip(),
|
|
143
|
+
"date": date.strip(),
|
|
144
|
+
"subject": subject.strip(),
|
|
145
|
+
"body": body.strip(),
|
|
146
|
+
})
|
|
147
|
+
return entries
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def worktree_changes() -> List[dict]:
|
|
151
|
+
"""Return staged, unstaged, and untracked paths using NUL-delimited status.
|
|
152
|
+
|
|
153
|
+
Rename detection is disabled so each status record has one unambiguous path.
|
|
154
|
+
"""
|
|
155
|
+
output = run_git(
|
|
156
|
+
"status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"
|
|
157
|
+
).stdout
|
|
158
|
+
changes = []
|
|
159
|
+
for record in output.split("\0"):
|
|
160
|
+
if not record:
|
|
161
|
+
continue
|
|
162
|
+
if len(record) < 4 or record[2] != " ":
|
|
163
|
+
raise GitError("Git returned an unexpected status record.")
|
|
164
|
+
changes.append({"status": record[:2], "path": record[3:]})
|
|
165
|
+
return changes
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def stage_paths(paths: List[str]) -> GitResult:
|
|
169
|
+
"""Stage only explicitly supplied paths, treating them as literal pathspecs."""
|
|
170
|
+
if not paths:
|
|
171
|
+
raise GitError("Select at least one path to stage.")
|
|
172
|
+
if any(not isinstance(path, str) or not path or "\0" in path for path in paths):
|
|
173
|
+
raise GitError("A selected path is invalid.")
|
|
174
|
+
unique_paths = list(dict.fromkeys(paths))
|
|
175
|
+
return run_git("--literal-pathspecs", "add", "--", *unique_paths)
|