1use std::collections::BTreeMap;
8use std::fmt;
9use std::path::{Component, Path, PathBuf};
10
11use serde::de::{self, Deserializer, SeqAccess, Visitor};
12
13#[cfg(test)]
14mod tests;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Root {
19 pub name: String,
21 pub path: PathBuf,
23 pub only: Option<Vec<String>>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
31pub enum RootError {
32 #[error("{list}: `{}` is listed twice", path.display())]
34 DuplicateEntry {
35 list: &'static str,
37 path: PathBuf,
39 },
40 #[error("{list}: `{}` is inside `{}`; nested entries aren't allowed", inner.display(), outer.display())]
42 Nested {
43 list: &'static str,
45 outer: PathBuf,
47 inner: PathBuf,
49 },
50 #[error("{list}: `{}` has no name; rename it in [{section}.roots]", path.display())]
52 Unnamed {
53 list: &'static str,
55 section: &'static str,
57 path: PathBuf,
59 },
60 #[error(
62 "{list}: `{}` and `{}` are both named `{name}`; rename one in [{section}.roots]",
63 first.display(),
64 second.display()
65 )]
66 DuplicateName {
67 list: &'static str,
69 section: &'static str,
71 name: String,
73 first: PathBuf,
75 second: PathBuf,
77 },
78 #[error(
80 "{list}: `{}` is named `{name}`, as the DAG root `{}`; rename one in \
81 [scripts.roots] or [dags.roots]",
82 script.display(),
83 dag.display()
84 )]
85 ScriptNamedAsDag {
86 list: &'static str,
88 name: String,
90 script: PathBuf,
92 dag: PathBuf,
94 },
95 #[error(
97 "[{section}.roots] `{name}` = `{}` is not an entry of {list}; renaming never adds directories",
98 path.display()
99 )]
100 RenameNotListed {
101 list: &'static str,
103 section: &'static str,
105 name: String,
107 path: PathBuf,
109 },
110}
111
112#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
115pub struct PathList(pub Vec<PathBuf>);
116
117impl schemars::JsonSchema for PathList {
118 fn schema_name() -> std::borrow::Cow<'static, str> {
119 "PathList".into()
120 }
121
122 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
123 schemars::json_schema!({
124 "anyOf": [
125 {"type": "array", "items": {"type": "string"}},
126 {"type": "string"}
127 ],
128 "description": "Directories: an array, or a colon-separated string as in `PATH`."
129 })
130 }
131}
132
133impl PathList {
134 #[must_use]
136 pub fn from_path_string(s: &str) -> Self {
137 Self(
138 s.split(':')
139 .filter(|p| !p.is_empty())
140 .map(PathBuf::from)
141 .collect(),
142 )
143 }
144}
145
146impl<'de> serde::Deserialize<'de> for PathList {
147 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
148 struct PathListVisitor;
149
150 impl<'de> Visitor<'de> for PathListVisitor {
151 type Value = PathList;
152
153 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 f.write_str("a list of paths, or a colon-separated string of paths")
155 }
156
157 fn visit_str<E: de::Error>(self, s: &str) -> Result<PathList, E> {
158 Ok(PathList::from_path_string(s))
159 }
160
161 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<PathList, A::Error> {
162 let mut paths = Vec::new();
163 while let Some(path) = seq.next_element::<String>()? {
164 paths.push(PathBuf::from(path));
165 }
166 Ok(PathList(paths))
167 }
168 }
169
170 d.deserialize_any(PathListVisitor)
171 }
172}
173
174#[must_use]
176pub fn normalize(path: &Path) -> PathBuf {
177 path.components()
178 .filter(|c| !matches!(c, Component::CurDir))
179 .collect()
180}
181
182pub fn resolve_roots(
192 list: &'static str,
193 section: &'static str,
194 entries: &PathList,
195 renames: &BTreeMap<String, PathBuf>,
196) -> Result<Vec<Root>, RootError> {
197 let paths: Vec<PathBuf> = entries.0.iter().map(|p| normalize(p)).collect();
198 for (i, a) in paths.iter().enumerate() {
199 for b in &paths[i + 1..] {
200 if a == b {
201 return Err(RootError::DuplicateEntry {
202 list,
203 path: a.clone(),
204 });
205 }
206 if b.starts_with(a) || a.starts_with(b) {
207 let (outer, inner) = if b.starts_with(a) { (a, b) } else { (b, a) };
208 return Err(RootError::Nested {
209 list,
210 outer: outer.clone(),
211 inner: inner.clone(),
212 });
213 }
214 }
215 }
216 let mut names_by_path: BTreeMap<PathBuf, &str> = BTreeMap::new();
217 for (name, path) in renames {
218 let path = normalize(path);
219 if !paths.contains(&path) {
220 return Err(RootError::RenameNotListed {
221 list,
222 section,
223 name: name.clone(),
224 path,
225 });
226 }
227 names_by_path.insert(path, name);
228 }
229 let mut roots: Vec<Root> = Vec::with_capacity(paths.len());
230 for path in paths {
231 let name = match names_by_path.get(&path) {
232 Some(name) => (*name).to_owned(),
233 None => match path.file_name() {
234 Some(name) => name.to_string_lossy().into_owned(),
235 None => {
236 return Err(RootError::Unnamed {
237 list,
238 section,
239 path,
240 });
241 }
242 },
243 };
244 if let Some(first) = roots.iter().find(|r| r.name == name) {
245 return Err(RootError::DuplicateName {
246 list,
247 section,
248 name,
249 first: first.path.clone(),
250 second: path,
251 });
252 }
253 let path = std::path::absolute(&path).unwrap_or(path);
257 roots.push(Root {
258 name,
259 path,
260 only: None,
261 });
262 }
263 Ok(roots)
264}
265
266pub fn check_apart(list: &'static str, dags: &[Root], scripts: &[Root]) -> Result<(), RootError> {
273 for script in scripts {
274 if let Some(dag) = dags.iter().find(|dag| dag.name == script.name) {
275 return Err(RootError::ScriptNamedAsDag {
276 list,
277 name: script.name.clone(),
278 script: script.path.clone(),
279 dag: dag.path.clone(),
280 });
281 }
282 }
283 Ok(())
284}