From 2915dea4fa1bb10fa4dbc17dd1d51ab917c0f5c4 Mon Sep 17 00:00:00 2001 From: Pedro Mendes Date: Wed, 21 Dec 2022 11:07:18 -0300 Subject: [PATCH] feat: Added retry flag to try commit with the last commit Now the commit message will be saved on git cache every time instead of only in hooks and hooks now will be only a passthrough to commit command --- src/commit.rs | 23 +++++++++++++++++------ src/main.rs | 14 ++++++++++++-- 2 files changed, 29 insertions(+), 8 deletions(-) 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(()); }