1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use std::path::{Path, PathBuf};
use super::cargo;
use super::cleanup::{
calculate_directory_size, clean_misc_directories, clean_profile_directory,
find_profile_directories,
};
use super::size::format_size;
use crate::error::{HoldError, Result};
use crate::logging::Logger;
/// Garbage collection
#[derive(Debug)]
pub struct Gc {
/// Target directory to clean
target_dir: PathBuf,
/// Maximum target directory size in bytes (if None, use age-based cleanup)
max_target_size: Option<u64>,
/// Dry run mode - don't actually delete anything
dry_run: bool,
/// Enable debug output
debug: bool,
/// Age threshold for cleanup (default: 7 days)
age_threshold_days: u32,
/// Additional binaries to preserve in ~/.cargo/bin (on top of defaults)
preserve_binaries: Vec<String>,
/// Timestamp of the previous build to preserve artifacts from
previous_build_mtime_nanos: Option<u128>,
/// Suppress informational logging when true
quiet: bool,
}
impl Gc {
/// Creates a new builder for [`Gc`]
pub fn builder() -> GcBuilder {
GcBuilder::default()
}
/// Get the target directory
pub fn target_dir(&self) -> &Path {
&self.target_dir
}
/// Get the maximum target size
pub fn max_target_size(&self) -> Option<u64> {
self.max_target_size
}
/// Check if dry run mode is enabled
pub fn dry_run(&self) -> bool {
self.dry_run
}
/// Check if debug mode is enabled
pub fn debug(&self) -> bool {
self.debug
}
/// Get the age threshold in days
pub fn age_threshold_days(&self) -> u32 {
self.age_threshold_days
}
/// Get the list of binaries to preserve
pub fn preserve_binaries(&self) -> &[String] {
&self.preserve_binaries
}
/// Get the previous build mtime in nanoseconds
pub fn previous_build_mtime_nanos(&self) -> Option<u128> {
self.previous_build_mtime_nanos
}
/// Check if quiet mode is enabled
pub fn quiet(&self) -> bool {
self.quiet
}
/// Main entry point for garbage collection
///
/// Performs comprehensive garbage collection on build artifacts using a
/// combined size and age-based strategy:
///
/// 1. **Size enforcement**: If max_target_size is specified and exceeded,
/// removes oldest artifacts first until the target directory is under
/// the limit
/// 2. **Age cleanup**: Removes all artifacts older than age_threshold_days
///
/// Both conditions are always applied together, ensuring consistent cleanup
/// behavior. The function also cleans cargo registry cache, git checkouts,
/// and other build directories.
///
/// # Arguments
///
/// * `config` - Garbage collection configuration
/// * `verbose` - Verbosity level for output
///
/// # Returns
///
/// Statistics about the garbage collection operation
pub fn perform_gc(&self, verbose: u8) -> Result<GcStats> {
let mut stats = GcStats::default();
let log = Logger::new(verbose, self.quiet());
if !log.quiet() && (log.level() > 0 || self.debug()) {
eprintln!("Starting garbage collection in {:?}", self.target_dir());
eprintln!("Cleanup criteria:");
if let Some(max_size) = self.max_target_size() {
eprintln!(" - Target directory size: {}", format_size(max_size));
}
eprintln!(
" - Remove artifacts older than {} days",
self.age_threshold_days()
);
}
// Calculate initial size (return 0 if directory doesn't exist)
stats.initial_size = if self.target_dir().exists() {
calculate_directory_size(self.target_dir())?
} else {
0
};
if !log.quiet() {
// Always provide feedback about the operation
eprintln!("Cleanup status:");
eprintln!(" Current size: {}", format_size(stats.initial_size));
if let Some(max_size) = self.max_target_size() {
eprintln!(" Target size: {}", format_size(max_size));
if stats.initial_size > max_size {
eprintln!(
" Need to free: {} (for size limit)",
format_size(stats.initial_size - max_size)
);
} else {
eprintln!(" Already within target size");
}
}
eprintln!(" Age threshold: {} days", self.age_threshold_days());
}
// Clean profile directories
let profile_dirs = find_profile_directories(self.target_dir())?;
for profile_dir in profile_dirs {
log.verbose(1, format!("Cleaning profile directory: {profile_dir:?}"));
let profile_stats = clean_profile_directory(&profile_dir, self, verbose, &stats)?;
stats.bytes_freed += profile_stats.bytes_freed;
stats.artifacts_removed += profile_stats.artifacts_removed;
stats.crates_cleaned += profile_stats.crates_cleaned;
stats.binaries_preserved += profile_stats.binaries_preserved;
}
// Clean other directories (doc, package, tmp)
stats.bytes_freed += clean_misc_directories(self.target_dir(), self, verbose)?;
// Clean cargo registry and downloads
log.verbose(1, "Cleaning cargo registry...");
let registry_stats = self.clean_cargo_registry(verbose)?;
stats.bytes_freed += registry_stats.bytes_freed;
stats.registry_bytes_freed = registry_stats.bytes_freed;
stats.registry_files_removed = registry_stats.files_removed;
stats.registry_dirs_removed = registry_stats.dirs_removed;
// Clean cargo binaries
log.verbose(1, "Cleaning cargo binaries...");
stats.bytes_freed += self.clean_cargo_bin(verbose)?;
// Calculate final size
stats.final_size = calculate_directory_size(self.target_dir())?;
Ok(stats)
}
/// Clean the cargo registry cache (~/.cargo/registry).
///
/// Removes old cached crates and git checkouts based on age threshold.
///
/// # Arguments
///
/// * `verbose` - Verbosity level for output
///
/// # Returns
///
/// Number of bytes freed
pub fn clean_cargo_registry(&self, verbose: u8) -> Result<cargo::CargoRegistryStats> {
let cargo_home = self.cargo_home()?;
self.clean_cargo_registry_with_home(&cargo_home, verbose)
}
/// Clean cargo registry with custom cargo home (for testing)
pub fn clean_cargo_registry_with_home(
&self,
cargo_home: &Path,
verbose: u8,
) -> Result<cargo::CargoRegistryStats> {
cargo::clean_cargo_registry_with_home(self, cargo_home, verbose)
}
/// Clean old binaries from ~/.cargo/bin.
///
/// Removes binaries older than 30 days, except for preserved binaries
/// and those in the default preservation list.
///
/// # Arguments
///
/// * `verbose` - Verbosity level for output
///
/// # Returns
///
/// Number of bytes freed
fn clean_cargo_bin(&self, verbose: u8) -> Result<u64> {
let cargo_home = self.cargo_home()?;
self.clean_cargo_bin_with_home(&cargo_home, verbose)
}
/// Clean cargo bin directory with custom cargo home.
///
/// This variant allows specifying a custom cargo home directory,
/// which is primarily used for testing.
///
/// # Arguments
///
/// * `cargo_home` - The cargo home directory (typically ~/.cargo)
/// * `verbose` - Verbosity level for output
///
/// # Returns
///
/// Number of bytes freed
pub fn clean_cargo_bin_with_home(&self, cargo_home: &Path, verbose: u8) -> Result<u64> {
cargo::clean_cargo_bin_with_home(self, cargo_home, verbose)
}
fn cargo_home(&self) -> Result<PathBuf> {
if let Some(path) = std::env::var_os("CARGO_HOME") {
return Ok(PathBuf::from(path));
}
Ok(home::home_dir()
.ok_or_else(|| HoldError::GcError("Could not determine home directory".to_string()))?
.join(".cargo"))
}
}
impl Default for Gc {
fn default() -> Self {
Self {
target_dir: PathBuf::from("target"),
max_target_size: None,
dry_run: false,
debug: false,
age_threshold_days: 7,
preserve_binaries: Vec::new(),
previous_build_mtime_nanos: None,
quiet: false,
}
}
}
/// Builder for [`Gc`]
#[derive(Debug, Default)]
pub struct GcBuilder {
target_dir: Option<PathBuf>,
max_target_size: Option<u64>,
dry_run: bool,
debug: bool,
age_threshold_days: Option<u32>,
preserve_binaries: Vec<String>,
previous_build_mtime_nanos: Option<u128>,
quiet: bool,
}
impl GcBuilder {
/// Set the target directory
pub fn target_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.target_dir = Some(dir.into());
self
}
/// Set the maximum target size
pub fn max_target_size(mut self, size: u64) -> Self {
self.max_target_size = Some(size);
self
}
/// Enable dry run mode
pub fn dry_run(mut self, enabled: bool) -> Self {
self.dry_run = enabled;
self
}
/// Enable debug mode
pub fn debug(mut self, enabled: bool) -> Self {
self.debug = enabled;
self
}
/// Set the age threshold in days
pub fn age_threshold_days(mut self, days: u32) -> Self {
self.age_threshold_days = Some(days);
self
}
/// Set the list of binaries to preserve
pub fn preserve_binaries(mut self, binaries: Vec<String>) -> Self {
self.preserve_binaries = binaries;
self
}
/// Add a single binary to preserve
pub fn preserve_binary(mut self, binary: impl Into<String>) -> Self {
self.preserve_binaries.push(binary.into());
self
}
/// Set the previous build mtime in nanoseconds
pub fn previous_build_mtime_nanos(mut self, nanos: u128) -> Self {
self.previous_build_mtime_nanos = Some(nanos);
self
}
/// Enable or disable quiet mode
pub fn quiet(mut self, quiet: bool) -> Self {
self.quiet = quiet;
self
}
/// Build the [`Gc`]
pub fn build(self) -> Gc {
Gc {
target_dir: self.target_dir.unwrap_or_else(|| PathBuf::from("target")),
max_target_size: self.max_target_size,
dry_run: self.dry_run,
debug: self.debug,
age_threshold_days: self.age_threshold_days.unwrap_or(7),
preserve_binaries: self.preserve_binaries,
previous_build_mtime_nanos: self.previous_build_mtime_nanos,
quiet: self.quiet,
}
}
}
/// Statistics about the garbage collection operation
#[derive(Debug, Default)]
pub struct GcStats {
/// Total bytes freed
pub bytes_freed: u64,
/// Bytes freed from cargo registry cleanup
pub registry_bytes_freed: u64,
/// Files removed from cargo registry cleanup
pub registry_files_removed: usize,
/// Directories removed from cargo registry cleanup
pub registry_dirs_removed: usize,
/// Number of artifacts removed
pub artifacts_removed: usize,
/// Number of crates cleaned
pub crates_cleaned: usize,
/// Initial target directory size
pub initial_size: u64,
/// Final target directory size
pub final_size: u64,
/// Number of binaries preserved
pub binaries_preserved: usize,
}