Skip to main content

lux_lib/build/
mod.rs

1use crate::build::backend::{BuildBackend, BuildInfo, RunBuildArgs};
2use crate::lockfile::{LockfileError, OptState, RemotePackageSourceUrl};
3use crate::lua_installation::LuaInstallationError;
4use crate::lua_rockspec::LuaVersionError;
5use crate::operations::{RemotePackageSourceMetadata, UnpackError};
6use crate::rockspec::{LuaVersionCompatibility, Rockspec};
7use crate::tree::{self, EntryType, InstallTree, TreeError};
8use bytes::Bytes;
9use std::collections::HashMap;
10use std::fs::DirEntry;
11use std::io::Cursor;
12use std::path::PathBuf;
13use std::{io, path::Path};
14
15use crate::{
16    config::Config,
17    hash::HasIntegrity,
18    lockfile::{LocalPackage, LocalPackageHashes, LockConstraint, PinnedState},
19    lua_installation::LuaInstallation,
20    lua_rockspec::BuildBackendSpec,
21    operations::{self, FetchSrcError},
22    package::PackageSpec,
23    progress::{Progress, ProgressBar},
24    remote_package_source::RemotePackageSource,
25    tree::RockLayout,
26};
27use bon::Builder;
28use builtin::BuiltinBuildError;
29use cmake::CMakeError;
30use command::CommandError;
31use external_dependency::{ExternalDependencyError, ExternalDependencyInfo};
32
33use indicatif::style::TemplateError;
34use itertools::Itertools;
35use luarocks::LuarocksBuildError;
36use make::MakeError;
37
38use patch::{Patch, PatchError};
39use rust_mlua::RustError;
40use source::SourceBuildError;
41use ssri::Integrity;
42use thiserror::Error;
43use treesitter_parser::TreesitterBuildError;
44use utils::{recursive_copy_dir, CompileCFilesError, InstallBinaryError};
45
46mod builtin;
47mod cmake;
48mod command;
49mod luarocks;
50mod make;
51mod patch;
52mod rust_mlua;
53mod source;
54mod treesitter_parser;
55
56pub(crate) mod backend;
57pub(crate) mod utils;
58
59pub mod external_dependency;
60
61/// A rocks package builder, providing fine-grained control
62/// over how a package should be built.
63#[derive(Builder)]
64#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
65pub struct Build<'a, R: Rockspec + HasIntegrity, T: InstallTree> {
66    rockspec: &'a R,
67    tree: &'a T,
68    entry_type: tree::EntryType,
69    config: &'a Config,
70    progress: &'a Progress<ProgressBar>,
71    lua: &'a LuaInstallation,
72
73    #[builder(default)]
74    pin: PinnedState,
75    #[builder(default)]
76    opt: OptState,
77    #[builder(default)]
78    constraint: LockConstraint,
79    #[builder(default)]
80    behaviour: BuildBehaviour,
81
82    #[builder(setters(vis = "pub(crate)"))]
83    source_spec: Option<RemotePackageSourceSpec>,
84
85    // TODO(vhyrro): Remove this and enforce that this is provided at a type level.
86    #[builder(setters(vis = "pub(crate)"))]
87    source: Option<RemotePackageSource>,
88}
89
90#[derive(Debug)]
91pub(crate) enum RemotePackageSourceSpec {
92    RockSpec(Option<RemotePackageSourceUrl>),
93    SrcRock(SrcRockSource),
94}
95
96/// A packed .src.rock archive.
97#[derive(Debug)]
98pub(crate) struct SrcRockSource {
99    pub bytes: Bytes,
100    pub source_url: RemotePackageSourceUrl,
101}
102
103// Overwrite the `build()` function to use our own instead.
104impl<R: Rockspec + HasIntegrity, T: InstallTree + Sync, State> BuildBuilder<'_, R, T, State>
105where
106    State: build_builder::State + build_builder::IsComplete,
107{
108    pub async fn build(self) -> Result<LocalPackage, BuildError> {
109        do_build(self._build()).await
110    }
111}
112
113#[derive(Error, Debug)]
114pub enum BuildError {
115    #[error("builtin build failed: {0}")]
116    Builtin(#[from] BuiltinBuildError),
117    #[error("cmake build failed: {0}")]
118    CMake(#[from] CMakeError),
119    #[error("make build failed: {0}")]
120    Make(#[from] MakeError),
121    #[error("command build failed: {0}")]
122    Command(#[from] CommandError),
123    #[error("rust-mlua build failed: {0}")]
124    Rust(#[from] RustError),
125    #[error("treesitter-parser build failed: {0}")]
126    TreesitterBuild(#[from] TreesitterBuildError),
127    #[error("luarocks build failed: {0}")]
128    LuarocksBuild(#[from] LuarocksBuildError),
129    #[error("building from rock source failed: {0}")]
130    SourceBuild(#[from] SourceBuildError),
131    #[error("IO operation failed: {0}")]
132    Io(#[from] io::Error),
133    #[error(transparent)]
134    Lockfile(#[from] LockfileError),
135    #[error(transparent)]
136    Tree(#[from] TreeError),
137    #[error("failed to create spinner: {0}")]
138    SpinnerFailure(#[from] TemplateError),
139    #[error(transparent)]
140    ExternalDependencyError(#[from] ExternalDependencyError),
141    #[error(transparent)]
142    PatchError(#[from] PatchError),
143    #[error(transparent)]
144    CompileCFiles(#[from] CompileCFilesError),
145    #[error(transparent)]
146    LuaVersion(#[from] LuaVersionError),
147    #[error("source integrity mismatch.\nExpected: {expected},\nbut got: {actual}")]
148    SourceIntegrityMismatch {
149        expected: Integrity,
150        actual: Integrity,
151    },
152    #[error("failed to unpack src.rock:\n{0}")]
153    UnpackSrcRock(UnpackError),
154    #[error("failed to fetch rock source:\n{0}")]
155    FetchSrcError(#[from] FetchSrcError),
156    #[error("failed to install binary {0}:\n{1}")]
157    InstallBinary(String, InstallBinaryError),
158    #[error(transparent)]
159    LuaInstallation(#[from] LuaInstallationError),
160}
161
162#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
163pub enum BuildBehaviour {
164    /// Don't force a rebuild if the package is already installed
165    #[default]
166    NoForce,
167    /// Force a rebuild if the package is already installed
168    Force,
169}
170
171async fn run_build<R: Rockspec + HasIntegrity, T: InstallTree + Sync>(
172    rockspec: &R,
173    args: RunBuildArgs<'_, T>,
174) -> Result<BuildInfo, BuildError> {
175    let progress = args.progress;
176    progress.map(|p| p.set_message("🛠️ Building..."));
177
178    Ok(
179        match rockspec.build().current_platform().build_backend.to_owned() {
180            Some(BuildBackendSpec::Builtin(build_spec)) => build_spec.run(args).await?,
181            Some(BuildBackendSpec::Make(make_spec)) => make_spec.run(args).await?,
182            Some(BuildBackendSpec::CMake(cmake_spec)) => cmake_spec.run(args).await?,
183            Some(BuildBackendSpec::Command(command_spec)) => command_spec.run(args).await?,
184            Some(BuildBackendSpec::RustMlua(rust_mlua_spec)) => rust_mlua_spec.run(args).await?,
185            Some(BuildBackendSpec::TreesitterParser(treesitter_parser_spec)) => {
186                treesitter_parser_spec.run(args).await?
187            }
188            Some(BuildBackendSpec::LuaRock(_)) => luarocks::build(rockspec, args).await?,
189            Some(BuildBackendSpec::Source) => source::build(args).await?,
190            None => BuildInfo::default(),
191        },
192    )
193}
194
195#[allow(clippy::too_many_arguments)]
196async fn install<R: Rockspec + HasIntegrity, T: InstallTree>(
197    rockspec: &R,
198    tree: &T,
199    output_paths: &RockLayout,
200    lua: &LuaInstallation,
201    build_dir: &Path,
202    entry_type: &EntryType,
203    progress: &Progress<ProgressBar>,
204    config: &Config,
205) -> Result<(), BuildError> {
206    progress.map(|p| {
207        p.set_message(format!(
208            "💻 Installing {} {}",
209            rockspec.package(),
210            rockspec.version()
211        ))
212    });
213
214    let install_spec = &rockspec.build().current_platform().install;
215    let lua_len = install_spec.lua.len();
216    let lib_len = install_spec.lib.len();
217    let bin_len = install_spec.bin.len();
218    let conf_len = install_spec.conf.len();
219    let total_len = lua_len + lib_len + bin_len + conf_len;
220    progress.map(|p| p.set_position(total_len as u64));
221
222    if lua_len > 0 {
223        progress.map(|p| p.set_message("📋 Copying Lua modules..."));
224    }
225    for (target, source) in &install_spec.lua {
226        let absolute_source = build_dir.join(source);
227        utils::copy_lua_to_module_path(&absolute_source, target, &output_paths.src)?;
228        progress.map(|p| p.set_position(p.position() + 1));
229    }
230    if lib_len > 0 {
231        progress.map(|p| p.set_message("📋 Compiling C libraries..."));
232    }
233    for (target, source) in &install_spec.lib {
234        let absolute_source = build_dir.join(source);
235        let resolved_target = output_paths.lib.join(target);
236        tokio::fs::copy(absolute_source, resolved_target).await?;
237        progress.map(|p| p.set_position(p.position() + 1));
238    }
239    if entry_type.is_entrypoint() {
240        if bin_len > 0 {
241            progress.map(|p| p.set_message("💻 Installing binaries..."));
242        }
243        let deploy_spec = rockspec.deploy().current_platform();
244        for (target, source) in &install_spec.bin {
245            utils::install_binary(
246                &build_dir.join(source),
247                target,
248                tree,
249                lua,
250                deploy_spec,
251                config,
252            )
253            .await
254            .map_err(|err| BuildError::InstallBinary(target.clone(), err))?;
255            progress.map(|p| p.set_position(p.position() + 1));
256        }
257    }
258    if conf_len > 0 {
259        progress.map(|p| p.set_message("📋 Copying configuration files..."));
260        for (target, source) in &install_spec.conf {
261            let absolute_source = build_dir.join(source);
262            let target = output_paths.conf.join(target);
263            if let Some(parent_dir) = target.parent() {
264                tokio::fs::create_dir_all(parent_dir).await?;
265            }
266            tokio::fs::copy(absolute_source, target).await?;
267            progress.map(|p| p.set_position(p.position() + 1));
268        }
269    }
270    Ok(())
271}
272
273async fn do_build<R, T>(build: Build<'_, R, T>) -> Result<LocalPackage, BuildError>
274where
275    R: Rockspec + HasIntegrity,
276    T: InstallTree + Sync,
277{
278    let rockspec = build.rockspec;
279
280    build.progress.map(|p| {
281        p.set_message(format!(
282            "🛠️ Building {}@{}...",
283            rockspec.package(),
284            rockspec.version()
285        ))
286    });
287
288    let lua = build.lua;
289
290    rockspec.validate_lua_version(&lua.version)?;
291
292    let tree = build.tree;
293
294    let temp_dir = tempfile::tempdir()?;
295
296    let source_metadata = match build.source_spec {
297        Some(RemotePackageSourceSpec::SrcRock(SrcRockSource { bytes, source_url })) => {
298            let hash = bytes.hash()?;
299            let cursor = Cursor::new(&bytes);
300            operations::unpack_src_rock(cursor, temp_dir.path().to_path_buf(), build.progress)
301                .await
302                .map_err(BuildError::UnpackSrcRock)?;
303            RemotePackageSourceMetadata { hash, source_url }
304        }
305        Some(RemotePackageSourceSpec::RockSpec(source_url)) => {
306            operations::FetchSrc::new(temp_dir.path(), rockspec, build.config, build.progress)
307                .maybe_source_url(source_url)
308                .fetch_internal()
309                .await?
310        }
311        None => {
312            operations::FetchSrc::new(temp_dir.path(), rockspec, build.config, build.progress)
313                .fetch_internal()
314                .await?
315        }
316    };
317
318    let hashes = LocalPackageHashes {
319        rockspec: rockspec.hash()?,
320        source: source_metadata.hash.clone(),
321    };
322
323    let mut package = LocalPackage::from(
324        &PackageSpec::new(rockspec.package().clone(), rockspec.version().clone()),
325        build.constraint,
326        rockspec.binaries(),
327        build
328            .source
329            .map(Result::Ok)
330            .unwrap_or_else(|| {
331                rockspec
332                    .to_lua_remote_rockspec_string()
333                    .map(RemotePackageSource::RockspecContent)
334            })
335            .unwrap_or(RemotePackageSource::Local),
336        Some(source_metadata.source_url.clone()),
337        hashes,
338    );
339    package.spec.pinned = build.pin;
340    package.spec.opt = build.opt;
341
342    match tree.lockfile()?.get(&package.id()) {
343        Some(package) if build.behaviour == BuildBehaviour::NoForce => Ok(package.clone()),
344        _ => {
345            let output_paths = match build.entry_type {
346                tree::EntryType::Entrypoint => tree.entrypoint(&package)?,
347                tree::EntryType::DependencyOnly => tree.dependency(&package)?,
348            };
349
350            let rock_source = rockspec.source().current_platform();
351            let build_dir = match &rock_source.unpack_dir {
352                Some(unpack_dir) => temp_dir.path().join(unpack_dir),
353                None => {
354                    // Some older/off-spec rockspecs don't specify a `source.dir`.
355                    // After unpacking the archive, if
356                    //
357                    //   - there exist no Lua or C sources
358                    //   - there exists a single subdirectory that is not a source
359                    //     or etc directory
360                    //
361                    // we assume it's the `source.dir`.
362                    // Unlike the LuaRocks implementation - which filters when fetching sources -
363                    // we only infer `source.dir` if the directory name is not 'src', 'lua'
364                    // or one of the `build.copy_directories`.
365                    // This allows us to build local projects with only a `src` directory.
366                    //
367                    // LuaRocks implementation:
368                    // https://github.com/luarocks/luarocks/blob/4188fdb235aca66530d274c782374cf6afba09b8/src/luarocks/fetch.tl?plain=1#L526
369                    let has_lua_or_c_sources = std::fs::read_dir(temp_dir.path())?
370                        .filter_map(Result::ok)
371                        .filter(|f| f.path().is_file())
372                        .any(|f| {
373                            f.path().extension().is_some_and(|ext| {
374                                matches!(ext.to_string_lossy().to_string().as_str(), "lua" | "c")
375                            })
376                        });
377                    if has_lua_or_c_sources {
378                        temp_dir.path().into()
379                    } else {
380                        let dir_entries = std::fs::read_dir(temp_dir.path())?
381                            .filter_map(Result::ok)
382                            .filter(|f| f.path().is_dir())
383                            .collect_vec();
384                        if dir_entries.len() == 1
385                            && !is_source_or_etc_dir(
386                                unsafe { dir_entries.first().unwrap_unchecked() },
387                                rockspec,
388                            )
389                        {
390                            unsafe {
391                                temp_dir
392                                    .path()
393                                    .join(dir_entries.first().unwrap_unchecked().path())
394                            }
395                        } else {
396                            temp_dir.path().into()
397                        }
398                    }
399                }
400            };
401
402            Patch::new(
403                &build_dir,
404                &rockspec.build().current_platform().patches,
405                build.progress,
406            )
407            .apply()?;
408
409            let external_dependencies = rockspec
410                .external_dependencies()
411                .current_platform()
412                .iter()
413                .map(|(name, dep)| {
414                    ExternalDependencyInfo::probe(name, dep, build.config.external_deps())
415                        .map(|info| (name.clone(), info))
416                })
417                .try_collect::<_, HashMap<_, _>, _>()?;
418
419            let output = run_build(
420                rockspec,
421                RunBuildArgs::new()
422                    .output_paths(&output_paths)
423                    .no_install(false)
424                    .lua(lua)
425                    .external_dependencies(&external_dependencies)
426                    .deploy(rockspec.deploy().current_platform())
427                    .config(build.config)
428                    .tree(tree)
429                    .build_dir(&build_dir)
430                    .progress(build.progress)
431                    .build(),
432            )
433            .await?;
434
435            package.spec.binaries.extend(output.binaries);
436
437            install(
438                rockspec,
439                tree,
440                &output_paths,
441                lua,
442                &build_dir,
443                &build.entry_type,
444                build.progress,
445                build.config,
446            )
447            .await?;
448
449            for directory in rockspec
450                .build()
451                .current_platform()
452                .copy_directories
453                .iter()
454                .filter(|dir| {
455                    dir.file_name()
456                        .is_some_and(|name| name != "doc" && name != "docs")
457                })
458            {
459                recursive_copy_dir(
460                    &build_dir.join(directory),
461                    &output_paths.etc.join(directory),
462                )
463                .await?;
464            }
465
466            recursive_copy_doc_dir(&output_paths, &build_dir).await?;
467
468            if let Ok(rockspec_str) = rockspec.to_lua_remote_rockspec_string() {
469                std::fs::write(output_paths.rockspec_path(), rockspec_str)?;
470            }
471
472            Ok(package)
473        }
474    }
475}
476
477fn is_source_or_etc_dir<R>(dir: &DirEntry, rockspec: &R) -> bool
478where
479    R: Rockspec + HasIntegrity,
480{
481    let copy_dirs = &rockspec.build().current_platform().copy_directories;
482    let dir_name = dir.file_name().to_string_lossy().to_string();
483    matches!(dir_name.as_str(), "lua" | "src")
484        || copy_dirs
485            .iter()
486            .any(|copy_dir_name| copy_dir_name == &PathBuf::from(&dir_name))
487}
488
489async fn recursive_copy_doc_dir(
490    output_paths: &RockLayout,
491    build_dir: &Path,
492) -> Result<(), BuildError> {
493    let mut doc_dir = build_dir.join("doc");
494    if !doc_dir.exists() {
495        doc_dir = build_dir.join("docs");
496    }
497    recursive_copy_dir(&doc_dir, &output_paths.doc).await?;
498    Ok(())
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504    use predicates::prelude::*;
505    use std::path::PathBuf;
506
507    use assert_fs::{
508        assert::PathAssert,
509        prelude::{PathChild, PathCopy},
510    };
511
512    use crate::{
513        config::ConfigBuilder,
514        lua_installation::{detect_installed_lua_version, LuaInstallation},
515        lua_version::LuaVersion,
516        progress::MultiProgress,
517        project::Project,
518        tree::RockLayout,
519    };
520
521    #[tokio::test]
522    async fn test_builtin_build() {
523        let lua_version = detect_installed_lua_version().or(Some(LuaVersion::Lua51));
524        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
525            .join("resources/test/sample-projects/no-build-spec/");
526        let tree_dir = assert_fs::TempDir::new().unwrap();
527        let config = ConfigBuilder::new()
528            .unwrap()
529            .lua_version(lua_version)
530            .user_tree(Some(tree_dir.to_path_buf()))
531            .build()
532            .unwrap();
533        let build_dir = assert_fs::TempDir::new().unwrap();
534        build_dir.copy_from(&project_root, &["**"]).unwrap();
535        let tree = config
536            .user_tree(config.lua_version().cloned().unwrap())
537            .unwrap();
538        let dest_dir = assert_fs::TempDir::new().unwrap();
539        let rock_layout = RockLayout {
540            rock_path: dest_dir.to_path_buf(),
541            etc: dest_dir.join("etc"),
542            lib: dest_dir.join("lib"),
543            src: dest_dir.join("src"),
544            bin: tree.bin(),
545            conf: dest_dir.join("conf"),
546            doc: dest_dir.join("doc"),
547        };
548        let lua_version = config.lua_version().unwrap_or(&LuaVersion::Lua51);
549        let progress = MultiProgress::new(&config);
550        let bar = progress.map(MultiProgress::new_bar);
551        let lua = LuaInstallation::new(lua_version, &config, &bar)
552            .await
553            .unwrap();
554        let project = Project::from_exact(&project_root).unwrap().unwrap();
555        let rockspec = project.toml().into_remote(None).unwrap();
556        let progress = MultiProgress::new(&config);
557        run_build(
558            &rockspec,
559            RunBuildArgs::new()
560                .output_paths(&rock_layout)
561                .no_install(false)
562                .lua(&lua)
563                .external_dependencies(&HashMap::default())
564                .deploy(rockspec.deploy().current_platform())
565                .config(&config)
566                .tree(&tree)
567                .build_dir(&build_dir)
568                .progress(&progress.map(|p| p.new_bar()))
569                .build(),
570        )
571        .await
572        .unwrap();
573        let foo_dir = dest_dir.child("src").child("foo");
574        foo_dir.assert(predicate::path::is_dir());
575        let foo_init = foo_dir.child("init.lua");
576        foo_init.assert(predicate::path::is_file());
577        foo_init.assert(predicate::str::contains("return true"));
578        let foo_bar_dir = foo_dir.child("bar");
579        foo_bar_dir.assert(predicate::path::is_dir());
580        let foo_bar_init = foo_bar_dir.child("init.lua");
581        foo_bar_init.assert(predicate::path::is_file());
582        foo_bar_init.assert(predicate::str::contains("return true"));
583        let foo_bar_baz = foo_bar_dir.child("baz.lua");
584        foo_bar_baz.assert(predicate::path::is_file());
585        foo_bar_baz.assert(predicate::str::contains("return true"));
586        let bin_file = tree_dir
587            .child(lua_version.to_string())
588            .child("bin")
589            .child("hello");
590        bin_file.assert(predicate::path::is_file());
591        bin_file.assert(predicate::str::contains("#!/usr/bin/env bash"));
592        bin_file.assert(predicate::str::contains("echo \"Hello\""));
593    }
594}