Skip to main content

euv_cli/dx/clean/
fn.rs

1use super::*;
2
3/// Cleans `dist/`, `target/mobile-hosts/`, `target/euv-icon-cache/`, stale `.euv-updates/staging/`, and optionally `cargo clean`.
4///
5/// # Arguments
6///
7/// - `&CleanOptions` - Root directory, `--all`, and `--dry-run` settings.
8///
9/// # Returns
10///
11/// - `io::Result<CleanReport>` - Reclaimed entries and byte totals, or I/O error.
12pub fn execute_clean(options: &CleanOptions) -> io::Result<CleanReport> {
13    let root: &Path = options.get_root_dir();
14    let dry_run: bool = options.get_dry_run();
15    let ota_store_dir: PathBuf = load_euv_config(root)
16        .ok()
17        .flatten()
18        .and_then(|loaded: LoadedEuvConfig| loaded.get_config().get_ota().try_get_store().clone())
19        .map(|configured: PathBuf| {
20            if configured.is_absolute() {
21                configured
22            } else {
23                root.join(configured)
24            }
25        })
26        .unwrap_or_else(|| root.join(DEFAULT_UPDATE_STORE_DIR));
27    let targets: [(PathBuf, &str); 4] = [
28        (root.join(CLEAN_DIR_DIST), CLEAN_CAT_DIST),
29        (
30            root.join(CLEAN_DIR_TARGET).join(CLEAN_DIR_MOBILE_HOSTS),
31            CLEAN_CAT_MOBILE_HOSTS,
32        ),
33        (
34            root.join(CLEAN_DIR_TARGET).join(CLEAN_DIR_ICON_CACHE),
35            CLEAN_CAT_ICON_CACHE,
36        ),
37        (ota_store_dir.join(STORE_DIR_STAGING), CLEAN_CAT_OTA_STAGING),
38    ];
39    let mut entries: Vec<CleanEntry> = Vec::new();
40    let mut total_bytes: u64 = 0;
41    for (dir_path, category) in targets.iter() {
42        if !dir_path.exists() {
43            continue;
44        }
45        let size_bytes: u64 = compute_dir_size_bytes(dir_path);
46        let removed: bool = if dry_run {
47            false
48        } else {
49            if dir_path.is_dir() {
50                fs::remove_dir_all(dir_path)?;
51            } else {
52                fs::remove_file(dir_path)?;
53            }
54            true
55        };
56        total_bytes = total_bytes.saturating_add(size_bytes);
57        entries.push(CleanEntry::new(
58            dir_path.display().to_string(),
59            (*category).to_string(),
60            size_bytes,
61            removed,
62        ));
63    }
64    let mut cargo_clean_ran: bool = false;
65    if options.get_all() {
66        let cargo_manifest: PathBuf = root.join(CARGO_TOML_NAME);
67        let target_dir: PathBuf = root.join(CLEAN_DIR_TARGET);
68        if cargo_manifest.is_file() && target_dir.exists() {
69            let target_bytes: u64 = compute_dir_size_bytes(&target_dir);
70            if !dry_run {
71                let args: Vec<String> = vec![
72                    ARG_CLEAN.to_string(),
73                    ARG_MANIFEST_PATH.to_string(),
74                    cargo_manifest.display().to_string(),
75                ];
76                let _: CommandRunMetrics =
77                    run_command_streaming(BIN_CARGO, &args, Some(root), &[], false)?;
78                cargo_clean_ran = true;
79            }
80            total_bytes = total_bytes.saturating_add(target_bytes);
81            entries.push(CleanEntry::new(
82                target_dir.display().to_string(),
83                CLEAN_CAT_CARGO_TARGET.to_string(),
84                target_bytes,
85                cargo_clean_ran,
86            ));
87        }
88    }
89    Ok(CleanReport::new(
90        root.display().to_string(),
91        dry_run,
92        entries,
93        total_bytes,
94        cargo_clean_ran,
95    ))
96}
97
98/// Formats a `CleanReport` into a crisp human-readable terminal table.
99///
100/// # Arguments
101///
102/// - `&CleanReport` - Clean execution summary.
103///
104/// # Returns
105///
106/// - `String` - Formatted terminal output.
107#[must_use]
108pub fn format_clean_report(report: &CleanReport) -> String {
109    if report.get_entries().is_empty() {
110        return CLEAN_EMPTY_MSG.to_string();
111    }
112    let mut table: TerminalTable = TerminalTable::with_headers(vec![
113        HEADER_STATUS.to_string(),
114        DOCTOR_HDR_CATEGORY.to_string(),
115        CLEAN_HDR_SIZE.to_string(),
116        CLEAN_HDR_PATH.to_string(),
117    ]);
118    for entry in report.get_entries().iter() {
119        let status: &str = if entry.get_removed() {
120            CLEAN_MODE_REMOVED
121        } else {
122            CLEAN_MODE_DRY_RUN
123        };
124        table.push_row(vec![
125            status.to_string(),
126            entry.get_category().clone(),
127            format_bytes_human(entry.get_bytes_reclaimed()),
128            entry.get_path().clone(),
129        ]);
130    }
131    let mut out: String = table.render();
132    let verb: &str = if report.get_dry_run() {
133        CLEAN_MODE_DRY_RUN
134    } else {
135        CLEAN_MODE_REMOVED
136    };
137    out.push_str(&format!(
138        "Total ({verb}): {} across {} location(s)\n",
139        format_bytes_human(report.get_total_bytes_reclaimed()),
140        report.get_entries().len()
141    ));
142    out
143}
144
145/// Recursively calculates total file bytes inside `path` without following symlinks.
146///
147/// # Arguments
148///
149/// - `&Path` - Root file or directory path.
150///
151/// # Returns
152///
153/// - `u64` - Total byte size across regular files beneath `path`.
154pub(crate) fn compute_dir_size_bytes(path: &Path) -> u64 {
155    let Ok(meta) = fs::symlink_metadata(path) else {
156        return 0;
157    };
158    if meta.file_type().is_symlink() {
159        return 0;
160    }
161    if meta.is_file() {
162        return meta.len();
163    }
164    if !meta.is_dir() {
165        return 0;
166    }
167    let mut total: u64 = 0;
168    if let Ok(entries) = fs::read_dir(path) {
169        for entry in entries.flatten() {
170            total = total.saturating_add(compute_dir_size_bytes(&entry.path()));
171        }
172    }
173    total
174}