Skip to main content

lux_lib/pipeline/
materialise.rs

1use crate::remote;
2use std::collections::HashMap;
3use std::io;
4use std::io::Cursor;
5use std::path::{Path, PathBuf};
6
7use bon::Builder;
8use bytes::Bytes;
9use futures::{StreamExt, TryStreamExt};
10use miette::Diagnostic;
11use tempfile::TempDir;
12use thiserror::Error;
13
14use crate::rockspec;
15use crate::{
16    build::{self, RemotePackageSourceSpec, SrcRockSource},
17    config::Config,
18    fs,
19    hash::HasIntegrity,
20    lockfile::{
21        LockedPackage, LockedPackageHashes, LockedPackageId, LockedPackageSpec,
22        RemotePackageSourceUrl,
23    },
24    operations::{self, fetch, unpack},
25    rockspec::Rockspec,
26    tree::EntryType,
27};
28
29use super::{
30    resolve::{ResolvedArtifacts, ResolvedPackage},
31    Artifacts,
32};
33
34#[derive(Clone, Debug)]
35pub(crate) enum PackageSource {
36    SourceDir(PathBuf),
37    Archive(Bytes),
38}
39
40pub(crate) struct MaterialisedPackage {
41    pub(crate) package: LockedPackage,
42    pub(crate) rockspec: rockspec::lua::Remote,
43    pub(crate) entry_type: EntryType,
44    pub(crate) build_behaviour: crate::build::BuildBehaviour,
45    pub(crate) artifact: PackageSource,
46    pub(crate) temp_dir: Option<TempDir>,
47}
48
49pub(crate) type MaterialiseArtifacts = Artifacts<HashMap<LockedPackageId, MaterialisedPackage>>;
50
51#[derive(Error, Debug, Diagnostic)]
52#[non_exhaustive]
53pub enum Error {
54    #[error(transparent)]
55    #[diagnostic(transparent)]
56    Fs(#[from] fs::Error),
57    #[error(transparent)]
58    #[diagnostic(transparent)]
59    Build(#[from] Box<build::Error>),
60    #[error("failed to hash the source for '{0}'")]
61    Hash(String, #[source] io::Error),
62    #[error("missing source url for '{0}'")]
63    MissingSourceUrl(String),
64}
65
66impl From<build::Error> for Error {
67    fn from(source: build::Error) -> Self {
68        Self::Build(Box::new(source))
69    }
70}
71
72#[derive(Builder)]
73#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
74pub(crate) struct Materialise<'a> {
75    #[builder(start_fn)]
76    pub(crate) config: &'a Config,
77    pub(crate) resolved: ResolvedArtifacts,
78}
79
80impl<State> MaterialiseBuilder<'_, State>
81where
82    State: materialise_builder::State + materialise_builder::IsComplete,
83{
84    pub(crate) async fn materialise(self) -> Result<MaterialiseArtifacts, Error> {
85        let args = self._build();
86        let config = args.config;
87
88        let artifacts: MaterialiseArtifacts = args
89            .resolved
90            .iter()
91            .map(|(section, packages)| (section, packages.map(|_| HashMap::new())))
92            .collect();
93
94        let jobs = args.resolved.into_iter().flat_map(|(section, packages)| {
95            packages
96                .into_iter()
97                .flatten()
98                .map(move |(id, package)| (section, id, package))
99        });
100
101        futures::stream::iter(jobs)
102            .map(|(section, id, package)| async move {
103                materialise(config, package)
104                    .await
105                    .map(|package| (section, id, package))
106            })
107            .buffered(config.max_jobs())
108            .try_fold(
109                artifacts,
110                |mut artifacts, (section, id, package)| async move {
111                    artifacts
112                        .get_mut(section)
113                        .get_or_insert_with(HashMap::new)
114                        .insert(id, package);
115                    Ok(artifacts)
116                },
117            )
118            .await
119    }
120}
121
122async fn materialise(
123    config: &Config,
124    resolved: ResolvedPackage,
125) -> Result<MaterialisedPackage, Error> {
126    let ResolvedPackage {
127        spec,
128        rockspec,
129        source,
130        source_url,
131        entry_type,
132        build_behaviour,
133        artifact,
134    } = resolved;
135
136    let name = spec.name().to_string();
137
138    let (package, artifact, temp_dir) = match artifact {
139        Some(PackageSource::Archive(bytes)) => match &source {
140            remote::package::Source::LuarocksBinaryRock(url) => {
141                let binary_url = url.clone();
142                let rockspec_hash = rockspec
143                    .hash()
144                    .await
145                    .map_err(|err| Error::Hash(name.clone(), err))?;
146                let source_hash = bytes
147                    .hash()
148                    .await
149                    .map_err(|err| Error::Hash(name.clone(), err))?;
150                let hashes = LockedPackageHashes {
151                    rockspec: rockspec_hash,
152                    source: source_hash,
153                };
154                let package = LockedPackage::new(
155                    spec,
156                    source,
157                    Some(RemotePackageSourceUrl::Url { url: binary_url }),
158                    hashes,
159                );
160                (package, PackageSource::Archive(bytes), None)
161            }
162            _ => {
163                let source_url = source_url
164                    .clone()
165                    .ok_or_else(|| Error::MissingSourceUrl(name.clone()))?;
166                let source_spec =
167                    RemotePackageSourceSpec::SrcRock(SrcRockSource { bytes, source_url });
168                let (package, dir, source_root) =
169                    fetch_and_hash_source(&rockspec, spec, Some(source_spec), Some(source), config)
170                        .await?;
171                let artifact = PackageSource::SourceDir(source_root);
172                (package, artifact, Some(dir))
173            }
174        },
175        Some(PackageSource::SourceDir(path)) => {
176            let rockspec_hash = rockspec
177                .hash()
178                .await
179                .map_err(|err| Error::Hash(name.clone(), err))?;
180            let source_hash = path
181                .hash()
182                .await
183                .map_err(|err| Error::Hash(name.clone(), err))?;
184            let hashes = LockedPackageHashes {
185                rockspec: rockspec_hash,
186                source: source_hash,
187            };
188            let package = LockedPackage::new(spec, source, source_url, hashes);
189            (package, PackageSource::SourceDir(path), None)
190        }
191        None => {
192            let source_spec = RemotePackageSourceSpec::RockSpec(source_url);
193            let (package, dir, source_root) =
194                fetch_and_hash_source(&rockspec, spec, Some(source_spec), Some(source), config)
195                    .await?;
196            let artifact = PackageSource::SourceDir(source_root);
197            (package, artifact, Some(dir))
198        }
199    };
200
201    Ok(MaterialisedPackage {
202        package,
203        rockspec,
204        entry_type,
205        build_behaviour,
206        artifact,
207        temp_dir,
208    })
209}
210
211fn is_src_rock_url(source_url: &RemotePackageSourceUrl) -> bool {
212    match source_url {
213        RemotePackageSourceUrl::Url { url } => url.path().ends_with(".src.rock"),
214        RemotePackageSourceUrl::File { path } => path.to_string_lossy().ends_with(".src.rock"),
215        RemotePackageSourceUrl::Git { .. } => false,
216    }
217}
218
219/// Resolves the source root inside an unpacked source rock.
220///
221/// The source root is `<unpacked>/<repository>` when that directory is the only
222/// entry besides the rockspec. Otherwise the source root is the unpacked root.
223///
224/// This matches the wrapper directory luarocks adds when packing a Git source rock,
225/// while leaving unwrapped source trees untouched.
226///
227/// For a git source rock containing `foo/`:
228///
229/// | unpacked contents        | returned source root |
230/// |--------------------------|----------------------|
231/// | `foo/` and the rockspec  | `<unpacked>/foo`     |
232/// | source files at the root | `<unpacked>`         |
233fn src_rock_source_root<R: Rockspec>(rockspec: &R, unpacked_root: &Path) -> PathBuf {
234    if let rockspec::source::Spec::Git(git) = &rockspec.source().current_platform().source_spec {
235        let repo_dir = unpacked_root.join(git.url.repo());
236        if let Ok(Some(entry)) = unpack::single_non_rockspec_entry(unpacked_root) {
237            if entry == repo_dir && entry.is_dir() {
238                return repo_dir;
239            }
240        }
241    }
242    unpacked_root.to_path_buf()
243}
244
245pub(crate) async fn fetch_and_hash_source<R: Rockspec + HasIntegrity>(
246    rockspec: &R,
247    spec: LockedPackageSpec,
248    source_spec: Option<RemotePackageSourceSpec>,
249    source: Option<remote::package::Source>,
250    config: &Config,
251) -> Result<(LockedPackage, TempDir, PathBuf), build::Error> {
252    let temp_dir = fs::tempfile::tempdir()?;
253    let is_src_rock = match &source_spec {
254        Some(RemotePackageSourceSpec::SrcRock(_)) => true,
255        Some(RemotePackageSourceSpec::RockSpec(Some(source_url))) => {
256            config.vendor_dir().is_none() && is_src_rock_url(source_url)
257        }
258        _ => false,
259    };
260
261    let source_metadata = match source_spec {
262        Some(RemotePackageSourceSpec::SrcRock(SrcRockSource { bytes, source_url })) => {
263            let hash = bytes.hash().await?;
264            let cursor = Cursor::new(bytes);
265            unpack::src_rock(cursor, temp_dir.path().to_path_buf())
266                .await
267                .map_err(build::Error::UnpackSrcRock)?;
268            fetch::RemotePackageSourceMetadata { hash, source_url }
269        }
270        Some(RemotePackageSourceSpec::RockSpec(source_url)) => {
271            operations::FetchSrc::new(temp_dir.path(), rockspec, config)
272                .maybe_source_url(source_url)
273                .fetch_internal()
274                .await?
275        }
276        None => {
277            operations::FetchSrc::new(temp_dir.path(), rockspec, config)
278                .fetch_internal()
279                .await?
280        }
281    };
282
283    let hashes = LockedPackageHashes {
284        rockspec: rockspec.hash().await?,
285        source: source_metadata.hash.clone(),
286    };
287
288    let package = LockedPackage::new(
289        spec,
290        source
291            .map(Result::Ok)
292            .unwrap_or_else(|| {
293                rockspec
294                    .to_lua_remote_rockspec_string()
295                    .map(remote::package::Source::RockspecContent)
296            })
297            .unwrap_or(remote::package::Source::Local),
298        Some(source_metadata.source_url.clone()),
299        hashes,
300    );
301
302    let source_root = if is_src_rock {
303        src_rock_source_root(rockspec, temp_dir.path())
304    } else {
305        temp_dir.path().to_path_buf()
306    };
307
308    Ok((package, temp_dir, source_root))
309}