use crate::lockfile::locked_package;
use crate::remote;
use std::collections::HashMap;
use std::io;
use std::io::Cursor;
use std::path::{Path, PathBuf};
use bon::Builder;
use bytes::Bytes;
use futures::{StreamExt, TryStreamExt};
use miette::Diagnostic;
use tempfile::TempDir;
use thiserror::Error;
use crate::rockspec;
use crate::{
build::{self, RemotePackageSourceSpec, SrcRockSource},
config::Config,
fs,
hash::HasIntegrity,
lockfile::{LockedPackage, RemotePackageSourceUrl},
operations::{self, fetch, unpack},
rockspec::Rockspec,
tree::EntryType,
};
use super::{
resolve::{ResolvedArtifacts, ResolvedPackage},
Artifacts,
};
#[derive(Clone, Debug)]
pub(crate) enum PackageSource {
SourceDir(PathBuf),
Archive(Bytes),
}
pub(crate) struct MaterialisedPackage {
pub(crate) package: LockedPackage,
pub(crate) rockspec: rockspec::lua::Remote,
pub(crate) entry_type: EntryType,
pub(crate) build_behaviour: build::Behaviour,
pub(crate) artifact: PackageSource,
pub(crate) temp_dir: Option<TempDir>,
}
pub(crate) type MaterialiseArtifacts = Artifacts<HashMap<locked_package::ID, MaterialisedPackage>>;
#[derive(Error, Debug, Diagnostic)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
#[diagnostic(transparent)]
Fs(#[from] fs::Error),
#[error(transparent)]
#[diagnostic(transparent)]
Build(#[from] Box<build::Error>),
#[error("failed to hash the source for '{0}'")]
Hash(String, #[source] io::Error),
#[error("missing source url for '{0}'")]
MissingSourceUrl(String),
}
impl From<build::Error> for Error {
fn from(source: build::Error) -> Self {
Self::Build(Box::new(source))
}
}
#[derive(Builder)]
#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
pub(crate) struct Materialise<'a> {
#[builder(start_fn)]
pub(crate) config: &'a Config,
pub(crate) resolved: ResolvedArtifacts,
}
impl<State> MaterialiseBuilder<'_, State>
where
State: materialise_builder::State + materialise_builder::IsComplete,
{
pub(crate) async fn materialise(self) -> Result<MaterialiseArtifacts, Error> {
let args = self._build();
let config = args.config;
let artifacts: MaterialiseArtifacts = args
.resolved
.iter()
.map(|(section, packages)| (section, packages.map(|_| HashMap::new())))
.collect();
let jobs = args.resolved.into_iter().flat_map(|(section, packages)| {
packages
.into_iter()
.flatten()
.map(move |(id, package)| (section, id, package))
});
futures::stream::iter(jobs)
.map(|(section, id, package)| async move {
materialise(config, package)
.await
.map(|package| (section, id, package))
})
.buffered(config.max_jobs())
.try_fold(
artifacts,
|mut artifacts, (section, id, package)| async move {
artifacts
.get_mut(section)
.get_or_insert_with(HashMap::new)
.insert(id, package);
Ok(artifacts)
},
)
.await
}
}
async fn materialise(
config: &Config,
resolved: ResolvedPackage,
) -> Result<MaterialisedPackage, Error> {
let ResolvedPackage {
spec,
rockspec,
source,
source_url,
entry_type,
build_behaviour,
artifact,
} = resolved;
let name = spec.name().to_string();
let (package, artifact, temp_dir) = match artifact {
Some(PackageSource::Archive(bytes)) => match &source {
remote::package::Source::LuarocksBinaryRock(url) => {
let binary_url = url.clone();
let rockspec_hash = rockspec
.hash()
.await
.map_err(|err| Error::Hash(name.clone(), err))?;
let source_hash = bytes
.hash()
.await
.map_err(|err| Error::Hash(name.clone(), err))?;
let hashes = locked_package::Hashes {
rockspec: rockspec_hash,
source: source_hash,
};
let package = LockedPackage::new(
spec,
source,
Some(RemotePackageSourceUrl::Url { url: binary_url }),
hashes,
);
(package, PackageSource::Archive(bytes), None)
}
_ => {
let source_url = source_url
.clone()
.ok_or_else(|| Error::MissingSourceUrl(name.clone()))?;
let source_spec =
RemotePackageSourceSpec::SrcRock(SrcRockSource { bytes, source_url });
let (package, dir, source_root) =
fetch_and_hash_source(&rockspec, spec, Some(source_spec), Some(source), config)
.await?;
let artifact = PackageSource::SourceDir(source_root);
(package, artifact, Some(dir))
}
},
Some(PackageSource::SourceDir(path)) => {
let rockspec_hash = rockspec
.hash()
.await
.map_err(|err| Error::Hash(name.clone(), err))?;
let source_hash = path
.hash()
.await
.map_err(|err| Error::Hash(name.clone(), err))?;
let hashes = locked_package::Hashes {
rockspec: rockspec_hash,
source: source_hash,
};
let package = LockedPackage::new(spec, source, source_url, hashes);
(package, PackageSource::SourceDir(path), None)
}
None => {
let source_spec = RemotePackageSourceSpec::RockSpec(source_url);
let (package, dir, source_root) =
fetch_and_hash_source(&rockspec, spec, Some(source_spec), Some(source), config)
.await?;
let artifact = PackageSource::SourceDir(source_root);
(package, artifact, Some(dir))
}
};
Ok(MaterialisedPackage {
package,
rockspec,
entry_type,
build_behaviour,
artifact,
temp_dir,
})
}
fn is_src_rock_url(source_url: &RemotePackageSourceUrl) -> bool {
match source_url {
RemotePackageSourceUrl::Url { url } => url.path().ends_with(".src.rock"),
RemotePackageSourceUrl::File { path } => path.to_string_lossy().ends_with(".src.rock"),
RemotePackageSourceUrl::Git { .. } => false,
}
}
fn src_rock_source_root<R: Rockspec>(
rockspec: &R,
source_url: &RemotePackageSourceUrl,
unpacked_root: &Path,
) -> PathBuf {
let git = match &rockspec.source().current_platform().source_spec {
rockspec::source::Spec::Git(git) if is_src_rock_url(source_url) => git,
_ => return unpacked_root.to_path_buf(),
};
let repo_dir = unpacked_root.join(git.url.repo());
match unpack::single_non_rockspec_entry(unpacked_root) {
Ok(Some(entry)) if entry == repo_dir && entry.is_dir() => repo_dir,
_ => unpacked_root.to_path_buf(),
}
}
pub(crate) async fn fetch_and_hash_source<R: Rockspec + HasIntegrity>(
rockspec: &R,
spec: locked_package::Spec,
source_spec: Option<RemotePackageSourceSpec>,
source: Option<remote::package::Source>,
config: &Config,
) -> Result<(LockedPackage, TempDir, PathBuf), build::Error> {
let temp_dir = fs::tempfile::tempdir()?;
let source_metadata = match source_spec {
Some(RemotePackageSourceSpec::SrcRock(SrcRockSource { bytes, source_url })) => {
let hash = bytes.hash().await?;
let cursor = Cursor::new(bytes);
unpack::src_rock(cursor, temp_dir.path().to_path_buf())
.await
.map_err(build::Error::UnpackSrcRock)?;
fetch::RemotePackageSourceMetadata { hash, source_url }
}
Some(RemotePackageSourceSpec::RockSpec(source_url)) => {
operations::FetchSrc::new(temp_dir.path(), rockspec, config)
.maybe_source_url(source_url)
.fetch_internal()
.await?
}
None => {
operations::FetchSrc::new(temp_dir.path(), rockspec, config)
.fetch_internal()
.await?
}
};
let hashes = locked_package::Hashes {
rockspec: rockspec.hash().await?,
source: source_metadata.hash.clone(),
};
let package = LockedPackage::new(
spec,
source
.map(Result::Ok)
.unwrap_or_else(|| {
rockspec
.to_lua_remote_rockspec_string()
.map(remote::package::Source::RockspecContent)
})
.unwrap_or(remote::package::Source::Local),
Some(source_metadata.source_url.clone()),
hashes,
);
let source_root = src_rock_source_root(rockspec, &source_metadata.source_url, temp_dir.path());
Ok((package, temp_dir, source_root))
}
#[cfg(test)]
mod tests {
use super::*;
fn git_rockspec() -> rockspec::lua::Remote {
rockspec::lua::Remote::new(
r#"
package = "busted"
version = "2.3.0-1"
source = { url = "git+https://github.com/lunarmodules/busted.git", tag = "v2.3.0" }
"#,
)
.unwrap()
}
fn unpacked_git_src_rock() -> tempfile::TempDir {
let unpacked = tempfile::tempdir().unwrap();
std::fs::write(unpacked.path().join("busted-2.3.0-1.rockspec"), "").unwrap();
std::fs::create_dir(unpacked.path().join("busted")).unwrap();
unpacked
}
#[test]
fn src_rock_source_root_finds_nested_git_checkout() {
let unpacked = unpacked_git_src_rock();
let source_url = RemotePackageSourceUrl::Url {
url: "https://luarocks.org/busted-2.3.0-1.src.rock"
.parse()
.unwrap(),
};
assert_eq!(
src_rock_source_root(&git_rockspec(), &source_url, unpacked.path()),
unpacked.path().join("busted")
);
}
#[test]
fn locked_git_source_uses_unpacked_root() {
let unpacked = unpacked_git_src_rock();
let source_url = RemotePackageSourceUrl::Git {
url: "https://github.com/lunarmodules/busted.git".into(),
checkout_ref: "v2.3.0".into(),
submodules: false,
};
assert_eq!(
src_rock_source_root(&git_rockspec(), &source_url, unpacked.path()),
unpacked.path()
);
}
#[tokio::test]
async fn git_source_falls_back_to_src_rock_source_root() {
use httptest::{http::Response, matchers::request, Expectation, Server};
use std::io::Write;
let mut src_rock = Vec::new();
{
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut src_rock));
let options = zip::write::SimpleFileOptions::default();
zip.start_file("busted-2.3.0-1.rockspec", options).unwrap();
zip.write_all(b"").unwrap();
zip.start_file("busted/busted.lua", options).unwrap();
zip.write_all(b"return {}").unwrap();
zip.finish().unwrap();
}
let server = Server::run();
server.expect(
Expectation::matching(request::method_path("GET", "/busted-2.3.0-1.src.rock"))
.respond_with(Response::builder().status(200).body(src_rock).unwrap()),
);
let config = crate::config::Builder::new()
.unwrap()
.server(Some(server.url("/").to_string().parse().unwrap()))
.build()
.unwrap();
let spec = locked_package::Spec::new(
&"busted".into(),
&"2.3.0-1".parse().unwrap(),
crate::lockfile::Constraint::Unconstrained,
Vec::new(),
Vec::new(),
&crate::lockfile::PinnedState::default(),
&crate::lockfile::OptState::default(),
);
let source_url = RemotePackageSourceUrl::Git {
url: "https://127.0.0.1:1/busted.git".into(),
checkout_ref: "v2.3.0".into(),
submodules: false,
};
let (_, temp_dir, source_root) = fetch_and_hash_source(
&git_rockspec(),
spec,
Some(RemotePackageSourceSpec::RockSpec(Some(source_url))),
None,
&config,
)
.await
.unwrap();
assert_eq!(source_root, temp_dir.path().join("busted"));
assert!(source_root.join("busted.lua").is_file());
}
}