1use std::env;
2
3use clap::Args;
4use lux_lib::{config::Config, lua, operations, path::Paths, workspace::Workspace};
5use miette::Result;
6
7#[derive(Args)]
8pub struct Exec {
9 #[arg(required = true, trailing_var_arg = true)]
11 command: Vec<String>,
12
13 #[clap(default_value_t = false)]
17 #[arg(long)]
18 no_loader: bool,
19}
20
21pub async fn exec(run: Exec, config: Config) -> Result<()> {
22 let workspace = Workspace::current()?;
23 let tree = match &workspace {
24 Some(project) => project.tree(&config)?,
25 None => {
26 let lua_version = lua::Version::from(&config)?.clone();
27 config.user_tree(lua_version)?
28 }
29 };
30
31 let paths = Paths::new(&tree)?;
32 unsafe {
33 env::set_var("PATH", paths.path_prepended().joined());
35 }
36 let [command, args @ ..] = run.command.as_slice() else {
37 unreachable!("command is required");
38 };
39
40 operations::Exec::new(command, workspace.as_ref(), &config)
41 .args(args.to_vec())
42 .disable_loader(run.no_loader)
43 .exec()
44 .await?;
45 Ok(())
46}
47
48#[cfg(test)]
49mod tests {
50 use crate::{Cli, Commands};
51 use clap::error::ErrorKind;
52 use clap::Parser;
53
54 #[test]
55 fn forwards_arguments_after_command() {
56 let cli = Cli::try_parse_from(["lx", "exec", "echo", "--help", "-n"]).unwrap();
57 let Commands::Exec(exec) = cli.command else {
58 unreachable!()
59 };
60 assert_eq!(exec.command, ["echo", "--help", "-n"]);
61 }
62
63 #[test]
64 fn parses_exec_flags_before_command() {
65 let cli = Cli::try_parse_from(["lx", "exec", "--no-loader", "echo", "-n", "hi"]).unwrap();
66 let Commands::Exec(exec) = cli.command else {
67 unreachable!()
68 };
69 assert!(exec.no_loader);
70 assert_eq!(exec.command, ["echo", "-n", "hi"]);
71 }
72
73 #[test]
74 fn exec_help_is_not_forwarded() {
75 let err = match Cli::try_parse_from(["lx", "exec", "--help"]) {
76 Err(err) => err,
77 Ok(_) => unreachable!(),
78 };
79 assert_eq!(err.kind(), ErrorKind::DisplayHelp);
80 }
81}