Skip to main content

rain_metadata/cli/
validate.rs

1use clap::Parser;
2use std::path::PathBuf;
3use crate::meta::KnownMeta;
4
5/// command for validating a meta
6#[derive(Parser)]
7pub struct Validate {
8    /// The known meta to validate against.
9    #[arg(short, long)]
10    meta: KnownMeta,
11    /// The input path to the json serialized metadata to validate against the
12    /// known schema.
13    #[arg(short, long)]
14    input_path: PathBuf,
15}
16
17pub fn validate(v: Validate) -> anyhow::Result<()> {
18    let data: Vec<u8> = std::fs::read(v.input_path)?;
19    // If we can normalize the input data then it is valid.
20    let _normalized = v.meta.normalize(&data)?;
21    Ok(())
22}
23
24#[cfg(all(test, not(target_family = "wasm")))]
25mod tests {
26    use super::*;
27    use std::io::Write;
28
29    /// A meta that normalizes is valid.
30    #[test]
31    fn test_validate_ok_for_valid_meta() {
32        let mut file = tempfile::NamedTempFile::new().unwrap();
33        file.write_all(
34            br#"[{"word":"stack","description":"Copies an existing value from the stack.","operandParserOffset":16}]"#,
35        )
36        .unwrap();
37        let v = Validate {
38            meta: KnownMeta::AuthoringMetaV1,
39            input_path: file.path().to_path_buf(),
40        };
41        assert!(validate(v).is_ok());
42    }
43
44    /// A meta that does not normalize is invalid: validity IS
45    /// normalizability.
46    #[test]
47    fn test_validate_err_for_invalid_meta() {
48        let mut file = tempfile::NamedTempFile::new().unwrap();
49        file.write_all(b"{\"not\": \"an authoring meta\"}").unwrap();
50        let v = Validate {
51            meta: KnownMeta::AuthoringMetaV1,
52            input_path: file.path().to_path_buf(),
53        };
54        assert!(validate(v).is_err());
55    }
56
57    /// Arbitrary bytes are not a valid authoring-meta-v2.
58    #[test]
59    fn test_validate_err_for_arbitrary_authoring_meta_v2() {
60        let mut file = tempfile::NamedTempFile::new().unwrap();
61        file.write_all(&[0xde, 0xad]).unwrap();
62        let v = Validate {
63            meta: KnownMeta::AuthoringMetaV2,
64            input_path: file.path().to_path_buf(),
65        };
66        assert!(validate(v).is_err());
67    }
68}