Skip to main content

trumly_fs/
pack.rs

1//! Packs: folders of ordinary node files (planes, types, link types, rules) that can be added to a model.
2//!
3//! A pack folder holds one `pack` node (the manifest) and the nodes it provides. Every provided node carries
4//! `fields.pack: <name>@<version>`, so once copied into a model it is still known to come from the pack.
5//! Adding is a copy with checks: required packs must be there, and a node that already exists is only
6//! replaced if it came from the same pack (an upgrade). Anything else is a conflict, and nothing is written.
7//!
8//! The manifest kept in a model also records `installed`: a hash of every node as the pack provided it. That is
9//! what lets us tell a node you changed from one you did not, so an upgrade replaces what is untouched, keeps what
10//! you edited, and a removal does not throw your work away.
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::fs;
14use std::path::{Path, PathBuf};
15
16use serde_json::{json, Value};
17use trumly_core::format::node_to_markdown;
18use trumly_core::model::Node;
19use trumly_core::parse::parse_node;
20use trumly_core::report::node_to_json;
21
22#[derive(Debug, Clone)]
23pub struct Pack {
24    pub name: String,
25    pub version: String,
26    pub description: String,
27    /// the short prefix of every node id this pack provides: `<namespace>--<local id>`
28    pub namespace: String,
29    /// packs that must already be in the model (or come along in the same add)
30    pub requires: Vec<String>,
31    /// child packs this one bundles: adding it brings them in too (a collection has only a manifest)
32    pub includes: Vec<String>,
33    /// (node id, file text), the manifest included
34    pub files: Vec<(String, String)>,
35}
36
37impl Pack {
38    pub fn tag(&self) -> String {
39        format!("{}@{}", self.name, self.version)
40    }
41
42    /// A short line per node the pack provides (the manifest left out), for looking inside a pack before adding it.
43    pub fn contents(&self) -> Vec<serde_json::Value> {
44        let text = |n: &Node, k: &str| n.fields.get(k).and_then(|v| v.as_str()).map(str::to_string);
45        let mut out: Vec<serde_json::Value> = self
46            .files
47            .iter()
48            .filter_map(|(_, t)| parse_node(t).ok())
49            .filter(|n| n.kind.as_deref() != Some("pack"))
50            .map(|n| {
51                serde_json::json!({
52                    "id": n.id, "type": n.kind, "title": n.title, "name": text(&n, "name"), "description": text(&n, "description"),
53                    "statement": text(&n, "statement"), "plane": n.plane,
54                    "order": n.fields.get("order").and_then(|v| v.as_i64()),
55                    "from": n.fields.get("from"), "to": n.fields.get("to"), "inverse": text(&n, "inverse"),
56                })
57            })
58            .collect();
59        out.sort_by(|a, b| a["id"].as_str().cmp(&b["id"].as_str()));
60        out
61    }
62}
63
64/// Something wrong, or worth a look, in a pack. `error` means it should not be shared as it is.
65#[derive(Debug, Clone, PartialEq)]
66pub struct Problem {
67    pub pack: String,
68    pub severity: &'static str,
69    pub message: String,
70}
71
72/// What a pack may carry: its own definitions, never ordinary nodes.
73const DEFINITION_KINDS: [&str; 4] = ["type", "link-type", "rule", "plane"];
74
75fn defined(pack: &Pack, kind: &str) -> Vec<String> {
76    pack.files.iter().filter_map(|(_, t)| parse_node(t).ok()).filter(|n| n.kind.as_deref() == Some(kind)).filter_map(|n| n.fields.get("name").and_then(Value::as_str).map(str::to_string)).collect()
77}
78
79/// Every pack this one brings with it or relies on, directly or not (its own name left out).
80fn reach(all: &[Pack], name: &str) -> BTreeSet<String> {
81    let mut seen = BTreeSet::new();
82    let mut todo = vec![name.to_string()];
83    while let Some(n) = todo.pop() {
84        if let Some(p) = all.iter().find(|p| p.name == n) {
85            for d in p.requires.iter().map(|r| split_req(r).0.to_string()).chain(p.includes.iter().cloned()) {
86                if seen.insert(d.clone()) {
87                    todo.push(d);
88                }
89            }
90        }
91    }
92    seen
93}
94
95/// Check packs against each other and against what a pack is for:
96/// - error: an ordinary node (not a type, link type, rule or plane) inside a pack;
97/// - warning: a type or link type another pack in the library also defines, when neither brings the other (two meanings for one name);
98/// - warning: a type named in a from/to list, a rule's filter or a check that neither the pack nor what it relies on defines.
99pub fn lint(all: &[Pack]) -> Vec<Problem> {
100    let mut out = Vec::new();
101    for p in all {
102        let mut push = |severity: &'static str, message: String| out.push(Problem { pack: p.name.clone(), severity, message });
103        let nodes: Vec<Node> = p.files.iter().filter_map(|(_, t)| parse_node(t).ok()).collect();
104        for n in nodes.iter().filter(|n| n.kind.as_deref() != Some("pack")) {
105            let k = n.kind.as_deref().unwrap_or("");
106            if !DEFINITION_KINDS.contains(&k) {
107                push("error", format!("“{}” is an ordinary node (type {}). A pack carries definitions only: types, link types, rules and planes.", n.id, if k.is_empty() { "none" } else { k }));
108            }
109        }
110        let mine = reach(all, &p.name);
111        for kind in ["type", "link-type"] {
112            let label = if kind == "type" { "type" } else { "link type" };
113            for name in defined(p, kind) {
114                for q in all.iter().filter(|q| q.name != p.name && defined(q, kind).contains(&name)) {
115                    if mine.contains(&q.name) || reach(all, &q.name).contains(&p.name) {
116                        continue; // related packs share on purpose
117                    }
118                    push("warning", format!("The {label} “{name}” is also defined by {}, which this pack does not bring. Two meanings for one name in a model; prefix yours (for example {}-{name}) or share a base pack.", q.name, p.namespace));
119                }
120            }
121        }
122        let mut known: BTreeSet<String> = defined(p, "type").into_iter().collect();
123        for q in all.iter().filter(|q| mine.contains(&q.name)) {
124            known.extend(defined(q, "type"));
125        }
126        let mut seen = BTreeSet::new();
127        let mut missing = |what: &str, t: &str| {
128            if !t.is_empty() && !known.contains(t) && seen.insert(format!("{what}/{t}")) {
129                push("warning", format!("{what} names the type “{t}”, which neither this pack nor the packs it relies on define."));
130            }
131        };
132        for n in &nodes {
133            let name = n.fields.get("name").and_then(Value::as_str).unwrap_or(&n.id).to_string();
134            match n.kind.as_deref() {
135                Some("link-type") => {
136                    for key in ["from", "to"] {
137                        for t in n.fields.get(key).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
138                            missing(&format!("The link type “{name}”"), t);
139                        }
140                    }
141                }
142                Some("rule") => {
143                    let what = format!("The rule “{}”", n.fields.get("statement").and_then(Value::as_str).unwrap_or(&n.title));
144                    if let Some(t) = n.fields.get("applies_to").and_then(|a| a.get("type")).and_then(Value::as_str) {
145                        missing(&what, t);
146                    }
147                    fn types_in(v: &Value, out: &mut Vec<String>) {
148                        match v {
149                            Value::Array(a) => a.iter().for_each(|x| types_in(x, out)),
150                            Value::Object(o) => o.iter().for_each(|(k, x)| match (k.as_str(), x.as_str()) {
151                                ("node_type" | "to_type" | "ancestor_type", Some(t)) => out.push(t.to_string()),
152                                _ => types_in(x, out),
153                            }),
154                            _ => {}
155                        }
156                    }
157                    let mut ts = Vec::new();
158                    if let Some(c) = n.fields.get("check") {
159                        types_in(c, &mut ts);
160                    }
161                    for t in ts {
162                        missing(&what, &t);
163                    }
164                }
165                _ => {}
166            }
167        }
168    }
169    out
170}
171
172/// What to do when a pack defines a type or link type whose name the model already defines.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
174pub enum Clash {
175    /// stop and write nothing (the default)
176    #[default]
177    Refuse,
178    /// the definition already there stays; the pack leaves its own out
179    Skip,
180    /// the pack's definition takes over; the one already there is deleted
181    Replace,
182}
183
184#[derive(Debug, Default)]
185pub struct Added {
186    /// pack definitions left out because the model already defined the name (`Clash::Skip`)
187    pub skipped: Vec<String>,
188    /// definitions already in the model that the pack replaced (`Clash::Replace`)
189    pub replaced: Vec<String>,
190    pub added: Vec<String>,
191    pub updated: Vec<String>,
192    /// ids from an earlier version of this pack that the new version no longer has and you had changed (left in place)
193    pub no_longer_in_pack: Vec<String>,
194    /// ids you had changed that the upgrade left alone
195    pub kept: Vec<String>,
196    /// ids an earlier version had that the new one dropped, and you had not touched (deleted)
197    pub removed: Vec<String>,
198}
199
200// ---------- hashing: has this node been changed since the pack put it there? ----------
201
202fn canonical(v: &Value, out: &mut String) {
203    match v {
204        Value::Object(m) => {
205            let mut keys: Vec<&String> = m.keys().collect();
206            keys.sort();
207            out.push('{');
208            for k in keys {
209                out.push_str(&Value::String(k.clone()).to_string());
210                out.push(':');
211                canonical(&m[k], out);
212                out.push(',');
213            }
214            out.push('}');
215        }
216        Value::Array(a) => {
217            out.push('[');
218            for x in a {
219                canonical(x, out);
220                out.push(',');
221            }
222            out.push(']');
223        }
224        other => out.push_str(&other.to_string()),
225    }
226}
227
228/// FNV-1a, 64 bit, as 16 hex digits. Not secret, just stable across versions and platforms.
229fn fnv(s: &str) -> String {
230    let mut h: u64 = 0xcbf29ce484222325;
231    for b in s.bytes() {
232        h ^= u64::from(b);
233        h = h.wrapping_mul(0x100000001b3);
234    }
235    format!("{h:016x}")
236}
237
238/// A hash of what a node says, not how its file is laid out: reformatting a file does not change it.
239pub fn node_hash(n: &Node) -> String {
240    // the `pack` tag records where the node came from and changes with every version, so it is not content
241    let mut bare = n.clone();
242    bare.fields.remove("pack");
243    let mut s = String::new();
244    canonical(&node_to_json(&bare), &mut s);
245    fnv(&s)
246}
247
248// ---------- versions: `requires` may say `data-model@^0.2` ----------
249
250fn parse_ver(v: &str) -> Option<(u64, u64, u64)> {
251    let mut it = v.trim().split('.');
252    let n = |x: Option<&str>| x.and_then(|x| x.parse::<u64>().ok());
253    let (a, b, c) = (n(it.next())?, n(it.next())?, n(it.next())?);
254    if it.next().is_some() { None } else { Some((a, b, c)) }
255}
256
257/// Does `version` satisfy `range`? A range is one or more space-separated comparators, all of which must hold:
258/// `^1.2.3` (compatible: below the next major, or next minor while major is 0), `~1.2.3` (below the next minor),
259/// `>=`, `>`, `<=`, `<`, `=` or a bare `1.2.3` (exact). Empty or `*` accepts anything, even a version that is not x.y.z.
260pub fn satisfies(version: &str, range: &str) -> bool {
261    let range = range.trim();
262    if range.is_empty() || range == "*" {
263        return true;
264    }
265    let Some(v) = parse_ver(version) else { return false };
266    range.split_whitespace().all(|c| {
267        let (op, rest) = ["^", "~", ">=", "<=", ">", "<", "="].iter().find_map(|o| c.strip_prefix(o).map(|r| (*o, r))).unwrap_or(("=", c));
268        let Some(r) = parse_ver(rest) else { return false };
269        match op {
270            "^" => v >= r && if r.0 > 0 { v.0 == r.0 } else if r.1 > 0 { v.0 == 0 && v.1 == r.1 } else { v.0 == 0 && v.1 == 0 && v.2 == r.2 },
271            "~" => v >= r && v.0 == r.0 && v.1 == r.1,
272            ">=" => v >= r,
273            ">" => v > r,
274            "<=" => v <= r,
275            "<" => v < r,
276            _ => v == r,
277        }
278    })
279}
280
281/// `data-model@^0.2` -> ("data-model", "^0.2")
282fn split_req(r: &str) -> (&str, &str) {
283    r.split_once('@').unwrap_or((r, ""))
284}
285
286fn md_files(dir: &Path) -> Result<Vec<PathBuf>, String> {
287    let mut out: Vec<PathBuf> = fs::read_dir(dir)
288        .map_err(|e| format!("cannot read {}: {e}", dir.display()))?
289        .filter_map(|e| e.ok().map(|e| e.path()))
290        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "md"))
291        .collect();
292    out.sort();
293    Ok(out)
294}
295
296/// Lower-case letters and digits in words joined by single dashes: it sits before the `--` in every id.
297pub fn valid_namespace(ns: &str) -> bool {
298    !ns.is_empty() && ns.len() <= 24 && ns.split('-').all(|w| !w.is_empty() && w.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()))
299}
300
301/// Read one pack folder and check it hangs together.
302pub fn read_pack(dir: &Path) -> Result<Pack, String> {
303    let mut items = Vec::new();
304    for path in md_files(dir)? {
305        let text = fs::read_to_string(&path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
306        items.push((path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_string(), text));
307    }
308    pack_from_texts(&dir.display().to_string(), items)
309}
310
311/// Build a pack from (file stem, file text) pairs; `label` names it in errors. Folders and the copy in the binary both come here.
312pub fn pack_from_texts(label: &str, items: Vec<(String, String)>) -> Result<Pack, String> {
313    let dir = Path::new(label);
314    let mut manifest = None;
315    let mut files = Vec::new();
316    for (stem, text) in items {
317        let node = parse_node(&text).map_err(|e| format!("{label}/{stem}.md: {}", e.as_str()))?;
318        if stem != node.id {
319            return Err(format!("{label}/{stem}.md: the file name must be the node id"));
320        }
321        if node.kind.as_deref() == Some("pack") {
322            if manifest.is_some() {
323                return Err(format!("{label}: more than one pack node"));
324            }
325            manifest = Some(node.clone());
326        }
327        files.push((node, text));
328    }
329    let m = manifest.ok_or(format!("{}: no node of type pack", dir.display()))?;
330    let text = |k: &str| m.fields.get(k).and_then(|v| v.as_str()).map(str::to_string);
331    let name = text("name").ok_or(format!("{}: the pack node needs fields.name", dir.display()))?;
332    let version = text("version").ok_or(format!("{}: the pack node needs fields.version (a string)", dir.display()))?;
333    let names = |k: &str| -> Vec<String> { m.fields.get(k).and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default() };
334    let (requires, includes) = (names("requires"), names("includes"));
335    let namespace = text("namespace").unwrap_or_else(|| name.clone());
336    if !valid_namespace(&namespace) {
337        return Err(format!("{}: namespace '{namespace}' must be lower-case letters, digits and single dashes", dir.display()));
338    }
339    let tag = format!("{name}@{version}");
340    for (n, _) in &files {
341        if !n.id.starts_with(&format!("{namespace}--")) {
342            return Err(format!("{}: node '{}' must have an id starting '{namespace}--' (the pack's namespace)", dir.display(), n.id));
343        }
344    }
345    for (n, _) in &files {
346        if n.kind.as_deref() != Some("pack") && n.fields.get("pack").and_then(|v| v.as_str()) != Some(tag.as_str()) {
347            return Err(format!("{}: node '{}' must have fields.pack: {tag}", dir.display(), n.id));
348        }
349    }
350    Ok(Pack { description: text("description").unwrap_or_default(), name, version, namespace, requires, includes, files: files.into_iter().map(|(n, t)| (n.id, t)).collect() })
351}
352
353/// Every pack folder directly inside `dir`, by name.
354pub fn list_packs(dir: &Path) -> Result<Vec<Pack>, String> {
355    let mut out = Vec::new();
356    let mut subs: Vec<PathBuf> = fs::read_dir(dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))?.filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.is_dir()).collect();
357    subs.sort();
358    for s in subs {
359        out.push(read_pack(&s)?);
360    }
361    Ok(out)
362}
363
364/// (path, id, kind, fields.pack) of every node file in a model folder.
365fn model_nodes(model: &Path) -> Result<Vec<(String, String, Option<String>, Option<String>)>, String> {
366    let files = crate::read_model(&model.to_string_lossy())?;
367    Ok(files
368        .into_iter()
369        .filter_map(|(path, text)| {
370            let n = parse_node(&text).ok()?;
371            let pack = n.fields.get("pack").and_then(|v| v.as_str()).map(str::to_string);
372            Some((path, n.id, n.kind, pack))
373        })
374        .collect())
375}
376
377/// The packs a model already has, as (name, version), from its `pack` nodes.
378pub fn installed(model: &Path) -> Result<Vec<(String, String)>, String> {
379    let files = crate::read_model(&model.to_string_lossy())?;
380    Ok(files
381        .into_iter()
382        .filter_map(|(_, text)| {
383            let n = parse_node(&text).ok().filter(|n| n.kind.as_deref() == Some("pack"))?;
384            let s = |k: &str| n.fields.get(k).and_then(|v| v.as_str()).map(str::to_string);
385            Some((s("name")?, s("version").unwrap_or_default()))
386        })
387        .collect())
388}
389
390/// The packs to add for `name`, dependencies first: its `requires`, then the pack itself, then its `includes`.
391/// `only` limits which of the root's children come along (a collection lets you pick); `None` takes them all.
392pub fn plan<'a>(all: &'a [Pack], name: &str, only: Option<&[String]>) -> Result<Vec<&'a Pack>, String> {
393    fn visit<'a>(all: &'a [Pack], name: &str, only: Option<&[String]>, out: &mut Vec<&'a Pack>, stack: &mut Vec<String>) -> Result<(), String> {
394        if out.iter().any(|p| p.name == name) {
395            return Ok(());
396        }
397        if stack.iter().any(|s| s == name) {
398            return Err(format!("packs depend on each other in a loop: {} -> {name}", stack.join(" -> ")));
399        }
400        let p = all.iter().find(|p| p.name == name).ok_or_else(|| format!("no pack called {name}"))?;
401        stack.push(name.to_string());
402        for r in &p.requires {
403            let (rn, range) = split_req(r);
404            visit(all, rn, None, out, stack)?;
405            let got = all.iter().find(|q| q.name == rn).map(|q| q.version.as_str()).unwrap_or("");
406            if !satisfies(got, range) {
407                return Err(format!("{} needs {rn}@{range}, but the packs folder has {rn} {got}", p.name));
408            }
409        }
410        out.push(p);
411        for c in &p.includes {
412            if only.is_none_or(|o| o.iter().any(|x| x == c)) {
413                visit(all, c, None, out, stack)?;
414            }
415        }
416        stack.pop();
417        Ok(())
418    }
419    if let Some(o) = only {
420        let root = all.iter().find(|p| p.name == name).ok_or_else(|| format!("no pack called {name}"))?;
421        if let Some(bad) = o.iter().find(|x| !root.includes.contains(x)) {
422            return Err(format!("{name} does not include {bad}"));
423        }
424    }
425    let mut out = Vec::new();
426    visit(all, name, only, &mut out, &mut Vec::new())?;
427    Ok(out)
428}
429
430/// (kind, name, fields.pack) of every type and link-type definition in the model.
431fn definition_names(model: &Path) -> Result<Vec<(String, String, Option<String>, String, String)>, String> {
432    let files = crate::read_model(&model.to_string_lossy())?;
433    Ok(files
434        .into_iter()
435        .filter_map(|(path, text)| {
436            let n = parse_node(&text).ok()?;
437            let kind = n.kind.clone().filter(|k| k == "type" || k == "link-type")?;
438            let name = n.fields.get("name")?.as_str()?.to_string();
439            Some((kind, name, n.fields.get("pack").and_then(|v| v.as_str()).map(str::to_string), n.id.clone(), path))
440        })
441        .collect())
442}
443
444/// (pack name, namespace) of every pack the model has.
445fn installed_namespaces(model: &Path) -> Result<Vec<(String, String)>, String> {
446    let files = crate::read_model(&model.to_string_lossy())?;
447    Ok(files
448        .into_iter()
449        .filter_map(|(_, text)| {
450            let n = parse_node(&text).ok().filter(|n| n.kind.as_deref() == Some("pack"))?;
451            let name = n.fields.get("name")?.as_str()?.to_string();
452            let ns = n.fields.get("namespace").and_then(|v| v.as_str()).map_or_else(|| name.clone(), str::to_string);
453            Some((name, ns))
454        })
455        .collect())
456}
457
458/// Add `name` and everything it needs or includes to a model (see `plan`). Nothing is written unless every pack in
459/// the plan can go in: requirements met (at a version that satisfies the range), no namespace shared with a different
460/// pack, and no clash with something the pack does not own (unless `force`). Nodes you changed since an earlier
461/// version of the pack went in are kept, not overwritten (unless `force`). Returns what happened to each pack, in the
462/// order added.
463pub fn add_tree(all: &[Pack], name: &str, only: Option<&[String]>, model: &Path, force: bool) -> Result<Vec<(String, Added)>, String> {
464    add_tree_with(all, name, only, model, force, Clash::Refuse)
465}
466
467/// `add_tree`, with a choice for what to do when a type or link type name is already defined (see `Clash`).
468pub fn add_tree_with(all: &[Pack], name: &str, only: Option<&[String]>, model: &Path, force: bool, clash: Clash) -> Result<Vec<(String, Added)>, String> {
469    let chain = plan(all, name, only)?;
470    let mut have: Vec<(String, String)> = installed(model)?;
471    let spaces = installed_namespaces(model)?;
472    let nodes = model_nodes(model)?;
473    let defs = definition_names(model)?;
474    let mut conflicts = Vec::new();
475    let mut name_clashes = 0usize;
476    let mut plan_skip: BTreeMap<String, Vec<String>> = BTreeMap::new();
477    let mut plan_drop: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
478    for pack in &chain {
479        let missing: Vec<&String> = pack.requires.iter().filter(|r| { let (rn, range) = split_req(r); !have.iter().any(|(n, v)| n == rn && satisfies(v, range)) }).collect();
480        if !missing.is_empty() {
481            return Err(format!("{} needs {} first", pack.name, missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
482        }
483        have.retain(|(n, _)| *n != pack.name);
484        have.push((pack.name.clone(), pack.version.clone()));
485        if let Some((other, _)) = spaces.iter().find(|(n, ns)| *ns == pack.namespace && *n != pack.name) {
486            return Err(format!("{} cannot be added: its namespace '{}' is already used by {other}", pack.name, pack.namespace));
487        }
488        let same = |p: &Option<String>| p.as_deref().is_some_and(|p| p.split('@').next() == Some(pack.name.as_str()));
489        for (id, _) in &pack.files {
490            if let Some((path, _, kind, from)) = nodes.iter().find(|(_, nid, _, _)| nid == id) {
491                // the manifest has no provenance of its own; the same pack's manifest is simply replaced
492                let own_manifest = *id == format!("{}--pack", pack.namespace) && kind.as_deref() == Some("pack");
493                if !same(from) && !own_manifest {
494                    conflicts.push(format!("{id} ({path}){}", from.as_deref().map(|f| format!(" is from {f}")).unwrap_or_else(|| " is already in the model".into())));
495                }
496            }
497        }
498        // a type or link type with the same name from anyone else would make the name ambiguous
499        for (_, text) in &pack.files {
500            let Ok(n) = parse_node(text) else { continue };
501            let (Some(kind), Some(dn)) = (n.kind.clone().filter(|k| k == "type" || k == "link-type"), n.fields.get("name").and_then(|v| v.as_str())) else { continue };
502            if let Some((_, _, from, eid, epath)) = defs.iter().find(|(k, nm, from, _, _)| *k == kind && nm == dn && !same(from)) {
503                match clash {
504                    Clash::Skip => plan_skip.entry(pack.name.clone()).or_default().push(n.id.clone()),
505                    Clash::Replace => plan_drop.entry(pack.name.clone()).or_default().push((eid.clone(), epath.clone())),
506                    Clash::Refuse => {
507                        name_clashes += 1;
508                        conflicts.push(format!("the {kind} '{dn}'{}", from.as_deref().map(|f| format!(" is already defined by {f}")).unwrap_or_else(|| " is already defined in the model".into())));
509                    }
510                }
511            }
512        }
513    }
514    if !conflicts.is_empty() && !force {
515        if name_clashes == conflicts.len() {
516            return Err(format!("cannot add {name}: name clash with existing definitions (use the ones already there, or replace them):\n  {}", conflicts.join("\n  ")));
517        }
518        return Err(format!("cannot add {name}: these already exist and are not from the pack (use --force to replace them):\n  {}", conflicts.join("\n  ")));
519    }
520    let mut out = Vec::new();
521    for pack in chain {
522        let skip = plan_skip.remove(&pack.name).unwrap_or_default();
523        let drop = plan_drop.remove(&pack.name).unwrap_or_default();
524        out.push((pack.name.clone(), write_pack(pack, model, force, &skip, &drop)?));
525    }
526    Ok(out)
527}
528
529/// The hashes a pack's manifest in the model recorded when it was installed: node id -> hash.
530fn recorded(manifest: &Node) -> BTreeMap<String, String> {
531    manifest
532        .fields
533        .get("installed")
534        .and_then(Value::as_object)
535        .map(|m| m.iter().filter_map(|(k, v)| v.as_str().map(|v| (k.clone(), v.to_string()))).collect())
536        .unwrap_or_default()
537}
538
539fn write_pack(pack: &Pack, model: &Path, force: bool, skip: &[String], drop: &[(String, String)]) -> Result<Added, String> {
540    let current: Vec<(String, Node)> = crate::read_model(&model.to_string_lossy())?.into_iter().filter_map(|(p, t)| parse_node(&t).ok().map(|n| (p, n))).collect();
541    let from_this = |n: &Node| n.fields.get("pack").and_then(Value::as_str).is_some_and(|p| p.split('@').next() == Some(pack.name.as_str()));
542    let manifest_id = format!("{}--pack", pack.namespace);
543    let old = current.iter().find(|(_, n)| n.kind.as_deref() == Some("pack") && n.fields.get("name").and_then(Value::as_str) == Some(pack.name.as_str())).map(|(_, n)| recorded(n)).unwrap_or_default();
544    let put = |rel: &str, text: &str| fs::write(model.join(rel), text).map_err(|e| format!("cannot write {}: {e}", model.join(rel).display()));
545    let mut report = Added::default();
546    for (id, path) in drop {
547        fs::remove_file(model.join(path)).map_err(|e| format!("cannot remove {path}: {e}"))?;
548        report.replaced.push(id.clone());
549    }
550    let mut installed_hashes = serde_json::Map::new();
551    for (id, text) in &pack.files {
552        if *id == manifest_id {
553            continue;
554        }
555        if skip.contains(id) {
556            report.skipped.push(id.clone());
557            continue;
558        }
559        let incoming = parse_node(text).map_err(|e| format!("{id}: {}", e.as_str()))?;
560        let want = node_hash(&incoming);
561        installed_hashes.insert(id.clone(), json!(want));
562        let Some((path, node)) = current.iter().find(|(_, n)| n.id == *id) else {
563            put(&format!("{id}.md"), text)?;
564            report.added.push(id.clone());
565            continue;
566        };
567        if !from_this(node) {
568            put(path, text)?; // only reachable with `force`: the clash was already reported
569            report.updated.push(id.clone());
570            continue;
571        }
572        let have = node_hash(node);
573        let tag_current = node.fields.get("pack") == incoming.fields.get("pack");
574        match old.get(id) {
575            // you changed it since it went in: your version stays, and we say so when the pack changed it too
576            Some(base) if have != *base && !force => {
577                if want != *base {
578                    report.kept.push(id.clone());
579                }
580            }
581            _ if have == want && tag_current => {}
582            _ => {
583                put(path, text)?;
584                report.updated.push(id.clone());
585            }
586        }
587    }
588    // nodes an earlier version had and this one dropped
589    for (path, n) in &current {
590        if from_this(n) && n.kind.as_deref() != Some("pack") && !pack.files.iter().any(|(id, _)| *id == n.id) {
591            if old.get(&n.id).is_some_and(|b| *b == node_hash(n)) {
592                fs::remove_file(model.join(path)).map_err(|e| format!("cannot remove {path}: {e}"))?;
593                report.removed.push(n.id.clone());
594            } else {
595                report.no_longer_in_pack.push(n.id.clone());
596            }
597        }
598    }
599    // the manifest goes in last, carrying the hashes of what the pack provided
600    let (_, mtext) = pack.files.iter().find(|(id, _)| *id == manifest_id).ok_or_else(|| format!("{} has no manifest", pack.name))?;
601    let mut m = parse_node(mtext).map_err(|e| e.as_str().to_string())?;
602    m.fields.insert("installed".to_string(), Value::Object(installed_hashes));
603    let existing = current.iter().find(|(_, n)| n.id == manifest_id).map(|(p, _)| p.clone());
604    put(existing.as_deref().unwrap_or(&format!("{manifest_id}.md")), &node_to_markdown(&m))?;
605    if existing.is_some() { report.updated.push(manifest_id) } else { report.added.push(manifest_id) }
606    Ok(report)
607}
608
609/// Copy a single pack into a model whose requirements are already in place. See `add_tree` for the checks.
610pub fn add(pack: &Pack, model: &Path, force: bool) -> Result<Added, String> {
611    let have = installed(model)?;
612    let missing: Vec<&String> = pack.requires.iter().filter(|r| { let (rn, range) = split_req(r); !have.iter().any(|(n, v)| n == rn && satisfies(v, range)) }).collect();
613    if !missing.is_empty() {
614        return Err(format!("{} needs {} first", pack.name, missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")));
615    }
616    let alone = Pack { requires: vec![], includes: vec![], ..pack.clone() };
617    add_tree(std::slice::from_ref(&alone), &alone.name, None, model, force).map(|mut v| v.remove(0).1)
618}
619
620/// What has become of an installed pack's nodes.
621#[derive(Debug, Default, Clone, PartialEq, Eq)]
622pub struct Status {
623    pub name: String,
624    pub version: String,
625    /// how many nodes are exactly as the pack provided them
626    pub clean: usize,
627    /// nodes you changed since the pack put them there
628    pub changed: Vec<String>,
629    /// nodes the pack provided that are no longer in the model
630    pub missing: Vec<String>,
631}
632
633/// For every pack in the model: which of its nodes you have changed or deleted. Needs no copy of the pack, because
634/// the manifest remembers what it installed. A pack installed before hashes were recorded reports everything clean.
635pub fn status(model: &Path) -> Result<Vec<Status>, String> {
636    let current: Vec<Node> = crate::read_model(&model.to_string_lossy())?.into_iter().filter_map(|(_, t)| parse_node(&t).ok()).collect();
637    let mut out = Vec::new();
638    for m in current.iter().filter(|n| n.kind.as_deref() == Some("pack")) {
639        let (Some(name), version) = (m.fields.get("name").and_then(Value::as_str), m.fields.get("version").and_then(Value::as_str).unwrap_or("")) else { continue };
640        let mut st = Status { name: name.to_string(), version: version.to_string(), ..Status::default() };
641        for (id, hash) in recorded(m) {
642            match current.iter().find(|n| n.id == id) {
643                None => st.missing.push(id),
644                Some(n) if node_hash(n) == hash => st.clean += 1,
645                Some(_) => st.changed.push(id),
646            }
647        }
648        out.push(st);
649    }
650    Ok(out)
651}
652
653/// What `remove` did.
654#[derive(Debug, Default)]
655pub struct Removed {
656    pub removed: Vec<String>,
657}
658
659/// Take a pack out of a model: its manifest and every node it provided. Refused (nothing is deleted) while another
660/// pack in the model requires it, while nodes of yours link to, sit under or are placed on its nodes, or while you
661/// have changed some of its nodes; `force` deletes anyway.
662pub fn remove(name: &str, model: &Path, force: bool) -> Result<Removed, String> {
663    let files = crate::read_model(&model.to_string_lossy())?;
664    let current: Vec<(String, Node)> = files.into_iter().filter_map(|(p, t)| parse_node(&t).ok().map(|n| (p, n))).collect();
665    let manifest = current.iter().find(|(_, n)| n.kind.as_deref() == Some("pack") && n.fields.get("name").and_then(Value::as_str) == Some(name)).ok_or_else(|| format!("{name} is not in this model"))?;
666    let tagged = |n: &Node| n.fields.get("pack").and_then(Value::as_str).is_some_and(|p| p.split('@').next() == Some(name));
667    let members: Vec<&(String, Node)> = current.iter().filter(|(_, n)| tagged(n) || n.id == manifest.1.id).collect();
668    let ids: Vec<&str> = members.iter().map(|(_, n)| n.id.as_str()).collect();
669    if !force {
670        // gather every reason at once, so the person sees the whole picture and not just the first thing in the way
671        let mut sections: Vec<String> = Vec::new();
672        let needers: Vec<String> = current
673            .iter()
674            .filter(|(_, n)| n.kind.as_deref() == Some("pack") && n.fields.get("name").and_then(Value::as_str) != Some(name))
675            .filter(|(_, n)| n.fields.get("requires").and_then(Value::as_array).is_some_and(|r| r.iter().filter_map(Value::as_str).any(|r| split_req(r).0 == name)))
676            .filter_map(|(_, n)| n.fields.get("name").and_then(Value::as_str).map(str::to_string))
677            .collect();
678        if !needers.is_empty() {
679            sections.push(format!("Used by {}.\n  They depend on its types, link types or rules. Remove {} first.", needers.join(", "), if needers.len() == 1 { "that pack" } else { "those packs" }));
680        }
681        let mut using = Vec::new();
682        for (_, n) in current.iter().filter(|(_, n)| !ids.contains(&n.id.as_str())) {
683            let label = if n.title != n.id { format!("{} ({})", n.title, n.id) } else { n.id.clone() };
684            let target = |id: &str| current.iter().find(|(_, m)| m.id == id).map(|(_, m)| if m.title != m.id { format!("{} ({})", m.title, m.id) } else { m.id.clone() }).unwrap_or_else(|| id.to_string());
685            let hits = n.links.iter().filter(|l| ids.contains(&l.to.as_str())).map(|l| format!("links to {} as '{}'", target(&l.to), l.kind))
686                .chain(n.parent.iter().filter(|p| ids.contains(&p.as_str())).map(|p| format!("sits under {}", target(p))))
687                .chain(n.plane.iter().filter(|p| ids.contains(&p.as_str())).map(|p| format!("is on the plane {}", target(p))));
688            for h in hits {
689                using.push(format!("{label} {h}"));
690            }
691        }
692        if !using.is_empty() {
693            let more = if using.len() > 12 { format!("\n  … and {} more", using.len() - 12) } else { String::new() };
694            sections.push(format!("Your model still uses it ({}):\n  {}{more}\n  Removing the pack would leave these pointing at things that no longer exist.", using.len(), using.iter().take(12).cloned().collect::<Vec<_>>().join("\n  ")));
695        }
696        let st = status(model)?.into_iter().find(|s| s.name == name).unwrap_or_default();
697        if !st.changed.is_empty() {
698            let names: Vec<String> = st.changed.iter().map(|id| current.iter().find(|(_, m)| m.id == *id).map(|(_, m)| if m.title != m.id { format!("{} ({})", m.title, m.id) } else { m.id.clone() }).unwrap_or_else(|| id.clone())).collect();
699            sections.push(format!("You changed {} of its nodes:\n  {}\n  Removing the pack deletes your changes with it.", st.changed.len(), names.join("\n  ")));
700        }
701        if !sections.is_empty() {
702            return Err(format!("{name} can't be removed yet.\n\n{}", sections.join("\n\n")));
703        }
704    }
705    let mut out = Removed::default();
706    for (path, n) in members {
707        fs::remove_file(model.join(path)).map_err(|e| format!("cannot remove {path}: {e}"))?;
708        out.removed.push(n.id.clone());
709    }
710    Ok(out)
711}
712
713/// Write a pack that was made in the model out to a pack folder `<packs>/<name>/`, so other models can add it:
714/// the manifest (without the install record) and every node that carries its tag. Returns the node count.
715/// The folder is checked as a pack before it replaces an earlier export.
716pub fn export(model: &Path, packs: &Path, name: &str) -> Result<usize, String> {
717    let current: Vec<Node> = crate::read_model(&model.to_string_lossy())?.into_iter().filter_map(|(_, t)| parse_node(&t).ok()).collect();
718    let mut manifest = current
719        .iter()
720        .find(|n| n.kind.as_deref() == Some("pack") && n.fields.get("name").and_then(Value::as_str) == Some(name))
721        .cloned()
722        .ok_or(format!("the model has no pack called '{name}'"))?;
723    manifest.fields.remove("installed");
724    let version = manifest.fields.get("version").and_then(Value::as_str).ok_or("the pack needs a version")?.to_string();
725    let tag = format!("{name}@{version}");
726    if name.is_empty() || name.contains(['/', '\\']) || name.starts_with('.') {
727        return Err(format!("'{name}' cannot be a folder name"));
728    }
729    let tmp = packs.join(format!(".export-{name}"));
730    let _ = fs::remove_dir_all(&tmp);
731    fs::create_dir_all(&tmp).map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
732    let result = (|| -> Result<usize, String> {
733        let put = |n: &Node| fs::write(tmp.join(format!("{}.md", n.id)), node_to_markdown(n)).map_err(|e| format!("cannot write {}: {e}", n.id));
734        put(&manifest)?;
735        let mut count = 0;
736        for n in current.iter().filter(|n| n.kind.as_deref().is_some_and(|k| DEFINITION_KINDS.contains(&k)) && n.fields.get("pack").and_then(Value::as_str) == Some(tag.as_str())) {
737            put(n)?;
738            count += 1;
739        }
740        read_pack(&tmp).map_err(|e| format!("not a valid pack yet: {e}"))?;
741        Ok(count)
742    })();
743    match result {
744        Ok(count) => {
745            let dest = packs.join(name);
746            let _ = fs::remove_dir_all(&dest);
747            fs::rename(&tmp, &dest).map_err(|e| format!("cannot write {}: {e}", dest.display()))?;
748            Ok(count)
749        }
750        Err(e) => {
751            let _ = fs::remove_dir_all(&tmp);
752            Err(e)
753        }
754    }
755}