Skip to main content

lux_lib/build/
install.rs

1use std::{
2    path::{Path, PathBuf},
3    process::Stdio,
4    string::FromUtf8Error,
5};
6
7use itertools::Itertools;
8use miette::Diagnostic;
9use path_slash::PathExt;
10use thiserror::Error;
11use tokio::process::Command;
12use walkdir::{DirEntry, WalkDir};
13use which::which;
14
15use crate::{
16    config::Config,
17    fs, lua,
18    path::{self, Paths},
19    rockspec,
20    tree::InstallTree,
21};
22
23#[derive(Debug, Error, Diagnostic)]
24pub enum Error {
25    #[error(transparent)]
26    #[diagnostic(transparent)]
27    Fs(#[from] fs::Error),
28    #[error(transparent)]
29    #[diagnostic(transparent)]
30    Paths(#[from] path::Error),
31    #[error(transparent)]
32    Utf8(#[from] FromUtf8Error),
33    #[error("no Lua executable found")]
34    NoLuaBinary {
35        #[help]
36        help: String,
37    },
38}
39
40/// Copies a lua source file to a specific destination. The destination is described by a
41/// `module.path` syntax (equivalent to the syntax provided to Lua's `require()` function).
42#[tracing::instrument(
43    name = "Copying Lua module",
44    level = "trace",
45    skip_all,
46    fields(
47        source = source.to_slash_lossy().to_string(),
48        target = target_module.to_string(),
49        target_dir = target_dir.to_slash_lossy().to_string(),
50    ),
51)]
52pub(crate) fn lua_module(
53    source: &PathBuf,
54    target_module: &rockspec::build::backend::Module,
55    target_dir: &Path,
56) -> Result<(), fs::Error> {
57    // Some rockspecs abuse `install.lua` to install non-lua files, such as teal (`.tl`) files.
58    let target_module_path = source
59        .extension()
60        .map(|ext| target_module.to_file_path(&format!(".{}", ext.to_string_lossy().as_ref())))
61        .unwrap_or_else(|| target_module.to_lua_path());
62    let target = target_dir.join(target_module_path);
63
64    if let Some(parent) = target.parent() {
65        fs::sync::create_dir_all(parent)?;
66    }
67
68    fs::sync::copy(source, &target)?;
69    fs::make_writable_sync(&target)?;
70
71    Ok(())
72}
73
74/// Returns the file path of the installed binary
75#[tracing::instrument(
76    name = "Installing binary",
77    level = "trace",
78    skip_all,
79    fields(
80        source = source.to_slash_lossy().to_string(),
81        target,
82    ),
83)]
84pub(crate) async fn binary(
85    source: &Path,
86    target: &str,
87    tree: &impl InstallTree,
88    lua: &lua::Installation,
89    deploy: &rockspec::deploy::Spec,
90    config: &Config,
91) -> Result<PathBuf, Error> where
92{
93    fs::tokio::create_dir_all(&tree.bin()).await?;
94    let paths = Paths::new(tree)?;
95    let script = if config.wrap_bin_scripts()
96        && deploy.wrap_bin_scripts
97        && is_compatible_lua_script(source, lua, &paths, config).await
98    {
99        wrapped_binary(source, target, tree, lua, config).await?
100    } else {
101        let target = tree.bin().join(target);
102        fs::tokio::copy(source, &target).await?;
103        target
104    };
105
106    #[cfg(unix)]
107    fs::set_executable_permissions(&script).await?;
108
109    Ok(script)
110}
111
112#[tracing::instrument("Installing wrapped binary", level = "trace", skip(tree))]
113async fn wrapped_binary(
114    source: &Path,
115    target: &str,
116    tree: &impl InstallTree,
117    lua: &lua::Installation,
118    config: &Config,
119) -> Result<PathBuf, Error> {
120    let unwrapped_bin_dir = tree.unwrapped_bin();
121    fs::tokio::create_dir_all(&unwrapped_bin_dir).await?;
122    let unwrapped_bin = unwrapped_bin_dir.join(target);
123    fs::tokio::copy(source, &unwrapped_bin).await?;
124    fs::make_writable(&unwrapped_bin).await?;
125
126    #[cfg(target_family = "unix")]
127    let target = tree.bin().join(target);
128    #[cfg(target_family = "windows")]
129    let target = tree.bin().join(format!("{}.bat", target));
130
131    let lua_bin = lua.lua_binary_or_config_override(config).ok_or({
132        let bin_name = config
133            .variables()
134            .get("LUA")
135            .cloned()
136            .or(lua
137                .bin()
138                .as_ref()
139                .map(|bin| bin.to_slash_lossy().to_string()))
140            .unwrap_or("lua".to_string());
141        Error::NoLuaBinary {
142            help: format!(
143                "make sure {bin_name} (version {}) is on the PATH or has been installed by Lux",
144                lua.version
145            ),
146        }
147    })?;
148
149    #[cfg(target_family = "unix")]
150    let content = format!(
151        r#"#!/bin/sh
152
153exec "{0}" "{1}" "$@"
154"#,
155        lua_bin,
156        unwrapped_bin.display(),
157    );
158    #[cfg(target_family = "windows")]
159    let content = format!(
160        r#"@echo off
161setlocal
162
163{0} "{1}" %*
164
165exit /b %ERRORLEVEL%
166"#,
167        lua_bin,
168        unwrapped_bin.display(),
169    );
170
171    fs::tokio::write(&target, content).await?;
172    Ok(target)
173}
174
175/// Tries to load the file with Lua. If the file can be loaded,
176/// we treat it as a valid Lua script.
177///
178/// NOTE: Lua may successfully load very short bash scripts (like `echo "Hello"`).
179/// But that's unlikely to be the case in practise.
180/// If a script is mistaken for a Lua script, package authors can disable
181/// wrapping with the `deploy.wrap_bin_scripts` rockspec config.
182#[tracing::instrument(level = "trace")]
183async fn is_compatible_lua_script(
184    file: &Path,
185    lua: &lua::Installation,
186    paths: &Paths,
187    config: &Config,
188) -> bool {
189    let lua_path = paths.package_path_prepended().joined();
190    let lua_cpath = paths.package_cpath_prepended().joined();
191    let path = paths.path_prepended().joined();
192    if let Some(lua_bin) = &lua.lua_binary_or_config_override(config) {
193        let lua_bin_path = PathBuf::from(lua_bin);
194        if lua_bin_path.is_file() || which(lua_bin).is_ok() {
195            Command::new(lua_bin)
196                .arg("-e")
197                .arg(format!(
198                    "if loadfile('{}') then os.exit(0) else os.exit(1) end",
199                    // On Windows, Lua escapes path separators, so we ensure forward slashes
200                    file.to_slash_lossy()
201                ))
202                .stderr(Stdio::null())
203                .stdout(Stdio::null())
204                .env("LUA_PATH", lua_path)
205                .env("LUA_CPATH", lua_cpath)
206                .env("PATH", path)
207                .status()
208                .await
209                .is_ok_and(|status| status.success())
210        } else {
211            is_compatible_lua_script_fallback(file, lua, config).await
212        }
213    } else {
214        false
215    }
216}
217
218/// Fallback function for `is_compatible_lua_script`.
219/// Uses the bundled Lua interpreter. This may be less reliable,
220/// as it cannot load scripts for an incompatible Lua version.
221/// But it works for test dependencies like nlua.
222#[tracing::instrument(level = "trace")]
223async fn is_compatible_lua_script_fallback(
224    file: &Path,
225    lua_installation: &lua::Installation,
226    config: &Config,
227) -> bool {
228    if let Ok(file_content) = fs::tokio::read_to_string(&file).await {
229        let file_content_without_comments = file_content
230            .lines()
231            .filter(|line| !line.trim_start().starts_with("#"))
232            .collect_vec()
233            .join("\n");
234        lua_installation
235            .lua_binary_or_config_override(config)
236            .is_some_and(|_| {
237                // Try to compile the content without executing it
238                ottavino::Lua::core()
239                    .try_enter(|ctx| {
240                        ottavino::Closure::load(
241                            ctx,
242                            None,
243                            file_content_without_comments.as_bytes(),
244                        )?;
245                        Ok(())
246                    })
247                    .is_ok()
248            })
249    } else {
250        false
251    }
252}
253
254#[tracing::instrument(level = "trace")]
255pub(crate) fn detect_binaries(build_dir: &Path) -> Vec<PathBuf> {
256    WalkDir::new(build_dir.join("src").join("bin"))
257        .into_iter()
258        .chain(WalkDir::new(build_dir.join("bin")))
259        .filter_map(|file| file.ok())
260        .filter(|file| file.clone().into_path().is_file())
261        .map(DirEntry::into_path)
262        .collect()
263}
264
265#[cfg(test)]
266mod tests {
267    use tokio::process::Command;
268
269    use crate::{config, lua, tree::Tree};
270
271    use super::*;
272
273    #[tokio::test]
274    async fn test_is_compatible_lua_script() {
275        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
276        let config = config::Builder::new()
277            .unwrap()
278            .lua_version(lua_version)
279            .build()
280            .unwrap();
281        let lua_version = config.lua_version().unwrap();
282        let lua = lua::Installation::new(lua_version, &config).await.unwrap();
283        let valid_script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
284            .join("resources/test/sample_lua_bin_script_valid");
285        let temp_dir = assert_fs::TempDir::new().unwrap().to_path_buf();
286        let tree = Tree::new(temp_dir, lua_version.clone(), &config).unwrap();
287        let paths = Paths::new(&tree).unwrap();
288        assert!(is_compatible_lua_script(&valid_script, &lua, &paths, &config).await);
289        let invalid_script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
290            .join("resources/test/sample_lua_bin_script_invalid");
291        assert!(!is_compatible_lua_script(&invalid_script, &lua, &paths, &config).await);
292    }
293
294    #[tokio::test]
295    async fn test_wrapped_binary() {
296        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
297        let temp = assert_fs::TempDir::new().unwrap();
298        let config = config::Builder::new()
299            .unwrap()
300            .lua_version(lua_version)
301            .user_tree(Some(temp.to_path_buf()))
302            .build()
303            .unwrap();
304        let lua_version = config.lua_version().unwrap();
305        let lua = lua::Installation::new(lua_version, &config).await.unwrap();
306        let tree = config.user_tree(lua_version.clone()).unwrap();
307        let valid_script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
308            .join("resources/test/sample_lua_bin_script_valid");
309        let script_name = "test_script";
310        let script_path = wrapped_binary(&valid_script, script_name, &tree, &lua, &config)
311            .await
312            .unwrap();
313
314        #[cfg(unix)]
315        fs::set_executable_permissions(&script_path).await.unwrap();
316
317        assert!(Command::new(script_path.to_string_lossy().to_string())
318            .status()
319            .await
320            .is_ok_and(|status| status.success()));
321    }
322}