use std::path::{Path, PathBuf};
use elemental_infra::downloader::{DownloadBatch, DownloadSession};
use elemental_schema::forge::ForgeInstallerProfile;
use crate::{
error::{Error, Result},
families::{
installer::{InstallerArchive, InstallerArtifact},
version_json::InstanceStorage,
},
};
use super::{InstallerPersistedState, InstallerStatePaths, state::read_embedded_version};
pub async fn prepare_installer_state(
session: &DownloadSession,
installer_artifact: &InstallerArtifact,
instance: &InstanceStorage,
libraries_root: &Path,
family_name: &str,
validate_profile: &(dyn Fn(&ForgeInstallerProfile) -> Result<()> + Send + Sync),
) -> Result<InstallerPersistedState> {
download_installer(session, installer_artifact, family_name).await?;
let archive = InstallerArchive::new(installer_artifact.path.clone());
let state_paths = InstallerStatePaths::new(instance, family_name)?;
let install_profile = read_install_profile(&archive, family_name).await?;
validate_profile(&install_profile)?;
finish_installer_state(
&archive,
&state_paths,
install_profile,
libraries_root,
family_name,
)
.await
}
async fn download_installer(
session: &DownloadSession,
installer_artifact: &InstallerArtifact,
family_name: &str,
) -> Result<()> {
session
.submit(DownloadBatch::new(vec![installer_artifact.download_task()]).group("installer"))
.await
.map_err(|source| Error::DownloadInstaller {
family_name: family_name.to_owned(),
source,
})?;
session
.success()
.await
.map_err(|source| Error::DownloadInstaller {
family_name: family_name.to_owned(),
source,
})
}
async fn read_install_profile(
archive: &InstallerArchive<PathBuf>,
family_name: &str,
) -> Result<ForgeInstallerProfile> {
let archive = archive.clone();
let family_name = family_name.to_owned();
tokio::task::spawn_blocking(move || {
archive
.read_json::<ForgeInstallerProfile>("install_profile.json")
.map_err(|source| Error::ReadInstallerProfile {
family_name,
source: Box::new(source),
})
})
.await?
}
async fn finish_installer_state(
archive: &InstallerArchive<PathBuf>,
state_paths: &InstallerStatePaths,
install_profile: ForgeInstallerProfile,
libraries_root: &Path,
family_name: &str,
) -> Result<InstallerPersistedState> {
let embedded_version = {
let archive = archive.clone();
let install_profile = install_profile.clone();
let family_name = family_name.to_owned();
tokio::task::spawn_blocking(move || {
read_embedded_version(&archive, &install_profile, &family_name)
})
.await??
};
state_paths
.persist_install_profile(&install_profile)
.await?;
state_paths
.persist_embedded_version(embedded_version.as_deref())
.await?;
archive
.extract_maven_artifacts(libraries_root)
.await
.map_err(|source| Error::ExtractInstallerMavenArtifacts {
family_name: family_name.to_owned(),
source: Box::new(source),
})?;
Ok(InstallerPersistedState {
install_profile,
embedded_version,
})
}