epicenter-cli 0.0.3

The state layer for Cargo builds: shared cache, durable vault, per-job dirs
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
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
//! Editing Cargo's global `config.toml` — the single source of truth.
//!
//! epicenter keeps NO state file of its own: the shared-cache decision lives
//! in `$CARGO_HOME/config.toml` as the `[build] build-dir` key, where cargo
//! (and any other tool) can read it. epicenter writes that key (`setup`),
//! reads it back, and verifies it (`doctor`).

use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};

use crate::paths::{self, DEFAULT_BUILD_DIR};

/// The effective shared-cache root. This is the **global** trust anchor
/// (`$CARGO_HOME/config.toml`, or the canonical default); project configs are
/// read only to detect and refuse a shadowing `build-dir`. `cargo metadata`
/// is deliberately not executed (it would trust/execute project config).
pub fn cache_root() -> Result<PathBuf> {
    // Security: never ask `cargo metadata` in the current directory. In a
    // repository, project `.cargo/config.toml` (including `build.rustc`)
    // is attacker-controlled and would both redirect the vault and execute
    // code during resolution. The global `$CARGO_HOME/config.toml` is the
    // only trust anchor.
    let trusted = trusted_cache_root()?;
    if let Some((path, value)) = project_build_dir_override()? {
        let global =
            cargo_configured("build-dir")?.unwrap_or_else(|| DEFAULT_BUILD_DIR.to_string());
        if value != global {
            anyhow::bail!(
                "refusing a project-controlled cache root: {} sets build-dir = {:?}, but the trusted global build-dir is {:?}. Move the decision to $CARGO_HOME/config.toml; epicenter never uses a project-controlled vault.",
                path.display(),
                value,
                global
            );
        }
    }
    Ok(trusted)
}

/// The effective project config is the deepest ancestor `.cargo/config*`.
/// Read it as text (never execute it); a differing `build-dir` is refused.
fn project_build_dir_override() -> Result<Option<(PathBuf, String)>> {
    let global = cargo_config_path().ok();
    let cwd = std::env::current_dir().context("resolving the current directory")?;
    for dir in cwd.ancestors() {
        for name in ["config.toml", "config"] {
            let candidate = dir.join(".cargo").join(name);
            if global.as_ref() == Some(&candidate) || !candidate.is_file() {
                continue;
            }
            let Ok(text) = crate::util::read_small_text_follow(&candidate, 1024 * 1024) else {
                continue;
            };
            if let Some(value) = read_build_key(&text, "build-dir") {
                return Ok(Some((candidate, value)));
            }
        }
    }
    Ok(None)
}

/// The trusted root: the global `$CARGO_HOME/config.toml` `build-dir` value,
/// or the canonical default template. Never reads a project config.
pub fn trusted_cache_root() -> Result<PathBuf> {
    let value = cargo_configured("build-dir")?.unwrap_or_else(|| DEFAULT_BUILD_DIR.to_string());
    paths::resolve_template(&value)
}

/// Config values are written inside single-quoted TOML strings. Reject the
/// characters that can break out of the literal or start a new key/line.
fn validate_config_value(value: &str, what: &str) -> Result<()> {
    if value.contains(['\n', '\r', '\0', '\'']) {
        anyhow::bail!("{what} contains a forbidden character (newline, NUL or single quote)");
    }
    Ok(())
}

/// Cargo's *global* config file: `$CARGO_HOME/config.toml`.
/// Settings there apply to every project on the machine.
pub fn cargo_config_path() -> Result<PathBuf> {
    Ok(paths::cargo_home()?.join("config.toml"))
}

/// What an edit to Cargo's config changed.
#[derive(Debug, PartialEq, Eq)]
pub enum CargoEdit {
    /// The file did not exist and was created.
    Created,
    /// The key was added to an existing `[build]` table.
    Inserted,
    /// The key existed with a different value and was replaced.
    Replaced,
    /// The key existed and was deleted.
    Removed,
    /// Nothing needed changing.
    AlreadySet,
    /// The key was appendend at the end of the toml file
    Appended,
}

impl CargoEdit {
    pub fn describe(&self) -> &'static str {
        match self {
            CargoEdit::Created => "created the file",
            CargoEdit::Inserted => "added",
            CargoEdit::Replaced => "updated",
            CargoEdit::Removed => "removed",
            CargoEdit::AlreadySet => "already set, unchanged",
            CargoEdit::Appended => "appended line at the EOF",
        }
    }
}

/// Sets `key = 'value'` inside the `[build]` table of a Cargo config,
/// as pure text surgery so user comments and formatting survive untouched.
fn set_build_key(text: &str, key: &str, value: &str) -> (String, CargoEdit) {
    let wanted = format!("{key} = '{value}'");
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();

    // Exact header match (whitespace-insensitive) — `.contains("[build]")`
    // would also match comments or sub-table names.
    let header = lines
        .iter()
        .position(|l| l.trim().replace([' ', '\t'], "") == "[build]");

    match header {
        Some(i) => {
            // Scan to the next table header: that is the whole [build] table.
            let mut j = i + 1;
            while j < lines.len() {
                let t = lines[j].trim();
                if t.starts_with('[') && t.ends_with(']') {
                    break;
                }
                if t.split_once('=').map_or(false, |(k, _)| k.trim() == key) {
                    if t == wanted {
                        return (text.to_string(), CargoEdit::AlreadySet);
                    }
                    lines[j] = wanted;
                    return (lines.join("\n") + "\n", CargoEdit::Replaced);
                }
                j += 1;
            }
            lines.insert(i + 1, wanted);
            (lines.join("\n") + "\n", CargoEdit::Inserted)
        }
        None => {
            let needs_blank = lines.last().map_or(false, |l| !l.trim().is_empty());
            if needs_blank {
                lines.push(String::new());
            }
            lines.push("[build]".to_string());
            lines.push(wanted);
            (lines.join("\n") + "\n", CargoEdit::Appended)
        }
    }
}

/// delete `key = ...` from the `[build]` table, if present.
fn remove_build_key(text: &str, key: &str) -> (String, CargoEdit) {
    let mut out: Vec<String> = Vec::new();
    let mut in_build = false;
    let mut removed = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            in_build = trimmed.replace([' ', '\t'], "") == "[build]";
            out.push(line.to_string());
            continue;
        }
        if in_build
            && trimmed
                .split_once('=')
                .map_or(false, |(candidate, _)| candidate.trim() == key)
        {
            removed = true;
            continue;
        }
        out.push(line.to_string());
    }
    if removed {
        (out.join("\n") + "\n", CargoEdit::Removed)
    } else {
        (text.to_string(), CargoEdit::AlreadySet)
    }
}
/// Parse the value of `key` out of the `[build]` table.
fn read_build_key(text: &str, key: &str) -> Option<String> {
    read_table_key(text, "build", key)
}

/// Strip a trailing `#` comment while respecting single/double quoted values.
fn strip_toml_comment(value: &str) -> &str {
    let mut quote: Option<char> = None;
    let mut escaped = false;
    for (index, ch) in value.char_indices() {
        if escaped {
            escaped = false;
            continue;
        }
        match quote {
            Some(q) => {
                if ch == '\\' && q == '"' {
                    escaped = true;
                } else if ch == q {
                    quote = None;
                }
            }
            None => {
                if ch == '#' {
                    return &value[..index];
                }
                if ch == '"' || ch == '\'' {
                    quote = Some(ch);
                }
            }
        }
    }
    value
}

/// Parse `key = value` out of any `[table]` of a cargo config text.
///
/// Only the exact table is scanned (until the next header line); a trailing
/// comment is stripped and surrounding quotes are removed.
pub fn read_table_key(text: &str, table: &str, key: &str) -> Option<String> {
    let header = format!("[{table}]");
    let mut in_table = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            in_table = trimmed.replace([' ', '\t'], "") == header;
            continue;
        }
        if !in_table {
            continue;
        }
        if let Some((candidate, value)) = trimmed.split_once('=') {
            if candidate.trim() != key {
                continue;
            }
            let value = strip_toml_comment(value).trim();
            let value = value
                .strip_prefix('\'')
                .and_then(|v| v.strip_suffix('\''))
                .or_else(|| value.strip_prefix('"').and_then(|v| v.strip_suffix('"')))
                .unwrap_or(value);
            return Some(value.trim().to_string());
        }
    }
    None
}

/// Look up a key in any table of Cargo's *global* config file.
pub fn cargo_configured_in(table: &str, key: &str) -> Result<Option<String>> {
    let path = cargo_config_path()?;
    if !path.exists() {
        return Ok(None);
    }
    let text = crate::util::read_small_text_follow(&path, 1024 * 1024)?;
    Ok(read_table_key(&text, table, key))
}

/// Look up a `[build]` key in Cargo's *global* config file on disk.
pub fn cargo_configured(key: &str) -> Result<Option<String>> {
    let path = cargo_config_path()?;
    if !path.exists() {
        return Ok(None);
    }
    let text = crate::util::read_small_text_follow(&path, 1024 * 1024)?;
    Ok(read_build_key(&text, key))
}

/// Read a `[build]` key from ANY cargo config file — doctor uses this to scan
/// the ancestor `.cargo/config.toml` chain for shadowing values. Read-only.
pub fn read_build_table_key(path: &Path, key: &str) -> Option<String> {
    let text = crate::util::read_small_text_follow(path, 1024 * 1024).ok()?;
    read_build_key(&text, key)
}

pub struct SetupReport {
    /// Where the shared cache now lives.
    pub root: PathBuf,
    /// What happened to the `build-dir` setting.
    pub build_dir_edit: CargoEdit,
    /// What happened to the `rustc-wrapper` (kache/sccache) setting, if touched.
    pub wrapper_edit: Option<CargoEdit>,
    /// Backup of the previous cargo config, if it was modified.
    pub backup: Option<PathBuf>,
    /// Is the override mode active (vs the canonical template)?
    pub using_override: bool,
}

/// The full `epicenter setup` orchestration: compute the decision, make the
/// directory, and write/merge the cargo config.
/// Normalize a user-provided `--cache-root` value.
///
/// - cargo template strings (`{…}`) pass through untouched — they resolve at
///   build time via cargo, exactly like the default template;
/// - `~` expands to the home directory;
/// - relative paths resolve against the current directory;
/// - absolute paths stay as-is.
pub fn normalize_root_input(raw: &str) -> Result<PathBuf> {
    let raw = raw.trim();
    anyhow::ensure!(!raw.is_empty(), "--cache-root must not be empty");
    if raw.contains('{') && raw.contains('}') {
        return Ok(PathBuf::from(raw)); // template passthrough
    }
    let home = paths::home()?;
    if raw == "~" || raw.starts_with("~/") || raw.starts_with("~\\") {
        let rest = raw[1..].trim_start_matches(['/', '\\']);
        return Ok(home.join(rest));
    }
    let path = PathBuf::from(raw);
    if path.is_absolute() {
        return Ok(path);
    }
    let cwd = std::env::current_dir().context("resolving a relative --cache-root")?;
    Ok(cwd.join(path))
}

/// Priority: CLI root > stored override (`~/.epicenter/config.toml`) > default
/// template. `--cache-root` and `--use-default` rewrite the stored decision;
/// without them the stored decision (if any) stays untouched.
pub fn setup(
    root_arg: Option<&str>,
    use_default: bool,
    with_wrapper: Option<&str>,
    without_wrapper: bool,
) -> Result<SetupReport> {
    // Decision precedence: CLI root > the value already in cargo's config >
    // the canonical default template. `--cache-root` / `--use-default`
    // REWRITE the cargo-config decision; without them it stays untouched.
    // There is no epicenter side-file — `~/.cargo/config.toml` is the state.
    let build_dir_value: String = if let Some(raw) = root_arg {
        normalize_root_input(raw)?.to_string_lossy().into_owned()
    } else if use_default {
        DEFAULT_BUILD_DIR.to_string()
    } else {
        cargo_configured("build-dir")?.unwrap_or_else(|| DEFAULT_BUILD_DIR.to_string())
    };

    validate_config_value(&build_dir_value, "build-dir")?;
    if let Some(name) = with_wrapper {
        validate_config_value(name, "rustc-wrapper")?;
    }

    // The filesystem view must always be RESOLVED (a template is not a path).
    let root = paths::resolve_template(&build_dir_value)?;
    crate::util::create_private_dir_all(&root)
        .with_context(|| format!("creating cache dir {}", root.display()))?;

    // No epicenter side-file: the decision itself is the cargo config below.
    let cargo_cfg = cargo_config_path()?;
    let (build_dir_edit, wrapper_edit, backup) = if !cargo_cfg.exists() {
        if let Some(parent) = cargo_cfg.parent() {
            fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
        }
        let mut text = format!("[build]\nbuild-dir = '{build_dir_value}'\n");
        let wrapper_edit = if let Some(name) = with_wrapper {
            text.push_str(&format!("rustc-wrapper = '{name}'\n"));
            Some(CargoEdit::Inserted)
        } else {
            None
        };
        fs::write(&cargo_cfg, text)?;
        (CargoEdit::Created, wrapper_edit, None)
    } else {
        let text = crate::util::read_small_text_follow(&cargo_cfg, 1024 * 1024)
            .with_context(|| format!("reading {}", cargo_cfg.display()))?;
        let (text, build_dir_edit) = set_build_key(&text, "build-dir", &build_dir_value);
        let (text, wrapper_edit) = match with_wrapper {
            Some(name) => {
                let (text, edit) = set_build_key(&text, "rustc-wrapper", name);
                (text, Some(edit))
            }
            None if without_wrapper => {
                let (text, edit) = remove_build_key(&text, "rustc-wrapper");
                (text, Some(edit))
            }
            None => (text, None),
        };
        let mut backup = None;
        let changed = build_dir_edit != CargoEdit::AlreadySet
            || wrapper_edit
                .as_ref()
                .is_some_and(|e| *e != CargoEdit::AlreadySet);
        if changed {
            backup = Some(backup_file(&cargo_cfg)?);
            fs::write(&cargo_cfg, text)
                .with_context(|| format!("writing {}", cargo_cfg.display()))?;
        }
        (build_dir_edit, wrapper_edit, backup)
    };

    Ok(SetupReport {
        root,
        build_dir_edit,
        wrapper_edit,
        backup,
        using_override: build_dir_value != DEFAULT_BUILD_DIR,
    })
}

/// Copy `path` to `path.epicenter-bak` before modifying it.
fn backup_file(path: &Path) -> Result<PathBuf> {
    let mut name = path.file_name().unwrap_or_default().to_os_string();
    name.push(".epicenter-bak");
    let base = path.with_file_name(name);
    // Never write through a pre-existing symlink; pick a fresh name instead.
    let mut backup = base.clone();
    let mut suffix = 0u32;
    while fs::symlink_metadata(&backup).is_ok() {
        suffix += 1;
        let mut name = base.file_name().unwrap_or_default().to_os_string();
        name.push(format!(".{suffix}"));
        backup = base.with_file_name(name);
    }
    // Follow a user's dotfile symlink deliberately, but create the backup
    // itself with O_EXCL (never write through a planted backup symlink).
    let source = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    crate::util::copy_file_hashed(&source, &backup)
        .with_context(|| format!("backing up {}", path.display()))?;
    if let Ok(meta) = fs::metadata(&source) {
        let _ = fs::set_permissions(&backup, meta.permissions());
    }
    Ok(backup)
}

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

    #[test]
    fn replaced_line_keeps_the_rest_of_the_file() {
        // Regression test for the split_inclusive `Replaced` bug: the kache
        // line and the [net] table had to survive the replacement.
        let src = "[build]\nbuild-dir = '/old'\nrustc-wrapper = \"kache\"\n\n[net]\nx = 1\n";
        let (out, edit) = set_build_key(src, "build-dir", "/cache");
        assert_eq!(edit, CargoEdit::Replaced);
        assert!(
            out.contains("rustc-wrapper = \"kache\""),
            "tail deleted:\n{out}"
        );
        assert!(out.contains("[net]"), "tail deleted:\n{out}");
        let dir = out.find("build-dir = '/cache'").unwrap();
        let net = out.find("[net]").unwrap();
        assert!(dir < net, "replaced value must stay inside [build]:\n{out}");
    }

    #[test]
    fn appends_table_without_merging_lines() {
        // Regression test for the collect::<String> `Appended` bug: joining
        // without separators fused `[net]` and `foo = 1` into one line.
        let (out, edit) = set_build_key("[net]\nfoo = 1\n", "build-dir", "/cache");
        assert_eq!(edit, CargoEdit::Appended);
        assert!(!out.contains("[net]foo"), "lines merged:\n{out}");
        assert!(out.contains("foo = 1"));
        let net = out.find("[net]").unwrap();
        let build = out.rfind("[build]").unwrap();
        assert!(net < build);
    }

    #[test]
    fn appends_build_table_when_missing() {
        let (out, edit) = set_build_key("[net]\nfoo = 1\n", "build-dir", "/cache");
        assert_eq!(edit, CargoEdit::Appended);
        assert!(out.contains("[build]\nbuild-dir = '/cache'"), "got:\n{out}");
    }

    #[test]
    fn inserts_into_existing_build_table() {
        let (out, edit) = set_build_key(
            "[build]\nrustflags = []\n\n[net]\nx = 1\n",
            "build-dir",
            "/cache",
        );
        assert_eq!(edit, CargoEdit::Inserted);
        // build-dir must land inside [build], i.e. after the header but before [net].
        let build = out.find("[build]").unwrap();
        let dir = out.find("build-dir").unwrap();
        let net = out.find("[net]").unwrap();
        assert!(build < dir && dir < net, "got:\n{out}");
    }

    #[test]
    fn replaces_old_value() {
        let (out, edit) = set_build_key("[build]\nbuild-dir = '/old'\n", "build-dir", "/cache");
        assert_eq!(edit, CargoEdit::Replaced);
        assert!(out.contains("build-dir = '/cache'"));
        assert!(!out.contains("/old"));
    }

    #[test]
    fn already_set_is_a_no_op() {
        let src = "[build]\nbuild-dir = '/cache'\n";
        let (out, edit) = set_build_key(src, "build-dir", "/cache");
        assert_eq!(edit, CargoEdit::AlreadySet);
        assert_eq!(out, src);
    }

    #[test]
    fn removes_wrapper_line() {
        let src = "[build]\nbuild-dir = '/cache'\nrustc-wrapper = 'sccache'\n";
        let (out, edit) = remove_build_key(src, "rustc-wrapper");
        assert_eq!(edit, CargoEdit::Removed);
        assert!(out.contains("build-dir"), "build-dir must survive:\n{out}");
        assert!(!out.contains("rustc-wrapper"));
    }

    #[test]
    fn remove_is_a_no_op_when_absent() {
        let src = "[build]\nbuild-dir = '/cache'\n";
        let (out, edit) = remove_build_key(src, "rustc-wrapper");
        assert_eq!(edit, CargoEdit::AlreadySet);
        assert_eq!(out, src);
    }

    #[test]
    fn reads_key_from_build_table() {
        assert_eq!(
            read_build_key("[build]\nbuild-dir = '/cache' # comment\n", "build-dir"),
            Some("/cache".to_string()),
        );
        assert_eq!(read_build_key("[build]\nother = 1\n", "build-dir"), None);
        // A build-dir under some OTHER table must not be picked up.
        assert_eq!(
            read_build_key("[net]\nbuild-dir = '/x'\n", "build-dir"),
            None
        );
    }

    #[test]
    fn reads_generic_table_keys() {
        let text = "[unstable]\nfine-grain-locking = true # concurrent builds\n\n[build]\nbuild-dir = '/x'\n";
        assert_eq!(
            read_table_key(text, "unstable", "fine-grain-locking"),
            Some("true".to_string())
        );
        assert_eq!(read_table_key(text, "build", "fine-grain-locking"), None);
        assert_eq!(
            read_table_key(text, "build", "build-dir"),
            Some("/x".to_string())
        );
        // A key mentioned in a comment elsewhere must not leak.
        assert_eq!(
            read_table_key(
                "[other]\n# fine-grain-locking = true\n",
                "unstable",
                "fine-grain-locking"
            ),
            None
        );
    }

    #[test]
    fn config_writes_reject_injection() {
        assert!(validate_config_value("x'\nrustc-wrapper = '/tmp/evil' #", "build-dir").is_err());
        assert!(validate_config_value("x\r\ny", "build-dir").is_err());
        assert!(validate_config_value("x\0y", "build-dir").is_err());
        assert!(validate_config_value("/tmp/cache", "build-dir").is_ok());
    }

    #[test]
    fn removal_is_scoped_to_the_build_table() {
        let src = "[build]\nbuild-dir = '/x'\n\n[target.x]\nrustc-wrapper = 'keep'\n";
        let (out, edit) = remove_build_key(src, "rustc-wrapper");
        assert_eq!(edit, CargoEdit::AlreadySet);
        assert!(out.contains("rustc-wrapper = 'keep'"));
    }

    #[test]
    fn comments_inside_quoted_values_are_preserved() {
        assert_eq!(
            read_build_key("[build]\nbuild-dir = '/tmp/a#b' # tail\n", "build-dir"),
            Some("/tmp/a#b".to_string())
        );
    }

    #[test]
    fn cache_root_input_is_normalized() {
        // Cargo templates pass through untouched.
        assert_eq!(
            normalize_root_input("{cargo-cache-home}/custom").unwrap(),
            PathBuf::from("{cargo-cache-home}/custom"),
        );
        // Absolute stays absolute.
        assert_eq!(
            normalize_root_input("/tmp/cache").unwrap(),
            PathBuf::from("/tmp/cache"),
        );
        // `~` expands to the home directory.
        let home = paths::home().unwrap();
        assert_eq!(normalize_root_input("~/cache").unwrap(), home.join("cache"));
        // Relative resolves against the current directory.
        let cwd = std::env::current_dir().unwrap();
        assert_eq!(
            normalize_root_input("cache/build").unwrap(),
            cwd.join("cache/build"),
        );
    }
}