Skip to main content

mortise_core/run/
mod.rs

1//! How PHP runs for an app: the kind of runner, the command line, and starting it.
2//!
3//! A command line is a program and a list of arguments. It never goes through a shell.
4//! With the `run` feature, [`test_php`] runs `artisan --version` through a runner.
5
6#[cfg(feature = "run")]
7pub mod ansi;
8#[cfg(feature = "run")]
9mod detect;
10#[cfg(feature = "run")]
11pub use detect::{Detected, detect, herd_config_dir};
12#[cfg(feature = "run")]
13pub mod history;
14pub(crate) mod process;
15#[cfg(feature = "run")]
16mod read;
17#[cfg(feature = "run")]
18pub use process::{Run, RunEnd, RunEvent, Runs, STOP_WAIT, StartError, Stream, stop_asks_first};
19#[cfg(feature = "run")]
20pub use read::{Read, ReadEnd};
21
22use std::path::{Path, PathBuf};
23use std::time::Duration;
24
25use serde::{Deserialize, Serialize};
26
27use crate::program::split_words;
28
29/// The program through which PHP runs artisan for an app.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(tag = "kind", rename_all = "kebab-case")]
32pub enum RunnerKind {
33    Herd,
34    Sail,
35    /// `docker compose exec` in the named service.
36    Docker {
37        service: String,
38    },
39    /// The words of a line the user typed.
40    Custom {
41        line: String,
42    },
43}
44
45impl RunnerKind {
46    /// The words before the artisan arguments, for this platform.
47    /// An empty Custom line gives no words.
48    pub fn prefix(&self) -> Vec<String> {
49        let words: &[&str] = match self {
50            RunnerKind::Herd if cfg!(windows) => &["herd.bat", "php", "artisan"],
51            RunnerKind::Herd => &["herd", "php", "artisan"],
52            RunnerKind::Sail => &["./vendor/bin/sail", "artisan"],
53            RunnerKind::Docker { service } => {
54                return ["docker", "compose", "exec", "-T", service, "php", "artisan"]
55                    .map(String::from)
56                    .to_vec();
57            }
58            RunnerKind::Custom { line } => return split_words(line),
59        };
60        words.iter().map(|word| word.to_string()).collect()
61    }
62
63    /// The text of the command field: the prefix as words one space apart, or the
64    /// Custom line as the user typed it. [`RunnerKind::from_line`] reads it back.
65    pub fn line(&self) -> String {
66        match self {
67            RunnerKind::Custom { line } => line.clone(),
68            other => other.prefix().join(" "),
69        }
70    }
71
72    /// The kind a command field holds. The words of Herd, or of Sail off Windows,
73    /// give that kind. `docker compose exec [-T] <service> php artisan` gives Docker
74    /// with that service, unless the service is empty or starts with `-`. Any other
75    /// text gives Custom with the text.
76    pub fn from_line(line: &str) -> RunnerKind {
77        let words = split_words(line);
78        let words: Vec<&str> = words.iter().map(String::as_str).collect();
79        for kind in [RunnerKind::Herd, RunnerKind::Sail] {
80            if (kind != RunnerKind::Sail || !cfg!(windows)) && words == kind.prefix() {
81                return kind;
82            }
83        }
84        let service = match words.as_slice() {
85            ["docker", "compose", "exec", "-T", service, "php", "artisan"]
86            | ["docker", "compose", "exec", service, "php", "artisan"] => Some(*service),
87            _ => None,
88        };
89        match service {
90            Some(service) if !service.is_empty() && !service.starts_with('-') => {
91                RunnerKind::Docker {
92                    service: service.to_string(),
93                }
94            }
95            _ => RunnerKind::Custom {
96                line: line.to_string(),
97            },
98        }
99    }
100}
101
102/// How PHP runs for one app.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(default)]
105pub struct PhpSettings {
106    /// `None`: not chosen yet. Detection proposes one; nothing runs.
107    pub runner: Option<RunnerKind>,
108    /// `None`: the app folder. A relative path starts at the app folder.
109    pub working_folder: Option<PathBuf>,
110    /// Minutes before a command is stopped. 10 by default (S8.2).
111    pub time_limit_minutes: u16,
112}
113
114impl Default for PhpSettings {
115    fn default() -> Self {
116        Self {
117            runner: None,
118            working_folder: None,
119            time_limit_minutes: 10,
120        }
121    }
122}
123
124impl PhpSettings {
125    /// The folder a command runs in, for the app in `root`.
126    pub fn folder(&self, root: &Path) -> PathBuf {
127        match &self.working_folder {
128            Some(folder) => root.join(folder),
129            None => root.to_owned(),
130        }
131    }
132
133    /// How long a command may run. 0 minutes reads as 1 minute.
134    pub fn time_limit(&self) -> Duration {
135        Duration::from_secs(u64::from(self.time_limit_minutes.max(1)) * 60)
136    }
137}
138
139/// A program and its arguments, started without a shell.
140#[cfg(feature = "run")]
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct CommandLine {
143    pub program: String,
144    pub args: Vec<String>,
145}
146
147#[cfg(feature = "run")]
148impl CommandLine {
149    /// The line that runs artisan with `arguments` through `runner`.
150    /// `--no-interaction --ansi` come right after the first argument, so a `--`
151    /// later in the list cannot turn them into plain words. A flag that the prefix,
152    /// or the arguments before a `--`, already hold is not added again.
153    /// `None` when the runner gives no program (an empty Custom line).
154    pub fn artisan(runner: &RunnerKind, arguments: &[&str]) -> Option<Self> {
155        let mut words = runner.prefix().into_iter();
156        let program = words.next()?;
157        let mut args: Vec<String> = words.collect();
158        let options = arguments.iter().take_while(|word| **word != "--");
159        let held: Vec<&str> = args
160            .iter()
161            .map(String::as_str)
162            .chain(options.copied())
163            .collect();
164        let flags = ["--no-interaction", "--ansi"]
165            .into_iter()
166            .filter(|flag| !held.contains(flag))
167            .map(String::from)
168            .collect::<Vec<_>>();
169        let (first, rest) = match arguments.split_first() {
170            Some((first, rest)) => (Some(*first), rest),
171            None => (None, arguments),
172        };
173        args.extend(first.map(String::from));
174        args.extend(flags);
175        args.extend(rest.iter().map(|word| word.to_string()));
176        Some(Self { program, args })
177    }
178
179    /// The line to show and copy, quoted for the shell of this platform.
180    /// The process always gets the list, not this text.
181    pub fn display(&self) -> String {
182        if cfg!(windows) {
183            powershell(self)
184        } else {
185            posix(self)
186        }
187    }
188
189    fn words(&self) -> impl Iterator<Item = &str> {
190        std::iter::once(self.program.as_str()).chain(self.args.iter().map(String::as_str))
191    }
192}
193
194/// How long "Test" waits for `artisan --version` before it stops it.
195#[cfg(feature = "run")]
196pub const TEST_LIMIT: Duration = Duration::from_secs(20);
197
198/// What came of a test of the runner of an app.
199#[cfg(feature = "run")]
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub enum TestOutcome {
202    /// The program ended with code 0. The first line it printed, without colour codes.
203    Answered(String),
204    Failed(Failure),
205}
206
207/// Why a test failed. The interface writes the text; this is data only.
208#[cfg(feature = "run")]
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub enum Failure {
211    /// The runner gives no program: an empty Custom line.
212    NoCommand,
213    /// The working folder is not a folder. Without this check a missing folder
214    /// reads as a missing program on macOS and Linux.
215    NoFolder { folder: PathBuf },
216    /// The system found no program by that name.
217    NotFound { program: String },
218    /// The program did not start for another reason, with the message of the system.
219    NotStarted { program: String, message: String },
220    /// The program ended with another code, or by a signal (`None`). The first line
221    /// of stderr that is not empty, else of stdout, else empty; without colour codes.
222    Exited { code: Option<i32>, line: String },
223    /// The program ran longer than the limit, in whole seconds, and was stopped.
224    TimedOut { seconds: u64 },
225}
226
227/// Runs `artisan --version` through `runner` in `folder`, for at most `limit`.
228/// It blocks, so an interface calls it off its drawing thread.
229#[cfg(feature = "run")]
230pub fn test_php(runner: &RunnerKind, folder: &Path, limit: Duration) -> TestOutcome {
231    let Some(line) = CommandLine::artisan(runner, &["--version"]) else {
232        return TestOutcome::Failed(Failure::NoCommand);
233    };
234    if !folder.is_dir() {
235        return TestOutcome::Failed(Failure::NoFolder {
236            folder: folder.to_owned(),
237        });
238    }
239    let captured = match process::capture(&line, folder, limit) {
240        Ok(captured) => captured,
241        Err(error) => return TestOutcome::Failed(process::not_started(error, &line.program)),
242    };
243    let first = |lines: &[String]| {
244        lines
245            .iter()
246            .map(|text| ansi::plain(text))
247            .find(|text| !text.trim().is_empty())
248    };
249    if captured.timed_out {
250        TestOutcome::Failed(Failure::TimedOut {
251            seconds: limit.as_secs(),
252        })
253    } else if captured.code == Some(0) {
254        TestOutcome::Answered(first(&captured.stdout).unwrap_or_default())
255    } else {
256        let line = first(&captured.stderr)
257            .or_else(|| first(&captured.stdout))
258            .unwrap_or_default();
259        TestOutcome::Failed(Failure::Exited {
260            code: captured.code,
261            line,
262        })
263    }
264}
265
266/// Whether a word can stand without quotes: not empty, and only ASCII letters,
267/// digits, `_ - . / : = +` and the letters in `more`.
268#[cfg(feature = "run")]
269fn bare(word: &str, more: &[char]) -> bool {
270    !word.is_empty()
271        && word
272            .chars()
273            .all(|c| c.is_ascii_alphanumeric() || "_-./:=+".contains(c) || more.contains(&c))
274}
275
276/// The line for POSIX `sh`. A word that is not bare goes in single quotes, and a
277/// `'` inside becomes `'\''`. A program with `=` is quoted too: `sh` reads
278/// `a=b cmd` as an assignment.
279#[cfg(feature = "run")]
280fn posix(line: &CommandLine) -> String {
281    line.words()
282        .enumerate()
283        .map(|(at, word)| {
284            if bare(word, &[]) && (at > 0 || !word.contains('=')) {
285                word.to_string()
286            } else {
287                format!("'{}'", word.replace('\'', r"'\''"))
288            }
289        })
290        .collect::<Vec<_>>()
291        .join(" ")
292}
293
294/// The line for PowerShell. A word that is not bare goes in single quotes, which
295/// expand nothing. A quote inside is doubled; PowerShell also reads the curly
296/// quotes as single quotes. A quoted program needs `& ` before it.
297///
298/// Known limit: Windows PowerShell 5.1 drops an empty argument and mangles a `"`
299/// inside an argument to a program. PowerShell 7.3 and later pass both, except to a
300/// `.bat` or `.cmd`: those still get their arguments the legacy way. So an empty
301/// argument can vanish when the copied Herd line (`herd.bat`) is pasted on Windows.
302#[cfg(feature = "run")]
303fn powershell(line: &CommandLine) -> String {
304    const QUOTES: [char; 5] = ['\'', '\u{2018}', '\u{2019}', '\u{201A}', '\u{201B}'];
305    let text = line
306        .words()
307        .map(|word| {
308            if bare(word, &['\\']) {
309                return word.to_string();
310            }
311            let mut quoted = String::from("'");
312            for c in word.chars() {
313                if QUOTES.contains(&c) {
314                    quoted.push(c);
315                }
316                quoted.push(c);
317            }
318            quoted.push('\'');
319            quoted
320        })
321        .collect::<Vec<_>>()
322        .join(" ");
323    if bare(&line.program, &['\\']) {
324        text
325    } else {
326        format!("& {text}")
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn from_line_reads_each_kind() {
336        let docker = RunnerKind::Docker {
337            service: "web".into(),
338        };
339        assert_eq!(
340            RunnerKind::from_line(&RunnerKind::Herd.line()),
341            RunnerKind::Herd
342        );
343        assert_eq!(RunnerKind::from_line(&docker.line()), docker);
344        assert_eq!(
345            RunnerKind::from_line("docker  compose exec web php artisan"),
346            docker
347        );
348        let sail = RunnerKind::from_line("./vendor/bin/sail artisan");
349        let custom = |line: &str| RunnerKind::Custom { line: line.into() };
350        if cfg!(windows) {
351            assert_eq!(sail, custom("./vendor/bin/sail artisan"));
352        } else {
353            assert_eq!(sail, RunnerKind::Sail);
354        }
355        for line in [
356            "\"/opt/my php/bin/php\" artisan",
357            "docker compose exec -T php artisan",
358            "docker compose exec -T \"\" php artisan",
359            "herd php artisan tinker",
360            "",
361        ] {
362            assert_eq!(RunnerKind::from_line(line), custom(line), "{line}");
363        }
364    }
365
366    #[test]
367    fn php_settings_give_the_folder_and_the_time_limit() {
368        let root = Path::new("/code/shop-api");
369        let mut php = PhpSettings {
370            time_limit_minutes: 0,
371            ..PhpSettings::default()
372        };
373        assert_eq!(php.folder(root), root);
374        assert_eq!(php.time_limit(), Duration::from_secs(60));
375        php.working_folder = Some("api".into());
376        assert_eq!(php.folder(root), root.join("api"));
377    }
378
379    #[test]
380    fn runner_kinds_keep_their_json_form() {
381        let json = r#"[{"kind":"herd"},{"kind":"sail"},{"kind":"docker","service":"app"},{"kind":"custom","line":"php artisan"}]"#;
382        let kinds: Vec<RunnerKind> = serde_json::from_str(json).unwrap();
383        assert_eq!(serde_json::to_string(&kinds).unwrap(), json);
384    }
385
386    #[cfg(feature = "run")]
387    fn line(words: &[&str]) -> CommandLine {
388        CommandLine {
389            program: words[0].into(),
390            args: words[1..].iter().map(|word| word.to_string()).collect(),
391        }
392    }
393
394    #[cfg(feature = "run")]
395    #[test]
396    fn artisan_puts_the_flags_after_the_first_argument() {
397        let custom = |line: &str| RunnerKind::Custom { line: line.into() };
398        let php = custom("php artisan");
399        assert_eq!(
400            CommandLine::artisan(&php, &["module:make", "Blog", "--", "--ansi"]),
401            Some(line(&[
402                "php",
403                "artisan",
404                "module:make",
405                "--no-interaction",
406                "--ansi",
407                "Blog",
408                "--",
409                "--ansi"
410            ]))
411        );
412        assert_eq!(
413            CommandLine::artisan(&php, &[]),
414            Some(line(&["php", "artisan", "--no-interaction", "--ansi"]))
415        );
416        let docker = RunnerKind::Docker {
417            service: "app".into(),
418        };
419        let version = CommandLine::artisan(&docker, &["--version"]).unwrap();
420        assert_eq!(version.program, "docker");
421        assert_eq!(
422            version.args.join(" "),
423            "compose exec -T app php artisan --version --no-interaction --ansi"
424        );
425        assert_eq!(
426            CommandLine::artisan(&custom("php artisan --ansi"), &["list", "--no-interaction"]),
427            Some(line(&[
428                "php",
429                "artisan",
430                "--ansi",
431                "list",
432                "--no-interaction"
433            ]))
434        );
435        assert_eq!(CommandLine::artisan(&custom(" "), &["--version"]), None);
436        // The line that Test runs for Herd, as the shell of the platform reads it (S35).
437        let herd = CommandLine::artisan(&RunnerKind::Herd, &["--version"]).unwrap();
438        let program = if cfg!(windows) { "herd.bat" } else { "herd" };
439        assert_eq!(
440            herd.display(),
441            format!("{program} php artisan --version --no-interaction --ansi")
442        );
443    }
444
445    #[cfg(feature = "run")]
446    #[test]
447    fn posix_quotes_what_sh_would_read() {
448        for (words, shown) in [
449            (
450                &["php", "module:make", "--name=Blog"][..],
451                "php module:make --name=Blog",
452            ),
453            (&["php", "My Blog"], "php 'My Blog'"),
454            (&["php", "it's"], r"php 'it'\''s'"),
455            (&["php", r#"say "hi""#], r#"php 'say "hi"'"#),
456            (&["php", ""], "php ''"),
457            (&["php", "$HOME"], "php '$HOME'"),
458            (&["php", r"a\b"], r"php 'a\b'"),
459            (
460                &[r"C:\Program Files\php\php.exe"],
461                r"'C:\Program Files\php\php.exe'",
462            ),
463            (&["php", "Füße"], "php 'Füße'"),
464            (
465                &["php", "a,b", "@x", "%PATH%", "a;b", "a*"],
466                "php 'a,b' '@x' '%PATH%' 'a;b' 'a*'",
467            ),
468            (&["bin/a=b", "x=y"], "'bin/a=b' x=y"),
469        ] {
470            assert_eq!(posix(&line(words)), shown);
471        }
472    }
473
474    #[cfg(feature = "run")]
475    #[test]
476    fn powershell_quotes_what_powershell_would_read() {
477        for (words, shown) in [
478            (
479                &["php", "module:make", "--name=Blog"][..],
480                "php module:make --name=Blog",
481            ),
482            (&["php", "My Blog"], "php 'My Blog'"),
483            (
484                &["php", "it's", "it\u{2019}s"],
485                "php 'it''s' 'it\u{2019}\u{2019}s'",
486            ),
487            (&["php", r#"say "hi""#], r#"php 'say "hi"'"#),
488            (&["php", ""], "php ''"),
489            (&["php", "$HOME"], "php '$HOME'"),
490            (&["php", r"a\b"], r"php a\b"),
491            (
492                &[r"C:\Program Files\php\php.exe"],
493                r"& 'C:\Program Files\php\php.exe'",
494            ),
495            (&["php", "Füße"], "php 'Füße'"),
496            (
497                &["php", "a,b", "@x", "%PATH%", "a;b", "a*"],
498                "php 'a,b' '@x' '%PATH%' 'a;b' 'a*'",
499            ),
500        ] {
501            assert_eq!(powershell(&line(words)), shown);
502        }
503    }
504}