cargo-hold 1.3.2

cargo-hold: A CI tool to ensure Cargo's incremental compilation is reliable by managing your caches intelligently
Documentation
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::SystemTime;

use regex::Regex;

use super::size::format_size;
use crate::error::{HoldError, Result};
use crate::logging::Logger;
use crate::timestamp::{saturating_duration_from_nanos, set_file_mtime};

/// Information about a single artifact
#[derive(Debug, Clone)]
pub(crate) struct ArtifactInfo {
    pub(crate) path: PathBuf,
    pub(crate) size: u64,
    pub(crate) _modified: SystemTime,
}

/// A crate artifact group (all related files for a single crate)
#[derive(Debug)]
pub(crate) struct CrateArtifact {
    pub(crate) name: String,
    pub(crate) hash: String,
    pub(crate) artifacts: Vec<ArtifactInfo>,
    pub(crate) total_size: u64,
    pub(crate) newest_mtime: SystemTime,
}

/// Collect all crate artifacts from a profile directory
pub(crate) fn collect_crate_artifacts(profile_dir: &Path) -> Result<Vec<CrateArtifact>> {
    let fingerprint_dir = profile_dir.join(".fingerprint");
    if !fingerprint_dir.exists() {
        return Ok(Vec::new());
    }

    let mut crate_map: HashMap<(String, String), CrateArtifact> = HashMap::new();

    // Scan fingerprint directory to identify crates
    let entries = fs::read_dir(&fingerprint_dir).map_err(|source| HoldError::IoError {
        path: fingerprint_dir.clone(),
        source,
    })?;

    for entry in entries {
        let entry = entry.map_err(|source| HoldError::IoError {
            path: fingerprint_dir.clone(),
            source,
        })?;
        let path = entry.path();

        if path.is_dir()
            && let Some((name, hash)) = parse_crate_artifact_name(&path)
        {
            let key = (name.clone(), hash.clone());
            let crate_artifact = crate_map.entry(key).or_insert_with(|| CrateArtifact {
                name,
                hash,
                artifacts: Vec::new(),
                total_size: 0,
                newest_mtime: SystemTime::UNIX_EPOCH,
            });

            // Add the fingerprint directory itself as an artifact
            add_artifact_file(&path, crate_artifact)?;
        }
    }

    // Now find related artifacts in deps and build directories
    for (subdir, _patterns) in &[("deps", vec!["*"]), ("build", vec!["*"])] {
        let dir = profile_dir.join(subdir);
        if !dir.exists() {
            continue;
        }

        let entries = fs::read_dir(&dir).map_err(|source| HoldError::IoError {
            path: dir.clone(),
            source,
        })?;

        for entry in entries {
            let entry = entry.map_err(|source| HoldError::IoError {
                path: dir.clone(),
                source,
            })?;
            let path = entry.path();

            // Try to match this file to a crate
            if let Some((name, hash)) = parse_crate_artifact_name(&path) {
                let key = (name.clone(), hash.clone());
                if let Some(crate_artifact) = crate_map.get_mut(&key) {
                    add_artifact_file(&path, crate_artifact)?;
                } else {
                    // This file doesn't have a corresponding fingerprint entry
                    // Create a new crate artifact for orphaned files
                    let mut artifact = CrateArtifact {
                        name: name.clone(),
                        hash: hash.clone(),
                        artifacts: Vec::new(),
                        total_size: 0,
                        newest_mtime: SystemTime::UNIX_EPOCH,
                    };
                    add_artifact_file(&path, &mut artifact)?;
                    crate_map.insert(key, artifact);
                }
            }
        }
    }

    Ok(crate_map.into_values().collect())
}

/// Parse a crate artifact filename to extract name and hash
pub(crate) fn parse_crate_artifact_name(path: &Path) -> Option<(String, String)> {
    static CRATE_ARTIFACT_RE: OnceLock<Regex> = OnceLock::new();

    let filename = path.file_name()?.to_str()?;
    let re = CRATE_ARTIFACT_RE.get_or_init(|| {
        Regex::new(r"^(.+)-([0-9a-f]{16})(?:\.|$)").expect("crate artifact regex should compile")
    });
    let captures = re.captures(filename)?;

    Some((captures[1].to_string(), captures[2].to_string()))
}

/// Add artifact files to a crate artifact
fn add_artifact_files(path: &Path, crate_artifact: &mut CrateArtifact) -> Result<()> {
    if path.is_file() {
        add_artifact_file(path, crate_artifact)?;
    } else if path.is_dir() {
        let entries = fs::read_dir(path).map_err(|source| HoldError::IoError {
            path: path.to_path_buf(),
            source,
        })?;

        for entry in entries {
            let entry = entry.map_err(|source| HoldError::IoError {
                path: path.to_path_buf(),
                source,
            })?;
            add_artifact_files(&entry.path(), crate_artifact)?;
        }
    }

    Ok(())
}

/// Add a single artifact file to a crate artifact
fn add_artifact_file(path: &Path, crate_artifact: &mut CrateArtifact) -> Result<()> {
    let metadata = fs::metadata(path).map_err(|source| HoldError::IoError {
        path: path.to_path_buf(),
        source,
    })?;

    // If it's a directory, add all its contents but not the directory itself
    if metadata.is_dir() {
        add_artifact_files(path, crate_artifact)?;
        // Also add the directory itself as an artifact to ensure it gets removed
        let artifact_info = ArtifactInfo {
            path: path.to_path_buf(),
            size: 0,                           // Directories don't have meaningful size
            _modified: SystemTime::UNIX_EPOCH, // Don't use directory mtime for age calculation
        };
        crate_artifact.artifacts.push(artifact_info);
    } else {
        // For files, track their modification time
        let modified = metadata.modified().map_err(|source| HoldError::IoError {
            path: path.to_path_buf(),
            source,
        })?;

        let artifact_info = ArtifactInfo {
            path: path.to_path_buf(),
            size: metadata.len(),
            _modified: modified,
        };

        crate_artifact.total_size += artifact_info.size;
        if modified > crate_artifact.newest_mtime {
            crate_artifact.newest_mtime = modified;
        }

        crate_artifact.artifacts.push(artifact_info);
    }

    Ok(())
}

/// Cutoff used to decide whether an artifact belongs to the previous CI build.
///
/// Returns `None` when previous-build preservation should be skipped entirely.
pub(crate) fn previous_build_preservation_cutoff(
    previous_build_mtime_nanos: Option<u128>,
    age_threshold_days: u32,
) -> Option<SystemTime> {
    let previous_mtime_nanos = previous_build_mtime_nanos?;
    if age_threshold_days == 0 {
        return None;
    }

    let (duration, saturated) = saturating_duration_from_nanos(previous_mtime_nanos);
    if saturated {
        eprintln!(
            "Warning: previous_build_mtime_nanos ({previous_mtime_nanos}) exceeds representable \
             range; clamping to ~year 2554."
        );
    }
    let mut previous_mtime = SystemTime::UNIX_EPOCH + duration;
    let now = SystemTime::now();
    if previous_mtime > now {
        previous_mtime = now;
    }

    let age_threshold = std::time::Duration::from_secs(age_threshold_days as u64 * 24 * 60 * 60);
    let elapsed_since_previous = now
        .duration_since(previous_mtime)
        .unwrap_or(std::time::Duration::ZERO);

    if elapsed_since_previous > age_threshold {
        return None;
    }

    let buffer = std::time::Duration::from_secs(5 * 60);
    Some(
        previous_mtime
            .checked_sub(buffer)
            .unwrap_or(SystemTime::UNIX_EPOCH),
    )
}

/// Refresh artifact mtimes when a restored CI cache has filesystem times older
/// than the last `heave` run.
///
/// GitHub Actions and similar caches often unpack with stale mtimes. Without
/// this pass, `heave` treats every artifact as ancient and deletes the cache
/// you just restored.
pub(crate) fn rejuvenate_stale_artifact_mtimes(
    artifacts: &mut [CrateArtifact],
    previous_build_mtime_nanos: Option<u128>,
    age_threshold_days: u32,
    dry_run: bool,
    verbose: u8,
    quiet: bool,
) -> Result<usize> {
    let log = Logger::new(verbose, quiet);
    let Some(cutoff) =
        previous_build_preservation_cutoff(previous_build_mtime_nanos, age_threshold_days)
    else {
        return Ok(0);
    };

    if artifacts.is_empty() {
        return Ok(0);
    }

    if artifacts
        .iter()
        .any(|artifact| artifact.newest_mtime >= cutoff)
    {
        return Ok(0);
    }

    let age_cutoff = SystemTime::now()
        .checked_sub(std::time::Duration::from_secs(
            age_threshold_days as u64 * 24 * 60 * 60,
        ))
        .unwrap_or(SystemTime::UNIX_EPOCH);

    let refresh_time = SystemTime::now();
    let mut files_touched = 0usize;
    let mut crates_refreshed = 0usize;

    for artifact in artifacts.iter_mut() {
        // Only bump artifacts that look like a recent build with unreliable mtimes.
        // Truly ancient crates stay old so age/size GC can still evict them.
        if artifact.newest_mtime < cutoff && artifact.newest_mtime >= age_cutoff {
            if dry_run {
                files_touched += artifact
                    .artifacts
                    .iter()
                    .filter(|info| info.path.is_file())
                    .count();
                artifact.newest_mtime = refresh_time;
                crates_refreshed += 1;
                continue;
            }

            let mut newest = SystemTime::UNIX_EPOCH;
            for info in &mut artifact.artifacts {
                if info.path.is_file() {
                    set_file_mtime(&info.path, refresh_time)?;
                    info._modified = refresh_time;
                    files_touched += 1;
                    if refresh_time > newest {
                        newest = refresh_time;
                    }
                }
            }
            if newest > artifact.newest_mtime {
                artifact.newest_mtime = newest;
            }
            crates_refreshed += 1;
        }
    }

    if crates_refreshed == 0 {
        return Ok(0);
    }

    if !log.quiet() {
        eprintln!(
            "  Refreshed mtimes on {crates_refreshed} crate artifact(s) with stale cache \
             timestamps"
        );
    }

    log.verbose(
        1,
        format!("  Refreshed mtimes on {files_touched} artifact file(s)"),
    );

    Ok(files_touched)
}

/// Select artifacts to remove based on both size and age constraints
///
/// This function implements a two-phase cleanup strategy:
/// 1. **Size enforcement**: If a size limit is specified and exceeded, removes
///    oldest artifacts first until the target directory is under the limit
/// 2. **Age cleanup**: After size compliance, removes any remaining artifacts
///    older than the specified age threshold
///
/// Both phases are always executed, ensuring consistent and predictable cleanup
/// behavior.
///
/// # Arguments
///
/// * `crate_artifacts` - List of crate artifacts to consider for removal
/// * `current_size` - Current total size of all artifacts in bytes
/// * `max_size` - Optional maximum size limit in bytes
/// * `age_threshold_days` - Age threshold in days (artifacts older than this
///   are removed)
/// * `previous_build_mtime_nanos` - Optional timestamp of the previous build to
///   preserve
/// * `verbose` - Verbosity level for debug output
/// * `quiet` - Suppress logging
///
/// # Returns
///
/// A vector of references to artifacts that should be removed
pub(crate) fn select_artifacts_for_removal(
    crate_artifacts: &[CrateArtifact],
    current_size: u64,
    max_size: Option<u64>,
    age_threshold_days: u32,
    previous_build_mtime_nanos: Option<u128>,
    verbose: u8,
    quiet: bool,
) -> Vec<&CrateArtifact> {
    let remaining = preserve_previous_build_artifacts(
        crate_artifacts.iter().collect(),
        previous_build_mtime_nanos,
        age_threshold_days,
        verbose,
        quiet,
    );

    let (mut to_remove, remaining) = select_for_size(remaining, current_size, max_size, quiet);
    let age_selected = select_for_age(remaining, age_threshold_days, verbose, quiet);
    to_remove.extend(age_selected);

    to_remove
}

fn preserve_previous_build_artifacts(
    artifacts: Vec<&CrateArtifact>,
    previous_build_mtime_nanos: Option<u128>,
    age_threshold_days: u32,
    verbose: u8,
    quiet: bool,
) -> Vec<&CrateArtifact> {
    let log = Logger::new(verbose, quiet);
    if let Some(previous_mtime_nanos) = previous_build_mtime_nanos {
        if let Some(cutoff_time) =
            previous_build_preservation_cutoff(Some(previous_mtime_nanos), age_threshold_days)
        {
            let (preserved, eligible): (Vec<_>, Vec<_>) = artifacts
                .into_iter()
                .partition(|artifact| artifact.newest_mtime >= cutoff_time);

            if !log.quiet() && !preserved.is_empty() {
                let preserved_size: u64 = preserved.iter().map(|a| a.total_size).sum();
                eprintln!(
                    "  Preserving {} artifacts ({}) from previous build",
                    preserved.len(),
                    format_size(preserved_size)
                );
                if log.level() > 1 {
                    for artifact in &preserved {
                        eprintln!("    Preserving: {}-{}", artifact.name, artifact.hash);
                    }
                }
            }

            return eligible;
        }

        log.verbose(
            1,
            "  Skipping previous build preservation (no cutoff; age threshold 0 or last heave too \
             old)",
        );
    }

    artifacts
}

fn select_for_size(
    mut remaining_artifacts: Vec<&CrateArtifact>,
    current_size: u64,
    max_size: Option<u64>,
    quiet: bool,
) -> (Vec<&CrateArtifact>, Vec<&CrateArtifact>) {
    let mut to_remove = Vec::new();
    let log = Logger::new(0, quiet);

    if let Some(max_size) = max_size {
        if !log.quiet() {
            eprintln!(
                "  Size-based cleanup: current={}, max={}",
                format_size(current_size),
                format_size(max_size)
            );
        }

        if current_size > max_size {
            let needed = current_size - max_size;
            if !log.quiet() {
                eprintln!("  Need to free: {}", format_size(needed));
            }

            // Sort by age (oldest first)
            remaining_artifacts.sort_by_key(|a| a.newest_mtime);

            let mut freed = 0u64;
            let mut kept_artifacts = Vec::new();

            for artifact in remaining_artifacts {
                if freed < needed {
                    to_remove.push(artifact);
                    freed += artifact.total_size;
                } else {
                    kept_artifacts.push(artifact);
                }
            }

            remaining_artifacts = kept_artifacts;

            if !log.quiet() {
                eprintln!(
                    "  Size cleanup will remove {} crates, freeing {}",
                    to_remove.len(),
                    format_size(freed)
                );
            }
        } else if !log.quiet() {
            eprintln!("  Already within target size");
        }
    }

    (to_remove, remaining_artifacts)
}

fn select_for_age(
    remaining_artifacts: Vec<&CrateArtifact>,
    age_threshold_days: u32,
    verbose: u8,
    quiet: bool,
) -> Vec<&CrateArtifact> {
    let mut to_remove = Vec::new();
    let log = Logger::new(verbose, quiet);

    if !log.quiet() {
        eprintln!("  Age-based cleanup: removing artifacts older than {age_threshold_days} days");
    }

    let cutoff = SystemTime::now()
        .checked_sub(std::time::Duration::from_secs(
            age_threshold_days as u64 * 24 * 60 * 60,
        ))
        .unwrap_or(SystemTime::UNIX_EPOCH);

    let now = SystemTime::now();
    let mut age_removed_count = 0;
    let mut age_removed_size = 0u64;

    for artifact in remaining_artifacts {
        let age_days = now
            .duration_since(artifact.newest_mtime)
            .map(|d| d.as_secs() / (24 * 60 * 60))
            .unwrap_or(0);

        if artifact.newest_mtime < cutoff {
            log.verbose(
                2,
                format!(
                    "    Removing old crate {}: age={} days",
                    artifact.name, age_days
                ),
            );
            age_removed_count += 1;
            age_removed_size += artifact.total_size;
            to_remove.push(artifact);
        }
    }

    if !log.quiet() {
        eprintln!(
            "  Age cleanup will remove {} additional crates, freeing {}",
            age_removed_count,
            format_size(age_removed_size)
        );
    }

    to_remove
}

/// Remove all artifacts for a crate
pub(crate) fn remove_crate_artifacts(crate_artifact: &CrateArtifact) -> Result<()> {
    for artifact in &crate_artifact.artifacts {
        if artifact.path.exists() {
            if artifact.path.is_dir() {
                fs::remove_dir_all(&artifact.path).map_err(|source| HoldError::IoError {
                    path: artifact.path.clone(),
                    source,
                })?;
            } else {
                fs::remove_file(&artifact.path).map_err(|source| HoldError::IoError {
                    path: artifact.path.clone(),
                    source,
                })?;
            }
        }
    }

    Ok(())
}