Skip to main content

specfold_core/check/limits/
generated.rs

1//! `[generated] manifest`: the files another tool writes and the sources it writes them from.
2//! A generated copy is not content-checked (its source is); rule G2 reports a manifest that
3//! cannot be read and a source that does not exist.
4
5use crate::config::Config;
6use anyhow::{Context, Result, anyhow, bail};
7use serde_json::Value;
8
9/// One generated file and the sources it is made from (repository paths).
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct Output {
12    pub path: String,
13    pub sources: Vec<String>,
14}
15
16/// The manifest's outputs; empty without `[generated] manifest`.
17#[derive(Debug, Clone, Default)]
18pub struct Generated {
19    pub outputs: Vec<Output>,
20}
21
22impl Generated {
23    /// Whether `path` is a generated file or lies inside a generated directory.
24    pub fn holds(&self, path: &str) -> bool {
25        self.outputs.iter().any(|o| crate::paths::is_under(path, &o.path))
26    }
27}
28
29/// Reads the manifest. Its value is an array of entries, or a table whose `outputs` or `files`
30/// key is one; an entry is a table with a string `path` (anything after `#` is a place inside
31/// the file and is dropped) and optionally `source` (a string) or `sources` (strings).
32pub fn load(cfg: &Config) -> Result<Generated> {
33    let Some(pointer) = &cfg.raw.generated.manifest else { return Ok(Generated::default()) };
34    let v = super::source::read(&cfg.spec_home, pointer).context("[generated] manifest")?;
35    parse(&v).with_context(|| format!("[generated] manifest = \"{pointer}\""))
36}
37
38fn parse(v: &Value) -> Result<Generated> {
39    let list = match v {
40        Value::Array(a) => a,
41        Value::Object(m) => match m.get("outputs").or_else(|| m.get("files")) {
42            Some(Value::Array(a)) => a,
43            _ => bail!("no array of entries (the value itself, or its outputs or files key)"),
44        },
45        _ => bail!("no array of entries (the value itself, or its outputs or files key)"),
46    };
47    let mut outputs: Vec<Output> = vec![];
48    for (i, e) in list.iter().enumerate() {
49        let at = || format!("entry {}", i + 1);
50        let path = e.get("path").and_then(Value::as_str).ok_or_else(|| anyhow!("{} has no string path", at()))?;
51        let path = path.split('#').next().unwrap_or(path).trim_end_matches('/').to_string();
52        if path.is_empty() {
53            bail!("{} has an empty path", at());
54        }
55        let mut sources = vec![];
56        if let Some(s) = e.get("source") {
57            sources.push(s.as_str().ok_or_else(|| anyhow!("{}: source is not a string", at()))?.to_string());
58        }
59        if let Some(s) = e.get("sources") {
60            let list = s.as_array().ok_or_else(|| anyhow!("{}: sources is not a list", at()))?;
61            for x in list {
62                sources.push(x.as_str().ok_or_else(|| anyhow!("{}: a source is not a string", at()))?.to_string());
63            }
64        }
65        match outputs.iter_mut().find(|o| o.path == path) {
66            Some(o) => o.sources.extend(sources),
67            None => outputs.push(Output { path, sources }),
68        }
69    }
70    for o in &mut outputs {
71        o.sources.sort();
72        o.sources.dedup();
73    }
74    Ok(Generated { outputs })
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    fn entries_merge_by_file_and_bad_entries_are_errors() {
83        let v = serde_json::json!({"version": 1, "outputs": [
84            {"path": "tool.json#a.b", "kind": "json"},
85            {"path": "tool.json#a.c", "source": "src/tool.toml"},
86            {"path": ".tool/skills/x/", "sources": ["skills/x/SKILL.md"]}
87        ]});
88        let g = parse(&v).unwrap();
89        assert_eq!(g.outputs.len(), 2);
90        assert_eq!(g.outputs[0], Output { path: "tool.json".into(), sources: vec!["src/tool.toml".into()] });
91        assert!(g.holds(".tool/skills/x/SKILL.md") && g.holds("tool.json") && !g.holds("tool.jsonc"));
92        assert!(parse(&serde_json::json!([{"kind": "x"}])).is_err());
93        assert!(parse(&serde_json::json!({"items": []})).is_err());
94        assert!(parse(&serde_json::json!([{"path": "a", "sources": "b"}])).is_err());
95    }
96}