scrusted-yaml 0.2.0

Validates, loads and resolves scripted-yaml files: YAML with FEEL formulas in marked keys, reloaded live.
Documentation
//! Where files come from (SPEC 5.2): the disk, memory, the bundled templates, or the
//! application's own source.

use std::collections::BTreeMap;
use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};

/// A file's text and the name it goes by.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Source {
    /// The name: in problems, and the `from` of the paths it names in turn.
    pub name: String,
    /// The text.
    pub text: String,
}

/// A source of files.
pub trait Files: Send + Sync {
    /// The text of `path` as written in `from` (None for the first file), and the name it goes by.
    /// Ok(None): there is no such file. An error is reported on the line that names the path.
    fn read(&self, path: &str, from: Option<&str>) -> io::Result<Option<Source>>;

    /// A token that changes when the file changes (mtime, hash, row version).
    fn version(&self, name: &str) -> io::Result<Option<String>>;

    /// Every file this source holds, by name, for a live set that loads them all (SPEC 6.1).
    fn list(&self) -> io::Result<Vec<String>> {
        Ok(Vec::new())
    }

    /// Whether two names are one file.
    fn key(&self, name: &str) -> String {
        name.to_string()
    }

    /// The folder to watch for changes, for a source on disk (SPEC 6.4). None: poll.
    fn watch_root(&self) -> Option<PathBuf> {
        None
    }
}

impl<T: Files + ?Sized> Files for Arc<T> {
    fn read(&self, path: &str, from: Option<&str>) -> io::Result<Option<Source>> {
        (**self).read(path, from)
    }
    fn version(&self, name: &str) -> io::Result<Option<String>> {
        (**self).version(name)
    }
    fn list(&self) -> io::Result<Vec<String>> {
        (**self).list()
    }
    fn key(&self, name: &str) -> String {
        (**self).key(name)
    }
    fn watch_root(&self) -> Option<PathBuf> {
        (**self).watch_root()
    }
}

/// Joins `path` to the folder of `from` and removes `.` and `..`: `pipelines/./x.yml` → `pipelines/x.yml`.
pub fn join_relative(path: &str, from: Option<&str>) -> String {
    let base = match from {
        Some(f) if !path.starts_with('/') => match f.rfind('/') {
            Some(i) => format!("{}/{}", &f[..i], path),
            None => path.to_string(),
        },
        _ => path.to_string(),
    };
    let mut parts: Vec<&str> = Vec::new();
    let absolute = base.starts_with('/');
    for part in base.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                if parts.last().is_some_and(|p| *p != "..") {
                    parts.pop();
                } else if !absolute {
                    parts.push("..");
                }
            }
            other => parts.push(other),
        }
    }
    let joined = parts.join("/");
    if absolute { format!("/{joined}") } else { joined }
}

/// Files held in memory, by name. A path is read beside the file that names it.
#[derive(Debug, Default)]
pub struct MemoryFiles {
    files: RwLock<BTreeMap<String, (String, u64)>>,
}

impl MemoryFiles {
    /// An empty set.
    pub fn new() -> Self {
        MemoryFiles::default()
    }

    /// A set from pairs of name and text.
    pub fn from_pairs<K: Into<String>, V: Into<String>>(pairs: impl IntoIterator<Item = (K, V)>) -> Self {
        let files = MemoryFiles::new();
        for (k, v) in pairs {
            files.set(k, v);
        }
        files
    }

    /// Adds or changes a file.
    pub fn set(&self, name: impl Into<String>, text: impl Into<String>) -> &Self {
        let mut files = self.files.write().unwrap_or_else(|e| e.into_inner());
        let name = name.into();
        let version = files.get(&name).map(|(_, v)| v + 1).unwrap_or(1);
        files.insert(name, (text.into(), version));
        self
    }

    /// Removes a file.
    pub fn remove(&self, name: &str) {
        self.files.write().unwrap_or_else(|e| e.into_inner()).remove(name);
    }
}

impl Files for MemoryFiles {
    fn read(&self, path: &str, from: Option<&str>) -> io::Result<Option<Source>> {
        let files = self.files.read().unwrap_or_else(|e| e.into_inner());
        if from.is_some() {
            let joined = join_relative(path, from);
            if let Some((text, _)) = files.get(&joined) {
                return Ok(Some(Source { name: joined, text: text.clone() }));
            }
        }
        Ok(files.get(path).map(|(text, _)| Source { name: path.to_string(), text: text.clone() }))
    }

    fn version(&self, name: &str) -> io::Result<Option<String>> {
        Ok(self.files.read().unwrap_or_else(|e| e.into_inner()).get(name).map(|(_, v)| v.to_string()))
    }

    fn list(&self) -> io::Result<Vec<String>> {
        Ok(self
            .files
            .read()
            .unwrap_or_else(|e| e.into_inner())
            .keys()
            .filter(|k| k.ends_with(".yml") || k.ends_with(".yaml"))
            .cloned()
            .collect())
    }
}

/// Files under a root folder on disk. Names are relative to the root; a path may not leave it.
#[derive(Debug, Clone)]
pub struct DiskFiles {
    root: PathBuf,
}

impl DiskFiles {
    /// Files under `root`.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        DiskFiles { root: root.into() }
    }

    /// The root folder.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// The path on disk of a name.
    pub fn path_of(&self, name: &str) -> PathBuf {
        self.root.join(name)
    }

    fn name_of(&self, path: &str, from: Option<&str>) -> io::Result<String> {
        let joined = join_relative(path, from);
        if joined.starts_with('/')
            || joined.split('/').next() == Some("..")
            || Path::new(&joined).components().any(|c| matches!(c, Component::Prefix(_)))
        {
            return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("\"{path}\" is outside the folder of the files")));
        }
        Ok(joined)
    }
}

impl Files for DiskFiles {
    fn read(&self, path: &str, from: Option<&str>) -> io::Result<Option<Source>> {
        let name = self.name_of(path, from)?;
        match std::fs::read_to_string(self.root.join(&name)) {
            Ok(text) => Ok(Some(Source { name, text })),
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(io::Error::new(e.kind(), format!("cannot read \"{path}\": {e}"))),
        }
    }

    fn version(&self, name: &str) -> io::Result<Option<String>> {
        match std::fs::metadata(self.root.join(name)) {
            Ok(meta) => {
                let modified =
                    meta.modified().ok().and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos()).unwrap_or(0);
                Ok(Some(format!("{modified}-{}", meta.len())))
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e),
        }
    }

    fn list(&self) -> io::Result<Vec<String>> {
        let mut out = Vec::new();
        fn walk(dir: &Path, prefix: &str, out: &mut Vec<String>) -> io::Result<()> {
            let mut entries: Vec<_> = std::fs::read_dir(dir)?.filter_map(Result::ok).collect();
            entries.sort_by_key(|e| e.file_name());
            for entry in entries {
                let name = entry.file_name().to_string_lossy().to_string();
                if name.starts_with('.') {
                    continue;
                }
                let rel = if prefix.is_empty() { name.clone() } else { format!("{prefix}/{name}") };
                let kind = entry.file_type()?;
                if kind.is_dir() {
                    walk(&entry.path(), &rel, out)?;
                } else if name.ends_with(".yml") || name.ends_with(".yaml") {
                    out.push(rel);
                }
            }
            Ok(())
        }
        walk(&self.root, "", &mut out)?;
        Ok(out)
    }

    fn watch_root(&self) -> Option<PathBuf> {
        Some(self.root.clone())
    }
}

/// The bundled templates of scripted-yaml 0.3.0, byte for byte (SPEC 4.11).
pub struct Templates;

impl Templates {
    /// The prefix that names a template.
    pub const PREFIX: &'static str = "scripted-yaml/";

    /// Each template: name and text.
    pub const ALL: &'static [(&'static str, &'static str)] = &[
        ("forms", include_str!("../templates/forms.yml")),
        ("navigation-ui", include_str!("../templates/navigation-ui.yml")),
        ("state-machine", include_str!("../templates/state-machine.yml")),
    ];

    /// True when a path names a template.
    pub fn is_template(path: &str) -> bool {
        path.starts_with(Self::PREFIX)
    }

    /// The text of a template by its path.
    pub fn text(path: &str) -> Option<&'static str> {
        let name = path.strip_prefix(Self::PREFIX)?;
        Self::ALL.iter().find(|(n, _)| *n == name).map(|(_, t)| *t)
    }

    /// The comment on the first line of a template.
    pub fn about(name: &str) -> String {
        let text = Self::ALL.iter().find(|(n, _)| *n == name).map(|(_, t)| *t).unwrap_or("");
        let first = text.lines().next().unwrap_or("");
        first.strip_prefix('#').map(|s| s.trim().to_string()).unwrap_or_default()
    }

    /// Reads a template, or explains that there is none.
    pub fn read(path: &str) -> io::Result<Source> {
        match Self::text(path) {
            Some(text) => Ok(Source { name: path.to_string(), text: text.to_string() }),
            None => {
                let names: Vec<String> = Self::ALL.iter().map(|(n, _)| format!("{}{n}", Self::PREFIX)).collect();
                Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("cannot read \"{path}\": there is no such template (only {})", names.join(", ")),
                ))
            }
        }
    }
}

/// Templates first, then the application's files.
pub(crate) struct WithTemplates(pub Arc<dyn Files>);

impl Files for WithTemplates {
    fn read(&self, path: &str, from: Option<&str>) -> io::Result<Option<Source>> {
        if Templates::is_template(path) {
            return Templates::read(path).map(Some);
        }
        self.0.read(path, from)
    }
    fn version(&self, name: &str) -> io::Result<Option<String>> {
        if Templates::is_template(name) {
            return Ok(Some("bundled".into()));
        }
        self.0.version(name)
    }
    fn list(&self) -> io::Result<Vec<String>> {
        self.0.list()
    }
    fn key(&self, name: &str) -> String {
        self.0.key(name)
    }
    fn watch_root(&self) -> Option<PathBuf> {
        self.0.watch_root()
    }
}