use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fs;
use std::io;
use std::path::{Path as FsPath, PathBuf};
use std::rc::Rc;
use crate::config::Config;
use crate::env;
use crate::mark::Mark;
use crate::names::similar_names;
use crate::path::Path;
use crate::problems::{Kind, Problem, Problems, Severity};
use crate::raw::Raw;
use crate::yaml::{self, Parsed};
const GLOBAL_STEM: &str = "config";
const EXTENSION: &str = "yaml";
const SPECIAL_DIR: &str = "Configs";
#[derive(Debug, Clone)]
pub struct Source {
directory: PathBuf,
env_suffix: Option<String>,
environment: Environment,
}
impl Source {
pub fn directory(path: impl Into<PathBuf>) -> Self {
Self {
directory: path.into(),
env_suffix: None,
environment: Environment::Process,
}
}
pub fn env_suffix(mut self, suffix: impl Into<String>) -> Self {
self.env_suffix = Some(suffix.into());
self
}
pub fn environment(
mut self,
variables: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Self {
self.environment = Environment::Given(
variables
.into_iter()
.map(|(name, value)| (name.into(), value.into()))
.collect(),
);
self
}
fn shown(&self, relative: &str) -> String {
let directory = self.directory.display().to_string();
if directory.is_empty() || directory == "." {
relative.to_owned()
} else {
format!("{directory}/{relative}")
}
}
}
#[derive(Debug, Clone)]
pub(crate) enum Environment {
Process,
Given(BTreeMap<String, String>),
}
impl Environment {
pub(crate) fn pairs(&self) -> Vec<(String, OsString)> {
match self {
Self::Process => std::env::vars_os()
.filter_map(|(name, value)| Some((name.into_string().ok()?, value)))
.collect(),
Self::Given(variables) => variables
.iter()
.map(|(name, value)| (name.clone(), value.into()))
.collect(),
}
}
}
#[derive(Debug, Clone)]
pub struct Loaded<T> {
pub value: T,
pub warnings: Vec<Problem>,
}
pub fn load<T: Config>(source: &Source) -> Result<Loaded<T>, Problems> {
read(source, |_, _| {})
}
pub(crate) fn read<T: Config>(
source: &Source,
after: impl FnOnce(&T, &mut Problems),
) -> Result<Loaded<T>, Problems> {
let mut problems = if env::lenient(&source.environment) {
Problems::lenient()
} else {
Problems::new()
};
let variables = env::select(T::NAME, &source.environment, &mut problems);
let root = Path::new();
let mut value = T::default();
for tree in trees::<T>(source, &mut problems) {
T::overlay(&mut value, &tree, &root, &mut problems).ok();
}
for variable in &variables {
T::overlay(&mut value, &env::tree(variable), &root, &mut problems).ok();
}
note_relaxed(&mut problems);
if problems.has_errors() {
return Err(problems);
}
value.check(&root, &mut problems);
after(&value, &mut problems);
if problems.has_errors() {
return Err(problems);
}
let warnings = problems
.into_iter()
.filter(|problem| problem.severity == Severity::Warning)
.collect();
Ok(Loaded { value, warnings })
}
fn note_relaxed(problems: &mut Problems) {
let relaxed = problems
.iter()
.any(|problem| problem.kind == Kind::UnknownName && problem.severity == Severity::Warning);
if relaxed {
let message = format!(
"unknown names are warnings because {}={} is set; fix the names above and remove the variable",
env::LENIENT_UNKNOWN_NAMES,
env::LENIENT_VALUE
);
problems.warning(Kind::Strictness, &Mark::Model, Path::new(), message);
}
}
pub(crate) fn check_global(known: &[&str], source: &Source) -> Result<Vec<Problem>, Problems> {
let mut problems = if env::lenient(&source.environment) {
Problems::lenient()
} else {
Problems::new()
};
for suffix in std::iter::once(None).chain(source.env_suffix.as_deref().map(Some)) {
let relative = Mode::Global.file("", suffix);
let Slurp::Read(text) = slurp(&source.directory.join(&relative)) else {
continue;
};
let shown = source.shown(&relative);
let parsed = yaml::read(&text, &Rc::from(shown.as_str()), &mut problems);
let Parsed::Tree(raw) = parsed else {
continue;
};
let Some(entries) = raw.entries() else {
let mark = Mark::File(shown.into(), 1);
let message = "expected a mapping at the top level of the file".to_owned();
problems.error(Kind::Source, &mark, Path::new(), message);
continue;
};
for (key, _) in entries {
if !known.contains(&key.text()) {
let similar = similar_names(key.text(), known);
problems.unknown_name(key.mark(), Path::new(), key.text(), similar);
}
}
}
note_relaxed(&mut problems);
if problems.has_errors() {
Err(problems)
} else {
let warnings = problems
.into_iter()
.filter(|problem| problem.severity == Severity::Warning)
.collect();
Ok(warnings)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Special,
Global,
}
impl Mode {
fn file(self, name: &str, suffix: Option<&str>) -> String {
let suffix = suffix.map_or(String::new(), |suffix| format!(".{suffix}"));
match self {
Self::Special => format!("{SPECIAL_DIR}/{name}{suffix}.{EXTENSION}"),
Self::Global => format!("{GLOBAL_STEM}{suffix}.{EXTENSION}"),
}
}
fn tree(self, key: &str, parsed: Parsed, shown: &str, problems: &mut Problems) -> Option<Raw> {
let mark = Mark::File(shown.into(), 1);
match parsed {
Parsed::Failed => None,
Parsed::Empty => {
problems.error(
Kind::Source,
&mark,
Path::new(),
"the file has no document".to_owned(),
);
None
}
Parsed::Tree(raw) => match self {
Self::Special => Some(raw),
Self::Global => {
let section = key;
let found = raw.entries().and_then(|entries| {
entries
.iter()
.find(|(key, _)| key.text() == section)
.map(|(_, value)| value)
});
match found {
Some(value) if !value.is_null() => Some(value.clone()),
Some(_) | None => {
let message = format!("the file has no section `{section}`");
problems.warning(Kind::Source, &mark, Path::new(), message);
None
}
}
}
},
}
}
}
fn trees<T: Config>(source: &Source, problems: &mut Problems) -> Vec<Raw> {
let suffix = source.env_suffix.as_deref();
let mut trees = Vec::new();
let mut mode: Option<Mode> = None;
for candidate in [Mode::Special, Mode::Global] {
let path = source.directory.join(candidate.file(T::NAME, None));
match slurp(&path) {
Slurp::Read(text) => {
if let Some(mode) = mode {
let mine = candidate.file(T::NAME, None);
let theirs = mode.file(T::NAME, None);
let message = format!("both `{theirs}` and `{mine}` exist; keep one of them");
problems.error(Kind::Source, &Mark::Model, Path::new(), message);
return Vec::new();
}
mode = Some(candidate);
trees.push((candidate, text, None));
}
Slurp::Failed(error) => failed(source, &candidate.file(T::NAME, None), error, problems),
Slurp::Missing => {}
}
}
if mode.is_none() {
mode = [Mode::Special, Mode::Global].into_iter().find(|candidate| {
matches!(
slurp(&source.directory.join(candidate.file(T::NAME, suffix))),
Slurp::Read(_)
)
});
if mode.is_none() && source.directory.exists() {
let special = Mode::Special.file(T::NAME, None);
let global = Mode::Global.file(T::NAME, None);
let message =
format!("no configuration file found: expected `{special}` or `{global}`");
problems.warning(Kind::Source, &Mark::Model, Path::new(), message);
}
}
let Some(mode) = mode else {
return Vec::new();
};
if suffix.is_some() {
let path = source.directory.join(mode.file(T::NAME, suffix));
match slurp(&path) {
Slurp::Read(text) => trees.push((mode, text, suffix)),
Slurp::Failed(error) => failed(source, &mode.file(T::NAME, suffix), error, problems),
Slurp::Missing => {}
}
}
trees
.into_iter()
.filter_map(|(mode, text, suffix)| {
let shown = source.shown(&mode.file(T::NAME, suffix));
let parsed = yaml::read(&text, &Rc::from(shown.as_str()), problems);
mode.tree(T::KEY, parsed, &shown, problems)
})
.collect()
}
fn failed(source: &Source, relative: &str, error: io::Error, problems: &mut Problems) {
let shown = source.shown(relative);
problems.error(
Kind::Source,
&Mark::Model,
Path::new(),
format!("cannot read `{shown}`: {error}"),
);
}
enum Slurp {
Missing,
Failed(io::Error),
Read(String),
}
fn slurp(path: &FsPath) -> Slurp {
match fs::read_to_string(path) {
Ok(text) => Slurp::Read(text),
Err(error) if error.kind() == io::ErrorKind::NotFound => Slurp::Missing,
Err(error) => Slurp::Failed(error),
}
}