Skip to main content

astrs_cli/command/
schema.rs

1//! `astrs schema` (blueprint §17): emit the manifest JSON schema.
2//!
3//! Delegates entirely to [`astrs_manifest::emit_schema`] — this module's
4//! only job is wiring that library function to stdout or a file, exactly
5//! so `xtask schema` (out of this stage's scope; xtask is off-limits per
6//! this wave's brief) can later call the same library function this
7//! command calls, rather than either place re-deriving the schema.
8
9use std::io::Write;
10use std::path::PathBuf;
11
12use crate::error::CliError;
13
14/// Arguments for `astrs schema`.
15#[derive(Debug, Clone, Default)]
16pub struct SchemaArgs {
17    /// Write the schema to this file instead of the output sink.
18    pub output: Option<PathBuf>,
19}
20
21/// The result of emitting the schema.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct SchemaReport {
24    /// The emitted schema text.
25    pub schema: String,
26    /// The file it was written to, if [`SchemaArgs::output`] was set.
27    pub written_to: Option<PathBuf>,
28}
29
30/// Emit the manifest JSON schema to `out`, or to [`SchemaArgs::output`]
31/// when set.
32///
33/// # Errors
34///
35/// Returns [`CliError::Io`] if writing to [`SchemaArgs::output`] (or, with
36/// no `output`, to `out` itself) fails.
37pub fn run(out: &mut dyn Write, args: &SchemaArgs) -> Result<SchemaReport, CliError> {
38    let schema = astrs_manifest::emit_schema();
39    match &args.output {
40        Some(path) => {
41            std::fs::write(path, &schema).map_err(|err| CliError::io(path, err))?;
42        }
43        None => {
44            writeln!(out, "{schema}").map_err(|e| CliError::io("<output>", e))?;
45        }
46    }
47    Ok(SchemaReport {
48        schema,
49        written_to: args.output.clone(),
50    })
51}
52
53#[cfg(test)]
54mod tests {
55    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
56    use super::*;
57
58    #[test]
59    fn default_output_writes_valid_json_to_the_sink() {
60        let mut out = Vec::new();
61        let report = run(&mut out, &SchemaArgs::default()).unwrap();
62        assert!(report.written_to.is_none());
63        let printed = String::from_utf8(out).unwrap();
64        let value: serde_json::Value = serde_json::from_str(printed.trim_end()).unwrap();
65        assert!(value.is_object());
66        assert_eq!(printed.trim_end(), report.schema);
67    }
68
69    #[test]
70    fn output_path_writes_to_the_file_not_the_sink() {
71        let dir =
72            std::env::temp_dir().join(format!("astrs-cli-schema-test-{}", std::process::id()));
73        std::fs::create_dir_all(&dir).unwrap();
74        let path = dir.join("schema.json");
75
76        let mut out = Vec::new();
77        let report = run(
78            &mut out,
79            &SchemaArgs {
80                output: Some(path.clone()),
81            },
82        )
83        .unwrap();
84        assert!(out.is_empty(), "nothing should be written to the sink");
85        assert_eq!(report.written_to, Some(path.clone()));
86        let on_disk = std::fs::read_to_string(&path).unwrap();
87        assert_eq!(on_disk, report.schema);
88
89        let _ = std::fs::remove_dir_all(&dir);
90    }
91
92    #[test]
93    fn schema_never_mentions_output_framing() {
94        // Blueprint §2.2: this field must not exist anywhere.
95        let mut out = Vec::new();
96        let report = run(&mut out, &SchemaArgs::default()).unwrap();
97        assert!(!report.schema.contains("output_framing"));
98    }
99
100    #[test]
101    fn unwritable_output_path_is_an_io_error() {
102        let path = PathBuf::from("/this/path/does/not/exist/schema.json");
103        let mut out = Vec::new();
104        let err = run(&mut out, &SchemaArgs { output: Some(path) }).unwrap_err();
105        assert!(matches!(err, CliError::Io { .. }));
106    }
107}