Skip to main content

lux_lib/operations/
run_lua.rs

1//! Run the `lua` binary with some given arguments.
2//!
3//! The interfaces exposed here ensure that the correct version of Lua is being used.
4
5use bon::Builder;
6
7use crate::{config::Config, lua, tree::InstallTree};
8
9use std::{
10    io,
11    path::{Path, PathBuf},
12    process::Stdio,
13};
14
15use miette::Diagnostic;
16use thiserror::Error;
17use tokio::process::Command;
18
19use crate::{
20    path::{self, LuaEnvironment, Paths},
21    tree,
22    tree::Tree,
23};
24
25#[derive(Error, Debug, Diagnostic)]
26pub enum Error {
27    #[error("failed to detect or install the lua runtime")]
28    #[diagnostic(forward(0))]
29    LuaInstallation(#[from] lua::installation::Error),
30    #[error("failed to run {lua_cmd}: {source}")]
31    LuaCommandFailed {
32        lua_cmd: String,
33        #[source]
34        source: io::Error,
35    },
36    #[error("{lua_cmd} exited with non-zero exit code: {}", exit_code.map(|code| code.to_string()).unwrap_or("unknown".into()))]
37    LuaCommandNonZeroExitCode {
38        lua_cmd: String,
39        exit_code: Option<i32>,
40    },
41    #[error(transparent)]
42    #[diagnostic(transparent)]
43    Paths(#[from] path::Error),
44
45    #[error(transparent)]
46    #[diagnostic(transparent)]
47    Tree(#[from] tree::Error),
48}
49
50#[derive(Builder)]
51#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
52pub struct RunLua<'a> {
53    root: &'a Path,
54    tree: &'a Tree,
55    config: &'a Config,
56    lua_cmd: lua::Binary,
57    args: &'a Vec<String>,
58    prepend_test_paths: Option<bool>,
59    prepend_build_paths: Option<bool>,
60    disable_loader: Option<bool>,
61    lua_init: Option<String>,
62    welcome_message: Option<String>,
63    environment: LuaEnvironment,
64}
65
66impl<State> RunLuaBuilder<'_, State>
67where
68    State: run_lua_builder::State + run_lua_builder::IsComplete,
69{
70    pub async fn run_lua(self) -> Result<(), Error> {
71        let args = self._build();
72        let mut paths = Paths::for_environment(args.tree, args.config, args.environment)?;
73
74        if args.prepend_test_paths.unwrap_or(false) {
75            let test_tree_path = args.tree.test_tree(args.config)?;
76
77            let test_path = Paths::new(&test_tree_path)?;
78
79            paths.prepend(&test_path);
80        }
81
82        if args.prepend_build_paths.unwrap_or(false) {
83            let build_tree_path = args.tree.build_tree(args.config)?;
84
85            let build_path = Paths::new(&build_tree_path)?;
86
87            paths.prepend(&build_path);
88        }
89
90        let lua_cmd: PathBuf = args.lua_cmd.try_into()?;
91
92        let loader_init = if args.tree.version().is_luau() || args.disable_loader.unwrap_or(false) {
93            "".to_string()
94        } else {
95            let is_lux_lua_available = detect_lux_lua(&lua_cmd, &paths, args.environment).await;
96            if !is_lux_lua_available && args.tree.version().lux_lib_dir().is_none() {
97                tracing::warn!("lux-lua library not found.\nCannot use the `lux.loader`.\nTo suppress this warning, set the `--no-loader` option.");
98                "".to_string()
99            } else {
100                paths.init()
101            }
102        };
103        let lua_init = format!(
104            r#"print([==[{}]==])
105{}
106{}
107        "#,
108            args.welcome_message.unwrap_or_default(),
109            args.lua_init.unwrap_or_default(),
110            loader_init
111        );
112
113        let status = match Command::new(&lua_cmd)
114            .current_dir(args.root)
115            .args(args.args)
116            .env("PATH", paths.path_prepended().joined())
117            .envs(paths.lua_env_vars(args.environment, &lua_init))
118            .status()
119            .await
120        {
121            Ok(status) => Ok(status),
122            Err(err) => Err(Error::LuaCommandFailed {
123                lua_cmd: lua_cmd.to_string_lossy().to_string(),
124                source: err,
125            }),
126        }?;
127        if status.success() {
128            Ok(())
129        } else {
130            Err(Error::LuaCommandNonZeroExitCode {
131                lua_cmd: lua_cmd.to_string_lossy().to_string(),
132                exit_code: status.code(),
133            })
134        }
135    }
136}
137
138/// Attempts to detect lux-lua by invoking a Lua command
139/// in case it's a Lua wrapper, like the one created
140/// in nixpkgs using `lua.withPackages (ps: [ps.lux-lua])`.
141/// If the command fails for any reason (including not being able to find the 'lux' module),
142/// this function evaluates to `false`.
143async fn detect_lux_lua(lua_cmd: &Path, paths: &Paths, environment: LuaEnvironment) -> bool {
144    detect_lua_module(lua_cmd, "lux", paths, environment).await
145}
146
147async fn detect_lua_module(
148    lua_cmd: &Path,
149    module: &str,
150    paths: &Paths,
151    environment: LuaEnvironment,
152) -> bool {
153    Command::new(lua_cmd)
154        .arg("-e")
155        .arg(format!(
156            "if pcall(require, '{}') then os.exit(0) else os.exit(1) end",
157            module
158        ))
159        .stderr(Stdio::null())
160        .stdout(Stdio::null())
161        .envs(paths.lua_env_vars(environment, ""))
162        .env("PATH", paths.path_prepended().joined())
163        .status()
164        .await
165        .is_ok_and(|status| status.success())
166}
167
168/// Resolves the interpreter binary for the given Lua version.
169///
170/// Falls back to probing, reusing or building a toolchain via
171/// `Installation` when no suitable binary is found on the PATH.
172pub(crate) async fn resolve_runtime(
173    version: &lua::Version,
174    config: &Config,
175) -> Result<PathBuf, Error> {
176    match <lua::Binary as TryInto<PathBuf>>::try_into(lua::Binary::new(version.clone(), config)) {
177        Ok(lua_cmd) => Ok(lua_cmd),
178        Err(err) => {
179            let lua_installation = lua::Installation::new(version, config).await?;
180            lua_installation
181                .bin()
182                .clone()
183                .ok_or(Error::LuaInstallation(err))
184        }
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use std::str::FromStr;
191
192    use super::*;
193    use crate::fs;
194    use crate::path::PackagePath;
195    use assert_fs::prelude::{PathChild, PathCreateDir};
196    use assert_fs::TempDir;
197    use path_slash::PathBufExt;
198    use which::which;
199
200    #[tokio::test]
201    async fn test_detect_lua_module() {
202        let temp_dir = TempDir::new().unwrap();
203        let lua_dir = temp_dir.child("lua");
204        lua_dir.create_dir_all().unwrap();
205        let lux_file = lua_dir.child("lux.lua").to_path_buf();
206        let lux_path_expr = lua_dir.child("?.lua").to_path_buf();
207        fs::tokio::write(&lux_file, "return true").await.unwrap();
208        let package_path =
209            PackagePath::from_str(lux_path_expr.to_slash_lossy().to_string().as_str()).unwrap();
210        let package_cpath = PackagePath::default();
211        let paths = Paths::test(lua::Version::Lua54, package_path, package_cpath);
212        let lua_cmd = which("lua")
213            .ok()
214            .or(which("luajit").ok())
215            .expect("lua not found");
216        let result = detect_lua_module(&lua_cmd, "lux", &paths, LuaEnvironment::Pure).await;
217        assert!(result, "detects module on the LUA_PATH");
218        let result = detect_lua_module(&lua_cmd, "lhflasdlkas", &paths, LuaEnvironment::Pure).await;
219        assert!(!result, "does not detect non-existing module");
220    }
221}