diff --git a/src/commit.rs b/src/commit.rs index c5caf63..dc9a9ce 100644 --- a/src/commit.rs +++ b/src/commit.rs @@ -16,15 +16,15 @@ pub fn git_exec(args: &[&str]) -> Result { } } -pub fn commit_as_hook(commit_message: &str) -> Result<()> { +pub fn get_git_path() -> Result { let output = git_exec(&["rev-parse", "--absolute-git-dir"])?; if !output.status.success() { - return Err(anyhow!("Could not get git directory")); + return Err(anyhow!( + "Failed to get git path. Make sure you are in a git repository" + )); } - let git_dir = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()); - let commit_file_path = git_dir.join("COMMIT_EDITMSG"); - fs::write(commit_file_path, commit_message)?; - Ok(()) + let path = String::from_utf8(output.stdout)?; + Ok(PathBuf::from(path.trim())) } pub fn commit(commit_message: &str) -> Result<()> { @@ -46,3 +46,14 @@ pub fn check_staged_files() -> Result<()> { } Ok(()) } + +pub fn read_cached_commit() -> Result { + let commit_file_path = get_git_path()?.join("COMMIT_EDITMSG"); + let commit_message = fs::read_to_string(commit_file_path)?; + Ok(commit_message) +} + +pub fn write_cached_commit(commit_message: &str) -> Result<()> { + fs::write(get_git_path()?.join("COMMIT_EDITMSG"), commit_message)?; + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 3e74e72..73582d1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,7 @@ use clap::Parser; use std::io::Write; use std::path::PathBuf; -use commit::{check_staged_files, commit, commit_as_hook}; +use commit::{check_staged_files, commit, read_cached_commit, write_cached_commit}; use commit_message::make_message_commit; const DEFAULT_CONFIG_FILE: &str = include_str!("../commit-default.json"); @@ -33,6 +33,9 @@ struct Args { /// Use as hook #[arg(long)] hook: bool, + /// Retry commit with the same message as the last one + #[arg(short, long)] + retry: bool, } fn main() -> Result<()> { @@ -45,17 +48,24 @@ fn main() -> Result<()> { check_staged_files()?; let args = Args::parse(); + if args.init { let mut file = std::fs::File::create("commit.json")?; file.write_all(DEFAULT_CONFIG_FILE.as_bytes())?; return Ok(()); } + if args.retry { + let commit_message = read_cached_commit()?; + commit(&commit_message)?; + return Ok(()); + } + let pattern = config::get_pattern(args.config)?; let commit_message = make_message_commit(pattern)?; + write_cached_commit(&commit_message)?; if args.hook { - commit_as_hook(&commit_message)?; return Ok(()); }