|
| 1 | +use std::{collections::HashSet, fs, path::Path}; |
| 2 | + |
| 3 | +use anyhow::Result; |
| 4 | + |
| 5 | +use crate::{ |
| 6 | + chunks::{Chunk, get_chunk_filename}, |
| 7 | + repo::{get_all_installed_packages, get_all_packages}, |
| 8 | +}; |
| 9 | + |
| 10 | +/// Removes chunks that aren't actually used by any packages in the Repository |
| 11 | +/// This is most useful for remote Repository administrators. |
| 12 | +/// |
| 13 | +/// # Errors |
| 14 | +/// |
| 15 | +/// - Filesystem errors (Permissions most likely) |
| 16 | +/// - Repository doesn't exist |
| 17 | +pub fn clean_unused(repo_path: &Path) -> Result<()> { |
| 18 | + let packages = get_all_packages(repo_path)?; |
| 19 | + let mut chunks: Vec<Chunk> = Vec::new(); |
| 20 | + |
| 21 | + for package in packages { |
| 22 | + for chunk in package.chunks.clone() { |
| 23 | + chunks.push(chunk); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + clean(&repo_path.join("chunks"), &chunks) |
| 28 | +} |
| 29 | + |
| 30 | +/// Removes chunks that are actually used by any packages in the Repository, but aren't installed |
| 31 | +/// This is most useful for end users. |
| 32 | +/// |
| 33 | +/// # Errors |
| 34 | +/// |
| 35 | +/// - Filesystem errors (Permissions most likely) |
| 36 | +/// - Repository doesn't exist |
| 37 | +pub fn clean_used(repo_path: &Path) -> Result<()> { |
| 38 | + let packages = get_all_installed_packages(repo_path)?; |
| 39 | + let mut chunks: Vec<Chunk> = Vec::new(); |
| 40 | + |
| 41 | + for package in packages { |
| 42 | + for chunk in package.chunks.clone() { |
| 43 | + chunks.push(chunk); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + clean(&repo_path.join("chunks"), &chunks) |
| 48 | +} |
| 49 | + |
| 50 | +/// Cleans a `chunk_store` of unused chunks, using the whitelist `allowed_chunks` |
| 51 | +fn clean(chunk_store_path: &Path, allowed_chunks: &[Chunk]) -> Result<()> { |
| 52 | + let allowed: HashSet<String> = allowed_chunks |
| 53 | + .iter() |
| 54 | + .map(|c| get_chunk_filename(&c.hash, c.permissions)) |
| 55 | + .collect(); |
| 56 | + |
| 57 | + for entry in fs::read_dir(chunk_store_path)? { |
| 58 | + let entry = entry?; |
| 59 | + let file_name = entry.file_name(); |
| 60 | + let Some(file_name_str) = file_name.to_str() else { |
| 61 | + continue; |
| 62 | + }; |
| 63 | + |
| 64 | + if allowed.contains(file_name_str) { |
| 65 | + fs::remove_file(entry.path())?; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + Ok(()) |
| 70 | +} |
0 commit comments