use std::fs::read_to_string;
use std::path::PathBuf;
use anyhow::{Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use cocogitto::command::commit::CommitOptions;
use conventional_commit_parser::parse;
use cucco::answers::{ExtractedAnswers, get_extracted_answers};
use cucco::commit::{commit, generate_commit_msg, stage_changes, write_commit_msg};
use cucco::config::{Config, ConfigArgs};
use cucco::questions::{create_prompt, prompt_confirm};
use cucco::scope::detect_scope_matches;
use cucco::status::{StagingStatus, check_staging, has_tracked_changes};
#[derive(Parser, Debug)]
#[command(
about = "🐓 An interactive CLI for creating conventional commits.",
version
)]
struct Args {
#[command(subcommand)]
command: Option<SubCmds>,
#[arg(
long,
default_missing_value = "true",
num_args = 0..=1,
value_name = "ENABLE",
help_heading = Some("Configuration"),
help = "Enables autocomplete for scope prompt via scanning commit history"
)]
autocomplete: Option<bool>,
#[arg(
long,
default_missing_value = "true",
num_args = 0..=1,
value_name = "ENABLE",
help_heading = Some("Configuration"),
help = "Enables breaking change prompts, one of them for adding the BREAKING CHANGE footer"
)]
breaking_changes: Option<bool>,
#[arg(
short,
long,
value_name = "FILE",
help_heading = Some("Configuration"),
help = "Path to a custom config file"
)]
config: Option<PathBuf>,
#[arg(
long,
default_missing_value = "true",
num_args = 0..=1,
value_name = "ENABLE",
help_heading = Some("Configuration"),
help = "Prepend the commit summary with relevant emoji based on commit type"
)]
emoji: Option<bool>,
#[arg(
long,
help = "Run as a git hook, writing the commit message to COMMIT_EDITMSG instead of committing",
conflicts_with = "all",
conflicts_with = "add_all"
)]
hook: bool,
#[arg(
long,
help = "Outputs the commit message to stdout instead of committing",
conflicts_with = "all",
conflicts_with = "add_all",
conflicts_with = "hook"
)]
stdout: bool,
#[arg(
long,
default_missing_value = "true",
num_args = 0..=1,
value_name = "ENABLE",
help_heading = Some("Configuration"),
help = "Enables issue prompts, to add a footer for issue references"
)]
issues: Option<bool>,
#[arg(
short = 'S',
long,
default_missing_value = "true",
num_args = 0..=1,
value_name = "ENABLE",
help_heading = Some("Configuration"),
help = "Sign the commit using the user's GPG key, if one is configured"
)]
sign: Option<bool>,
#[arg(
short,
long,
help = "Stage modified and deleted tracked files, like `git commit -a`"
)]
all: bool,
#[arg(
short = 'A',
long,
help = "Stage all changes, untracked files included, like `git add -A`",
conflicts_with = "all"
)]
add_all: bool,
#[arg(
long,
help = "Bypass the pre-commit and post-commit git hooks",
conflicts_with = "hook"
)]
no_verify: bool,
#[arg(
short = 'y',
long,
help = "Skip the confirmation prompt and proceed with the commit"
)]
yes: bool,
#[arg(
short = 'C',
value_name = "PATH",
help = "Run as if cucco was started in <path>"
)]
current_workdir: Option<PathBuf>,
}
#[derive(Debug, Subcommand)]
enum SubCmds {
#[command(about = "Generate shell completions")]
Completions { shell: clap_complete_command::Shell },
}
fn main() -> Result<()> {
let Args {
command,
autocomplete,
breaking_changes,
config,
emoji,
hook,
stdout,
issues,
sign,
all,
add_all,
no_verify,
yes,
current_workdir,
} = Args::parse();
if let Some(command) = command {
match command {
SubCmds::Completions { shell } => {
shell.generate(&mut Args::command(), &mut std::io::stdout());
}
}
return Ok(());
}
let current_dir = match current_workdir {
Some(dir) => dir,
None => std::env::current_dir()?,
};
let repo = gix::discover(¤t_dir).context("could not find git repository")?;
let commit_editmsg = repo.path().join("COMMIT_EDITMSG");
let commit_message = match read_to_string(commit_editmsg) {
Ok(contents) => contents.lines().next().unwrap_or("").to_string(),
Err(_) => "".to_string(),
};
if hook && parse(&commit_message).is_ok() {
return Ok(());
}
if !hook && !stdout && !add_all {
if all {
if !has_tracked_changes(&repo)? {
anyhow::bail!("no tracked changes to commit (use -A to include untracked files)");
}
} else {
match check_staging(&repo)? {
StagingStatus::Empty => {
anyhow::bail!("no files staged for commit");
}
StagingStatus::Partial { staged, unstaged } => {
eprintln!(
"Warning: {staged} file(s) staged for commit, \
{unstaged} file(s) with unstaged changes not included\n"
);
}
StagingStatus::Ready { .. } => {}
}
}
}
let config = Config::new(Some(ConfigArgs {
autocomplete,
breaking_changes,
emoji,
issues,
path: config,
sign,
_user_config_path: None,
_current_dir: Some(current_dir.clone()),
..Default::default()
}))?;
if all || add_all {
stage_changes(&repo, add_all).context("failed to pre-stage changes")?;
}
let scope_matches = detect_scope_matches(&repo, &config)?;
let answers = create_prompt(commit_message, &config, &scope_matches)?;
let ExtractedAnswers {
body,
commit_type,
is_breaking_change,
scope,
summary,
} = get_extracted_answers(answers, config.emoji, &config.commit_types)?;
let message = generate_commit_msg(
&commit_type,
scope.as_deref(),
&summary,
body.as_deref(),
is_breaking_change,
)?;
if stdout {
println!("{message}");
} else {
eprintln!("\n{message}\n");
}
if stdout {
return Ok(());
}
if !yes && !prompt_confirm()? {
eprintln!("Commit aborted.");
return Ok(());
}
if hook {
write_commit_msg(
&repo,
&commit_type,
scope.as_deref(),
&summary,
body.as_deref(),
is_breaking_change,
)?;
} else {
let options = CommitOptions {
commit_type: commit_type.as_str(),
scope,
summary,
body,
footer: None,
breaking: is_breaking_change,
sign: config.sign,
add_files: add_all,
update_files: all,
};
commit(current_dir, options, no_verify)?;
}
Ok(())
}