Skip to main content

jan_cli/
spec_load.rs

1//! YAML spec loading with `include` links and host-OS filtering.
2
3use std::collections::{BTreeMap, HashSet};
4use std::path::{Path, PathBuf};
5
6use anyhow::{bail, Context, Result};
7use serde::Deserialize;
8use std::borrow::Cow;
9
10use crate::{CommandNode, ExecSpec, Metadata, RootSpec};
11
12/// Which platform string to use when filtering `os:` lists on commands.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct HostPlatform {
15    /// Normalized id: `linux`, `macos`, `windows`, or another `std::env::consts::OS` value.
16    pub id: Cow<'static, str>,
17}
18
19impl HostPlatform {
20    /// Resolve the process host, honoring `JAN_OS` when set (for tests and overrides).
21    pub fn detect() -> Self {
22        if let Ok(v) = std::env::var("JAN_OS") {
23            let s = v.trim().to_ascii_lowercase();
24            if !s.is_empty() {
25                return Self::from_normalized(&s);
26            }
27        }
28        Self::from_normalized(std::env::consts::OS)
29    }
30
31    fn from_normalized(os: &str) -> Self {
32        let id = match os {
33            "darwin" | "macos" => Cow::Borrowed("macos"),
34            "linux" => Cow::Borrowed("linux"),
35            "windows" => Cow::Borrowed("windows"),
36            other => Cow::Owned(other.to_string()),
37        };
38        Self { id }
39    }
40}
41
42fn normalize_os_token(tok: &str) -> String {
43    match tok.trim().to_ascii_lowercase().as_str() {
44        "darwin" => "macos".to_string(),
45        s => s.to_string(),
46    }
47}
48
49fn node_visible_for_platform(os_list: &[String], platform: &str) -> bool {
50    if os_list.is_empty() {
51        return true;
52    }
53    os_list.iter().any(|o| normalize_os_token(o) == platform)
54}
55
56#[derive(Debug, Deserialize)]
57struct RawRootSpec {
58    metadata: Option<Metadata>,
59    #[serde(default)]
60    include: Vec<String>,
61    #[serde(default)]
62    commands: BTreeMap<String, RawCommandNode>,
63}
64
65#[derive(Debug, Deserialize)]
66struct RawCommandNode {
67    #[serde(default)]
68    os: Vec<String>,
69    #[serde(default)]
70    about: String,
71    path: Option<String>,
72    #[serde(default)]
73    dependencies: Vec<String>,
74    #[serde(default)]
75    requires: Vec<String>,
76    #[serde(default)]
77    env: BTreeMap<String, String>,
78    include: Option<String>,
79    #[serde(default)]
80    commands: BTreeMap<String, RawCommandNode>,
81    exec: Option<ExecSpec>,
82}
83
84#[derive(Clone)]
85struct LoadCtx {
86    /// Canonical root of the directory selected by `jan use`.
87    ///
88    /// Every include is interpreted relative to this directory, including includes
89    /// found in nested YAML files. Canonicalization also prevents symlink escapes.
90    use_root: PathBuf,
91}
92
93impl LoadCtx {
94    fn read_include(&self, rel: &str) -> Result<String> {
95        let path = resolve_under(&self.use_root, rel)?;
96        std::fs::read_to_string(&path)
97            .with_context(|| format!("read included spec {}", path.display()))
98    }
99
100    fn visit_token(&self, rel: &str) -> Result<String> {
101        let p = resolve_under(&self.use_root, rel)?;
102        Ok(p.to_string_lossy().to_string())
103    }
104}
105
106fn resolve_under(use_root: &Path, rel: &str) -> Result<PathBuf> {
107    let rel = rel.trim();
108    if rel.is_empty() {
109        bail!("empty include path");
110    }
111    let p = Path::new(rel);
112    if p.is_absolute() {
113        bail!("include path must be relative to the jan use root: {rel}");
114    }
115    if p.components()
116        .any(|c| matches!(c, std::path::Component::ParentDir))
117    {
118        bail!("include path must not contain `..`: {rel}");
119    }
120
121    let full = use_root.join(p);
122    let resolved = full
123        .canonicalize()
124        .with_context(|| format!("include path not found: {}", full.display()))?;
125    if !resolved.starts_with(use_root) {
126        bail!(
127            "include escapes jan use root: {} (root: {})",
128            resolved.display(),
129            use_root.display()
130        );
131    }
132    if !resolved.is_file() {
133        bail!("include is not a file: {}", resolved.display());
134    }
135    Ok(resolved)
136}
137
138fn merge_os_filters(outer: &[String], inner: &[String]) -> Result<Vec<String>> {
139    match (outer.is_empty(), inner.is_empty()) {
140        (true, true) => Ok(vec![]),
141        (true, false) => Ok(inner.to_vec()),
142        (false, true) => Ok(outer.to_vec()),
143        (false, false) => {
144            let merged: Vec<String> = outer
145                .iter()
146                .filter(|o| {
147                    let n = normalize_os_token(o);
148                    inner.iter().any(|i| normalize_os_token(i) == n)
149                })
150                .cloned()
151                .collect();
152            if merged.is_empty() {
153                bail!(
154                    "conflicting `os:` filters between include wrapper and included file \
155                     (no platform appears in both lists)"
156                );
157            }
158            Ok(merged)
159        }
160    }
161}
162
163fn overlay_about(overlay: &str, base: String) -> String {
164    let o = overlay.trim();
165    if o.is_empty() {
166        base
167    } else {
168        o.to_string()
169    }
170}
171
172fn resolve_raw_command_node(
173    raw: RawCommandNode,
174    ctx: &LoadCtx,
175    visited: &mut HashSet<String>,
176) -> Result<CommandNode> {
177    if raw.include.is_some() && (raw.exec.is_some() || !raw.commands.is_empty()) {
178        bail!("command with `include` cannot also define `exec` or nested `commands` in the same YAML map");
179    }
180
181    let mut raw = raw;
182    if let Some(rel) = raw.include.take() {
183        let token = ctx.visit_token(&rel)?;
184        if !visited.insert(token.clone()) {
185            bail!("include cycle detected at `{token}`");
186        }
187        let text = ctx.read_include(&rel)?;
188        let inner: RawCommandNode =
189            serde_yaml::from_str(&text).with_context(|| format!("parse include `{rel}`"))?;
190        let mut node = resolve_raw_command_node(inner, ctx, visited)?;
191        visited.remove(&token);
192        node.os = merge_os_filters(&raw.os, &node.os)?;
193        node.about = overlay_about(&raw.about, node.about);
194        return Ok(node);
195    }
196
197    let mut commands = BTreeMap::new();
198    for (name, child) in raw.commands {
199        commands.insert(name, resolve_raw_command_node(child, ctx, visited)?);
200    }
201
202    Ok(CommandNode {
203        os: raw.os,
204        about: raw.about,
205        path: raw.path,
206        dependencies: raw.dependencies,
207        requires: raw.requires,
208        env: raw.env,
209        commands,
210        exec: raw.exec,
211    })
212}
213
214fn merge_root_includes(mut root: RawRootSpec, use_root: &Path) -> Result<RawRootSpec> {
215    let mut merged = BTreeMap::new();
216    for inc in &root.include {
217        let path = resolve_under(use_root, inc)?;
218        let text = std::fs::read_to_string(&path)
219            .with_context(|| format!("read root include {}", path.display()))?;
220        let fragment: RawRootSpec =
221            serde_yaml::from_str(&text).with_context(|| format!("parse {}", path.display()))?;
222        let mut expanded = merge_root_includes(fragment, use_root)?;
223        merged.append(&mut expanded.commands);
224    }
225    merged.append(&mut root.commands);
226    root.commands = merged;
227    root.include.clear();
228    Ok(root)
229}
230
231fn materialize_root(raw: RawRootSpec, ctx: &LoadCtx) -> Result<RootSpec> {
232    let mut visited = HashSet::new();
233    let mut commands = BTreeMap::new();
234    for (name, node) in raw.commands {
235        commands.insert(name, resolve_raw_command_node(node, ctx, &mut visited)?);
236    }
237    Ok(RootSpec {
238        metadata: raw.metadata,
239        commands,
240    })
241}
242
243fn validate_root(spec: &RootSpec) -> Result<()> {
244    for (name, node) in &spec.commands {
245        node.validate(name)?;
246    }
247    Ok(())
248}
249
250pub fn load_spec_from_path(spec_path: &Path, platform: HostPlatform) -> Result<RootSpec> {
251    let spec_path = spec_path
252        .canonicalize()
253        .with_context(|| format!("canonicalize spec file {}", spec_path.display()))?;
254    let text = std::fs::read_to_string(&spec_path)
255        .with_context(|| format!("read spec file {}", spec_path.display()))?;
256    let raw: RawRootSpec = serde_yaml::from_str(&text).context("parse YAML spec")?;
257    let use_root = spec_path
258        .parent()
259        .unwrap_or_else(|| Path::new("."))
260        .to_path_buf();
261    let raw = merge_root_includes(raw, &use_root)?;
262    let ctx = LoadCtx { use_root };
263    let mut spec = materialize_root(raw, &ctx)?;
264    // Validate structure before OS filtering: filtering can drop nested nodes (e.g. empty
265    // placeholders) and would otherwise hide invalid `exec` + `commands` combinations.
266    validate_root(&spec)?;
267    filter_spec_for_platform(&mut spec, platform.id.as_ref());
268    Ok(spec)
269}
270
271/// Parse an in-memory spec. Every `include` resolves relative to `use_root`.
272/// Pass `None` only when the document has no root `include` keys.
273pub fn load_spec_from_str(
274    raw: &str,
275    use_root: Option<&Path>,
276    platform: HostPlatform,
277) -> Result<RootSpec> {
278    let raw: RawRootSpec = serde_yaml::from_str(raw).context("parse YAML spec")?;
279    let canonical_root = use_root
280        .map(|root| {
281            root.canonicalize()
282                .with_context(|| format!("canonicalize jan use root {}", root.display()))
283        })
284        .transpose()?;
285    let raw = if let Some(root) = canonical_root.as_deref() {
286        merge_root_includes(raw, root)?
287    } else {
288        if !raw.include.is_empty() {
289            bail!("root-level `include` requires a base directory (pass when calling load_spec_from_str)");
290        }
291        raw
292    };
293    let ctx = LoadCtx {
294        use_root: canonical_root.unwrap_or_else(|| PathBuf::from(".")),
295    };
296    let mut spec = materialize_root(raw, &ctx)?;
297    validate_root(&spec)?;
298    filter_spec_for_platform(&mut spec, platform.id.as_ref());
299    Ok(spec)
300}
301
302pub fn filter_spec_for_platform(spec: &mut RootSpec, platform_id: &str) {
303    filter_command_map(&mut spec.commands, platform_id);
304}
305
306fn filter_command_map(map: &mut BTreeMap<String, CommandNode>, platform_id: &str) {
307    map.retain(|_, node| {
308        if !node_visible_for_platform(&node.os, platform_id) {
309            return false;
310        }
311        filter_command_map(&mut node.commands, platform_id);
312        if node.exec.is_some() {
313            return true;
314        }
315        !node.commands.is_empty()
316    });
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use crate::ExecSpec;
323    use std::fs;
324
325    #[test]
326    fn os_filter_drops_linux_only_branch() {
327        let mut spec = RootSpec {
328            metadata: None,
329            commands: BTreeMap::from([(
330                "sys".into(),
331                CommandNode {
332                    os: vec!["linux".into()],
333                    about: "linux".into(),
334                    commands: BTreeMap::from([(
335                        "ports".into(),
336                        CommandNode {
337                            exec: Some(ExecSpec {
338                                argv: vec!["echo".into(), "x".into()],
339                                passthrough: false,
340                            }),
341                            ..Default::default()
342                        },
343                    )]),
344                    ..Default::default()
345                },
346            )]),
347        };
348        filter_spec_for_platform(&mut spec, "macos");
349        assert!(spec.commands.is_empty());
350    }
351
352    #[test]
353    fn nested_include_resolves_from_use_root() {
354        let tmp = tempfile::tempdir().unwrap();
355        let root = tmp.path();
356        fs::create_dir(root.join("sub")).unwrap();
357        fs::write(
358            root.join("leaf.yaml"),
359            "about: root leaf\nexec:\n  argv: [\"echo\", \"root\"]\n",
360        )
361        .unwrap();
362        fs::write(root.join("sub/outer.yaml"), "include: leaf.yaml\n").unwrap();
363        fs::write(
364            root.join("scripts.spec.yaml"),
365            "commands:\n  outer:\n    include: sub/outer.yaml\n",
366        )
367        .unwrap();
368
369        let spec =
370            load_spec_from_path(&root.join("scripts.spec.yaml"), HostPlatform::detect()).unwrap();
371        assert_eq!(
372            spec.commands["outer"].exec.as_ref().unwrap().argv,
373            vec!["echo", "root"]
374        );
375    }
376
377    #[test]
378    fn include_rejects_absolute_and_parent_paths() {
379        let tmp = tempfile::tempdir().unwrap();
380        let root = tmp.path().join("tree");
381        fs::create_dir(&root).unwrap();
382        let outside = tmp.path().join("outside.yaml");
383        fs::write(
384            &outside,
385            "about: outside\nexec:\n  argv: [\"echo\", \"outside\"]\n",
386        )
387        .unwrap();
388
389        for include in [
390            outside.to_string_lossy().into_owned(),
391            "../outside.yaml".to_string(),
392        ] {
393            fs::write(
394                root.join("scripts.spec.yaml"),
395                format!("commands:\n  escaped:\n    include: {include:?}\n"),
396            )
397            .unwrap();
398            let err = load_spec_from_path(&root.join("scripts.spec.yaml"), HostPlatform::detect())
399                .unwrap_err();
400            assert!(
401                err.to_string().contains("must be relative")
402                    || err.to_string().contains("must not contain `..`"),
403                "{err:#}"
404            );
405        }
406    }
407
408    #[cfg(unix)]
409    #[test]
410    fn include_rejects_symlink_escape() {
411        use std::os::unix::fs::symlink;
412
413        let tmp = tempfile::tempdir().unwrap();
414        let root = tmp.path().join("tree");
415        fs::create_dir(&root).unwrap();
416        let outside = tmp.path().join("outside.yaml");
417        fs::write(
418            &outside,
419            "about: outside\nexec:\n  argv: [\"echo\", \"outside\"]\n",
420        )
421        .unwrap();
422        symlink(&outside, root.join("linked.yaml")).unwrap();
423        fs::write(
424            root.join("scripts.spec.yaml"),
425            "commands:\n  escaped:\n    include: linked.yaml\n",
426        )
427        .unwrap();
428
429        let err = load_spec_from_path(&root.join("scripts.spec.yaml"), HostPlatform::detect())
430            .unwrap_err();
431        assert!(err.to_string().contains("escapes jan use root"), "{err:#}");
432    }
433}