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