yosh-plugin-manager 0.2.7

Plugin manager for yosh shell
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
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
//! Declarative scenarios for `yosh plugin test`. One TOML file per
//! scenario; each scenario is a sequence of `step` entries, each step
//! is one exec / hook invocation plus an `expect` block.

use std::collections::BTreeMap;
use std::path::PathBuf;

use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct Scenario {
    pub plugin: PathBuf,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub env: EnvConfig,
    #[serde(default)]
    pub files: BTreeMap<String, String>,
    #[serde(rename = "step", default)]
    pub steps: Vec<Step>,
}

#[derive(Debug, Default, Deserialize)]
pub struct EnvConfig {
    #[serde(default)]
    pub caps: Vec<String>,
    #[serde(default)]
    pub vars: BTreeMap<String, String>,
    #[serde(default)]
    pub exported: Vec<String>,
    #[serde(default)]
    pub cwd: String,
    #[serde(default)]
    pub allow_exec: Vec<String>,
    #[serde(default)]
    pub sandbox_root: String,
    #[serde(default = "default_timeout_ms")]
    pub timeout_ms: u64,
}

fn default_timeout_ms() -> u64 {
    5000
}

#[derive(Debug, Deserialize)]
#[serde(tag = "call", rename_all = "lowercase")]
pub enum Step {
    Exec {
        args: Vec<String>,
        #[serde(default)]
        expect: Expect,
    },
    Hook {
        name: HookName,
        args: Vec<toml::Value>,
        #[serde(default)]
        expect: Expect,
    },
}

#[derive(Debug, Deserialize, PartialEq, Eq, Clone, Copy)]
#[serde(rename_all = "kebab-case")]
pub enum HookName {
    PreExec,
    PostExec,
    OnCd,
    PrePrompt,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Expect {
    pub exit: Option<i32>,
    pub stdout: Option<String>,
    pub stderr: Option<String>,
    pub stdout_contains: Option<String>,
    pub stderr_contains: Option<String>,
    pub stdout_regex: Option<String>,
    pub stderr_regex: Option<String>,
    pub vars_set: Option<BTreeMap<String, String>>,
    pub vars_export: Option<BTreeMap<String, String>>,
    pub files_write: Option<BTreeMap<String, FileExpect>>,
    pub exec_called: Option<Vec<ExecCallExpect>>,
    pub trap: Option<bool>,
}

// Note: `denied: bool` (listed in spec §5 as a future expect key) is
// intentionally not implemented here. Observing capability-denied
// errors from the harness requires plumbing a counter through every
// host import (each `Err(Denied)` increments). Deferred — for now,
// authors detect denial via `stdout_regex` on guest-side error
// handling or via specific `exit` codes the guest returns on
// `Err(ErrorCode::Denied)`.

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum FileExpect {
    Bytes(String),
    Struct {
        #[serde(default)]
        len: Option<usize>,
        #[serde(default)]
        bytes_eq: Option<String>,
    },
}

#[derive(Debug, Deserialize)]
pub struct ExecCallExpect {
    pub program: String,
    #[serde(default)]
    pub args: Vec<String>,
    pub exit: Option<i32>,
}

pub fn parse(path: &std::path::Path) -> Result<Scenario, String> {
    let s = std::fs::read_to_string(path).map_err(|e| format!("read {}: {}", path.display(), e))?;
    let parsed: Scenario =
        toml::from_str(&s).map_err(|e| format!("parse {}: {}", path.display(), e))?;
    Ok(parsed)
}

use crate::runner::{HookCall, RunOutcome, invoke_exec, invoke_hook, load_plugin};
use crate::test_host::TestState;
use yosh_plugin_api::pattern::CommandPattern;
use yosh_plugin_api::{capabilities_to_bitflags, parse_capability};

#[derive(Debug)]
pub enum StepResult {
    Pass,
    Fail(String),
}

pub fn run_scenario(path: &std::path::Path) -> Vec<StepResult> {
    let scenario = match parse(path) {
        Ok(s) => s,
        Err(e) => return vec![StepResult::Fail(format!("parse error: {}", e))],
    };

    let wasm_path = path
        .parent()
        .map(|p| p.join(&scenario.plugin))
        .unwrap_or(scenario.plugin.clone());
    let mut results = Vec::new();

    for (idx, step) in scenario.steps.iter().enumerate() {
        let state = build_state(&scenario);
        let timeout = std::time::Duration::from_millis(scenario.env.timeout_ms);
        let loaded = match load_plugin(&wasm_path, state, timeout) {
            Ok(l) => l,
            Err(e) => {
                results.push(StepResult::Fail(format!("step {}: load: {}", idx + 1, e)));
                continue;
            }
        };

        let (outcome, expect) = match step {
            Step::Exec { args, expect } => {
                if args.is_empty() {
                    results.push(StepResult::Fail(format!(
                        "step {}: exec needs at least 1 arg",
                        idx + 1
                    )));
                    continue;
                }
                let (cmd, rest) = (&args[0], &args[1..]);
                (invoke_exec(loaded, cmd, rest), expect)
            }
            Step::Hook { name, args, expect } => {
                let call = match build_hook_call(*name, args) {
                    Ok(c) => c,
                    Err(e) => {
                        results.push(StepResult::Fail(format!(
                            "step {}: hook args: {}",
                            idx + 1,
                            e
                        )));
                        continue;
                    }
                };
                (invoke_hook(loaded, call), expect)
            }
        };

        results.push(evaluate(idx + 1, &outcome, expect));
    }

    if results.is_empty() {
        results.push(StepResult::Pass);
    }
    results
}

fn build_state(scenario: &Scenario) -> TestState {
    let mut state = TestState::default();
    let parsed_caps: Vec<_> = scenario
        .env
        .caps
        .iter()
        .filter_map(|s| parse_capability(s))
        .collect();
    state.caps = capabilities_to_bitflags(&parsed_caps);
    for (k, v) in &scenario.env.vars {
        state.vars.insert(k.clone(), v.clone());
    }
    for k in &scenario.env.exported {
        state.exported.insert(k.clone());
    }
    if !scenario.env.cwd.is_empty() {
        state.cwd = scenario.env.cwd.clone().into();
    }
    state.allow_exec = scenario
        .env
        .allow_exec
        .iter()
        .filter_map(|p| CommandPattern::parse(p).ok())
        .collect();
    if !scenario.env.sandbox_root.is_empty() {
        state.sandbox_root = Some(std::path::PathBuf::from(&scenario.env.sandbox_root));
    } else {
        for (k, v) in &scenario.files {
            state
                .files
                .insert(std::path::PathBuf::from(k), v.as_bytes().to_vec());
        }
    }
    state
}

fn build_hook_call(name: HookName, args: &[toml::Value]) -> Result<HookCall, String> {
    fn s(v: &toml::Value) -> Result<String, String> {
        v.as_str()
            .map(|s| s.to_string())
            .ok_or_else(|| "expected string".into())
    }
    fn i(v: &toml::Value) -> Result<i32, String> {
        v.as_integer()
            .map(|i| i as i32)
            .ok_or_else(|| "expected integer".into())
    }
    match name {
        HookName::PreExec => Ok(HookCall::PreExec {
            command_line: s(args.first().ok_or("missing arg")?)?,
        }),
        HookName::PostExec => {
            let cl = s(args.first().ok_or("missing command_line")?)?;
            let ec = i(args.get(1).ok_or("missing exit_code")?)?;
            Ok(HookCall::PostExec {
                command_line: cl,
                exit_code: ec,
            })
        }
        HookName::OnCd => {
            let old = s(args.first().ok_or("missing old")?)?;
            let new = s(args.get(1).ok_or("missing new")?)?;
            Ok(HookCall::OnCd { old, new })
        }
        HookName::PrePrompt => Ok(HookCall::PrePrompt),
    }
}

fn evaluate(step_idx: usize, o: &RunOutcome, e: &Expect) -> StepResult {
    macro_rules! fail {
        ($($t:tt)*) => {{ return StepResult::Fail(format!("step {}: {}", step_idx, format_args!($($t)*))) }};
    }

    if let Some(want) = e.exit {
        match o.exit_code {
            Some(got) if got == want => {}
            Some(got) => fail!("exit: want {}, got {}", want, got),
            None => fail!("exit: want {}, got (no exit code — hook?)", want),
        }
    }

    let stdout_str = String::from_utf8_lossy(&o.stdout);
    let stderr_str = String::from_utf8_lossy(&o.stderr);

    if let Some(want) = &e.stdout
        && stdout_str != *want
    {
        fail!("stdout mismatch: want {:?}, got {:?}", want, stdout_str);
    }
    if let Some(want) = &e.stderr
        && stderr_str != *want
    {
        fail!("stderr mismatch: want {:?}, got {:?}", want, stderr_str);
    }
    if let Some(sub) = &e.stdout_contains
        && !stdout_str.contains(sub.as_str())
    {
        fail!("stdout_contains {:?} not found in {:?}", sub, stdout_str);
    }
    if let Some(sub) = &e.stderr_contains
        && !stderr_str.contains(sub.as_str())
    {
        fail!("stderr_contains {:?} not found in {:?}", sub, stderr_str);
    }
    if let Some(re) = &e.stdout_regex {
        let rx = regex::Regex::new(re).map_err(|err| err.to_string());
        match rx {
            Ok(rx) if !rx.is_match(&stdout_str) => {
                fail!("stdout_regex {:?} did not match {:?}", re, stdout_str)
            }
            Err(err) => fail!("stdout_regex invalid: {}", err),
            _ => {}
        }
    }
    if let Some(re) = &e.stderr_regex {
        let rx = regex::Regex::new(re).map_err(|err| err.to_string());
        match rx {
            Ok(rx) if !rx.is_match(&stderr_str) => {
                fail!("stderr_regex {:?} did not match {:?}", re, stderr_str)
            }
            Err(err) => fail!("stderr_regex invalid: {}", err),
            _ => {}
        }
    }

    if let Some(want) = &e.vars_set {
        let got: BTreeMap<String, String> = o.set_log.iter().cloned().collect();
        if got != *want {
            fail!("vars_set: want {:?}, got {:?}", want, got);
        }
    }
    if let Some(want) = &e.vars_export {
        let got: BTreeMap<String, String> = o.export_log.iter().cloned().collect();
        if got != *want {
            fail!("vars_export: want {:?}, got {:?}", want, got);
        }
    }

    if let Some(want) = &e.files_write {
        let got: BTreeMap<String, usize> = o
            .write_log
            .iter()
            .map(|(p, n)| (p.display().to_string(), *n))
            .collect();
        for (path, expectation) in want {
            match expectation {
                FileExpect::Bytes(b) => {
                    let want_len = b.len();
                    match got.get(path) {
                        Some(actual) if *actual == want_len => {}
                        Some(actual) => fail!(
                            "files_write[{}] len: want {}, got {}",
                            path,
                            want_len,
                            actual
                        ),
                        None => fail!("files_write[{}] not written", path),
                    }
                }
                FileExpect::Struct { len, bytes_eq } => {
                    if let Some(l) = len {
                        match got.get(path) {
                            Some(actual) if *actual == *l => {}
                            Some(actual) => {
                                fail!("files_write[{}] len: want {}, got {}", path, l, actual)
                            }
                            None => fail!("files_write[{}] not written", path),
                        }
                    }
                    if let Some(b) = bytes_eq {
                        let want_len = b.len();
                        match got.get(path) {
                            Some(actual) if *actual == want_len => {}
                            Some(actual) => fail!(
                                "files_write[{}] bytes_eq len: want {}, got {}",
                                path,
                                want_len,
                                actual
                            ),
                            None => fail!("files_write[{}] not written", path),
                        }
                    }
                }
            }
        }
    }

    if let Some(want_seq) = &e.exec_called {
        if want_seq.len() != o.exec_log.len() {
            fail!(
                "exec_called: want {} calls, got {}",
                want_seq.len(),
                o.exec_log.len()
            );
        }
        for (i, (w, g)) in want_seq.iter().zip(o.exec_log.iter()).enumerate() {
            if w.program != g.program {
                fail!(
                    "exec_called[{}].program: want {}, got {}",
                    i,
                    w.program,
                    g.program
                );
            }
            if w.args != g.args {
                fail!(
                    "exec_called[{}].args: want {:?}, got {:?}",
                    i,
                    w.args,
                    g.args
                );
            }
            if let Some(exit) = w.exit
                && exit != g.exit_code
            {
                fail!(
                    "exec_called[{}].exit: want {}, got {}",
                    i,
                    exit,
                    g.exit_code
                );
            }
        }
    }

    if let Some(want) = e.trap {
        let got = o.error_kind == Some("trap");
        if got != want {
            fail!("trap: want {}, got {}", want, got);
        }
    }

    StepResult::Pass
}

#[cfg(test)]
mod evaluator_tests {
    use super::*;
    use crate::runner::RunOutcome;

    fn outcome_with(exit: Option<i32>, stdout: &[u8]) -> RunOutcome {
        RunOutcome {
            exit_code: exit,
            stdout: stdout.to_vec(),
            stderr: Vec::new(),
            set_log: Vec::new(),
            export_log: Vec::new(),
            write_log: Vec::new(),
            exec_log: Vec::new(),
            error: None,
            error_kind: None,
        }
    }

    #[test]
    fn expect_exit_match_passes() {
        let o = outcome_with(Some(0), b"");
        let e = Expect {
            exit: Some(0),
            ..Default::default()
        };
        assert!(matches!(evaluate(1, &o, &e), StepResult::Pass));
    }

    #[test]
    fn expect_exit_mismatch_fails() {
        let o = outcome_with(Some(2), b"");
        let e = Expect {
            exit: Some(0),
            ..Default::default()
        };
        match evaluate(1, &o, &e) {
            StepResult::Fail(s) => assert!(s.contains("exit")),
            _ => panic!("expected fail"),
        }
    }

    #[test]
    fn expect_stdout_contains_works() {
        let o = outcome_with(Some(0), b"hello world\n");
        let e = Expect {
            stdout_contains: Some("world".into()),
            ..Default::default()
        };
        assert!(matches!(evaluate(1, &o, &e), StepResult::Pass));
    }

    #[test]
    fn run_dir_collects_toml_files() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.toml");
        std::fs::write(
            &a,
            r#"
            plugin = "missing.wasm"
            [[step]]
            call = "exec"
            args = ["x"]
        "#,
        )
        .unwrap();
        let reports = run_dir(tmp.path(), None);
        assert_eq!(reports.len(), 1);
        assert!(!reports[0].passed()); // wasm missing
    }

    #[test]
    fn format_summary_json_has_summary_line() {
        let reports = vec![];
        let s = format_summary_json(&reports);
        assert!(s.contains("\"summary\""));
    }
}

#[derive(Debug)]
pub struct ScenarioReport {
    pub file: std::path::PathBuf,
    pub steps: Vec<StepResult>,
}

impl ScenarioReport {
    pub fn passed(&self) -> bool {
        self.steps.iter().all(|r| matches!(r, StepResult::Pass))
    }
}

pub fn run_dir(path: &std::path::Path, filter: Option<&str>) -> Vec<ScenarioReport> {
    let mut reports = Vec::new();
    let filter_rx = filter.and_then(|f| match regex::Regex::new(f) {
        Ok(rx) => Some(rx),
        Err(e) => {
            eprintln!(
                "yosh-plugin: ignoring invalid --filter regex {:?}: {}",
                f, e
            );
            None
        }
    });

    fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
        let Ok(rd) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in rd.flatten() {
            let p = entry.path();
            if p.is_dir() {
                walk(&p, out);
            } else if p.extension().and_then(|s| s.to_str()) == Some("toml") {
                out.push(p);
            }
        }
    }

    let mut paths = Vec::new();
    if path.is_dir() {
        walk(path, &mut paths);
    } else if path.exists() {
        paths.push(path.to_path_buf());
    }
    paths.sort();

    for p in paths {
        if let Some(rx) = &filter_rx
            && !rx.is_match(&p.to_string_lossy())
        {
            continue;
        }
        let results = run_scenario(&p);
        reports.push(ScenarioReport {
            file: p,
            steps: results,
        });
    }
    reports
}

pub fn format_summary_human(reports: &[ScenarioReport]) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let _ = writeln!(out, "running {} scenarios", reports.len());
    let mut passed = 0;
    let mut failed = 0;
    for r in reports {
        if r.passed() {
            passed += 1;
            let _ = writeln!(out, "  \u{2713} {}", r.file.display());
        } else {
            failed += 1;
            let _ = writeln!(out, "  \u{2717} {}", r.file.display());
            for s in &r.steps {
                if let StepResult::Fail(msg) = s {
                    let _ = writeln!(out, "      {}", msg);
                }
            }
        }
    }
    let _ = writeln!(out, "{} passed, {} failed", passed, failed);
    out
}

pub fn format_summary_json(reports: &[ScenarioReport]) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let mut passed = 0;
    let mut failed = 0;
    for r in reports {
        if r.passed() {
            passed += 1;
            let _ = writeln!(
                out,
                "{}",
                serde_json::json!({
                    "file": r.file.display().to_string(),
                    "status": "pass",
                    "steps": r.steps.len()
                })
            );
        } else {
            failed += 1;
            let reason = r
                .steps
                .iter()
                .find_map(|s| match s {
                    StepResult::Fail(m) => Some(m.clone()),
                    _ => None,
                })
                .unwrap_or_default();
            let _ = writeln!(
                out,
                "{}",
                serde_json::json!({
                    "file": r.file.display().to_string(),
                    "status": "fail",
                    "reason": reason
                })
            );
        }
    }
    let _ = writeln!(
        out,
        "{}",
        serde_json::json!({
            "summary": { "passed": passed, "failed": failed, "total": reports.len() }
        })
    );
    out
}

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

    fn parse_str(s: &str) -> Result<Scenario, String> {
        toml::from_str(s).map_err(|e| e.to_string())
    }

    #[test]
    fn minimal_scenario_parses() {
        let sc = parse_str(
            r#"
            plugin = "a.wasm"
            [[step]]
            call = "exec"
            args = ["echo", "hi"]
        "#,
        )
        .unwrap();
        assert_eq!(sc.plugin.to_str().unwrap(), "a.wasm");
        assert_eq!(sc.steps.len(), 1);
        match &sc.steps[0] {
            Step::Exec { args, .. } => {
                assert_eq!(args, &vec!["echo".to_string(), "hi".to_string()])
            }
            _ => panic!("expected exec step"),
        }
    }

    #[test]
    fn unknown_expect_key_rejected() {
        let err = parse_str(
            r#"
            plugin = "a.wasm"
            [[step]]
            call = "exec"
            args = ["x"]
            [step.expect]
            mystery = "boom"
        "#,
        )
        .unwrap_err();
        assert!(err.contains("mystery") || err.contains("unknown field"));
    }

    #[test]
    fn hook_step_parses() {
        let sc = parse_str(
            r#"
            plugin = "a.wasm"
            [[step]]
            call = "hook"
            name = "on-cd"
            args = ["/old", "/new"]
        "#,
        )
        .unwrap();
        match &sc.steps[0] {
            Step::Hook { name, args, .. } => {
                assert_eq!(*name, HookName::OnCd);
                assert_eq!(args.len(), 2);
            }
            _ => panic!("expected hook step"),
        }
    }
}