bashkit 0.5.0

Awesomely fast virtual sandbox with bash and file system
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
//! Integration tests for custom builtins
//!
//! Tests the public API for registering and using custom builtin commands.

use async_trait::async_trait;
use bashkit::{Bash, Builtin, BuiltinContext, ExecResult, FileSystem, InMemoryFs};
use bashkit::{
    BashkitContext, ClapBuiltin,
    clap::{Parser, Subcommand},
};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

/// Helper struct for testing - a simple echo with prefix
struct PrefixEcho {
    prefix: String,
}

#[async_trait]
impl Builtin for PrefixEcho {
    async fn execute(&self, ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
        let msg = ctx.args.join(" ");
        Ok(ExecResult::ok(format!("{}{}\n", self.prefix, msg)))
    }
}

/// Helper struct - transforms stdin
struct Transform {
    transform_fn: fn(&str) -> String,
}

#[async_trait]
impl Builtin for Transform {
    async fn execute(&self, ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
        let input = ctx.stdin.unwrap_or("");
        Ok(ExecResult::ok((self.transform_fn)(input)))
    }
}

/// Helper struct - reads from filesystem
struct FileReader;

#[async_trait]
impl Builtin for FileReader {
    async fn execute(&self, ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
        let path = match ctx.args.first() {
            Some(p) => std::path::Path::new(p),
            None => return Ok(ExecResult::err("Usage: readfile <path>\n".to_string(), 1)),
        };
        match ctx.fs.read_file(path).await {
            Ok(content) => Ok(ExecResult::ok(
                String::from_utf8_lossy(&content).to_string(),
            )),
            Err(e) => Ok(ExecResult::err(format!("Error: {}\n", e), 1)),
        }
    }
}

/// Helper struct - counter with shared state
struct Counter {
    count: Arc<AtomicU64>,
}

#[async_trait]
impl Builtin for Counter {
    async fn execute(&self, _ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
        let value = self.count.fetch_add(1, Ordering::SeqCst) + 1;
        Ok(ExecResult::ok(format!("{}\n", value)))
    }
}

/// Helper struct - returns error
struct Fail {
    message: String,
    code: i32,
}

#[async_trait]
impl Builtin for Fail {
    async fn execute(&self, _ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
        Ok(ExecResult::err(format!("{}\n", self.message), self.code))
    }
}

/// Helper struct - reads env vars
struct EnvDumper;

#[async_trait]
impl Builtin for EnvDumper {
    async fn execute(&self, ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
        let mut output = String::new();
        let mut keys: Vec<_> = ctx.env.keys().collect();
        keys.sort();
        for key in keys {
            if let Some(value) = ctx.env.get(key) {
                output.push_str(&format!("{}={}\n", key, value));
            }
        }
        Ok(ExecResult::ok(output))
    }
}

#[derive(Parser)]
#[command(name = "hello-clap", about = "greet someone")]
struct HelloClapArgs {
    #[arg(short, long, default_value = "World")]
    name: String,

    #[arg(short, long)]
    shout: bool,
}

struct HelloClap;

#[async_trait]
impl ClapBuiltin for HelloClap {
    type Args = HelloClapArgs;

    async fn execute_clap(
        &self,
        args: Self::Args,
        ctx: &mut BashkitContext<'_>,
    ) -> bashkit::Result<()> {
        let greeting = format!("Hello, {}!", args.name);
        let greeting = if args.shout {
            greeting.to_uppercase()
        } else {
            greeting
        };
        ctx.write_stdout(format!("{greeting}\n"));
        Ok(())
    }
}

#[derive(Parser)]
#[command(name = "math-clap")]
struct MathClapArgs {
    #[command(subcommand)]
    command: MathClapCommand,
}

#[derive(Subcommand)]
enum MathClapCommand {
    Add { left: i64, right: i64 },
    Fail { message: String },
    StdinLen,
}

struct MathClap;

#[async_trait]
impl ClapBuiltin for MathClap {
    type Args = MathClapArgs;

    async fn execute_clap(
        &self,
        args: Self::Args,
        ctx: &mut BashkitContext<'_>,
    ) -> bashkit::Result<()> {
        let value = match args.command {
            MathClapCommand::Add { left, right } => left + right,
            MathClapCommand::Fail { message } => {
                ctx.fail(format!("math-clap: {message}\n"), 7);
                return Ok(());
            }
            MathClapCommand::StdinLen => ctx.stdin().unwrap_or("").len() as i64,
        };
        ctx.write_stdout(format!("{value}\n"));
        Ok(())
    }
}

// =============================================================================
// Basic functionality tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_simple() {
    let mut bash = Bash::builder()
        .builtin(
            "prefix",
            Box::new(PrefixEcho {
                prefix: "[LOG] ".to_string(),
            }),
        )
        .build();

    let result = bash.exec("prefix hello world").await.unwrap();
    assert_eq!(result.stdout, "[LOG] hello world\n");
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn test_custom_builtin_no_args() {
    let mut bash = Bash::builder()
        .builtin(
            "prefix",
            Box::new(PrefixEcho {
                prefix: ">>> ".to_string(),
            }),
        )
        .build();

    let result = bash.exec("prefix").await.unwrap();
    assert_eq!(result.stdout, ">>> \n");
}

#[tokio::test]
async fn test_custom_builtin_clap_parser() {
    let mut bash = Bash::builder()
        .builtin("hello-clap", Box::new(HelloClap))
        .build();

    let result = bash.exec("hello-clap --name Alice --shout").await.unwrap();
    assert_eq!(result.stdout, "HELLO, ALICE!\n");
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn test_custom_builtin_clap_help_and_errors() {
    let mut bash = Bash::builder()
        .builtin("hello-clap", Box::new(HelloClap))
        .build();

    let help = bash.exec("hello-clap --help").await.unwrap();
    assert_eq!(help.exit_code, 0);
    assert!(help.stdout.contains("Usage: hello-clap"));
    assert!(help.stderr.is_empty());

    let error = bash.exec("hello-clap --unknown").await.unwrap();
    assert_eq!(error.exit_code, 2);
    assert!(error.stderr.contains("unexpected argument"));
    assert!(error.stdout.is_empty());
}

#[tokio::test]
async fn test_custom_builtin_clap_subcommands_and_stdin() {
    let mut bash = Bash::builder()
        .builtin("math-clap", Box::new(MathClap))
        .build();

    let add = bash.exec("math-clap add 20 22").await.unwrap();
    assert_eq!(add.stdout, "42\n");
    assert_eq!(add.exit_code, 0);

    let stdin_len = bash.exec("printf abc | math-clap stdin-len").await.unwrap();
    assert_eq!(stdin_len.stdout, "3\n");
    assert_eq!(stdin_len.exit_code, 0);

    let fail = bash.exec("math-clap fail nope").await.unwrap();
    assert_eq!(fail.stdout, "");
    assert_eq!(fail.stderr, "math-clap: nope\n");
    assert_eq!(fail.exit_code, 7);
}

// =============================================================================
// Pipeline tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_in_pipeline() {
    fn to_upper(s: &str) -> String {
        s.to_uppercase()
    }

    let mut bash = Bash::builder()
        .builtin(
            "upper",
            Box::new(Transform {
                transform_fn: to_upper,
            }),
        )
        .build();

    let result = bash.exec("echo hello | upper").await.unwrap();
    assert_eq!(result.stdout, "HELLO\n");
}

#[tokio::test]
async fn test_custom_builtin_pipeline_chain() {
    fn to_upper(s: &str) -> String {
        s.to_uppercase()
    }

    fn reverse(s: &str) -> String {
        s.chars().rev().collect()
    }

    let mut bash = Bash::builder()
        .builtin(
            "upper",
            Box::new(Transform {
                transform_fn: to_upper,
            }),
        )
        .builtin(
            "reverse",
            Box::new(Transform {
                transform_fn: reverse,
            }),
        )
        .build();

    let result = bash.exec("echo abc | upper | reverse").await.unwrap();
    // "abc\n" -> "ABC\n" -> "\nCBA"
    assert_eq!(result.stdout, "\nCBA");
}

// =============================================================================
// Filesystem access tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_filesystem_access() {
    let fs = Arc::new(InMemoryFs::new());
    // Create parent directory first
    fs.mkdir(std::path::Path::new("/data"), false)
        .await
        .unwrap();
    fs.write_file(
        std::path::Path::new("/data/test.txt"),
        b"custom content here",
    )
    .await
    .unwrap();

    let mut bash = Bash::builder()
        .fs(fs)
        .builtin("readfile", Box::new(FileReader))
        .build();

    let result = bash.exec("readfile /data/test.txt").await.unwrap();
    assert_eq!(result.stdout, "custom content here");
    assert_eq!(result.exit_code, 0);
}

#[tokio::test]
async fn test_custom_builtin_filesystem_error() {
    let mut bash = Bash::builder()
        .builtin("readfile", Box::new(FileReader))
        .build();

    let result = bash.exec("readfile /nonexistent").await.unwrap();
    assert!(result.stderr.contains("Error:"));
    assert_eq!(result.exit_code, 1);
}

// =============================================================================
// Stateful builtin tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_shared_state() {
    let counter = Arc::new(AtomicU64::new(0));

    let mut bash = Bash::builder()
        .builtin(
            "counter",
            Box::new(Counter {
                count: counter.clone(),
            }),
        )
        .build();

    let result = bash.exec("counter").await.unwrap();
    assert_eq!(result.stdout, "1\n");

    let result = bash.exec("counter").await.unwrap();
    assert_eq!(result.stdout, "2\n");

    let result = bash.exec("counter").await.unwrap();
    assert_eq!(result.stdout, "3\n");

    // Verify counter state
    assert_eq!(counter.load(Ordering::SeqCst), 3);
}

// =============================================================================
// Error handling tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_returns_error() {
    let mut bash = Bash::builder()
        .builtin(
            "fail",
            Box::new(Fail {
                message: "Something went wrong".to_string(),
                code: 42,
            }),
        )
        .build();

    let result = bash.exec("fail").await.unwrap();
    assert_eq!(result.stderr, "Something went wrong\n");
    assert_eq!(result.exit_code, 42);
}

#[tokio::test]
async fn test_custom_builtin_error_in_conditional() {
    let mut bash = Bash::builder()
        .builtin(
            "fail",
            Box::new(Fail {
                message: "error".to_string(),
                code: 1,
            }),
        )
        .builtin(
            "prefix",
            Box::new(PrefixEcho {
                prefix: "".to_string(),
            }),
        )
        .build();

    // fail || echo should run echo
    let result = bash.exec("fail || prefix success").await.unwrap();
    assert_eq!(result.stdout, "success\n");
    assert_eq!(result.exit_code, 0);
}

// =============================================================================
// Override default builtin tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_override_echo() {
    let mut bash = Bash::builder()
        .builtin(
            "echo",
            Box::new(PrefixEcho {
                prefix: "[CUSTOM] ".to_string(),
            }),
        )
        .build();

    let result = bash.exec("echo hello").await.unwrap();
    assert_eq!(result.stdout, "[CUSTOM] hello\n");
}

// =============================================================================
// Environment access tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_environment_access() {
    let mut bash = Bash::builder()
        .env("FOO", "bar")
        .env("BAZ", "qux")
        .builtin("dumpenv", Box::new(EnvDumper))
        .build();

    let result = bash.exec("dumpenv").await.unwrap();
    assert!(result.stdout.contains("FOO=bar"));
    assert!(result.stdout.contains("BAZ=qux"));
}

// =============================================================================
// Script integration tests
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_in_for_loop() {
    let mut bash = Bash::builder()
        .builtin(
            "prefix",
            Box::new(PrefixEcho {
                prefix: "- ".to_string(),
            }),
        )
        .build();

    let script = r#"
        for item in a b c; do
            prefix $item
        done
    "#;

    let result = bash.exec(script).await.unwrap();
    assert_eq!(result.stdout, "- a\n- b\n- c\n");
}

#[tokio::test]
async fn test_custom_builtin_in_if_condition() {
    let mut bash = Bash::builder()
        .builtin(
            "fail",
            Box::new(Fail {
                message: "".to_string(),
                code: 1,
            }),
        )
        .build();

    let script = r#"
        if fail; then
            echo "should not reach"
        else
            echo "correctly handled"
        fi
    "#;

    let result = bash.exec(script).await.unwrap();
    assert_eq!(result.stdout, "correctly handled\n");
}

#[tokio::test]
async fn test_custom_builtin_with_variable_expansion() {
    let mut bash = Bash::builder()
        .builtin(
            "prefix",
            Box::new(PrefixEcho {
                prefix: "".to_string(),
            }),
        )
        .build();

    let result = bash.exec("NAME=Alice; prefix Hello $NAME").await.unwrap();
    assert_eq!(result.stdout, "Hello Alice\n");
}

// =============================================================================
// Multiple custom builtins tests
// =============================================================================

#[tokio::test]
async fn test_multiple_custom_builtins() {
    fn to_upper(s: &str) -> String {
        s.to_uppercase()
    }

    let counter = Arc::new(AtomicU64::new(0));

    let mut bash = Bash::builder()
        .builtin(
            "prefix",
            Box::new(PrefixEcho {
                prefix: "[LOG] ".to_string(),
            }),
        )
        .builtin(
            "upper",
            Box::new(Transform {
                transform_fn: to_upper,
            }),
        )
        .builtin("counter", Box::new(Counter { count: counter }))
        .builtin(
            "fail",
            Box::new(Fail {
                message: "error".to_string(),
                code: 1,
            }),
        )
        .build();

    // Test all work independently
    let result = bash.exec("prefix test").await.unwrap();
    assert_eq!(result.stdout, "[LOG] test\n");

    let result = bash.exec("echo hello | upper").await.unwrap();
    assert_eq!(result.stdout, "HELLO\n");

    let result = bash.exec("counter").await.unwrap();
    assert_eq!(result.stdout, "1\n");

    let result = bash.exec("fail").await.unwrap();
    assert_eq!(result.exit_code, 1);
}

// =============================================================================
// Edge cases
// =============================================================================

#[tokio::test]
async fn test_custom_builtin_empty_name() {
    // Empty command names should work (though unusual)
    struct Empty;

    #[async_trait]
    impl Builtin for Empty {
        async fn execute(&self, _ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
            Ok(ExecResult::ok("empty\n".to_string()))
        }
    }

    let mut bash = Bash::builder().builtin("_", Box::new(Empty)).build();

    let result = bash.exec("_").await.unwrap();
    assert_eq!(result.stdout, "empty\n");
}

#[tokio::test]
async fn test_custom_builtin_special_characters_in_output() {
    struct SpecialOutput;

    #[async_trait]
    impl Builtin for SpecialOutput {
        async fn execute(&self, _ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
            Ok(ExecResult::ok("line1\nline2\ttab\n".to_string()))
        }
    }

    let mut bash = Bash::builder()
        .builtin("special", Box::new(SpecialOutput))
        .build();

    let result = bash.exec("special").await.unwrap();
    assert_eq!(result.stdout, "line1\nline2\ttab\n");
}