1use std::process::Command;
2
3use clap::Args;
4use eyre::{eyre, Result};
5use itertools::Itertools;
6use lux_lib::{
7 config::{Config, LuaVersion},
8 operations::{self, LuaBinary},
9 project::Project,
10 rockspec::LuaVersionCompatibility,
11};
12
13use crate::build::{self, Build};
14
15#[derive(Args, Default)]
16#[clap(disable_help_flag = true)]
17pub struct RunLua {
18 args: Option<Vec<String>>,
20
21 #[arg(long)]
23 lua: Option<String>,
24
25 #[arg(long)]
27 help: bool,
28
29 #[clap(flatten)]
30 build: Build,
31}
32
33pub async fn run_lua(run_lua: RunLua, config: Config) -> Result<()> {
34 let lua_cmd = run_lua.lua.map(LuaBinary::Custom).unwrap_or(LuaBinary::Lua);
35
36 if run_lua.help {
37 return print_lua_help(&lua_cmd);
38 }
39
40 let project = Project::current()?;
41 let (lua_version, root, tree) = match &project {
42 Some(project) => (
43 project.toml().lua_version_matches(&config)?,
44 project.root().to_path_buf(),
45 project.tree(&config)?,
46 ),
47 None => {
48 let version = LuaVersion::from(&config)?.clone();
49 (
50 version.clone(),
51 std::env::current_dir()?,
52 config.user_tree(version)?,
53 )
54 }
55 };
56
57 if project.is_some() {
58 build::build(run_lua.build, config.clone()).await?;
59 }
60
61 operations::run_lua(
62 &root,
63 &tree,
64 lua_version,
65 lua_cmd,
66 &run_lua.args.unwrap_or_default(),
67 )
68 .await?;
69
70 Ok(())
71}
72
73fn print_lua_help(lua_cmd: &LuaBinary) -> Result<()> {
74 let output = match Command::new(lua_cmd.to_string())
75 .arg("-h")
77 .output()
78 {
79 Ok(output) => Ok(output),
80 Err(err) => Err(eyre!("Failed to run {}: {}", lua_cmd, err)),
81 }?;
82 let lua_help = String::from_utf8_lossy(&output.stderr)
83 .lines()
84 .skip(2)
85 .map(|line| format!(" {}", line))
86 .collect_vec()
87 .join("\n");
88 print!(
89 "
90Usage: lx lua -- [LUA_OPTIONS] [SCRIPT [ARGS]]...
91
92Arguments:
93 [LUA_OPTIONS]...
94{}
95
96Options:
97 --lua Path to the Lua interpreter to use
98 --no-lock When building a project, ignore the project's lockfile and don't create one
99 -h, --help Print help
100",
101 lua_help,
102 );
103 Ok(())
104}
105
106#[cfg(test)]
107mod test {
108 use std::path::PathBuf;
109
110 use lux_lib::config::ConfigBuilder;
111 use serial_test::serial;
112
113 use super::*;
114
115 #[serial]
116 #[tokio::test]
117 async fn test_run_lua() {
118 let args = RunLua {
119 args: Some(vec!["-v".into()]),
120 ..RunLua::default()
121 };
122 let temp: PathBuf = assert_fs::TempDir::new().unwrap().path().into();
123 let cwd = &std::env::current_dir().unwrap();
124 tokio::fs::create_dir_all(&temp).await.unwrap();
125 std::env::set_current_dir(&temp).unwrap();
126 let config = ConfigBuilder::new()
127 .unwrap()
128 .user_tree(Some(temp.clone()))
129 .build()
130 .unwrap();
131 run_lua(args, config).await.unwrap();
132 std::env::set_current_dir(cwd).unwrap();
133 }
134}