cmt 0.5.16

CLI tool that generates commit messages using AI
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use arboard::Clipboard;
use cmt::ai_mod::{default_model, list_models};
use cmt::config_mod::{file as config_file, Config};
use cmt::pricing::{self, PricingCache};
use cmt::template_mod::TemplateManager;
use cmt::{
    analyze_diff, append_to_cmtignore, create_commit, generate_commit_message, get_current_branch,
    get_readme_excerpt, load_cmtignore, Args, CommitError, CommitOptions, Spinner,
};
use colored::*;
use dotenv::dotenv;
use git2::Repository;
use std::io::{self, Write};
use std::time::Instant;
use std::{env, process};

enum CommitAction {
    Commit,
    Cancel,
    Hint,
}

#[tokio::main]
async fn main() {
    dotenv().ok(); // Load .env file if it exists
    let args = Args::new_from(env::args());

    // Start pricing fetch in background (will be ready by time generation completes)
    let mut pricing_cache = PricingCache::new();

    // Handle configuration initialization
    if args.init_config {
        match config_file::create_config_file(args.config_path.as_deref()) {
            Ok(path) => {
                println!("{}", "Configuration file created:".green().bold());
                println!("{}", path.display());
                process::exit(0);
            }
            Err(e) => {
                eprintln!("{}", "Error creating configuration file:".red().bold());
                eprintln!("{}", e);
                process::exit(1);
            }
        }
    }

    // Handle listing available models (doesn't need templates)
    if args.list_models {
        let provider_name = &args.provider;

        match list_models(provider_name).await {
            Ok(models) => {
                println!(
                    "{}",
                    format!("Available models for {}:", provider_name)
                        .green()
                        .bold(),
                );

                // Sort models alphabetically for better readability
                let mut sorted_models = models;
                sorted_models.sort();

                let default = default_model(provider_name);
                for model in sorted_models {
                    // Highlight the default model
                    if model == default {
                        println!("- {} (default)", model.cyan());
                    } else {
                        println!("- {}", model);
                    }
                }
                process::exit(0);
            }
            Err(e) => {
                eprintln!(
                    "{}",
                    format!("Error fetching models for {}:", provider_name)
                        .red()
                        .bold()
                );
                eprintln!("{}", e);
                process::exit(1);
            }
        }
    }

    // Handle showing template content (doesn't need TemplateManager)
    if let Some(template_name) = &args.show_template {
        match config_file::get_template(template_name) {
            Ok(content) => {
                println!(
                    "{}",
                    format!("Template '{}':", template_name).green().bold()
                );
                println!("{}", content);
                process::exit(0);
            }
            Err(e) => {
                eprintln!(
                    "{}",
                    format!("Error showing template '{}':", template_name)
                        .red()
                        .bold()
                );
                eprintln!("{}", e);
                process::exit(1);
            }
        }
    }

    // Handle creating a new template (doesn't need TemplateManager)
    if let Some(template_name) = &args.create_template {
        // Ensure template directory exists
        if let Err(e) = config_file::create_template_dir() {
            eprintln!("{}", "Error creating template directory:".red().bold());
            eprintln!("{}", e);
            process::exit(1);
        }

        // Get template content
        let content = match &args.template_content {
            Some(content) => content.clone(),
            None => {
                eprintln!(
                    "{}",
                    "Error: --template-content is required when creating a template"
                        .red()
                        .bold()
                );
                eprintln!("Example: cmt --create-template my-template --template-content \"{{type}}: {{subject}}\\n\\n{{details}}\"");
                process::exit(1);
            }
        };

        // Save the template
        match config_file::save_template(template_name, &content) {
            Ok(_) => {
                println!(
                    "{}",
                    format!("Template '{}' created successfully.", template_name)
                        .green()
                        .bold()
                );
                println!("You can use it with: cmt --template {}", template_name);
                process::exit(0);
            }
            Err(e) => {
                eprintln!(
                    "{}",
                    format!("Error creating template '{}':", template_name)
                        .red()
                        .bold()
                );
                eprintln!("{}", e);
                process::exit(1);
            }
        }
    }

    // Initialize template manager (only needed for --list-templates and commit generation)
    let template_manager = match TemplateManager::new() {
        Ok(manager) => manager,
        Err(e) => {
            eprintln!("{}", "Error initializing templates:".red().bold());
            eprintln!("{}", e);
            process::exit(1);
        }
    };

    // Handle listing available templates
    if args.list_templates {
        println!("{}", "Available templates:".green().bold());
        for template in template_manager.list_templates() {
            println!("- {}", template);
        }
        process::exit(0);
    }

    // Load configuration
    let mut config = match Config::load() {
        Ok(config) => config,
        Err(e) => {
            eprintln!(
                "{}",
                "Warning: Failed to load configuration:".yellow().bold()
            );
            eprintln!("{}", e);
            Config::default()
        }
    };

    // Override config with CLI args
    let cli_config = Config::from_args(&args);
    config.merge(&cli_config);

    // Open git repository (discover searches up the directory tree)
    let repo = match Repository::discover(".") {
        Ok(repo) => repo,
        Err(e) => {
            eprintln!("{}", "Error opening git repository:".red().bold());
            eprintln!("{}", e);
            process::exit(1);
        }
    };

    // Get repository root for .cmtignore
    let repo_root = repo.workdir().unwrap_or_else(|| std::path::Path::new("."));

    // Load .cmtignore patterns
    let cmtignore_patterns = load_cmtignore(repo_root);

    // Get staged changes (includes both diff text and stats in one pass)
    let staged = match cmt::get_staged_changes(
        &repo,
        args.context_lines,
        args.max_lines_per_file,
        args.max_line_width,
        args.max_file_lines,
        &cmtignore_patterns,
    ) {
        Ok(changes) => changes,
        Err(e) => {
            eprintln!("{}", "Error:".red().bold());
            eprintln!("{}", e);
            process::exit(1);
        }
    };

    // Handle files that exceed the threshold (prompt to add to .cmtignore)
    if !staged.stats.skipped_files.is_empty() && !args.yes && !args.message_only {
        println!();
        println!(
            "{}",
            format!(
                "The following files exceed {} lines changed:",
                args.max_file_lines
            )
            .yellow()
            .bold()
        );
        for (file, adds, dels) in &staged.stats.skipped_files {
            let total = adds + dels;
            let lines_display = if total >= 1000 {
                format!("{}K lines", total / 1000)
            } else {
                format!("{} lines", total)
            };
            println!("  - {} ({})", file, lines_display);
        }
        println!();

        print!(
            "{}",
            "Would you like to add them to .cmtignore? [Y/n] ".cyan()
        );
        io::stdout().flush().unwrap();

        let mut input = String::new();
        let should_add = if io::stdin().read_line(&mut input).is_ok() {
            let input = input.trim().to_lowercase();
            input.is_empty() || input == "y" || input == "yes"
        } else {
            false
        };

        if should_add {
            let files_to_add: Vec<String> = staged
                .stats
                .skipped_files
                .iter()
                .map(|(f, _, _)| f.clone())
                .collect();

            match append_to_cmtignore(repo_root, &files_to_add) {
                Ok(()) => {
                    println!(
                        "{}",
                        "Added to .cmtignore. These files will be skipped for analysis in future runs."
                            .green()
                    );
                    println!(
                        "{}",
                        "(They will still be committed normally, just not sent to the LLM.)"
                            .dimmed()
                    );
                    println!();
                }
                Err(e) => {
                    eprintln!(
                        "{}",
                        format!("Warning: Failed to update .cmtignore: {}", e)
                            .yellow()
                            .bold()
                    );
                }
            }
        }
    }

    let staged_changes = staged.diff_text.clone();

    // Determine diff size for adaptive behaviors (very high thresholds - Gemini supports 1M tokens)
    let is_very_large_diff = staged.stats.files_changed > 150
        || (staged.stats.insertions + staged.stats.deletions) > 50000;

    // Get recent commits - only skip for extremely large diffs
    let include_recent = !args.no_recent_commits && !is_very_large_diff;
    let effective_recent_count = if include_recent {
        args.recent_commits_count // Always use full count - we have the token budget
    } else {
        0
    };

    if !args.no_recent_commits && !include_recent {
        eprintln!(
            "{}",
            "Skipping recent commits for this extremely large diff.".yellow()
        );
    }

    let recent_commits = if include_recent {
        match cmt::get_recent_commits(&repo, effective_recent_count) {
            Ok(commits) => commits,
            Err(e) => {
                eprintln!(
                    "{}",
                    "Warning: Failed to get recent commits:".yellow().bold()
                );
                eprintln!("{}", e);
                String::new()
            }
        }
    } else {
        String::new()
    };

    // Analyze the diff for better commit type classification
    let analysis = match analyze_diff(&repo) {
        Ok(a) => Some(a),
        Err(e) => {
            eprintln!("{}", "Warning: Failed to analyze diff:".yellow().bold());
            eprintln!("{}", e);
            None
        }
    };

    // Get current branch name for context
    let branch_name = get_current_branch(&repo);

    // Get README excerpt for project context (first 50 lines)
    let readme_excerpt = get_readme_excerpt(&repo, 50);

    // Show raw diff if requested
    if args.show_raw_diff {
        println!("{}", "Raw diff:".cyan().bold());
        println!("{}", staged_changes);
        if let Some(ref a) = analysis {
            println!("\n{}", "Diff analysis:".cyan().bold());
            println!("{}", a.summary());
        }
        println!();
    }

    // Get model info for display
    let model_name = args
        .model
        .clone()
        .unwrap_or_else(|| default_model(&args.provider).to_string());

    // Show diff stats before sending to LLM (unless message-only mode)
    if !args.message_only && !args.no_diff_stats {
        staged.stats.print();
    }

    // Generate commit message with spinner (only in interactive mode)
    let spinner = if !args.message_only {
        Some(Spinner::new(&format!(
            "Generating commit message with {}...",
            model_name
        )))
    } else {
        None
    };

    let start_time = Instant::now();
    let result = match generate_commit_message(
        &args,
        &staged_changes,
        &recent_commits,
        analysis.as_ref(),
        branch_name.as_deref(),
        readme_excerpt.as_deref(),
        &template_manager,
    )
    .await
    {
        Ok(result) => {
            if let Some(s) = &spinner {
                s.finish_and_clear();
            }
            result
        }
        Err(e) => {
            if let Some(s) = &spinner {
                s.finish_and_clear();
            }
            eprintln!("{}", "Error generating commit message:".red().bold());
            eprintln!("{}", e);
            process::exit(1);
        }
    };
    let elapsed = start_time.elapsed();
    let commit_message = result.message;

    // Copy to clipboard if requested
    if args.copy {
        match Clipboard::new() {
            Ok(mut clipboard) => {
                if let Err(e) = clipboard.set_text(&commit_message) {
                    eprintln!(
                        "{}",
                        format!("Warning: Failed to copy to clipboard: {}", e)
                            .yellow()
                            .bold()
                    );
                } else if !args.message_only {
                    println!("{}", "✓ Copied to clipboard".green());
                }
            }
            Err(e) => {
                eprintln!(
                    "{}",
                    format!("Warning: Failed to access clipboard: {}", e)
                        .yellow()
                        .bold()
                );
            }
        }
    }

    // Output the commit message
    if args.message_only {
        // Output just the message for piping to git commit
        print!("{}", commit_message);
    } else {
        // Show the generated commit message
        println!("{}", "Commit message:".green().bold());
        println!("{}", commit_message);

        // Use actual token counts from API, or estimate if not available
        let (input_tokens, output_tokens) = match (result.input_tokens, result.output_tokens) {
            (Some(input), Some(output)) => (input, output),
            _ => {
                // Fallback: estimate ~4 chars per token
                let est_input = (staged_changes.len() + recent_commits.len()) as u64 / 4;
                let est_output = commit_message.len() as u64 / 4;
                (est_input, est_output)
            }
        };
        let total_tokens = input_tokens + output_tokens;
        let elapsed_secs = elapsed.as_secs_f32();

        let cost_str = pricing_cache
            .get_model_pricing(&args.provider, &model_name)
            .and_then(|p| pricing::calculate_cost(&p, input_tokens, output_tokens))
            .map(|c| format!(", {}", pricing::format_cost(c)))
            .unwrap_or_default();

        // Show ~ prefix only if we're estimating
        let token_prefix = if result.input_tokens.is_some() {
            ""
        } else {
            "~"
        };
        println!(
            "{}",
            format!(
                "{}{} tokens, {:.1}s{}",
                token_prefix, total_tokens, elapsed_secs, cost_str
            )
            .dimmed()
        );

        // Handle commit prompt (default behavior unless --no-commit)
        if !args.no_commit {
            let mut current_message = commit_message.clone();
            let mut current_args = args.clone();

            loop {
                let action = if current_args.yes {
                    CommitAction::Commit
                } else {
                    // Prompt for action
                    print!(
                        "{}",
                        "[y]es to commit, [n]o to cancel, [h]int to regenerate: ".cyan()
                    );
                    io::stdout().flush().unwrap();

                    let mut input = String::new();
                    if io::stdin().read_line(&mut input).is_ok() {
                        let input = input.trim().to_lowercase();
                        match input.as_str() {
                            "y" | "yes" => CommitAction::Commit,
                            "n" | "no" | "" => CommitAction::Cancel,
                            "h" | "hint" => CommitAction::Hint,
                            _ => CommitAction::Cancel,
                        }
                    } else {
                        CommitAction::Cancel
                    }
                };

                match action {
                    CommitAction::Commit => {
                        // Create the commit using git commit (respects hooks)
                        let options = CommitOptions {
                            no_verify: current_args.no_verify,
                        };
                        match create_commit(&repo, &current_message, &options) {
                            Ok(result) => {
                                println!(
                                    "{}",
                                    format!("✓ Created commit: {}", &result.oid[..7])
                                        .green()
                                        .bold()
                                );
                            }
                            Err(err @ CommitError::PreCommitFailed { .. }) => {
                                eprintln!("{}", "Pre-commit hook failed.".red().bold());
                                if let Some(output) = err.hook_output() {
                                    eprintln!();
                                    eprintln!("{}", output);
                                }
                                eprintln!("{}", "Use --no-verify (-n) to skip hooks.".yellow());
                                process::exit(1);
                            }
                            Err(err @ CommitError::CommitMsgFailed { .. }) => {
                                eprintln!("{}", "Commit-msg hook failed.".red().bold());
                                if let Some(output) = err.hook_output() {
                                    eprintln!();
                                    eprintln!("{}", output);
                                }
                                eprintln!("{}", "Use --no-verify (-n) to skip hooks.".yellow());
                                process::exit(1);
                            }
                            Err(e) => {
                                eprintln!("{}", "Error creating commit:".red().bold());
                                eprintln!("{}", e);
                                process::exit(1);
                            }
                        }
                        break;
                    }
                    CommitAction::Cancel => {
                        println!("{}", "Commit cancelled.".yellow());
                        break;
                    }
                    CommitAction::Hint => {
                        // Prompt for hint
                        print!("{}", "Enter hint: ".cyan());
                        io::stdout().flush().unwrap();

                        let mut hint_input = String::new();
                        if io::stdin().read_line(&mut hint_input).is_ok() {
                            let hint = hint_input.trim();
                            if !hint.is_empty() {
                                current_args.hint = Some(hint.to_string());

                                // Regenerate with spinner
                                let spinner =
                                    Spinner::new(&format!("Regenerating with {}...", model_name));
                                match generate_commit_message(
                                    &current_args,
                                    &staged_changes,
                                    &recent_commits,
                                    analysis.as_ref(),
                                    branch_name.as_deref(),
                                    readme_excerpt.as_deref(),
                                    &template_manager,
                                )
                                .await
                                {
                                    Ok(new_result) => {
                                        spinner.finish_and_clear();
                                        current_message = new_result.message;
                                        println!();
                                        println!("{}", "Commit message:".green().bold());
                                        println!("{}", current_message);
                                    }
                                    Err(e) => {
                                        spinner.finish_and_clear();
                                        eprintln!(
                                            "{}",
                                            "Error regenerating commit message:".red().bold()
                                        );
                                        eprintln!("{}", e);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}