cargo-lbin 0.9.0

Thin cargo-install wrapper targeting /usr/local/bin, crates.io only
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
//! Stage builds.
//!
//! `cargo install --root <stage>` runs as the invoking user: registry cache,
//! build scripts and proc macros never execute as root. The stage's
//! `.crates2.json` is then the source of truth for what was actually built —
//! version and binary names — regardless of what the index promised earlier.

use anyhow::{Context, Result, bail};
use semver::Version;
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fs;
#[cfg(feature = "tui")]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(feature = "tui")]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;

const CRATES_IO_SOURCE: &str = "registry+https://github.com/rust-lang/crates.io-index";

#[derive(Debug)]
pub struct Built {
    pub version: Version,
    pub bins: Vec<String>,
    pub bin_paths: Vec<PathBuf>,
}

#[derive(Deserialize)]
struct Crates2 {
    installs: BTreeMap<String, InstallInfo>,
}

#[derive(Deserialize)]
struct InstallInfo {
    bins: Vec<String>,
}

/// What tests may substitute for `cargo`: an absolute path to a fake,
/// read by `command` under cfg(test). A plain synchronized value instead
/// of mutating `$PATH` — the environment is process-global and other
/// test threads read it concurrently, which is exactly the unsafety
/// `std::env::set_var` was made unsafe to spotlight. Plain cfg(test):
/// the harness serves the terminal pipeline (migrate) as much as the
/// captured one, so it must exist with the tui feature off.
#[cfg(test)]
static CARGO_PROGRAM: std::sync::RwLock<Option<PathBuf>> = std::sync::RwLock::new(None);

/// Serializes tests that install a fake cargo, so one test's fake never
/// answers another test's spawn.
#[cfg(test)]
static FAKE_CARGO_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// RAII around the fake: holds the serialization lock, installs the
/// override, and clears it on drop, panics included. The guarantee is
/// exactly as strong as the mutex's reach — tests that spawn cargo
/// without taking this guard would still see an active override; today
/// no such test exists, and this comment is where that assumption is
/// written down.
#[cfg(test)]
pub(crate) struct FakeCargo {
    _serial: std::sync::MutexGuard<'static, ()>,
}

#[cfg(test)]
impl FakeCargo {
    pub(crate) fn install(script: &Path) -> Self {
        let serial = FAKE_CARGO_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        *CARGO_PROGRAM.write().unwrap() = Some(script.to_path_buf());
        Self { _serial: serial }
    }
}

#[cfg(test)]
impl Drop for FakeCargo {
    fn drop(&mut self) {
        *CARGO_PROGRAM.write().unwrap() = None;
    }
}

fn cargo_program() -> std::ffi::OsString {
    #[cfg(test)]
    if let Some(p) = CARGO_PROGRAM.read().unwrap().clone() {
        return p.into_os_string();
    }
    std::ffi::OsString::from("cargo")
}

fn command(name: &str, version: Option<&Version>, locked: bool, stage: &Path) -> Command {
    let mut cmd = Command::new(cargo_program());
    cmd.arg("install").arg(name).arg("--root").arg(stage);
    if let Some(version) = version {
        cmd.arg("--version").arg(format!("={version}"));
    }
    if locked {
        cmd.arg("--locked");
    }
    // Cargo otherwise tells the user to add the temporary stage/bin to PATH.
    // Append it for the child process so Cargo suppresses that misleading
    // warning without changing command resolution.
    if let Some(path) = std::env::var_os("PATH") {
        let mut dirs: Vec<PathBuf> = std::env::split_paths(&path).collect();
        dirs.push(stage.join("bin"));
        if let Ok(joined) = std::env::join_paths(dirs) {
            cmd.env("PATH", joined);
        }
    }
    cmd
}

/// Build `name` from crates.io into the stage root — at exactly
/// `version` if one is given, else the newest cargo picks. The exact
/// form is spelled out (`--version =1.2.3`) rather than relying on
/// cargo treating a bare version as exact: the intent should be in the
/// command line, not in a default.
pub fn build(name: &str, version: Option<&Version>, locked: bool, stage: &Path) -> Result<Built> {
    fs::create_dir_all(stage).with_context(|| format!("creating {}", stage.display()))?;
    // Compiler output goes straight to the terminal; the user should see the
    // build exactly as cargo presents it.
    let status = command(name, version, locked, stage)
        .status()
        .context("failed to spawn cargo")?;
    if !status.success() {
        bail!("cargo install {name} failed with {status}");
    }
    verified_info(name, version, stage)
}

/// Wait up to one tick for the kernel side of the pipe to become
/// readable (or hung up). `Ok(true)` means "read now"; `Ok(false)` is a
/// quiet tick for the read loop's cancel check — including EINTR, which
/// interrupted the wait without producing data: nothing read, nothing
/// lost, and the tick's bounded latency is precisely the property the
/// poll exists for, so a signal must not become a license to block. A
/// real poll error is an error: it goes down the same teardown as a
/// read error, not into a blocking read that would wedge on the very
/// pipe poll just failed to ask about.
#[cfg(feature = "tui")]
fn poll_readable(fd: std::os::fd::RawFd) -> std::io::Result<bool> {
    let mut pfd = libc::pollfd {
        fd,
        events: libc::POLLIN,
        revents: 0,
    };
    // SAFETY: poll(2) reads/writes the one pollfd it is given; the
    // struct lives on this stack frame for the whole call.
    let n = unsafe { libc::poll(&raw mut pfd, 1, 100) };
    match n {
        0 => Ok(false),
        1.. => Ok(true),
        _ => {
            let e = std::io::Error::last_os_error();
            if e.kind() == std::io::ErrorKind::Interrupted {
                Ok(false)
            } else {
                Err(e)
            }
        }
    }
}

/// The captured build's read loop, EOF to EOF. EOF is the exit — and
/// EOF is withheld for as long as *any* group member keeps the
/// inherited stderr open. A TERM-ignoring child would otherwise wedge a
/// cancellation in a perfect circle: the sweep waits for the reap, the
/// reap waits for EOF, EOF waits for the stray, the stray waits for the
/// sweep. So the blocking read is fronted by a bounded poll, and on
/// quiet ticks the loop checks for exactly that circle: a cancel in
/// flight with the leader already gone means the survivors' supervisor
/// is dead, no further grace is owed, and the remainder of the group is
/// swept with SIGKILL here — the strays die, EOF arrives, the loop ends.
/// `try_wait` reaps the leader when it answers; `Child` caches the
/// status, so the caller's `wait()` still returns it. A read error ends
/// the loop and is returned; the caller owns the teardown.
#[cfg(feature = "tui")]
fn drain_stderr(
    reader: &mut std::io::BufReader<std::process::ChildStderr>,
    child: &mut std::process::Child,
    control: &crate::BuildControl,
    pgid: Option<i32>,
    on_line: &mut dyn FnMut(&str),
    lines: &mut Vec<String>,
) -> Option<std::io::Error> {
    let mut buf: Vec<u8> = Vec::new();
    let mut swept = false;
    loop {
        if control.cancelled() && !swept && matches!(child.try_wait(), Ok(Some(_))) {
            swept = true;
            if let Some(pgid) = pgid {
                // SAFETY: kill(2) with a negative pid signals the
                // process group; ESRCH — already empty — is a no-op.
                unsafe {
                    libc::kill(-pgid, libc::SIGKILL);
                }
            }
        }
        // The poll asks the kernel — but `read_until` serves from the
        // BufReader first, and one kernel read can park several lines in
        // that buffer. Polling an already-drained pipe while buffered
        // lines wait would hold them hostage to cargo's next write; the
        // buffer is consulted first, and only an empty one earns a tick.
        if reader.buffer().is_empty() {
            match poll_readable(std::os::fd::AsRawFd::as_raw_fd(reader.get_ref())) {
                Ok(true) => {}
                Ok(false) => continue,
                Err(e) => return Some(e),
            }
        }
        buf.clear();
        match std::io::BufRead::read_until(reader, b'\n', &mut buf) {
            Ok(0) => return None,
            Ok(_) => {
                while matches!(buf.last(), Some(b'\n' | b'\r')) {
                    buf.pop();
                }
                // Build scripts and linkers answer to neither cargo nor
                // CARGO_TERM_COLOR; sanitize once, for screen and log.
                let line = crate::text::sanitize(&String::from_utf8_lossy(&buf));
                on_line(&line);
                lines.push(line);
            }
            // EINTR: nothing read, nothing lost; simply try again.
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Some(e),
        }
    }
}

/// `build` for a frontend that owns the screen: cargo's stderr is piped
/// (which makes cargo drop its own progress bar) and forwarded line by
/// line to `on_line`; nothing reaches the terminal. Plain text is
/// enforced, not assumed: cargo's own coloring is disabled outright and
/// every line is control-character sanitized, because a build script or
/// linker answers to neither cargo nor `CARGO_TERM_COLOR`. stdout is discarded — `cargo install` speaks on
/// stderr, and a stray stdout write must not corrupt an alternate
/// screen.
///
/// On failure the full captured output is written to
/// `<log_dir>/build-<name>-<pid>-<nanos>.log` and the error carries the
/// interesting tail — from the first compiler error onward when there is
/// one, the last lines otherwise — plus the log path, so "failed" is
/// never blind even when the frontend showed only a gauge.
#[cfg(feature = "tui")]
pub fn build_captured(
    name: &str,
    version: Option<&Version>,
    locked: bool,
    stage: &Path,
    log_dir: &Path,
    on_line: &mut dyn FnMut(&str),
    control: &crate::BuildControl,
) -> Result<Built> {
    fs::create_dir_all(stage).with_context(|| format!("creating {}", stage.display()))?;
    let mut cmd = command(name, version, locked, stage);
    // A pipe usually makes cargo drop colors on its own, but `term.color
    // = "always"` or an inherited CARGO_TERM_COLOR=always would still
    // paint ANSI into the capture — and the parser matches on plain
    // prefixes, the failure panel shows the lines verbatim. Captured
    // means captured; the terminal build stays untouched.
    cmd.env("CARGO_TERM_COLOR", "never");
    // Its own process group, so a cancel can address cargo *and* every
    // rustc and build script it is running with one negative-pid kill.
    // Signalling cargo alone would orphan running compilations, which
    // keep writing into the stage the caller is about to discard. The
    // terminal build stays in the session's foreground group on
    // purpose: there, Ctrl-C reaching everything is the terminal's job.
    std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
    let mut child = cmd
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .context("failed to spawn cargo")?;
    // The child is its own group leader, so its pid is the group id.
    // Announced before the first read: a cancel that arrives while
    // cargo is spawning must find something to signal, not a
    // forever-empty slot — and `spawned` also delivers a cancel that
    // was accepted before there was anything to signal. Kept locally
    // too, for the sweep below.
    let pgid = i32::try_from(child.id()).ok();
    if let Some(pgid) = pgid {
        control.spawned(pgid);
    }
    let stderr = child
        .stderr
        .take()
        .context("cargo spawned without a stderr pipe")?;
    // read_until + lossy conversion instead of `.lines()`: a build
    // script or linker can emit bytes that are not UTF-8, and a reader
    // that errors out here would return before `child.wait()` — leaving
    // the child running and unreaped, since Child is not killed on drop.
    // Whatever happens on the pipe, the process is always collected.
    let mut reader = std::io::BufReader::new(stderr);
    let mut lines: Vec<String> = Vec::new();
    let read_error = drain_stderr(&mut reader, &mut child, control, pgid, on_line, &mut lines);
    if read_error.is_some() {
        // The reader abandons the pipe with cargo possibly still
        // writing; a full pipe would park cargo on write while we park
        // on wait — a quiet mutual stall. Kill first, then reap — and
        // kill the whole group: the build runs in its own process group
        // precisely so rustc and build scripts cannot outlive cargo,
        // and a leader-only kill here would abandon them to keep
        // writing into a stage about to be discarded. The build is
        // already lost to the read failure either way.
        if let Ok(pgid) = i32::try_from(child.id()) {
            // SAFETY: kill(2) with a negative pid signals the process
            // group; no memory is touched and an error (ESRCH: already
            // gone) is an acceptable no-op.
            unsafe {
                libc::kill(-pgid, libc::SIGKILL);
            }
        }
    }
    let status = child.wait();
    // The leader's death does not end the group: a child that ignores
    // SIGTERM — a build script, say: precisely the population the group
    // exists to cover — survives it, and the group id stays alive with
    // any surviving member. On a cancellation those survivors are
    // strays: their supervisor is gone, so no further grace is owed,
    // and the stage they may still be writing to is about to be removed
    // — the remainder of the group is therefore SIGKILLed as cleanup,
    // not escalation, before the address is withdrawn. SIGKILL cannot
    // be ignored; this sweep is what makes "a cancel leaves no orphans
    // writing into the stage" true rather than merely usual. Usually it
    // already ran from the read loop (a stray holding stderr is exactly
    // how EOF gets withheld — see there); this one covers the leader
    // dying after the last line without ever wedging the pipe, and a
    // repeat is a no-op.
    if control.cancelled()
        && let Some(pgid) = pgid
    {
        // SAFETY: kill(2) with a negative pid signals the process
        // group; no memory is touched, and ESRCH — the group already
        // empty — is the happy case.
        unsafe {
            libc::kill(-pgid, libc::SIGKILL);
        }
    }
    // The announcement is withdrawn once this side is done signalling:
    // after the leader's reap and, on a cancellation, after the sweep —
    // the post-wait I/O (failure log, stage verification) stays outside
    // the window. Withdrawn on a failed wait too: the child's state is
    // then unknown, and "never signal" is the only safe direction to be
    // wrong in.
    control.reaped();
    let status = status.context("waiting for cargo")?;
    if let Some(e) = read_error {
        return Err(failure_with_log(
            log_dir,
            name,
            &lines,
            format!("reading cargo output failed: {e}"),
            &tail_from(&lines, lines.len().saturating_sub(TAIL_LINES)),
        ));
    }
    if !status.success() {
        // Ended by the cancel, not by cargo: no failure log — an error
        // that says the person's own decision was carried out is not a
        // diagnosis — and the stage is removed rather than kept, since
        // the only thing it is evidence of is that decision. Both
        // conditions, deliberately: the phase alone would lose the race
        // where cargo dies of its own causes an instant before a late
        // cancel is accepted (a normal exit code is cargo's own verdict
        // and must surface as the failure it is, phase notwithstanding);
        // exit-by-signal alone would misfile an external kill — an OOM,
        // say — as a cancellation nobody requested.
        use std::os::unix::process::ExitStatusExt;
        if control.cancelled() && status.signal().is_some() {
            let _ = fs::remove_dir_all(stage);
            return Err(anyhow::Error::new(crate::BuildCancelled));
        }
        // Tail from the first compiler error when there is one — the
        // lines before it are successful units, noise here.
        let start = lines
            .iter()
            .position(|l| {
                matches!(
                    crate::progress::parse_line(l),
                    crate::progress::BuildEvent::Error
                )
            })
            .unwrap_or(lines.len().saturating_sub(TAIL_LINES));
        return Err(failure_with_log(
            log_dir,
            name,
            &lines,
            format!("cargo install {name} failed with {status}"),
            &tail_from(&lines, start),
        ));
    }
    // The failure contract — diagnosis plus the full log — holds past the
    // exit code: cargo saying 0 and the stage failing verification (a
    // missing or forged .crates2.json, a version mismatch) is a failure
    // of this build like any other, and its log matters just as much.
    verified_info(name, version, stage).map_err(|e| {
        failure_with_log(
            log_dir,
            name,
            &lines,
            format!("cargo exited successfully, but: {e:#}"),
            &tail_from(&lines, lines.len().saturating_sub(TAIL_LINES)),
        )
    })
}

#[cfg(feature = "tui")]
fn tail_from(lines: &[String], start: usize) -> Vec<&str> {
    lines[start..]
        .iter()
        .take(TAIL_LINES)
        .map(String::as_str)
        .collect()
}

/// One shape for every captured-build failure: headline, then the log
/// path — right under it, because a shallow panel truncates from the
/// bottom and the pointer to everything else must survive — then the
/// tail.
#[cfg(feature = "tui")]
fn failure_with_log(
    log_dir: &Path,
    name: &str,
    lines: &[String],
    headline: String,
    tail: &[&str],
) -> anyhow::Error {
    let log = write_build_log(log_dir, name, lines);
    let mut msg = headline;
    match log {
        Ok(path) => {
            msg.push_str("\nfull log: ");
            msg.push_str(&path.display().to_string());
        }
        Err(e) => {
            use std::fmt::Write as _;
            let _ = write!(msg, "\n(could not write the full log: {e:#})");
        }
    }
    for l in tail {
        msg.push_str("\n  ");
        msg.push_str(l);
    }
    anyhow::anyhow!(msg)
}

#[cfg(feature = "tui")]
const TAIL_LINES: usize = 12;

#[cfg(feature = "tui")]
/// The full captured output, written to a fresh, private file:
/// `create_new` turns the PID+nanos naming from "collision absurdly
/// unlikely" into "overwrite impossible" — an existing file is an error,
/// never silently replaced evidence — and 0600 keeps build.rs output,
/// which can quote the environment, out of other users' reach. Exactly
/// 0600, not merely "no wider": open-time mode is an upper bound under
/// umask (0777 would leave the log unreadable to its own owner), so a
/// chmod on the descriptor restores the owner's rw — safe against the
/// window, since the file is born at most tighter, never looser.
fn write_build_log(log_dir: &Path, name: &str, lines: &[String]) -> Result<PathBuf> {
    fs::create_dir_all(log_dir)
        .with_context(|| format!("creating log directory {}", log_dir.display()))?;
    let stamp = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    let path = log_dir.join(format!("build-{name}-{}-{stamp}.log", std::process::id()));
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(&path)
        .with_context(|| format!("creating build log {}", path.display()))?;
    file.set_permissions(fs::Permissions::from_mode(0o600))
        .with_context(|| format!("setting permissions on build log {}", path.display()))?;
    let mut body = lines.join("\n");
    body.push('\n');
    std::io::Write::write_all(&mut file, body.as_bytes())
        .with_context(|| format!("writing build log {}", path.display()))?;
    Ok(path)
}

/// Read the stage and verify it holds what was asked for — shared tail
/// of both build variants.
fn verified_info(name: &str, version: Option<&Version>, stage: &Path) -> Result<Built> {
    let built = staged_info(name, stage)?;
    // What the stage holds is the truth about what was built; check it
    // against what was asked rather than assume cargo honoured `=`.
    if let Some(version) = version
        && built.version != *version
    {
        bail!(
            "asked for {name} {version} but the stage holds {}",
            built.version
        );
    }
    Ok(built)
}

/// Read what the stage actually contains for `name` from `.crates2.json`.
fn staged_info(name: &str, stage: &Path) -> Result<Built> {
    let path = stage.join(".crates2.json");
    let raw = fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
    let parsed: Crates2 =
        serde_json::from_str(&raw).with_context(|| format!("parsing {}", path.display()))?;

    // Key format: `name version (source)`. The stage only ever holds one
    // version per crate (cargo replaces on reinstall), but be defensive and
    // take the semver max if we ever see more.
    let mut best: Option<Built> = None;
    for (key, info) in &parsed.installs {
        let mut parts = key.split_whitespace();
        let (Some(key_name), Some(key_version), Some(key_source)) =
            (parts.next(), parts.next(), parts.next())
        else {
            continue;
        };
        if key_name != name || !key_source.contains(CRATES_IO_SOURCE) {
            continue;
        }
        let version = Version::parse(key_version)
            .with_context(|| format!("unparsable staged version `{key_version}`"))?;
        let replace = match &best {
            Some(b) => version > b.version,
            None => true,
        };
        if replace {
            // Stage bookkeeping is also disk input steering placement; hold
            // it to the same standard as the manifest: valid filenames, no
            // duplicates — caught here, before anything touches the prefix.
            crate::validate::validate_bin_list(&info.bins)
                .with_context(|| format!("stage bookkeeping for `{name}`"))?;
            let bin_dir = stage.join("bin");
            best = Some(Built {
                bin_paths: info.bins.iter().map(|b| bin_dir.join(b)).collect(),
                bins: info.bins.clone(),
                version,
            });
        }
    }
    best.with_context(|| format!("`{name}` missing from stage bookkeeping after build"))
}

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

    #[test]
    fn staged_info_parses_crates2() {
        let dir = std::env::temp_dir().join("cargo-lbin-test-stage");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join(".crates2.json"),
            r#"{"installs":{
                "hexyl 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)":
                    {"bins":["hexyl"]},
                "other 1.0.0 (git+https://example.com/other#abc)":
                    {"bins":["other"]}
            }}"#,
        )
        .unwrap();

        let built = staged_info("hexyl", &dir).unwrap();
        assert_eq!(built.version, Version::parse("0.14.0").unwrap());
        assert_eq!(built.bins, vec!["hexyl"]);
        assert!(
            staged_info("other", &dir).is_err(),
            "git source must not match"
        );
        assert!(staged_info("absent", &dir).is_err());

        // Forged bookkeeping with duplicate bins must fail here, before
        // anything would touch the prefix.
        fs::write(
            dir.join(".crates2.json"),
            r#"{"installs":{
                "dupes 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)":
                    {"bins":["foo","foo"]}
            }}"#,
        )
        .unwrap();
        let err = format!("{:#}", staged_info("dupes", &dir).unwrap_err());
        assert!(err.contains("listed twice"), "{err}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(feature = "tui")]
    #[test]
    fn captured_build_forwards_lines_and_logs_failures() {
        use std::os::unix::fs::PermissionsExt;

        let root = std::env::temp_dir().join("cargo-lbin-test-captured");
        let _ = fs::remove_dir_all(&root);
        let fake_bin = root.join("bin");
        let stage = root.join("stage");
        let logs = root.join("logs");
        fs::create_dir_all(&fake_bin).unwrap();

        // A fake `cargo` first: fails after emitting a compiler error, so
        // the tail must start at the error and the full log must exist.
        let script = fake_bin.join("cargo");
        fs::write(
            &script,
            "#!/bin/sh\n\
             echo '   Compiling one v1.0.0' >&2\n\
             echo '   Compiling two v2.0.0' >&2\n\
             echo 'error[E0308]: mismatched types' >&2\n\
             echo 'note: expected u8' >&2\n\
             exit 101\n",
        )
        .unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();

        // Injected, not resolved: mutating $PATH would be process-global
        // unsafety; the guard hands the fake to `command` directly and
        // clears it on drop, panics included.
        let _fake = FakeCargo::install(&script);

        let mut seen: Vec<String> = Vec::new();
        let control = crate::BuildControl::new();
        let err = build_captured(
            "boomcrate",
            None,
            false,
            &stage,
            &logs,
            &mut |l| {
                seen.push(l.to_owned());
            },
            &control,
        )
        .unwrap_err();
        let msg = format!("{err:#}");
        assert_eq!(seen.len(), 4, "every stderr line reaches the frontend");
        assert!(
            msg.contains("error[E0308]") && msg.contains("note: expected u8"),
            "tail starts at the first compiler error: {msg}"
        );
        assert!(
            !msg.contains("Compiling one"),
            "successful units stay out of the tail: {msg}"
        );
        assert!(msg.contains("full log:"), "log path travels in the error");
        let log = fs::read_dir(&logs).unwrap().next().unwrap().unwrap().path();
        // The screw is torqued; mark it with paint: 0600 is a guarantee
        // of write_build_log, not a happy accident of the umask.
        let mode = fs::metadata(&log).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "the build log is private to the user");
        let full = fs::read_to_string(&log).unwrap();
        assert!(
            full.contains("Compiling one") && full.contains("note: expected u8"),
            "the log holds everything the tail dropped"
        );

        let _ = fs::remove_dir_all(&root);
    }

    /// The other half of the captured contract: success streams lines
    /// through the same parser path, and an exit-0 build that staged
    /// nothing still fails with the log written — split from the
    /// failure-diagnostics test above along its own seam.
    #[cfg(feature = "tui")]
    #[test]
    fn captured_build_streams_success_and_verifies_the_stage() {
        use std::os::unix::fs::PermissionsExt;

        let root = std::env::temp_dir().join("cargo-lbin-test-captured-ok");
        let _ = fs::remove_dir_all(&root);
        let fake_bin = root.join("bin");
        let stage = root.join("stage");
        let logs = root.join("logs");
        fs::create_dir_all(&fake_bin).unwrap();
        let script = fake_bin.join("cargo");
        fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();
        fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        let _fake = FakeCargo::install(&script);

        // The fake succeeding: lines still stream, the stage is
        // verified through the same path as the terminal build.
        fs::write(
            &script,
            "#!/bin/sh\n\
                 echo '   Compiling okcrate v0.1.0' >&2\n\
                 echo '    Finished release [optimized]' >&2\n\
                 mkdir -p \"$4\"\n\
                 printf '%s' '{\"installs\":{\"okcrate 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)\":{\"bins\":[\"okcrate\"]}}}' > \"$4/.crates2.json\"\n\
                 exit 0\n",
        )
        .unwrap();
        let mut count = 0usize;
        let built = build_captured(
            "okcrate",
            None,
            false,
            &stage,
            &logs,
            &mut |l| {
                if matches!(
                    crate::progress::parse_line(l),
                    crate::progress::BuildEvent::Compiling { .. }
                ) {
                    count += 1;
                }
            },
            &crate::BuildControl::new(),
        )
        .unwrap();
        assert_eq!(count, 1);
        assert_eq!(built.bins, vec!["okcrate"]);

        // A fake that exits 0 without staging anything: the failure
        // contract must hold past the exit code, log included.
        fs::write(&script, "#!/bin/sh\nexit 0\n").unwrap();
        let _ = fs::remove_dir_all(&logs);
        let err = build_captured(
            "ghost",
            None,
            false,
            &stage,
            &logs,
            &mut |_| {},
            &crate::BuildControl::new(),
        )
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("cargo exited successfully, but:"),
            "verification failure names itself: {msg}"
        );
        assert!(
            msg.contains("full log:"),
            "verification failure still writes and names the log: {msg}"
        );

        let _ = fs::remove_dir_all(&root);
    }
}