Skip to main content

ahk_cli/
v1ref.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The reference of the v1: the binary of the AutoHotkey v1 and what it
3//! says about a script.
4//!
5//! The tree answers a script one way and the v1 another; the difference
6//! is the bug to find. The tools of this module run the same script under
7//! the two and give the two answers side by side, so a client reads the
8//! difference without a shell and without the window of the v1.
9
10use std::io::Read;
11use std::path::{Path, PathBuf};
12use std::process::{Command, Stdio};
13use std::time::{Duration, Instant};
14
15/// The binary of the v1 that is the reference of the tree.
16///
17/// The path is read from `AHK_V1` when it is there, and this is the
18/// place of the install of the v1.1.37.02 on a machine of Windows.
19const THE_V1: &str = "C:\\Program Files\\AutoHotkey\\v1.1.37.02\\AutoHotkeyU64.exe";
20
21/// The seconds the v1 may take before the answer is taken as hung.
22const THE_SECONDS: u64 = 10;
23
24/// The path of the binary of the v1.
25pub fn the_path_of_the_v1() -> String {
26    std::env::var("AHK_V1").unwrap_or_else(|_| THE_V1.to_string())
27}
28
29/// What the v1 said about a script.
30#[derive(Debug, Default)]
31pub struct TheAnswer {
32    /// The text that the v1 wrote out.
33    pub output: String,
34    /// The code of the end of the v1, and `None` when it did not end.
35    pub code: Option<i32>,
36    /// Whether the v1 was still running when the time was over.
37    pub hung: bool,
38    /// The reason the v1 could not be run at all.
39    pub failure: Option<String>,
40}
41
42impl TheAnswer {
43    /// The lines of the answer, with the line of the script in them.
44    ///
45    /// The v1 writes the errors like this:
46    ///
47    /// ```text
48    /// probe.ahk (12) : ==> Message
49    /// ```
50    ///
51    /// The script is written with the directive of the v1 in front, and
52    /// the line of the error is one more than the line of the script.
53    pub fn the_errors(&self) -> Vec<String> {
54        self.output
55            .lines()
56            .filter(|line| line.contains("==>"))
57            .map(the_line_of_the_script)
58            .collect()
59    }
60}
61
62/// Take one line of the v1 and give it back with the line of the script.
63///
64/// The directive of the v1 is a line of its own in front of the script,
65/// and the line of the error is one more than the line of the script.
66fn the_line_of_the_script(line: &str) -> String {
67    let Some(mark) = line.find(" : ==> ") else {
68        return line.to_string();
69    };
70    let (head, tail) = line.split_at(mark);
71    let Some(open) = head.rfind('(') else {
72        return line.to_string();
73    };
74    let Some(close) = head[open..].find(')') else {
75        return line.to_string();
76    };
77    let close = open + close;
78    let digits = &head[open + 1..close];
79    let Ok(number) = digits.trim().parse::<u64>() else {
80        return line.to_string();
81    };
82    if number == 0 {
83        return line.to_string();
84    }
85    format!("{}({}){}", &head[..open], number - 1, &head[close + 1..])
86        + tail
87}
88
89/// The file of the script, and the directory of it.
90fn the_file_of_the_script(source: &str) -> std::io::Result<PathBuf> {
91    let dir = std::env::temp_dir().join(format!("ahk-mcp-{}", std::process::id()));
92    std::fs::create_dir_all(&dir)?;
93    let file = dir.join("probe.ahk");
94    // The errors of the run go to the output and not to a dialog of the
95    // machine: the dialog waits for a mouse that nobody moves. The
96    // directive is the one of the v1 (`Set +ErrorStdOut` is of the v2).
97    std::fs::write(&file, format!("#ErrorStdOut\n{source}"))?;
98    Ok(file)
99}
100
101/// Run the source under the binary of the v1 and answer with what it
102/// said.
103pub fn the_run_of_the_v1(source: &str) -> TheAnswer {
104    let path = the_path_of_the_v1();
105    if !Path::new(&path).exists() {
106        return TheAnswer {
107            failure: Some(format!(
108                "the binary of the v1 is not there: {path} (the path comes from AHK_V1)"
109            )),
110            ..TheAnswer::default()
111        };
112    }
113    let file = match the_file_of_the_script(source) {
114        Ok(file) => file,
115        Err(e) => {
116            return TheAnswer {
117                failure: Some(format!("the script was not written: {e}")),
118                ..TheAnswer::default()
119            }
120        }
121    };
122    let mut child = match Command::new(&path)
123        .arg("/ErrorStdOut")
124        .arg(&file)
125        .stdin(Stdio::null())
126        .stdout(Stdio::piped())
127        .stderr(Stdio::piped())
128        .spawn()
129    {
130        Ok(child) => child,
131        Err(e) => {
132            return TheAnswer {
133                failure: Some(format!("the v1 did not start: {e}")),
134                ..TheAnswer::default()
135            }
136        }
137    };
138    let deadline = Instant::now() + Duration::from_secs(THE_SECONDS);
139    let mut code = None;
140    let mut hung = false;
141    loop {
142        match child.try_wait() {
143            Ok(Some(status)) => {
144                code = status.code();
145                break;
146            }
147            Ok(None) => {
148                if Instant::now() >= deadline {
149                    let _ = child.kill();
150                    let _ = child.wait();
151                    hung = true;
152                    break;
153                }
154                std::thread::sleep(Duration::from_millis(20));
155            }
156            Err(e) => {
157                return TheAnswer {
158                    failure: Some(format!("the v1 was not waited for: {e}")),
159                    ..TheAnswer::default()
160                };
161            }
162        }
163    }
164    let mut output = String::new();
165    let mut errors = String::new();
166    if let Some(mut out) = child.stdout.take() {
167        let _ = out.read_to_string(&mut output);
168    }
169    if let Some(mut err) = child.stderr.take() {
170        let _ = err.read_to_string(&mut errors);
171    }
172    if !errors.is_empty() {
173        output.push_str(&errors);
174    }
175    TheAnswer {
176        output,
177        code,
178        hung,
179        failure: None,
180    }
181}