Skip to main content

lux_lib/build/
mod.rs

1use crate::build::backend::{BuildBackend, BuildInfo, RunBuildArgs};
2use crate::fs;
3use crate::lockfile::locked_package;
4use crate::lockfile::{self, RemotePackageSourceUrl};
5use crate::operations::{fetch, unpack};
6use crate::project;
7use crate::rockspec::Rockspec;
8use crate::tree::{self, EntryType, InstallTree};
9use bon::Builder;
10use bytes::Bytes;
11use std::collections::HashMap;
12use std::fs::DirEntry;
13use std::path::PathBuf;
14use std::{io, path::Path};
15use tracing::Instrument;
16
17use crate::{config::Config, hash::HasIntegrity, lockfile::LockedPackage, lua, rockspec};
18use external_dependency::ExternalDependencyInfo;
19
20use itertools::Itertools;
21
22use miette::Diagnostic;
23use patch::Patch;
24use ssri::Integrity;
25use thiserror::Error;
26
27pub mod builtin;
28pub mod cmake;
29pub mod command;
30pub mod compile;
31pub mod install;
32pub mod luarocks;
33#[cfg(feature = "luau-transpile")]
34pub mod luau;
35pub mod make;
36pub mod patch;
37pub mod rust_binary;
38pub mod rust_mlua;
39pub mod source;
40pub mod treesitter_parser;
41
42pub(crate) mod backend;
43pub(crate) mod cargo;
44pub(crate) mod dependency;
45pub(crate) use builtin::autodetect_modules;
46
47pub mod external_dependency;
48
49#[derive(Debug)]
50pub(crate) enum RemotePackageSourceSpec {
51    RockSpec(Option<RemotePackageSourceUrl>),
52    SrcRock(SrcRockSource),
53}
54
55/// A packed .src.rock archive.
56#[derive(Debug)]
57pub(crate) struct SrcRockSource {
58    pub bytes: Bytes,
59    pub source_url: RemotePackageSourceUrl,
60}
61
62#[derive(Error, Debug, Diagnostic)]
63#[non_exhaustive]
64pub enum Error {
65    #[error("builtin build failed")]
66    #[diagnostic(forward(0))]
67    Builtin(#[from] builtin::Error),
68    #[error("cmake build failed")]
69    #[diagnostic(forward(0))]
70    CMake(#[from] cmake::Error),
71    #[error("make build failed")]
72    #[diagnostic(forward(0))]
73    Make(#[from] make::Error),
74    #[error("command build failed")]
75    #[diagnostic(forward(0))]
76    Command(#[from] command::Error),
77    #[error("rust-mlua build failed")]
78    #[diagnostic(forward(0))]
79    Rust(#[from] rust_mlua::Error),
80    #[error("rust-binary build failed")]
81    #[diagnostic(forward(0))]
82    RustBinary(#[from] rust_binary::Error),
83    #[error("treesitter-parser build failed")]
84    #[diagnostic(forward(0))]
85    TreesitterBuild(#[from] treesitter_parser::Error),
86    #[error("luarocks build failed")]
87    #[diagnostic(forward(0))]
88    LuarocksBuild(#[from] luarocks::Error),
89    #[error("building from rock source failed")]
90    #[diagnostic(forward(0))]
91    SourceBuild(#[from] Box<source::Error>),
92    #[error("unsupported build backend for luau")]
93    #[diagnostic(help("lux can build luau packages with the following build backends: 'builtin', 'source' & 'none'"))]
94    LuauUnsupportedBuildBackend,
95    #[error("luau does not support native dependencies")]
96    #[diagnostic(help("the luau runtime cannot load C libraries. use pure-Luau packages or Lua"))]
97    LuauNativeDepsUnsupported,
98    #[error("IO operation failed")]
99    Io(#[from] io::Error),
100    #[error(transparent)]
101    #[diagnostic(transparent)]
102    Fs(#[from] fs::Error),
103    #[error(transparent)]
104    #[diagnostic(transparent)]
105    Lockfile(#[from] lockfile::Error),
106    #[error(transparent)]
107    #[diagnostic(transparent)]
108    Tree(#[from] tree::Error),
109
110    #[error(transparent)]
111    #[diagnostic(transparent)]
112    ExternalDependency(#[from] external_dependency::Error),
113    #[error(transparent)]
114    #[diagnostic(transparent)]
115    Patch(#[from] patch::Error),
116    #[error(transparent)]
117    #[diagnostic(transparent)]
118    CompileCFiles(#[from] compile::c_files::Error),
119    #[error(transparent)]
120    #[diagnostic(transparent)]
121    LuaVersion(#[from] rockspec::Error),
122    #[error(
123        r#"source integrity mismatch.
124- source: {src}
125- expected: {expected}
126- got: {actual}"#
127    )]
128    #[diagnostic(help(
129        r#"the source may have been modified or a tag may have been moved.
130check the source, then rerun the command with `--no-lock` to update the hash."#
131    ))]
132    SourceIntegrityMismatch {
133        src: String,
134        expected: Integrity,
135        actual: Integrity,
136    },
137    #[error("failed to unpack src.rock")]
138    #[diagnostic(forward(0))]
139    UnpackSrcRock(#[source] unpack::Error),
140    #[error("failed to fetch rock source")]
141    #[diagnostic(forward(0))]
142    FetchSrc(#[from] fetch::Error),
143    #[error("failed to install binary '{file_name}'")]
144    InstallBinary {
145        file_name: String,
146        #[diagnostic_source]
147        source: install::Error,
148    },
149    #[error(transparent)]
150    #[diagnostic(transparent)]
151    LuaInstallation(#[from] lua::installation::Error),
152}
153
154impl From<source::Error> for Error {
155    fn from(source: source::Error) -> Self {
156        Self::SourceBuild(Box::new(source))
157    }
158}
159
160#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
161pub enum Behaviour {
162    /// If a package with the same version is already installed, do nothing.
163    /// Otherwise, behave like [`Behaviour::Conflict`].
164    Ignore,
165    /// Error if an entrypoint with the same name is already installed, even if
166    /// it is the same version.
167    Conflict,
168    /// Remove any installed entrypoint with the same name and rebuild.
169    Force,
170}
171
172#[tracing::instrument(level = "trace", skip_all)]
173async fn run_build<R: Rockspec + HasIntegrity, T: InstallTree + Sync>(
174    rockspec: &R,
175    args: RunBuildArgs<'_, T>,
176) -> Result<BuildInfo, Error> {
177    if args.tree.version() == &lua::Version::Luau
178        && rockspec
179            .build()
180            .current_platform()
181            .backend
182            .as_ref()
183            .is_some_and(|backend| {
184                !matches!(
185                    backend,
186                    rockspec::build::backend::Spec::Builtin(_)
187                        | rockspec::build::backend::Spec::Source
188                )
189            })
190    {
191        Err(Error::LuauUnsupportedBuildBackend)
192    } else {
193        Ok(
194            match rockspec.build().current_platform().backend.to_owned() {
195                Some(rockspec::build::backend::Spec::Builtin(build_spec)) => {
196                    build_spec.run(args).await?
197                }
198                Some(rockspec::build::backend::Spec::Make(make_spec)) => {
199                    make_spec.run(args).await?
200                }
201                Some(rockspec::build::backend::Spec::CMake(cmake_spec)) => {
202                    cmake_spec.run(args).await?
203                }
204                Some(rockspec::build::backend::Spec::Command(command_spec)) => {
205                    command_spec.run(args).await?
206                }
207                Some(rockspec::build::backend::Spec::RustMlua(rust_mlua_spec)) => {
208                    rust_mlua_spec.run(args).await?
209                }
210                Some(rockspec::build::backend::Spec::RustBinary(rust_binary_spec)) => {
211                    rust_binary_spec.run(args).await?
212                }
213                Some(rockspec::build::backend::Spec::TreesitterParser(treesitter_parser_spec)) => {
214                    treesitter_parser_spec.run(args).await?
215                }
216                Some(rockspec::build::backend::Spec::LuaRock(build_backend_name)) => {
217                    luarocks::build(&build_backend_name, rockspec, args).await?
218                }
219                Some(rockspec::build::backend::Spec::Source) => source::build(args).await?,
220                None => BuildInfo::default(),
221            },
222        )
223    }
224}
225
226#[allow(clippy::too_many_arguments)]
227#[tracing::instrument(level = "trace", skip(rockspec, tree, config))]
228async fn install<R: Rockspec + HasIntegrity, T: InstallTree>(
229    rockspec: &R,
230    tree: &T,
231    package: &locked_package::Spec,
232    lua: &lua::Installation,
233    build_dir: &Path,
234    entry_type: &EntryType,
235    config: &Config,
236) -> Result<(), Error> {
237    let install_spec = &rockspec.build().current_platform().install;
238    let layout = tree.layout_for(package);
239    {
240        let span = tracing::info_span!("Copying Lua modules");
241        let _enter = span.enter();
242        for (target, source) in &install_spec.lua {
243            let _enter = span.enter();
244            let absolute_source = build_dir.join(source);
245            install::lua_module(&absolute_source, target, &layout.src)?;
246        }
247    }
248    {
249        let span = tracing::info_span!("Compiling C libraries");
250        let _enter = span.enter();
251        for (target, source) in &install_spec.lib {
252            let absolute_source = build_dir.join(source);
253            let resolved_target = layout.lib.join(target);
254            // NOTE: Some rockspecs have redundant module definitions,
255            // assuming that the linker outputs them to the build dir root.
256            // See https://github.com/lumen-oss/lux/issues/2101
257            if !resolved_target.exists() {
258                if let Some(parent) = resolved_target.parent() {
259                    fs::tokio::create_dir_all(&parent).await?;
260                }
261                fs::tokio::copy(&absolute_source, &resolved_target)
262                    .instrument(tracing::trace_span!("copying target"))
263                    .await?;
264            }
265            fs::make_writable(&resolved_target).await?;
266        }
267    }
268    if entry_type.is_entrypoint() {
269        let span = tracing::info_span!("Installing binaries");
270        let _enter = span.enter();
271        let deploy_spec = rockspec.deploy().current_platform();
272        for (target, source) in &install_spec.bin {
273            install::binary(
274                &build_dir.join(source),
275                target,
276                tree,
277                lua,
278                deploy_spec,
279                config,
280            )
281            .instrument(tracing::trace_span!("installing binary"))
282            .await
283            .map_err(|err| Error::InstallBinary {
284                file_name: target.clone(),
285                source: err,
286            })?;
287        }
288    }
289    if !install_spec.conf.is_empty() {
290        let span = tracing::info_span!("Copying configuration files");
291        let _enter = span.enter();
292        for (target, source) in &install_spec.conf {
293            let absolute_source = build_dir.join(source);
294            let target = {
295                let joined = layout.conf.join(target);
296                match joined.file_name() {
297                    Some(_) => joined,
298                    None => joined.join(absolute_source.file_name().unwrap_or_default()),
299                }
300            };
301            if let Some(parent_dir) = target.parent() {
302                fs::tokio::create_dir_all(parent_dir)
303                    .instrument(tracing::trace_span!("creating configuration directory"))
304                    .await?;
305            }
306            fs::tokio::copy(&absolute_source, &target)
307                .instrument(tracing::trace_span!("copying configuration file"))
308                .await?;
309            fs::make_writable(&target).await?;
310        }
311    }
312    Ok(())
313}
314
315// TODO(vhyrro): break apart deployment into a separate step (once we implement transactions)
316#[derive(Builder)]
317#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
318pub(crate) struct Deploy<'a, R: Rockspec + HasIntegrity, T: InstallTree + Sync> {
319    #[builder(start_fn)]
320    rockspec: &'a R,
321    #[builder(start_fn)]
322    tree: &'a T,
323    package: LockedPackage,
324    lua: &'a lua::Installation,
325    source_root: &'a Path,
326    entry_type: EntryType,
327    config: &'a Config,
328    behaviour: Behaviour,
329}
330
331impl<R, T, State> DeployBuilder<'_, R, T, State>
332where
333    R: Rockspec + HasIntegrity,
334    T: InstallTree + Sync,
335    State: deploy_builder::State + deploy_builder::IsComplete,
336{
337    pub(crate) async fn deploy(self) -> Result<LockedPackage, Error> {
338        do_deploy(self._build()).await
339    }
340}
341
342#[tracing::instrument(level = "trace", skip_all, fields(package = deploy.rockspec.package().to_string()))]
343async fn do_deploy<R, T>(deploy: Deploy<'_, R, T>) -> Result<LockedPackage, Error>
344where
345    R: Rockspec + HasIntegrity,
346    T: InstallTree + Sync,
347{
348    let Deploy {
349        rockspec,
350        tree,
351        package,
352        lua,
353        source_root,
354        entry_type,
355        config,
356        behaviour,
357    } = deploy;
358
359    if matches!(behaviour, Behaviour::Ignore | Behaviour::Conflict) {
360        if let Some(existing) = tree.lockfile()?.get(&package.id()) {
361            return Ok(existing.clone());
362        }
363    }
364
365    // TODO(vhyrro): When we implement transactionality make this a Drop guard
366    // or something else.
367    tree.prepare(&package.spec)?;
368    let layout = tree.layout_for(&package.spec);
369
370    let rock_source = rockspec.source().current_platform();
371    let build_dir = resolve_source_dir(
372        source_root,
373        rock_source.unpack_dir.as_deref(),
374        &rockspec.build().current_platform().copy_directories,
375    )?;
376
377    Patch::new(&build_dir, &rockspec.build().current_platform().patches).apply()?;
378
379    let external_dependencies = rockspec
380        .external_dependencies()
381        .current_platform()
382        .iter()
383        .map(|(name, dep)| {
384            ExternalDependencyInfo::probe(name, dep, config.external_deps())
385                .map(|info| (name.clone(), info))
386        })
387        .try_collect::<_, HashMap<_, _>, _>()?;
388
389    let format = rockspec.format().clone().unwrap_or(rockspec::Format::_1_0);
390    let dependency_layouts = if format >= rockspec::Format::_3_1 {
391        dependency::Layouts::new(&package.spec, lua, tree, config)?
392    } else {
393        dependency::Layouts::default()
394    };
395
396    let output = run_build(
397        rockspec,
398        RunBuildArgs::new()
399            .package(&package.spec)
400            .no_install(false)
401            .lua(lua)
402            .external_dependencies(&external_dependencies)
403            .deploy(rockspec.deploy().current_platform())
404            .config(config)
405            .tree(tree)
406            .build_dir(&build_dir)
407            .build_dependencies(rockspec.build_dependencies().current_platform())
408            .dependency_layouts(&dependency_layouts)
409            .build(),
410    )
411    .await?;
412
413    let mut binaries = rockspec.binaries();
414    binaries.extend(output.binaries);
415    tree.lockfile()?
416        .write_guard()
417        .set_binaries(&package, binaries);
418
419    install(
420        rockspec,
421        tree,
422        &package.spec,
423        lua,
424        &build_dir,
425        &entry_type,
426        config,
427    )
428    .await?;
429
430    for directory in rockspec
431        .build()
432        .current_platform()
433        .copy_directories
434        .iter()
435        .filter(|dir| {
436            dir.file_name()
437                .is_some_and(|name| name != "doc" && name != "docs")
438        })
439    {
440        project::copy_dir(&build_dir.join(directory), &layout.etc.join(directory)).await?;
441    }
442
443    recursive_copy_doc_dir(&layout.doc, &build_dir).await?;
444
445    if let Ok(rockspec_str) = rockspec.to_lua_remote_rockspec_string() {
446        fs::sync::write(layout.rockspec_path(), rockspec_str)?;
447    }
448
449    tree.finalize(&package, entry_type)?;
450
451    Ok(package)
452}
453
454fn is_source_or_etc_dir(dir: &DirEntry, copy_dirs: &[PathBuf]) -> bool {
455    let dir_name = dir.file_name().to_string_lossy().to_string();
456    matches!(dir_name.as_str(), "lua" | "src")
457        || copy_dirs
458            .iter()
459            .any(|copy_dir_name| copy_dir_name == &PathBuf::from(&dir_name))
460}
461
462/// Resolve the directory containing a rock's sources within an extracted source archive.
463/// When the rockspec has no `source.dir`, fall back to the archive's single top-level directory.
464pub(crate) fn resolve_source_dir(
465    source_root: &Path,
466    unpack_dir: Option<&Path>,
467    copy_dirs: &[PathBuf],
468) -> Result<PathBuf, fs::Error> {
469    if let Some(unpack_dir) = unpack_dir {
470        return Ok(source_root.join(unpack_dir));
471    }
472    // Some older/off-spec rockspecs don't specify a `source.dir`.
473    // After unpacking the archive, if
474    //
475    //   - there exist no Lua or C sources
476    //   - there exists a single subdirectory that is not a source
477    //     or etc directory
478    //
479    // we assume it's the `source.dir`.
480    // Unlike the LuaRocks implementation - which filters when fetching sources -
481    // we only infer `source.dir` if the directory name is not 'src', 'lua'
482    // or one of the `build.copy_directories`.
483    // This allows us to build local projects with only a `src` directory.
484    //
485    // LuaRocks implementation:
486    // https://github.com/luarocks/luarocks/blob/4188fdb235aca66530d274c782374cf6afba09b8/src/luarocks/fetch.tl?plain=1#L526
487    let has_lua_or_c_sources = fs::sync::read_dir(source_root)?
488        .filter_map(Result::ok)
489        .filter(|entry| entry.path().is_file())
490        .any(|entry| {
491            entry.path().extension().is_some_and(|ext| {
492                matches!(
493                    ext.to_string_lossy().to_string().as_str(),
494                    "lua" | "luau" | "c"
495                )
496            })
497        });
498    if has_lua_or_c_sources {
499        return Ok(source_root.to_path_buf());
500    }
501    let dir_entries = fs::sync::read_dir(source_root)?
502        .filter_map(Result::ok)
503        .filter(|entry| entry.path().is_dir())
504        .collect_vec();
505    if dir_entries.len() == 1 && !is_source_or_etc_dir(&dir_entries[0], copy_dirs) {
506        Ok(dir_entries[0].path())
507    } else {
508        Ok(source_root.to_path_buf())
509    }
510}
511
512#[tracing::instrument(level = "trace")]
513async fn recursive_copy_doc_dir(target_doc_dir: &Path, build_dir: &Path) -> Result<(), Error> {
514    let mut doc_dir = build_dir.join("doc");
515    if !doc_dir.exists() {
516        doc_dir = build_dir.join("docs");
517    }
518    project::copy_dir(&doc_dir, target_doc_dir).await?;
519    Ok(())
520}
521
522#[cfg(test)]
523mod tests {
524    use super::*;
525    use crate::package;
526    use crate::remote;
527    use predicates::prelude::*;
528    use std::{
529        io::{Cursor, Write},
530        path::PathBuf,
531    };
532    use zip::write::SimpleFileOptions;
533
534    use assert_fs::{
535        assert::PathAssert,
536        prelude::{PathChild, PathCopy},
537    };
538
539    use is_executable::IsExecutable;
540
541    use crate::pipeline::build_local::Build;
542    use crate::{
543        config,
544        lockfile::{self, OptState, PinnedState},
545        lua,
546        project::Project,
547    };
548    #[cfg(feature = "impure_tests")]
549    use crate::{
550        operations::{self, download},
551        tree::Tree,
552    };
553
554    #[tokio::test]
555    async fn test_builtin_build() {
556        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
557        let project_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
558            .join("resources/test/sample-projects/no-build-spec/");
559        let tree_dir = assert_fs::TempDir::new().unwrap();
560        let config = config::Builder::new()
561            .unwrap()
562            .lua_version(lua_version)
563            .user_tree(Some(tree_dir.to_path_buf()))
564            .build()
565            .unwrap();
566        let build_dir = assert_fs::TempDir::new().unwrap();
567        build_dir.copy_from(&project_root, &["**"]).unwrap();
568        let tree = config
569            .user_tree(config.lua_version().cloned().unwrap())
570            .unwrap();
571        let lua_version = config.lua_version().unwrap_or(&lua::Version::Lua51);
572        let lua = lua::Installation::new(lua_version, &config).await.unwrap();
573        let project = Project::from_exact(&project_root).unwrap().unwrap();
574        let rockspec = project.toml().into_remote(None).unwrap();
575        let package = LockedPackage::from(
576            &package::Spec::new(rockspec.package().clone(), rockspec.version().clone()),
577            lockfile::Constraint::Unconstrained,
578            remote::package::Source::Test,
579            None,
580            locked_package::Hashes {
581                rockspec: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
582                    .parse()
583                    .unwrap(),
584                source: "sha256-uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="
585                    .parse()
586                    .unwrap(),
587            },
588        );
589        tree.prepare(&package.spec).unwrap();
590        let src_dir = tree.layout_for(&package.spec).src;
591        let dependency_layouts = dependency::Layouts::default();
592        run_build(
593            &rockspec,
594            RunBuildArgs::new()
595                .package(&package.spec)
596                .no_install(false)
597                .lua(&lua)
598                .external_dependencies(&HashMap::default())
599                .deploy(rockspec.deploy().current_platform())
600                .config(&config)
601                .tree(&tree)
602                .build_dir(&build_dir)
603                .build_dependencies(rockspec.build_dependencies().current_platform())
604                .dependency_layouts(&dependency_layouts)
605                .build(),
606        )
607        .await
608        .unwrap();
609        let foo_dir = src_dir.join("foo");
610        assert!(foo_dir.is_dir());
611        let foo_init = foo_dir.join("init.lua");
612        assert!(foo_init.is_file());
613        assert!(std::fs::read_to_string(&foo_init)
614            .unwrap()
615            .contains("return true"));
616        let foo_bar_dir = foo_dir.join("bar");
617        assert!(foo_bar_dir.is_dir());
618        let foo_bar_init = foo_bar_dir.join("init.lua");
619        assert!(foo_bar_init.is_file());
620        assert!(std::fs::read_to_string(&foo_bar_init)
621            .unwrap()
622            .contains("return true"));
623        let foo_bar_baz = foo_bar_dir.join("baz.lua");
624        assert!(foo_bar_baz.is_file());
625        assert!(std::fs::read_to_string(&foo_bar_baz)
626            .unwrap()
627            .contains("return true"));
628        let bin_file = tree_dir
629            .child(lua_version.to_string())
630            .child("bin")
631            .child("hello");
632        bin_file.assert(predicate::path::is_file());
633        bin_file.assert(predicate::str::contains("#!/usr/bin/env bash"));
634        bin_file.assert(predicate::str::contains("echo \"Hello\""));
635    }
636
637    #[cfg(unix)]
638    #[tokio::test]
639    async fn test_install_bin_sets_executable_permissions() {
640        let rockspec = rockspec::lua::Remote::new(
641            r#"
642rockspec_format = "3.0"
643package = "test-builtin-bin"
644version = "1.0-1"
645source = { url = "https://github.com/lumen-oss/luarocks-stub" }
646build = {
647    type = "builtin",
648    install = { bin = { mytool = "mytool" } },
649}
650deploy = { wrap_bin_scripts = false }
651"#,
652        )
653        .unwrap();
654        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
655        let tree_dir = assert_fs::TempDir::new().unwrap();
656        let build_dir = assert_fs::TempDir::new().unwrap();
657        let config = config::Builder::new()
658            .unwrap()
659            .lua_version(lua_version)
660            .user_tree(Some(tree_dir.to_path_buf()))
661            .build()
662            .unwrap();
663        let lua = lua::Installation::new_from_config(&config).await.unwrap();
664        let tree = config
665            .user_tree(config.lua_version().cloned().unwrap())
666            .unwrap();
667        let package = locked_package::Spec::new(
668            rockspec.package(),
669            rockspec.version(),
670            lockfile::Constraint::Unconstrained,
671            Vec::new(),
672            Vec::new(),
673            &PinnedState::default(),
674            &OptState::default(),
675        );
676        tree.prepare(&package).unwrap();
677        crate::fs::tokio::write(build_dir.path().join("mytool"), "#!/bin/sh\necho hi\n")
678            .await
679            .unwrap();
680        install(
681            &rockspec,
682            &tree,
683            &package,
684            &lua,
685            build_dir.path(),
686            &EntryType::Entrypoint,
687            &config,
688        )
689        .await
690        .unwrap();
691        assert!(tree.bin().join("mytool").is_executable());
692    }
693
694    #[tokio::test]
695    async fn git_src_rock_with_repo_directory_builds() {
696        let dir = assert_fs::TempDir::new().unwrap();
697        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
698        let config = config::Builder::new()
699            .unwrap()
700            .user_tree(Some(dir.to_path_buf()))
701            .lua_version(lua_version)
702            .build()
703            .unwrap();
704        let lua = lua::Installation::new_from_config(&config).await.unwrap();
705        let tree = config.user_tree(lua.version.clone()).unwrap();
706
707        let rockspec_content = r#"
708package = "git-src-rock"
709version = "1.0.0-1"
710source = { url = "git+https://example.com/example/git-src-rock.git" }
711dependencies = { "lua >= 5.1" }
712build = {
713    type = "builtin",
714    modules = { ["git_src_rock"] = "lua/git_src_rock.lua" },
715}
716"#;
717        let rockspec = rockspec::lua::Remote::new(rockspec_content).unwrap();
718
719        let mut archive = Cursor::new(Vec::new());
720        {
721            let mut zip = zip::ZipWriter::new(&mut archive);
722            zip.start_file(
723                "git-src-rock-1.0.0-1.rockspec",
724                SimpleFileOptions::default(),
725            )
726            .unwrap();
727            zip.write_all(rockspec_content.as_bytes()).unwrap();
728            zip.start_file(
729                "git-src-rock/lua/git_src_rock.lua",
730                SimpleFileOptions::default(),
731            )
732            .unwrap();
733            zip.write_all(b"return {}").unwrap();
734            zip.finish().unwrap();
735        }
736        let bytes = Bytes::from(archive.into_inner());
737
738        let package = Build::new()
739            .rockspec(&rockspec)
740            .lua(&lua)
741            .tree(&tree)
742            .entry_type(EntryType::Entrypoint)
743            .config(&config)
744            .behaviour(Behaviour::Force)
745            .source_spec(RemotePackageSourceSpec::SrcRock(SrcRockSource {
746                bytes,
747                source_url: RemotePackageSourceUrl::Url {
748                    url: "https://example.org/git-src-rock-1.0.0-1.src.rock"
749                        .parse()
750                        .unwrap(),
751                },
752            }))
753            .build()
754            .await
755            .unwrap();
756
757        assert!(tree
758            .layout_for(package.spec())
759            .src
760            .join("git_src_rock.lua")
761            .is_file());
762    }
763
764    #[tokio::test]
765    async fn installed_rockspec_has_remote_source() {
766        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
767            .join("resources/test/sample-projects/no-source/");
768        let project_root = assert_fs::TempDir::new().unwrap();
769        project_root.copy_from(&sample_project, &["**"]).unwrap();
770
771        let source_url = "https://github.com/lumen-oss/luarocks-stub";
772        let lux_toml = project_root.path().join("lux.toml");
773        let content = format!(
774            "{}\n[source]\nurl = \"{source_url}\"\n",
775            std::fs::read_to_string(&lux_toml).unwrap()
776        );
777        std::fs::write(&lux_toml, content).unwrap();
778
779        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
780        let tree_dir = assert_fs::TempDir::new().unwrap();
781        let config = config::Builder::new()
782            .unwrap()
783            .lua_version(lua_version)
784            .user_tree(Some(tree_dir.to_path_buf()))
785            .build()
786            .unwrap();
787        let tree = config
788            .user_tree(config.lua_version().cloned().unwrap())
789            .unwrap();
790        let lua = lua::Installation::new_from_config(&config).await.unwrap();
791
792        let project = Project::from_exact(project_root.path()).unwrap().unwrap();
793        let rockspec = project.build_rockspec().unwrap();
794
795        let package = Build::new()
796            .rockspec(&rockspec)
797            .lua(&lua)
798            .tree(&tree)
799            .entry_type(EntryType::Entrypoint)
800            .config(&config)
801            .behaviour(Behaviour::Force)
802            .build()
803            .await
804            .unwrap();
805
806        let installed =
807            std::fs::read_to_string(tree.layout_for(&package.spec).rockspec_path()).unwrap();
808        let installed = rockspec::lua::Remote::new(&installed).unwrap();
809
810        match &installed.source().current_platform().source_spec {
811            rockspec::source::Spec::Url(url) => assert_eq!(url.as_str(), source_url),
812            other => panic!("expected a URL source, got {other:?}"),
813        }
814    }
815
816    #[tokio::test]
817    async fn test_install_conf_directory_target() {
818        let rockspec = rockspec::lua::Remote::new(
819            r#"
820rockspec_format = "3.0"
821package = "test-install-conf"
822version = "1.0-1"
823source = { url = "https://github.com/lumen-oss/luarocks-stub" }
824build = {
825    type = "builtin",
826    install = {
827        conf = {
828            [".."] = "shell.nix",
829            ["plain.conf"] = "plain.conf",
830        },
831    },
832}
833"#,
834        )
835        .unwrap();
836        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
837        let tree_dir = assert_fs::TempDir::new().unwrap();
838        let build_dir = assert_fs::TempDir::new().unwrap();
839        let config = config::Builder::new()
840            .unwrap()
841            .lua_version(lua_version)
842            .user_tree(Some(tree_dir.to_path_buf()))
843            .build()
844            .unwrap();
845        let lua = lua::Installation::new_from_config(&config).await.unwrap();
846        let tree = config
847            .user_tree(config.lua_version().cloned().unwrap())
848            .unwrap();
849        let package = locked_package::Spec::new(
850            rockspec.package(),
851            rockspec.version(),
852            lockfile::Constraint::Unconstrained,
853            Vec::new(),
854            Vec::new(),
855            &PinnedState::default(),
856            &OptState::default(),
857        );
858        tree.prepare(&package).unwrap();
859        for file in ["shell.nix", "plain.conf"] {
860            crate::fs::tokio::write(build_dir.path().join(file), "return {}")
861                .await
862                .unwrap();
863        }
864        install(
865            &rockspec,
866            &tree,
867            &package,
868            &lua,
869            build_dir.path(),
870            &EntryType::Entrypoint,
871            &config,
872        )
873        .await
874        .unwrap();
875        let layout = tree.layout_for(&package);
876        assert!(layout.etc.join("shell.nix").is_file());
877        assert!(layout.conf.join("plain.conf").is_file());
878    }
879
880    #[cfg(feature = "impure_tests")]
881    const LUATEST_SRC_ROCK: &str = "resources/test/luatest-0.2-1.src.rock";
882    #[cfg(feature = "impure_tests")]
883    const LUATEST_SRC_ROCK_SOURCE_HASH: &str =
884        "sha256-2jS0XOq0iIVhsZJ3BVqXSlKsx2vsqCAaaYyqcBEb7RI=";
885    #[cfg(feature = "impure_tests")]
886    const LUATEST_ROCKSPEC_HASH: &str = "sha256-NljJ20A+VadUyhhBjrRnojeQjSqRpQy7FWcgjUt2Fdc=";
887
888    #[cfg(feature = "impure_tests")]
889    fn luatest_src_rock_bytes() -> Bytes {
890        Bytes::copy_from_slice(
891            &std::fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(LUATEST_SRC_ROCK))
892                .unwrap(),
893        )
894    }
895
896    #[cfg(feature = "impure_tests")]
897    fn luatest_config(dir: &assert_fs::TempDir) -> Config {
898        config::Builder::new()
899            .unwrap()
900            .user_tree(Some(dir.to_path_buf()))
901            .lua_version(Some(lua::Version::Lua51))
902            .build()
903            .unwrap()
904    }
905
906    #[cfg(feature = "impure_tests")]
907    async fn build_luatest(
908        config: &Config,
909        tree: &Tree,
910        entry_type: EntryType,
911        behaviour: Behaviour,
912    ) -> LockedPackage {
913        let bytes = luatest_src_rock_bytes();
914        let rock = download::PackedRockBytes {
915            name: "luatest".into(),
916            version: "0.2-1".parse().unwrap(),
917            bytes: bytes.clone(),
918            file_name: "luatest-0.2-1.src.rock".into(),
919            url: "https://example.org/luatest-0.2-1.src.rock"
920                .parse()
921                .unwrap(),
922        };
923        let rockspec = download::unpack_rockspec(&rock).await.unwrap();
924        let lua = lua::Installation::new_from_config(config).await.unwrap();
925        Build::new()
926            .rockspec(&rockspec)
927            .lua(&lua)
928            .tree(tree)
929            .entry_type(entry_type)
930            .config(config)
931            .behaviour(behaviour)
932            .source_spec(RemotePackageSourceSpec::SrcRock(SrcRockSource {
933                bytes,
934                source_url: RemotePackageSourceUrl::Url {
935                    url: "https://example.org/luatest-0.2-1.src.rock"
936                        .parse()
937                        .unwrap(),
938                },
939            }))
940            .build()
941            .await
942            .unwrap()
943    }
944
945    #[cfg(feature = "impure_tests")]
946    #[tokio::test]
947    async fn luatest_src_rock_produces_expected_hashes() {
948        let dir = assert_fs::TempDir::new().unwrap();
949        let config = luatest_config(&dir);
950        let tree = config.user_tree(lua::Version::Lua51).unwrap();
951
952        let package = build_luatest(&config, &tree, EntryType::Entrypoint, Behaviour::Force).await;
953
954        assert_eq!(
955            package.hashes().source,
956            LUATEST_SRC_ROCK_SOURCE_HASH.parse().unwrap()
957        );
958        assert_eq!(
959            package.hashes().rockspec,
960            LUATEST_ROCKSPEC_HASH.parse().unwrap()
961        );
962        assert_eq!(
963            package.hashes().source,
964            luatest_src_rock_bytes().hash().await.unwrap()
965        );
966        assert!(tree.bin().join("luatest").is_file());
967    }
968
969    #[cfg(feature = "impure_tests")]
970    #[tokio::test]
971    async fn force_build_is_deterministic() {
972        let dir1 = assert_fs::TempDir::new().unwrap();
973        let config1 = luatest_config(&dir1);
974        let tree1 = config1.user_tree(lua::Version::Lua51).unwrap();
975
976        let dir2 = assert_fs::TempDir::new().unwrap();
977        let config2 = luatest_config(&dir2);
978        let tree2 = config2.user_tree(lua::Version::Lua51).unwrap();
979
980        let package1 =
981            build_luatest(&config1, &tree1, EntryType::Entrypoint, Behaviour::Force).await;
982        let package2 =
983            build_luatest(&config2, &tree2, EntryType::Entrypoint, Behaviour::Force).await;
984
985        assert_eq!(package1, package2);
986        assert_eq!(package1.hashes(), package2.hashes());
987    }
988
989    #[cfg(feature = "impure_tests")]
990    #[tokio::test]
991    async fn noforce_skips_rebuild_when_package_is_locked() {
992        let dir = assert_fs::TempDir::new().unwrap();
993        let config = luatest_config(&dir);
994        let tree = config.user_tree(lua::Version::Lua51).unwrap();
995
996        let package = build_luatest(&config, &tree, EntryType::Entrypoint, Behaviour::Force).await;
997        let bin = tree.bin().join("luatest");
998        assert!(bin.is_file());
999
1000        // Simulate a committed install
1001        {
1002            let mut lockfile = tree.lockfile().unwrap().write_guard();
1003            lockfile.add_entrypoint(&package);
1004        }
1005
1006        // Simulate a partially broken install.
1007        std::fs::remove_file(&bin).unwrap();
1008
1009        let skipped = build_luatest(&config, &tree, EntryType::Entrypoint, Behaviour::Ignore).await;
1010        assert_eq!(skipped.id(), package.id());
1011        assert!(!bin.is_file());
1012
1013        build_luatest(&config, &tree, EntryType::Entrypoint, Behaviour::Force).await;
1014        assert!(bin.is_file());
1015    }
1016}