1use std::fs;
2use std::path::PathBuf;
3
4use anyhow::{Result, anyhow};
5
6pub fn get_cache_root() -> Result<PathBuf> {
12 let home_dir = crate::utils::get_user_home()
13 .ok_or_else(|| anyhow!("Could not find home directory."))?;
14 Ok(home_dir.join(".zoi").join("cache"))
15}
16
17pub fn get_archive_cache_root() -> Result<PathBuf> {
23 let cache_root = get_cache_root()?;
24 Ok(cache_root.join("archives"))
25}
26
27pub fn get_pkgdef_cache_root() -> Result<PathBuf> {
33 let cache_root = get_cache_root()?;
34 Ok(cache_root.join("pkgdefs"))
35}
36
37pub fn mirror_candidate_urls(url: &str) -> Vec<String> {
40 let mut urls = vec![url.to_string()];
41 let Ok(config) = crate::config::read_config() else {
42 return urls;
43 };
44
45 let Some(filename) =
46 url.split('/').next_back().filter(|part| !part.is_empty())
47 else {
48 return urls;
49 };
50
51 for mirror in config.cache_mirrors {
52 urls.push(format!("{}/{}", mirror.trim_end_matches('/'), filename));
53 }
54
55 urls
56}
57
58pub fn clear(dry_run: bool) -> Result<()> {
64 let cache_dir = get_cache_root()?;
65 if cache_dir.exists() {
66 if dry_run {
67 println!(
68 "(Dry-run) Would remove cache directory: {}",
69 cache_dir.display()
70 );
71 } else {
72 println!("Removing cache directory: {}", cache_dir.display());
73 fs::remove_dir_all(cache_dir)?;
74 }
75 } else {
76 println!("Cache directory does not exist. Nothing to clean.");
77 }
78 Ok(())
79}
80
81pub fn clear_archives(dry_run: bool) -> Result<()> {
87 let archive_cache_dir = get_archive_cache_root()?;
88 if archive_cache_dir.exists() {
89 if dry_run {
90 println!(
91 "(Dry-run) Would remove archive cache directory: {}",
92 archive_cache_dir.display()
93 );
94 } else {
95 println!(
96 "Removing archive cache directory: {}",
97 archive_cache_dir.display()
98 );
99 fs::remove_dir_all(archive_cache_dir)?;
100 }
101 } else {
102 println!("Archive cache directory does not exist. Nothing to clean.");
103 }
104 Ok(())
105}