1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use {
    serde_json,
    serde_json::Value,
    std::borrow::Cow,
    std::error,
    std::fmt,
    std::fs::File,
    std::io::{self, Read},
    std::path::Path,
};

#[derive(Debug)]
pub struct JsonSchema<'a> {
    // Cow allows us to store either owned values when needed (as in new_from_file) or borrowed
    // values when lifetimes allow (as in new).
    pub name: Cow<'a, str>,
    pub schema: Cow<'a, str>,
}

impl<'a> JsonSchema<'a> {
    pub const fn new(name: &'a str, schema: &'a str) -> Self {
        Self { name: Cow::Borrowed(name), schema: Cow::Borrowed(schema) }
    }

    pub fn new_from_file(file: &Path) -> Result<Self, Error> {
        let mut schema_buf = String::new();
        File::open(&file)?.read_to_string(&mut schema_buf)?;
        Ok(JsonSchema {
            name: Cow::Owned(file.to_string_lossy().into_owned()),
            schema: Cow::Owned(schema_buf),
        })
    }
}

// Directly include schemas in the library. These are used to parse component manifests.
pub const CMX_SCHEMA: &JsonSchema<'_> =
    &JsonSchema::new("cmx_schema.json", include_str!("../cmx_schema.json"));

/// The location in the file where an error was detected.
#[derive(PartialEq, Clone, Debug)]
pub struct Location {
    /// One-based line number of the error.
    pub line: usize,

    /// One-based column number of the error.
    pub column: usize,
}

/// Enum type that can represent any error encountered by a cmx operation.
#[derive(Debug)]
pub enum Error {
    Io(io::Error),
    Parse { err: String, location: Option<Location>, filename: Option<String> },
    Validate { schema_name: Option<String>, err: String, filename: Option<String> },
}

impl error::Error for Error {}

impl Error {
    pub fn parse(
        err: impl fmt::Display,
        location: Option<Location>,
        filename: Option<&Path>,
    ) -> Self {
        Self::Parse {
            err: err.to_string(),
            location,
            filename: filename.map(|f| f.to_string_lossy().into_owned()),
        }
    }

    pub fn validate(err: impl fmt::Display) -> Self {
        Self::Validate { schema_name: None, err: err.to_string(), filename: None }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self {
            Error::Io(err) => write!(f, "IO error: {}", err),
            Error::Parse { err, location, filename } => {
                let mut prefix = String::new();
                if let Some(filename) = filename {
                    prefix.push_str(&format!("{}:", filename));
                }
                if let Some(location) = location {
                    // Check for a syntax error generated by pest. These error messages have
                    // the line and column number embedded in them, so we don't want to
                    // duplicate that.
                    //
                    // TODO: If serde_json5 had an error type for json5 syntax errors, we wouldn't
                    // need to parse the string like this.
                    if !err.starts_with(" -->") {
                        prefix.push_str(&format!("{}:{}:", location.line, location.column));
                    }
                }
                if !prefix.is_empty() {
                    write!(f, "Error at {} {}", prefix, err)
                } else {
                    write!(f, "{}", err)
                }
            }
            Error::Validate { schema_name: _, err, filename } => {
                let mut prefix = String::new();
                if let Some(filename) = filename {
                    prefix.push_str(&format!("{}:", filename));
                }
                if !prefix.is_empty() {
                    write!(f, "Error at {} {}", prefix, err)
                } else {
                    write!(f, "{}", err)
                }
            }
        }
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Error::Io(err)
    }
}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        use serde_json::error::Category;
        match err.classify() {
            Category::Io | Category::Eof => Error::Io(err.into()),
            Category::Syntax => {
                let line = err.line();
                let column = err.column();
                Error::parse(err, Some(Location { line, column }), None)
            }
            Category::Data => Error::validate(err),
        }
    }
}
pub fn from_json_str(json: &str, filename: &Path) -> Result<Value, Error> {
    serde_json::from_str(json).map_err(|e| {
        Error::parse(
            format!("Couldn't read input as JSON: {}", e),
            Some(Location { line: e.line(), column: e.column() }),
            Some(filename),
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::format_err;
    use assert_matches::assert_matches;
    use cm_types;

    #[test]
    fn test_parse_error() {
        let result = serde_json::from_str::<cm_types::Name>("foo").map_err(Error::from);
        assert_matches!(result, Err(Error::Parse { .. }));

        let result = Error::parse(format_err!("oops"), None, None);
        assert_eq!(format!("{}", result), "oops");

        let result = Error::parse(format_err!("oops"), Some(Location { line: 2, column: 3 }), None);
        assert_eq!(format!("{}", result), "Error at 2:3: oops");

        let result = Error::parse(
            format_err!("oops"),
            Some(Location { line: 2, column: 3 }),
            Some(&Path::new("test.cml")),
        );
        assert_eq!(format!("{}", result), "Error at test.cml:2:3: oops");

        let result = Error::parse(
            format_err!(" --> pest error"),
            Some(Location { line: 42, column: 42 }),
            Some(&Path::new("test.cml")),
        );
        assert_eq!(format!("{}", result), "Error at test.cml:  --> pest error");
    }

    #[test]
    fn test_validation_error() {
        let result = serde_json::from_str::<cm_types::Name>("\"foo$\"").map_err(Error::from);
        assert_matches!(result, Err(Error::Validate { .. }));

        let mut result = Error::validate(format_err!("oops"));
        assert_eq!(format!("{}", result), "oops");

        if let Error::Validate { filename, .. } = &mut result {
            *filename = Some("test.cml".to_string());
        }
        assert_eq!(format!("{}", result), "Error at test.cml: oops");
    }
}