use crate::error::{Failure, Result};
use directories::ProjectDirs;
use std::path::{Path, PathBuf};
pub const FILE_NAME: &str = "config.toml";
const QUALIFIER: &str = "";
const ORGANISATION: &str = "";
const APPLICATION: &str = "mariadb-cli";
pub fn config_dir(override_dir: Option<&Path>) -> Result<PathBuf> {
if let Some(chosen) = override_dir {
return Ok(chosen.to_path_buf());
}
ProjectDirs::from(QUALIFIER, ORGANISATION, APPLICATION)
.map(|dirs| dirs.config_dir().to_path_buf())
.ok_or_else(|| {
Failure::config(
"config.no_home_directory",
"this host does not say where a user's files belong",
)
.with_hint("pass --config-dir to name the location yourself")
})
}
pub fn config_file(override_dir: Option<&Path>) -> Result<PathBuf> {
Ok(config_dir(override_dir)?.join(FILE_NAME))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_named_location_wins_over_the_system_one() {
let chosen = Path::new("/tmp/some-location");
assert_eq!(
config_dir(Some(chosen)).expect("named location"),
PathBuf::from("/tmp/some-location")
);
}
#[test]
fn the_file_always_sits_inside_the_directory() {
let chosen = Path::new("/tmp/some-location");
let file = config_file(Some(chosen)).expect("named location");
assert_eq!(file.parent(), Some(chosen));
assert_eq!(
file.file_name().and_then(std::ffi::OsStr::to_str),
Some(FILE_NAME)
);
}
#[test]
fn the_system_location_is_never_assembled_by_hand() {
match config_dir(None) {
Ok(path) => assert!(path.is_absolute(), "a guessed relative path is a defect"),
Err(failure) => assert_eq!(failure.code(), "config.no_home_directory"),
}
}
}