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