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
//! Path manipulation builtins - basename, dirname

use async_trait::async_trait;
use std::path::Path;

use super::{Builtin, Context};
use crate::error::Result;
use crate::interpreter::ExecResult;

/// The basename builtin - strip directory and suffix from filenames.
///
/// Usage: basename NAME [SUFFIX]
///        basename OPTION... NAME...
///
/// Print NAME with any leading directory components removed.
/// If SUFFIX is specified, also remove a trailing SUFFIX.
pub struct Basename;

#[async_trait]
impl Builtin for Basename {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: basename NAME [SUFFIX]\nPrint NAME with leading directory components removed.\nIf SUFFIX is specified, also remove a trailing SUFFIX.\n\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("basename (bashkit) 0.1"),
        ) {
            return Ok(r);
        }
        if ctx.args.is_empty() {
            return Ok(ExecResult::err(
                "basename: missing operand\n".to_string(),
                1,
            ));
        }

        let mut output = String::new();
        let mut args_iter = ctx.args.iter();

        // Get the path argument
        let path_arg = args_iter
            .next()
            .expect("args_iter.next() valid: guarded by is_empty() check above");
        let path = Path::new(path_arg);

        // Get the basename
        let basename = path
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| {
                // Handle special cases like "/" or empty
                if path_arg == "/" {
                    "/".to_string()
                } else if path_arg.is_empty() {
                    String::new()
                } else {
                    path_arg.clone()
                }
            });

        // Check for suffix argument
        let result = if let Some(suffix) = args_iter.next() {
            if let Some(stripped) = basename.strip_suffix(suffix.as_str()) {
                stripped.to_string()
            } else {
                basename
            }
        } else {
            basename
        };

        output.push_str(&result);
        output.push('\n');

        Ok(ExecResult::ok(output))
    }
}

/// The dirname builtin - strip last component from file name.
///
/// Usage: dirname NAME...
///
/// Output each NAME with its last non-slash component and trailing slashes removed.
/// If NAME contains no slashes, output "." (current directory).
pub struct Dirname;

#[async_trait]
impl Builtin for Dirname {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: dirname NAME...\nOutput each NAME with its last non-slash component and trailing slashes removed.\nIf NAME contains no slashes, output '.' (current directory).\n\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("dirname (bashkit) 0.1"),
        ) {
            return Ok(r);
        }
        if ctx.args.is_empty() {
            return Ok(ExecResult::err("dirname: missing operand\n".to_string(), 1));
        }

        let mut output = String::new();

        for (i, arg) in ctx.args.iter().enumerate() {
            if i > 0 {
                output.push('\n');
            }

            let path = Path::new(arg);
            let dirname = path
                .parent()
                .map(|p| {
                    let s = p.to_string_lossy();
                    if s.is_empty() {
                        ".".to_string()
                    } else {
                        s.to_string()
                    }
                })
                .unwrap_or_else(|| {
                    // Handle special cases
                    if arg == "/" {
                        "/".to_string()
                    } else {
                        ".".to_string()
                    }
                });

            output.push_str(&dirname);
        }

        output.push('\n');
        Ok(ExecResult::ok(output))
    }
}

/// The realpath builtin - resolve absolute pathname.
///
/// Usage: realpath [PATH...]
///
/// Resolves `.` and `..` components and prints absolute canonical paths.
/// In bashkit's virtual filesystem, symlink resolution is not performed.
pub struct Realpath;

#[async_trait]
impl Builtin for Realpath {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: realpath [PATH...]\nPrint the resolved absolute pathname.\n\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("realpath (bashkit) 0.1"),
        ) {
            return Ok(r);
        }
        if ctx.args.is_empty() {
            return Ok(ExecResult::err(
                "realpath: missing operand\n".to_string(),
                1,
            ));
        }

        let mut output = String::new();
        for arg in ctx.args {
            if arg.starts_with('-') {
                continue; // skip flags like -e, -m, -s
            }
            let resolved = super::resolve_path(ctx.cwd, arg);
            output.push_str(&resolved.to_string_lossy());
            output.push('\n');
        }

        Ok(ExecResult::ok(output))
    }
}

/// The readlink builtin - print resolved symbolic links or canonical file names.
///
/// Argument surface is generated from uutils/coreutils' `uu_app()` via the
/// `bashkit-coreutils-port` codegen tool — see `generated/readlink_args.rs`.
/// Behaviour stays local against the bashkit VFS.
///
/// Usage: readlink [-f|-m|-e] FILE...
///
/// Options:
///   -f    canonicalize: follow symlinks, resolve `.`/`..`; all but last component must exist
///   -m    canonicalize-missing: like -f but no component needs to exist
///   -e    canonicalize-existing: like -f but all components must exist
///   (no flag) print symlink target without canonicalization
pub struct Readlink;

#[async_trait]
impl Builtin for Readlink {
    #[allow(clippy::collapsible_if)]
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        let argv: Vec<std::ffi::OsString> = std::iter::once(std::ffi::OsString::from("readlink"))
            .chain(ctx.args.iter().map(std::ffi::OsString::from))
            .collect();

        let cmd = super::generated::readlink_args::readlink_command()
            .help_template("Usage: {usage}\n{about}\n\n{all-args}\n");
        let matches = match cmd.try_get_matches_from(argv) {
            Ok(m) => m,
            Err(e) => {
                let kind = e.kind();
                let rendered = e.render().to_string();
                if matches!(
                    kind,
                    clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion
                ) {
                    return Ok(ExecResult::ok(rendered));
                }
                return Ok(ExecResult::err(rendered, 2));
            }
        };

        // -e/-m/-f are mutually exclusive in spirit; check most-restrictive
        // first, matching uutils' precedence.
        let mode = if matches.get_flag("canonicalize-existing") {
            ReadlinkMode::CanonicalizeExisting
        } else if matches.get_flag("canonicalize-missing") {
            ReadlinkMode::CanonicalizeMissing
        } else if matches.get_flag("canonicalize") {
            ReadlinkMode::Canonicalize
        } else {
            ReadlinkMode::Raw
        };

        // -n suppresses the trailing terminator entirely; -z swaps it
        // to NUL. Both can come from the codegen-generated args now
        // that the parser handles them; the previous handwritten path
        // silently accepted -n as a no-op, so honoring it is a strict
        // improvement.
        let suppress_terminator = matches.get_flag("no-newline");
        let zero_terminated = matches.get_flag("zero");
        let terminator: char = if zero_terminated { '\0' } else { '\n' };

        let files: Vec<String> = matches
            .get_many::<std::ffi::OsString>("files")
            .map(|vs| vs.map(|v| v.to_string_lossy().into_owned()).collect())
            .unwrap_or_default();

        if files.is_empty() {
            return Ok(ExecResult::err(
                "readlink: missing operand\n".to_string(),
                1,
            ));
        }

        let mut output = String::new();
        let mut exit_code = 0;
        let total_files = files.len();

        for (idx, file) in files.iter().enumerate() {
            let resolved = super::resolve_path(ctx.cwd, file);
            let is_last = idx + 1 == total_files;
            let needs_terminator = !(suppress_terminator && is_last);

            match mode {
                ReadlinkMode::Raw => {
                    // No flag: read symlink target
                    match ctx.fs.read_link(&resolved).await {
                        Ok(target) => {
                            output.push_str(&target.to_string_lossy());
                            if needs_terminator {
                                output.push(terminator);
                            }
                        }
                        Err(_) => {
                            exit_code = 1;
                        }
                    }
                }
                ReadlinkMode::Canonicalize | ReadlinkMode::CanonicalizeMissing => {
                    // -f and -m: canonicalize path (resolve . and ..)
                    // -m doesn't require existence, -f requires all but last
                    let parent_missing = if mode == ReadlinkMode::Canonicalize {
                        resolved
                            .parent()
                            .filter(|p| !p.as_os_str().is_empty())
                            .map(|p| ctx.fs.exists(p))
                    } else {
                        None
                    };
                    if let Some(fut) = parent_missing {
                        if !fut.await.unwrap_or(false) {
                            exit_code = 1;
                            continue;
                        }
                    }
                    output.push_str(&resolved.to_string_lossy());
                    if needs_terminator {
                        output.push(terminator);
                    }
                }
                ReadlinkMode::CanonicalizeExisting => {
                    // -e: all components must exist
                    if ctx.fs.exists(&resolved).await.unwrap_or(false) {
                        output.push_str(&resolved.to_string_lossy());
                        if needs_terminator {
                            output.push(terminator);
                        }
                    } else {
                        exit_code = 1;
                    }
                }
            }
        }

        if exit_code != 0 && output.is_empty() {
            Ok(ExecResult::err(String::new(), exit_code))
        } else if exit_code != 0 {
            // Some files succeeded, some failed
            let mut result = ExecResult::with_code(output, exit_code);
            result.exit_code = exit_code;
            Ok(result)
        } else {
            Ok(ExecResult::ok(output))
        }
    }
}

#[derive(PartialEq)]
enum ReadlinkMode {
    Raw,
    Canonicalize,
    CanonicalizeMissing,
    CanonicalizeExisting,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    use crate::fs::InMemoryFs;

    async fn run_basename(args: &[&str]) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/");

        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        Basename.execute(ctx).await.unwrap()
    }

    async fn run_dirname(args: &[&str]) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/");

        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        Dirname.execute(ctx).await.unwrap()
    }

    #[tokio::test]
    async fn test_basename_simple() {
        let result = run_basename(&["/usr/bin/sort"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "sort\n");
    }

    #[tokio::test]
    async fn test_basename_with_suffix() {
        let result = run_basename(&["file.txt", ".txt"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "file\n");
    }

    #[tokio::test]
    async fn test_basename_no_suffix_match() {
        let result = run_basename(&["file.txt", ".doc"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "file.txt\n");
    }

    #[tokio::test]
    async fn test_basename_no_dir() {
        let result = run_basename(&["filename"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "filename\n");
    }

    #[tokio::test]
    async fn test_basename_trailing_slash() {
        let result = run_basename(&["/usr/bin/"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "bin\n");
    }

    #[tokio::test]
    async fn test_basename_missing_operand() {
        let result = run_basename(&[]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("missing operand"));
    }

    #[tokio::test]
    async fn test_dirname_simple() {
        let result = run_dirname(&["/usr/bin/sort"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "/usr/bin\n");
    }

    #[tokio::test]
    async fn test_dirname_no_dir() {
        let result = run_dirname(&["filename"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, ".\n");
    }

    #[tokio::test]
    async fn test_dirname_root() {
        let result = run_dirname(&["/"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "/\n");
    }

    #[tokio::test]
    async fn test_dirname_trailing_slash() {
        let result = run_dirname(&["/usr/bin/"]).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "/usr\n");
    }

    #[tokio::test]
    async fn test_dirname_missing_operand() {
        let result = run_dirname(&[]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("missing operand"));
    }

    // readlink tests

    use crate::fs::FileSystem;

    async fn run_readlink_with_fs(args: &[&str], fs: Arc<dyn FileSystem>) -> ExecResult {
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/");

        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        Readlink.execute(ctx).await.unwrap()
    }

    #[tokio::test]
    async fn test_readlink_missing_operand() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        let result = run_readlink_with_fs(&[], fs).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("missing operand"));
    }

    #[tokio::test]
    async fn test_readlink_raw_symlink() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        fs.symlink(Path::new("/target"), Path::new("/link"))
            .await
            .unwrap();
        let result = run_readlink_with_fs(&["/link"], fs).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "/target\n");
    }

    #[tokio::test]
    async fn test_readlink_raw_not_symlink() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        fs.write_file(Path::new("/file"), b"data").await.unwrap(); // write a regular file
        let result = run_readlink_with_fs(&["/file"], fs).await;
        // Not a symlink → failure, no output
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.is_empty());
    }

    #[tokio::test]
    async fn test_readlink_raw_nonexistent() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        let result = run_readlink_with_fs(&["/nonexistent"], fs).await;
        assert_eq!(result.exit_code, 1);
    }

    #[tokio::test]
    async fn test_readlink_f_canonicalize() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        fs.mkdir(Path::new("/home"), true).await.unwrap();
        fs.mkdir(Path::new("/home/user"), true).await.unwrap();
        let result = run_readlink_with_fs(&["-f", "/home/user/../user/./file"], fs).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "/home/user/file\n");
    }

    #[tokio::test]
    async fn test_readlink_m_canonicalize_missing() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        // -m doesn't require existence
        let result = run_readlink_with_fs(&["-m", "/a/b/../c"], fs).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "/a/c\n");
    }

    #[tokio::test]
    async fn test_readlink_e_existing() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        fs.mkdir(Path::new("/existing"), false).await.unwrap();
        let result = run_readlink_with_fs(&["-e", "/existing"], fs).await;
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "/existing\n");
    }

    #[tokio::test]
    async fn test_readlink_e_nonexistent() {
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        let result = run_readlink_with_fs(&["-e", "/nonexistent"], fs).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.is_empty());
    }

    #[tokio::test]
    async fn test_readlink_invalid_option() {
        // The codegen-ported argument surface uses clap, which exits 2
        // (not the GNU coreutils convention of 1) on unknown flags.
        // The clap-vs-GNU exit-code divergence is documented in
        // `tests/spec_cases/bash/readlink.test.sh` (### bash_diff).
        // -z is a valid flag now (zero-terminate output), so the test
        // uses a string that is plainly not a flag bashkit ports.
        let fs = Arc::new(InMemoryFs::new()) as Arc<dyn FileSystem>;
        let result = run_readlink_with_fs(&["--definitely-not-a-flag", "/file"], fs).await;
        assert_eq!(result.exit_code, 2);
        let stderr_lower = result.stderr.to_lowercase();
        assert!(
            stderr_lower.contains("unexpected argument")
                || stderr_lower.contains("unknown argument")
                || stderr_lower.contains("invalid option"),
            "expected clap unknown-flag stderr, got {}",
            result.stderr
        );
    }
}