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, 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, Tree},
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> {
66    rockspec: &'a R,
67    tree: &'a Tree,
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, State> BuildBuilder<'_, R, 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, 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>(
172    rockspec: &R,
173    args: RunBuildArgs<'_>,
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>(
197    rockspec: &R,
198    tree: &Tree,
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>(build: Build<'_, R>) -> Result<LocalPackage, BuildError>
274where
275    R: Rockspec + HasIntegrity,
276{
277    let rockspec = build.rockspec;
278
279    build.progress.map(|p| {
280        p.set_message(format!(
281            "🛠️ Building {}@{}...",
282            rockspec.package(),
283            rockspec.version()
284        ))
285    });
286
287    let lua = build.lua;
288
289    rockspec.validate_lua_version(&lua.version)?;
290
291    let tree = build.tree;
292
293    let temp_dir = tempfile::tempdir()?;
294
295    let source_metadata = match build.source_spec {
296        Some(RemotePackageSourceSpec::SrcRock(SrcRockSource { bytes, source_url })) => {
297            let hash = bytes.hash()?;
298            let cursor = Cursor::new(&bytes);
299            operations::unpack_src_rock(cursor, temp_dir.path().to_path_buf(), build.progress)
300                .await
301                .map_err(BuildError::UnpackSrcRock)?;
302            RemotePackageSourceMetadata { hash, source_url }
303        }
304        Some(RemotePackageSourceSpec::RockSpec(source_url)) => {
305            operations::FetchSrc::new(temp_dir.path(), rockspec, build.config, build.progress)
306                .maybe_source_url(source_url)
307                .fetch_internal()
308                .await?
309        }
310        None => {
311            operations::FetchSrc::new(temp_dir.path(), rockspec, build.config, build.progress)
312                .fetch_internal()
313                .await?
314        }
315    };
316
317    let hashes = LocalPackageHashes {
318        rockspec: rockspec.hash()?,
319        source: source_metadata.hash.clone(),
320    };
321
322    let mut package = LocalPackage::from(
323        &PackageSpec::new(rockspec.package().clone(), rockspec.version().clone()),
324        build.constraint,
325        rockspec.binaries(),
326        build
327            .source
328            .map(Result::Ok)
329            .unwrap_or_else(|| {
330                rockspec
331                    .to_lua_remote_rockspec_string()
332                    .map(RemotePackageSource::RockspecContent)
333            })
334            .unwrap_or(RemotePackageSource::Local),
335        Some(source_metadata.source_url.clone()),
336        hashes,
337    );
338    package.spec.pinned = build.pin;
339    package.spec.opt = build.opt;
340
341    match tree.lockfile()?.get(&package.id()) {
342        Some(package) if build.behaviour == BuildBehaviour::NoForce => Ok(package.clone()),
343        _ => {
344            let output_paths = match build.entry_type {
345                tree::EntryType::Entrypoint => tree.entrypoint(&package)?,
346                tree::EntryType::DependencyOnly => tree.dependency(&package)?,
347            };
348
349            let rock_source = rockspec.source().current_platform();
350            let build_dir = match &rock_source.unpack_dir {
351                Some(unpack_dir) => temp_dir.path().join(unpack_dir),
352                None => {
353                    // Some older/off-spec rockspecs don't specify a `source.dir`.
354                    // After unpacking the archive, if
355                    //
356                    //   - there exist no Lua or C sources
357                    //   - there exists a single subdirectory that is not a source
358                    //     or etc directory
359                    //
360                    // we assume it's the `source.dir`.
361                    // Unlike the LuaRocks implementation - which filters when fetching sources -
362                    // we only infer `source.dir` if the directory name is not 'src', 'lua'
363                    // or one of the `build.copy_directories`.
364                    // This allows us to build local projects with only a `src` directory.
365                    //
366                    // LuaRocks implementation:
367                    // https://github.com/luarocks/luarocks/blob/4188fdb235aca66530d274c782374cf6afba09b8/src/luarocks/fetch.tl?plain=1#L526
368                    let has_lua_or_c_sources = std::fs::read_dir(temp_dir.path())?
369                        .filter_map(Result::ok)
370                        .filter(|f| f.path().is_file())
371                        .any(|f| {
372                            f.path().extension().is_some_and(|ext| {
373                                matches!(ext.to_string_lossy().to_string().as_str(), "lua" | "c")
374                            })
375                        });
376                    if has_lua_or_c_sources {
377                        temp_dir.path().into()
378                    } else {
379                        let dir_entries = std::fs::read_dir(temp_dir.path())?
380                            .filter_map(Result::ok)
381                            .filter(|f| f.path().is_dir())
382                            .collect_vec();
383                        if dir_entries.len() == 1
384                            && !is_source_or_etc_dir(
385                                unsafe { dir_entries.first().unwrap_unchecked() },
386                                rockspec,
387                            )
388                        {
389                            unsafe {
390                                temp_dir
391                                    .path()
392                                    .join(dir_entries.first().unwrap_unchecked().path())
393                            }
394                        } else {
395                            temp_dir.path().into()
396                        }
397                    }
398                }
399            };
400
401            Patch::new(
402                &build_dir,
403                &rockspec.build().current_platform().patches,
404                build.progress,
405            )
406            .apply()?;
407
408            let external_dependencies = rockspec
409                .external_dependencies()
410                .current_platform()
411                .iter()
412                .map(|(name, dep)| {
413                    ExternalDependencyInfo::probe(name, dep, build.config.external_deps())
414                        .map(|info| (name.clone(), info))
415                })
416                .try_collect::<_, HashMap<_, _>, _>()?;
417
418            let output = run_build(
419                rockspec,
420                RunBuildArgs::new()
421                    .output_paths(&output_paths)
422                    .no_install(false)
423                    .lua(lua)
424                    .external_dependencies(&external_dependencies)
425                    .deploy(rockspec.deploy().current_platform())
426                    .config(build.config)
427                    .tree(tree)
428                    .build_dir(&build_dir)
429                    .progress(build.progress)
430                    .build(),
431            )
432            .await?;
433
434            package.spec.binaries.extend(output.binaries);
435
436            install(
437                rockspec,
438                tree,
439                &output_paths,
440                lua,
441                &build_dir,
442                &build.entry_type,
443                build.progress,
444                build.config,
445            )
446            .await?;
447
448            for directory in rockspec
449                .build()
450                .current_platform()
451                .copy_directories
452                .iter()
453                .filter(|dir| {
454                    dir.file_name()
455                        .is_some_and(|name| name != "doc" && name != "docs")
456                })
457            {
458                recursive_copy_dir(
459                    &build_dir.join(directory),
460                    &output_paths.etc.join(directory),
461                )
462                .await?;
463            }
464
465            recursive_copy_doc_dir(&output_paths, &build_dir).await?;
466
467            if let Ok(rockspec_str) = rockspec.to_lua_remote_rockspec_string() {
468                std::fs::write(output_paths.rockspec_path(), rockspec_str)?;
469            }
470
471            Ok(package)
472        }
473    }
474}
475
476fn is_source_or_etc_dir<R>(dir: &DirEntry, rockspec: &R) -> bool
477where
478    R: Rockspec + HasIntegrity,
479{
480    let copy_dirs = &rockspec.build().current_platform().copy_directories;
481    let dir_name = dir.file_name().to_string_lossy().to_string();
482    matches!(dir_name.as_str(), "lua" | "src")
483        || copy_dirs
484            .iter()
485            .any(|copy_dir_name| copy_dir_name == &PathBuf::from(&dir_name))
486}
487
488async fn recursive_copy_doc_dir(
489    output_paths: &RockLayout,
490    build_dir: &Path,
491) -> Result<(), BuildError> {
492    let mut doc_dir = build_dir.join("doc");
493    if !doc_dir.exists() {
494        doc_dir = build_dir.join("docs");
495    }
496    recursive_copy_dir(&doc_dir, &output_paths.doc).await?;
497    Ok(())
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503    use predicates::prelude::*;
504    use std::path::PathBuf;
505
506    use assert_fs::{
507        assert::PathAssert,
508        prelude::{PathChild, PathCopy},
509    };
510
511    use crate::{
512        config::ConfigBuilder,
513        lua_installation::{detect_installed_lua_version, LuaInstallation},
514        lua_version::LuaVersion,
515        progress::MultiProgress,
516        project::Project,
517        tree::RockLayout,
518    };
519
520    #[tokio::test]
521    async fn test_builtin_build() {
522        let lua_version = detect_installed_lua_version().or(Some(LuaVersion::Lua51));
523        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
524            .join("resources/test/sample-projects/no-build-spec/");
525        let tree_dir = assert_fs::TempDir::new().unwrap();
526        let config = ConfigBuilder::new()
527            .unwrap()
528            .lua_version(lua_version)
529            .user_tree(Some(tree_dir.to_path_buf()))
530            .build()
531            .unwrap();
532        let build_dir = assert_fs::TempDir::new().unwrap();
533        build_dir.copy_from(&project_root, &["**"]).unwrap();
534        let tree = config
535            .user_tree(config.lua_version().cloned().unwrap())
536            .unwrap();
537        let dest_dir = assert_fs::TempDir::new().unwrap();
538        let rock_layout = RockLayout {
539            rock_path: dest_dir.to_path_buf(),
540            etc: dest_dir.join("etc"),
541            lib: dest_dir.join("lib"),
542            src: dest_dir.join("src"),
543            bin: tree.bin(),
544            conf: dest_dir.join("conf"),
545            doc: dest_dir.join("doc"),
546        };
547        let lua_version = config.lua_version().unwrap_or(&LuaVersion::Lua51);
548        let progress = MultiProgress::new(&config);
549        let bar = progress.map(MultiProgress::new_bar);
550        let lua = LuaInstallation::new(lua_version, &config, &bar)
551            .await
552            .unwrap();
553        let project = Project::from(&project_root).unwrap().unwrap();
554        let rockspec = project.toml().into_remote(None).unwrap();
555        let progress = MultiProgress::new(&config);
556        run_build(
557            &rockspec,
558            RunBuildArgs::new()
559                .output_paths(&rock_layout)
560                .no_install(false)
561                .lua(&lua)
562                .external_dependencies(&HashMap::default())
563                .deploy(rockspec.deploy().current_platform())
564                .config(&config)
565                .tree(&tree)
566                .build_dir(&build_dir)
567                .progress(&progress.map(|p| p.new_bar()))
568                .build(),
569        )
570        .await
571        .unwrap();
572        let foo_dir = dest_dir.child("src").child("foo");
573        foo_dir.assert(predicate::path::is_dir());
574        let foo_init = foo_dir.child("init.lua");
575        foo_init.assert(predicate::path::is_file());
576        foo_init.assert(predicate::str::contains("return true"));
577        let foo_bar_dir = foo_dir.child("bar");
578        foo_bar_dir.assert(predicate::path::is_dir());
579        let foo_bar_init = foo_bar_dir.child("init.lua");
580        foo_bar_init.assert(predicate::path::is_file());
581        foo_bar_init.assert(predicate::str::contains("return true"));
582        let foo_bar_baz = foo_bar_dir.child("baz.lua");
583        foo_bar_baz.assert(predicate::path::is_file());
584        foo_bar_baz.assert(predicate::str::contains("return true"));
585        let bin_file = tree_dir
586            .child(lua_version.to_string())
587            .child("bin")
588            .child("hello");
589        bin_file.assert(predicate::path::is_file());
590        bin_file.assert(predicate::str::contains("#!/usr/bin/env bash"));
591        bin_file.assert(predicate::str::contains("echo \"Hello\""));
592    }
593}