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;
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);
let spinner_handle = tokio::spawn(async move {
let mut stdout = io::stdout();
loop {
tokio::select! {
_ = rx.recv() => break, () = time::sleep(Duration::from_millis(100)) => {
let (frame, message, _color, _width) = spinner.tick();
let _ = write!(stdout, "\r{frame} {message}");
let _ = stdout.flush();
}
}
}
let _ = write!(stdout, "\r{}\r", " ".repeat(80));
let _ = stdout.flush();
});
let result = operation().await;
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)?;
let service =
create_commit_service(&common, repository_url.clone(), &config, verify).map_err(|e| {
ui::print_error(&format!("Error: {e}"));
e
})?;
let completion_service = create_completion_service(&common, repository_url, &config, verify)
.map_err(|e| {
ui::print_error(&format!("Error: {e}"));
e
})?;
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(());
}
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());
let random_message = messages::get_waiting_message();
let spinner = ui::create_tui_spinner(&random_message.text);
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 {
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(());
}
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(())
}
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)?;
let service = setup_pr_service(&common, repository_url, &config)?;
let pr_description = generate_pr_based_on_parameters(service, common, config, from, to).await?;
println!("{}", format_pull_request(&pr_description));
Ok(())
}
#[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)?;
let context_ratio = context_ratio.unwrap_or(0.5);
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}"));
}
ui::print_info(&format!(
"Completing message with prefix '{}' using {:.0}% context ratio",
prefix,
context_ratio * 100.0
));
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
})?;
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(());
}
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());
let random_message = messages::get_waiting_message();
let spinner = ui::create_tui_spinner(&format!(
"{} - Completing commit message",
random_message.text
));
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(());
}
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(());
}
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(())
}
fn setup_pr_service(
common: &CommonParams,
repository_url: Option<String>,
config: &Config,
) -> Result<Arc<CommitService>> {
create_commit_service(
common,
repository_url,
config,
false, )
}
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());
let random_message = messages::get_waiting_message();
let spinner = ui::create_tui_spinner(
format!("{} - Generating PR description", random_message.text).as_str(),
);
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)
}
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> {
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)
{
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 {
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
}
}
async fn handle_to_only_parameter(
service: Arc<CommitService>,
effective_instructions: &str,
to_ref: String,
random_message: &messages::ColoredMessage,
) -> Result<super::types::GeneratedPullRequest> {
if is_likely_commit_hash(&to_ref) {
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) {
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 {
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
}
}
async fn handle_from_only_parameter(
service: Arc<CommitService>,
effective_instructions: &str,
from_ref: String,
random_message: &messages::ColoredMessage,
) -> Result<super::types::GeneratedPullRequest> {
if is_likely_commit_hash(&from_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_commitish_syntax(&from_ref) {
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 {
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
}
}
async fn handle_no_parameters(
service: Arc<CommitService>,
effective_instructions: &str,
random_message: &messages::ColoredMessage,
) -> Result<super::types::GeneratedPullRequest> {
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
}
fn is_likely_commit_hash_or_commitish(reference: &str) -> bool {
if reference.len() >= 7 && reference.chars().all(|c| c.is_ascii_hexdigit()) {
return true;
}
is_commitish_syntax(reference)
}
fn is_commitish_syntax(reference: &str) -> bool {
reference.contains('~') || reference.contains('^') || reference.starts_with('@')
}
fn is_likely_commit_hash(reference: &str) -> bool {
reference.len() >= 7 && reference.chars().all(|c| c.is_ascii_hexdigit())
}
fn create_commit_service(
common: &CommonParams,
repository_url: Option<String>,
config: &Config,
verify: bool,
) -> Result<Arc<CommitService>> {
let repo_url = repository_url.or(common.repository_url.clone());
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")?,
);
service
.check_environment()
.context("Environment check failed")?;
Ok(service)
}
fn create_completion_service(
common: &CommonParams,
repository_url: Option<String>,
config: &Config,
verify: bool,
) -> Result<Arc<CompletionService>> {
let repo_url = repository_url.or(common.repository_url.clone());
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")?,
);
service
.check_environment()
.context("Environment check failed")?;
Ok(service)
}