yosh 0.1.2

A POSIX-compliant shell implemented in Rust
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
use std::os::fd::AsRawFd;
use std::path::PathBuf;
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use expectrl::{Eof, Expect, Regex, Session, session::OsSession};

const TIMEOUT: Duration = Duration::from_secs(15);
const RAW_MODE_WAIT_TIMEOUT: Duration = Duration::from_secs(5);

// ── TempDir (inline, avoids pulling in mock_terminal via mod helpers) ─────

static TEMP_DIR_COUNTER: AtomicU64 = AtomicU64::new(0);

struct TempDir {
    path: PathBuf,
}

impl TempDir {
    fn new() -> Self {
        let mut path = std::env::temp_dir();
        let id = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let seq = TEMP_DIR_COUNTER.fetch_add(1, Ordering::Relaxed);
        path.push(format!("yosh-pty-test-{}-{}", id, seq));
        std::fs::create_dir_all(&path).unwrap();
        TempDir { path }
    }

    fn path(&self) -> &PathBuf {
        &self.path
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

// ── Helpers ─────────────────────────────────────────────────────────────

/// Returns (session, tmpdir). The tmpdir must be kept alive for the
/// duration of the test so that yosh's HOME directory is not deleted.
fn spawn_yosh() -> (OsSession, TempDir) {
    let bin = env!("CARGO_BIN_EXE_yosh");
    let tmpdir = TempDir::new();

    let mut cmd = Command::new(bin);
    cmd.env("TERM", "dumb");
    cmd.env("HOME", tmpdir.path());

    let mut session = Session::spawn(cmd).expect("failed to spawn yosh");
    session.set_expect_timeout(Some(TIMEOUT));
    (session, tmpdir)
}

fn wait_for_prompt(session: &mut OsSession) {
    session.expect("$ ").expect("prompt not found");
    wait_for_raw_mode(session);
}

fn wait_for_ps2(session: &mut OsSession) {
    session.expect("> ").expect("PS2 prompt not found");
    wait_for_raw_mode(session);
}

/// Block until yosh has called `enable_raw_mode()` on the PTY slave.
///
/// The previous implementation used a fixed 50ms sleep, which is a classic
/// flaky-test pattern — under load the child can take longer than that to
/// transition from canonical to raw mode, and input sent in the race window
/// gets processed by the cooked line discipline (ICRNL translation, ECHO,
/// ICANON buffering) instead of yosh's LineEditor.
///
/// Both ends of a PTY share one termios struct, so `tcgetattr` on the master
/// fd (which expectrl exposes via `AsRawFd`) observes the slave-side settings.
/// Poll for `ICANON` cleared — raw mode disables it — and return as soon as
/// the transition is visible.
fn wait_for_raw_mode(session: &OsSession) {
    let fd = session.as_raw_fd();
    let deadline = Instant::now() + RAW_MODE_WAIT_TIMEOUT;
    loop {
        let mut termios: libc::termios = unsafe { std::mem::zeroed() };
        let rc = unsafe { libc::tcgetattr(fd, &mut termios) };
        if rc == 0 && (termios.c_lflag & (libc::ICANON as libc::tcflag_t)) == 0 {
            return;
        }
        if Instant::now() >= deadline {
            let errno = if rc != 0 {
                std::io::Error::last_os_error().to_string()
            } else {
                "ok".to_string()
            };
            panic!(
                "wait_for_raw_mode timed out: tcgetattr rc={} ({}), c_lflag=0x{:x}",
                rc, errno, termios.c_lflag,
            );
        }
        std::thread::sleep(Duration::from_millis(2));
    }
}

/// Wait for command output (a line following a newline, not the input echo).
/// Uses a regex that matches the pattern preceded by a newline. The \r before
/// \n is optional because crossterm raw mode suppresses PTY ONLCR output
/// processing when active — so output may arrive as either \r\n or just \n.
fn expect_output(session: &mut OsSession, text: &str, msg: &str) {
    // \r? makes the carriage return optional to handle both ONLCR and raw mode
    let pattern = format!("\r?\n{}", text);
    session
        .expect(Regex(&pattern))
        .unwrap_or_else(|e| panic!("{}: {}", msg, e));
}

/// Send Ctrl+D and wait for the shell to exit cleanly.
fn exit_shell(session: &mut OsSession) {
    session.send("\x04").unwrap();
    // Wait for EOF to ensure the yosh process has fully exited before the
    // next test starts — avoids PTY resource contention between tests.
    let _ = session.expect(Eof);
}

// ── Tests ───────────────────────────────────────────────────────────────

#[test]
fn test_pty_echo_command() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    s.send("echo hello\r").unwrap();
    expect_output(&mut s, "hello", "echo output not found");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_ctrl_d_exits() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    s.send("\x04").unwrap();
    s.expect(Eof).expect("shell did not exit on Ctrl+D");
}

#[test]
fn test_pty_ctrl_c_interrupts_input() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Type something, then Ctrl+C
    s.send("partial input").unwrap();
    s.send("\x03").unwrap();

    // Should get a new prompt
    wait_for_prompt(&mut s);

    // Can still run commands
    s.send("echo ok\r").unwrap();
    expect_output(&mut s, "ok", "command after Ctrl+C failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_history_up_re_executes() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    s.send("echo first_cmd\r").unwrap();
    expect_output(&mut s, "first_cmd", "first command output not found");
    wait_for_prompt(&mut s);

    // Press Up then Enter to re-execute
    s.send("\x1b[A").unwrap(); // Up arrow (ANSI escape)
    s.send("\r").unwrap();
    expect_output(&mut s, "first_cmd", "history re-execution failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_backspace_editing() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Type "echoo", backspace, " works"
    s.send("echoo").unwrap();
    s.send("\x7f").unwrap(); // Backspace
    s.send(" works\r").unwrap();
    expect_output(&mut s, "works", "line editing with backspace failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_ps2_continuation() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Incomplete command: if true; then
    s.send("if true; then\r").unwrap();
    wait_for_ps2(&mut s);

    // Body — still incomplete (needs fi)
    s.send("echo continued\r").unwrap();
    wait_for_ps2(&mut s);

    s.send("fi\r").unwrap();
    expect_output(&mut s, "continued", "if-then-fi output not found");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_ctrl_r_history_search() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Build up history
    s.send("echo alpha\r").unwrap();
    expect_output(&mut s, "alpha", "first echo alpha failed");
    wait_for_prompt(&mut s);

    s.send("echo beta\r").unwrap();
    expect_output(&mut s, "beta", "echo beta failed");
    wait_for_prompt(&mut s);

    // Ctrl+R to search - wait for search UI, type query, then select and execute
    s.send("\x12").unwrap(); // Ctrl+R
    // Wait for the search UI query line to appear
    s.expect("2/2 > ").expect("Ctrl+R search UI did not appear");
    // FuzzySearchUI::run() draws UI then enables raw mode — wait for transition
    wait_for_raw_mode(&s);

    // Type "echo alpha" to uniquely select it
    s.send("echo alpha").unwrap();
    // Wait for filter to narrow down to unique match
    s.expect("1/1 > ")
        .expect("search query did not filter to unique match");

    s.send("\r").unwrap(); // Select from search
    // After selection, FuzzySearchUI exits and LineEditor re-enables raw mode
    wait_for_raw_mode(&s);
    s.send("\r").unwrap(); // Execute
    expect_output(&mut s, "alpha", "Ctrl+R history search failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_autosuggest_accept_with_right_arrow() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Execute a command to populate history
    s.send("echo autosuggest_test_value\r").unwrap();
    expect_output(&mut s, "autosuggest_test_value", "initial echo failed");
    wait_for_prompt(&mut s);

    // Type prefix "echo auto" — suggestion should appear
    s.send("echo auto").unwrap();
    // Brief pause for suggestion to render
    std::thread::sleep(Duration::from_millis(50));

    // Press Right arrow to accept the suggestion
    s.send("\x1b[C").unwrap(); // Right arrow (ANSI escape)
    // Brief pause for acceptance
    std::thread::sleep(Duration::from_millis(50));

    // Press Enter to execute
    s.send("\r").unwrap();
    expect_output(
        &mut s,
        "autosuggest_test_value",
        "autosuggest acceptance failed",
    );
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_tab_completion() {
    let (mut s, tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Create a uniquely named file in the temp HOME directory
    let test_file = tmpdir.path().join("yosh_tab_test_unique.txt");
    std::fs::write(&test_file, "hello").unwrap();

    // cd to HOME (which is tmpdir)
    s.send("cd\r").unwrap();
    wait_for_prompt(&mut s);

    // Type "echo yosh_tab" then Tab to complete the filename
    s.send("echo yosh_tab").unwrap();
    std::thread::sleep(Duration::from_millis(50));
    s.send("\t").unwrap(); // Tab
    std::thread::sleep(Duration::from_millis(100));

    // Press Enter to execute — echo will print the completed filename
    s.send("\r").unwrap();
    expect_output(
        &mut s,
        "yosh_tab_test_unique.txt",
        "Tab completion failed to complete and execute",
    );
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_command_completion() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // "ech" + Tab should complete to "echo" (builtin)
    s.send("ech").unwrap();
    std::thread::sleep(Duration::from_millis(50));
    s.send("\t").unwrap();
    std::thread::sleep(Duration::from_millis(100));

    // Add " hello" and press Enter to execute "echo hello"
    s.send(" hello\r").unwrap();
    expect_output(&mut s, "hello", "Command completion for 'echo' failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_command_completion_after_pipe() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // "echo hello | ca" + Tab inserts the common prefix of ca* commands.
    // Then send "t" to ensure we have "cat", then Enter.
    s.send("echo hello | ca").unwrap();
    std::thread::sleep(Duration::from_millis(50));
    s.send("\t").unwrap();
    std::thread::sleep(Duration::from_millis(100));
    // Send "t\r" in case Tab only completed up to the common prefix "ca"
    s.send("t\r").unwrap();
    expect_output(&mut s, "hello", "Command completion after pipe failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_path_completion_in_argument_position() {
    let (mut s, tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Create a uniquely named file
    let test_file = tmpdir.path().join("yosh_argcomp_unique.txt");
    std::fs::write(&test_file, "content").unwrap();

    // cd to HOME
    s.send("cd\r").unwrap();
    wait_for_prompt(&mut s);

    // "cat yosh_argcomp" + Tab should path-complete to "yosh_argcomp_unique.txt"
    s.send("cat yosh_argcomp").unwrap();
    std::thread::sleep(Duration::from_millis(50));
    s.send("\t").unwrap();
    std::thread::sleep(Duration::from_millis(100));

    // Press Enter — should print the file content
    s.send("\r").unwrap();
    expect_output(
        &mut s,
        "content",
        "Path completion in argument position failed",
    );
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_syntax_highlight_keyword() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Type "if" — should be highlighted as Keyword (Bold + Magenta)
    s.send("if").unwrap();
    std::thread::sleep(Duration::from_millis(100));

    // Cancel with Ctrl+C
    s.send("\x03").unwrap(); // Ctrl+C to cancel
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_syntax_highlight_valid_command() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Type "echo hi" — echo should be highlighted as CommandValid (Bold + Green)
    s.send("echo hi\r").unwrap();
    expect_output(&mut s, "hi", "echo with highlighting failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_syntax_highlight_pipe() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Execute a pipe command with highlighting active
    s.send("echo pipe_ok | cat\r").unwrap();
    expect_output(&mut s, "pipe_ok", "pipe with highlighting failed");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn ansi_colored_prompt() {
    let (mut session, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut session);

    // Set PS1 to an ANSI-colored prompt using command substitution with printf
    session
        .send("PS1=$(printf '\\033[32m$ \\033[0m')\r")
        .unwrap();
    wait_for_raw_mode(&session);

    // The prompt should render and accept input
    session.expect("$").expect("colored prompt not found");
    wait_for_raw_mode(&session);

    session.send("echo hello\r").unwrap();
    expect_output(&mut session, "hello", "echo after colored prompt");

    exit_shell(&mut session);
}

#[test]
fn multi_line_prompt() {
    let (mut session, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut session);

    // Set a two-line PS1: info line + prompt char
    // Use printf to get the newline in the prompt
    session.send("PS1=$(printf 'info line\\n> ')\r").unwrap();
    wait_for_raw_mode(&session);

    session
        .expect(">")
        .expect("multi-line prompt char not found");
    wait_for_raw_mode(&session);

    session.send("echo works\r").unwrap();
    expect_output(&mut session, "works", "echo after multi-line prompt");

    exit_shell(&mut session);
}

#[test]
fn test_pty_sighup_saves_history() {
    let (mut s, tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Execute a command so it gets added to history
    s.send("echo sighup_test_marker\r").unwrap();
    expect_output(&mut s, "sighup_test_marker", "echo output");
    wait_for_prompt(&mut s);

    // Send SIGHUP to the yosh process
    // get_process() returns &UnixProcess which Derefs to PtyProcess; pid() returns nix::unistd::Pid
    let pid = s.get_process().pid();
    unsafe {
        libc::kill(pid.as_raw(), libc::SIGHUP);
    }

    // Wait for yosh to exit
    let _ = s.expect(Eof);

    // Verify history file was written
    let histfile = tmpdir.path().join(".yosh_history");
    let contents =
        std::fs::read_to_string(&histfile).expect("history file should exist after SIGHUP");
    assert!(
        contents.contains("echo sighup_test_marker"),
        "history file should contain the command, got: {:?}",
        contents
    );
}

#[test]
fn test_pty_set_plus_m_disables_job_control() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Interactive shell starts with monitor=on; disable it
    s.send("set +m\r").unwrap();
    wait_for_prompt(&mut s);

    // fg should fail with "no job control"
    s.send("fg\r").unwrap();
    s.expect("no job control")
        .expect("fg should report 'no job control' after set +m");
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}

#[test]
fn test_pty_set_minus_m_reenables_job_control() {
    let (mut s, _tmpdir) = spawn_yosh();
    wait_for_prompt(&mut s);

    // Disable then re-enable monitor mode
    s.send("set +m\r").unwrap();
    wait_for_prompt(&mut s);
    s.send("set -m\r").unwrap();
    wait_for_prompt(&mut s);

    // Start a foreground job
    s.send("sleep 100\r").unwrap();
    // Brief pause to let sleep start
    std::thread::sleep(Duration::from_millis(200));

    // Ctrl+Z to suspend
    s.send("\x1a").unwrap();

    // Shell should regain control and show prompt
    wait_for_prompt(&mut s);

    // jobs should show the stopped job
    s.send("jobs\r").unwrap();
    s.expect("Stopped")
        .expect("jobs should show Stopped after Ctrl+Z suspend");
    wait_for_prompt(&mut s);

    // Cleanup: kill the stopped job
    s.send("kill %1\r").unwrap();
    wait_for_prompt(&mut s);

    exit_shell(&mut s);
}