Skip to main content

xtask/
commands.rs

1use anyhow::Result;
2use which::which;
3use xshell::{Cmd, Shell, cmd};
4
5use crate::Config;
6
7pub fn actionlint_cmd<'a>(config: &Config, sh: &'a Shell) -> Option<Cmd<'a>> {
8    create_cmd(
9        "actionlint",
10        "https://github.com/rhysd/actionlint",
11        config,
12        sh,
13    )
14}
15
16pub fn cargo_cmd<'a>(config: &Config, sh: &'a Shell) -> Option<Cmd<'a>> {
17    create_cmd(
18        "cargo",
19        "https://www.rust-lang.org/learn/get-started",
20        config,
21        sh,
22    )
23}
24
25pub fn cross_cmd<'a>(config: &Config, sh: &'a Shell) -> Option<Cmd<'a>> {
26    create_cmd("cross", "https://github.com/cross-rs/cross", config, sh)
27}
28
29pub fn prettier_cmd<'a>(config: &Config, sh: &'a Shell) -> Option<Cmd<'a>> {
30    create_cmd("prettier", "https://prettier.io", config, sh)
31}
32
33pub fn typos_cmd<'a>(config: &Config, sh: &'a Shell) -> Option<Cmd<'a>> {
34    create_cmd("typos", "https://github.com/crate-ci/typos", config, sh)
35}
36
37fn create_cmd<'a>(
38    cmd_name: &str,
39    install_url: &str,
40    config: &Config,
41    sh: &'a Shell,
42) -> Option<Cmd<'a>> {
43    if check_command(cmd_name, install_url, config).is_err() {
44        return None;
45    }
46
47    let cmd = cmd!(sh, "{cmd_name}");
48
49    Some(cmd)
50}
51
52fn check_command(cmd_name: &str, install_url: &str, config: &Config) -> Result<()> {
53    // only ignore missing commands when not running in a CI environment
54    let is_local = !is_ci::cached();
55    match which(cmd_name) {
56        Ok(_) => {
57            // the command exists, we're good
58            Ok(())
59        }
60        Err(_) if config.ignore_missing_commands && is_local => {
61            println!("Warning: command not found `{cmd_name}`");
62            println!("Install: {install_url}");
63            Err(anyhow::Error::msg("command is missing, but ignored"))
64        }
65        Err(_) if is_ci::cached() => {
66            println!("Error: command not found `{cmd_name}`");
67            println!("Install: {install_url}");
68            std::process::exit(1);
69        }
70        Err(_) => {
71            println!("Error: command not found `{cmd_name}`; skip this task with --ignore-missing");
72            println!("Install: {install_url}");
73            std::process::exit(1);
74        }
75    }
76}