cargo-steward 0.2.3

Keeps Cargo build output fast and bounded: stops the debug object-file leak, cleans stale and orphaned build directories, and checks your setup
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Settings, where cargo-steward keeps its files, and parsers for the sizes
//! and durations used in settings.

use std::env;
use std::fs;
use std::io;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

/// Where cargo-steward keeps its settings and bookkeeping:
/// `$CARGO_STEWARD_HOME`, else `$CARGO_HOME/steward`, else `~/.cargo/steward`.
#[derive(Debug, Clone)]
pub struct Paths {
    pub home: PathBuf,
}

impl Paths {
    pub fn resolve() -> Option<Paths> {
        if let Some(dir) = env::var_os("CARGO_STEWARD_HOME").filter(|v| !v.is_empty()) {
            return Some(Paths { home: dir.into() });
        }
        Some(Paths {
            home: cargo_home()?.join("steward"),
        })
    }

    pub fn config(&self) -> PathBuf {
        self.home.join("config.toml")
    }

    /// Append-only record of compiles, written by the wrapper.
    pub fn ledger(&self) -> PathBuf {
        self.home.join("ledger.jsonl")
    }

    /// The ledger, compacted per build directory.
    pub fn registry(&self) -> PathBuf {
        self.home.join("registry.json")
    }

    /// Modified whenever a cleanup starts; its age decides when the next is due.
    pub fn stamp(&self) -> PathBuf {
        self.home.join("gc.stamp")
    }

    /// How long to wait after a cleanup before low free space starts
    /// another, while cleanups free nothing (seconds).
    pub fn gc_backoff(&self) -> PathBuf {
        self.home.join("gc.backoff")
    }

    /// Held by the running cleanup so only one runs at a time.
    pub fn gc_lock(&self) -> PathBuf {
        self.home.join("gc.lock")
    }

    /// When the last applied deduplication started: the next one after a
    /// cleanup only looks at what changed since.
    pub fn dedup_stamp(&self) -> PathBuf {
        self.home.join("dedup.stamp")
    }

    /// Output of automatic cleanups.
    pub fn log(&self) -> PathBuf {
        self.home.join("gc.log")
    }

    /// The lock files compiles hold while `max-compiles` limits them.
    pub fn compile_slots(&self) -> PathBuf {
        self.home.join("compile-slots")
    }
}

/// `$CARGO_HOME`, defaulting to `~/.cargo` as cargo does.
pub fn cargo_home() -> Option<PathBuf> {
    env::var_os("CARGO_HOME")
        .filter(|v| !v.is_empty())
        .map(PathBuf::from)
        .or_else(|| env::var_os("HOME").map(|h| PathBuf::from(h).join(".cargo")))
}

/// The user-wide Cargo config file Cargo reads in `cargo_home`. Cargo reads
/// the older extensionless `config` whenever it exists, even next to a
/// `config.toml` (it warns and ignores `config.toml`), so that one wins
/// unless it is the same file as `config.toml` through a link. Without
/// either, `config.toml`, where a new one goes.
pub fn user_cargo_config(cargo_home: &Path) -> PathBuf {
    let toml = cargo_home.join("config.toml");
    let legacy = cargo_home.join("config");
    if legacy.exists() && !crate::fsutil::same_file(&legacy, &toml) {
        legacy
    } else {
        toml
    }
}

/// The settings file, `config.toml` in [`Paths::home`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct Config {
    /// Wrapper that rustc runs through, such as `sccache`.
    pub inner_wrapper: Option<String>,
    /// Remove the debug object files that each rebuild leaves behind.
    pub leak_fix: bool,
    /// Start a cleanup in the background after builds when one is due.
    pub auto_gc: bool,
    /// How often an automatic cleanup is due.
    pub gc_interval: String,
    /// Directory trees searched for build directories, in addition to the
    /// ones the wrapper has seen.
    pub scan_roots: Vec<PathBuf>,
    /// Remove a build unit (new layout) that no build has used for this long.
    pub unit_idle: String,
    /// Remove a crate's incremental cache that no build has used for this long.
    pub incremental_idle: String,
    /// Remove the old-layout files of a build directory once the new layout
    /// is in use and no old-layout build has run for this long.
    pub legacy_idle: String,
    /// Remove a whole build directory that no build has used for this long.
    pub dir_idle: String,
    /// Remove a build directory this long after every workspace that built
    /// into it was deleted.
    pub orphan_grace: String,
    /// Never remove a whole build directory used more recently than this,
    /// even when the disk is low on space.
    pub recent_guard: String,
    /// When a disk has less free space than this, remove the least recently
    /// used build directories on it...
    pub min_free: String,
    /// ...until it has this much free again.
    pub target_free: String,
    /// `setup` set `build.build-dir`, so `setup --undo` removes it.
    pub managed_build_dir: bool,
    /// The `build.rustc-wrapper` Cargo's config had before `setup` made it
    /// cargo-steward, which `setup --undo` puts back; empty when there was
    /// none. Unset in settings from versions that didn't record it, where
    /// `setup --undo` puts back the inner wrapper instead.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_wrapper: Option<String>,
    /// The `build.build-dir` Cargo's config had before `setup --build-dir`
    /// replaced it, which `setup --undo` puts back; empty when there was
    /// none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previous_build_dir: Option<String>,
    /// Keep replaced object files at most this long while a program
    /// started from their unit's executable runs, so it keeps readable
    /// backtraces.
    pub object_grace: String,
    /// Before removing a whole build directory, check that no running
    /// process was started from it; and keep replaced object files within
    /// `object-grace` only for running programs (when off, for all of it).
    pub process_guard: bool,
    /// Run at most this many compiles at once, machine-wide. Unset or 0 for
    /// no limit.
    pub max_compiles: Option<u32>,
    /// Estimated memory reservations for concurrent compiles; not an RSS cap.
    pub compile_memory_budget: Option<String>,
    /// Reservation for a compile with no direct-compiler RSS observation.
    pub compile_memory_estimate: String,
    /// Record per-unit execution/queue costs alongside build output.
    pub record_costs: bool,
    /// Start a new worktree's build directory as a clone of its repository's
    /// main build directory (copy-on-write; APFS, btrfs, XFS).
    pub seed: bool,
    /// Let cleanup replace identical files across build directories with
    /// copy-on-write clones.
    pub dedup: bool,
    /// For the `cargo` proxy: put each worktree's target directory under
    /// this root, as `<root>/<repo>-<hash>/<worktree>`.
    pub target_root: Option<PathBuf>,
    /// For the `cargo` proxy: point TMPDIR for builds at a per-worktree
    /// directory under this root.
    pub tmp_root: Option<PathBuf>,
    /// For the `cargo` proxy: run at most this many cargo builds at once.
    pub max_builds: Option<u32>,
    /// For the `cargo` proxy: the real cargo to run. Found on PATH if unset.
    pub real_cargo: Option<PathBuf>,
    /// For the `cargo` proxy: when it routes a workspace's build output, also
    /// point a missing `<workspace>/target` at it (when git ignores `target`),
    /// so scripts expecting `./target` and builds that bypass the proxy, such
    /// as an IDE's, land in the same place. Not for forced routes.
    pub link_target: bool,
    /// For the `cargo` proxy: settings for commands run under particular
    /// directories, overriding `target-root`, `tmp-root` and `max-builds`.
    /// The longest matching `path` wins.
    pub routes: Vec<Route>,
}

/// Proxy settings for commands run under one directory tree.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Route {
    /// Applies to commands whose directory is this one or below it.
    pub path: PathBuf,
    /// As the top-level `target-root`; unset routes no target directory.
    #[serde(default)]
    pub target_root: Option<PathBuf>,
    /// As the top-level `tmp-root`.
    #[serde(default)]
    pub tmp_root: Option<PathBuf>,
    /// As the top-level `max-builds`, with its own set of slots.
    #[serde(default)]
    pub max_builds: Option<u32>,
    /// Route even when `CARGO_TARGET_DIR` is already set or a workspace
    /// config sets `build.target-dir`, as a per-invocation shim that always
    /// sets the target dir would. Only `--target-dir` and `--config` on the
    /// command line still win.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub force: bool,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            inner_wrapper: None,
            leak_fix: true,
            auto_gc: false,
            gc_interval: "1h".into(),
            scan_roots: Vec::new(),
            unit_idle: "14d".into(),
            incremental_idle: "7d".into(),
            legacy_idle: "3d".into(),
            dir_idle: "21d".into(),
            orphan_grace: "2d".into(),
            recent_guard: "1d".into(),
            min_free: "50GiB".into(),
            target_free: "100GiB".into(),
            managed_build_dir: false,
            previous_wrapper: None,
            previous_build_dir: None,
            object_grace: "10m".into(),
            process_guard: true,
            max_compiles: None,
            compile_memory_budget: None,
            compile_memory_estimate: "2GiB".into(),
            record_costs: true,
            seed: true,
            dedup: true,
            target_root: None,
            tmp_root: None,
            max_builds: None,
            real_cargo: None,
            routes: Vec::new(),
            link_target: false,
        }
    }
}

/// [`Config`]'s thresholds, parsed.
#[derive(Debug, Clone, Copy)]
pub struct Policy {
    pub gc_interval: Duration,
    pub unit_idle: Duration,
    pub incremental_idle: Duration,
    pub legacy_idle: Duration,
    pub dir_idle: Duration,
    pub orphan_grace: Duration,
    pub recent_guard: Duration,
    pub min_free: u64,
    pub target_free: u64,
    pub object_grace: Duration,
}

impl Config {
    pub fn policy(&self) -> Result<Policy> {
        let duration = |key: &str, value: &str| {
            humantime::parse_duration(value.trim()).with_context(|| format!("{key} = {value:?}"))
        };
        let size = |key: &str, value: &str| {
            parse_size(value).with_context(|| format!("{key} = {value:?}"))
        };
        let policy = Policy {
            gc_interval: duration("gc-interval", &self.gc_interval)?,
            unit_idle: duration("unit-idle", &self.unit_idle)?,
            incremental_idle: duration("incremental-idle", &self.incremental_idle)?,
            legacy_idle: duration("legacy-idle", &self.legacy_idle)?,
            dir_idle: duration("dir-idle", &self.dir_idle)?,
            orphan_grace: duration("orphan-grace", &self.orphan_grace)?,
            recent_guard: duration("recent-guard", &self.recent_guard)?,
            min_free: size("min-free", &self.min_free)?,
            target_free: size("target-free", &self.target_free)?,
            object_grace: duration("object-grace", &self.object_grace)?,
        };
        if policy.target_free < policy.min_free {
            bail!("target-free must be at least min-free");
        }
        if size("compile-memory-estimate", &self.compile_memory_estimate)? == 0 {
            bail!("compile-memory-estimate must be positive");
        }
        if let Some(budget) = &self.compile_memory_budget
            && size("compile-memory-budget", budget)? == 0
        {
            bail!("compile-memory-budget must be positive");
        }
        Ok(policy)
    }
}

/// Reads the settings file. A missing file means the defaults.
pub fn load(paths: &Paths) -> Result<Config> {
    let path = paths.config();
    match fs::read_to_string(&path) {
        Ok(text) => toml::from_str(&text).with_context(|| format!("reading {}", path.display())),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Config::default()),
        Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
    }
}

/// Reads the settings so that each one that's wrong falls back to its
/// default alone, and says what was wrong. For what must run whatever the
/// file holds (the wrapper and the proxy run every build) and for reports:
/// a typo in one setting no longer silently drops `inner-wrapper` (sccache)
/// and `auto-gc` with it. A file that isn't TOML at all gives the defaults.
pub fn load_lenient(paths: &Paths) -> (Config, Vec<String>) {
    let path = paths.config();
    match fs::read_to_string(&path) {
        Ok(text) => lenient(&text, &path),
        Err(e) if e.kind() == io::ErrorKind::NotFound => (Config::default(), Vec::new()),
        Err(e) => (
            Config::default(),
            vec![format!(
                "reading {}: {e}; using the defaults",
                path.display()
            )],
        ),
    }
}

/// [`Config`] and its thresholds ([`Config::policy`]) from `table`.
fn parse_table(table: &toml::Table) -> std::result::Result<Config, String> {
    let config: Config = toml::Value::Table(table.clone())
        .try_into()
        .map_err(|e: toml::de::Error| e.message().to_owned())?;
    config.policy().map_err(|e| format!("{e:#}"))?;
    Ok(config)
}

fn lenient(text: &str, path: &std::path::Path) -> (Config, Vec<String>) {
    let table: toml::Table = match text.parse() {
        Ok(table) => table,
        Err(e) => {
            return (
                Config::default(),
                vec![format!(
                    "{} isn't valid TOML ({}); using the defaults",
                    path.display(),
                    e.message()
                )],
            );
        }
    };
    // Settings are taken one at a time, in rounds, so one that only fits
    // with another (`target-free` above a raised `min-free`) still counts.
    let mut accepted = toml::Table::new();
    let mut config = Config::default();
    let mut pending: Vec<(String, toml::Value, String)> = table
        .into_iter()
        .map(|(key, value)| (key, value, String::new()))
        .collect();
    loop {
        let before = pending.len();
        pending.retain_mut(|(key, value, error)| {
            let mut candidate = accepted.clone();
            candidate.insert(key.clone(), value.clone());
            match parse_table(&candidate) {
                Ok(parsed) => {
                    accepted = candidate;
                    config = parsed;
                    false
                }
                Err(e) => {
                    *error = e;
                    true
                }
            }
        });
        if pending.is_empty() || pending.len() == before {
            break;
        }
    }
    let mut problems: Vec<String> = pending
        .into_iter()
        .map(|(key, _, error)| format!("{key}: {error}; using the default"))
        .collect();
    // A key that changes nothing and isn't one cargo-steward writes back is
    // one it doesn't know: most likely a typo.
    let known: std::collections::BTreeSet<String> = toml::Value::try_from(&config)
        .ok()
        .and_then(|v| v.as_table().map(|t| t.keys().cloned().collect()))
        .unwrap_or_default();
    for key in accepted.keys().filter(|k| !known.contains(*k)) {
        let mut without = accepted.clone();
        without.remove(key);
        if parse_table(&without).is_ok_and(|c| c == config) {
            problems.push(format!("{key}: not a cargo-steward setting; ignored"));
        }
    }
    (config, problems)
}

/// [`load_lenient`], printing what was wrong as warnings.
pub fn load_warning(paths: &Paths) -> Config {
    let (config, problems) = load_lenient(paths);
    for problem in problems {
        eprintln!("warning: cargo-steward: settings: {problem}");
    }
    config
}

pub fn save(paths: &Paths, config: &Config) -> Result<()> {
    fs::create_dir_all(&paths.home)
        .with_context(|| format!("creating {}", paths.home.display()))?;
    let text = toml::to_string_pretty(config)?;
    write_atomic(&paths.config(), text.as_bytes())
}

/// Writes through a temporary file and a rename, so readers never see a
/// partial file. A symlink is written through, so it stays a link to the
/// replaced file (as dotfile managers set up), and the replaced file's
/// permissions are kept.
pub fn write_atomic(path: &Path, contents: &[u8]) -> Result<()> {
    let path = resolve_links(path);
    let permissions = fs::metadata(&path)
        .ok()
        .filter(fs::Metadata::is_file)
        .map(|m| m.permissions());
    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
    if let Err(e) = write_with_permissions(&tmp, contents, permissions.as_ref()) {
        let _ = fs::remove_file(&tmp);
        return Err(e).with_context(|| format!("writing {}", tmp.display()));
    }
    if let Err(e) = fs::rename(&tmp, &path) {
        let _ = fs::remove_file(&tmp);
        return Err(e).with_context(|| format!("writing {}", path.display()));
    }
    Ok(())
}

/// Writes `contents` to `path`, giving a file it creates `permissions` (if
/// any) from the start, so it is never readable by more than it should be.
pub fn write_with_permissions(
    path: &Path,
    contents: &[u8],
    permissions: Option<&fs::Permissions>,
) -> io::Result<()> {
    let mut options = fs::OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    if let Some(permissions) = permissions {
        use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
        options.mode(permissions.mode());
    }
    let mut file = options.open(path)?;
    file.write_all(contents)?;
    // The mode given at creation is reduced by the umask, and an existing
    // file keeps its own.
    if let Some(permissions) = permissions {
        file.set_permissions(permissions.clone())?;
    }
    Ok(())
}

/// The file `path` finally names after following symlinks, which need not
/// exist yet. Gives up after as many links as the system would follow.
fn resolve_links(path: &Path) -> PathBuf {
    let mut path = path.to_path_buf();
    for _ in 0..40 {
        let Ok(target) = fs::read_link(&path) else {
            break;
        };
        // An absolute target replaces the whole path.
        path = match path.parent() {
            Some(dir) => dir.join(target),
            None => target,
        };
    }
    path
}

/// Parses sizes like `50GiB`, `100G`, `512MiB` or `1024`. Units are binary
/// whether or not they say so.
pub fn parse_size(text: &str) -> Result<u64> {
    let text = text.trim();
    let split = text
        .find(|c: char| !(c.is_ascii_digit() || c == '.'))
        .unwrap_or(text.len());
    let (number, unit) = text.split_at(split);
    let value: f64 = number.parse().context("expected a number")?;
    let multiplier: u64 = match unit.trim().to_ascii_lowercase().as_str() {
        "" | "b" => 1,
        "k" | "kb" | "kib" => 1 << 10,
        "m" | "mb" | "mib" => 1 << 20,
        "g" | "gb" | "gib" => 1 << 30,
        "t" | "tb" | "tib" => 1 << 40,
        other => bail!("unknown unit {other:?}"),
    };
    Ok((value * multiplier as f64) as u64)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_sizes() {
        assert_eq!(parse_size("1024").unwrap(), 1024);
        assert_eq!(parse_size("50GiB").unwrap(), 50 << 30);
        assert_eq!(parse_size(" 1.5 G ").unwrap(), 3 << 29);
        assert_eq!(parse_size("2tb").unwrap(), 2 << 40);
        assert!(parse_size("ten").is_err());
        assert!(parse_size("5 parsecs").is_err());
    }

    #[test]
    fn defaults_parse_and_round_trip() {
        let config = Config::default();
        config.policy().unwrap();
        let text = toml::to_string_pretty(&config).unwrap();
        assert_eq!(toml::from_str::<Config>(&text).unwrap(), config);
    }

    #[test]
    fn partial_files_keep_the_other_defaults() {
        let config: Config = toml::from_str("auto-gc = true\ndir-idle = \"7d\"\n").unwrap();
        assert!(config.auto_gc);
        assert_eq!(config.dir_idle, "7d");
        assert_eq!(config.unit_idle, Config::default().unit_idle);
    }

    #[test]
    fn rejects_inverted_free_space_thresholds() {
        let config = Config {
            min_free: "100G".into(),
            target_free: "50G".into(),
            ..Config::default()
        };
        assert!(config.policy().is_err());
    }

    #[test]
    fn keeps_every_file_in_the_home_directory() {
        let paths = Paths {
            home: PathBuf::from("/s"),
        };
        assert_eq!(paths.config(), PathBuf::from("/s/config.toml"));
        assert_eq!(paths.ledger(), PathBuf::from("/s/ledger.jsonl"));
        assert_eq!(paths.registry(), PathBuf::from("/s/registry.json"));
        assert_eq!(paths.stamp(), PathBuf::from("/s/gc.stamp"));
        assert_eq!(paths.gc_lock(), PathBuf::from("/s/gc.lock"));
        assert_eq!(paths.log(), PathBuf::from("/s/gc.log"));
        assert_eq!(paths.compile_slots(), PathBuf::from("/s/compile-slots"));
    }

    #[test]
    fn saves_loads_and_reports_unreadable_settings() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = Paths {
            home: tmp.path().join("steward"),
        };
        assert_eq!(load(&paths).unwrap(), Config::default());
        let config = Config {
            auto_gc: true,
            scan_roots: vec!["/v".into()],
            ..Config::default()
        };
        save(&paths, &config).unwrap();
        assert_eq!(load(&paths).unwrap(), config);
        // Only the settings file is left; the temporary one was renamed.
        let names: Vec<_> = fs::read_dir(&paths.home).unwrap().flatten().collect();
        assert_eq!(names.len(), 1);

        fs::write(paths.config(), "auto-gc = \"yes\"\n").unwrap();
        let err = format!("{:#}", load(&paths).unwrap_err());
        assert!(err.contains("reading"), "{err}");

        fs::remove_file(paths.config()).unwrap();
        fs::create_dir(paths.config()).unwrap();
        assert!(load(&paths).is_err(), "a directory isn't a missing file");
    }

    #[test]
    fn names_the_setting_that_doesnt_parse() {
        let config = Config {
            dir_idle: "soon".into(),
            ..Config::default()
        };
        let err = format!("{:#}", config.policy().unwrap_err());
        assert!(err.contains("dir-idle = \"soon\""), "{err}");
        let config = Config {
            min_free: "lots".into(),
            ..Config::default()
        };
        let err = format!("{:#}", config.policy().unwrap_err());
        assert!(err.contains("min-free"), "{err}");

        let bad = || "never".to_string();
        type Set = fn(&mut Config, String);
        let cases: [(&str, Set); 8] = [
            ("gc-interval", |c, v| c.gc_interval = v),
            ("unit-idle", |c, v| c.unit_idle = v),
            ("incremental-idle", |c, v| c.incremental_idle = v),
            ("legacy-idle", |c, v| c.legacy_idle = v),
            ("orphan-grace", |c, v| c.orphan_grace = v),
            ("recent-guard", |c, v| c.recent_guard = v),
            ("target-free", |c, v| c.target_free = v),
            ("object-grace", |c, v| c.object_grace = v),
        ];
        for (key, set) in cases {
            let mut config = Config::default();
            set(&mut config, bad());
            let err = format!("{:#}", config.policy().unwrap_err());
            assert!(err.contains(&format!("{key} = \"never\"")), "{err}");
        }
    }

    #[test]
    fn parses_every_unit() {
        assert_eq!(parse_size("3b").unwrap(), 3);
        assert_eq!(parse_size("2k").unwrap(), 2 << 10);
        assert_eq!(parse_size("2KiB").unwrap(), 2 << 10);
        assert_eq!(parse_size("5mb").unwrap(), 5 << 20);
        assert_eq!(parse_size("1t").unwrap(), 1 << 40);
    }

    #[test]
    fn reports_settings_that_cant_be_written() {
        let tmp = tempfile::tempdir().unwrap();
        // The home is a file, so it can't be created as a directory.
        let file = tmp.path().join("file");
        fs::write(&file, "x").unwrap();
        let err = format!(
            "{:#}",
            save(&Paths { home: file.clone() }, &Config::default()).unwrap_err()
        );
        assert!(err.contains("creating"), "{err}");

        // No directory to write the temporary file in.
        let err = format!(
            "{:#}",
            write_atomic(&tmp.path().join("missing/config.toml"), b"x").unwrap_err()
        );
        assert!(err.contains("writing"), "{err}");

        // A non-empty directory where the file goes can't be replaced, and
        // the temporary file is still named in the error.
        let dir = tmp.path().join("config.toml");
        fs::create_dir_all(dir.join("inside")).unwrap();
        let err = format!("{:#}", write_atomic(&dir, b"x").unwrap_err());
        assert!(err.contains(&format!("writing {}", dir.display())), "{err}");
        assert!(dir.join("inside").is_dir());
        // The temporary file isn't left behind.
        let names: Vec<_> = fs::read_dir(tmp.path()).unwrap().flatten().collect();
        assert_eq!(names.len(), 2, "{names:?}");
    }

    fn lenient_str(text: &str) -> (Config, Vec<String>) {
        lenient(text, std::path::Path::new("config.toml"))
    }

    #[test]
    fn a_bad_setting_falls_back_alone() {
        let (config, problems) = lenient_str(
            "inner-wrapper = \"sccache\"\nauto-gc = \"yes\"\ndir-idle = \"soon\"\n\
             unit-idle = \"3d\"\n",
        );
        assert_eq!(config.inner_wrapper.as_deref(), Some("sccache"));
        assert_eq!(config.unit_idle, "3d");
        assert!(!config.auto_gc, "the default");
        assert_eq!(config.dir_idle, Config::default().dir_idle);
        assert_eq!(problems.len(), 2, "{problems:?}");
        assert!(problems.iter().any(|p| p.starts_with("auto-gc:")));
        assert!(problems.iter().any(|p| p.starts_with("dir-idle:")));
    }

    #[test]
    fn settings_that_only_fit_together_are_both_kept() {
        let (config, problems) = lenient_str("target-free = \"300G\"\nmin-free = \"200G\"\n");
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(config.min_free, "200G");
        assert_eq!(config.target_free, "300G");
    }

    #[test]
    fn unknown_settings_and_broken_files_are_reported() {
        let (config, problems) = lenient_str("auto-gc = true\nmax_builds = 3\n");
        assert!(config.auto_gc);
        assert_eq!(config.max_builds, None);
        assert_eq!(
            problems,
            ["max_builds: not a cargo-steward setting; ignored"]
        );
        // A setting given its default value is still a known one.
        assert!(lenient_str("leak-fix = true\n").1.is_empty());

        let (config, problems) = lenient_str("auto-gc = \n");
        assert_eq!(config, Config::default());
        assert_eq!(problems.len(), 1);
        assert!(problems[0].contains("isn't valid TOML"), "{problems:?}");

        let tmp = tempfile::tempdir().unwrap();
        let paths = Paths {
            home: tmp.path().to_path_buf(),
        };
        assert_eq!(load_lenient(&paths), (Config::default(), Vec::new()));
    }

    #[test]
    fn the_compile_limit_round_trips_and_loads_leniently() {
        let config = Config {
            max_compiles: Some(4),
            ..Config::default()
        };
        let text = toml::to_string_pretty(&config).unwrap();
        assert!(text.contains("max-compiles = 4"), "{text}");
        assert_eq!(toml::from_str::<Config>(&text).unwrap(), config);
        assert_eq!(Config::default().max_compiles, None);

        let (config, problems) = lenient_str("max-compiles = 2\n");
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(config.max_compiles, Some(2));
        // Zero means no limit, and is still a known setting.
        let (config, problems) = lenient_str("max-compiles = 0\n");
        assert!(problems.is_empty(), "{problems:?}");
        assert_eq!(config.max_compiles, Some(0));
        let (config, problems) = lenient_str("max-compiles = -1\nauto-gc = true\n");
        assert_eq!(config.max_compiles, None);
        assert!(config.auto_gc);
        assert_eq!(problems.len(), 1, "{problems:?}");
        assert!(problems[0].starts_with("max-compiles:"), "{problems:?}");
    }

    /// A symlinked config stays a link to the file it names, and a private
    /// file stays private.
    #[cfg(unix)]
    #[test]
    fn writes_through_links_and_keeps_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
        let dotfiles = tmp.path().join("dotfiles");
        fs::create_dir_all(&dotfiles).unwrap();
        let real = dotfiles.join("cargo.toml");
        fs::write(&real, "old").unwrap();
        fs::set_permissions(&real, fs::Permissions::from_mode(0o600)).unwrap();
        let home = tmp.path().join("home");
        fs::create_dir_all(&home).unwrap();
        let link = home.join("config.toml");
        // A relative link, resolved against the link's directory.
        std::os::unix::fs::symlink("../dotfiles/cargo.toml", &link).unwrap();

        write_atomic(&link, b"new").unwrap();
        assert!(fs::symlink_metadata(&link).unwrap().is_symlink());
        assert_eq!(fs::read_to_string(&real).unwrap(), "new");
        assert_eq!(mode(&real), 0o600);
        assert_eq!(fs::read_dir(&home).unwrap().count(), 1);
        assert_eq!(fs::read_dir(&dotfiles).unwrap().count(), 1);

        // A link to a file that doesn't exist yet creates that file.
        let dangling = home.join("other.toml");
        std::os::unix::fs::symlink(dotfiles.join("new.toml"), &dangling).unwrap();
        write_atomic(&dangling, b"x").unwrap();
        assert!(fs::symlink_metadata(&dangling).unwrap().is_symlink());
        assert_eq!(fs::read_to_string(dotfiles.join("new.toml")).unwrap(), "x");

        // Permissions given to a new file apply from the start.
        let private = tmp.path().join("private");
        write_with_permissions(&private, b"x", Some(&fs::Permissions::from_mode(0o600))).unwrap();
        assert_eq!(mode(&private), 0o600);
    }

    /// Settings files written before setup recorded what it replaced still
    /// load, and an unset record isn't written.
    #[test]
    fn records_of_what_setup_replaced_are_optional() {
        let config: Config = toml::from_str("managed-build-dir = true\n").unwrap();
        assert_eq!(config.previous_wrapper, None);
        assert_eq!(config.previous_build_dir, None);
        let text = toml::to_string_pretty(&Config::default()).unwrap();
        assert!(!text.contains("previous"), "{text}");
        let config = Config {
            previous_wrapper: Some(String::new()),
            previous_build_dir: Some("/b/{workspace-path-hash}".into()),
            ..Config::default()
        };
        let text = toml::to_string_pretty(&config).unwrap();
        assert!(text.contains("previous-wrapper = \"\""), "{text}");
        assert!(text.contains("previous-build-dir = "), "{text}");
        assert_eq!(toml::from_str::<Config>(&text).unwrap(), config);
    }

    /// Cargo reads the extensionless `config` whenever it exists.
    #[test]
    fn finds_the_user_cargo_config_cargo_reads() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        assert_eq!(user_cargo_config(home), home.join("config.toml"));
        fs::write(home.join("config.toml"), "").unwrap();
        assert_eq!(user_cargo_config(home), home.join("config.toml"));
        fs::write(home.join("config"), "").unwrap();
        assert_eq!(user_cargo_config(home), home.join("config"));
        fs::remove_file(home.join("config.toml")).unwrap();
        assert_eq!(user_cargo_config(home), home.join("config"));
        // `config` linked to `config.toml` (for older cargos) is config.toml.
        #[cfg(unix)]
        {
            fs::remove_file(home.join("config")).unwrap();
            fs::write(home.join("config.toml"), "").unwrap();
            std::os::unix::fs::symlink("config.toml", home.join("config")).unwrap();
            assert_eq!(user_cargo_config(home), home.join("config.toml"));
        }
    }
}