1use std::path::PathBuf;
2
3use tokio::process::Command;
4
5use clap::Args;
6use eyre::{eyre, Result};
7use itertools::Itertools;
8use lux_lib::{
9 config::{Config, LuaVersion},
10 lua_installation::LuaBinary,
11 operations,
12 project::Project,
13 rockspec::LuaVersionCompatibility,
14};
15
16use crate::build::{self, Build};
17
18#[derive(Args, Default)]
19#[clap(disable_help_flag = true)]
20pub struct RunLua {
21 args: Option<Vec<String>>,
23
24 #[arg(long)]
26 lua: Option<String>,
27
28 #[arg(long)]
30 test: bool,
31
32 #[arg(long)]
34 build: bool,
35
36 #[clap(default_value_t = false)]
40 #[arg(long)]
41 no_loader: bool,
42
43 #[clap(flatten)]
44 build_args: Build,
45
46 #[arg(long)]
48 help: bool,
49}
50
51pub async fn run_lua(run_lua: RunLua, config: Config) -> Result<()> {
52 let project = Project::current()?;
53 let (lua_version, root, tree, mut welcome_message) = match &project {
54 Some(project) => (
55 project.toml().lua_version_matches(&config)?,
56 project.root().to_path_buf(),
57 project.tree(&config)?,
58 format!(
59 "Welcome to the lux Lua repl for {}.",
60 project.toml().package()
61 ),
62 ),
63 None => {
64 let version = LuaVersion::from(&config)?.clone();
65 (
66 version.clone(),
67 std::env::current_dir()?,
68 config.user_tree(version)?,
69 "Welcome to the lux Lua repl.".into(),
70 )
71 }
72 };
73
74 welcome_message = format!(
75 r#"{welcome_message}
76Run `lx lua --help` for options.
77To exit type 'exit()' or <C-d>.
78"#,
79 );
80
81 let lua_cmd = run_lua
82 .lua
83 .map(LuaBinary::Custom)
84 .unwrap_or(LuaBinary::new(lua_version, &config));
85
86 if run_lua.help {
87 return print_lua_help(&lua_cmd).await;
88 }
89
90 if project.is_some() {
91 build::build(run_lua.build_args, config.clone()).await?;
92 }
93
94 let args = &run_lua.args.unwrap_or_default();
95
96 operations::RunLua::new()
97 .root(&root)
98 .tree(&tree)
99 .config(&config)
100 .lua_cmd(lua_cmd)
101 .args(args)
102 .prepend_test_paths(run_lua.test)
103 .prepend_build_paths(run_lua.build)
104 .disable_loader(run_lua.no_loader)
105 .lua_init("exit = os.exit".to_string())
106 .welcome_message(welcome_message)
107 .run_lua()
108 .await?;
109
110 Ok(())
111}
112
113async fn print_lua_help(lua_cmd: &LuaBinary) -> Result<()> {
114 let lua_cmd_path: PathBuf = lua_cmd.clone().try_into()?;
115 let output = match Command::new(lua_cmd_path.to_string_lossy().to_string())
116 .arg("-h")
118 .output()
119 .await
120 {
121 Ok(output) => Ok(output),
122 Err(err) => Err(eyre!("Failed to run {}: {}", lua_cmd, err)),
123 }?;
124 let lua_help = String::from_utf8_lossy(&output.stderr)
125 .lines()
126 .skip(2)
127 .map(|line| format!(" {line}"))
128 .collect_vec()
129 .join("\n");
130 print!(
131 "
132Usage: lx lua -- [LUA_OPTIONS] [SCRIPT [ARGS]]...
133
134Arguments:
135 [LUA_OPTIONS]...
136{lua_help}
137
138Options:
139 --lua Path to the Lua interpreter to use
140 -h, --help Print help
141
142Build options (if running a repl for a project):
143 --test Prepend test dependencies to the LUA_PATH and LUA_CPATH
144 --build Prepend build dependencies to the LUA_PATH and LUA_CPATH
145 --no-lock Ignore the project's lockfile and don't create one
146 --only-deps Build only the dependencies
147",
148 );
149 Ok(())
150}
151
152#[cfg(test)]
153mod test {
154 use std::path::PathBuf;
155
156 use lux_lib::config::ConfigBuilder;
157 use serial_test::serial;
158
159 use super::*;
160
161 #[serial]
162 #[tokio::test]
163 async fn test_run_lua() {
164 let args = RunLua {
165 args: Some(vec!["-v".into()]),
166 ..RunLua::default()
167 };
168 let temp: PathBuf = assert_fs::TempDir::new().unwrap().path().into();
169 let cwd = &std::env::current_dir().unwrap();
170 tokio::fs::create_dir_all(&temp).await.unwrap();
171 std::env::set_current_dir(&temp).unwrap();
172 let config = ConfigBuilder::new()
173 .unwrap()
174 .user_tree(Some(temp.clone()))
175 .build()
176 .unwrap();
177 run_lua(args, config).await.unwrap();
178 std::env::set_current_dir(cwd).unwrap();
179 }
180}