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
use std::{io, path, process, str::FromStr};

#[derive(Clone)]
struct Version {
    major: u8,
    minor: u8,
    patch: u8,
}

#[derive(Debug)]
pub enum RunResult {
    Ok,
    Err(String),
    Warn(String),
}

impl From<&io::Error> for RunResult {
    fn from(value: &io::Error) -> Self {
        RunResult::Err(value.to_string())
    }
}

impl FromStr for Version {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let re = regex::Regex::new(r".*version ([\d]+)\.([\d]+)\.([\d]+).*").unwrap();
        let caps = re.captures(s).ok_or("Failed to match version")?;

        Ok(Version {
            major: caps[1].parse().map_err(|_| "Invalid major version")?,
            minor: caps[2].parse().map_err(|_| "Invalid minor version")?,
            patch: caps[3].parse().map_err(|_| "Invalid patch level")?,
        })
    }
}

pub struct Runner {
    cmd: path::PathBuf,
    version: Option<Version>,
}

impl Runner {
    pub fn new<P>(path: P) -> Runner
    where
        P: AsRef<path::Path>,
    {
        let cmd = path::PathBuf::from(path.as_ref());
        Runner { cmd, version: None }
    }

    fn eval_status(status: process::ExitStatus) -> Result<(), io::Error> {
        match status.code() {
            Some(code) if code == 0 => (),
            Some(code) => {
                return Err(io::Error::new(
                    io::ErrorKind::Other,
                    format!("Process terminated with code {code}"),
                ));
            }
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::Interrupted,
                    "Process terminated by signal",
                ))
            }
        };
        Ok(())
    }

    pub fn get_version(&self) -> Option<String> {
        self.version
            .as_ref()
            .map(|v| format!("{}.{}.{}", v.major, v.minor, v.patch))
    }

    pub fn get_path(&self) -> path::PathBuf {
        self.cmd.clone()
    }

    pub fn validate(&mut self) -> Result<(), io::Error> {
        let cmd = process::Command::new(self.cmd.as_path())
            .arg("--version")
            .output()?;

        if let Err(err) = Runner::eval_status(cmd.status) {
            log::error!(
                "Execution failed:\n{}",
                String::from_utf8_lossy(&cmd.stderr)
            );
            return Err(err);
        }

        // example output of clang-format:
        // clang-format version 4.0.0 (tags/checker/checker-279)
        let stdout = String::from_utf8_lossy(&cmd.stdout);

        self.version = Some(stdout.parse::<Version>().map_err(|err| {
            io::Error::new(
                io::ErrorKind::Other,
                format!("Failed to parse --version output {stdout}: {err}"),
            )
        })?);
        Ok(())
    }

    fn run(mut cmd: process::Command, ignore_warn: bool) -> RunResult {
        let output = cmd.output();
        if let Err(err) = &output {
            return err.into();
        }
        let output = output.unwrap();

        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);

        if let Err(err) = Runner::eval_status(output.status) {
            if stderr.len() != 0 {
                return RunResult::Err(format!("{err}\n---\n{stderr}---\n{stdout}"));
            }
            return (&err).into();
        } else if !ignore_warn && !stderr.is_empty() {
            return RunResult::Warn(format!("warnings encountered\n---\n{stderr}---\n{stdout}"));
        }
        RunResult::Ok
    }

    pub fn run_tidy<P, Q>(&self, file: P, build_root: Q, fix: bool, ignore_warn: bool) -> RunResult
    where
        P: AsRef<path::Path>,
        Q: AsRef<path::Path>,
    {
        let mut cmd = process::Command::new(self.cmd.as_path());

        cmd.arg(file.as_ref().as_os_str());
        // TODO: the --config-file option does not exist for clang-tidy 10.0
        // if let Some(config_file) = config_file {
        //     cmd.arg(format!(
        //         "--config-file={}",
        //         config_file.as_ref().to_string_lossy()
        //     ));
        // }
        cmd.arg(format!("-p={}", build_root.as_ref().to_string_lossy()));
        if fix {
            cmd.arg("-fix");
        }
        // This suppresses printing statistics about ignored warnings:
        // cmd.arg("-quiet");

        Runner::run(cmd, ignore_warn)
    }

    pub fn supports_config_file(&self) -> Result<(), io::Error> {
        if self.version.is_none() {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "Unknown version, --config-file requires \
                clang-format version 12.0.0 or higher",
            ));
        }

        let version = self.version.as_ref().unwrap();
        if version.major < 9u8 {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                format!(
                    "Invalid version {}, --config-file check requires \
                    clang-format version 12.0.0 or higher",
                    self.get_version().unwrap()
                ),
            ));
        }

        Ok(())
    }
}

impl Clone for Runner {
    fn clone(&self) -> Runner {
        Runner {
            cmd: path::PathBuf::from(self.cmd.as_path()),
            version: self.version.clone(),
        }
    }
}