kaish-kernel 0.16.0

Core kernel for kaish: lexer, parser, interpreter, and runtime
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
//! set — Set shell options (like set -e, set -o trash).

use async_trait::async_trait;
use clap::{CommandFactory, Parser};

use crate::ast::Value;
use crate::interpreter::{ExecResult, OutputData, OutputNode};
use crate::tools::{schema_from_clap, ExecContext, ToolCtx, GlobalFlags, Tool, ToolArgs, ToolSchema};

/// Set tool: configure shell options.
///
/// Supports:
/// - `-e` / `+e`: Enable/disable error-exit mode (exit on command failure)
/// - `-o trash` / `+o trash`: Enable/disable trash-on-delete for rm
/// - `-o glob` / `+o glob`: Enable/disable bare glob expansion
/// - `-o output-limit[=SIZE]` / `+o output-limit`: Cap or uncap output size
///
/// An unrecognized bare short flag (`set -q`, `set -v`) is silently ignored
/// for bash compatibility — kaish implements one small, enumerable subset of
/// bash's option surface, not the rest. `-o NAME` is different: NAME names
/// one specific thing out of that small set, so a typo or a bash option
/// kaish doesn't have (`pipefail`) fails loudly instead of no-opping — see
/// `apply_set_o`.
pub struct Set;

/// The `-o`/`+o` names kaish implements.
const VALID_SET_O_NAMES: &[&str] = &["glob", "output-limit[=SIZE]", "pipefail", "trash"];

/// Applies one `-o NAME` (`enable = true`) or `+o NAME` (`enable = false`).
///
/// Shared by both parse shapes `set` can end up with for `-o NAME`: the
/// ordinary `positional = ["-o", "NAME"]` shape, and the flags-split shape
/// (`flags = {"o"}, positional = ["NAME"]`) the binder produces when `-o`
/// arrives as the only flag on its token. Keeping one function means the two
/// shapes can't drift into accepting different names.
fn apply_set_o(ctx: &mut ExecContext, name: &str, enable: bool) -> Result<(), String> {
    // Quote back the sigil the author actually typed. `set +o bogus` reporting
    // `set: -o bogus` sends them looking at a line they did not write.
    let sigil = if enable { '-' } else { '+' };
    match name {
        "trash" => ctx.scope.set_trash_enabled(enable),
        "glob" => ctx.scope.set_glob_enabled(enable),
        "pipefail" => ctx.scope.set_pipefail_enabled(enable),
        "output-limit" => {
            if enable {
                if ctx.output_limit.max_bytes().is_none() {
                    ctx.output_limit.set_limit(Some(
                        crate::output_limit::OutputLimitConfig::default_limit(),
                    ));
                }
            } else {
                ctx.output_limit.set_limit(None);
            }
        }
        _ if enable && name.starts_with("output-limit=") => {
            let size_str = &name["output-limit=".len()..];
            let bytes = crate::output_limit::parse_size(size_str)
                .map_err(|e| format!("set: {sigil}o output-limit={size_str}: {e}"))?;
            ctx.output_limit.set_limit(Some(bytes));
        }
        _ => {
            return Err(format!(
                "set: {sigil}o {name}: unknown option — valid names are {}",
                VALID_SET_O_NAMES.join(", ")
            ));
        }
    }
    Ok(())
}

/// clap-derived argv layer for set.
///
/// `set` has bespoke argv handling — it reads `-e`/`+e`/`-o NAME` from
/// args.flags and args.positional directly. clap is only used here as a
/// schema sink and to honor the global `--json` flag.
#[derive(Parser, Debug)]
#[command(name = "set", about = "Set shell options")]
struct SetArgs {
    #[command(flatten)]
    global: GlobalFlags,

    /// Shell option arguments (`-e`, `+e`, `-o NAME`, `+o NAME`).
    options: Vec<String>,
}

#[async_trait]
impl Tool for Set {
    fn name(&self) -> &str {
        "set"
    }

    fn schema(&self) -> ToolSchema {
        schema_from_clap(
            &SetArgs::command(),
            "set",
            "Set shell options",
            [
                ("Exit on error", "set -e"),
                ("Disable exit on error", "set +e"),
                ("Enable trash-on-delete", "set -o trash"),
                ("Disable glob expansion", "set +o glob"),
            ],
        )
    }

    async fn execute(&self, args: ToolArgs, ctx: &mut dyn ToolCtx) -> ExecResult {
        let Some(ctx) = ctx.as_any_mut().downcast_mut::<ExecContext>() else {
            return ExecResult::failure(1, "internal error: kernel builtin requires ExecContext");
        };
        // set has bespoke argv handling — strip the user-provided -e / -o etc.
        // tokens from the argv before handing to clap, otherwise clap would
        // reject unknown flags. Only `--json` (global) needs to clap-parse.
        let mut clap_argv: Vec<String> = Vec::new();
        if args.flags.contains("json") {
            clap_argv.push("--json".to_string());
        }
        let parsed = match SetArgs::try_parse_from(
            std::iter::once("set".to_string()).chain(clap_argv),
        ) {
            Ok(p) => p,
            Err(e) => return ExecResult::failure(2, format!("set: {e}")),
        };
        parsed.global.apply(ctx);

        // No arguments: show current settings
        if args.positional.is_empty() && args.flags.is_empty() {
            let mut output = String::new();
            if ctx.scope.error_exit_enabled() {
                output.push_str("set -e\n");
            }
            if ctx.scope.trash_enabled() {
                output.push_str("set -o trash\n");
            }
            if !ctx.scope.glob_enabled() {
                output.push_str("set +o glob\n");
            }
            if let Some(bytes) = ctx.output_limit.max_bytes() {
                output.push_str(&format!("set -o output-limit={}\n", format_size_for_set(bytes)));
            }
            return ExecResult::with_output(OutputData::text(output.trim_end()));
        }

        // Process flags (from parser: ShortFlag("e") -> args.flags contains "e")
        for flag in &args.flags {
            match flag.as_str() {
                "e" => ctx.scope.set_error_exit(true),
                "o" => {} // handled below with positional args
                // Deliberately left silent: unlike `-o NAME`, a bare short
                // flag here (`-u`, `-x`, `-v`, a stray "q" from `set -q`,
                // ...) isn't drawn from one small named set we can check
                // against and report — bash has dozens, kaish implements
                // only `-e`/`-o`, and scripts written for bash routinely
                // carry the rest (`set -x` for tracing, `-u`/`-v` and more).
                // Rejecting them would break real scripts that already
                // tolerate kaish ignoring what it doesn't implement, for no
                // gain: there's no fixed list to name in the error the way
                // `apply_set_o` names its valid `-o` set.
                _ => {}
            }
        }

        // Process positional args.
        // From parser: PlusFlag("e") -> String("+e"), String("-o") followed by String("trash"), etc.
        let positionals: Vec<&str> = args
            .positional
            .iter()
            .filter_map(|v| match v {
                Value::String(s) => Some(s.as_str()),
                _ => None,
            })
            .collect();

        // `set -o` with no name reports every option and its state, as bash
        // does. Without this there was no way to ASK whether an option was on
        // — bare `set` prints only what differs from the default, so an
        // option at its default was indistinguishable from an unknown one.
        // Both parse shapes reach here: `flags = {"o"}` with nothing after,
        // and a literal `"-o"` positional that is last.
        let bare_dash_o = (args.flags.contains("o") && positionals.is_empty())
            || positionals.last().is_some_and(|p| *p == "-o");
        if bare_dash_o {
            return ExecResult::with_output(OutputData::table(
                vec!["OPTION".to_string(), "STATE".to_string()],
                vec![
                    option_row("errexit", ctx.scope.error_exit_enabled()),
                    option_row("glob", ctx.scope.glob_enabled()),
                    option_row("pipefail", ctx.scope.pipefail_enabled()),
                    option_row("output-limit", ctx.output_limit.max_bytes().is_some()),
                    option_row("trash", ctx.scope.trash_enabled()),
                ],
            ));
        }

        let mut i = 0;
        while i < positionals.len() {
            let opt = positionals[i];
            match opt {
                "-e" => ctx.scope.set_error_exit(true),
                "+e" => ctx.scope.set_error_exit(false),
                "-o" => {
                    // Consume next positional as option name
                    if let Some(&name) = positionals.get(i + 1) {
                        if let Err(msg) = apply_set_o(ctx, name, true) {
                            return ExecResult::failure(1, msg);
                        }
                        i += 1; // skip the option name
                    }
                }
                "+o" => {
                    if let Some(&name) = positionals.get(i + 1) {
                        if let Err(msg) = apply_set_o(ctx, name, false) {
                            return ExecResult::failure(1, msg);
                        }
                        i += 1;
                    }
                }
                // Same reasoning as the flags loop above: a bare token here
                // is a bash short flag/word kaish doesn't implement (e.g.
                // "-u" arriving as a positional in some parses), not a `-o`
                // name — no fixed list to check it against.
                _ => {}
            }
            i += 1;
        }

        // Handle case where parser split `-o` into flags and the option name
        // ended up as a bare positional (flags=["o"], positional=["trash"]).
        // Only fire if no "-o" or "+o" appeared in positionals (which would have
        // already consumed the option name above). Only "-o" reaches here as a
        // bare flag: `+o` always arrives as a literal "+o" positional (see the
        // `PlusFlag` handling in parser.rs), so this path never needs to
        // disable — it always calls `apply_set_o` with `enable = true`, same
        // as the ordinary `"-o"` branch above, so the two shapes agree on
        // which names are valid (`apply_set_o` is the single source of truth).
        if args.flags.contains("o")
            && !positionals.iter().any(|p| *p == "-o" || *p == "+o")
        {
            if let Some(&name) = positionals.first() {
                if let Err(msg) = apply_set_o(ctx, name, true) {
                    return ExecResult::failure(1, msg);
                }
            }
        }

        ExecResult::success("")
    }
}

/// One `set -o` report row. `on`/`off` matches what bash prints.
fn option_row(name: &str, enabled: bool) -> OutputNode {
    OutputNode::new(name).with_cells(vec![if enabled { "on" } else { "off" }.to_string()])
}

fn format_size_for_set(bytes: usize) -> String {
    if bytes % (1024 * 1024) == 0 {
        format!("{}M", bytes / (1024 * 1024))
    } else if bytes % 1024 == 0 {
        format!("{}K", bytes / 1024)
    } else {
        bytes.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vfs::{MemoryFs, VfsRouter};
    use std::sync::Arc;

    fn make_ctx() -> ExecContext {
        let mut vfs = VfsRouter::new();
        vfs.mount("/", MemoryFs::new());
        ExecContext::new(Arc::new(vfs))
    }

    #[tokio::test]
    async fn test_set_e_enables_error_exit() {
        let mut ctx = make_ctx();
        assert!(!ctx.scope.error_exit_enabled());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-e".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(ctx.scope.error_exit_enabled());
    }

    #[tokio::test]
    async fn test_set_plus_e_disables_error_exit() {
        let mut ctx = make_ctx();
        ctx.scope.set_error_exit(true);
        assert!(ctx.scope.error_exit_enabled());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("+e".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(!ctx.scope.error_exit_enabled());
    }

    #[tokio::test]
    async fn test_set_ignores_unknown_bare_flags() {
        // Bare short flags kaish doesn't implement (-u, -x) are still
        // silently ignored for bash compatibility — see the comment on the
        // flags-loop `_ => {}` arm.
        let mut ctx = make_ctx();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-u".into()));
        args.positional.push(Value::String("-x".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
    }

    /// `set -o pipefail` used to be refused as unimplemented. It is
    /// implemented now, so it succeeds and turns the option on. An option
    /// kaish genuinely does not have must still be refused, or this would
    /// prove only that `set -o` stopped checking anything.
    #[tokio::test]
    async fn test_set_o_pipefail_enables_it() {
        let mut ctx = make_ctx();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-o".into()));
        args.positional.push(Value::String("pipefail".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok(), "err={}", result.err);
        assert!(ctx.scope.pipefail_enabled());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("+o".into()));
        args.positional.push(Value::String("pipefail".into()));
        assert!(Set.execute(args, &mut ctx).await.ok());
        assert!(!ctx.scope.pipefail_enabled());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-o".into()));
        args.positional.push(Value::String("nosuchoption".into()));
        let result = Set.execute(args, &mut ctx).await;
        assert!(!result.ok(), "an unknown -o name must still be refused");
    }

    #[tokio::test]
    async fn test_set_no_args_shows_settings() {
        let mut ctx = make_ctx();
        ctx.scope.set_error_exit(true);

        let args = ToolArgs::new();
        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(result.text_out().contains("set -e"));
    }

    #[tokio::test]
    async fn test_set_euo_pipefail_sets_all_of_them() {
        // The muscle-memory prelude. It used to die on `-o pipefail`, which
        // in an embedder whose exit status is a policy decision turned a
        // habitual first line into a deny-everything guard.
        let mut ctx = make_ctx();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-e".into()));
        args.positional.push(Value::String("-u".into()));
        args.positional.push(Value::String("-o".into()));
        args.positional.push(Value::String("pipefail".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok(), "err={}", result.err);
        assert!(ctx.scope.error_exit_enabled());
        assert!(ctx.scope.pipefail_enabled());
    }

    #[tokio::test]
    async fn the_flag_split_parse_path_still_enables() {
        // When the parser produces `flags=["o"] positional=["trash"]` the
        // option never reaches the `-o` branch, so the fallback below it has
        // to catch the name. Pinned to a surviving option after the approval
        // policy it originally covered was removed — the parse quirk is the
        // thing under test, not the option.
        let mut ctx = make_ctx();

        let mut args = ToolArgs::new();
        args.flags.insert("o".to_string());
        args.positional.push(Value::String("trash".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(ctx.scope.trash_enabled());
    }

    #[tokio::test]
    async fn test_set_o_trash_enables() {
        let mut ctx = make_ctx();
        assert!(!ctx.scope.trash_enabled());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-o".into()));
        args.positional.push(Value::String("trash".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(ctx.scope.trash_enabled());
    }

    #[tokio::test]
    async fn test_set_plus_o_trash_disables() {
        let mut ctx = make_ctx();
        ctx.scope.set_trash_enabled(true);

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("+o".into()));
        args.positional.push(Value::String("trash".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(!ctx.scope.trash_enabled());
    }

    #[tokio::test]
    async fn test_set_no_args_shows_all_options() {
        let mut ctx = make_ctx();
        ctx.scope.set_trash_enabled(true);

        let args = ToolArgs::new();
        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(result.text_out().contains("set -o trash"));
    }

    #[tokio::test]
    async fn test_set_o_unknown_name_fails() {
        let mut ctx = make_ctx();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-o".into()));
        args.positional.push(Value::String("bogusname".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(!result.ok());
        assert!(result.err.contains("bogusname"));
        assert!(
            result.err.contains("glob") && result.err.contains("trash") && result.err.contains("output-limit"),
            "error should name the valid set: {:?}",
            result.err
        );
    }

    #[tokio::test]
    async fn test_set_o_output_limit_enables_default() {
        let mut ctx = make_ctx();
        assert!(!ctx.output_limit.is_enabled());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-o".into()));
        args.positional.push(Value::String("output-limit".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(ctx.output_limit.is_enabled());
        assert_eq!(ctx.output_limit.max_bytes(), Some(crate::output_limit::OutputLimitConfig::default_limit()));
    }

    #[tokio::test]
    async fn test_set_o_output_limit_with_size() {
        let mut ctx = make_ctx();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("-o".into()));
        args.positional.push(Value::String("output-limit=16K".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert_eq!(ctx.output_limit.max_bytes(), Some(16 * 1024));
    }

    #[tokio::test]
    async fn test_set_plus_o_output_limit_disables() {
        let mut ctx = make_ctx();
        ctx.output_limit.set_limit(Some(8 * 1024));
        assert!(ctx.output_limit.is_enabled());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("+o".into()));
        args.positional.push(Value::String("output-limit".into()));

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(!ctx.output_limit.is_enabled());
    }

    #[tokio::test]
    async fn test_set_no_args_shows_output_limit() {
        let mut ctx = make_ctx();
        ctx.output_limit.set_limit(Some(4 * 1024));

        let args = ToolArgs::new();
        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(result.text_out().contains("set -o output-limit=4K"));
    }

    #[tokio::test]
    async fn test_set_no_args_hides_output_limit_when_disabled() {
        let mut ctx = make_ctx();
        // output_limit disabled by default in test ctx

        let args = ToolArgs::new();
        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(!result.text_out().contains("output-limit"));
    }

    #[test]
    fn test_format_size_for_set() {
        assert_eq!(format_size_for_set(1024), "1K");
        assert_eq!(format_size_for_set(8 * 1024), "8K");
        assert_eq!(format_size_for_set(1024 * 1024), "1M");
        assert_eq!(format_size_for_set(512), "512");
    }
}