cargo-plushie 0.7.1

Cargo subcommand for building and downloading Plushie renderer binaries
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
//! Diagnostic report for `cargo plushie doctor`.
//!
//! Gathers the checks a user typically runs by hand when a wire-mode
//! setup misbehaves: Rust toolchain, cargo-plushie version, mode
//! environment variables, renderer discovery, binary architecture,
//! detected native widgets, and version skew between the app's
//! `plushie-renderer-lib` and the discovered binary.
//!
//! The command is read-only: it never starts the host app, never
//! modifies files, and never spawns the renderer in a way that could
//! affect live sessions. The version probe talks to the binary over
//! `--mock --json`, which is the protocol-only stub path.

use crate::{Result, discover, platform};
use anyhow::Context;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

/// Input for [`run_doctor`].
pub struct DoctorOpts<'a> {
    /// Directory containing the app's Cargo.toml.
    pub manifest_dir: &'a Path,
    /// Minimum supported Rust toolchain version.
    pub min_rustc_version: &'a str,
}

/// Diagnostic outcome. The `critical` field is the gate on exit code:
/// any critical finding makes `cargo plushie doctor` exit non-zero so
/// CI setups can treat it as a hard failure.
#[derive(Debug, Default)]
pub struct DoctorReport {
    /// Ordered list of (label, value, severity) rows.
    pub rows: Vec<Row>,
    /// True when at least one critical issue was detected.
    pub critical: bool,
}

/// A single row in the diagnostic report.
#[derive(Debug)]
pub struct Row {
    /// Short label shown on the left.
    pub label: String,
    /// Rendered value (may span multiple lines).
    pub value: String,
    /// Severity (drives the leading symbol and exit-code gate).
    pub severity: Severity,
}

/// Row severity classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// Normal informational row.
    Ok,
    /// Worth mentioning but not broken.
    Warn,
    /// Broken: will fail at handshake or run time.
    Critical,
}

impl Severity {
    /// Leading symbol printed in the report.
    fn symbol(self) -> &'static str {
        match self {
            Self::Ok => "OK",
            Self::Warn => "WARN",
            Self::Critical => "FAIL",
        }
    }
}

/// Gather the diagnostic rows and return a populated [`DoctorReport`].
///
/// # Errors
///
/// Propagates [`cargo_metadata`] failures when the workspace dep
/// graph cannot be resolved. Missing binaries, missing env vars,
/// and missing tools are reported as rows, not errors.
pub fn run_doctor(opts: &DoctorOpts<'_>) -> Result<DoctorReport> {
    let mut report = DoctorReport::default();

    // -- Toolchain --
    push_rustc_row(&mut report, opts.min_rustc_version);
    report.rows.push(Row {
        label: "cargo-plushie".to_string(),
        value: env!("CARGO_PKG_VERSION").to_string(),
        severity: Severity::Ok,
    });

    // -- Host --
    report.rows.push(Row {
        label: "host".to_string(),
        value: format!("{}-{}", platform::os_name(), platform::arch_name()),
        severity: Severity::Ok,
    });

    // -- Environment --
    for var in [
        "PLUSHIE_BINARY_PATH",
        "PLUSHIE_RUST_SOURCE_PATH",
        "PLUSHIE_MODE",
        "PLUSHIE_SOCKET",
    ] {
        let (value, severity) = match std::env::var(var) {
            Ok(v) => (v, Severity::Ok),
            Err(_) => ("(unset)".to_string(), Severity::Ok),
        };
        report.rows.push(Row {
            label: var.to_string(),
            value,
            severity,
        });
    }

    // -- Renderer discovery --
    let discovered = discover_renderer(opts.manifest_dir);
    match &discovered {
        Some(path) => report.rows.push(Row {
            label: "renderer".to_string(),
            value: path.display().to_string(),
            severity: Severity::Ok,
        }),
        None => {
            report.critical = true;
            report.rows.push(Row {
                label: "renderer".to_string(),
                value: renderer_not_found_hint(),
                severity: Severity::Critical,
            });
        }
    }

    // -- Architecture --
    if let Some(path) = discovered.as_deref() {
        push_arch_row(&mut report, path);
    }

    // -- Metadata-driven checks --
    push_metadata_rows(&mut report, opts.manifest_dir)?;

    // -- Version skew --
    if let Some(path) = discovered.as_deref() {
        push_version_skew_row(&mut report, path, opts.manifest_dir);
    }

    Ok(report)
}

/// Write a textual report to `writer` using aligned columns.
///
/// # Errors
///
/// Propagates the writer's errors.
pub fn write_report<W: Write>(report: &DoctorReport, writer: &mut W) -> std::io::Result<()> {
    let max_label = report.rows.iter().map(|r| r.label.len()).max().unwrap_or(0);
    for row in &report.rows {
        let pad = " ".repeat(max_label.saturating_sub(row.label.len()));
        let symbol = row.severity.symbol();
        // Multi-line values indent subsequent lines under the value column.
        let mut lines = row.value.lines();
        let first = lines.next().unwrap_or("");
        writeln!(
            writer,
            "  [{symbol:^4}] {label}{pad}  {first}",
            label = row.label
        )?;
        // Prefix width: 2 leading spaces + `[XXXX]` (6) + ` ` (1) +
        // padded label + `  ` (2) = 11 + max_label. Continuation
        // lines align under the first line's value column.
        let indent = " ".repeat(11 + max_label);
        for line in lines {
            writeln!(writer, "{indent}{line}")?;
        }
    }
    if report.critical {
        writeln!(writer)?;
        writeln!(writer, "Critical issues detected; see entries marked FAIL.")?;
    }
    Ok(())
}

fn push_rustc_row(report: &mut DoctorReport, min_version: &str) {
    let output = Command::new("rustc").arg("--version").output();
    let Ok(output) = output else {
        report.critical = true;
        report.rows.push(Row {
            label: "rustc".to_string(),
            value: "rustc not found on PATH".to_string(),
            severity: Severity::Critical,
        });
        return;
    };
    if !output.status.success() {
        report.critical = true;
        report.rows.push(Row {
            label: "rustc".to_string(),
            value: "rustc --version returned a non-zero status".to_string(),
            severity: Severity::Critical,
        });
        return;
    }
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let version = parse_rustc_version(&stdout);
    let severity = match &version {
        Some(v) if !version_at_least(v, min_version) => Severity::Critical,
        _ => Severity::Ok,
    };
    let value = match (&version, severity) {
        (Some(v), Severity::Critical) => {
            format!("{stdout} (below supported {min_version}; host rustc reports {v})")
        }
        _ => stdout,
    };
    if severity == Severity::Critical {
        report.critical = true;
    }
    report.rows.push(Row {
        label: "rustc".to_string(),
        value,
        severity,
    });
}

/// Extract the dotted version (e.g. `1.92.0`) from a rustc
/// `--version` line. Returns `None` if the format is unexpected.
fn parse_rustc_version(line: &str) -> Option<String> {
    // Typical shape: `rustc 1.92.0 (abcdef 2025-10-31)`.
    let rest = line.strip_prefix("rustc ")?;
    let version = rest.split_whitespace().next()?;
    Some(version.to_string())
}

/// Numeric comparison over dotted version strings. Missing
/// components are treated as 0; non-numeric components short-circuit
/// to `false` so unparseable values don't falsely clear the gate.
fn version_at_least(actual: &str, min: &str) -> bool {
    fn parts(s: &str) -> Option<Vec<u64>> {
        s.split('.').map(|p| p.parse::<u64>().ok()).collect()
    }
    let Some(a) = parts(actual) else { return false };
    let Some(m) = parts(min) else { return false };
    for i in 0..a.len().max(m.len()) {
        let av = a.get(i).copied().unwrap_or(0);
        let mv = m.get(i).copied().unwrap_or(0);
        if av > mv {
            return true;
        }
        if av < mv {
            return false;
        }
    }
    true
}

fn push_arch_row(report: &mut DoctorReport, binary: &Path) {
    let host = platform::arch_name();
    match detect_binary_arch(binary) {
        Some(arch) if arch == host => report.rows.push(Row {
            label: "arch".to_string(),
            value: format!("{arch} (matches host)"),
            severity: Severity::Ok,
        }),
        Some(arch) => {
            report.critical = true;
            report.rows.push(Row {
                label: "arch".to_string(),
                value: format!("{arch} (host is {host}; runtime will mis-spawn)"),
                severity: Severity::Critical,
            });
        }
        None => report.rows.push(Row {
            label: "arch".to_string(),
            value: "unknown (file(1) unavailable or unrecognised output)".to_string(),
            severity: Severity::Warn,
        }),
    }
}

/// Invoke `file(1)` on Unix to classify the binary's architecture.
/// Windows and unknown platforms return `None`.
fn detect_binary_arch(path: &Path) -> Option<String> {
    if cfg!(not(unix)) {
        return None;
    }
    let output = Command::new("file").arg(path).output().ok()?;
    if !output.status.success() {
        return None;
    }
    let lower = String::from_utf8_lossy(&output.stdout).to_ascii_lowercase();
    if lower.contains("x86-64") || lower.contains("x86_64") || lower.contains("amd64") {
        Some("x86_64".to_string())
    } else if lower.contains("aarch64") || lower.contains("arm64") {
        Some("aarch64".to_string())
    } else {
        None
    }
}

fn push_metadata_rows(report: &mut DoctorReport, manifest_dir: &Path) -> Result<()> {
    let metadata = cargo_metadata::MetadataCommand::new()
        .manifest_path(manifest_dir.join("Cargo.toml"))
        .exec()
        .with_context(|| "cargo metadata failed")?;

    // Widget discovery from the dep graph.
    let widgets = discover::discover_widgets(manifest_dir)?;
    let widgets_row = if widgets.is_empty() {
        "(none)".to_string()
    } else {
        widgets
            .iter()
            .map(|w| format!("{} ({})", w.crate_name, w.type_name))
            .collect::<Vec<_>>()
            .join("\n")
    };
    report.rows.push(Row {
        label: "native widgets".to_string(),
        value: widgets_row,
        severity: Severity::Ok,
    });

    // Declared renderer-lib version from the dep graph.
    let renderer_version = metadata
        .packages
        .iter()
        .find(|p| p.name == "plushie-renderer-lib")
        .map(|p| p.version.to_string());
    let value = renderer_version.unwrap_or_else(|| "(not in dep graph)".to_string());
    report.rows.push(Row {
        label: "renderer-lib".to_string(),
        value,
        severity: Severity::Ok,
    });

    Ok(())
}

fn push_version_skew_row(report: &mut DoctorReport, binary: &Path, manifest_dir: &Path) {
    let Ok(metadata) = cargo_metadata::MetadataCommand::new()
        .manifest_path(manifest_dir.join("Cargo.toml"))
        .exec()
    else {
        return;
    };
    let expected = metadata
        .packages
        .iter()
        .find(|p| p.name == "plushie-renderer-lib")
        .map(|p| p.version.to_string());
    let Some(expected) = expected else {
        return;
    };

    match probe_renderer_version(binary) {
        Some(actual) if actual == expected => report.rows.push(Row {
            label: "version skew".to_string(),
            value: format!("matched ({actual})"),
            severity: Severity::Ok,
        }),
        Some(actual) => {
            report.critical = true;
            report.rows.push(Row {
                label: "version skew".to_string(),
                value: format!(
                    "app expects {expected} but binary reports {actual}; \
                     handshake will reject incompatible protocol versions"
                ),
                severity: Severity::Critical,
            });
        }
        None => report.rows.push(Row {
            label: "version skew".to_string(),
            value: "could not probe binary (mock handshake failed)".to_string(),
            severity: Severity::Warn,
        }),
    }
}

/// Spawn the renderer with `--mock --json`, feed a minimal Settings
/// message, and parse the `version` field from the hello response.
///
/// The probe is bounded: the child's stdin is closed immediately,
/// and we only read the first line from stdout. A hung or
/// incompatible binary will not block the doctor run forever.
fn probe_renderer_version(binary: &Path) -> Option<String> {
    let mut child = Command::new(binary)
        .args(["--mock", "--json"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;

    let settings = format!(
        r#"{{"type":"settings","session":"","protocol_version":{},"codec":"json"}}{}"#,
        plushie_core::protocol::PROTOCOL_VERSION,
        "\n"
    );
    {
        let mut stdin = child.stdin.take()?;
        let _ = stdin.write_all(settings.as_bytes());
        let _ = stdin.flush();
    }

    let mut buf = Vec::with_capacity(1024);
    let mut stdout = child.stdout.take()?;
    // Bound the read to the first newline so a stalled child can't
    // hang the doctor. 4KB is generous for a hello JSON payload.
    let mut byte = [0u8; 1];
    let start = std::time::Instant::now();
    loop {
        if start.elapsed() > Duration::from_secs(5) {
            let _ = child.kill();
            return None;
        }
        match stdout.read(&mut byte) {
            Ok(0) => break,
            Ok(_) => {
                buf.push(byte[0]);
                if byte[0] == b'\n' {
                    break;
                }
                if buf.len() > 4096 {
                    break;
                }
            }
            Err(_) => break,
        }
    }
    let _ = child.kill();
    let _ = child.wait();
    let line = String::from_utf8(buf).ok()?;
    let value: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
    value.get("version")?.as_str().map(str::to_string)
}

/// Four-step discovery mirroring the SDK's `wire_discovery` chain.
/// Returns the first hit or `None` if everything falls through.
fn discover_renderer(manifest_dir: &Path) -> Option<PathBuf> {
    if let Some(env) = std::env::var_os("PLUSHIE_BINARY_PATH") {
        let p = PathBuf::from(env);
        if p.is_file() {
            return Some(p);
        }
    }
    let target_dir = std::env::var_os("CARGO_TARGET_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| manifest_dir.join("target"));

    // Custom build output.
    for profile in ["release", "debug"] {
        let profile_dir = target_dir.join("plushie-renderer/target").join(profile);
        if let Ok(entries) = std::fs::read_dir(&profile_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if is_executable_file(&path)
                    && path.extension().is_none_or(|e| e != "d" && e != "rlib")
                {
                    return Some(path);
                }
            }
        }
    }

    // Downloaded stock binary.
    let download = target_dir
        .join("plushie/bin")
        .join(platform::download_name());
    if is_executable_file(&download) {
        return Some(download);
    }

    // PATH.
    let name = if cfg!(target_os = "windows") {
        "plushie-renderer.exe"
    } else {
        "plushie-renderer"
    };
    if let Some(path_var) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&path_var) {
            let candidate = dir.join(name);
            if is_executable_file(&candidate) {
                return Some(candidate);
            }
        }
    }
    None
}

#[cfg(unix)]
fn is_executable_file(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    match std::fs::metadata(path) {
        Ok(meta) => meta.is_file() && (meta.permissions().mode() & 0o111) != 0,
        Err(_) => false,
    }
}

#[cfg(not(unix))]
fn is_executable_file(path: &Path) -> bool {
    path.is_file()
}

fn renderer_not_found_hint() -> String {
    "not found. Try one of:\n  \
     cargo plushie build      (widget-aware custom build)\n  \
     cargo plushie download   (precompiled stock binary)\n  \
     cargo install plushie-renderer   (build stock from source)\n\
     or set PLUSHIE_BINARY_PATH to an existing binary."
        .to_string()
}

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

    #[test]
    fn parse_rustc_version_standard_shape() {
        let v = parse_rustc_version("rustc 1.92.0 (abcdef0 2025-10-31)");
        assert_eq!(v.as_deref(), Some("1.92.0"));
    }

    #[test]
    fn parse_rustc_version_rejects_garbage() {
        assert!(parse_rustc_version("").is_none());
        assert!(parse_rustc_version("gcc 14.1.0").is_none());
    }

    #[test]
    fn version_at_least_compares_numerically() {
        assert!(version_at_least("1.92.0", "1.92"));
        assert!(version_at_least("1.92.0", "1.92.0"));
        assert!(version_at_least("2.0.0", "1.92.0"));
        assert!(!version_at_least("1.91.9", "1.92.0"));
        assert!(!version_at_least("1.91", "1.92.0"));
    }

    #[test]
    fn write_report_renders_aligned_columns() {
        let mut report = DoctorReport::default();
        report.rows.push(Row {
            label: "short".to_string(),
            value: "value1".to_string(),
            severity: Severity::Ok,
        });
        report.rows.push(Row {
            label: "longer-label".to_string(),
            value: "value2\ncontinuation".to_string(),
            severity: Severity::Warn,
        });
        let mut buf = Vec::new();
        write_report(&report, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("OK"));
        assert!(out.contains("WARN"));
        assert!(out.contains("continuation"));
    }

    #[test]
    fn write_report_mentions_critical_when_flagged() {
        let mut report = DoctorReport {
            critical: true,
            ..Default::default()
        };
        report.rows.push(Row {
            label: "renderer".to_string(),
            value: "missing".to_string(),
            severity: Severity::Critical,
        });
        let mut buf = Vec::new();
        write_report(&report, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("Critical issues detected"));
    }
}