1use anyhow::{Result, anyhow};
2use std::fs;
3use std::path::PathBuf;
4
5pub fn get_cache_root() -> Result<PathBuf> {
6 let home_dir =
7 crate::utils::get_user_home().ok_or_else(|| anyhow!("Could not find home directory."))?;
8 Ok(home_dir.join(".zoi").join("cache"))
9}
10
11pub fn get_archive_cache_root() -> Result<PathBuf> {
12 let cache_root = get_cache_root()?;
13 Ok(cache_root.join("archives"))
14}
15
16pub fn get_pkgdef_cache_root() -> Result<PathBuf> {
17 let cache_root = get_cache_root()?;
18 Ok(cache_root.join("pkgdefs"))
19}
20
21pub fn mirror_candidate_urls(url: &str) -> Vec<String> {
22 let mut urls = vec![url.to_string()];
23 let Ok(config) = crate::config::read_config() else {
24 return urls;
25 };
26
27 let Some(filename) = url.split('/').next_back().filter(|part| !part.is_empty()) else {
28 return urls;
29 };
30
31 for mirror in config.cache_mirrors {
32 urls.push(format!("{}/{}", mirror.trim_end_matches('/'), filename));
33 }
34
35 urls
36}
37
38pub fn clear(dry_run: bool) -> Result<()> {
39 let cache_dir = get_cache_root()?;
40 if cache_dir.exists() {
41 if dry_run {
42 println!(
43 "(Dry-run) Would remove cache directory: {}",
44 cache_dir.display()
45 );
46 } else {
47 println!("Removing cache directory: {}", cache_dir.display());
48 fs::remove_dir_all(cache_dir)?;
49 }
50 } else {
51 println!("Cache directory does not exist. Nothing to clean.");
52 }
53 Ok(())
54}
55
56pub fn clear_archives(dry_run: bool) -> Result<()> {
57 let archive_cache_dir = get_archive_cache_root()?;
58 if archive_cache_dir.exists() {
59 if dry_run {
60 println!(
61 "(Dry-run) Would remove archive cache directory: {}",
62 archive_cache_dir.display()
63 );
64 } else {
65 println!(
66 "Removing archive cache directory: {}",
67 archive_cache_dir.display()
68 );
69 fs::remove_dir_all(archive_cache_dir)?;
70 }
71 } else {
72 println!("Archive cache directory does not exist. Nothing to clean.");
73 }
74 Ok(())
75}