From c779148b30b8b5cc9fdd94fe2f4ffa53a375c09b Mon Sep 17 00:00:00 2001 From: Wander Nauta Date: Sun, 25 Apr 2021 15:23:24 +0200 Subject: [PATCH] Load a commit.template message if one is configured (#546) If a commit message template is set with... git config commit.template /path/to/some/file.txt ...this fills the commit message box (and therefore, later, the external editor) with the contents of that file, as long as you don't have something more interesting typed there already. Like the `git commit` command, this doesn't let you create a commit that has just the template as its message, unchanged. Unlike the `git commit` command, not being able to read the template file is not fatal: specifically, if the commit.template setting is pointed at a file that does not exist, this does nothing. Resolves #546. --- src/components/commit.rs | 35 +++++++++++++++++++++++++++++++---- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/components/commit.rs b/src/components/commit.rs index b55a98c2e8..1f7dbb15ab 100644 --- a/src/components/commit.rs +++ b/src/components/commit.rs @@ -13,12 +13,12 @@ use crate::{ use anyhow::Result; use asyncgit::{ cached, - sync::{self, CommitId, HookResult}, + sync::{self, utils::get_config_string, CommitId, HookResult}, CWD, }; use crossterm::event::Event; use std::{ - fs::File, + fs::{read_to_string, File}, io::{Read, Write}, path::PathBuf, }; @@ -35,6 +35,7 @@ pub struct CommitComponent { queue: Queue, key_config: SharedKeyConfig, git_branch_name: cached::BranchName, + commit_template: Option, } impl DrawableComponent for CommitComponent { @@ -129,6 +130,13 @@ impl Component for CommitComponent { self.input .set_title(strings::commit_title(&self.key_config)); + + if self.is_empty() { + if let Some(s) = &self.commit_template { + self.input.set_text(s.clone()); + } + } + self.input.show()?; Ok(()) @@ -154,12 +162,22 @@ impl CommitComponent { ), key_config, git_branch_name: cached::BranchName::new(CWD), + commit_template: None, } } /// pub fn update(&mut self) -> Result<()> { self.git_branch_name.lookup().map(Some).unwrap_or(None); + + self.commit_template.get_or_insert_with(|| { + get_config_string(CWD, "commit.template") + .ok() + .unwrap_or(None) + .and_then(|path| read_to_string(path).ok()) + .unwrap_or_else(String::new) + }); + Ok(()) } @@ -291,13 +309,22 @@ impl CommitComponent { } fn can_commit(&self) -> bool { - !self.input.get_text().is_empty() + !self.is_empty() && self.is_changed() } fn can_amend(&self) -> bool { self.amend.is_none() && sync::get_head(CWD).is_ok() - && self.input.get_text().is_empty() + && (self.is_empty() || !self.is_changed()) + } + + fn is_empty(&self) -> bool { + self.input.get_text().is_empty() + } + + fn is_changed(&self) -> bool { + Some(self.input.get_text().trim()) + != self.commit_template.as_ref().map(|s| s.trim()) } fn amend(&mut self) -> Result<()> {