1
//! Locate and validate the optional external Conjure parser.
2

            
3
use anyhow::{Result, anyhow, bail};
4
use versions::Versioning;
5

            
6
const CONJURE_MIN_VERSION: &str = "2.6.1"; // v2.6.1
7
const CORRECT_FIRST_LINE: &str = "Conjure: The Automated Constraint Modelling Tool";
8

            
9
/// Checks if the conjure executable is present in PATH and if it is the correct version.
10
/// Returns () on success and an error on failure.
11
366
pub fn conjure_executable() -> Result<()> {
12
366
    let mut cmd = std::process::Command::new("conjure");
13
366
    let output = cmd.arg("--version").output()?;
14
366
    let stdout = String::from_utf8(output.stdout)?;
15
366
    let stderr = String::from_utf8(output.stderr)?;
16

            
17
366
    if !stderr.is_empty() {
18
        bail!("'conjure' results in error: ".to_string() + &stderr);
19
366
    }
20
366
    let first = stdout
21
366
        .lines()
22
366
        .next()
23
366
        .ok_or(anyhow!("Could not read stdout"))?;
24
366
    if first != CORRECT_FIRST_LINE {
25
        let path = std::env::var("PATH")?;
26
        let paths = std::env::split_paths(&path);
27
        let num_conjures = paths.filter(|path| path.join("conjure").exists()).count();
28
        if num_conjures > 1 {
29
            bail!(
30
                "Conjure may be present in PATH after a conflicting name. \
31
            Make sure to prepend the correct path to Conjure to PATH."
32
            )
33
        } else {
34
            bail!("The correct Conjure executable is not present in PATH.")
35
        }
36
366
    }
37

            
38
366
    let version_line = stdout
39
366
        .lines()
40
366
        .nth(1)
41
366
        .ok_or(anyhow!("Could not read Conjure's stdout"))?;
42
366
    let version_and_repo = version_line.strip_prefix("Conjure v").ok_or(anyhow!(
43
366
        "Could not read Conjure's version from: {version_line}"
44
366
    ))?;
45
366
    let (version, _) = version_and_repo
46
366
        .split_once(" (Repository version ")
47
366
        .ok_or(anyhow!(
48
366
            "Could not read Conjure's version from: {version_line}"
49
366
        ))?;
50

            
51
366
    if Versioning::new(version) < Versioning::new(CONJURE_MIN_VERSION) {
52
        bail!("Conjure version is too old (< {CONJURE_MIN_VERSION}): {version}");
53
366
    }
54
366
    Ok(())
55
366
}