kaish-kernel 0.8.2

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
//! set — Set shell options (like set -e, set -o latch).

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

use crate::ast::Value;
use crate::interpreter::{ExecResult, OutputData};
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 latch` / `+o latch`: Enable/disable confirmation latch for dangerous ops
/// - `-o trash` / `+o trash`: Enable/disable trash-on-delete for rm
///
/// Unrecognized options are silently ignored for bash compatibility.
pub struct Set;

/// clap-derived argv layer for set. See docs/clap-migration.md.
///
/// `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 confirmation latch", "set -o latch"),
                ("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.latch_enabled() {
                output.push_str("set -o latch\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
                _ => {}   // silently ignore for bash compatibility
            }
        }

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

        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) {
                        match name {
                            "latch" => ctx.scope.set_latch_enabled(true),
                            "trash" => ctx.scope.set_trash_enabled(true),
                            "glob" => ctx.scope.set_glob_enabled(true),
                            _ => {
                                if name == "output-limit" || name.starts_with("output-limit=") {
                                    if let Some(size_str) = name.strip_prefix("output-limit=") {
                                        if let Ok(bytes) = crate::output_limit::parse_size(size_str) {
                                            ctx.output_limit.set_limit(Some(bytes));
                                        }
                                    } else if ctx.output_limit.max_bytes().is_none() {
                                        ctx.output_limit.set_limit(Some(crate::output_limit::OutputLimitConfig::default_limit()));
                                    }
                                }
                            }
                        }
                        i += 1; // skip the option name
                    }
                }
                "+o" => {
                    if let Some(&name) = positionals.get(i + 1) {
                        match name {
                            "latch" => ctx.scope.set_latch_enabled(false),
                            "trash" => ctx.scope.set_trash_enabled(false),
                            "glob" => ctx.scope.set_glob_enabled(false),
                            "output-limit" => ctx.output_limit.set_limit(None),
                            _ => {}
                        }
                        i += 1;
                    }
                }
                _ => {} // silently ignore
            }
            i += 1;
        }

        // Handle case where parser split `-o` into flags and the option name
        // ended up as a bare positional (flags=["o"], positional=["latch"]).
        // Only fire if no "-o" or "+o" appeared in positionals (which would have
        // already consumed the option name above).
        if args.flags.contains("o")
            && !positionals.iter().any(|p| *p == "-o" || *p == "+o")
        {
            // The first positional that matches a known option name gets enabled
            for &name in &positionals {
                match name {
                    "latch" => { ctx.scope.set_latch_enabled(true); break; }
                    "trash" => { ctx.scope.set_trash_enabled(true); break; }
                    "glob" => { ctx.scope.set_glob_enabled(true); break; }
                    _ => {
                        if name == "output-limit" || name.starts_with("output-limit=") {
                            if let Some(size_str) = name.strip_prefix("output-limit=") {
                                if let Ok(bytes) = crate::output_limit::parse_size(size_str) {
                                    ctx.output_limit.set_limit(Some(bytes));
                                }
                            } else if ctx.output_limit.max_bytes().is_none() {
                                ctx.output_limit.set_limit(Some(crate::output_limit::OutputLimitConfig::default_limit()));
                            }
                            break;
                        }
                    }
                }
            }
        }

        ExecResult::success("")
    }
}

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_options() {
        let mut ctx = make_ctx();

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

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

    #[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() {
        // Common bash idiom: set -euo pipefail
        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());
        assert!(ctx.scope.error_exit_enabled());
    }

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

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

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

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

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

        let result = Set.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(!ctx.scope.latch_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_latch_enabled(true);
        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 latch"));
        assert!(result.text_out().contains("set -o trash"));
    }

    #[tokio::test]
    async fn test_set_o_unknown_ignored() {
        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());
    }

    #[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");
    }
}