use std::collections::BTreeMap;
use std::io;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Source {
pub name: String,
pub text: String,
}
pub trait Files: Send + Sync {
fn read(&self, path: &str, from: Option<&str>) -> io::Result<Option<Source>>;
fn version(&self, name: &str) -> io::Result<Option<String>>;
fn list(&self) -> io::Result<Vec<String>> {
Ok(Vec::new())
}
fn key(&self, name: &str) -> String {
name.to_string()
}
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()
}
}
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 }
}
#[derive(Debug, Default)]
pub struct MemoryFiles {
files: RwLock<BTreeMap<String, (String, u64)>>,
}
impl MemoryFiles {
pub fn new() -> Self {
MemoryFiles::default()
}
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
}
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
}
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())
}
}
#[derive(Debug, Clone)]
pub struct DiskFiles {
root: PathBuf,
}
impl DiskFiles {
pub fn new(root: impl Into<PathBuf>) -> Self {
DiskFiles { root: root.into() }
}
pub fn root(&self) -> &Path {
&self.root
}
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())
}
}
pub struct Templates;
impl Templates {
pub const PREFIX: &'static str = "scripted-yaml/";
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")),
];
pub fn is_template(path: &str) -> bool {
path.starts_with(Self::PREFIX)
}
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)
}
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()
}
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(", ")),
))
}
}
}
}
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()
}
}