gitai/features/commit/
cli.rs

1use super::completion::CompletionService;
2use super::format_commit_result;
3use super::service::CommitService;
4use super::types::{format_commit_message, format_pull_request};
5use crate::common::CommonParams;
6use crate::config::Config;
7use crate::core::messages;
8use crate::features::commit::types;
9use crate::git::GitRepo;
10use crate::tui::run_tui_commit;
11use crate::ui::{self, SpinnerState};
12
13use anyhow::{Context, Result};
14use std::{
15    io::{self, Write},
16    sync::Arc,
17    time::Duration,
18};
19use tokio::time;
20
21/// Run an async operation with a CLI spinner display
22async fn run_with_spinner<F, Fut, T>(
23    mut spinner: SpinnerState,
24    operation: F,
25) -> Result<T, anyhow::Error>
26where
27    F: FnOnce() -> Fut,
28    Fut: std::future::Future<Output = Result<T, anyhow::Error>>,
29{
30    let (tx, mut rx) = tokio::sync::mpsc::channel(1);
31
32    // Spawn spinner animation task
33    let spinner_handle = tokio::spawn(async move {
34        let mut stdout = io::stdout();
35        loop {
36            tokio::select! {
37                _ = rx.recv() => break, // Stop signal received
38                () = time::sleep(Duration::from_millis(100)) => {
39                    let (frame, message, _color, _width) = spinner.tick();
40                    let _ = write!(stdout, "\r{frame} {message}");
41                    let _ = stdout.flush();
42                }
43            }
44        }
45        // Clear the spinner line
46        let _ = write!(stdout, "\r{}\r", " ".repeat(80));
47        let _ = stdout.flush();
48    });
49
50    // Run the operation
51    let result = operation().await;
52
53    // Stop the spinner
54    let _ = tx.send(()).await;
55    spinner_handle.await?;
56
57    result
58}
59
60#[allow(clippy::fn_params_excessive_bools)]
61#[allow(clippy::too_many_lines)]
62#[allow(clippy::too_many_arguments)]
63pub async fn handle_message_command(
64    common: CommonParams,
65    auto_commit: bool,
66    print: bool,
67    verify: bool,
68    dry_run: bool,
69    amend: bool,
70    commit_ref: Option<String>,
71    repository_url: Option<String>,
72) -> Result<()> {
73    let mut config = Config::load()?;
74    common.apply_to_config(&mut config)?;
75
76    // Create the service using the common function
77    let service =
78        create_commit_service(&common, repository_url.clone(), &config, verify).map_err(|e| {
79            ui::print_error(&format!("Error: {e}"));
80            e
81        })?;
82
83    // Create the completion service
84    let completion_service = create_completion_service(&common, repository_url, &config, verify)
85        .map_err(|e| {
86            ui::print_error(&format!("Error: {e}"));
87            e
88        })?;
89
90    // Validate amend parameters
91    if !amend && commit_ref.is_some() {
92        ui::print_error("--commit can only be used with --amend");
93        return Err(anyhow::anyhow!("--commit requires --amend"));
94    }
95
96    if amend && commit_ref.is_some() && commit_ref.as_deref() != Some("HEAD") {
97        ui::print_error(
98            "Currently, only amending HEAD is supported. For amending other commits, use git directly.",
99        );
100        ui::print_info("Example: git commit --amend");
101        return Err(anyhow::anyhow!(
102            "Only HEAD amendments are currently supported"
103        ));
104    }
105
106    let git_info = service.get_git_info().await?;
107
108    if git_info.staged_files.is_empty() && !dry_run && !amend {
109        ui::print_warning(
110            "No staged changes. Please stage your changes before generating a commit message.",
111        );
112        ui::print_info("You can stage changes using 'git add <file>' or 'git add .'");
113        return Ok(());
114    }
115
116    // Run pre-commit hook before we do anything else
117    if let Err(e) = service.pre_commit() {
118        ui::print_error(&format!("Pre-commit failed: {e}"));
119        return Err(e);
120    }
121
122    let effective_instructions = common
123        .instructions
124        .unwrap_or_else(|| config.instructions.clone());
125
126    // Create spinner for message generation
127    let random_message = messages::get_waiting_message();
128    let spinner = ui::create_tui_spinner(&random_message.text);
129
130    // Generate an initial message with spinner display
131    let initial_message = if dry_run {
132        types::GeneratedMessage {
133            title: "Fix bug in UI rendering".to_string(),
134            message: "Updated the layout to properly handle dynamic constraints and improve user experience.".to_string(),
135        }
136    } else {
137        run_with_spinner(spinner, || {
138            service.generate_message(&effective_instructions)
139        })
140        .await?
141    };
142
143    if print {
144        println!("{}", format_commit_message(&initial_message));
145        return Ok(());
146    }
147
148    if auto_commit {
149        // Only allow auto-commit for local repositories
150        if service.is_remote_repository() {
151            ui::print_error(
152                "Cannot automatically commit to a remote repository. Use --print instead.",
153            );
154            return Err(anyhow::anyhow!(
155                "Auto-commit not supported for remote repositories"
156            ));
157        }
158
159        if dry_run {
160            ui::print_info("Dry run mode: would amend commit with message:");
161            println!("{}", format_commit_message(&initial_message));
162            return Ok(());
163        }
164
165        match service.perform_commit(
166            &format_commit_message(&initial_message),
167            amend,
168            commit_ref.as_deref(),
169        ) {
170            Ok(result) => {
171                let output =
172                    format_commit_result(&result, &format_commit_message(&initial_message));
173                println!("{output}");
174            }
175            Err(e) => {
176                eprintln!("Failed to commit: {e}");
177                return Err(e);
178            }
179        }
180        return Ok(());
181    }
182
183    // Only allow interactive commit for local repositories
184    if service.is_remote_repository() {
185        ui::print_warning(
186            "Interactive commit not available for remote repositories. Using print mode instead.",
187        );
188        println!("{}", format_commit_message(&initial_message));
189        return Ok(());
190    }
191
192    run_tui_commit(
193        vec![initial_message],
194        effective_instructions,
195        service,
196        completion_service,
197    )
198    .await?;
199
200    Ok(())
201}
202
203/// Handles the PR description generation command
204pub async fn handle_pr_command(
205    common: CommonParams,
206    _print: bool,
207    repository_url: Option<String>,
208    from: Option<String>,
209    to: Option<String>,
210) -> Result<()> {
211    let mut config = Config::load()?;
212    common.apply_to_config(&mut config)?;
213
214    // Setup the service
215    let service = setup_pr_service(&common, repository_url, &config)?;
216
217    // Generate the PR description
218    let pr_description = generate_pr_based_on_parameters(service, common, config, from, to).await?;
219
220    // Print the PR description to stdout
221    println!("{}", format_pull_request(&pr_description));
222
223    Ok(())
224}
225
226/// Handles the commit message completion command
227#[allow(clippy::too_many_arguments)]
228#[allow(clippy::fn_params_excessive_bools)]
229pub async fn handle_completion_command(
230    common: CommonParams,
231    prefix: String,
232    context_ratio: Option<f32>,
233    print: bool,
234    verify: bool,
235    dry_run: bool,
236    amend: bool,
237    commit_ref: Option<String>,
238    repository_url: Option<String>,
239) -> Result<()> {
240    let mut config = Config::load()?;
241    common.apply_to_config(&mut config)?;
242
243    // Default context ratio to 0.5 (50%) if not specified
244    let context_ratio = context_ratio.unwrap_or(0.5);
245
246    // Validate context ratio
247    if !(0.0..=1.0).contains(&context_ratio) {
248        ui::print_error("Context ratio must be between 0.0 and 1.0");
249        return Err(anyhow::anyhow!("Invalid context ratio: {context_ratio}"));
250    }
251
252    // Provide helpful information about context ratios
253    ui::print_info(&format!(
254        "Completing message with prefix '{}' using {:.0}% context ratio",
255        prefix,
256        context_ratio * 100.0
257    ));
258
259    // Create the completion service
260    let service = create_completion_service(
261        &common,
262        repository_url,
263        &config,
264        verify,
265    ).map_err(|e| {
266        ui::print_error(&format!("Error: {e}"));
267        ui::print_info("\nPlease ensure the following:");
268        ui::print_info("1. Git is installed and accessible from the command line.");
269        ui::print_info(
270            "2. You are running this command from within a Git repository or provide a repository URL with --repo.",
271        );
272        e
273    })?;
274
275    // Validate amend parameters
276    if !amend && commit_ref.is_some() {
277        ui::print_error("--commit can only be used with --amend");
278        return Err(anyhow::anyhow!("--commit requires --amend"));
279    }
280
281    if amend && commit_ref.is_some() && commit_ref.as_deref() != Some("HEAD") {
282        ui::print_error(
283            "Currently, only amending HEAD is supported. For amending other commits, use git directly.",
284        );
285        ui::print_info("Example: git commit --amend");
286        return Err(anyhow::anyhow!(
287            "Only HEAD amendments are currently supported"
288        ));
289    }
290
291    let git_info = service.get_git_info().await?;
292
293    if git_info.staged_files.is_empty() && !dry_run && !amend {
294        ui::print_warning(
295            "No staged changes. Please stage your changes before completing a commit message.",
296        );
297        ui::print_info("You can stage changes using 'git add <file>' or 'git add .'");
298        return Ok(());
299    }
300
301    // Run pre-commit hook before we do anything else
302    if let Err(e) = service.pre_commit() {
303        ui::print_error(&format!("Pre-commit failed: {e}"));
304        return Err(e);
305    }
306
307    let _effective_instructions = common
308        .instructions
309        .unwrap_or_else(|| config.instructions.clone());
310
311    // Create spinner for completion generation
312    let random_message = messages::get_waiting_message();
313    let spinner = ui::create_tui_spinner(&format!(
314        "{} - Completing commit message",
315        random_message.text
316    ));
317
318    // Generate completion with spinner display
319    let completed_message = if dry_run {
320        types::GeneratedMessage {
321            title: format!("{}: Complete the implementation", prefix),
322            message: "Add comprehensive error handling and improve code documentation.".to_string(),
323        }
324    } else {
325        run_with_spinner(spinner, || service.complete_message(&prefix, context_ratio)).await?
326    };
327
328    if print {
329        println!("{}", format_commit_message(&completed_message));
330        return Ok(());
331    }
332
333    // For completion, we don't support auto-commit since the user needs to review the completion
334    if service.is_remote_repository() {
335        ui::print_warning(
336            "Completion not available for remote repositories. Using print mode instead.",
337        );
338        println!("{}", format_commit_message(&completed_message));
339        return Ok(());
340    }
341
342    // Show the completed message and let user decide
343    ui::print_info(&format!("Prefix: {}", prefix));
344    ui::print_info("Completed message:");
345    println!("{}", format_commit_message(&completed_message));
346
347    ui::print_info(
348        "\nUse --print to output only the completed message, or --auto-commit to commit directly.",
349    );
350
351    Ok(())
352}
353
354/// Sets up the PR service with proper configuration
355fn setup_pr_service(
356    common: &CommonParams,
357    repository_url: Option<String>,
358    config: &Config,
359) -> Result<Arc<CommitService>> {
360    // Use the common function for service creation
361    create_commit_service(
362        common,
363        repository_url,
364        config,
365        false, // verification not needed for PR descriptions
366    )
367}
368
369/// Generates a PR description based on the provided parameters
370async fn generate_pr_based_on_parameters(
371    service: Arc<CommitService>,
372    common: CommonParams,
373    config: Config,
374    from: Option<String>,
375    to: Option<String>,
376) -> Result<super::types::GeneratedPullRequest> {
377    let effective_instructions = common
378        .instructions
379        .unwrap_or_else(|| config.instructions.clone());
380
381    // Create spinner for PR generation
382    let random_message = messages::get_waiting_message();
383    let spinner = ui::create_tui_spinner(
384        format!("{} - Generating PR description", random_message.text).as_str(),
385    );
386
387    // Generate PR description with spinner display
388    let pr_description = run_with_spinner(spinner, || async {
389        match (from, to) {
390            (Some(from_ref), Some(to_ref)) => {
391                handle_from_and_to_parameters(
392                    service,
393                    &effective_instructions,
394                    from_ref,
395                    to_ref,
396                    random_message,
397                )
398                .await
399            }
400            (None, Some(to_ref)) => {
401                handle_to_only_parameter(service, &effective_instructions, to_ref, random_message)
402                    .await
403            }
404            (Some(from_ref), None) => {
405                handle_from_only_parameter(
406                    service,
407                    &effective_instructions,
408                    from_ref,
409                    random_message,
410                )
411                .await
412            }
413            (None, None) => {
414                handle_no_parameters(service, &effective_instructions, random_message).await
415            }
416        }
417    })
418    .await?;
419
420    Ok(pr_description)
421}
422
423/// Handle case where both --from and --to parameters are provided
424async fn handle_from_and_to_parameters(
425    service: Arc<CommitService>,
426    effective_instructions: &str,
427    from_ref: String,
428    to_ref: String,
429    random_message: &messages::ColoredMessage,
430) -> Result<super::types::GeneratedPullRequest> {
431    // Special case: if from and to are the same, treat as single commit analysis
432    if from_ref == to_ref {
433        ui::create_tui_spinner(
434            format!(
435                "{} - Analyzing single commit: {}",
436                random_message.text, from_ref
437            )
438            .as_str(),
439        )
440        .tick();
441
442        service
443            .generate_pr_for_commit_range(
444                effective_instructions,
445                &format!("{from_ref}^"),
446                &from_ref,
447            )
448            .await
449    } else if is_likely_commit_hash_or_commitish(&from_ref)
450        || is_likely_commit_hash_or_commitish(&to_ref)
451    {
452        // Check if these look like commit hashes (7+ hex chars) or branches
453        // Treat as commit range
454        ui::create_tui_spinner(
455            format!(
456                "{} - Analyzing commit range: {}..{}",
457                random_message.text, from_ref, to_ref
458            )
459            .as_str(),
460        )
461        .tick();
462
463        service
464            .generate_pr_for_commit_range(effective_instructions, &from_ref, &to_ref)
465            .await
466    } else {
467        // Treat as branch comparison
468        ui::create_tui_spinner(
469            format!(
470                "{} - Comparing branches: {} -> {}",
471                random_message.text, from_ref, to_ref
472            )
473            .as_str(),
474        )
475        .tick();
476
477        service
478            .generate_pr_for_branch_diff(effective_instructions, &from_ref, &to_ref)
479            .await
480    }
481}
482
483/// Handle case where only --to parameter is provided
484async fn handle_to_only_parameter(
485    service: Arc<CommitService>,
486    effective_instructions: &str,
487    to_ref: String,
488    random_message: &messages::ColoredMessage,
489) -> Result<super::types::GeneratedPullRequest> {
490    // Check if this is a single commit hash
491    if is_likely_commit_hash(&to_ref) {
492        // For a single commit specified with --to, compare it against its parent
493        ui::create_tui_spinner(
494            format!(
495                "{} - Analyzing single commit: {}",
496                random_message.text, to_ref
497            )
498            .as_str(),
499        )
500        .tick();
501
502        service
503            .generate_pr_for_commit_range(effective_instructions, &format!("{to_ref}^"), &to_ref)
504            .await
505    } else if is_commitish_syntax(&to_ref) {
506        // For commitish like HEAD~2, compare it against its parent (single commit analysis)
507        SpinnerState::with_message(
508            format!(
509                "{} - Analyzing single commit: {}",
510                random_message.text, to_ref
511            )
512            .as_str(),
513        );
514
515        service
516            .generate_pr_for_commit_range(effective_instructions, &format!("{to_ref}^"), &to_ref)
517            .await
518    } else {
519        // Default from to "main" if only to is specified with a branch name
520        SpinnerState::with_message(
521            format!("{} - Comparing main -> {}", random_message.text, to_ref).as_str(),
522        );
523
524        service
525            .generate_pr_for_branch_diff(effective_instructions, "main", &to_ref)
526            .await
527    }
528}
529
530/// Handle case where only --from parameter is provided
531async fn handle_from_only_parameter(
532    service: Arc<CommitService>,
533    effective_instructions: &str,
534    from_ref: String,
535    random_message: &messages::ColoredMessage,
536) -> Result<super::types::GeneratedPullRequest> {
537    // Check if this looks like a single commit hash that we should compare against its parent
538    if is_likely_commit_hash(&from_ref) {
539        // For a single commit hash, compare it against its parent (commit^..commit)
540        ui::create_tui_spinner(
541            format!(
542                "{} - Analyzing single commit: {}",
543                random_message.text, from_ref
544            )
545            .as_str(),
546        )
547        .tick();
548
549        service
550            .generate_pr_for_commit_range(
551                effective_instructions,
552                &format!("{from_ref}^"),
553                &from_ref,
554            )
555            .await
556    } else if is_commitish_syntax(&from_ref) {
557        // For commitish like HEAD~2, compare from that point to HEAD (reviewing multiple commits)
558        ui::create_tui_spinner(
559            format!(
560                "{} - Analyzing range: {}..HEAD",
561                random_message.text, from_ref
562            )
563            .as_str(),
564        )
565        .tick();
566
567        service
568            .generate_pr_for_commit_range(effective_instructions, &from_ref, "HEAD")
569            .await
570    } else {
571        // For a branch name, compare to HEAD
572        ui::create_tui_spinner(
573            format!(
574                "{} - Analyzing range: {}..HEAD",
575                random_message.text, from_ref
576            )
577            .as_str(),
578        )
579        .tick();
580
581        service
582            .generate_pr_for_commit_range(effective_instructions, &from_ref, "HEAD")
583            .await
584    }
585}
586
587/// Handle case where no parameters are provided
588async fn handle_no_parameters(
589    service: Arc<CommitService>,
590    effective_instructions: &str,
591    random_message: &messages::ColoredMessage,
592) -> Result<super::types::GeneratedPullRequest> {
593    // This case should be caught by validation, but provide a sensible fallback
594    ui::create_tui_spinner(format!("{} - Comparing main -> HEAD", random_message.text).as_str())
595        .tick();
596
597    service
598        .generate_pr_for_branch_diff(effective_instructions, "main", "HEAD")
599        .await
600}
601
602/// Heuristic to determine if a reference looks like a commit hash or commitish
603fn is_likely_commit_hash_or_commitish(reference: &str) -> bool {
604    // Check for commit hash (7+ hex chars)
605    if reference.len() >= 7 && reference.chars().all(|c| c.is_ascii_hexdigit()) {
606        return true;
607    }
608
609    // Check for Git commitish syntax
610    is_commitish_syntax(reference)
611}
612
613/// Check if a reference uses Git commitish syntax
614fn is_commitish_syntax(reference: &str) -> bool {
615    // Common commitish patterns:
616    // HEAD~2, HEAD^, @~3, main~1, origin/main^, etc.
617    reference.contains('~') || reference.contains('^') || reference.starts_with('@')
618}
619
620/// Heuristic to determine if a reference looks like a commit hash (legacy function for backward compatibility)
621fn is_likely_commit_hash(reference: &str) -> bool {
622    reference.len() >= 7 && reference.chars().all(|c| c.is_ascii_hexdigit())
623}
624
625/// Common function to set up `CommitService`
626fn create_commit_service(
627    common: &CommonParams,
628    repository_url: Option<String>,
629    config: &Config,
630    verify: bool,
631) -> Result<Arc<CommitService>> {
632    // Combine repository URL from CLI and CommonParams
633    let repo_url = repository_url.or(common.repository_url.clone());
634
635    // Create the git repository
636    let git_repo = GitRepo::new_from_url(repo_url).context("Failed to create GitRepo")?;
637
638    let repo_path = git_repo.repo_path().clone();
639    let provider_name = &config.default_provider;
640
641    let service = Arc::new(
642        CommitService::new(config.clone(), &repo_path, provider_name, verify, git_repo)
643            .context("Failed to create CommitService")?,
644    );
645
646    // Check environment prerequisites
647    service
648        .check_environment()
649        .context("Environment check failed")?;
650
651    Ok(service)
652}
653
654/// Common function to set up `CompletionService`
655fn create_completion_service(
656    common: &CommonParams,
657    repository_url: Option<String>,
658    config: &Config,
659    verify: bool,
660) -> Result<Arc<CompletionService>> {
661    // Combine repository URL from CLI and CommonParams
662    let repo_url = repository_url.or(common.repository_url.clone());
663
664    // Create the git repository
665    let git_repo = GitRepo::new_from_url(repo_url).context("Failed to create GitRepo")?;
666
667    let repo_path = git_repo.repo_path().clone();
668    let provider_name = &config.default_provider;
669
670    let service = Arc::new(
671        CompletionService::new(config.clone(), &repo_path, provider_name, verify, git_repo)
672            .context("Failed to create CompletionService")?,
673    );
674
675    // Check environment prerequisites
676    service
677        .check_environment()
678        .context("Environment check failed")?;
679
680    Ok(service)
681}