Skip to main content

lux_lib/build/
mod.rs

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