git-comma 1.0.7

AI-powered git commit message generator using OpenRouter API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
mod ai;
mod config;
mod error;
mod filter;
mod openrouter;
mod preflight;
mod prompt;
mod sanitization;
mod setup;
mod tui;
mod ui;

use clap::Parser;
use config::{home_config_path, Config, ConfigError};

#[derive(Parser)]
#[command(name = "comma")]
#[command(version, about = "AI-powered git commit message generator")]
struct Cli {
    /// Run the interactive setup flow
    #[arg(long)]
    setup: bool,
    /// Disable smart diff filtering (include all files in AI diff)
    #[arg(long)]
    no_filter: bool,
}

fn fallback_editor() -> String {
    match crate::ai::open_editor("") {
        Ok(content) => content,
        Err(e) => {
            eprintln!("Editor error: {}", e);
            std::process::exit(1);
        }
    }
}

fn handle_commit_failure() {
    eprintln!("❌ Commit rejected by system (possibly pre-commit hook/linter failed).");
    eprintln!("💡 Draft is safe! After fixing, run:");
    eprintln!("   git commit -F .git/comma_msg.txt");
    std::process::exit(1);
}

fn run_git_add() -> bool {
    std::process::Command::new("git")
        .args(["add", "."])
        .spawn()
        .map(|mut child| child.wait().map(|e| e.success()).unwrap_or(false))
        .unwrap_or(false)
}

fn main() {
    let cli = Cli::parse();

    if cli.setup {
        match setup::run_setup_flow(false) {
            Ok(_) => std::process::exit(0),
            Err(e) => {
                eprintln!("❌ Setup failed: {}", e);
                std::process::exit(1);
            }
        }
    }

    let config_path = home_config_path().expect("Failed to determine config path");
    let config = match Config::load_from_path(&config_path) {
        Ok(cfg) => cfg,
        Err(ConfigError::MalformedJson) => {
            eprintln!("Config corrupted. Deleting and re-setting up...");
            if let Err(e) = std::fs::remove_file(&config_path) {
                eprintln!("Warning: Failed to delete corrupted config: {}. Will overwrite.", e);
            }
            match setup::run_setup_flow(true) {
                Ok(cfg) => cfg,
                Err(e) => {
                    eprintln!("❌ Setup failed: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Err(_) if !config_path.exists() => {
            match setup::run_setup_flow(true) {
                Ok(cfg) => cfg,
                Err(e) => {
                    eprintln!("❌ Setup failed: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Err(e) => {
            eprintln!("Failed to read config: {}. Re-running setup...", e);
            match setup::run_setup_flow(true) {
                Ok(cfg) => cfg,
                Err(e) => {
                    eprintln!("❌ Setup failed: {}", e);
                    std::process::exit(1);
                }
            }
        }
    };

    // Pre-flight check
    let preflight_result = if cli.no_filter {
        match preflight::run_with_filter(preflight::FilterMode::NoFilter) {
            Ok(success) => success,
            Err(preflight::PreflightError::WorkingTreeClean) => {
                println!("✨ Working tree clean.");
                std::process::exit(0);
            }
            Err(preflight::PreflightError::NotGitRepo) => {
                eprintln!("Error: This is not a git repository.");
                std::process::exit(1);
            }
            Err(preflight::PreflightError::GitCommandFailed { command, source }) => {
                eprintln!("Error: Git command '{}' failed: {}", command, source);
                std::process::exit(1);
            }
            Err(preflight::PreflightError::NoStagedFiles { unstaged }) => {
                ui::print_unstaged_files(&unstaged);
                if ui::prompt_git_add() {
                    if run_git_add() {
                        match preflight::run_with_filter(preflight::FilterMode::NoFilter) {
                            Ok(success) => success,
                            Err(preflight::PreflightError::NoStagedFiles { .. }) => {
                                eprintln!("Still no files staged after git add.");
                                std::process::exit(1);
                            }
                            Err(preflight::PreflightError::WorkingTreeClean) => {
                                println!("✨ Working tree clean.");
                                std::process::exit(0);
                            }
                            Err(preflight::PreflightError::NotGitRepo) => {
                                eprintln!("Error: This is not a git repository.");
                                std::process::exit(1);
                            }
                            Err(e) => {
                                eprintln!("Error: {}", e);
                                std::process::exit(1);
                            }
                        }
                    } else {
                        eprintln!("git add . failed.");
                        std::process::exit(1);
                    }
                } else {
                    std::process::exit(1);
                }
            }
            Err(preflight::PreflightError::DiffTooLarge { size }) => {
                match ui::confirm_large_diff(size) {
                    Ok(true) => {
                        match preflight::run_with_filter(preflight::FilterMode::NoFilter) {
                            Ok(success) => success,
                            Err(e) => {
                                eprintln!("Error: {}", e);
                                std::process::exit(1);
                            }
                        }
                    }
                    Ok(false) | Err(()) => {
                        eprintln!("\n❌ Cancelled. Stage fewer files and try again.");
                        std::process::exit(1);
                    }
                }
            }
        }
    } else {
        match preflight::run() {
            Ok(success) => success,
            Err(preflight::PreflightError::WorkingTreeClean) => {
                println!("✨ Working tree clean.");
                std::process::exit(0);
            }
            Err(preflight::PreflightError::NotGitRepo) => {
                eprintln!("Error: This is not a git repository.");
                std::process::exit(1);
            }
            Err(preflight::PreflightError::GitCommandFailed { command, source }) => {
                eprintln!("Error: Git command '{}' failed: {}", command, source);
                std::process::exit(1);
            }
            Err(preflight::PreflightError::NoStagedFiles { unstaged }) => {
                ui::print_unstaged_files(&unstaged);
                if ui::prompt_git_add() {
                    if run_git_add() {
                        match preflight::run() {
                            Ok(success) => success,
                            Err(preflight::PreflightError::NoStagedFiles { .. }) => {
                                eprintln!("Still no files staged after git add.");
                                std::process::exit(1);
                            }
                            Err(preflight::PreflightError::WorkingTreeClean) => {
                                println!("✨ Working tree clean.");
                                std::process::exit(0);
                            }
                            Err(preflight::PreflightError::NotGitRepo) => {
                                eprintln!("Error: This is not a git repository.");
                                std::process::exit(1);
                            }
                            Err(e) => {
                                eprintln!("Error: {}", e);
                                std::process::exit(1);
                            }
                        }
                    } else {
                        eprintln!("git add . failed.");
                        std::process::exit(1);
                    }
                } else {
                    std::process::exit(1);
                }
            }
            Err(preflight::PreflightError::DiffTooLarge { size }) => {
                match ui::confirm_large_diff(size) {
                    Ok(true) => {
                        match preflight::run_with_diff_bypass() {
                            Ok(success) => success,
                            Err(e) => {
                                eprintln!("Error: {}", e);
                                std::process::exit(1);
                            }
                        }
                    }
                    Ok(false) | Err(()) => {
                        eprintln!("\n❌ Cancelled. Stage fewer files and try again.");
                        std::process::exit(1);
                    }
                }
            }
        }
    };

    // Recovery Loop: obtain valid draft with bounded retry
    let mut working_config = config.clone();
    let mut attempt = 0;
    let max_attempts = 3;
    let mut draft = loop {
        attempt += 1;

        // STATIC MESSAGE PATH — skip AI, go directly to TUI
        if preflight_result.is_static_message {
            break preflight_result.diff_content.clone();
        }

        print!("⏳ Analyzing the diff and crafting the commit message...");
        std::io::Write::flush(&mut std::io::stdout()).ok();

        match crate::ai::run_ai_engine(
            &working_config.api_key,
            &working_config.model_id,
            &preflight_result.diff_content,
        ) {
            Ok(d) => break d,
            Err(crate::ai::AiError::ModelUnavailable(ref msg)) | Err(crate::ai::AiError::RateLimitExceeded(ref msg)) => {
                if attempt >= max_attempts {
                    eprintln!("\n{} after {} attempts.", msg, max_attempts);
                    eprintln!("💡 Continuing in manual editor mode...");
                    let content = fallback_editor();
                    break content;
                }
                match ui::prompt_model_switch(&working_config.model_id) {
                Ok(true) => {
                    match setup::run_setup_flow(false) {
                        Ok(new_config) => {
                            working_config = new_config;
                            continue;
                        }
                        Err(e) => {
                            eprintln!("\n⚠️ Setup failed: {}", e);
                            eprintln!("Re-entering setup flow...");
                            match setup::run_setup_flow(true) {
                                Ok(new_config) => {
                                    working_config = new_config;
                                    continue;
                                }
                                Err(e) => {
                                    eprintln!("❌ Setup failed: {}", e);
                                    std::process::exit(1);
                                }
                            }
                        }
                    }
                }
                Ok(false) | Err(()) => {
                    eprintln!("\n💡 Continuing in manual editor mode...");
                    let content = fallback_editor();
                    break content;
                }
            }
            }
            Err(crate::ai::AiError::Network(_)) => {
                eprintln!("\n❌ Network error. Continuing in manual editor mode...");
                let content = fallback_editor();
                break content;
            }
            Err(crate::ai::AiError::EmptyResponse) => {
                eprintln!("\n❌ Empty response from API. Continuing in manual editor mode...");
                let content = fallback_editor();
                break content;
            }
            Err(crate::ai::AiError::Api(_)) => {
                eprintln!("\n❌ Failed to contact OpenRouter. Continuing in manual editor mode...");
                let content = fallback_editor();
                break content;
            }
        }
    };

    // Lazy-save: persist new model if it changed
    if working_config.model_id != config.model_id {
        if let Err(e) = working_config.save(&config_path) {
            eprintln!("Warning: Failed to save new model config: {}", e);
        } else {
            println!("✅ Model successfully changed!");
        }
    }

    // Show result
    println!("\n==================================================");
    println!("{}", draft);
    println!("==================================================\n");

    // Action loop
    loop {
        match crate::ai::prompt_action(&draft) {
            Ok(crate::ai::Action::Accept) => {
                // Execute commit with draft
                if let Some(repo_root) = crate::ai::get_repo_root() {
                    match crate::ai::commit_with_draft(&draft, &repo_root) {
                        Ok(()) => {
                            println!("🎉 Commit successful!");
                            break;
                        }
                        Err(_e) => {
                            handle_commit_failure();
                        }
                    }
                } else {
                    eprintln!("❌ Could not find git repository root.");
                    std::process::exit(1);
                }
            }
            Ok(crate::ai::Action::Edit) => {
                match crate::ai::open_editor(&draft) {
                    Ok(edited) => {
                        if edited != draft {
                            println!("\n📝 Draft updated.");
                        }
                        // Execute commit with edited draft
                        if let Some(repo_root) = crate::ai::get_repo_root() {
                            match crate::ai::commit_with_draft(&edited, &repo_root) {
                                Ok(()) => {
                                    println!("🎉 Commit successful!");
                                    break;
                                }
                                Err(_e) => {
                                    handle_commit_failure();
                                }
                            }
                        } else {
                            eprintln!("❌ Could not find git repository root.");
                            std::process::exit(1);
                        }
                    }
                    Err(e) => {
                        eprintln!("Editor error: {}", e);
                    }
                }
            }
            Ok(crate::ai::Action::Regenerate) => {
                if preflight_result.is_static_message {
                    eprintln!("Regenerate is not available: no diff content (all files were filtered).");
                    continue;
                }
                match crate::ai::prompt_custom_instruction() {
                    Ok(instruction) => {
                        match crate::ai::regenerate_with_instruction(
                            &working_config.api_key,
                            &working_config.model_id,
                            &preflight_result.diff_content,
                            &instruction,
                        ) {
                            Ok(new_draft) => {
                                println!("\n==================================================");
                                println!("{}", new_draft);
                                println!("==================================================\n");
                                draft = new_draft;
                            }
                            Err(e) => {
                                eprintln!("\n❌ Regenerate failed: {}", e);
                            }
                        }
                    }
                    Err(_) => continue,
                }
            }
            Ok(crate::ai::Action::Cancel) => {
                std::process::exit(0);
            }
            Err(_) => {
                eprintln!("Action cancelled or prompt error.");
                std::process::exit(0);
            }
        }
    }
}