Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow configuring protofetch with a config file #120

Merged
merged 1 commit into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 3 additions & 24 deletions src/api/builder.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
use std::{env, error::Error, path::PathBuf};

use home::home_dir;

use crate::{
config::ProtofetchConfig, git::cache::ProtofetchGitCache, model::protofetch::Protocol,
Protofetch,
};
use crate::{config::ProtofetchConfig, git::cache::ProtofetchGitCache, Protofetch};

#[derive(Default)]
pub struct ProtofetchBuilder {
Expand Down Expand Up @@ -76,19 +71,11 @@ impl ProtofetchBuilder {

let lock_file_name = lock_file_name.unwrap_or_else(|| PathBuf::from("protofetch.lock"));

let cache_directory = root.join(
cache_directory_path
.or(config.cache_dir)
.unwrap_or_else(default_cache_directory),
);
let cache_directory = root.join(cache_directory_path.unwrap_or(config.cache_dir));

let git_config = git2::Config::open_default()?;

let cache = ProtofetchGitCache::new(
cache_directory,
git_config,
config.default_protocol.unwrap_or(Protocol::Ssh),
)?;
let cache = ProtofetchGitCache::new(cache_directory, git_config, config.default_protocol)?;

Ok(Protofetch {
cache,
Expand All @@ -99,11 +86,3 @@ impl ProtofetchBuilder {
})
}
}

fn default_cache_directory() -> PathBuf {
let mut cache_directory =
home_dir().expect("Could not find home dir. Please define $HOME env variable.");
cache_directory.push(".protofetch");
cache_directory.push("cache");
cache_directory
}
113 changes: 99 additions & 14 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
use std::{collections::HashMap, path::PathBuf};

use config::{Config, ConfigError, Environment};
use anyhow::bail;
use config::{Config, ConfigError, Environment, File, FileFormat};
use log::{debug, trace};
use serde::Deserialize;

use crate::model::protofetch::Protocol;

#[derive(Debug)]
pub struct ProtofetchConfig {
pub cache_dir: Option<PathBuf>,
pub default_protocol: Option<Protocol>,
pub cache_dir: PathBuf,
pub default_protocol: Protocol,
}

impl ProtofetchConfig {
pub fn load() -> anyhow::Result<Self> {
let raw_config = RawConfig::load(None)?;
let config_dir = config_dir();
let raw_config = RawConfig::load(config_dir, None, None)?;

Ok(Self {
cache_dir: raw_config.cache.dir,
default_protocol: raw_config.git.protocol,
})
let config = Self {
cache_dir: match raw_config.cache.dir {
Some(cache_dir) => cache_dir,
None => default_cache_dir()?,
},
default_protocol: raw_config.git.protocol.unwrap_or(Protocol::Ssh),
};
trace!("Loaded configuration: {:?}", config);

Ok(config)
}
}

Expand All @@ -40,28 +50,75 @@ struct GitConfig {
}

impl RawConfig {
fn load(env: Option<HashMap<String, String>>) -> Result<Self, ConfigError> {
Config::builder()
fn load(
config_dir: Option<PathBuf>,
config_override: Option<toml::Table>,
env_override: Option<HashMap<String, String>>,
) -> Result<Self, ConfigError> {
let mut builder = Config::builder();

if let Some(mut path) = config_dir {
path.push("config.toml");
debug!("Loading configuration from {}", path.display());
builder = builder.add_source(File::from(path).required(false));
}

if let Some(config_override) = config_override {
builder = builder.add_source(File::from_str(
&config_override.to_string(),
FileFormat::Toml,
));
}

builder
.add_source(
Environment::with_prefix("PROTOFETCH")
.separator("_")
.source(env),
.source(env_override),
)
.build()?
.try_deserialize()
}
}

fn config_dir() -> Option<PathBuf> {
if let Ok(path) = std::env::var("PROTOFETCH_CONFIG_DIR") {
return Some(PathBuf::from(path));
}
if let Ok(path) = std::env::var("XDG_CONFIG_HOME") {
let mut path = PathBuf::from(path);
path.push("protofetch");
return Some(path);
}
if let Some(mut path) = home::home_dir() {
path.push(".config");
path.push("protofetch");
return Some(path);
}
None
}

fn default_cache_dir() -> anyhow::Result<PathBuf> {
if let Some(mut path) = home::home_dir() {
path.push(".protofetch");
path.push("cache");
return Ok(path);
}
bail!("Could not find home dir. Please define $HOME env variable.")
}

#[cfg(test)]
mod tests {
use toml::toml;

use super::*;

use pretty_assertions::assert_eq;

#[test]
fn load_empty() {
let env = HashMap::from([]);
let config = RawConfig::load(Some(env)).unwrap();
let env = HashMap::new();
let config = RawConfig::load(None, Some(Default::default()), Some(env)).unwrap();
assert_eq!(
config,
RawConfig {
Expand All @@ -77,7 +134,35 @@ mod tests {
("PROTOFETCH_CACHE_DIR".to_owned(), "/cache".to_owned()),
("PROTOFETCH_GIT_PROTOCOL".to_owned(), "ssh".to_owned()),
]);
let config = RawConfig::load(Some(env)).unwrap();
let config = RawConfig::load(None, Some(Default::default()), Some(env)).unwrap();
assert_eq!(
config,
RawConfig {
cache: CacheConfig {
dir: Some("/cache".into())
},
git: GitConfig {
protocol: Some(Protocol::Ssh)
}
}
)
}

#[test]
fn load_config_file() {
let env = HashMap::new();
let config = RawConfig::load(
None,
Some(toml! {
[cache]
dir = "/cache"

[git]
protocol = "ssh"
}),
Some(env),
)
.unwrap();
assert_eq!(
config,
RawConfig {
Expand Down