From bbc366b6374f3e5c9359e4b7ab9e670d7b55cc5f Mon Sep 17 00:00:00 2001 From: Patrick Pichler Date: Wed, 6 Oct 2021 20:32:47 +0200 Subject: [PATCH] Add systemwide config file support There is now support for a systemwide config file. The location of the system wide config file is `$(BAT_SYSTEM_CONFIG_PREFIX)/bat/config`. `$(BAT_SYSTEM_CONFIG_PREFIX)` has to be provided at compile time as an environment variable. If the environment variable is not set, a default is used. This default is `C:\ProgramData` for windows and `/etc` for every other os. fixes #668 --- src/bin/bat/config.rs | 32 +++++++++++++++++++++++++++----- src/bin/bat/main.rs | 3 ++- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/bin/bat/config.rs b/src/bin/bat/config.rs index 12fba8bddc..ea3f4fa521 100644 --- a/src/bin/bat/config.rs +++ b/src/bin/bat/config.rs @@ -6,6 +6,22 @@ use std::path::PathBuf; use crate::directories::PROJECT_DIRS; +#[cfg(not(target_os = "windows"))] +const DEFAULT_SYSTEM_CONFIG_PREFIX: &str = "/etc"; + +#[cfg(target_os = "windows")] +const DEFAULT_SYSTEM_CONFIG_PREFIX: &str = "C:\\ProgramData"; + +pub fn system_config_file() -> PathBuf { + let folder = option_env!("BAT_SYSTEM_CONFIG_PREFIX").unwrap_or(DEFAULT_SYSTEM_CONFIG_PREFIX); + let mut path = PathBuf::from(folder); + + path.push("bat"); + path.push("config"); + + path +} + pub fn config_file() -> PathBuf { env::var("BAT_CONFIG_PATH") .ok() @@ -87,11 +103,17 @@ pub fn generate_config_file() -> bat::error::Result<()> { } pub fn get_args_from_config_file() -> Result, shell_words::ParseError> { - Ok(fs::read_to_string(config_file()) - .ok() - .map(|content| get_args_from_str(&content)) - .transpose()? - .unwrap_or_else(Vec::new)) + let mut config = String::new(); + + if let Ok(c) = fs::read_to_string(system_config_file()) { + config.push_str(&c); + } + + if let Ok(c) = fs::read_to_string(config_file()) { + config.push_str(&c); + } + + get_args_from_str(&config) } pub fn get_args_from_env_var() -> Option, shell_words::ParseError>> { diff --git a/src/bin/bat/main.rs b/src/bin/bat/main.rs index 891aace8d6..3642dd9a6c 100644 --- a/src/bin/bat/main.rs +++ b/src/bin/bat/main.rs @@ -18,7 +18,7 @@ use ansi_term::Style; use crate::{ app::App, - config::{config_file, generate_config_file}, + config::{config_file, system_config_file, generate_config_file}, }; use assets::{assets_from_cache_or_binary, cache_dir, clear_assets, config_dir}; @@ -252,6 +252,7 @@ fn invoke_bugreport(app: &App) { "NO_COLOR", "MANPAGER", ])) + .info(FileContent::new("System Config file", system_config_file())) .info(FileContent::new("Config file", config_file())) .info(CompileTimeInformation::default());