Skip to main content

lux_lib/pipeline/
build.rs

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