Skip to main content

lux_cli/
run_lua.rs

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