use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Deserializer};
use crate::error::{Error, Result};
pub const CONFIG_DIR: &str = ".mmz";
const CONFIG_NAMES: [&str; 2] = ["config.yaml", "config.yml"];
const fn default_gitignore() -> bool {
true
}
fn default_cache_dir() -> String {
".mmz/cache".to_owned()
}
fn normalize_tags<'de, D>(deserializer: D) -> std::result::Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
let raw = Vec::<String>::deserialize(deserializer)?;
Ok(raw
.into_iter()
.map(|tag| tag.trim().to_owned())
.filter(|tag| !tag.is_empty())
.collect())
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MatchMode {
#[default]
Prefix,
Exact,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StrictCase {
NoMatch,
NoInputs,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(transparent)]
pub struct StrictPolicy {
cases: BTreeSet<StrictCase>,
}
impl StrictPolicy {
#[must_use]
pub fn all() -> Self {
Self {
cases: [StrictCase::NoMatch, StrictCase::NoInputs]
.into_iter()
.collect(),
}
}
#[must_use]
pub fn enforces(&self, case: StrictCase) -> bool {
self.cases.contains(&case)
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
#[serde(default)]
pub scopes: BTreeMap<String, Vec<String>>,
#[serde(default)]
pub commands: Vec<Command>,
#[serde(default = "default_gitignore")]
pub gitignore: bool,
#[serde(default = "default_cache_dir")]
pub cache_dir: String,
#[serde(default = "StrictPolicy::all")]
pub strict: StrictPolicy,
#[serde(default)]
pub on_hit: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Command {
pub name: String,
#[serde(default)]
pub inputs: Vec<String>,
#[serde(rename = "match", default)]
pub match_mode: MatchMode,
#[serde(default, deserialize_with = "normalize_tags")]
pub tags: Vec<String>,
#[serde(default)]
pub on_hit: Option<String>,
}
impl Manifest {
pub fn load(path: &Path) -> Result<Self> {
let text = fs::read_to_string(path)?;
let manifest: Self =
serde_yaml_ng::from_str(&text).map_err(|source| Error::ManifestParse {
path: path.to_path_buf(),
source: Box::new(source),
})?;
manifest.validate()?;
Ok(manifest)
}
pub fn validate(&self) -> Result<()> {
let mut seen: Vec<&str> = Vec::new();
for (index, command) in self.commands.iter().enumerate() {
if command.name.trim().is_empty() {
return Err(Error::EmptyCommandName(index + 1));
}
if seen.contains(&command.name.as_str()) {
return Err(Error::DuplicateCommand(command.name.clone()));
}
seen.push(command.name.as_str());
if let Some(mac) = crate::parametric::parse(&command.name)? {
if !self.scopes.contains_key(&mac.scope) {
return Err(Error::UnknownScope {
command: command.name.clone(),
scope: mac.scope,
});
}
}
for scope in &command.inputs {
if !self.scopes.contains_key(scope) {
return Err(Error::UnknownScope {
command: command.name.clone(),
scope: scope.clone(),
});
}
}
let mut seen_tags: Vec<&str> = Vec::new();
for tag in &command.tags {
if seen_tags.contains(&tag.as_str()) {
return Err(Error::DuplicateTag {
command: command.name.clone(),
tag: tag.clone(),
});
}
seen_tags.push(tag.as_str());
}
}
Ok(())
}
pub fn globs_for(&self, command: &Command) -> Result<Vec<String>> {
let mut out: Vec<String> = Vec::new();
for scope in &command.inputs {
let globs = self.scopes.get(scope).ok_or_else(|| Error::UnknownScope {
command: command.name.clone(),
scope: scope.clone(),
})?;
for glob in globs {
if !out.contains(glob) {
out.push(glob.clone());
}
}
}
Ok(out)
}
#[must_use]
pub fn discover(start: &Path) -> Option<PathBuf> {
let mut dir = Some(start);
while let Some(current) = dir {
for name in CONFIG_NAMES {
let candidate = current.join(CONFIG_DIR).join(name);
if candidate.is_file() {
return Some(candidate);
}
}
dir = current.parent();
}
None
}
pub fn locate(cwd: &Path) -> Result<Located> {
let path = Self::discover(cwd).ok_or_else(|| Error::NoManifest {
start: cwd.to_path_buf(),
})?;
let root = path
.parent()
.and_then(Path::parent)
.ok_or_else(|| Error::Internal("config path has no project root".to_owned()))?
.to_path_buf();
let manifest = Self::load(&path)?;
Ok(Located {
path,
root,
manifest,
})
}
}
pub struct Located {
pub path: PathBuf,
pub root: PathBuf,
pub manifest: Manifest,
}
#[cfg(test)]
#[path = "manifest_tests.rs"]
mod tests;