xtask-todo-lib 0.1.21

Todo workspace library and cargo devshell subcommand
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
//! REPL: read-eval-print loop with `parse_line` and `execute_pipeline`; handles exit/quit.
//!
//! TTY: rustyline Editor with path completion (`CompletionType::List`, bash-like);
//! non-TTY: `read_line` loop.
//! On exit (exit/quit or EOF), VFS is auto-saved to `bin_path`.
//! Shared loop body is in `process_line` so it can be unit-tested.

use std::cell::RefCell;
use std::io::{BufRead, Read, Write};
use std::path::Path;
use std::rc::Rc;

use rustyline::config::Configurer;
use rustyline::{CompletionType, Editor};

use super::command::{execute_pipeline, ExecContext, RunResult};
use super::completion::DevShellHelper;
use super::parser;
use super::script;
use super::serialization;
use super::session_store;
use super::vfs::Vfs;
use super::vm::SessionHolder;

/// Result of processing one REPL line: continue the loop or exit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StepResult {
    Continue,
    Exit,
}

/// Process one input line: parse, optionally run pipeline, return whether to exit.
/// Handles `source path` and `. path` by loading script text via [`crate::devshell::script::read_script_source_text`]
/// (workspace guest / VFS, then host) and running it.
/// Used by both TTY and non-TTY loops; exposed for tests.
pub fn process_line<R, W1, W2>(
    vfs: &Rc<RefCell<Vfs>>,
    vm_session: &Rc<RefCell<SessionHolder>>,
    line: &str,
    stdin: &mut R,
    stdout: &mut W1,
    stderr: &mut W2,
) -> StepResult
where
    R: BufRead + Read,
    W1: Write,
    W2: Write,
{
    let line_trimmed = line.trim();
    if line_trimmed.is_empty() {
        return StepResult::Continue;
    }

    // REPL source: "source path" or ". path" — run file as script (VFS or host)
    if let Some(path) = line_trimmed.strip_prefix("source ") {
        let path = path.trim();
        if path.is_empty() {
            let _ = writeln!(stderr, "source: missing path");
            return StepResult::Continue;
        }
        let content = script::read_script_source_text(vfs, vm_session, path);
        match content {
            Some(c) => {
                let _ = script::run_script(
                    vfs,
                    vm_session,
                    &c,
                    Path::new(""),
                    false,
                    stdin,
                    stdout,
                    stderr,
                );
            }
            None => {
                let _ = writeln!(stderr, "source: cannot read {path}");
            }
        }
        return StepResult::Continue;
    }
    if let Some(path) = line_trimmed.strip_prefix(". ") {
        let path = path.trim();
        if path.is_empty() {
            let _ = writeln!(stderr, ".: missing path");
            return StepResult::Continue;
        }
        let content = script::read_script_source_text(vfs, vm_session, path);
        match content {
            Some(c) => {
                let _ = script::run_script(
                    vfs,
                    vm_session,
                    &c,
                    Path::new(""),
                    false,
                    stdin,
                    stdout,
                    stderr,
                );
            }
            None => {
                let _ = writeln!(stderr, ".: cannot read {path}");
            }
        }
        return StepResult::Continue;
    }

    let pipeline = match parser::parse_line(line_trimmed) {
        Ok(p) => p,
        Err(e) => {
            let _ = writeln!(stderr, "parse error: {e}");
            return StepResult::Continue;
        }
    };
    let first_argv0 = pipeline
        .commands
        .first()
        .and_then(|c| c.argv.first())
        .map(String::as_str);
    if first_argv0 == Some("exit") || first_argv0 == Some("quit") {
        return StepResult::Exit;
    }
    let mut vfs_ref = vfs.borrow_mut();
    let mut sess_ref = vm_session.borrow_mut();
    let mut ctx = ExecContext {
        vfs: &mut vfs_ref,
        stdin,
        stdout,
        stderr,
        vm_session: &mut sess_ref,
    };
    match execute_pipeline(&mut ctx, &pipeline) {
        Ok(RunResult::Exit) => StepResult::Exit,
        Ok(RunResult::Continue) => StepResult::Continue,
        Err(e) => {
            let _ = writeln!(stderr, "error: {e}");
            StepResult::Continue
        }
    }
}

/// Run the REPL until exit/quit or EOF.
///
/// When `is_tty`: uses rustyline Editor with tab completion (command + path).
/// When not TTY: uses `stdin.read_line` (pipe/script compatible).
/// On exit, the VFS is automatically saved to `bin_path`.
pub fn run<R, W1, W2>(
    vfs: &Rc<RefCell<Vfs>>,
    vm_session: &Rc<RefCell<SessionHolder>>,
    is_tty: bool,
    bin_path: &Path,
    stdin: &mut R,
    stdout: &mut W1,
    stderr: &mut W2,
) -> Result<(), ()>
where
    R: BufRead + Read,
    W1: Write,
    W2: Write,
{
    if is_tty {
        run_tty(vfs, vm_session, bin_path, stdin, stdout, stderr)
    } else {
        run_readline(vfs, vm_session, bin_path, stdin, stdout, stderr)
    }
}

fn save_on_exit<W2: Write>(
    vfs: &Rc<RefCell<Vfs>>,
    vm_session: &Rc<RefCell<SessionHolder>>,
    bin_path: &Path,
    stderr: &mut W2,
) {
    let cwd = vfs.borrow().cwd().to_string();
    {
        let mut vfs_mut = vfs.borrow_mut();
        if let Err(e) = vm_session.borrow_mut().shutdown(&mut vfs_mut, &cwd) {
            let _ = writeln!(stderr, "dev_shell: session shutdown: {e}");
        }
    }
    if vfs.borrow().is_host_backed() {
        let _ = writeln!(
            stderr,
            "dev_shell: host workspace: skipping .dev_shell.bin (tree is on disk under DEVSHELL_WORKSPACE_ROOT)"
        );
        return;
    }
    if vm_session.borrow().is_guest_primary() {
        let _ = writeln!(
            stderr,
            "dev_shell: guest-primary mode: skipping legacy .dev_shell.bin save (design §10; guest workspace is authoritative)"
        );
        if let Err(e) = session_store::save_guest_primary(bin_path, vfs.borrow().cwd()) {
            let _ = writeln!(
                stderr,
                "dev_shell: failed to write guest-primary session {}: {e}",
                session_store::session_metadata_path(bin_path).display()
            );
        }
    } else if let Err(e) = serialization::save_to_file(&vfs.borrow(), bin_path) {
        let _ = writeln!(stderr, "save on exit failed: {e}");
    }
}

/// TTY branch: rustyline Editor with `DevShellHelper` (path completion via vfs).
fn run_tty<R, W1, W2>(
    vfs: &Rc<RefCell<Vfs>>,
    vm_session: &Rc<RefCell<SessionHolder>>,
    bin_path: &Path,
    stdin: &mut R,
    stdout: &mut W1,
    stderr: &mut W2,
) -> Result<(), ()>
where
    R: BufRead + Read,
    W1: Write,
    W2: Write,
{
    let mut editor = Editor::new().map_err(|_| ())?;
    // Bash/readline-style: extend to longest common prefix; second Tab lists options.
    // Default rustyline `Circular` cycles candidates and then restores the pre-Tab line,
    // so e.g. `cat s` → Tab → `cat src` → Tab → `cat s` again (surprising vs shells).
    editor.set_completion_type(CompletionType::List);
    editor.set_helper(Some(DevShellHelper::new(vfs.clone(), vm_session.clone())));

    loop {
        let prompt = format!("{} $ ", vfs.borrow().cwd());
        let line = match editor.readline(&prompt) {
            Ok(line) => line,
            Err(rustyline::error::ReadlineError::Eof) => {
                save_on_exit(vfs, vm_session, bin_path, stderr);
                return Ok(());
            }
            Err(rustyline::error::ReadlineError::Interrupted) => continue,
            Err(e) => {
                let _ = writeln!(stderr, "readline error: {e}");
                continue;
            }
        };
        if process_line(vfs, vm_session, &line, stdin, stdout, stderr) == StepResult::Exit {
            break;
        }
    }
    save_on_exit(vfs, vm_session, bin_path, stderr);
    Ok(())
}

/// Non-TTY branch: `read_line` loop; `borrow_mut` once per iteration for prompt and `ExecContext`.
fn run_readline<R, W1, W2>(
    vfs: &Rc<RefCell<Vfs>>,
    vm_session: &Rc<RefCell<SessionHolder>>,
    bin_path: &Path,
    stdin: &mut R,
    stdout: &mut W1,
    stderr: &mut W2,
) -> Result<(), ()>
where
    R: BufRead + Read,
    W1: Write,
    W2: Write,
{
    let mut line = String::new();
    loop {
        line.clear();
        let cwd = vfs.borrow().cwd().to_string();
        let _ = write!(stdout, "{cwd} $ ");
        let _ = stdout.flush();
        let n = stdin.read_line(&mut line).map_err(|_| ())?;
        if n == 0 {
            save_on_exit(vfs, vm_session, bin_path, stderr);
            return Ok(());
        }
        if process_line(vfs, vm_session, &line, stdin, stdout, stderr) == StepResult::Exit {
            break;
        }
    }
    save_on_exit(vfs, vm_session, bin_path, stderr);
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::io::Cursor;
    use std::rc::Rc;

    use super::super::vfs::Vfs;
    use super::super::vm::SessionHolder;
    use super::{process_line, StepResult};

    fn vm_test() -> Rc<RefCell<SessionHolder>> {
        Rc::new(RefCell::new(SessionHolder::new_host()))
    }

    #[test]
    fn process_line_empty_returns_continue() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(&vfs, &vm, "  \n", &mut stdin, &mut stdout, &mut stderr);
        assert_eq!(r, StepResult::Continue);
    }

    #[test]
    fn process_line_exit_returns_exit() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(&vfs, &vm, "exit", &mut stdin, &mut stdout, &mut stderr);
        assert_eq!(r, StepResult::Exit);
    }

    #[test]
    fn process_line_quit_returns_exit() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(&vfs, &vm, "quit", &mut stdin, &mut stdout, &mut stderr);
        assert_eq!(r, StepResult::Exit);
    }

    #[test]
    fn process_line_parse_error_returns_continue() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(&vfs, &vm, "echo >", &mut stdin, &mut stdout, &mut stderr);
        assert_eq!(r, StepResult::Continue);
        let err = String::from_utf8(stderr).unwrap();
        assert!(err.contains("parse error"));
    }

    #[test]
    fn process_line_pwd_continues_and_writes() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(&vfs, &vm, "pwd", &mut stdin, &mut stdout, &mut stderr);
        assert_eq!(r, StepResult::Continue);
        let out = String::from_utf8(stdout).unwrap();
        assert!(out.contains('/'));
    }

    #[test]
    fn process_line_unknown_command_continues_and_stderr() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(
            &vfs,
            &vm,
            "unknowncmd",
            &mut stdin,
            &mut stdout,
            &mut stderr,
        );
        assert_eq!(r, StepResult::Continue);
        let err = String::from_utf8(stderr).unwrap();
        assert!(err.contains("unknown command"));
    }

    #[test]
    fn process_line_source_runs_script_from_host() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let dir = std::env::temp_dir().join(format!("devshell_repl_source_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let script_path = dir.join("repl_sourced.dsh");
        std::fs::write(&script_path, "echo repl_sourced\n").unwrap();
        let line = format!("source {}", script_path.display());
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(&vfs, &vm, &line, &mut stdin, &mut stdout, &mut stderr);
        assert_eq!(r, StepResult::Continue);
        let out = String::from_utf8(stdout).unwrap();
        assert!(out.contains("repl_sourced"), "stdout: {out}");
        let _ = std::fs::remove_file(&script_path);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn process_line_dot_path_runs_script() {
        let vfs = Rc::new(RefCell::new(Vfs::new()));
        let vm = vm_test();
        let dir = std::env::temp_dir().join(format!("devshell_repl_dot_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let script_path = dir.join("dot_sourced.dsh");
        std::fs::write(&script_path, "echo dot_ok\n").unwrap();
        let line = format!(". {}", script_path.display());
        let mut stdin = Cursor::new(b"");
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let r = process_line(&vfs, &vm, &line, &mut stdin, &mut stdout, &mut stderr);
        assert_eq!(r, StepResult::Continue);
        let out = String::from_utf8(stdout).unwrap();
        assert!(out.contains("dot_ok"), "stdout: {out}");
        let _ = std::fs::remove_file(&script_path);
        let _ = std::fs::remove_dir(&dir);
    }
}