1use std::path::PathBuf;
2
3use path_slash::PathExt;
4use tokio::process::Command;
5
6use clap::Args;
7use itertools::Itertools;
8use lux_lib::{
9 config::Config,
10 lua_installation::{LuaBinary, LuaInstallation},
11 lua_version::LuaVersion,
12 operations,
13 path::LuaEnvironment,
14 workspace::Workspace,
15};
16
17use miette::{IntoDiagnostic, Result, WrapErr};
18
19use crate::build::{self, Build};
20
21use lux_lib::build::BuildBehaviour;
22
23#[derive(Args, Default)]
24#[clap(disable_help_flag = true)]
25pub struct RunLua {
26 args: Option<Vec<String>>,
28
29 #[arg(long)]
31 lua: Option<String>,
32
33 #[arg(long)]
35 test: bool,
36
37 #[arg(long)]
39 build: bool,
40
41 #[clap(default_value_t = false)]
45 #[arg(long)]
46 no_loader: bool,
47
48 #[arg(long, conflicts_with = "impure")]
52 pure: bool,
53
54 #[arg(long, conflicts_with = "pure")]
57 impure: bool,
58
59 #[clap(flatten)]
60 build_args: Build,
61
62 #[arg(long)]
64 help: bool,
65}
66
67pub async fn run_lua(run_lua: RunLua, config: Config) -> Result<()> {
68 let workspace = Workspace::current()?;
69 let environment = if run_lua.pure || (workspace.is_some() && !run_lua.impure) {
70 LuaEnvironment::Pure
71 } else {
72 LuaEnvironment::Impure
73 };
74 let (lua_version, root, tree, mut welcome_message) = match &workspace {
75 Some(workspace) => {
76 let package_names = workspace
77 .members()
78 .iter()
79 .map(|project| project.toml().package())
80 .join(",");
81 (
82 workspace.lua_version(&config)?,
83 workspace.root().to_path_buf(),
84 workspace.tree(&config)?,
85 format!("Welcome to the lux Lua repl for {package_names}.",),
86 )
87 }
88 None => {
89 let version = LuaVersion::from(&config)?.clone();
90 (
91 version.clone(),
92 std::env::current_dir().into_diagnostic()?,
93 config.user_tree(version)?,
94 "Welcome to the lux Lua repl.".into(),
95 )
96 }
97 };
98
99 welcome_message = format!(
100 r#"{welcome_message}
101Run `lx lua --help` for options.
102To exit type 'exit()' or <C-d>.
103"#,
104 );
105
106 let lua_cmd = match run_lua.lua.map(LuaBinary::Custom) {
107 Some(lua_cmd) => lua_cmd,
108 None => {
109 let lua_cmd = LuaInstallation::new(&lua_version, &config)
110 .await?
111 .bin()
112 .as_ref()
113 .map(|lua_bin| LuaBinary::Custom(lua_bin.to_slash_lossy().to_string()))
114 .unwrap_or_else(|| LuaBinary::new(lua_version, &config));
115 lua_cmd
116 }
117 };
118
119 if run_lua.help {
120 return print_lua_help(&lua_cmd).await;
121 }
122
123 if workspace.is_some() {
124 build::build_with_behaviour(run_lua.build_args, config.clone(), BuildBehaviour::Ignore)
125 .await?;
126 }
127
128 let args = &run_lua.args.unwrap_or_default();
129
130 operations::RunLua::new()
131 .root(&root)
132 .tree(&tree)
133 .config(&config)
134 .lua_cmd(lua_cmd)
135 .args(args)
136 .prepend_test_paths(run_lua.test)
137 .prepend_build_paths(run_lua.build)
138 .disable_loader(run_lua.no_loader)
139 .environment(environment)
140 .lua_init("exit = os.exit".to_string())
141 .welcome_message(welcome_message)
142 .run_lua()
143 .await?;
144
145 Ok(())
146}
147
148async fn print_lua_help(lua_cmd: &LuaBinary) -> Result<()> {
149 let lua_cmd_path: PathBuf = lua_cmd.clone().try_into()?;
150 let output = Command::new(lua_cmd_path.to_string_lossy().to_string())
151 .arg("-h")
153 .output()
154 .await
155 .into_diagnostic()
156 .wrap_err(format!("Failed to run {lua_cmd}"))?;
157 let lua_help = String::from_utf8_lossy(&output.stderr)
158 .lines()
159 .skip(2)
160 .map(|line| format!(" {line}"))
161 .collect_vec()
162 .join("\n");
163 print!(
164 "
165Usage: lx lua -- [LUA_OPTIONS] [SCRIPT [ARGS]]...
166
167Arguments:
168 [LUA_OPTIONS]...
169{lua_help}
170
171Options:
172 --lua Path to the Lua interpreter to use
173 --pure Only load packages from the current project
174 --impure Also expose user-installed packages and system Lua paths
175 -h, --help Print help
176
177The default environment is pure inside a project and impure outside one.
178
179Build options (if running a repl for a project):
180 --test Prepend test dependencies to the LUA_PATH and LUA_CPATH
181 --build Prepend build dependencies to the LUA_PATH and LUA_CPATH
182 --no-lock Ignore the project's lockfile and don't create one
183 --only-deps Build only the dependencies
184",
185 );
186 Ok(())
187}
188
189#[cfg(test)]
190mod tests {
191 use std::path::PathBuf;
192
193 use lux_lib::config::ConfigBuilder;
194 use serial_test::serial;
195
196 use super::*;
197
198 #[serial]
199 #[tokio::test]
200 async fn test_run_lua() {
201 let args = RunLua {
202 args: Some(vec!["-v".into()]),
203 ..RunLua::default()
204 };
205 let temp: PathBuf = assert_fs::TempDir::new().unwrap().path().into();
206 let data_dir: PathBuf = assert_fs::TempDir::new().unwrap().path().into();
207 let cwd = &std::env::current_dir().unwrap();
208 tokio::fs::create_dir_all(&temp).await.unwrap();
209 std::env::set_current_dir(&temp).unwrap();
210 let config = ConfigBuilder::new()
211 .unwrap()
212 .user_tree(Some(temp.clone()))
213 .data_dir(Some(data_dir))
214 .build()
215 .unwrap();
216 run_lua(args, config).await.unwrap();
217 std::env::set_current_dir(cwd).unwrap();
218 }
219}