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