diff --git a/backend/src/pacman-repo-utils/src/repo_init.rs b/backend/src/pacman-repo-utils/src/repo_init.rs index 122c39d..8cc872d 100644 --- a/backend/src/pacman-repo-utils/src/repo_init.rs +++ b/backend/src/pacman-repo-utils/src/repo_init.rs @@ -8,32 +8,52 @@ use std::os::unix::fs::symlink; use std::path::PathBuf; pub fn init_repo_impl(path: &PathBuf, name: &str) -> anyhow::Result<()> { - let db_file = path.join(format!("{}.db.tar.gz", name)); - let files_file = path.join(format!("{}.files.tar.gz", name)); - - // create repo folder - if fs::metadata(&db_file).is_ok() || fs::metadata(&files_file).is_ok() { + if repo_exists(path, name).is_ok() { info!("Pacman repo archive already exists"); return Ok(()); } + // create repo folder info!("Initializing empty pacman Repo archive"); _ = fs::create_dir(path); - let tar_gz = File::create(&db_file)?; - let enc = GzEncoder::new(tar_gz, Compression::default()); - let mut tar = tar::Builder::new(enc); - tar.finish() - .map_err(|_| anyhow!("failed to create repo archive"))?; - symlink(&db_file, path.join(format!("{}.db", name))) - .map_err(|_| anyhow!("failed to create repo symlink"))?; + create_empty_archive(&path, &name, "db")?; + create_empty_archive(&path, &name, "files")?; + Ok(()) +} + +/// check if repo archives and symlink exist +fn repo_exists(path: &PathBuf, name: &str) -> anyhow::Result<()> { + for suffix in ["db", "files"] { + let files = get_archive_names(name, suffix); + for file in [files.0, files.1] { + if fs::metadata(&path.join(&file)).is_err() { + return Err(anyhow!("{} doesn't exist", file)); + } + } + } + Ok(()) +} - let tar_gz = File::create(&files_file)?; +/// assembles filneame of archive and symlink +fn get_archive_names(name: &str, suffix: &str) -> (String, String) { + let file_name = format!("{}.{}.tar.gz", name, suffix); + let symlink_name = format!("{}.{}", name, suffix); + (file_name, symlink_name) +} + +/// create empty archive and corresponding symlink +fn create_empty_archive(path: &PathBuf, name: &str, suffix: &str) -> anyhow::Result<()> { + let (archive_file_name, symlink_name) = get_archive_names(name, suffix); + let archive_path = path.join(&archive_file_name); + let symlink_path = path.join(&symlink_name); + + let tar_gz = File::create(archive_path)?; let enc = GzEncoder::new(tar_gz, Compression::default()); let mut tar = tar::Builder::new(enc); tar.finish() .map_err(|_| anyhow!("failed to create repo archive"))?; - symlink(&files_file, path.join(format!("{}.files", name))) + symlink(archive_file_name, symlink_path) .map_err(|_| anyhow!("failed to create repo symlink"))?; Ok(()) -} +} \ No newline at end of file