Skip to main content

lux_lib/build/
mod.rs

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