gait 0.1.3

AI-powered toolkit that enhances `Git` workflow
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use super::completion::CompletionService;
use super::format_commit_result;
use super::service::CommitService;
use super::types::{format_commit_message, format_pull_request};
use crate::common::CommonParams;
use crate::config::Config;
use crate::core::messages;
use crate::features::commit::types;
use crate::git::GitRepo;
use crate::tui::run_tui_commit;
use crate::ui::{self, SpinnerState};

use anyhow::{Context, Result};
use std::{
    io::{self, Write},
    sync::Arc,
    time::Duration,
};
use tokio::time;

/// Run an async operation with a CLI spinner display
async fn run_with_spinner<F, Fut, T>(
    mut spinner: SpinnerState,
    operation: F,
) -> Result<T, anyhow::Error>
where
    F: FnOnce() -> Fut,
    Fut: std::future::Future<Output = Result<T, anyhow::Error>>,
{
    let (tx, mut rx) = tokio::sync::mpsc::channel(1);

    // Spawn spinner animation task
    let spinner_handle = tokio::spawn(async move {
        let mut stdout = io::stdout();
        loop {
            tokio::select! {
                _ = rx.recv() => break, // Stop signal received
                () = time::sleep(Duration::from_millis(100)) => {
                    let (frame, message, _color, _width) = spinner.tick();
                    let _ = write!(stdout, "\r{frame} {message}");
                    let _ = stdout.flush();
                }
            }
        }
        // Clear the spinner line
        let _ = write!(stdout, "\r{}\r", " ".repeat(80));
        let _ = stdout.flush();
    });

    // Run the operation
    let result = operation().await;

    // Stop the spinner
    let _ = tx.send(()).await;
    spinner_handle.await?;

    result
}

#[allow(clippy::fn_params_excessive_bools)]
#[allow(clippy::too_many_lines)]
#[allow(clippy::too_many_arguments)]
pub async fn handle_message_command(
    common: CommonParams,
    auto_commit: bool,
    print: bool,
    verify: bool,
    dry_run: bool,
    amend: bool,
    commit_ref: Option<String>,
    repository_url: Option<String>,
) -> Result<()> {
    let mut config = Config::load()?;
    common.apply_to_config(&mut config)?;

    // Create the service using the common function
    let service =
        create_commit_service(&common, repository_url.clone(), &config, verify).map_err(|e| {
            ui::print_error(&format!("Error: {e}"));
            e
        })?;

    // Create the completion service
    let completion_service = create_completion_service(&common, repository_url, &config, verify)
        .map_err(|e| {
            ui::print_error(&format!("Error: {e}"));
            e
        })?;

    // Validate amend parameters
    if !amend && commit_ref.is_some() {
        ui::print_error("--commit can only be used with --amend");
        return Err(anyhow::anyhow!("--commit requires --amend"));
    }

    if amend && commit_ref.is_some() && commit_ref.as_deref() != Some("HEAD") {
        ui::print_error(
            "Currently, only amending HEAD is supported. For amending other commits, use git directly.",
        );
        ui::print_info("Example: git commit --amend");
        return Err(anyhow::anyhow!(
            "Only HEAD amendments are currently supported"
        ));
    }

    let git_info = service.get_git_info().await?;

    if git_info.staged_files.is_empty() && !dry_run && !amend {
        ui::print_warning(
            "No staged changes. Please stage your changes before generating a commit message.",
        );
        ui::print_info("You can stage changes using 'git add <file>' or 'git add .'");
        return Ok(());
    }

    // Run pre-commit hook before we do anything else
    if let Err(e) = service.pre_commit() {
        ui::print_error(&format!("Pre-commit failed: {e}"));
        return Err(e);
    }

    let effective_instructions = common
        .instructions
        .unwrap_or_else(|| config.instructions.clone());

    // Create spinner for message generation
    let random_message = messages::get_waiting_message();
    let spinner = ui::create_tui_spinner(&random_message.text);

    // Generate an initial message with spinner display
    let initial_message = if dry_run {
        types::GeneratedMessage {
            title: "Fix bug in UI rendering".to_string(),
            message: "Updated the layout to properly handle dynamic constraints and improve user experience.".to_string(),
        }
    } else {
        run_with_spinner(spinner, || {
            service.generate_message(&effective_instructions)
        })
        .await?
    };

    if print {
        println!("{}", format_commit_message(&initial_message));
        return Ok(());
    }

    if auto_commit {
        // Only allow auto-commit for local repositories
        if service.is_remote_repository() {
            ui::print_error(
                "Cannot automatically commit to a remote repository. Use --print instead.",
            );
            return Err(anyhow::anyhow!(
                "Auto-commit not supported for remote repositories"
            ));
        }

        if dry_run {
            ui::print_info("Dry run mode: would amend commit with message:");
            println!("{}", format_commit_message(&initial_message));
            return Ok(());
        }

        match service.perform_commit(
            &format_commit_message(&initial_message),
            amend,
            commit_ref.as_deref(),
        ) {
            Ok(result) => {
                let output =
                    format_commit_result(&result, &format_commit_message(&initial_message));
                println!("{output}");
            }
            Err(e) => {
                eprintln!("Failed to commit: {e}");
                return Err(e);
            }
        }
        return Ok(());
    }

    // Only allow interactive commit for local repositories
    if service.is_remote_repository() {
        ui::print_warning(
            "Interactive commit not available for remote repositories. Using print mode instead.",
        );
        println!("{}", format_commit_message(&initial_message));
        return Ok(());
    }

    run_tui_commit(
        vec![initial_message],
        effective_instructions,
        service,
        completion_service,
    )
    .await?;

    Ok(())
}

/// Handles the PR description generation command
pub async fn handle_pr_command(
    common: CommonParams,
    _print: bool,
    repository_url: Option<String>,
    from: Option<String>,
    to: Option<String>,
) -> Result<()> {
    let mut config = Config::load()?;
    common.apply_to_config(&mut config)?;

    // Setup the service
    let service = setup_pr_service(&common, repository_url, &config)?;

    // Generate the PR description
    let pr_description = generate_pr_based_on_parameters(service, common, config, from, to).await?;

    // Print the PR description to stdout
    println!("{}", format_pull_request(&pr_description));

    Ok(())
}

/// Handles the commit message completion command
#[allow(clippy::too_many_arguments)]
#[allow(clippy::fn_params_excessive_bools)]
pub async fn handle_completion_command(
    common: CommonParams,
    prefix: String,
    context_ratio: Option<f32>,
    print: bool,
    verify: bool,
    dry_run: bool,
    amend: bool,
    commit_ref: Option<String>,
    repository_url: Option<String>,
) -> Result<()> {
    let mut config = Config::load()?;
    common.apply_to_config(&mut config)?;

    // Default context ratio to 0.5 (50%) if not specified
    let context_ratio = context_ratio.unwrap_or(0.5);

    // Validate context ratio
    if !(0.0..=1.0).contains(&context_ratio) {
        ui::print_error("Context ratio must be between 0.0 and 1.0");
        return Err(anyhow::anyhow!("Invalid context ratio: {context_ratio}"));
    }

    // Provide helpful information about context ratios
    ui::print_info(&format!(
        "Completing message with prefix '{}' using {:.0}% context ratio",
        prefix,
        context_ratio * 100.0
    ));

    // Create the completion service
    let service = create_completion_service(
        &common,
        repository_url,
        &config,
        verify,
    ).map_err(|e| {
        ui::print_error(&format!("Error: {e}"));
        ui::print_info("\nPlease ensure the following:");
        ui::print_info("1. Git is installed and accessible from the command line.");
        ui::print_info(
            "2. You are running this command from within a Git repository or provide a repository URL with --repo.",
        );
        e
    })?;

    // Validate amend parameters
    if !amend && commit_ref.is_some() {
        ui::print_error("--commit can only be used with --amend");
        return Err(anyhow::anyhow!("--commit requires --amend"));
    }

    if amend && commit_ref.is_some() && commit_ref.as_deref() != Some("HEAD") {
        ui::print_error(
            "Currently, only amending HEAD is supported. For amending other commits, use git directly.",
        );
        ui::print_info("Example: git commit --amend");
        return Err(anyhow::anyhow!(
            "Only HEAD amendments are currently supported"
        ));
    }

    let git_info = service.get_git_info().await?;

    if git_info.staged_files.is_empty() && !dry_run && !amend {
        ui::print_warning(
            "No staged changes. Please stage your changes before completing a commit message.",
        );
        ui::print_info("You can stage changes using 'git add <file>' or 'git add .'");
        return Ok(());
    }

    // Run pre-commit hook before we do anything else
    if let Err(e) = service.pre_commit() {
        ui::print_error(&format!("Pre-commit failed: {e}"));
        return Err(e);
    }

    let _effective_instructions = common
        .instructions
        .unwrap_or_else(|| config.instructions.clone());

    // Create spinner for completion generation
    let random_message = messages::get_waiting_message();
    let spinner = ui::create_tui_spinner(&format!(
        "{} - Completing commit message",
        random_message.text
    ));

    // Generate completion with spinner display
    let completed_message = if dry_run {
        types::GeneratedMessage {
            title: format!("{}: Complete the implementation", prefix),
            message: "Add comprehensive error handling and improve code documentation.".to_string(),
        }
    } else {
        run_with_spinner(spinner, || service.complete_message(&prefix, context_ratio)).await?
    };

    if print {
        println!("{}", format_commit_message(&completed_message));
        return Ok(());
    }

    // For completion, we don't support auto-commit since the user needs to review the completion
    if service.is_remote_repository() {
        ui::print_warning(
            "Completion not available for remote repositories. Using print mode instead.",
        );
        println!("{}", format_commit_message(&completed_message));
        return Ok(());
    }

    // Show the completed message and let user decide
    ui::print_info(&format!("Prefix: {}", prefix));
    ui::print_info("Completed message:");
    println!("{}", format_commit_message(&completed_message));

    ui::print_info(
        "\nUse --print to output only the completed message, or --auto-commit to commit directly.",
    );

    Ok(())
}

/// Sets up the PR service with proper configuration
fn setup_pr_service(
    common: &CommonParams,
    repository_url: Option<String>,
    config: &Config,
) -> Result<Arc<CommitService>> {
    // Use the common function for service creation
    create_commit_service(
        common,
        repository_url,
        config,
        false, // verification not needed for PR descriptions
    )
}

/// Generates a PR description based on the provided parameters
async fn generate_pr_based_on_parameters(
    service: Arc<CommitService>,
    common: CommonParams,
    config: Config,
    from: Option<String>,
    to: Option<String>,
) -> Result<super::types::GeneratedPullRequest> {
    let effective_instructions = common
        .instructions
        .unwrap_or_else(|| config.instructions.clone());

    // Create spinner for PR generation
    let random_message = messages::get_waiting_message();
    let spinner = ui::create_tui_spinner(
        format!("{} - Generating PR description", random_message.text).as_str(),
    );

    // Generate PR description with spinner display
    let pr_description = run_with_spinner(spinner, || async {
        match (from, to) {
            (Some(from_ref), Some(to_ref)) => {
                handle_from_and_to_parameters(
                    service,
                    &effective_instructions,
                    from_ref,
                    to_ref,
                    random_message,
                )
                .await
            }
            (None, Some(to_ref)) => {
                handle_to_only_parameter(service, &effective_instructions, to_ref, random_message)
                    .await
            }
            (Some(from_ref), None) => {
                handle_from_only_parameter(
                    service,
                    &effective_instructions,
                    from_ref,
                    random_message,
                )
                .await
            }
            (None, None) => {
                handle_no_parameters(service, &effective_instructions, random_message).await
            }
        }
    })
    .await?;

    Ok(pr_description)
}

/// Handle case where both --from and --to parameters are provided
async fn handle_from_and_to_parameters(
    service: Arc<CommitService>,
    effective_instructions: &str,
    from_ref: String,
    to_ref: String,
    random_message: &messages::ColoredMessage,
) -> Result<super::types::GeneratedPullRequest> {
    // Special case: if from and to are the same, treat as single commit analysis
    if from_ref == to_ref {
        ui::create_tui_spinner(
            format!(
                "{} - Analyzing single commit: {}",
                random_message.text, from_ref
            )
            .as_str(),
        )
        .tick();

        service
            .generate_pr_for_commit_range(
                effective_instructions,
                &format!("{from_ref}^"),
                &from_ref,
            )
            .await
    } else if is_likely_commit_hash_or_commitish(&from_ref)
        || is_likely_commit_hash_or_commitish(&to_ref)
    {
        // Check if these look like commit hashes (7+ hex chars) or branches
        // Treat as commit range
        ui::create_tui_spinner(
            format!(
                "{} - Analyzing commit range: {}..{}",
                random_message.text, from_ref, to_ref
            )
            .as_str(),
        )
        .tick();

        service
            .generate_pr_for_commit_range(effective_instructions, &from_ref, &to_ref)
            .await
    } else {
        // Treat as branch comparison
        ui::create_tui_spinner(
            format!(
                "{} - Comparing branches: {} -> {}",
                random_message.text, from_ref, to_ref
            )
            .as_str(),
        )
        .tick();

        service
            .generate_pr_for_branch_diff(effective_instructions, &from_ref, &to_ref)
            .await
    }
}

/// Handle case where only --to parameter is provided
async fn handle_to_only_parameter(
    service: Arc<CommitService>,
    effective_instructions: &str,
    to_ref: String,
    random_message: &messages::ColoredMessage,
) -> Result<super::types::GeneratedPullRequest> {
    // Check if this is a single commit hash
    if is_likely_commit_hash(&to_ref) {
        // For a single commit specified with --to, compare it against its parent
        ui::create_tui_spinner(
            format!(
                "{} - Analyzing single commit: {}",
                random_message.text, to_ref
            )
            .as_str(),
        )
        .tick();

        service
            .generate_pr_for_commit_range(effective_instructions, &format!("{to_ref}^"), &to_ref)
            .await
    } else if is_commitish_syntax(&to_ref) {
        // For commitish like HEAD~2, compare it against its parent (single commit analysis)
        SpinnerState::with_message(
            format!(
                "{} - Analyzing single commit: {}",
                random_message.text, to_ref
            )
            .as_str(),
        );

        service
            .generate_pr_for_commit_range(effective_instructions, &format!("{to_ref}^"), &to_ref)
            .await
    } else {
        // Default from to "main" if only to is specified with a branch name
        SpinnerState::with_message(
            format!("{} - Comparing main -> {}", random_message.text, to_ref).as_str(),
        );

        service
            .generate_pr_for_branch_diff(effective_instructions, "main", &to_ref)
            .await
    }
}

/// Handle case where only --from parameter is provided
async fn handle_from_only_parameter(
    service: Arc<CommitService>,
    effective_instructions: &str,
    from_ref: String,
    random_message: &messages::ColoredMessage,
) -> Result<super::types::GeneratedPullRequest> {
    // Check if this looks like a single commit hash that we should compare against its parent
    if is_likely_commit_hash(&from_ref) {
        // For a single commit hash, compare it against its parent (commit^..commit)
        ui::create_tui_spinner(
            format!(
                "{} - Analyzing single commit: {}",
                random_message.text, from_ref
            )
            .as_str(),
        )
        .tick();

        service
            .generate_pr_for_commit_range(
                effective_instructions,
                &format!("{from_ref}^"),
                &from_ref,
            )
            .await
    } else if is_commitish_syntax(&from_ref) {
        // For commitish like HEAD~2, compare from that point to HEAD (reviewing multiple commits)
        ui::create_tui_spinner(
            format!(
                "{} - Analyzing range: {}..HEAD",
                random_message.text, from_ref
            )
            .as_str(),
        )
        .tick();

        service
            .generate_pr_for_commit_range(effective_instructions, &from_ref, "HEAD")
            .await
    } else {
        // For a branch name, compare to HEAD
        ui::create_tui_spinner(
            format!(
                "{} - Analyzing range: {}..HEAD",
                random_message.text, from_ref
            )
            .as_str(),
        )
        .tick();

        service
            .generate_pr_for_commit_range(effective_instructions, &from_ref, "HEAD")
            .await
    }
}

/// Handle case where no parameters are provided
async fn handle_no_parameters(
    service: Arc<CommitService>,
    effective_instructions: &str,
    random_message: &messages::ColoredMessage,
) -> Result<super::types::GeneratedPullRequest> {
    // This case should be caught by validation, but provide a sensible fallback
    ui::create_tui_spinner(format!("{} - Comparing main -> HEAD", random_message.text).as_str())
        .tick();

    service
        .generate_pr_for_branch_diff(effective_instructions, "main", "HEAD")
        .await
}

/// Heuristic to determine if a reference looks like a commit hash or commitish
fn is_likely_commit_hash_or_commitish(reference: &str) -> bool {
    // Check for commit hash (7+ hex chars)
    if reference.len() >= 7 && reference.chars().all(|c| c.is_ascii_hexdigit()) {
        return true;
    }

    // Check for Git commitish syntax
    is_commitish_syntax(reference)
}

/// Check if a reference uses Git commitish syntax
fn is_commitish_syntax(reference: &str) -> bool {
    // Common commitish patterns:
    // HEAD~2, HEAD^, @~3, main~1, origin/main^, etc.
    reference.contains('~') || reference.contains('^') || reference.starts_with('@')
}

/// Heuristic to determine if a reference looks like a commit hash (legacy function for backward compatibility)
fn is_likely_commit_hash(reference: &str) -> bool {
    reference.len() >= 7 && reference.chars().all(|c| c.is_ascii_hexdigit())
}

/// Common function to set up `CommitService`
fn create_commit_service(
    common: &CommonParams,
    repository_url: Option<String>,
    config: &Config,
    verify: bool,
) -> Result<Arc<CommitService>> {
    // Combine repository URL from CLI and CommonParams
    let repo_url = repository_url.or(common.repository_url.clone());

    // Create the git repository
    let git_repo = GitRepo::new_from_url(repo_url).context("Failed to create GitRepo")?;

    let repo_path = git_repo.repo_path().clone();
    let provider_name = &config.default_provider;

    let service = Arc::new(
        CommitService::new(config.clone(), &repo_path, provider_name, verify, git_repo)
            .context("Failed to create CommitService")?,
    );

    // Check environment prerequisites
    service
        .check_environment()
        .context("Environment check failed")?;

    Ok(service)
}

/// Common function to set up `CompletionService`
fn create_completion_service(
    common: &CommonParams,
    repository_url: Option<String>,
    config: &Config,
    verify: bool,
) -> Result<Arc<CompletionService>> {
    // Combine repository URL from CLI and CommonParams
    let repo_url = repository_url.or(common.repository_url.clone());

    // Create the git repository
    let git_repo = GitRepo::new_from_url(repo_url).context("Failed to create GitRepo")?;

    let repo_path = git_repo.repo_path().clone();
    let provider_name = &config.default_provider;

    let service = Arc::new(
        CompletionService::new(config.clone(), &repo_path, provider_name, verify, git_repo)
            .context("Failed to create CompletionService")?,
    );

    // Check environment prerequisites
    service
        .check_environment()
        .context("Environment check failed")?;

    Ok(service)
}