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 installed_rockspec_has_remote_source() {
757        let sample_project = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
758            .join("resources/test/sample-projects/no-source/");
759        let project_root = assert_fs::TempDir::new().unwrap();
760        project_root.copy_from(&sample_project, &["**"]).unwrap();
761
762        let source_url = "https://github.com/lumen-oss/luarocks-stub";
763        let lux_toml = project_root.path().join("lux.toml");
764        let content = format!(
765            "{}\n[source]\nurl = \"{source_url}\"\n",
766            std::fs::read_to_string(&lux_toml).unwrap()
767        );
768        std::fs::write(&lux_toml, content).unwrap();
769
770        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
771        let tree_dir = assert_fs::TempDir::new().unwrap();
772        let config = config::Builder::new()
773            .unwrap()
774            .lua_version(lua_version)
775            .user_tree(Some(tree_dir.to_path_buf()))
776            .build()
777            .unwrap();
778        let tree = config
779            .user_tree(config.lua_version().cloned().unwrap())
780            .unwrap();
781        let lua = lua::Installation::new_from_config(&config).await.unwrap();
782
783        let project = Project::from_exact(project_root.path()).unwrap().unwrap();
784        let rockspec = project.build_rockspec().unwrap();
785
786        let package = Build::new()
787            .rockspec(&rockspec)
788            .lua(&lua)
789            .tree(&tree)
790            .entry_type(EntryType::Entrypoint)
791            .config(&config)
792            .behaviour(BuildBehaviour::Force)
793            .build()
794            .await
795            .unwrap();
796
797        let installed =
798            std::fs::read_to_string(tree.layout_for(&package.spec).rockspec_path()).unwrap();
799        let installed = rockspec::lua::Remote::new(&installed).unwrap();
800
801        match &installed.source().current_platform().source_spec {
802            rockspec::source::Spec::Url(url) => assert_eq!(url.as_str(), source_url),
803            other => panic!("expected a URL source, got {other:?}"),
804        }
805    }
806
807    #[tokio::test]
808    async fn test_install_conf_directory_target() {
809        let rockspec = rockspec::lua::Remote::new(
810            r#"
811rockspec_format = "3.0"
812package = "test-install-conf"
813version = "1.0-1"
814source = { url = "https://github.com/lumen-oss/luarocks-stub" }
815build = {
816    type = "builtin",
817    install = {
818        conf = {
819            [".."] = "shell.nix",
820            ["plain.conf"] = "plain.conf",
821        },
822    },
823}
824"#,
825        )
826        .unwrap();
827        let lua_version = lua::detect::installed_version().or(Some(lua::Version::Lua51));
828        let tree_dir = assert_fs::TempDir::new().unwrap();
829        let build_dir = assert_fs::TempDir::new().unwrap();
830        let config = config::Builder::new()
831            .unwrap()
832            .lua_version(lua_version)
833            .user_tree(Some(tree_dir.to_path_buf()))
834            .build()
835            .unwrap();
836        let lua = lua::Installation::new_from_config(&config).await.unwrap();
837        let tree = config
838            .user_tree(config.lua_version().cloned().unwrap())
839            .unwrap();
840        let package = LockedPackageSpec::new(
841            rockspec.package(),
842            rockspec.version(),
843            lockfile::Constraint::Unconstrained,
844            Vec::new(),
845            Vec::new(),
846            &PinnedState::default(),
847            &OptState::default(),
848        );
849        tree.prepare(&package).unwrap();
850        for file in ["shell.nix", "plain.conf"] {
851            crate::fs::tokio::write(build_dir.path().join(file), "return {}")
852                .await
853                .unwrap();
854        }
855        install(
856            &rockspec,
857            &tree,
858            &package,
859            &lua,
860            build_dir.path(),
861            &EntryType::Entrypoint,
862            &config,
863        )
864        .await
865        .unwrap();
866        let layout = tree.layout_for(&package);
867        assert!(layout.etc.join("shell.nix").is_file());
868        assert!(layout.conf.join("plain.conf").is_file());
869    }
870
871    #[cfg(feature = "impure_tests")]
872    const LUATEST_SRC_ROCK: &str = "resources/test/luatest-0.2-1.src.rock";
873    #[cfg(feature = "impure_tests")]
874    const LUATEST_SRC_ROCK_SOURCE_HASH: &str =
875        "sha256-2jS0XOq0iIVhsZJ3BVqXSlKsx2vsqCAaaYyqcBEb7RI=";
876    #[cfg(feature = "impure_tests")]
877    const LUATEST_ROCKSPEC_HASH: &str = "sha256-NljJ20A+VadUyhhBjrRnojeQjSqRpQy7FWcgjUt2Fdc=";
878
879    #[cfg(feature = "impure_tests")]
880    fn luatest_src_rock_bytes() -> Bytes {
881        Bytes::copy_from_slice(
882            &std::fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(LUATEST_SRC_ROCK))
883                .unwrap(),
884        )
885    }
886
887    #[cfg(feature = "impure_tests")]
888    fn luatest_config(dir: &assert_fs::TempDir) -> Config {
889        config::Builder::new()
890            .unwrap()
891            .user_tree(Some(dir.to_path_buf()))
892            .lua_version(Some(lua::Version::Lua51))
893            .build()
894            .unwrap()
895    }
896
897    #[cfg(feature = "impure_tests")]
898    async fn build_luatest(
899        config: &Config,
900        tree: &Tree,
901        entry_type: EntryType,
902        behaviour: BuildBehaviour,
903    ) -> LockedPackage {
904        let bytes = luatest_src_rock_bytes();
905        let rock = download::PackedRockBytes {
906            name: "luatest".into(),
907            version: "0.2-1".parse().unwrap(),
908            bytes: bytes.clone(),
909            file_name: "luatest-0.2-1.src.rock".into(),
910            url: "https://example.org/luatest-0.2-1.src.rock"
911                .parse()
912                .unwrap(),
913        };
914        let rockspec = download::unpack_rockspec(&rock).await.unwrap();
915        let lua = lua::Installation::new_from_config(config).await.unwrap();
916        Build::new()
917            .rockspec(&rockspec)
918            .lua(&lua)
919            .tree(tree)
920            .entry_type(entry_type)
921            .config(config)
922            .behaviour(behaviour)
923            .source_spec(RemotePackageSourceSpec::SrcRock(SrcRockSource {
924                bytes,
925                source_url: RemotePackageSourceUrl::Url {
926                    url: "https://example.org/luatest-0.2-1.src.rock"
927                        .parse()
928                        .unwrap(),
929                },
930            }))
931            .build()
932            .await
933            .unwrap()
934    }
935
936    #[cfg(feature = "impure_tests")]
937    #[tokio::test]
938    async fn luatest_src_rock_produces_expected_hashes() {
939        let dir = assert_fs::TempDir::new().unwrap();
940        let config = luatest_config(&dir);
941        let tree = config.user_tree(lua::Version::Lua51).unwrap();
942
943        let package =
944            build_luatest(&config, &tree, EntryType::Entrypoint, BuildBehaviour::Force).await;
945
946        assert_eq!(
947            package.hashes().source,
948            LUATEST_SRC_ROCK_SOURCE_HASH.parse().unwrap()
949        );
950        assert_eq!(
951            package.hashes().rockspec,
952            LUATEST_ROCKSPEC_HASH.parse().unwrap()
953        );
954        assert_eq!(
955            package.hashes().source,
956            luatest_src_rock_bytes().hash().await.unwrap()
957        );
958        assert!(tree.bin().join("luatest").is_file());
959    }
960
961    #[cfg(feature = "impure_tests")]
962    #[tokio::test]
963    async fn force_build_is_deterministic() {
964        let dir1 = assert_fs::TempDir::new().unwrap();
965        let config1 = luatest_config(&dir1);
966        let tree1 = config1.user_tree(lua::Version::Lua51).unwrap();
967
968        let dir2 = assert_fs::TempDir::new().unwrap();
969        let config2 = luatest_config(&dir2);
970        let tree2 = config2.user_tree(lua::Version::Lua51).unwrap();
971
972        let package1 = build_luatest(
973            &config1,
974            &tree1,
975            EntryType::Entrypoint,
976            BuildBehaviour::Force,
977        )
978        .await;
979        let package2 = build_luatest(
980            &config2,
981            &tree2,
982            EntryType::Entrypoint,
983            BuildBehaviour::Force,
984        )
985        .await;
986
987        assert_eq!(package1, package2);
988        assert_eq!(package1.hashes(), package2.hashes());
989    }
990
991    #[cfg(feature = "impure_tests")]
992    #[tokio::test]
993    async fn noforce_skips_rebuild_when_package_is_locked() {
994        let dir = assert_fs::TempDir::new().unwrap();
995        let config = luatest_config(&dir);
996        let tree = config.user_tree(lua::Version::Lua51).unwrap();
997
998        let package =
999            build_luatest(&config, &tree, EntryType::Entrypoint, BuildBehaviour::Force).await;
1000        let bin = tree.bin().join("luatest");
1001        assert!(bin.is_file());
1002
1003        // Simulate a committed install
1004        {
1005            let mut lockfile = tree.lockfile().unwrap().write_guard();
1006            lockfile.add_entrypoint(&package);
1007        }
1008
1009        // Simulate a partially broken install.
1010        std::fs::remove_file(&bin).unwrap();
1011
1012        let skipped = build_luatest(
1013            &config,
1014            &tree,
1015            EntryType::Entrypoint,
1016            BuildBehaviour::Ignore,
1017        )
1018        .await;
1019        assert_eq!(skipped.id(), package.id());
1020        assert!(!bin.is_file());
1021
1022        build_luatest(&config, &tree, EntryType::Entrypoint, BuildBehaviour::Force).await;
1023        assert!(bin.is_file());
1024    }
1025}