zshrs 0.10.9

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, SQLite caching
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
707
//! File operation builtins - port of Modules/files.c
//!
//! Provides mkdir, rmdir, ln, mv, rm, chmod, chown, chgrp, sync builtins.

use std::fs::{self};
use std::io;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::Path;

/// Options for mkdir
#[derive(Debug, Default)]
/// `mkdir` option flags.
/// Mirrors the `Options ops` flag bag `bin_mkdir()` from
/// Src/Modules/files.c:63 reads — `-p` (create parents), `-m`
/// (mode).
pub struct MkdirOptions {
    pub parents: bool,
    pub mode: Option<u32>,
}

/// Create a directory
/// `mkdir` builtin.
/// Port of `bin_mkdir()` + `domkdir()` from
/// Src/Modules/files.c:63/115 — same `mkdir(2)`-with-mode
/// logic and the same `-p` parent-creation walk.
pub fn mkdir(path: &Path, options: &MkdirOptions) -> Result<(), String> {
    let mode = options.mode.unwrap_or(0o777);

    if options.parents {
        mkdir_parents(path, mode)
    } else {
        mkdir_single(path, mode)
    }
}

fn mkdir_single(path: &Path, mode: u32) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::ffi::CString;

        let path_str = path.to_string_lossy();
        let path_c = CString::new(path_str.as_bytes()).map_err(|e| e.to_string())?;

        let result = unsafe { libc::mkdir(path_c.as_ptr(), mode as libc::mode_t) };
        if result < 0 {
            Err(format!(
                "cannot make directory '{}': {}",
                path.display(),
                io::Error::last_os_error()
            ))
        } else {
            Ok(())
        }
    }

    #[cfg(not(unix))]
    {
        fs::create_dir(path)
            .map_err(|e| format!("cannot make directory '{}': {}", path.display(), e))
    }
}

fn mkdir_parents(path: &Path, mode: u32) -> Result<(), String> {
    if path.exists() {
        if path.is_dir() {
            return Ok(());
        }
        return Err(format!(
            "'{}' exists but is not a directory",
            path.display()
        ));
    }

    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            mkdir_parents(parent, mode | 0o300)?;
        }
    }

    mkdir_single(path, mode)
}

/// Remove a directory
/// `rmdir` builtin.
/// Port of `bin_rmdir()` from Src/Modules/files.c:150 — wraps
/// `rmdir(2)` with errno → diagnostic conversion.
pub fn rmdir(path: &Path) -> Result<(), String> {
    fs::remove_dir(path).map_err(|e| format!("cannot remove directory '{}': {}", path.display(), e))
}

/// Options for link operations
#[derive(Debug, Default)]
/// `ln` option flags.
/// Mirrors the `Options ops` flag bag `bin_ln()` from
/// Src/Modules/files.c:200 reads — `-s` (symbolic), `-f`
/// (force), `-d` (allow superuser to link dirs).
pub struct LinkOptions {
    pub symbolic: bool,
    pub force: bool,
    pub interactive: bool,
    pub no_dereference: bool,
    pub allow_dir: bool,
}

/// Create a link (hard or symbolic)
/// `ln` builtin.
/// Port of `bin_ln()` from Src/Modules/files.c:200 —
/// dispatches between hardlink and symlink based on options,
/// then calls into `domove()` (line 298) for force-replace
/// semantics.
pub fn link(source: &Path, target: &Path, options: &LinkOptions) -> Result<(), String> {
    let target_path = if target.is_dir() && !options.no_dereference {
        let filename = source
            .file_name()
            .ok_or_else(|| "invalid source path".to_string())?;
        target.join(filename)
    } else {
        target.to_path_buf()
    };

    if target_path.exists() {
        if options.force {
            fs::remove_file(&target_path)
                .map_err(|e| format!("cannot remove '{}': {}", target_path.display(), e))?;
        } else if !options.interactive {
            return Err(format!("'{}' already exists", target_path.display()));
        }
    }

    #[cfg(unix)]
    {
        if !options.allow_dir && source.is_dir() && !options.symbolic {
            return Err(format!(
                "'{}': hard link not allowed for directory",
                source.display()
            ));
        }

        if options.symbolic {
            std::os::unix::fs::symlink(source, &target_path)
                .map_err(|e| format!("cannot create symlink '{}': {}", target_path.display(), e))
        } else {
            fs::hard_link(source, &target_path)
                .map_err(|e| format!("cannot create hard link '{}': {}", target_path.display(), e))
        }
    }

    #[cfg(not(unix))]
    {
        fs::hard_link(source, &target_path)
            .map_err(|e| format!("cannot create link '{}': {}", target_path.display(), e))
    }
}

/// Options for move/rename
#[derive(Debug, Default)]
/// `mv` option flags.
/// Mirrors the flag bag `bin_ln()` (Src/Modules/files.c:200)
/// dispatches when `func == BIN_MV` — `-f` / `-i` interactivity
/// and the no-clobber path.
pub struct MoveOptions {
    pub force: bool,
    pub interactive: bool,
}

/// Move/rename a file
/// `mv` builtin.
/// Port of the rename-or-copy path inside `domove()` from
/// Src/Modules/files.c:298 — wraps `rename(2)` with the C
/// source's interactive-prompt and force-overwrite logic.
pub fn mv(source: &Path, target: &Path, options: &MoveOptions) -> Result<(), String> {
    let target_path = if target.is_dir() {
        let filename = source
            .file_name()
            .ok_or_else(|| "invalid source path".to_string())?;
        target.join(filename)
    } else {
        target.to_path_buf()
    };

    if target_path.exists() && !options.force && !options.interactive && target_path.is_dir() {
        return Err(format!(
            "'{}': cannot overwrite directory",
            target_path.display()
        ));
    }

    fs::rename(source, &target_path).map_err(|e| {
        format!(
            "cannot move '{}' to '{}': {}",
            source.display(),
            target_path.display(),
            e
        )
    })
}

/// Options for remove
#[derive(Debug, Default)]
/// `rm` option flags.
/// Mirrors the `Options ops` flag bag `bin_rm()` from
/// Src/Modules/files.c:616 reads — `-f` / `-i` / `-r` / `-s`.
pub struct RemoveOptions {
    pub force: bool,
    pub recursive: bool,
    pub interactive: bool,
    pub dir: bool,
}

/// Remove a file or directory
/// `rm` builtin.
/// Port of `bin_rm()` from Src/Modules/files.c:616 — drives
/// the `recursivecmd()` walker (line 378) with
/// `rm_leaf` (line 546) / `rm_dirpost` (line 594) callbacks.
pub fn rm(path: &Path, options: &RemoveOptions) -> Result<(), String> {
    if !path.exists() {
        if options.force {
            return Ok(());
        }
        return Err(format!(
            "cannot remove '{}': No such file or directory",
            path.display()
        ));
    }

    if path.is_dir() {
        if options.recursive {
            rm_recursive(path, options)
        } else if options.dir {
            fs::remove_dir(path).map_err(|e| format!("cannot remove '{}': {}", path.display(), e))
        } else if !options.force {
            Err(format!(
                "cannot remove '{}': Is a directory",
                path.display()
            ))
        } else {
            Ok(())
        }
    } else {
        fs::remove_file(path).map_err(|e| format!("cannot remove '{}': {}", path.display(), e))
    }
}

#[allow(clippy::only_used_in_recursion)]
fn rm_recursive(path: &Path, options: &RemoveOptions) -> Result<(), String> {
    if path.is_dir() {
        for entry in fs::read_dir(path)
            .map_err(|e| format!("cannot read directory '{}': {}", path.display(), e))?
        {
            let entry = entry.map_err(|e| e.to_string())?;
            rm_recursive(&entry.path(), options)?;
        }
        fs::remove_dir(path).map_err(|e| format!("cannot remove '{}': {}", path.display(), e))
    } else {
        fs::remove_file(path).map_err(|e| format!("cannot remove '{}': {}", path.display(), e))
    }
}

/// Change file permissions
/// `chmod` builtin.
/// Port of `bin_chmod()` + `chmod_dochmod()` from
/// Src/Modules/files.c:655/642 — same `chmod(2)` per-file
/// dispatch, walked recursively via `recursivecmd()` when `-R`.
pub fn chmod(path: &Path, mode: u32, recursive: bool) -> Result<(), String> {
    #[cfg(unix)]
    {
        use std::ffi::CString;

        let path_str = path.to_string_lossy();
        let path_c = CString::new(path_str.as_bytes()).map_err(|e| e.to_string())?;

        let result = unsafe { libc::chmod(path_c.as_ptr(), mode as libc::mode_t) };
        if result < 0 {
            return Err(format!(
                "cannot change mode of '{}': {}",
                path.display(),
                io::Error::last_os_error()
            ));
        }

        if recursive && path.is_dir() {
            for entry in fs::read_dir(path)
                .map_err(|e| format!("cannot read directory '{}': {}", path.display(), e))?
            {
                let entry = entry.map_err(|e| e.to_string())?;
                chmod(&entry.path(), mode, true)?;
            }
        }

        Ok(())
    }

    #[cfg(not(unix))]
    {
        Err("chmod not supported on this platform".to_string())
    }
}

/// Change file owner/group
#[cfg(unix)]
/// `chown`/`chgrp` builtin.
/// Port of `bin_chown()` + `chown_dochown()` /
/// `chown_dolchown()` from Src/Modules/files.c (~line 700) —
/// `chown(2)` / `lchown(2)` per file, walked recursively when
/// `-R`.
pub fn chown(
    path: &Path,
    uid: Option<u32>,
    gid: Option<u32>,
    recursive: bool,
    no_dereference: bool,
) -> Result<(), String> {
    use std::ffi::CString;

    let path_str = path.to_string_lossy();
    let path_c = CString::new(path_str.as_bytes()).map_err(|e| e.to_string())?;

    let uid = uid
        .map(|u| u as libc::uid_t)
        .unwrap_or(u32::MAX as libc::uid_t);
    let gid = gid
        .map(|g| g as libc::gid_t)
        .unwrap_or(u32::MAX as libc::gid_t);

    let result = if no_dereference {
        unsafe { libc::lchown(path_c.as_ptr(), uid, gid) }
    } else {
        unsafe { libc::chown(path_c.as_ptr(), uid, gid) }
    };

    if result < 0 {
        return Err(format!(
            "cannot change owner of '{}': {}",
            path.display(),
            io::Error::last_os_error()
        ));
    }

    if recursive && path.is_dir() {
        for entry in fs::read_dir(path)
            .map_err(|e| format!("cannot read directory '{}': {}", path.display(), e))?
        {
            let entry = entry.map_err(|e| e.to_string())?;
            chown(&entry.path(), Some(uid), Some(gid), true, no_dereference)?;
        }
    }

    Ok(())
}

/// Get user ID from username
#[cfg(unix)]
/// Look up a uid by username.
/// zshrs convenience over `getpwnam(3)` — the C source inlines
/// this lookup inside `parse_chown_spec` equivalents in
/// Src/Modules/files.c.
pub fn get_uid(username: &str) -> Option<u32> {
    use std::ffi::CString;

    if let Ok(uid) = username.parse::<u32>() {
        return Some(uid);
    }

    let username_c = CString::new(username).ok()?;
    unsafe {
        let pwd = libc::getpwnam(username_c.as_ptr());
        if pwd.is_null() {
            None
        } else {
            Some((*pwd).pw_uid)
        }
    }
}

/// Get group ID from group name
#[cfg(unix)]
/// Look up a gid by group name.
/// zshrs convenience over `getgrnam(3)`.
pub fn get_gid(groupname: &str) -> Option<u32> {
    use std::ffi::CString;

    if let Ok(gid) = groupname.parse::<u32>() {
        return Some(gid);
    }

    let groupname_c = CString::new(groupname).ok()?;
    unsafe {
        let grp = libc::getgrnam(groupname_c.as_ptr());
        if grp.is_null() {
            None
        } else {
            Some((*grp).gr_gid)
        }
    }
}

/// Parse chown spec (user:group or user.group)
#[cfg(unix)]
/// Parse a `user[:group]` chown spec.
/// Port of the chown-arg parser inside `bin_chown()`
/// (Src/Modules/files.c) — accepts `user`, `:group`,
/// `user:group`, plus the legacy `user.group` form.
pub fn parse_chown_spec(spec: &str) -> Result<(Option<u32>, Option<u32>), String> {
    let (user_part, group_part) = if let Some(pos) = spec.find(':') {
        let (u, g) = spec.split_at(pos);
        (u, Some(&g[1..]))
    } else if let Some(pos) = spec.find('.') {
        let (u, g) = spec.split_at(pos);
        (u, Some(&g[1..]))
    } else {
        (spec, None)
    };

    let uid = if user_part.is_empty() {
        None
    } else {
        Some(get_uid(user_part).ok_or_else(|| format!("{}: no such user", user_part))?)
    };

    let gid = match group_part {
        Some("") => {
            if let Some(uid_val) = uid {
                unsafe {
                    let pwd = libc::getpwuid(uid_val);
                    if pwd.is_null() {
                        return Err(format!("{}: no such user", user_part));
                    }
                    Some((*pwd).pw_gid)
                }
            } else {
                None
            }
        }
        Some(g) => Some(get_gid(g).ok_or_else(|| format!("{}: no such group", g))?),
        None => None,
    };

    Ok((uid, gid))
}

/// Sync filesystem
/// Force a filesystem sync.
/// Port of `bin_sync()` from Src/Modules/files.c:53 — wraps
/// `sync(2)`.
pub fn sync_fs() {
    #[cfg(unix)]
    unsafe {
        libc::sync();
    }
}

/// Convert octal mode to display string
/// Render a Unix mode bitmask as a 10-char `ls -l` string.
/// zshrs convenience — Src/Modules/files.c emits the same
/// shape inline for diagnostic output.
pub fn mode_to_string(mode: u32) -> String {
    let mut result = String::with_capacity(10);

    let file_type = match mode & 0o170000 {
        0o140000 => 's',
        0o120000 => 'l',
        0o100000 => '-',
        0o060000 => 'b',
        0o040000 => 'd',
        0o020000 => 'c',
        0o010000 => 'p',
        _ => '?',
    };
    result.push(file_type);

    let perms = [
        (mode & 0o400 != 0, 'r'),
        (mode & 0o200 != 0, 'w'),
        (
            mode & 0o100 != 0,
            if mode & 0o4000 != 0 { 's' } else { 'x' },
        ),
        (mode & 0o040 != 0, 'r'),
        (mode & 0o020 != 0, 'w'),
        (
            mode & 0o010 != 0,
            if mode & 0o2000 != 0 { 's' } else { 'x' },
        ),
        (mode & 0o004 != 0, 'r'),
        (mode & 0o002 != 0, 'w'),
        (
            mode & 0o001 != 0,
            if mode & 0o1000 != 0 { 't' } else { 'x' },
        ),
    ];

    for (set, ch) in perms {
        if set {
            result.push(ch);
        } else if ch == 's' {
            result.push('S');
        } else if ch == 't' {
            result.push('T');
        } else {
            result.push('-');
        }
    }

    result
}

/// Parse octal mode string
/// Parse an `ls -l`-style mode string back to a u32 bitmask.
/// zshrs-original convenience — used by tests / format
/// round-trips. C source's parser lives in `chmod`'s symbolic
/// mode parser.
pub fn parse_mode(s: &str) -> Option<u32> {
    u32::from_str_radix(s, 8).ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::File;
    use std::io::Write;
    use tempfile::TempDir;

    #[test]
    fn test_mkdir_single() {
        let dir = TempDir::new().unwrap();
        let new_dir = dir.path().join("newdir");

        let options = MkdirOptions::default();
        mkdir(&new_dir, &options).unwrap();

        assert!(new_dir.exists());
        assert!(new_dir.is_dir());
    }

    #[test]
    fn test_mkdir_parents() {
        let dir = TempDir::new().unwrap();
        let deep_dir = dir.path().join("a/b/c/d");

        let options = MkdirOptions {
            parents: true,
            ..Default::default()
        };
        mkdir(&deep_dir, &options).unwrap();

        assert!(deep_dir.exists());
        assert!(deep_dir.is_dir());
    }

    #[test]
    fn test_rmdir() {
        let dir = TempDir::new().unwrap();
        let new_dir = dir.path().join("to_remove");

        fs::create_dir(&new_dir).unwrap();
        assert!(new_dir.exists());

        rmdir(&new_dir).unwrap();
        assert!(!new_dir.exists());
    }

    #[test]
    fn test_rm_file() {
        let dir = TempDir::new().unwrap();
        let file_path = dir.path().join("test.txt");

        {
            let mut f = File::create(&file_path).unwrap();
            f.write_all(b"test").unwrap();
        }

        let options = RemoveOptions::default();
        rm(&file_path, &options).unwrap();
        assert!(!file_path.exists());
    }

    #[test]
    fn test_rm_recursive() {
        let dir = TempDir::new().unwrap();
        let sub_dir = dir.path().join("subdir");
        fs::create_dir(&sub_dir).unwrap();

        let file_path = sub_dir.join("test.txt");
        {
            let mut f = File::create(&file_path).unwrap();
            f.write_all(b"test").unwrap();
        }

        let options = RemoveOptions {
            recursive: true,
            ..Default::default()
        };
        rm(&sub_dir, &options).unwrap();
        assert!(!sub_dir.exists());
    }

    #[test]
    fn test_mv() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("source.txt");
        let dst = dir.path().join("dest.txt");

        {
            let mut f = File::create(&src).unwrap();
            f.write_all(b"content").unwrap();
        }

        let options = MoveOptions::default();
        mv(&src, &dst, &options).unwrap();

        assert!(!src.exists());
        assert!(dst.exists());
    }

    #[test]
    #[cfg(unix)]
    fn test_link_hard() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("source.txt");
        let dst = dir.path().join("link.txt");

        {
            let mut f = File::create(&src).unwrap();
            f.write_all(b"content").unwrap();
        }

        let options = LinkOptions::default();
        link(&src, &dst, &options).unwrap();

        assert!(dst.exists());
        assert_eq!(
            fs::metadata(&src).unwrap().ino(),
            fs::metadata(&dst).unwrap().ino()
        );
    }

    #[test]
    #[cfg(unix)]
    fn test_link_symbolic() {
        let dir = TempDir::new().unwrap();
        let src = dir.path().join("source.txt");
        let dst = dir.path().join("symlink.txt");

        {
            let mut f = File::create(&src).unwrap();
            f.write_all(b"content").unwrap();
        }

        let options = LinkOptions {
            symbolic: true,
            ..Default::default()
        };
        link(&src, &dst, &options).unwrap();

        assert!(dst.is_symlink());
    }

    #[test]
    #[cfg(unix)]
    fn test_chmod() {
        let dir = TempDir::new().unwrap();
        let file_path = dir.path().join("test.txt");

        {
            let mut f = File::create(&file_path).unwrap();
            f.write_all(b"test").unwrap();
        }

        chmod(&file_path, 0o755, false).unwrap();

        let meta = fs::metadata(&file_path).unwrap();
        assert_eq!(meta.mode() & 0o777, 0o755);
    }

    #[test]
    fn test_mode_to_string() {
        assert_eq!(mode_to_string(0o100644), "-rw-r--r--");
        assert_eq!(mode_to_string(0o100755), "-rwxr-xr-x");
        assert_eq!(mode_to_string(0o040755), "drwxr-xr-x");
        assert_eq!(mode_to_string(0o120777), "lrwxrwxrwx");
    }

    #[test]
    fn test_parse_mode() {
        assert_eq!(parse_mode("755"), Some(0o755));
        assert_eq!(parse_mode("644"), Some(0o644));
        assert_eq!(parse_mode("777"), Some(0o777));
        assert_eq!(parse_mode("invalid"), None);
    }

    #[test]
    #[cfg(unix)]
    fn test_get_uid() {
        assert!(get_uid("root").is_some() || get_uid("0").is_some());
        assert_eq!(get_uid("0"), Some(0));
    }

    #[test]
    #[cfg(unix)]
    fn test_parse_chown_spec() {
        let result = parse_chown_spec("0:0");
        assert!(result.is_ok());
        let (uid, gid) = result.unwrap();
        assert_eq!(uid, Some(0));
        assert_eq!(gid, Some(0));
    }
}