Skip to main content

lux_lib/pipeline/
build.rs

1use crate::lockfile::locked_package;
2use std::collections::{HashMap, HashSet};
3
4use bon::Builder;
5use miette::Diagnostic;
6use thiserror::Error;
7
8use crate::rockspec;
9use crate::{
10    build::Deploy,
11    config::Config,
12    lockfile::LockedPackage,
13    lua,
14    luarocks::{
15        self,
16        install_binary_rock::{self, BinaryRockInstall},
17    },
18    rockspec::Rockspec,
19    tree::{self, InstallTree},
20};
21
22use super::materialise::{MaterialisedPackage, PackageSource};
23
24#[derive(Error, Debug, Diagnostic)]
25#[non_exhaustive]
26pub enum Error {
27    #[error("failed to build '{0}'")]
28    Build(String, #[source] Box<crate::build::Error>),
29    #[error(transparent)]
30    #[diagnostic(transparent)]
31    Tree(#[from] tree::Error),
32    #[error("failed to install pre-built rock '{0}'")]
33    InstallBinaryRock(String, #[source] Box<install_binary_rock::Error>),
34    #[error(transparent)]
35    #[diagnostic(transparent)]
36    LuaInstallation(#[from] lua::installation::Error),
37    #[error("error preparing the LuaRocks compatibility layer")]
38    #[diagnostic(forward(0))]
39    LuaRocks(#[from] Box<luarocks::installation::Error>),
40}
41
42impl From<luarocks::installation::Error> for Error {
43    fn from(source: luarocks::installation::Error) -> Self {
44        Self::LuaRocks(Box::new(source))
45    }
46}
47
48/// A rocks package builder, providing fine-grained control
49/// over how a package should be built.
50#[derive(Builder)]
51#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
52pub(crate) struct Build<'a, T: InstallTree + Send + Sync> {
53    #[builder(start_fn)]
54    pub(crate) config: &'a Config,
55    #[builder(start_fn)]
56    pub(crate) tree: &'a T,
57    #[builder(field)]
58    pub(crate) packages: Vec<MaterialisedPackage>,
59}
60
61impl<T, State> BuildBuilder<'_, T, State>
62where
63    T: InstallTree + Send + Sync,
64    State: build_builder::State,
65{
66    pub(crate) fn packages(mut self, packages: Vec<MaterialisedPackage>) -> Self {
67        self.packages = packages;
68        self
69    }
70}
71
72impl<T, State> BuildBuilder<'_, T, State>
73where
74    T: InstallTree + Send + Sync,
75    State: build_builder::State + build_builder::IsComplete,
76{
77    pub(crate) async fn build(self) -> Result<Vec<LockedPackage>, Error> {
78        let args = self._build();
79        let lua = lua::Installation::new_from_config(args.config).await?;
80
81        let needs_luarocks = args.packages.iter().any(|package| {
82            matches!(
83                package.rockspec.build().current_platform().backend,
84                Some(rockspec::build::backend::Spec::LuaRock(_))
85            )
86        });
87        if needs_luarocks {
88            luarocks::Installation::new(args.config, args.tree.build_tree(args.config)?)?
89                .ensure_installed(&lua)
90                .await?;
91        }
92
93        let mut installed = Vec::new();
94
95        for downloaded in order_by_build_dependencies(args.packages) {
96            let MaterialisedPackage {
97                package,
98                rockspec,
99                entry_type,
100                build_behaviour: package_behaviour,
101                artifact,
102                temp_dir: _temp_dir,
103            } = downloaded;
104
105            let is_entrypoint = entry_type.is_entrypoint();
106
107            let pkg = match artifact {
108                PackageSource::SourceDir(path) => Deploy::new(&rockspec, args.tree)
109                    .package(package)
110                    .lua(&lua)
111                    .source_root(&path)
112                    .entry_type(entry_type)
113                    .config(args.config)
114                    .behaviour(package_behaviour)
115                    .deploy()
116                    .await
117                    .map_err(|err| {
118                        Error::Build(
119                            format!("{}-{}", rockspec.package(), rockspec.version()),
120                            Box::new(err),
121                        )
122                    })?,
123                PackageSource::Archive(bytes) => BinaryRockInstall::new(
124                    &rockspec,
125                    package.spec().clone(),
126                    bytes,
127                    package.source().clone(),
128                    entry_type,
129                    args.config,
130                    args.tree,
131                )
132                .behaviour(package_behaviour)
133                .install()
134                .await
135                .map_err(|err| {
136                    Error::InstallBinaryRock(rockspec.package().to_string(), Box::new(err))
137                })?,
138            };
139
140            // Record the installed package in the tree lockfile so that its paths are visible to
141            // the packages built after it (e.g. LuaRocks build backends), as well as future builds.
142            {
143                let mut lockfile = args.tree.lockfile()?.write_guard();
144                if is_entrypoint {
145                    lockfile.add_entrypoint(&pkg);
146                } else {
147                    lockfile.add(&pkg);
148                }
149            }
150
151            installed.push(pkg);
152        }
153
154        Ok(installed)
155    }
156}
157
158fn order_by_build_dependencies(packages: Vec<MaterialisedPackage>) -> Vec<MaterialisedPackage> {
159    fn visit(
160        id: locked_package::ID,
161        by_id: &mut HashMap<locked_package::ID, MaterialisedPackage>,
162        visited: &mut HashSet<locked_package::ID>,
163        ordered: &mut Vec<MaterialisedPackage>,
164    ) {
165        if !visited.insert(id.clone()) {
166            return;
167        }
168
169        let build_dependencies: Vec<locked_package::ID> = by_id
170            .get(&id)
171            .map(|package| {
172                package
173                    .package
174                    .spec
175                    .build_dependencies()
176                    .into_iter()
177                    .cloned()
178                    .collect()
179            })
180            .unwrap_or_default();
181
182        for dependency in build_dependencies {
183            visit(dependency, by_id, visited, ordered);
184        }
185
186        if let Some(package) = by_id.remove(&id) {
187            ordered.push(package);
188        }
189    }
190
191    let mut by_id: HashMap<locked_package::ID, MaterialisedPackage> = packages
192        .into_iter()
193        .map(|package| (package.package.id(), package))
194        .collect();
195
196    let mut ordered = Vec::new();
197    let mut visited = HashSet::new();
198
199    let ids: Vec<locked_package::ID> = by_id.keys().cloned().collect();
200    for id in ids {
201        visit(id, &mut by_id, &mut visited, &mut ordered);
202    }
203
204    ordered
205}