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
use {Context, Test, Directive, Command, TestResultKind};
use std::process;
use std::collections::HashMap;
use regex::Regex;

use tool;
use std;

pub struct Instance
{
    pub invocation: tool::Invocation,
}

impl Instance
{
    pub fn new(invocation: tool::Invocation) -> Self {
        Instance { invocation: invocation }
    }

    pub fn run(self, test: &Test, context: &Context) -> TestResultKind {
        let exe_path = context.executable_path(&self.invocation.executable);
        let mut cmd = self.build_command(test, context);

        let output = match cmd.output() {
            Ok(o) => o,
            Err(e) => match e.kind() {
                std::io::ErrorKind::NotFound => {
                    return TestResultKind::Fail(
                        format!("executable not found: {}",
                                exe_path), "".to_owned());
                },
                _ => {
                    return TestResultKind::Fail(
                        format!("could not execute: '{}', {}",
                                exe_path, e), "".to_owned());
                },
            },
        };

        if !output.status.success() {
            let stderr = String::from_utf8(output.stderr).unwrap();

            return TestResultKind::Fail(format!(
                "{} exited with code {}", exe_path,
                output.status.code().unwrap()),
                stderr
            );
        }

        let stdout = String::from_utf8(output.stdout).unwrap();

        let stdout_lines: Vec<_> = stdout.lines().map(|l| l.trim().to_owned()).collect();
        let stdout: String = stdout_lines.join("\n");

        Checker::new(stdout).run(&test)
    }

    pub fn build_command(&self, test: &Test, context: &Context) -> process::Command {
        let exe_path = context.executable_path(&self.invocation.executable);
        let mut cmd = process::Command::new(&exe_path);

        for arg in self.invocation.arguments.iter() {
            let arg_str = arg.resolve(test);
            cmd.arg(arg_str);
        }

        cmd
    }
}

struct Checker
{
    stdout: String,
    variables: HashMap<String, String>,
}

impl Checker
{
    fn new(stdout: String) -> Self {
        Checker {
            stdout: stdout,
            variables: HashMap::new(),
        }
    }

    fn run(&mut self, test: &Test) -> TestResultKind {
        for directive in test.directives.iter() {
            match directive.command {
                Command::Run(..) => (),
                Command::Check(ref regex) => {
                    let regex = self.resolve_variables(regex.clone());

                    let beginning_line = match self.stdout.lines().next() {
                        Some(l) => l.to_owned(),
                        None => return TestResultKind::fail(
                            format_check_error(test, directive, "reached end of file", "")
                        ),
                    };

                    let mut matched_line = None;
                    let tmp: Vec<_> = self.stdout.lines().map(|l| l.to_owned()).skip_while(|line| {
                        if regex.is_match(&line) {
                            matched_line = Some(line.to_owned());
                            false // stop processing lines
                        } else {
                            true
                        }
                    }).skip(1).collect();
                    self.stdout = tmp.join("\n");

                    if let Some(matched_line) = matched_line {
                        self.process_captures(&regex, &matched_line);
                    } else {
                        return TestResultKind::fail(
                            format_check_error(test,
                                               directive,
                                               &format!("could not find match: '{}'", regex),
                                               &beginning_line,
                            )
                        );
                    }
                },
                Command::CheckNext(ref regex) => {
                    let regex = self.resolve_variables(regex.clone());

                    if let Some(ref next_line) = self.stdout.lines().next().map(|l| l.to_owned()) {
                        if regex.is_match(&next_line) {
                            let lines: Vec<_> = self.stdout.lines().skip(1).map(|l| l.to_owned()).collect();
                            self.stdout = lines.join("\n");

                            self.process_captures(&regex, &next_line);
                        } else {
                            return TestResultKind::fail(
                                format_check_error(test,
                                                   directive,
                                                   &format!("could not find match: '{}'", regex),
                                                   &next_line)
                                );
                        }
                    } else {
                        return TestResultKind::fail(format!("check-next reached the end of file"));
                    }
                },
            }
        }

        TestResultKind::Pass
    }

    pub fn process_captures(&mut self, regex: &Regex, line: &str) {
        // We shouldn't be calling this function if it didn't match.
        debug_assert_eq!(regex.is_match(line), true);
        let captures = if let Some(captures) = regex.captures(line) {
            captures
        } else {
            return;
        };

        for capture_name in regex.capture_names() {
            // we only care about named captures.
            if let Some(name) = capture_name {
                let captured_value = captures.name(name).unwrap();

                self.variables.insert(name.to_owned(), captured_value.to_owned());
            }
        }
    }

    pub fn resolve_variables(&self, mut regex: Regex) -> Regex {
        for (name, value) in self.variables.iter() {
            let subst_expr = format!("[[{}]]", name);
            let regex_str = format!("{}", regex);
            let regex_str = regex_str.replace(&subst_expr, value);
            regex = Regex::new(&regex_str).unwrap();
        }

        regex
    }
}

fn format_check_error(test: &Test,
                      directive: &Directive,
                      msg: &str,
                      next_line: &str) -> String {
    self::format_error(test, directive, msg, next_line)
}

fn format_error(test: &Test,
                directive: &Directive,
                msg: &str,
                next_line: &str) -> String {
    format!("{}:{}: {}\nnext line: '{}'", test.path, directive.line, msg, next_line)
}