1
use anyhow::{Result, anyhow, bail};
2
use versions::Versioning;
3

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

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

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

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

            
49
176
    if Versioning::new(version) < Versioning::new(CONJURE_MIN_VERSION) {
50
        bail!("Conjure version is too old (< {CONJURE_MIN_VERSION}): {version}");
51
176
    }
52
176
    Ok(())
53
176
}