Skip to main content

lux_lib/pipeline/
materialise.rs

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