use std::fs;
use camino::Utf8Path;
use color_eyre::eyre::Context;
use tracing::{debug, warn};
use super::copy::copy_dir_recursive;
use crate::error::BootstrapResult;
const COMPLETION_MARKER: &str = ".complete";
const LOG_TARGET: &str = "pg_embed::cache";
pub fn populate_cache(
source: &Utf8Path,
cache_dir: &Utf8Path,
version: &str,
) -> BootstrapResult<()> {
let version_dir = cache_dir.join(version);
log_populate_start(source, cache_dir, version);
fs::create_dir_all(&version_dir)
.with_context(|| format!("failed to create cache directory: {version_dir}"))?;
copy_dir_recursive(source.as_std_path(), version_dir.as_std_path())
.with_context(|| format!("failed to copy binaries to cache: {version_dir}"))?;
write_completion_marker(&version_dir)?;
log_populate_complete(version, &version_dir);
Ok(())
}
fn log_populate_start(source: &Utf8Path, cache_dir: &Utf8Path, version: &str) {
debug!(
target: LOG_TARGET,
source = %source,
cache_dir = %cache_dir,
version = %version,
"populating cache"
);
}
fn log_populate_complete(version: &str, version_dir: &Utf8Path) {
debug!(
target: LOG_TARGET,
version = %version,
path = %version_dir,
"cache population completed"
);
}
fn write_completion_marker(cache_path: &Utf8Path) -> BootstrapResult<()> {
let marker = cache_path.join(COMPLETION_MARKER);
fs::write(&marker, "")
.with_context(|| format!("failed to write cache completion marker: {marker}"))?;
Ok(())
}
pub fn try_populate_cache(source: &Utf8Path, cache_dir: &Utf8Path, version: &str) {
if let Err(err) = populate_cache(source, cache_dir, version) {
warn!(
target: LOG_TARGET,
error = %err,
version = %version,
"failed to populate cache, future runs may re-download"
);
}
}