From 4058ce12ea7fb26f21bee4f1541a06c6b63a88a9 Mon Sep 17 00:00:00 2001 From: nickelc Date: Sun, 12 Mar 2023 11:46:56 +0100 Subject: [PATCH] Merge the different `GitConfig` constructors for a config file (#1342) The `try_create_from_path` function and the `from_path` function for tests can be merged into a single function. --- src/cli.rs | 5 +++-- src/git_config/mod.rs | 45 ++++++++++++++----------------------------- 2 files changed, 17 insertions(+), 33 deletions(-) diff --git a/src/cli.rs b/src/cli.rs index 853b9a7da..1028fc3a6 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,6 +1,6 @@ use std::collections::{HashMap, HashSet}; use std::ffi::OsString; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use bat::assets::HighlightingAssets; use clap::{ColorChoice, CommandFactory, FromArgMatches, Parser}; @@ -1142,7 +1142,8 @@ impl Opt { if let Some(path) = matches.get_one::("config") { if !path.is_empty() { - final_config = Some(GitConfig::try_create_from_path(&env, path)); + let path = Path::new(path); + final_config = Some(GitConfig::from_path(&env, path, true)); } } diff --git a/src/git_config/mod.rs b/src/git_config/mod.rs index 5a1301125..f508b9335 100644 --- a/src/git_config/mod.rs +++ b/src/git_config/mod.rs @@ -64,13 +64,15 @@ impl GitConfig { } } - #[cfg(not(test))] - pub fn try_create_from_path(env: &DeltaEnv, path: &String) -> Self { - use crate::fatal; + #[cfg(test)] + pub fn try_create(_env: &DeltaEnv) -> Option { + unreachable!("GitConfig::try_create() is not available when testing"); + } - let config = git2::Config::open(Path::new(path)); + pub fn from_path(env: &DeltaEnv, path: &Path, honor_env_var: bool) -> Self { + use crate::fatal; - match config { + match git2::Config::open(path) { Ok(mut config) => { let config = config.snapshot().unwrap_or_else(|err| { fatal(format!("Failed to read git config: {err}")); @@ -78,9 +80,15 @@ impl GitConfig { Self { config, - config_from_env_var: parse_config_from_env_var(env), + config_from_env_var: if honor_env_var { + parse_config_from_env_var(env) + } else { + HashMap::new() + }, repo: None, enabled: true, + #[cfg(test)] + path: path.into(), } } Err(e) => { @@ -89,31 +97,6 @@ impl GitConfig { } } - #[cfg(test)] - pub fn try_create(_env: &DeltaEnv) -> Option { - unreachable!("GitConfig::try_create() is not available when testing"); - } - - #[cfg(test)] - pub fn try_create_from_path(_env: &DeltaEnv, _path: &String) -> Self { - unreachable!("GitConfig::try_create_from_path() is not available when testing"); - } - - #[cfg(test)] - pub fn from_path(env: &DeltaEnv, path: &Path, honor_env_var: bool) -> Self { - Self { - config: git2::Config::open(path).unwrap(), - config_from_env_var: if honor_env_var { - parse_config_from_env_var(env) - } else { - HashMap::new() - }, - repo: None, - enabled: true, - path: path.into(), - } - } - pub fn get(&self, key: &str) -> Option where T: GitConfigGet,