Skip to main content

lux_cli/
exec.rs

1use std::env;
2
3use clap::Args;
4use lux_lib::{
5    config::Config, lua_version::LuaVersion, operations, path::Paths, workspace::Workspace,
6};
7use miette::Result;
8
9#[derive(Args)]
10pub struct Exec {
11    /// The command to run, followed by arguments to pass to it.
12    #[arg(required = true, trailing_var_arg = true)]
13    command: Vec<String>,
14
15    /// Do not add `require('lux').loader()` to `LUA_INIT`.
16    /// If a rock has conflicting transitive dependencies,
17    /// disabling the Lux loader may result in the wrong modules being loaded.
18    #[clap(default_value_t = false)]
19    #[arg(long)]
20    no_loader: bool,
21}
22
23pub async fn exec(run: Exec, config: Config) -> Result<()> {
24    let workspace = Workspace::current()?;
25    let tree = match &workspace {
26        Some(project) => project.tree(&config)?,
27        None => {
28            let lua_version = LuaVersion::from(&config)?.clone();
29            config.user_tree(lua_version)?
30        }
31    };
32
33    let paths = Paths::new(&tree)?;
34    unsafe {
35        // safe as long as this is single-threaded
36        env::set_var("PATH", paths.path_prepended().joined());
37    }
38    let [command, args @ ..] = run.command.as_slice() else {
39        unreachable!("command is required");
40    };
41
42    operations::Exec::new(command, workspace.as_ref(), &config)
43        .args(args.to_vec())
44        .disable_loader(run.no_loader)
45        .exec()
46        .await?;
47    Ok(())
48}
49
50#[cfg(test)]
51mod tests {
52    use crate::{Cli, Commands};
53    use clap::error::ErrorKind;
54    use clap::Parser;
55
56    #[test]
57    fn forwards_arguments_after_command() {
58        let cli = Cli::try_parse_from(["lx", "exec", "echo", "--help", "-n"]).unwrap();
59        let Commands::Exec(exec) = cli.command else {
60            unreachable!()
61        };
62        assert_eq!(exec.command, ["echo", "--help", "-n"]);
63    }
64
65    #[test]
66    fn parses_exec_flags_before_command() {
67        let cli = Cli::try_parse_from(["lx", "exec", "--no-loader", "echo", "-n", "hi"]).unwrap();
68        let Commands::Exec(exec) = cli.command else {
69            unreachable!()
70        };
71        assert!(exec.no_loader);
72        assert_eq!(exec.command, ["echo", "-n", "hi"]);
73    }
74
75    #[test]
76    fn exec_help_is_not_forwarded() {
77        let err = match Cli::try_parse_from(["lx", "exec", "--help"]) {
78            Err(err) => err,
79            Ok(_) => unreachable!(),
80        };
81        assert_eq!(err.kind(), ErrorKind::DisplayHelp);
82    }
83}