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