1
use crate::errors::EssenceParseError;
2
use conjure_cp_core::parse::model_from_json;
3
use conjure_cp_core::{Model, context::Context};
4
use std::sync::{Arc, RwLock};
5

            
6
3498
pub fn parse_essence_file(
7
3498
    path: &str,
8
3498
    context: Arc<RwLock<Context<'static>>>,
9
3498
) -> Result<Model, EssenceParseError> {
10
3498
    let mut cmd = std::process::Command::new("conjure");
11
3498
    let output = match cmd
12
3498
        .arg("pretty")
13
3498
        .arg("--output-format=astjson")
14
3498
        .arg(path)
15
3498
        .output()
16
    {
17
3498
        Ok(output) => output,
18
        Err(e) => return Err(EssenceParseError::ConjurePrettyError(e.to_string())),
19
    };
20

            
21
3498
    if !output.status.success() {
22
11
        let stderr_string = String::from_utf8(output.stderr)
23
11
            .unwrap_or("stderr is not a valid UTF-8 string".to_string());
24
11
        return Err(EssenceParseError::ConjurePrettyError(stderr_string));
25
3487
    }
26

            
27
3487
    let astjson = match String::from_utf8(output.stdout) {
28
3487
        Ok(astjson) => astjson,
29
        Err(e) => {
30
            return Err(EssenceParseError::ConjurePrettyError(format!(
31
                "Error parsing output from conjure: {e:#?}"
32
            )));
33
        }
34
    };
35

            
36
3487
    let parsed_model = model_from_json(&astjson, context)?;
37
3487
    Ok(parsed_model)
38
3498
}