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
74pub(crate) fn sources(
75    build_dir: &Path,
76    target_dir: &Path,
77    files: &[PathBuf],
78) -> Result<(), fs::Error> {
79    for file in files {
80        let target = target_dir.join(file.components().skip(1).collect::<PathBuf>());
81        if let Some(parent) = target.parent() {
82            fs::sync::create_dir_all(parent)?;
83        }
84        fs::sync::copy(build_dir.join(file), &target)?;
85        fs::make_writable_sync(&target)?;
86    }
87    Ok(())
88}
89
90/// Returns the file path of the installed binary
91#[tracing::instrument(
92    name = "Installing binary",
93    level = "trace",
94    skip_all,
95    fields(
96        source = source.to_slash_lossy().to_string(),
97        target,
98    ),
99)]
100pub(crate) async fn binary(
101    source: &Path,
102    target: &str,
103    tree: &impl InstallTree,
104    lua: &lua::Installation,
105    deploy: &rockspec::deploy::Spec,
106    config: &Config,
107) -> Result<PathBuf, Error> where
108{
109    fs::tokio::create_dir_all(&tree.bin()).await?;
110    let paths = Paths::new(tree)?;
111    let script = if config.wrap_bin_scripts()
112        && deploy.wrap_bin_scripts
113        && is_compatible_lua_script(source, lua, &paths, config).await
114    {
115        wrapped_binary(source, target, tree, lua, config).await?
116    } else {
117        let target = tree.bin().join(target);
118        fs::tokio::copy(source, &target).await?;
119        target
120    };
121
122    #[cfg(unix)]
123    fs::set_executable_permissions(&script).await?;
124
125    Ok(script)
126}
127
128#[tracing::instrument("Installing wrapped binary", level = "trace", skip(tree))]
129async fn wrapped_binary(
130    source: &Path,
131    target: &str,
132    tree: &impl InstallTree,
133    lua: &lua::Installation,
134    config: &Config,
135) -> Result<PathBuf, Error> {
136    let unwrapped_bin_dir = tree.unwrapped_bin();
137    fs::tokio::create_dir_all(&unwrapped_bin_dir).await?;
138    let unwrapped_bin = unwrapped_bin_dir.join(target);
139    fs::tokio::copy(source, &unwrapped_bin).await?;
140    fs::make_writable(&unwrapped_bin).await?;
141
142    #[cfg(target_family = "unix")]
143    let target = tree.bin().join(target);
144    #[cfg(target_family = "windows")]
145    let target = tree.bin().join(format!("{}.bat", target));
146
147    let lua_bin = lua.lua_binary_or_config_override(config).ok_or({
148        let bin_name = config
149            .variables()
150            .get("LUA")
151            .cloned()
152            .or(lua
153                .bin()
154                .as_ref()
155                .map(|bin| bin.to_slash_lossy().to_string()))
156            .unwrap_or("lua".to_string());
157        Error::NoLuaBinary {
158            help: format!(
159                "make sure {bin_name} (version {}) is on the PATH or has been installed by Lux",
160                lua.version
161            ),
162        }
163    })?;
164
165    #[cfg(target_family = "unix")]
166    let content = format!(
167        r#"#!/bin/sh
168
169exec "{0}" "{1}" "$@"
170"#,
171        lua_bin,
172        unwrapped_bin.display(),
173    );
174    #[cfg(target_family = "windows")]
175    let content = format!(
176        r#"@echo off
177setlocal
178
179{0} "{1}" %*
180
181exit /b %ERRORLEVEL%
182"#,
183        lua_bin,
184        unwrapped_bin.display(),
185    );
186
187    fs::tokio::write(&target, content).await?;
188    Ok(target)
189}
190
191/// Tries to load the file with Lua. If the file can be loaded,
192/// we treat it as a valid Lua script.
193///
194/// NOTE: Lua may successfully load very short bash scripts (like `echo "Hello"`).
195/// But that's unlikely to be the case in practise.
196/// If a script is mistaken for a Lua script, package authors can disable
197/// wrapping with the `deploy.wrap_bin_scripts` rockspec config.
198#[tracing::instrument(level = "trace")]
199async fn is_compatible_lua_script(
200    file: &Path,
201    lua: &lua::Installation,
202    paths: &Paths,
203    config: &Config,
204) -> bool {
205    let lua_path = paths.package_path_prepended().joined();
206    let lua_cpath = paths.package_cpath_prepended().joined();
207    let path = paths.path_prepended().joined();
208    if let Some(lua_bin) = &lua.lua_binary_or_config_override(config) {
209        let lua_bin_path = PathBuf::from(lua_bin);
210        if lua_bin_path.is_file() || which(lua_bin).is_ok() {
211            Command::new(lua_bin)
212                .arg("-e")
213                .arg(format!(
214                    "if loadfile('{}') then os.exit(0) else os.exit(1) end",
215                    // On Windows, Lua escapes path separators, so we ensure forward slashes
216                    file.to_slash_lossy()
217                ))
218                .stderr(Stdio::null())
219                .stdout(Stdio::null())
220                .env("LUA_PATH", lua_path)
221                .env("LUA_CPATH", lua_cpath)
222                .env("PATH", path)
223                .status()
224                .await
225                .is_ok_and(|status| status.success())
226        } else {
227            is_compatible_lua_script_fallback(file, lua, config).await
228        }
229    } else {
230        false
231    }
232}
233
234/// Fallback function for `is_compatible_lua_script`.
235/// Uses the bundled Lua interpreter. This may be less reliable,
236/// as it cannot load scripts for an incompatible Lua version.
237/// But it works for test dependencies like nlua.
238#[tracing::instrument(level = "trace")]
239async fn is_compatible_lua_script_fallback(
240    file: &Path,
241    lua_installation: &lua::Installation,
242    config: &Config,
243) -> bool {
244    if let Ok(file_content) = fs::tokio::read_to_string(&file).await {
245        let file_content_without_comments = file_content
246            .lines()
247            .filter(|line| !line.trim_start().starts_with("#"))
248            .collect_vec()
249            .join("\n");
250        lua_installation
251            .lua_binary_or_config_override(config)
252            .is_some_and(|_| {
253                // Try to compile the content without executing it
254                ottavino::Lua::core()
255                    .try_enter(|ctx| {
256                        ottavino::Closure::load(
257                            ctx,
258                            None,
259                            file_content_without_comments.as_bytes(),
260                        )?;
261                        Ok(())
262                    })
263                    .is_ok()
264            })
265    } else {
266        false
267    }
268}
269
270#[tracing::instrument(level = "trace")]
271pub(crate) fn detect_binaries(build_dir: &Path) -> Vec<PathBuf> {
272    WalkDir::new(build_dir.join("src").join("bin"))
273        .into_iter()
274        .chain(WalkDir::new(build_dir.join("bin")))
275        .filter_map(|file| file.ok())
276        .filter(|file| file.clone().into_path().is_file())
277        .map(DirEntry::into_path)
278        .collect()
279}
280
281#[cfg(test)]
282mod tests {
283    use tokio::process::Command;
284
285    use crate::{config, lua, tree::Tree};
286
287    use super::*;
288
289    #[tokio::test]
290    async fn test_is_compatible_lua_script() {
291        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
292        let config = config::Builder::new()
293            .unwrap()
294            .lua_version(lua_version)
295            .build()
296            .unwrap();
297        let lua_version = config.lua_version().unwrap();
298        let lua = lua::Installation::new(lua_version, &config).await.unwrap();
299        let valid_script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
300            .join("resources/test/sample_lua_bin_script_valid");
301        let temp_dir = assert_fs::TempDir::new().unwrap().to_path_buf();
302        let tree = Tree::new(temp_dir, lua_version.clone(), &config).unwrap();
303        let paths = Paths::new(&tree).unwrap();
304        assert!(is_compatible_lua_script(&valid_script, &lua, &paths, &config).await);
305        let invalid_script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
306            .join("resources/test/sample_lua_bin_script_invalid");
307        assert!(!is_compatible_lua_script(&invalid_script, &lua, &paths, &config).await);
308    }
309
310    #[tokio::test]
311    async fn test_wrapped_binary() {
312        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
313        let temp = assert_fs::TempDir::new().unwrap();
314        let config = config::Builder::new()
315            .unwrap()
316            .lua_version(lua_version)
317            .user_tree(Some(temp.to_path_buf()))
318            .build()
319            .unwrap();
320        let lua_version = config.lua_version().unwrap();
321        let lua = lua::Installation::new(lua_version, &config).await.unwrap();
322        let tree = config.user_tree(lua_version.clone()).unwrap();
323        let valid_script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
324            .join("resources/test/sample_lua_bin_script_valid");
325        let script_name = "test_script";
326        let script_path = wrapped_binary(&valid_script, script_name, &tree, &lua, &config)
327            .await
328            .unwrap();
329
330        #[cfg(unix)]
331        fs::set_executable_permissions(&script_path).await.unwrap();
332
333        assert!(Command::new(script_path.to_string_lossy().to_string())
334            .status()
335            .await
336            .is_ok_and(|status| status.success()));
337    }
338}