lux-lib 0.71.0

Library for the lux package manager for Lua
Documentation
#[cfg(feature = "wally")]
pub(crate) mod wally;

use crate::package;
use crate::remote;
use crate::rockspec;
use std::path::PathBuf;

use bon::Builder;
use miette::Diagnostic;
use thiserror::Error;

use crate::{
    config::Config,
    operations::{self, download, fetch_vendored, install},
    package::db::{search, PackageDB},
    project::Project,
    rockspec::Rockspec,
};

use super::materialise::PackageSource;

#[derive(Clone, Debug)]
pub(crate) struct FoundPackage {
    pub(crate) remote: remote::Package,
    pub(crate) rockspec: rockspec::lua::Remote,
    pub(crate) artifact: Option<PackageSource>,
}

impl FoundPackage {
    /// Builds a discovered package from an already-parsed rockspec, so it can
    /// be resolved as a root without contacting a remote package database.
    pub(crate) fn from_rockspec(rockspec: rockspec::lua::Remote) -> Self {
        let source = rockspec
            .to_lua_remote_rockspec_string()
            .map(remote::package::Source::RockspecContent)
            .unwrap_or(remote::package::Source::Local);
        let remote = remote::Package::new(
            package::Spec::new(rockspec.package().clone(), rockspec.version().clone()),
            source,
            None,
        );
        Self {
            remote,
            rockspec,
            artifact: None,
        }
    }

    /// Builds a discovered package from a project root rockspec, using the
    /// project's own directory as the source.
    pub(crate) fn from_project_root(rockspec: rockspec::lua::Remote, root_dir: PathBuf) -> Self {
        let remote = remote::Package::new(
            package::Spec::new(rockspec.package().clone(), rockspec.version().clone()),
            remote::package::Source::Local,
            None,
        );
        Self {
            remote,
            rockspec,
            artifact: Some(PackageSource::SourceDir(root_dir)),
        }
    }
}

#[derive(Error, Debug, Diagnostic)]
#[non_exhaustive]
pub enum Error {
    #[error(transparent)]
    #[diagnostic(transparent)]
    Search(#[from] search::Error),
    #[error("failed to acquire metadata for '{0}'")]
    #[diagnostic(forward(1))]
    Download(package::Req, Box<download::Error>),
    #[error("failed to fetch vendored package for '{0}'")]
    #[diagnostic(forward(1))]
    FetchVendored(package::Req, Box<fetch_vendored::Error>),
    #[error(transparent)]
    #[diagnostic(transparent)]
    Project(#[from] crate::project::Error),
    #[error(transparent)]
    #[diagnostic(transparent)]
    LocalRockspec(#[from] crate::project::IntoLocalRockspecError),
    #[cfg(feature = "wally")]
    #[error(transparent)]
    #[diagnostic(transparent)]
    Wally(#[from] wally::Error),
    #[cfg(not(feature = "wally"))]
    #[error("wally support is disabled in this build")]
    #[diagnostic(help("this build of Lux was compiled without the `wally` feature"))]
    WallyDisabled,
}

#[derive(Builder)]
#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
pub(crate) struct Discover<'a> {
    #[builder(start_fn)]
    pub(crate) package_db: PackageDB,
    #[builder(start_fn)]
    pub(crate) config: &'a Config,
}

impl<State> DiscoverBuilder<'_, State>
where
    State: discover_builder::State + discover_builder::IsComplete,
{
    pub(crate) async fn discover(self, spec: &install::Spec) -> Result<FoundPackage, Error> {
        let args = self._build();
        if let Some(found) = discover_project(spec)? {
            return Ok(found);
        }
        if let Some(source) = &spec.source {
            return discover_source_spec(spec, source, args.config).await;
        }
        discover_package_db(spec, &args.package_db, args.config).await
    }
}

fn discover_project(spec: &install::Spec) -> Result<Option<FoundPackage>, Error> {
    let Some(rockspec::source::Spec::File(path)) = &spec.source else {
        return Ok(None);
    };
    Ok(match Project::from_exact(path)? {
        Some(project) if project.toml().package() == spec.package.name() => {
            Some(FoundPackage::from_project_root(
                project.local_remote_rockspec()?,
                project.root().to_path_buf(),
            ))
        }
        _ => None,
    })
}

async fn discover_source_spec(
    spec: &install::Spec,
    source: &rockspec::source::Spec,
    _config: &Config,
) -> Result<FoundPackage, Error> {
    match source {
        rockspec::source::Spec::Git(_)
        | rockspec::source::Spec::File(_)
        | rockspec::source::Spec::Url(_) => discover_fetchable_source(spec, source.clone()),
        #[cfg(feature = "wally")]
        rockspec::source::Spec::Wally(wally_req) => {
            wally::discover(&spec.package, wally_req, _config)
                .await
                .map_err(Error::Wally)
        }
        #[cfg(not(feature = "wally"))]
        rockspec::source::Spec::Wally(_) => Err(Error::WallyDisabled),
    }
}

fn discover_fetchable_source(
    spec: &install::Spec,
    source: rockspec::source::Spec,
) -> Result<FoundPackage, Error> {
    let download =
        download::RemoteRock::from_package_req_and_source_spec(spec.package.clone(), source)
            .map_err(|err| Error::Download(spec.package.clone(), Box::new(err)))?;
    let rockspec = download.rockspec().clone();
    let remote = remote::Package::new(
        spec.package.clone().try_into().map_err(|err| {
            Error::Download(spec.package.clone(), Box::new(download::Error::from(err)))
        })?,
        download.rockspec_download().source.clone(),
        download.rockspec_download().source_url.clone(),
    );
    Ok(FoundPackage {
        remote,
        rockspec,
        artifact: None,
    })
}

async fn discover_package_db(
    spec: &install::Spec,
    package_db: &PackageDB,
    config: &Config,
) -> Result<FoundPackage, Error> {
    if let Some(found) = package_db.resolve(spec).await? {
        Ok(found)
    } else {
        download_remote(spec, package_db, config).await
    }
}

async fn download_remote(
    spec: &install::Spec,
    package_db: &PackageDB,
    config: &Config,
) -> Result<FoundPackage, Error> {
    if package_db.has_remote_sources() {
        let mut remote = package_db.find(&spec.package, None).await?;
        #[cfg(feature = "wally")]
        if let remote::package::Source::Wally(index_url) = &remote.source {
            return wally::discover_locked(&remote, index_url, config)
                .await
                .map_err(Error::Wally);
        }
        #[cfg(not(feature = "wally"))]
        if let remote::package::Source::Wally(_) = &remote.source {
            return Err(Error::WallyDisabled);
        }
        let download = if let Some(vendor_dir) = config.vendor_dir() {
            operations::FetchVendored::new()
                .vendor_dir(vendor_dir)
                .package(&spec.package)
                .package_db(package_db)
                .fetch_vendored_rock()
                .await
                .map_err(|err| Error::FetchVendored(spec.package.clone(), Box::new(err)))?
        } else {
            operations::Download::new(&spec.package, config)
                .package_db(package_db)
                .download_remote_rock()
                .await
                .map_err(|err| Error::Download(spec.package.clone(), Box::new(err)))?
        };
        let rockspec = download.rockspec().clone();
        let artifact = match &download {
            download::RemoteRock::SrcRock {
                src_rock,
                source_url,
                ..
            } => {
                remote.source_url = Some(source_url.clone());
                Some(PackageSource::Archive(src_rock.clone()))
            }
            download::RemoteRock::BinaryRock { packed_rock, .. } => {
                Some(PackageSource::Archive(packed_rock.clone()))
            }
            download::RemoteRock::RockspecOnly { .. } => None,
        };
        Ok(FoundPackage {
            remote,
            rockspec,
            artifact,
        })
    } else {
        Err(Error::Search(search::Error::RockNotFound(
            spec.package.clone(),
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    use crate::{build::BuildBehaviour, config, tree::EntryType};

    #[test]
    fn from_rockspec_builds_local_found_package() {
        let content = "rockspec_format = '1.0'\npackage = 'foo'\nversion = '1.0.0-1'\nsource = { url = 'https://example.com/foo.zip' }";
        let Ok(rockspec) = rockspec::lua::Remote::new(content) else {
            unreachable!("invalid test rockspec");
        };

        let found = FoundPackage::from_rockspec(rockspec);

        assert_eq!(found.remote.spec.name().to_string(), "foo");
        assert_eq!(found.remote.spec.version().to_string(), "1.0.0-1");
        assert!(matches!(
            found.remote.source,
            remote::package::Source::RockspecContent(_)
        ));
        assert!(found.artifact.is_none());
    }

    // https://github.com/lumen-oss/lux/issues/2018
    #[tokio::test]
    async fn resolves_path_dependency_from_project_manifest() {
        let bar_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("resources/test/sample-projects/multi-project-local-deps/projects/bar");

        let config = config::Builder::new().unwrap().build().unwrap();
        let spec = install::Spec::new(
            package::Req::new("bar".into(), Some("1.0.0".into())).unwrap(),
            EntryType::DependencyOnly,
        )
        .build_behaviour(BuildBehaviour::Ignore)
        .maybe_source(Some(rockspec::source::Spec::File(bar_dir)))
        .build();

        let found = Discover::new(PackageDB::from_local(Vec::new()), &config)
            .discover(&spec)
            .await
            .unwrap();

        assert!(found
            .rockspec
            .dependencies()
            .current_platform()
            .iter()
            .any(|dependency| dependency.name().to_string() == "foo"));
    }
}