Skip to main content

mars_schema/
tree.rs

1//! Host-independent package tree access.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5/// Read access to a package tree through normalized package-relative paths.
6///
7/// Paths use `/` separators, are never absolute, and contain no empty, `.` or
8/// `..` components. The empty path names the tree root for directory queries.
9///
10/// A path that does not exist is absent, not an error, and so is a path below a file: `read`
11/// and `is_file` answer `None` and `false` for `agents/x.md/anything`.
12pub trait TreeSource {
13    fn read(&self, path: &str) -> Option<Vec<u8>>;
14    fn is_file(&self, path: &str) -> bool;
15    fn is_dir(&self, path: &str) -> bool;
16
17    /// Return the direct child paths of `dir` in stable lexical order.
18    fn children(&self, dir: &str) -> Vec<String>;
19}
20
21/// An in-memory package tree for WASM callers and fixtures.
22#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct FileTree {
24    files: BTreeMap<String, Vec<u8>>,
25    children: BTreeMap<String, BTreeSet<String>>,
26}
27
28impl FileTree {
29    pub fn new() -> Self {
30        Self::default()
31    }
32
33    pub fn from_files(
34        files: impl IntoIterator<Item = (String, Vec<u8>)>,
35    ) -> Result<Self, TreePathError> {
36        let mut tree = Self::new();
37        for (path, bytes) in files {
38            tree.insert(path, bytes)?;
39        }
40        Ok(tree)
41    }
42
43    pub fn insert(
44        &mut self,
45        path: impl Into<String>,
46        bytes: impl Into<Vec<u8>>,
47    ) -> Result<(), TreePathError> {
48        let path = path.into();
49        validate_file_path(&path)?;
50        let components = path.split('/').collect::<Vec<_>>();
51        let has_file_ancestor =
52            (1..components.len()).any(|end| self.files.contains_key(&components[..end].join("/")));
53        let descendant_prefix = format!("{path}/");
54        let has_file_descendant = self
55            .files
56            .range(path.clone()..)
57            .next()
58            .is_some_and(|(file, _)| file.starts_with(&descendant_prefix));
59        if has_file_ancestor || has_file_descendant {
60            return Err(TreePathError {
61                path,
62                reason: "a path cannot be both a file and a directory",
63            });
64        }
65        index_children(&mut self.children, &path);
66        self.files.insert(path, bytes.into());
67        Ok(())
68    }
69
70    pub fn files(&self) -> &BTreeMap<String, Vec<u8>> {
71        &self.files
72    }
73}
74
75impl TreeSource for FileTree {
76    fn read(&self, path: &str) -> Option<Vec<u8>> {
77        self.files.get(path).cloned()
78    }
79
80    fn is_file(&self, path: &str) -> bool {
81        self.files.contains_key(path)
82    }
83
84    fn is_dir(&self, path: &str) -> bool {
85        path.is_empty() || self.children.contains_key(path)
86    }
87
88    fn children(&self, dir: &str) -> Vec<String> {
89        self.children
90            .get(dir)
91            .map(|children| children.iter().cloned().collect())
92            .unwrap_or_default()
93    }
94}
95
96/// A view of a tree below one directory: `prefix` becomes the root.
97pub struct SubTree<'a, T: TreeSource> {
98    inner: &'a T,
99    prefix: String,
100}
101
102impl<'a, T: TreeSource> SubTree<'a, T> {
103    /// `prefix` is a normalized directory path of `inner`.
104    pub fn new(inner: &'a T, prefix: impl Into<String>) -> Self {
105        Self {
106            inner,
107            prefix: prefix.into(),
108        }
109    }
110
111    fn full(&self, path: &str) -> String {
112        match (self.prefix.is_empty(), path.is_empty()) {
113            (true, _) => path.to_owned(),
114            (false, true) => self.prefix.clone(),
115            (false, false) => format!("{}/{path}", self.prefix),
116        }
117    }
118}
119
120impl<T: TreeSource> TreeSource for SubTree<'_, T> {
121    fn read(&self, path: &str) -> Option<Vec<u8>> {
122        self.inner.read(&self.full(path))
123    }
124
125    fn is_file(&self, path: &str) -> bool {
126        self.inner.is_file(&self.full(path))
127    }
128
129    fn is_dir(&self, path: &str) -> bool {
130        self.inner.is_dir(&self.full(path))
131    }
132
133    fn children(&self, dir: &str) -> Vec<String> {
134        let skip = if self.prefix.is_empty() {
135            0
136        } else {
137            self.prefix.len() + 1
138        };
139        self.inner
140            .children(&self.full(dir))
141            .into_iter()
142            .map(|child| child[skip..].to_owned())
143            .collect()
144    }
145}
146
147fn index_children(index: &mut BTreeMap<String, BTreeSet<String>>, path: &str) {
148    let components = path.split('/').collect::<Vec<_>>();
149    for child_index in 0..components.len() {
150        let parent = components[..child_index].join("/");
151        let child = components[..=child_index].join("/");
152        index.entry(parent).or_default().insert(child);
153    }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
157#[error("invalid package tree path `{path}`: {reason}")]
158pub struct TreePathError {
159    pub path: String,
160    pub reason: &'static str,
161}
162
163impl TreePathError {
164    /// A stable identifier for callers that map failures to their own codes.
165    pub fn code(&self) -> &'static str {
166        "tree.invalid-path"
167    }
168}
169
170fn validate_file_path(path: &str) -> Result<(), TreePathError> {
171    let invalid = |reason| TreePathError {
172        path: path.to_owned(),
173        reason,
174    };
175    if path.is_empty() {
176        return Err(invalid("a file path cannot be empty"));
177    }
178    if path.starts_with('/') {
179        return Err(invalid("paths must be package-relative"));
180    }
181    if path.contains('\\') {
182        return Err(invalid("paths must use `/` separators"));
183    }
184    if path
185        .split('/')
186        .any(|component| component.is_empty() || matches!(component, "." | ".."))
187    {
188        return Err(invalid("paths must be normalized"));
189    }
190    Ok(())
191}