fgate 0.6.1

The fair gate: coding agents sharing one machine take turns for builds, within CPU and memory ceilings
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
//! A cargo target directory shared by several checkouts of one workspace (git worktrees, one per agent, all building
//! into one `CARGO_TARGET_DIR` so the dependencies are built once).
//!
//! Cargo names a workspace member's build output by its path relative to the workspace, not by the checkout it came
//! from, so every checkout writes its own crates to the same files. It then decides from file times whether they are
//! fresh: a build from another checkout that happened later looks newer than your sources, and cargo reuses it, so
//! your build runs another checkout's code, or fails against its older or newer API. The dependencies are the same
//! in every checkout and safe to share.
//!
//! So before a compiling cargo command fgate looks at who built that profile last (a `.fgate-checkouts` file in the
//! target directory). When it was another checkout, or nobody is recorded, it cleans this workspace's own packages
//! for that profile first (`cargo clean -p <member> …`, the dependencies stay) and records this checkout. Setting
//! `switch_clean = 0` turns it off.
//!
//! That clean also deletes the executables a checkout has just built, as soon as the next checkout's build gets
//! the slot. So after a build, while the slot is still held, fgate copies the workspace's executables into the
//! checkout itself (`<checkout>/target/fgate-bin/<profile>/`), where no other checkout's build touches them
//! (`keep_bins`; 0: off). It copies only when the record says this checkout built the profile last, so a kept
//! executable is always this checkout's own code.
//!
//! The clean, the build and the keep belong together: with two build slots, another checkout's clean could run
//! between this build and its keep (deleting what it built), or between its own clean and build, so that the record
//! names one checkout while the crates are another's. So a build into a shared target holds that target's lock
//! (`.fgate-lock` in it) from before its clean until after its keep. Cargo lets only one build use a target directory
//! at a time anyway, so this costs no parallel building; only the waiting is fgate's instead of cargo's.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::SystemTime;

/// The record in the target directory: one line per profile, `<profile key>\t<workspace root>`.
const STAMP: &str = ".fgate-checkouts";

/// The lock a build holds on a shared target directory from its clean to its keep.
const LOCK: &str = ".fgate-lock";

/// Set on a command that holds a shared target's lock: the target, so a nested `fgate cargo …` in it doesn't wait for
/// its own parent.
pub const LOCK_VAR: &str = "FGATE_TARGET_LOCK";

/// A held lock on a shared target directory; dropping it (or the process ending) gives it back.
pub struct TargetLock {
    _file: std::fs::File,
    pub target: PathBuf,
}

/// Takes the shared target's lock, waiting while another build holds it. None when this command's parent already
/// holds it, or the lock file can't be made (the build then goes ahead without it).
pub fn lock(shared: &Shared) -> Option<TargetLock> {
    let target = &shared.target;
    if std::env::var_os(LOCK_VAR).is_some_and(|held| same(&held.to_string_lossy(), target)) {
        return None;
    }
    std::fs::create_dir_all(target).ok()?;
    let file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(target.join(LOCK))
        .ok()?;
    let started = std::time::Instant::now();
    let mut said = false;
    while !crate::sys::try_lock(&file) {
        if !said && started.elapsed() > std::time::Duration::from_secs(1) {
            eprintln!(
                "fgate: waiting for another build into {} to finish (a build's clean, build and kept executables go \
                 together)",
                target.display()
            );
            said = true;
        }
        std::thread::sleep(std::time::Duration::from_millis(200));
    }
    Some(TargetLock {
        _file: file,
        target: target.clone(),
    })
}

/// Cargo's subcommands (and their aliases) that compile the workspace.
const COMPILING: [&str; 14] = [
    "build", "b", "check", "c", "test", "t", "run", "r", "clippy", "doc", "d", "bench", "rustc",
    "rustdoc",
];

/// What a cargo command line says about where and how it builds.
#[derive(Debug, PartialEq, Eq)]
pub struct Build {
    /// The requested cargo executable and optional rustup toolchain, also used by helper commands.
    cargo: String,
    toolchain: Option<String>,
    /// `--target-dir` from the command line (the environment's comes later).
    pub target_dir: Option<PathBuf>,
    /// `--manifest-path`, which picks the workspace instead of the current folder.
    pub manifest: Option<PathBuf>,
    /// The profile flags to repeat for `cargo clean` (`--release`, `--profile p`) and `--target t`.
    pub flags: Vec<String>,
    /// The output folder within the target directory: `debug`, `release`, a custom profile's name, under the
    /// target triple's folder when one is given.
    pub key: String,
}

impl Build {
    fn cargo(&self) -> Command {
        let mut command = Command::new(&self.cargo);
        if let Some(toolchain) = &self.toolchain {
            command.arg(toolchain);
        }
        command
    }
}

/// The build a command asks for, if it is a compiling cargo command (`cargo +nightly test …`, `cargo.exe b`).
pub fn parse(command: &[String]) -> Option<Build> {
    let (sub, build) = parse_any(command)?;
    COMPILING.contains(&sub.as_str()).then_some(build)
}

/// Whether the command's program is cargo (`cargo`, `cargo.exe`, a path to it).
pub fn is_cargo(command: &[String]) -> bool {
    command.first().is_some_and(|program| {
        Path::new(program)
            .file_stem()
            .is_some_and(|s| s.to_string_lossy().to_lowercase() == "cargo")
    })
}

/// What a cargo command line says, with its subcommand, whatever the subcommand.
fn parse_any(command: &[String]) -> Option<(String, Build)> {
    let program = command.first()?;
    if !is_cargo(command) {
        return None;
    }
    // Everything after `--` belongs to the program cargo runs.
    let args: Vec<&String> = command[1..]
        .iter()
        .take_while(|a| a.as_str() != "--")
        .collect();
    let mut sub = None;
    let mut target_dir = None;
    let mut manifest = None;
    let mut profile: Option<String> = None;
    let mut triple: Option<String> = None;
    let mut i = 0;
    while i < args.len() {
        let a = args[i].as_str();
        // A flag's value, `--flag value` (taking the next argument) or `--flag=value`.
        let mut value = |flag: &str| -> Option<String> {
            if a == flag {
                i += 1;
                args.get(i).map(|v| v.to_string())
            } else {
                a.strip_prefix(&format!("{flag}=")).map(str::to_string)
            }
        };
        if let Some(v) = value("--target-dir") {
            target_dir = Some(PathBuf::from(v));
        } else if let Some(v) = value("--manifest-path") {
            manifest = Some(PathBuf::from(v));
        } else if let Some(v) = value("--profile") {
            profile = Some(v);
        } else if let Some(v) = value("--target") {
            triple = Some(v);
        } else if a == "--release" || a == "-r" {
            profile = Some("release".into());
        } else if sub.is_none() && !a.starts_with('-') && !a.starts_with('+') {
            // The toolchain (`+nightly`) and cargo's own options come before the subcommand.
            sub = Some(a.to_string());
        }
        i += 1;
    }
    let sub = sub?;
    let default = if sub == "bench" { "bench" } else { "dev" };
    let profile = profile.unwrap_or_else(|| default.into());
    let dir = match profile.as_str() {
        "dev" | "test" => "debug",
        "release" | "bench" => "release",
        other => other,
    };
    let mut flags = match profile.as_str() {
        "dev" => vec![],
        "release" => vec!["--release".into()],
        other => vec!["--profile".into(), other.to_string()],
    };
    if let Some(t) = &triple {
        flags.extend(["--target".to_string(), t.clone()]);
    }
    let key = match &triple {
        Some(t) => format!("{t}/{dir}"),
        None => dir.to_string(),
    };
    let build = Build {
        cargo: program.clone(),
        toolchain: command.get(1).filter(|a| a.starts_with('+')).cloned(),
        target_dir,
        manifest,
        flags,
        key,
    };
    Some((sub, build))
}

/// The packaging a command does, if it is a `cargo publish` or `cargo package` that verifies the package by
/// building it.
pub fn publishes(command: &[String]) -> Option<Build> {
    let (sub, build) = parse_any(command)?;
    let skips = command
        .iter()
        .take_while(|a| a.as_str() != "--")
        .any(|a| a == "--no-verify" || a == "--list" || a == "-l");
    (["publish", "package"].contains(&sub.as_str()) && !skips).then_some(build)
}

/// After a `cargo publish` or `cargo package` that succeeded: its verify step built the packaged copy in
/// `target/package/<name>-<version>/` under the same names as the workspace's own build, and cargo's records then
/// point at the copy's sources, so a later `cargo build` takes the published version for fresh and stops rebuilding.
/// Cleaning the workspace's packages (their dev builds) makes the next build start from the real sources.
pub fn clean_after_publish(build: &Build) {
    let Some(members) = metadata(build).map(|m| package_names(&m)) else {
        return;
    };
    if members.is_empty() {
        return;
    }
    let mut clean = build.cargo();
    clean.arg("clean").arg("--quiet");
    for m in &members {
        clean.args(["-p", m]);
    }
    clean.args(&build.flags);
    if let Some(d) = &build.target_dir {
        clean.arg("--target-dir").arg(d);
    }
    if let Some(m) = &build.manifest {
        clean.arg("--manifest-path").arg(m);
    }
    match clean.status() {
        Ok(s) if s.success() => eprintln!(
            "fgate: cleaned this workspace's {} package(s) after the verify build, so the next cargo build \
             compiles from the real sources, not the packaged copy",
            members.len()
        ),
        Ok(s) => eprintln!("fgate: cargo clean after the verify build failed ({s})"),
        Err(e) => eprintln!("fgate: could not run cargo clean after the verify build ({e})"),
    }
}

/// A compiling cargo command into a target directory that other checkouts may share.
pub struct Shared {
    build: Build,
    /// The shared target directory.
    target: PathBuf,
    /// The workspace the command builds.
    root: PathBuf,
}

/// The shared build `command` makes, if it is a compiling cargo command into a target directory set from outside
/// the workspace (`--target-dir`, `CARGO_TARGET_DIR`, `CARGO_BUILD_TARGET_DIR`).
pub fn shared(command: &[String]) -> Option<Shared> {
    let build = parse(command)?;
    // Without one of these, the workspace's own target folder: nobody else builds there.
    let target = build
        .target_dir
        .clone()
        .or_else(|| std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from))
        .or_else(|| std::env::var_os("CARGO_BUILD_TARGET_DIR").map(PathBuf::from))?;
    let root = workspace_root(&build)?;
    Some(Shared {
        build,
        target,
        root,
    })
}

/// Before the command runs: cleans this workspace's packages in the shared target directory when another checkout
/// built that profile last. Says what it did; any failure only skips the check (the build itself goes ahead).
pub fn prepare(shared: &Shared) {
    let Shared {
        build,
        target,
        root,
    } = shared;
    let stamp = target.join(STAMP);
    let text = std::fs::read_to_string(&stamp).unwrap_or_default();
    let last = last_builder(&text, &build.key);
    if last.as_deref().is_some_and(|l| same(l, root)) {
        return;
    }
    let Some(members) = metadata(build).map(|m| package_names(&m)) else {
        return;
    };
    if members.is_empty() {
        return;
    }
    match &last {
        Some(other) => eprintln!(
            "fgate: {} in {} was last built by another checkout ({other}): cleaning this workspace's {} \
             package(s) there first, so cargo doesn't reuse them (switch_clean)",
            build.key,
            target.display(),
            members.len()
        ),
        None => eprintln!(
            "fgate: nobody is recorded as building {} in {}: cleaning this workspace's {} package(s) there once \
             (switch_clean)",
            build.key,
            target.display(),
            members.len()
        ),
    }
    let mut clean = build.cargo();
    clean.arg("clean");
    for m in &members {
        clean.args(["-p", m]);
    }
    clean.args(&build.flags);
    if let Some(d) = &build.target_dir {
        clean.arg("--target-dir").arg(d);
    }
    if let Some(m) = &build.manifest {
        clean.arg("--manifest-path").arg(m);
    }
    match clean.status() {
        Ok(s) if s.success() => {
            let _ = std::fs::create_dir_all(target);
            let _ = std::fs::write(&stamp, record(&text, &build.key, &root.to_string_lossy()));
        }
        Ok(s) => eprintln!("fgate: cargo clean failed ({s}); building without it"),
        Err(e) => eprintln!("fgate: could not run cargo clean ({e}); building without it"),
    }
}

/// After the command, while its slot is still held: copies the workspace's executables in the shared target
/// directory into the checkout (`kept_dir`), where the next checkout's clean can't delete them. Only when the record
/// says this checkout built the profile last, so the copies are its own code. Says what it kept; a failure only
/// leaves a note.
pub fn keep(shared: &Shared) {
    let Shared {
        build,
        target,
        root,
    } = shared;
    let text = std::fs::read_to_string(target.join(STAMP)).unwrap_or_default();
    if !last_builder(&text, &build.key).is_some_and(|l| same(&l, root)) {
        return;
    }
    let Some(bins) = metadata(build).map(|m| bin_names(&m)) else {
        return;
    };
    let from = target.join(&build.key);
    let to = kept_dir(root, &build.key);
    let mut kept = Vec::new();
    for name in bins {
        let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
        let source = from.join(&file);
        if !source.is_file() {
            continue;
        }
        match copy_if_changed(&source, &to.join(&file)) {
            Ok(true) => kept.push(file),
            Ok(false) => kept.push(format!("{file} (unchanged)")),
            Err(e) => eprintln!(
                "fgate: could not keep {file} in {}: {e} (keep_bins)",
                to.display()
            ),
        }
    }
    if !kept.is_empty() {
        eprintln!(
            "fgate: kept {} in {}: run it from there, the shared target's copy goes with the next checkout's \
             build (keep_bins)",
            kept.join(", "),
            to.display()
        );
    }
}

/// Where a checkout's executables of one profile are kept.
fn kept_dir(root: &Path, key: &str) -> PathBuf {
    root.join("target").join("fgate-bin").join(key)
}

/// Copies `from` to `to` unless `to` already has its size and modification time. Says whether it copied. The copy
/// takes `from`'s modification time, and replaces `to` by renaming it away first, which Windows allows even while
/// `to` is running.
pub fn copy_if_changed(from: &Path, to: &Path) -> std::io::Result<bool> {
    let meta = std::fs::metadata(from)?;
    let modified: SystemTime = meta.modified()?;
    if let Ok(old) = std::fs::metadata(to) {
        if old.len() == meta.len() && old.modified().ok() == Some(modified) {
            return Ok(false);
        }
    }
    if let Some(dir) = to.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let fresh = to.with_extension("fgate-new");
    std::fs::copy(from, &fresh)?;
    std::fs::File::options()
        .write(true)
        .open(&fresh)?
        .set_modified(modified)?;
    if to.exists() {
        let old = to.with_extension("fgate-old");
        // Left over from a copy that was running last time; still running, it stays.
        let _ = std::fs::remove_file(&old);
        std::fs::rename(to, &old)?;
        let _ = std::fs::remove_file(&old);
    }
    std::fs::rename(&fresh, to)?;
    Ok(true)
}

/// The workspace the command builds (its root folder), as cargo finds it.
fn workspace_root(build: &Build) -> Option<PathBuf> {
    let mut c = build.cargo();
    c.args(["locate-project", "--workspace", "--message-format", "plain"]);
    if let Some(m) = &build.manifest {
        c.arg("--manifest-path").arg(m);
    }
    let out = c.output().ok().filter(|o| o.status.success())?;
    let toml = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
    toml.parent().map(Path::to_path_buf)
}

/// The workspace's own packages, as `cargo metadata --no-deps` describes them.
fn metadata(build: &Build) -> Option<serde_json::Value> {
    let mut c = build.cargo();
    c.args(["metadata", "--no-deps", "--format-version", "1"]);
    if let Some(m) = &build.manifest {
        c.arg("--manifest-path").arg(m);
    }
    let out = c.output().ok().filter(|o| o.status.success())?;
    serde_json::from_slice(&out.stdout).ok()
}

fn packages(metadata: &serde_json::Value) -> impl Iterator<Item = &serde_json::Value> {
    metadata
        .get("packages")
        .and_then(|p| p.as_array())
        .into_iter()
        .flatten()
}

/// The workspace's packages, by name.
fn package_names(metadata: &serde_json::Value) -> Vec<String> {
    packages(metadata)
        .filter_map(|p| p.get("name")?.as_str().map(str::to_string))
        .collect()
}

/// The workspace's executables (bin targets), by name.
fn bin_names(metadata: &serde_json::Value) -> Vec<String> {
    packages(metadata)
        .filter_map(|p| p.get("targets")?.as_array())
        .flatten()
        .filter(|t| {
            t.get("kind")
                .and_then(|k| k.as_array())
                .is_some_and(|k| k.iter().any(|k| k == "bin"))
        })
        .filter_map(|t| t.get("name")?.as_str().map(str::to_string))
        .collect()
}

/// Who the record says built `key` last.
fn last_builder(text: &str, key: &str) -> Option<String> {
    text.lines().find_map(|l| {
        let (k, root) = l.split_once('\t')?;
        (k == key).then(|| root.to_string())
    })
}

/// The record with `key` now built by `root`.
fn record(text: &str, key: &str, root: &str) -> String {
    let mut out: Vec<String> = text
        .lines()
        .filter(|l| l.split_once('\t').is_some_and(|(k, _)| k != key))
        .map(str::to_string)
        .collect();
    out.push(format!("{key}\t{root}"));
    out.join("\n") + "\n"
}

/// Whether two workspace roots are the same folder (Windows paths ignore case and slash direction).
fn same(a: &str, b: &Path) -> bool {
    let norm = |s: &str| {
        let s = s.replace('\\', "/");
        let s = s.trim_end_matches('/');
        if cfg!(windows) {
            s.to_lowercase()
        } else {
            s.to_string()
        }
    };
    norm(a) == norm(&b.to_string_lossy())
}

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

    fn cmd(s: &str) -> Vec<String> {
        s.split_whitespace().map(str::to_string).collect()
    }

    #[test]
    fn finds_compiling_cargo_commands_and_their_profile() {
        let b = parse(&cmd(
            "cargo run -p viewer --release -- --building x --release",
        ))
        .unwrap();
        assert_eq!(
            (b.key.as_str(), b.flags.clone()),
            ("release", vec!["--release".to_string()])
        );
        let b = parse(&cmd("cargo.exe +nightly t -p sim")).unwrap();
        assert_eq!((b.key.as_str(), b.flags.len()), ("debug", 0));
        let b = parse(&cmd(
            "cargo clippy --workspace --profile=ci --target x86_64-pc-windows-msvc",
        ))
        .unwrap();
        assert_eq!(b.key, "x86_64-pc-windows-msvc/ci");
        assert_eq!(b.flags, cmd("--profile ci --target x86_64-pc-windows-msvc"));
        assert_eq!(parse(&cmd("cargo bench")).unwrap().key, "release");
        let b = parse(&cmd(
            "cargo build --target-dir E:/t --manifest-path a/Cargo.toml",
        ))
        .unwrap();
        assert_eq!(b.target_dir, Some(PathBuf::from("E:/t")));
        assert_eq!(b.manifest, Some(PathBuf::from("a/Cargo.toml")));
        // A flag's value before the subcommand is not the subcommand.
        let b = parse(&cmd(
            "cargo --target-dir E:/t --manifest-path x/Cargo.toml build",
        ))
        .unwrap();
        assert_eq!(
            (b.target_dir, b.key.as_str()),
            (Some(PathBuf::from("E:/t")), "debug")
        );
        assert!(parse(&cmd("cargo --manifest-path build fmt")).is_none());
    }

    #[test]
    fn leaves_other_commands_alone() {
        for c in [
            "cargo fmt --all",
            "cargo clean -p a",
            "cargo install fgate",
            "python shots.py",
            "cargo",
        ] {
            assert!(parse(&cmd(c)).is_none(), "{c}");
        }
    }

    #[test]
    fn finds_publishing_that_builds_the_package() {
        for c in [
            "cargo publish",
            "cargo +stable publish --dry-run",
            "cargo package --allow-dirty",
            "cargo.exe publish -p fgate --manifest-path x/Cargo.toml",
        ] {
            assert!(publishes(&cmd(c)).is_some(), "{c}");
        }
        for c in [
            "cargo publish --no-verify",
            "cargo package --list",
            "cargo build",
            "cargo run -- publish",
            "cargo login",
        ] {
            assert!(publishes(&cmd(c)).is_none(), "{c}");
        }
        let b = publishes(&cmd("cargo publish --target x86_64-pc-windows-msvc")).unwrap();
        assert_eq!(b.flags, cmd("--target x86_64-pc-windows-msvc"));
    }

    #[test]
    fn helper_commands_preserve_the_cargo_executable_and_toolchain() {
        for (input, executable, toolchain) in [
            ("cargo build", "cargo", None),
            ("cargo +nightly build", "cargo", Some("+nightly")),
            (
                "tools/cargo.exe +1.87.0 test",
                "tools/cargo.exe",
                Some("+1.87.0"),
            ),
            ("cargo run -- +nightly", "cargo", None),
        ] {
            let build = parse(&cmd(input)).unwrap();
            for subcommand in ["locate-project", "metadata", "clean"] {
                let mut helper = build.cargo();
                helper.arg(subcommand);
                assert_eq!(helper.get_program(), executable);
                let expected: Vec<_> = toolchain.into_iter().chain([subcommand]).collect();
                assert_eq!(helper.get_args().collect::<Vec<_>>(), expected);
            }
        }
    }

    #[test]
    fn the_record_keeps_one_builder_per_profile() {
        let t = record("", "debug", "E:/a");
        let t = record(&t, "release", "E:/b");
        let t = record(&t, "debug", "E:/c");
        assert_eq!(last_builder(&t, "debug").as_deref(), Some("E:/c"));
        assert_eq!(last_builder(&t, "release").as_deref(), Some("E:/b"));
        assert_eq!(last_builder(&t, "ci"), None);
        assert!(same("E:/code/game/", Path::new("E:/code/game")));
    }

    #[test]
    fn finds_the_workspace_packages_and_executables() {
        let m: serde_json::Value = serde_json::from_str(
            r#"{"packages": [
                {"name": "game", "targets": [
                    {"name": "game", "kind": ["lib"]},
                    {"name": "game-viewer", "kind": ["bin"]},
                    {"name": "bench", "kind": ["bench"]}]},
                {"name": "tools", "targets": [{"name": "tools", "kind": ["bin"]}]}
            ]}"#,
        )
        .unwrap();
        assert_eq!(package_names(&m), ["game", "tools"]);
        assert_eq!(bin_names(&m), ["game-viewer", "tools"]);
        assert!(bin_names(&serde_json::json!({})).is_empty());
    }

    #[test]
    fn kept_executables_live_in_the_checkout_per_profile() {
        let root = Path::new("/w/game");
        assert_eq!(
            kept_dir(root, "release"),
            Path::new("/w/game/target/fgate-bin/release")
        );
        assert_eq!(
            kept_dir(root, "x86_64-pc-windows-msvc/debug"),
            Path::new("/w/game/target/fgate-bin/x86_64-pc-windows-msvc/debug")
        );
    }

    #[test]
    fn a_build_holds_the_shared_target_until_it_is_done() {
        let dir = std::env::temp_dir().join(format!("fgate-lock-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let shared = Shared {
            build: parse(&cmd("cargo build")).unwrap(),
            target: dir.clone(),
            root: dir.clone(),
        };
        let held = lock(&shared).unwrap();
        let other = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(dir.join(LOCK))
            .unwrap();
        assert!(!crate::sys::try_lock(&other), "another build waits");
        drop(held);
        assert!(crate::sys::try_lock(&other), "and goes once it is done");
        crate::sys::unlock(&other);
        drop(other);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn copies_only_what_changed() {
        let dir = std::env::temp_dir().join(format!("fgate-keep-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let from = dir.join("game.exe");
        let to = dir.join("kept").join("game.exe");
        std::fs::write(&from, "one").unwrap();
        assert!(copy_if_changed(&from, &to).unwrap());
        assert!(!copy_if_changed(&from, &to).unwrap());
        std::fs::write(&from, "two!").unwrap();
        assert!(copy_if_changed(&from, &to).unwrap());
        assert_eq!(std::fs::read_to_string(&to).unwrap(), "two!");
        assert!(
            !to.with_extension("fgate-new").exists() && !to.with_extension("fgate-old").exists()
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}