Skip to main content

astrs_cli/command/
expand.rs

1//! `astrs expand` (blueprint §8.5, §17): print a manifest with every
2//! `module:`-sourced node flattened, in stable YAML — the shape
3//! `astrs-graph` and the runtime actually consume.
4
5use std::io::Write;
6use std::path::{Path, PathBuf};
7
8use astrs_manifest::Manifest;
9use astrs_manifest::expand::FsModuleLoader;
10
11use crate::error::CliError;
12
13/// Arguments for `astrs expand`.
14#[derive(Debug, Clone)]
15pub struct ExpandArgs {
16    /// The manifest file to expand.
17    pub manifest_path: PathBuf,
18}
19
20/// The result of expanding one manifest.
21#[derive(Debug, Clone, PartialEq)]
22pub struct ExpandReport {
23    /// The flattened manifest.
24    pub manifest: Manifest,
25    /// [`Self::manifest`] rendered as YAML — exactly what was written to
26    /// the output sink.
27    pub yaml: String,
28}
29
30/// Run `astrs expand`: parse, validate, expand, and print the flattened
31/// manifest as YAML.
32///
33/// Unlike `validate`, a manifest that fails any of these steps aborts the
34/// command outright — there is no meaningful "flattened YAML" to print
35/// for a manifest that never became valid, so this is one of the few
36/// commands where an upstream failure becomes this function's own `Err`
37/// rather than report content (see `crate::error` module docs).
38///
39/// # Errors
40///
41/// Returns [`CliError::Io`] if the file cannot be read (or the output
42/// sink cannot be written to), [`CliError::Manifest`] if it does not
43/// parse, [`CliError::Validation`] if it fails structural validation
44/// (checked both before and after expansion — see `command::validate`'s
45/// own docs for why), or [`CliError::Expand`] if module expansion itself
46/// fails.
47pub fn run(out: &mut dyn Write, args: &ExpandArgs) -> Result<ExpandReport, CliError> {
48    let content = std::fs::read_to_string(&args.manifest_path)
49        .map_err(|err| CliError::io(&args.manifest_path, err))?;
50    let manifest = Manifest::from_yaml_str(&content)?;
51    manifest.validate()?;
52
53    let base_dir = base_dir_of(&args.manifest_path);
54    let loader = FsModuleLoader;
55    let expanded = manifest.expand(&base_dir, &loader)?;
56    expanded.validate()?;
57
58    let yaml = expanded.to_yaml().map_err(CliError::Manifest)?;
59    writeln!(out, "{yaml}").map_err(|e| CliError::io("<output>", e))?;
60
61    Ok(ExpandReport {
62        manifest: expanded,
63        yaml,
64    })
65}
66
67/// See `command::validate::base_dir_of` — duplicated rather than shared
68/// because it is a two-line, crate-visibility-free helper and both call
69/// sites want it `private` to their own module for independent testing.
70fn base_dir_of(manifest_path: &Path) -> PathBuf {
71    match manifest_path.parent() {
72        Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
73        _ => PathBuf::from("."),
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
80    use super::*;
81
82    fn write_temp(name: &str, content: &str) -> PathBuf {
83        // A monotonic counter, not just `(pid, name)`, disambiguates the
84        // directory -- see `command::graph`'s own test helper for the
85        // observed race this guards against if a future test ever reuses
86        // an existing `name` under cargo's multi-threaded test runner.
87        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
88        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
89        let dir = std::env::temp_dir().join(format!(
90            "astrs-cli-expand-test-{}-{name}-{n}",
91            std::process::id()
92        ));
93        std::fs::create_dir_all(&dir).unwrap();
94        let path = dir.join("root.yaml");
95        std::fs::write(&path, content).unwrap();
96        path
97    }
98
99    #[test]
100    fn a_manifest_with_no_modules_is_a_no_op() {
101        let path = write_temp("no-modules", "nodes:\n  - id: solo\n    path: ./solo\n");
102        let mut out = Vec::new();
103        let report = run(
104            &mut out,
105            &ExpandArgs {
106                manifest_path: path,
107            },
108        )
109        .unwrap();
110        assert_eq!(report.manifest.nodes.len(), 1);
111        let printed = String::from_utf8(out).unwrap();
112        // Round-trips through the manifest parser to the identical
113        // structure -- proving `expand`'s printed text really is what
114        // `ExpandReport::yaml` says it is, without pinning the exact
115        // bytes `Manifest::to_yaml` happens to emit today (that crate's
116        // own tests already freeze its formatting).
117        let reparsed = Manifest::from_yaml_str(printed.trim_end()).unwrap();
118        assert_eq!(reparsed, report.manifest);
119    }
120
121    #[test]
122    fn a_module_reference_is_flattened_and_disappears() {
123        let dir = std::env::temp_dir().join(format!(
124            "astrs-cli-expand-test-{}-module",
125            std::process::id()
126        ));
127        std::fs::create_dir_all(&dir).unwrap();
128        std::fs::write(
129            dir.join("root.yaml"),
130            "nodes:\n  - id: camera\n    path: ./camera\n    outputs: [frames]\n  - id: m\n    module: ./perception.yaml\n    inputs:\n      frames: camera/frames\n",
131        )
132        .unwrap();
133        std::fs::write(
134            dir.join("perception.yaml"),
135            "module:\n  name: perception\n  inputs: [frames]\nnodes:\n  - id: detector\n    path: ./detector\n    inputs:\n      frames: _mod/frames\n",
136        )
137        .unwrap();
138
139        let mut out = Vec::new();
140        let report = run(
141            &mut out,
142            &ExpandArgs {
143                manifest_path: dir.join("root.yaml"),
144            },
145        )
146        .unwrap();
147        let ids: Vec<_> = report
148            .manifest
149            .nodes
150            .iter()
151            .map(|n| n.id.as_str())
152            .collect();
153        assert_eq!(ids, vec!["camera", "m.detector"]);
154        assert!(report.manifest.module.is_none());
155        assert!(!report.yaml.contains("module:"));
156
157        let _ = std::fs::remove_dir_all(&dir);
158    }
159
160    #[test]
161    fn malformed_yaml_is_a_manifest_error() {
162        let path = write_temp("bad-yaml", "nodes: [");
163        let mut out = Vec::new();
164        let err = run(
165            &mut out,
166            &ExpandArgs {
167                manifest_path: path,
168            },
169        )
170        .unwrap_err();
171        assert!(matches!(err, CliError::Manifest(_)));
172    }
173
174    #[test]
175    fn missing_file_is_an_io_error() {
176        let path = std::env::temp_dir().join("astrs-cli-expand-does-not-exist.yaml");
177        let mut out = Vec::new();
178        let err = run(
179            &mut out,
180            &ExpandArgs {
181                manifest_path: path,
182            },
183        )
184        .unwrap_err();
185        assert!(matches!(err, CliError::Io { .. }));
186    }
187
188    #[test]
189    fn structural_violation_is_a_validation_error() {
190        let path = write_temp(
191            "dup",
192            "nodes:\n  - id: x\n    path: ./x\n  - id: x\n    path: ./y\n",
193        );
194        let mut out = Vec::new();
195        let err = run(
196            &mut out,
197            &ExpandArgs {
198                manifest_path: path,
199            },
200        )
201        .unwrap_err();
202        assert!(matches!(err, CliError::Validation(_)));
203    }
204
205    #[test]
206    fn missing_module_file_is_an_expand_error() {
207        let path = write_temp(
208            "missing-module",
209            "nodes:\n  - id: m\n    module: ./missing.yaml\n",
210        );
211        let mut out = Vec::new();
212        let err = run(
213            &mut out,
214            &ExpandArgs {
215                manifest_path: path,
216            },
217        )
218        .unwrap_err();
219        assert!(matches!(err, CliError::Expand(_)));
220    }
221
222    #[test]
223    fn expand_output_is_stable_across_repeated_runs() {
224        let path = write_temp("stable", "nodes:\n  - id: solo\n    path: ./solo\n");
225        let mut first = Vec::new();
226        let mut second = Vec::new();
227        run(
228            &mut first,
229            &ExpandArgs {
230                manifest_path: path.clone(),
231            },
232        )
233        .unwrap();
234        run(
235            &mut second,
236            &ExpandArgs {
237                manifest_path: path,
238            },
239        )
240        .unwrap();
241        assert_eq!(first, second);
242    }
243
244    #[test]
245    fn base_dir_of_bare_filename_is_dot() {
246        assert_eq!(base_dir_of(Path::new("root.yaml")), PathBuf::from("."));
247    }
248}