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/cli.py
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
"""Command-line interface for Commitron."""
|
|
2
|
+
import argparse
|
|
3
|
+
import getpass
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import List
|
|
8
|
+
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
from rich.panel import Panel
|
|
11
|
+
from rich.prompt import Confirm, Prompt
|
|
12
|
+
from rich.text import Text
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .ai import (AIError, MAX_DIFF_CHUNKS, explain_changes, explain_git_error, generate_messages,
|
|
16
|
+
split_diff, suggest_branch_name, suggest_logical_commits, summarize_history)
|
|
17
|
+
from .git_ops import (GitError, branches, commit, create_branch, current_branch,
|
|
18
|
+
diff_stat, ensure_repo, files_changed, history, history_entries, run_git,
|
|
19
|
+
staged_diff, status_porcelain, switch_branch, unstaged_diff, repository_root,
|
|
20
|
+
worktree_changes, stage_paths)
|
|
21
|
+
from .safety import find_secret_warnings
|
|
22
|
+
from .credentials import (CredentialError, credential_status, set_credential, delete_credential, PROVIDER_ENV)
|
|
23
|
+
from .config import (config_path, load_config, save_config, load_project_convention,
|
|
24
|
+
save_project_convention, list_profiles, save_profile, use_profile, delete_profile)
|
|
25
|
+
|
|
26
|
+
console = Console()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
# Helper: list all provider names known to Commitron
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
def _auth_providers() -> List[str]:
|
|
33
|
+
"""Return the list of providers that accept an API key (auth commands)."""
|
|
34
|
+
from .providers import PROVIDERS, PROVIDER_KEY_VARS
|
|
35
|
+
return sorted(k for k in PROVIDERS if PROVIDER_KEY_VARS.get(k))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _parser() -> argparse.ArgumentParser:
|
|
39
|
+
parser = argparse.ArgumentParser(prog="commitron", description="A safer AI-powered Git assistant")
|
|
40
|
+
parser.add_argument("--version", action="version", version=f"Commitron {__version__}")
|
|
41
|
+
parser.add_argument("--verbose", "-v", action="store_true", help="Print detailed AI request/debug output")
|
|
42
|
+
sub = parser.add_subparsers(dest="command")
|
|
43
|
+
|
|
44
|
+
commit_parser = sub.add_parser("commit", help="Generate a commit message from staged changes")
|
|
45
|
+
commit_parser.add_argument("--verbose", "-v", action="store_true", help="Print detailed AI request/debug output")
|
|
46
|
+
commit_parser.add_argument("--dry-run", action="store_true", help="Preview only; never create a commit")
|
|
47
|
+
commit_parser.add_argument("--style", choices=["conventional", "gitmoji", "plain"], default="conventional")
|
|
48
|
+
commit_parser.add_argument("--count", type=int, default=3)
|
|
49
|
+
commit_parser.add_argument("-y", "--yes", action="store_true", help="Skip final commit confirmation")
|
|
50
|
+
commit_parser.add_argument("--allow-secrets", action="store_true", help="Skip the heuristic secret warning")
|
|
51
|
+
|
|
52
|
+
auth_parser = sub.add_parser("auth", help="Manage API credentials in the OS keychain")
|
|
53
|
+
auth_sub = auth_parser.add_subparsers(dest="auth_action", required=True)
|
|
54
|
+
auth_set = auth_sub.add_parser("set", help="Save a provider API key in the OS keychain")
|
|
55
|
+
auth_set.add_argument("provider", choices=_auth_providers(),
|
|
56
|
+
help="API key provider. (Ollama has no API key to store; set the model via 'commitron config'.)")
|
|
57
|
+
auth_delete = auth_sub.add_parser("delete", help="Delete a provider API key from the OS keychain")
|
|
58
|
+
auth_delete.add_argument("provider", choices=_auth_providers())
|
|
59
|
+
auth_sub.add_parser("status", help="Show credential availability without revealing secrets")
|
|
60
|
+
|
|
61
|
+
sub.add_parser("menu", help="Open the interactive terminal menu")
|
|
62
|
+
sub.add_parser("status", help="Show Git status and current branch")
|
|
63
|
+
sub.add_parser("doctor", help="Check environment health: Git, config, credentials, provider reachability")
|
|
64
|
+
sub.add_parser("stage", help="Interactively stage only selected changed paths")
|
|
65
|
+
diff_parser = sub.add_parser("diff", help="Show a Git diff")
|
|
66
|
+
diff_parser.add_argument("--unstaged", action="store_true", help="Show unstaged working-tree changes")
|
|
67
|
+
diff_parser.add_argument("--stat", action="store_true", help="Show a compact change summary")
|
|
68
|
+
explain_parser = sub.add_parser("explain", help="Explain staged changes with the configured AI provider")
|
|
69
|
+
explain_parser.add_argument("--verbose", "-v", action="store_true", help="Print detailed AI request/debug output")
|
|
70
|
+
explain_parser.add_argument("--unstaged", action="store_true", help="Explain unstaged working-tree changes instead")
|
|
71
|
+
explain_parser.add_argument("--allow-secrets", action="store_true", help="Skip the heuristic secret warning")
|
|
72
|
+
files_parser = sub.add_parser("files", help="List files changed in the Git index or working tree")
|
|
73
|
+
files_parser.add_argument("--unstaged", action="store_true", help="List unstaged changes")
|
|
74
|
+
config_parser = sub.add_parser("config", help="View or update local Commitron settings")
|
|
75
|
+
config_sub = config_parser.add_subparsers(dest="config_action", required=True)
|
|
76
|
+
config_sub.add_parser("show", help="Show effective configuration (API keys are never stored)")
|
|
77
|
+
config_sub.add_parser("path", help="Print the configuration file location")
|
|
78
|
+
config_sub.add_parser("wizard", help="Interactively configure the AI provider")
|
|
79
|
+
profile_parser = config_sub.add_parser("profile", help="Save and switch named provider profiles")
|
|
80
|
+
profile_sub = profile_parser.add_subparsers(dest="profile_action", required=True)
|
|
81
|
+
profile_sub.add_parser("list", help="List saved profiles")
|
|
82
|
+
profile_save = profile_sub.add_parser("save", help="Save current settings as a profile")
|
|
83
|
+
profile_save.add_argument("name")
|
|
84
|
+
profile_use = profile_sub.add_parser("use", help="Apply a saved profile")
|
|
85
|
+
profile_use.add_argument("name")
|
|
86
|
+
profile_delete = profile_sub.add_parser("delete", help="Delete a saved profile")
|
|
87
|
+
profile_delete.add_argument("name")
|
|
88
|
+
set_parser = config_sub.add_parser("set", help="Set provider, model, or base_url")
|
|
89
|
+
set_parser.add_argument("key", choices=["provider", "model", "base_url"])
|
|
90
|
+
set_parser.add_argument("value")
|
|
91
|
+
log_parser = sub.add_parser("history", help="Show recent commits")
|
|
92
|
+
log_parser.add_argument("--verbose", "-v", action="store_true", help="Print detailed AI request/debug output")
|
|
93
|
+
log_parser.add_argument("-n", "--limit", type=int, default=10)
|
|
94
|
+
log_parser.add_argument("--analyze", action="store_true", help="Summarize recent commit history with AI")
|
|
95
|
+
helper_parser = sub.add_parser("git-help", help="Explain a Git error and suggest safe diagnostic steps")
|
|
96
|
+
helper_parser.add_argument("--verbose", "-v", action="store_true", help="Print detailed AI request/debug output")
|
|
97
|
+
helper_parser.add_argument("--error", required=True, help="Paste the Git error message")
|
|
98
|
+
helper_parser.add_argument("--context", default="", help="Optional command or situation context")
|
|
99
|
+
branch_parser = sub.add_parser("branch", help="List, create, or switch branches")
|
|
100
|
+
branch_parser.add_argument("--verbose", "-v", action="store_true", help="Print detailed AI request/debug output")
|
|
101
|
+
branch_parser.add_argument("action", nargs="?", choices=["create", "switch", "suggest"])
|
|
102
|
+
branch_parser.add_argument("name", nargs="?")
|
|
103
|
+
branch_parser.add_argument("--description", "-d", help="Task description for an AI branch-name suggestion")
|
|
104
|
+
|
|
105
|
+
split_parser = sub.add_parser("split", help="Suggest logical commit groups from staged files; does not stage or commit")
|
|
106
|
+
split_parser.add_argument("--verbose", "-v", action="store_true", help="Print detailed AI request/debug output")
|
|
107
|
+
split_parser.add_argument("--style", choices=["conventional", "gitmoji", "plain"], default="conventional")
|
|
108
|
+
split_parser.add_argument("--allow-secrets", action="store_true", help="Skip the heuristic secret warning")
|
|
109
|
+
|
|
110
|
+
convention_parser = sub.add_parser("convention", help="Manage repository-specific commit conventions")
|
|
111
|
+
convention_sub = convention_parser.add_subparsers(dest="convention_action", required=True)
|
|
112
|
+
convention_sub.add_parser("show", help="Show the current repository convention")
|
|
113
|
+
convention_set = convention_sub.add_parser("set", help="Save commit-message guidance in .commitron.json")
|
|
114
|
+
convention_set.add_argument("text", help="Project-specific commit-message instructions")
|
|
115
|
+
convention_sub.add_parser("clear", help="Remove the repository-specific commit convention")
|
|
116
|
+
return parser
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _commit_command(args: argparse.Namespace) -> int:
|
|
120
|
+
if not 1 <= args.count <= 5:
|
|
121
|
+
console.print("[red]--count must be between 1 and 5.[/red]")
|
|
122
|
+
return 2
|
|
123
|
+
diff = staged_diff()
|
|
124
|
+
if not diff.strip():
|
|
125
|
+
console.print("[yellow]No staged changes found. Stage only the files you intend to commit, then retry.[/yellow]")
|
|
126
|
+
console.print("[dim]Commitron never runs 'git add .' automatically.[/dim]")
|
|
127
|
+
return 1
|
|
128
|
+
chunk_count = len(split_diff(diff))
|
|
129
|
+
if chunk_count > MAX_DIFF_CHUNKS:
|
|
130
|
+
console.print(Text(
|
|
131
|
+
"Staged diff exceeds the safe processing limit ({} chunks; maximum {}). "
|
|
132
|
+
"No diff content was sent. Split the changes into smaller commits.".format(
|
|
133
|
+
chunk_count, MAX_DIFF_CHUNKS
|
|
134
|
+
), style="yellow"
|
|
135
|
+
))
|
|
136
|
+
return 1
|
|
137
|
+
if chunk_count > 1:
|
|
138
|
+
console.print(Text(
|
|
139
|
+
"Large diff: Commitron will analyze all {} chunks in separate AI requests, "
|
|
140
|
+
"then combine their summaries. This may use more provider quota.".format(chunk_count),
|
|
141
|
+
style="yellow"
|
|
142
|
+
))
|
|
143
|
+
if not Confirm.ask("Send the complete staged diff for analysis?", default=False):
|
|
144
|
+
return 1
|
|
145
|
+
try:
|
|
146
|
+
convention = load_project_convention(Path(repository_root()))
|
|
147
|
+
warnings = find_secret_warnings(diff + "\n" + convention)
|
|
148
|
+
if warnings and not args.allow_secrets:
|
|
149
|
+
console.print(Panel("Possible sensitive content detected: " + ", ".join(warnings), title="Privacy warning", border_style="yellow"))
|
|
150
|
+
console.print("[yellow]The staged diff and project convention may be sent to the configured AI provider.[/yellow]")
|
|
151
|
+
if not Confirm.ask("Send this content anyway?", default=False):
|
|
152
|
+
return 1
|
|
153
|
+
with console.status("[bold green]Generating commit message options..."):
|
|
154
|
+
options = generate_messages(diff, args.count, args.style, convention, verbose=bool(args.verbose))
|
|
155
|
+
except AIError as exc:
|
|
156
|
+
console.print(Text("AI error: " + str(exc), style="red"))
|
|
157
|
+
return 1
|
|
158
|
+
console.print(Panel(Text("\n".join("{}. {}".format(i, msg) for i, msg in enumerate(options, 1))), title="Suggested commit messages"))
|
|
159
|
+
if args.yes:
|
|
160
|
+
message = options[0]
|
|
161
|
+
else:
|
|
162
|
+
choices = [str(i) for i in range(1, len(options) + 1)] + ["e", "c"]
|
|
163
|
+
choice = Prompt.ask("Choose a number, e to edit, or c to cancel", choices=choices, default="1")
|
|
164
|
+
if choice == "c":
|
|
165
|
+
console.print("Cancelled.")
|
|
166
|
+
return 0
|
|
167
|
+
message = Prompt.ask("Commit message") if choice == "e" else options[int(choice) - 1]
|
|
168
|
+
if args.dry_run:
|
|
169
|
+
console.print(Panel(Text(message), title="Dry run — no commit created", border_style="blue"))
|
|
170
|
+
return 0
|
|
171
|
+
if not args.yes and not Confirm.ask("Create commit with the selected message?", default=False):
|
|
172
|
+
console.print("Cancelled.")
|
|
173
|
+
return 0
|
|
174
|
+
result = commit(message)
|
|
175
|
+
if result.returncode:
|
|
176
|
+
console.print(Text("Git commit failed: " + (result.stderr.strip() or result.stdout.strip()), style="red"))
|
|
177
|
+
return result.returncode or 1
|
|
178
|
+
console.print("[green]Commit created successfully.[/green]")
|
|
179
|
+
if result.stdout.strip():
|
|
180
|
+
console.print(Text(result.stdout.strip()))
|
|
181
|
+
return 0
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _doctor_command() -> int:
|
|
185
|
+
"""Report environment health: Git, Python, config, credentials, provider reachability."""
|
|
186
|
+
import platform
|
|
187
|
+
from .providers import PROVIDER_KEY_VARS, DEFAULT_URLS
|
|
188
|
+
|
|
189
|
+
issues = 0
|
|
190
|
+
|
|
191
|
+
def check(label: str, ok: bool, detail: str) -> None:
|
|
192
|
+
nonlocal issues
|
|
193
|
+
if not ok:
|
|
194
|
+
issues += 1
|
|
195
|
+
console.print(Text("{:24} {} {}".format(
|
|
196
|
+
label, "[green]OK[/green]" if ok else "[red]FAIL[/red]", detail)))
|
|
197
|
+
|
|
198
|
+
# Python version
|
|
199
|
+
py_ok = sys.version_info >= (3, 11)
|
|
200
|
+
check("Python", py_ok, "{} on {}".format(platform.python_version(), platform.system()))
|
|
201
|
+
|
|
202
|
+
# Git executable + repository
|
|
203
|
+
try:
|
|
204
|
+
git_result = run_git("--version")
|
|
205
|
+
check("Git", True, git_result.stdout.strip())
|
|
206
|
+
except GitError as exc:
|
|
207
|
+
check("Git", False, str(exc))
|
|
208
|
+
try:
|
|
209
|
+
ensure_repo()
|
|
210
|
+
check("Repository", True, "inside a Git working tree")
|
|
211
|
+
except GitError:
|
|
212
|
+
check("Repository", False, "not inside a Git repository (run commitron from a repo)")
|
|
213
|
+
|
|
214
|
+
# Configuration file
|
|
215
|
+
try:
|
|
216
|
+
cfg = load_config()
|
|
217
|
+
check("Config", True, "{} / {} ({})".format(
|
|
218
|
+
cfg["provider"], cfg["model"] or "default model", config_path()))
|
|
219
|
+
except ValueError as exc:
|
|
220
|
+
check("Config", False, str(exc))
|
|
221
|
+
cfg = {"provider": "gemini"}
|
|
222
|
+
|
|
223
|
+
# Credentials for the active provider
|
|
224
|
+
provider = cfg.get("provider", "gemini")
|
|
225
|
+
key_env = PROVIDER_KEY_VARS.get(provider, "")
|
|
226
|
+
if provider == "ollama":
|
|
227
|
+
credential_status("ollama")
|
|
228
|
+
check("Credential", True, "ollama is local; no key required")
|
|
229
|
+
elif key_env and os.environ.get(key_env, "").strip():
|
|
230
|
+
check("Credential", True, "{} set in environment".format(key_env))
|
|
231
|
+
else:
|
|
232
|
+
saved = credential_status(provider) if provider in PROVIDER_ENV else "not configured"
|
|
233
|
+
ok = saved == "saved in OS keychain"
|
|
234
|
+
check("Credential", ok, "{}".format(saved))
|
|
235
|
+
|
|
236
|
+
# Provider reachability (quick TCP connect test; never sends code)
|
|
237
|
+
url = DEFAULT_URLS.get(provider, "")
|
|
238
|
+
if url:
|
|
239
|
+
try:
|
|
240
|
+
import socket
|
|
241
|
+
from urllib.parse import urlsplit
|
|
242
|
+
parsed = urlsplit(url)
|
|
243
|
+
host = parsed.hostname or ""
|
|
244
|
+
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
|
245
|
+
with socket.create_connection((host, port), timeout=5):
|
|
246
|
+
check("Network", True, "{} reachable at {}:{}".format(provider, host, port))
|
|
247
|
+
except OSError as exc:
|
|
248
|
+
check("Network", False, "{} unreachable: {}".format(provider, exc))
|
|
249
|
+
|
|
250
|
+
console.print()
|
|
251
|
+
if issues:
|
|
252
|
+
console.print(Text("{} check(s) failed. Fix them above, then re-run 'commitron doctor'.".format(issues), style="yellow"))
|
|
253
|
+
return 1
|
|
254
|
+
console.print(Text("All checks passed.", style="green"))
|
|
255
|
+
return 0
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _manage_profiles_menu() -> int:
|
|
259
|
+
"""Interactively save, apply, and delete named provider profiles."""
|
|
260
|
+
while True:
|
|
261
|
+
console.print(Panel(Text("Manage provider profiles", style="bold"), title="AI profiles"))
|
|
262
|
+
action = Prompt.ask(
|
|
263
|
+
"Profile action",
|
|
264
|
+
choices=["List", "Save current settings", "Apply profile", "Delete profile", "Back"],
|
|
265
|
+
default="List",
|
|
266
|
+
)
|
|
267
|
+
if action == "Back":
|
|
268
|
+
return 0
|
|
269
|
+
if action == "List":
|
|
270
|
+
profiles = list_profiles()
|
|
271
|
+
if not profiles:
|
|
272
|
+
console.print(Text("No saved profiles."))
|
|
273
|
+
else:
|
|
274
|
+
for name, values in sorted(profiles.items()):
|
|
275
|
+
endpoint = values["base_url"] or "provider default"
|
|
276
|
+
console.print(Text("{} — {} / {} ({})".format(
|
|
277
|
+
name, values["provider"], values["model"] or "default model", endpoint
|
|
278
|
+
)))
|
|
279
|
+
elif action == "Save current settings":
|
|
280
|
+
name = Prompt.ask("New profile name")
|
|
281
|
+
if name in list_profiles() and not Confirm.ask(
|
|
282
|
+
"Profile '{}' already exists. Overwrite it?".format(name), default=False
|
|
283
|
+
):
|
|
284
|
+
console.print("Cancelled.")
|
|
285
|
+
continue
|
|
286
|
+
path = save_profile(name)
|
|
287
|
+
console.print(Text("Saved profile '{}' to {}".format(name, path), style="green"))
|
|
288
|
+
elif action == "Apply profile":
|
|
289
|
+
profiles = list_profiles()
|
|
290
|
+
if not profiles:
|
|
291
|
+
console.print("No profiles to apply.")
|
|
292
|
+
continue
|
|
293
|
+
name = Prompt.ask("Profile to apply", choices=sorted(profiles))
|
|
294
|
+
path = use_profile(name)
|
|
295
|
+
console.print(Text("Applied profile '{}' from {}".format(name, path), style="green"))
|
|
296
|
+
else:
|
|
297
|
+
profiles = list_profiles()
|
|
298
|
+
if not profiles:
|
|
299
|
+
console.print("No profiles to delete.")
|
|
300
|
+
continue
|
|
301
|
+
name = Prompt.ask("Profile to delete", choices=sorted(profiles))
|
|
302
|
+
if not Confirm.ask("Delete profile '{}' permanently?".format(name), default=False):
|
|
303
|
+
console.print("Cancelled.")
|
|
304
|
+
continue
|
|
305
|
+
path = delete_profile(name)
|
|
306
|
+
console.print(Text("Deleted profile '{}' from {}".format(name, path), style="green"))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _interactive_menu() -> int:
|
|
310
|
+
"""Run a small keyboard-friendly command menu; actions remain explicit CLI commands."""
|
|
311
|
+
actions = {
|
|
312
|
+
"Status": ["status"],
|
|
313
|
+
"Stage selected files": ["stage"],
|
|
314
|
+
"Review staged diff": ["diff"],
|
|
315
|
+
"Review unstaged diff": ["diff", "--unstaged"],
|
|
316
|
+
"Smart commit": ["commit"],
|
|
317
|
+
"Explain staged changes": ["explain"],
|
|
318
|
+
"Commit history": ["history"],
|
|
319
|
+
"AI settings": ["config", "wizard"],
|
|
320
|
+
"API credentials": ["auth", "status"],
|
|
321
|
+
"Manage AI profiles": "profiles",
|
|
322
|
+
"Exit": None,
|
|
323
|
+
}
|
|
324
|
+
while True:
|
|
325
|
+
console.print(Panel(Text("Choose a Git workflow or settings task", style="bold"), title="Commitron"))
|
|
326
|
+
choice = Prompt.ask("Action", choices=list(actions), default="Status")
|
|
327
|
+
command = actions[choice]
|
|
328
|
+
if command is None:
|
|
329
|
+
console.print("Goodbye.")
|
|
330
|
+
return 0
|
|
331
|
+
if command == "profiles":
|
|
332
|
+
result = _manage_profiles_menu()
|
|
333
|
+
else:
|
|
334
|
+
result = main(command)
|
|
335
|
+
if result not in (0,):
|
|
336
|
+
console.print(Text("Action exited with status {}.".format(result), style="yellow"))
|
|
337
|
+
if not Confirm.ask("Return to the menu?", default=True):
|
|
338
|
+
return 0
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def main(argv=None) -> int:
|
|
342
|
+
parser = _parser()
|
|
343
|
+
raw_args = list(sys.argv[1:] if argv is None else argv)
|
|
344
|
+
known_commands = {"auth", "menu", "commit", "status", "stage", "diff", "history", "branch", "explain", "files", "config", "split", "convention", "git-help", "doctor"}
|
|
345
|
+
# Keep the original convenient default: options without a subcommand mean `commit`.
|
|
346
|
+
if not raw_args:
|
|
347
|
+
raw_args = ["commit"]
|
|
348
|
+
elif raw_args[0] not in known_commands and raw_args[0] not in {"-h", "--help", "--version"}:
|
|
349
|
+
raw_args.insert(0, "commit")
|
|
350
|
+
args = parser.parse_args(raw_args)
|
|
351
|
+
command = args.command or "commit"
|
|
352
|
+
# --verbose also enables retry-visibility inside the provider layer.
|
|
353
|
+
if getattr(args, "verbose", False):
|
|
354
|
+
os.environ["COMMITRON_VERBOSE"] = "1"
|
|
355
|
+
try:
|
|
356
|
+
if command == "menu":
|
|
357
|
+
return _interactive_menu()
|
|
358
|
+
if command == "doctor":
|
|
359
|
+
return _doctor_command()
|
|
360
|
+
if command == "auth":
|
|
361
|
+
if args.auth_action == "status":
|
|
362
|
+
for provider in _auth_providers() + ["ollama"]:
|
|
363
|
+
console.print(Text("{}: {}".format(provider, credential_status(provider))))
|
|
364
|
+
elif args.auth_action == "set":
|
|
365
|
+
if not sys.stdin.isatty():
|
|
366
|
+
raise CredentialError("Run 'commitron auth set' from an interactive terminal so the API key is not echoed.")
|
|
367
|
+
secret = getpass.getpass("{} API key (input hidden): ".format(args.provider.title()))
|
|
368
|
+
set_credential(args.provider, secret)
|
|
369
|
+
console.print(Text("{} credential saved to the OS keychain.".format(args.provider.title()), style="green"))
|
|
370
|
+
else:
|
|
371
|
+
if not Confirm.ask("Delete the saved {} credential from the OS keychain?".format(args.provider.title()), default=False):
|
|
372
|
+
console.print("Cancelled.")
|
|
373
|
+
return 0
|
|
374
|
+
removed = delete_credential(args.provider)
|
|
375
|
+
console.print(Text("Credential deleted." if removed else "No saved credential was found."))
|
|
376
|
+
return 0
|
|
377
|
+
if command == "config":
|
|
378
|
+
if args.config_action == "show":
|
|
379
|
+
config = load_config()
|
|
380
|
+
config_text = "\n".join("{}: {}".format(k, v or "(provider default)") for k, v in config.items()) + "\nConfig file: " + str(config_path())
|
|
381
|
+
console.print(Panel(Text(config_text), title="Commitron configuration"))
|
|
382
|
+
elif args.config_action == "path":
|
|
383
|
+
console.print(Text(str(config_path())))
|
|
384
|
+
elif args.config_action == "set":
|
|
385
|
+
path = save_config({args.key: args.value})
|
|
386
|
+
console.print(Text("Saved {} to {}".format(args.key, path), style="green"))
|
|
387
|
+
elif args.config_action == "wizard":
|
|
388
|
+
current = load_config()
|
|
389
|
+
provider = Prompt.ask("AI provider", choices=_auth_providers() + ["ollama"], default=current["provider"])
|
|
390
|
+
model = Prompt.ask("Model (blank = provider default)", default=current["model"])
|
|
391
|
+
base_url = Prompt.ask("Custom base URL (blank = provider default)", default=current["base_url"])
|
|
392
|
+
path = save_config({"provider": provider, "model": model, "base_url": base_url})
|
|
393
|
+
console.print(Text("Configuration saved to {}. API keys are not stored in config; use environment variables or the optional OS keychain.".format(path), style="green"))
|
|
394
|
+
else:
|
|
395
|
+
action = args.profile_action
|
|
396
|
+
if action == "list":
|
|
397
|
+
profiles = list_profiles()
|
|
398
|
+
if not profiles:
|
|
399
|
+
console.print(Text("No saved profiles."))
|
|
400
|
+
else:
|
|
401
|
+
for name, values in sorted(profiles.items()):
|
|
402
|
+
console.print(Text("{} — {} / {}".format(name, values["provider"], values["model"] or "default model")))
|
|
403
|
+
elif action == "save":
|
|
404
|
+
path = save_profile(args.name)
|
|
405
|
+
console.print(Text("Saved profile '{}' to {}".format(args.name, path), style="green"))
|
|
406
|
+
elif action == "use":
|
|
407
|
+
path = use_profile(args.name)
|
|
408
|
+
console.print(Text("Applied profile '{}' from {}".format(args.name, path), style="green"))
|
|
409
|
+
else:
|
|
410
|
+
if not Confirm.ask("Delete profile '{}' permanently?".format(args.name), default=False):
|
|
411
|
+
console.print("Cancelled.")
|
|
412
|
+
return 0
|
|
413
|
+
path = delete_profile(args.name)
|
|
414
|
+
console.print(Text("Deleted profile '{}' from {}".format(args.name, path), style="green"))
|
|
415
|
+
return 0
|
|
416
|
+
if command == "convention":
|
|
417
|
+
ensure_repo()
|
|
418
|
+
root = Path(repository_root())
|
|
419
|
+
if args.convention_action == "show":
|
|
420
|
+
value = load_project_convention(root)
|
|
421
|
+
console.print(Text(value or "No repository-specific convention is configured."))
|
|
422
|
+
elif args.convention_action == "set":
|
|
423
|
+
path = save_project_convention(root, args.text)
|
|
424
|
+
console.print(Text("Saved repository commit convention to {}".format(path), style="green"))
|
|
425
|
+
else:
|
|
426
|
+
path = save_project_convention(root, "")
|
|
427
|
+
console.print(Text("Removed repository-specific commit convention from {}".format(path), style="green"))
|
|
428
|
+
return 0
|
|
429
|
+
ensure_repo()
|
|
430
|
+
if command == "commit":
|
|
431
|
+
return _commit_command(args)
|
|
432
|
+
if command == "stage":
|
|
433
|
+
changes = worktree_changes()
|
|
434
|
+
if not changes:
|
|
435
|
+
console.print(Text("Working tree is clean; there are no paths to stage."))
|
|
436
|
+
return 0
|
|
437
|
+
console.print(Panel(Text("Select only the paths you want in the next commit."), title="Interactive staging"))
|
|
438
|
+
for index, item in enumerate(changes, 1):
|
|
439
|
+
console.print(Text("{}. [{}] {}".format(index, item["status"], item["path"])))
|
|
440
|
+
raw_selection = Prompt.ask("Enter comma-separated numbers, or c to cancel", default="c").strip()
|
|
441
|
+
if raw_selection.lower() == "c":
|
|
442
|
+
console.print("Cancelled. The Git index was not changed.")
|
|
443
|
+
return 0
|
|
444
|
+
try:
|
|
445
|
+
selected_numbers = [int(part.strip()) for part in raw_selection.split(",")]
|
|
446
|
+
except ValueError:
|
|
447
|
+
console.print(Text("Invalid selection. Use comma-separated file numbers.", style="red"))
|
|
448
|
+
return 2
|
|
449
|
+
if not selected_numbers or len(set(selected_numbers)) != len(selected_numbers) or any(
|
|
450
|
+
number < 1 or number > len(changes) for number in selected_numbers
|
|
451
|
+
):
|
|
452
|
+
console.print(Text("Selection contains duplicate or out-of-range numbers.", style="red"))
|
|
453
|
+
return 2
|
|
454
|
+
selected = [changes[number - 1] for number in selected_numbers]
|
|
455
|
+
console.print(Panel(Text("\n".join("[{}] {}".format(item["status"], item["path"]) for item in selected)), title="Paths to stage"))
|
|
456
|
+
if not Confirm.ask("Stage exactly these {} path(s)?".format(len(selected)), default=False):
|
|
457
|
+
console.print("Cancelled. The Git index was not changed.")
|
|
458
|
+
return 0
|
|
459
|
+
stage_paths([item["path"] for item in selected])
|
|
460
|
+
console.print(Text("Staged {} selected path(s).".format(len(selected)), style="green"))
|
|
461
|
+
elif command == "status":
|
|
462
|
+
console.print(Text("Branch: " + current_branch(), style="bold"))
|
|
463
|
+
console.print(Text(status_porcelain() or "Working tree clean"))
|
|
464
|
+
elif command == "diff":
|
|
465
|
+
if args.stat:
|
|
466
|
+
output = diff_stat(staged=not args.unstaged)
|
|
467
|
+
else:
|
|
468
|
+
output = unstaged_diff() if args.unstaged else staged_diff()
|
|
469
|
+
console.print(Text(output or "No matching diff."))
|
|
470
|
+
elif command == "files":
|
|
471
|
+
names = files_changed(staged=not args.unstaged)
|
|
472
|
+
console.print(Text("\n".join(names) if names else "No changed tracked files."))
|
|
473
|
+
elif command == "explain":
|
|
474
|
+
diff = unstaged_diff() if args.unstaged else staged_diff()
|
|
475
|
+
if not diff.strip():
|
|
476
|
+
console.print("[yellow]No matching changes found.[/yellow]")
|
|
477
|
+
return 1
|
|
478
|
+
chunk_count = len(split_diff(diff))
|
|
479
|
+
if chunk_count > MAX_DIFF_CHUNKS:
|
|
480
|
+
console.print(Text(
|
|
481
|
+
"Diff exceeds the safe processing limit ({} chunks; maximum {}). "
|
|
482
|
+
"No diff content was sent. Narrow the changes and retry.".format(
|
|
483
|
+
chunk_count, MAX_DIFF_CHUNKS
|
|
484
|
+
), style="yellow"
|
|
485
|
+
))
|
|
486
|
+
return 1
|
|
487
|
+
if chunk_count > 1:
|
|
488
|
+
console.print(Text(
|
|
489
|
+
"Large diff: all {} chunks will be sent in separate AI requests; "
|
|
490
|
+
"this may use more provider quota.".format(chunk_count), style="yellow"
|
|
491
|
+
))
|
|
492
|
+
if not Confirm.ask("Send the complete diff for analysis?", default=False):
|
|
493
|
+
return 1
|
|
494
|
+
warnings = find_secret_warnings(diff)
|
|
495
|
+
if warnings and not args.allow_secrets:
|
|
496
|
+
console.print(Panel("Possible sensitive content detected: " + ", ".join(warnings), title="Privacy warning", border_style="yellow"))
|
|
497
|
+
console.print("[yellow]This diff may be sent to the configured AI provider.[/yellow]")
|
|
498
|
+
if not Confirm.ask("Send this diff anyway?", default=False):
|
|
499
|
+
return 1
|
|
500
|
+
with console.status("[bold green]Analyzing changes..."):
|
|
501
|
+
explanation = explain_changes(diff, verbose=bool(args.verbose))
|
|
502
|
+
console.print(Panel(Text(explanation), title="Change explanation"))
|
|
503
|
+
elif command == "history":
|
|
504
|
+
if not 1 <= args.limit <= 100:
|
|
505
|
+
parser.error("history --limit must be between 1 and 100")
|
|
506
|
+
if args.analyze:
|
|
507
|
+
entries = history_entries(args.limit)
|
|
508
|
+
if not entries:
|
|
509
|
+
console.print(Text("No commits found."))
|
|
510
|
+
return 0
|
|
511
|
+
payload = "\n".join(
|
|
512
|
+
"{} {} {}\n{}".format(item["hash"][:12], item["date"], item["subject"], item["body"])
|
|
513
|
+
for item in entries
|
|
514
|
+
)
|
|
515
|
+
warnings = find_secret_warnings(payload)
|
|
516
|
+
if warnings:
|
|
517
|
+
console.print(Panel("Possible sensitive content detected: " + ", ".join(warnings), title="Privacy warning", border_style="yellow"))
|
|
518
|
+
console.print(Text("Commit subjects and bodies will be sent to the configured AI provider."))
|
|
519
|
+
if not Confirm.ask("Send the last {} commit records for analysis?".format(len(entries)), default=False):
|
|
520
|
+
console.print("Cancelled. No data was sent.")
|
|
521
|
+
return 0
|
|
522
|
+
with console.status("[bold green]Analyzing commit history..."):
|
|
523
|
+
analysis = summarize_history(entries, verbose=bool(args.verbose))
|
|
524
|
+
console.print(Panel(Text(analysis), title="Commit history analysis"))
|
|
525
|
+
else:
|
|
526
|
+
console.print(Text(history(args.limit) or "No commits found."))
|
|
527
|
+
elif command == "git-help":
|
|
528
|
+
warnings = find_secret_warnings(args.error + "\n" + args.context)
|
|
529
|
+
if warnings:
|
|
530
|
+
console.print(Panel("Possible sensitive content detected: " + ", ".join(warnings), title="Privacy warning", border_style="yellow"))
|
|
531
|
+
console.print(Text("The supplied error and context will be sent to the configured AI provider."))
|
|
532
|
+
if not Confirm.ask("Send this Git error for explanation?", default=False):
|
|
533
|
+
console.print("Cancelled. No data was sent.")
|
|
534
|
+
return 0
|
|
535
|
+
with console.status("[bold green]Explaining Git error..."):
|
|
536
|
+
explanation = explain_git_error(args.error, args.context, verbose=bool(args.verbose))
|
|
537
|
+
console.print(Panel(Text(explanation), title="Git error explanation"))
|
|
538
|
+
elif command == "branch":
|
|
539
|
+
if args.action is None:
|
|
540
|
+
console.print(Text(branches() or "No branches found."))
|
|
541
|
+
elif args.action == "suggest":
|
|
542
|
+
if not args.description:
|
|
543
|
+
parser.error("branch suggest requires --description")
|
|
544
|
+
existing = branches().splitlines()
|
|
545
|
+
if not Confirm.ask("Send the task description and existing branch names to the configured AI provider?", default=False):
|
|
546
|
+
console.print("Cancelled. No data was sent.")
|
|
547
|
+
return 0
|
|
548
|
+
branch_context = args.description + "\n" + "\n".join(existing)
|
|
549
|
+
warnings = find_secret_warnings(branch_context)
|
|
550
|
+
if warnings:
|
|
551
|
+
console.print(Panel("Possible sensitive content detected: " + ", ".join(warnings), title="Privacy warning", border_style="yellow"))
|
|
552
|
+
if not Confirm.ask("Send this information anyway?", default=False):
|
|
553
|
+
return 1
|
|
554
|
+
with console.status("[bold green]Generating branch-name suggestion..."):
|
|
555
|
+
suggestion = suggest_branch_name(args.description, existing, verbose=bool(args.verbose))
|
|
556
|
+
console.print(Panel(Text(suggestion), title="Suggested branch name"))
|
|
557
|
+
console.print(Text("Suggestion only: no branch was created. Review it before using it.", style="dim"))
|
|
558
|
+
elif not args.name:
|
|
559
|
+
parser.error("branch create/switch requires a branch name")
|
|
560
|
+
elif args.action == "create":
|
|
561
|
+
create_branch(args.name)
|
|
562
|
+
console.print(Text("Created and switched to " + args.name, style="green"))
|
|
563
|
+
else:
|
|
564
|
+
switch_branch(args.name)
|
|
565
|
+
console.print(Text("Switched to " + args.name, style="green"))
|
|
566
|
+
elif command == "split":
|
|
567
|
+
diff = staged_diff()
|
|
568
|
+
changed = files_changed(staged=True)
|
|
569
|
+
if len(changed) < 2 or not diff.strip():
|
|
570
|
+
console.print(Text("Stage changes in at least two tracked files to request file-level logical commit suggestions.", style="yellow"))
|
|
571
|
+
return 1
|
|
572
|
+
chunk_count = len(split_diff(diff))
|
|
573
|
+
if chunk_count > MAX_DIFF_CHUNKS:
|
|
574
|
+
console.print(Text("Staged diff exceeds the safe processing limit. No diff content was sent.", style="yellow"))
|
|
575
|
+
return 1
|
|
576
|
+
if chunk_count > 1:
|
|
577
|
+
console.print(Text("Large diff: all {} chunks will be analyzed; this may use more provider quota.".format(chunk_count), style="yellow"))
|
|
578
|
+
if not Confirm.ask("Send the complete staged diff for logical grouping?", default=False):
|
|
579
|
+
return 1
|
|
580
|
+
convention = load_project_convention(Path(repository_root()))
|
|
581
|
+
warnings = find_secret_warnings(diff + "\n" + convention)
|
|
582
|
+
if warnings and not args.allow_secrets:
|
|
583
|
+
console.print(Panel("Possible sensitive content detected: " + ", ".join(warnings), title="Privacy warning", border_style="yellow"))
|
|
584
|
+
console.print("[yellow]The staged diff and project convention may be sent to the configured AI provider.[/yellow]")
|
|
585
|
+
if not Confirm.ask("Send this content anyway?", default=False):
|
|
586
|
+
return 1
|
|
587
|
+
try:
|
|
588
|
+
with console.status("[bold green]Analyzing staged files for logical commit groups..."):
|
|
589
|
+
groups = suggest_logical_commits(diff, changed, args.style, convention, verbose=bool(args.verbose))
|
|
590
|
+
except AIError as exc:
|
|
591
|
+
console.print(Text("AI error: " + str(exc), style="red"))
|
|
592
|
+
return 1
|
|
593
|
+
for index, group in enumerate(groups, 1):
|
|
594
|
+
console.print(Panel(
|
|
595
|
+
Text("Message: {}\nReason: {}\nFiles:\n{}".format(
|
|
596
|
+
group["message"], group["reason"],
|
|
597
|
+
"\n".join(" - " + item for item in group["files"])
|
|
598
|
+
)), title="Suggested logical commit {}".format(index)
|
|
599
|
+
))
|
|
600
|
+
console.print(Text("Suggestions only: no files were staged, unstaged, or committed. Review the groups and perform any staging manually.", style="yellow"))
|
|
601
|
+
return 0
|
|
602
|
+
except GitError as exc:
|
|
603
|
+
console.print(Text("Git error: " + str(exc), style="red"))
|
|
604
|
+
return 1
|
|
605
|
+
except (AIError, CredentialError, ValueError) as exc:
|
|
606
|
+
console.print(Text("Error: " + str(exc), style="red"))
|
|
607
|
+
return 1
|
|
608
|
+
except KeyboardInterrupt:
|
|
609
|
+
console.print("\n[yellow]Interrupted.[/yellow]")
|
|
610
|
+
return 130
|
|
611
|
+
except EOFError:
|
|
612
|
+
console.print("\n[yellow]Input closed; no further action was taken.[/yellow]")
|
|
613
|
+
return 130
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
if __name__ == "__main__":
|
|
617
|
+
raise SystemExit(main())
|