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
217fn src_rock_source_root<R: Rockspec>(
230 rockspec: &R,
231 source_url: &RemotePackageSourceUrl,
232 unpacked_root: &Path,
233) -> PathBuf {
234 let git = match &rockspec.source().current_platform().source_spec {
235 rockspec::source::Spec::Git(git) if is_src_rock_url(source_url) => git,
236 _ => return unpacked_root.to_path_buf(),
237 };
238 let repo_dir = unpacked_root.join(git.url.repo());
239 match unpack::single_non_rockspec_entry(unpacked_root) {
240 Ok(Some(entry)) if entry == repo_dir && entry.is_dir() => repo_dir,
241 _ => unpacked_root.to_path_buf(),
242 }
243}
244
245pub(crate) async fn fetch_and_hash_source<R: Rockspec + HasIntegrity>(
246 rockspec: &R,
247 spec: locked_package::Spec,
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 source_metadata = match source_spec {
254 Some(RemotePackageSourceSpec::SrcRock(SrcRockSource { bytes, source_url })) => {
255 let hash = bytes.hash().await?;
256 let cursor = Cursor::new(bytes);
257 unpack::src_rock(cursor, temp_dir.path().to_path_buf())
258 .await
259 .map_err(build::Error::UnpackSrcRock)?;
260 fetch::RemotePackageSourceMetadata { hash, source_url }
261 }
262 Some(RemotePackageSourceSpec::RockSpec(source_url)) => {
263 operations::FetchSrc::new(temp_dir.path(), rockspec, config)
264 .maybe_source_url(source_url)
265 .fetch_internal()
266 .await?
267 }
268 None => {
269 operations::FetchSrc::new(temp_dir.path(), rockspec, config)
270 .fetch_internal()
271 .await?
272 }
273 };
274
275 let hashes = locked_package::Hashes {
276 rockspec: rockspec.hash().await?,
277 source: source_metadata.hash.clone(),
278 };
279
280 let package = LockedPackage::new(
281 spec,
282 source
283 .map(Result::Ok)
284 .unwrap_or_else(|| {
285 rockspec
286 .to_lua_remote_rockspec_string()
287 .map(remote::package::Source::RockspecContent)
288 })
289 .unwrap_or(remote::package::Source::Local),
290 Some(source_metadata.source_url.clone()),
291 hashes,
292 );
293
294 let source_root = src_rock_source_root(rockspec, &source_metadata.source_url, temp_dir.path());
295
296 Ok((package, temp_dir, source_root))
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 fn git_rockspec() -> rockspec::lua::Remote {
304 rockspec::lua::Remote::new(
305 r#"
306package = "busted"
307version = "2.3.0-1"
308source = { url = "git+https://github.com/lunarmodules/busted.git", tag = "v2.3.0" }
309"#,
310 )
311 .unwrap()
312 }
313
314 fn unpacked_git_src_rock() -> tempfile::TempDir {
315 let unpacked = tempfile::tempdir().unwrap();
316 std::fs::write(unpacked.path().join("busted-2.3.0-1.rockspec"), "").unwrap();
317 std::fs::create_dir(unpacked.path().join("busted")).unwrap();
318 unpacked
319 }
320
321 #[test]
322 fn src_rock_source_root_finds_nested_git_checkout() {
323 let unpacked = unpacked_git_src_rock();
324 let source_url = RemotePackageSourceUrl::Url {
325 url: "https://luarocks.org/busted-2.3.0-1.src.rock"
326 .parse()
327 .unwrap(),
328 };
329
330 assert_eq!(
331 src_rock_source_root(&git_rockspec(), &source_url, unpacked.path()),
332 unpacked.path().join("busted")
333 );
334 }
335
336 #[test]
337 fn locked_git_source_uses_unpacked_root() {
338 let unpacked = unpacked_git_src_rock();
339 let source_url = RemotePackageSourceUrl::Git {
340 url: "https://github.com/lunarmodules/busted.git".into(),
341 checkout_ref: "v2.3.0".into(),
342 submodules: false,
343 };
344
345 assert_eq!(
346 src_rock_source_root(&git_rockspec(), &source_url, unpacked.path()),
347 unpacked.path()
348 );
349 }
350
351 #[tokio::test]
352 async fn git_source_falls_back_to_src_rock_source_root() {
353 use httptest::{http::Response, matchers::request, Expectation, Server};
354 use std::io::Write;
355
356 let mut src_rock = Vec::new();
357 {
358 let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut src_rock));
359 let options = zip::write::SimpleFileOptions::default();
360 zip.start_file("busted-2.3.0-1.rockspec", options).unwrap();
361 zip.write_all(b"").unwrap();
362 zip.start_file("busted/busted.lua", options).unwrap();
363 zip.write_all(b"return {}").unwrap();
364 zip.finish().unwrap();
365 }
366
367 let server = Server::run();
368 server.expect(
369 Expectation::matching(request::method_path("GET", "/busted-2.3.0-1.src.rock"))
370 .respond_with(Response::builder().status(200).body(src_rock).unwrap()),
371 );
372 let config = crate::config::Builder::new()
373 .unwrap()
374 .server(Some(server.url("/").to_string().parse().unwrap()))
375 .build()
376 .unwrap();
377 let spec = locked_package::Spec::new(
378 &"busted".into(),
379 &"2.3.0-1".parse().unwrap(),
380 crate::lockfile::Constraint::Unconstrained,
381 Vec::new(),
382 Vec::new(),
383 &crate::lockfile::PinnedState::default(),
384 &crate::lockfile::OptState::default(),
385 );
386 let source_url = RemotePackageSourceUrl::Git {
387 url: "https://127.0.0.1:1/busted.git".into(),
388 checkout_ref: "v2.3.0".into(),
389 submodules: false,
390 };
391
392 let (_, temp_dir, source_root) = fetch_and_hash_source(
393 &git_rockspec(),
394 spec,
395 Some(RemotePackageSourceSpec::RockSpec(Some(source_url))),
396 None,
397 &config,
398 )
399 .await
400 .unwrap();
401
402 assert_eq!(source_root, temp_dir.path().join("busted"));
403 assert!(source_root.join("busted.lua").is_file());
404 }
405}