xtask-todo-lib 0.1.32

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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Optional session-scoped VM execution (γ CLI / β sidecar): host [`SessionHolder::Host`], Unix γ [`SessionHolder::Gamma`].

use std::cell::RefCell;
use std::io::Write;
use std::rc::Rc;

mod config;
mod guest_fs_ops;
#[cfg(unix)]
mod lima_diagnostics;
#[cfg(feature = "beta-vm")]
mod podman_machine;
#[cfg(feature = "beta-vm")]
mod session_beta;
#[cfg(unix)]
mod session_gamma;
mod session_host;
pub mod sync;
mod workspace_host;

pub use config::{
    exec_timeout_ms_from_env, workspace_mode_from_env, VmConfig, WorkspaceMode, ENV_DEVSHELL_VM,
    ENV_DEVSHELL_VM_BACKEND, ENV_DEVSHELL_VM_BETA_SESSION_STAGING, ENV_DEVSHELL_VM_CONTAINER_IMAGE,
    ENV_DEVSHELL_VM_DISABLE_PODMAN_SSH_HOME, ENV_DEVSHELL_VM_EAGER,
    ENV_DEVSHELL_VM_EXEC_TIMEOUT_MS, ENV_DEVSHELL_VM_LIMA_INSTANCE, ENV_DEVSHELL_VM_LINUX_BINARY,
    ENV_DEVSHELL_VM_REPO_ROOT, ENV_DEVSHELL_VM_SKIP_PODMAN_BOOTSTRAP, ENV_DEVSHELL_VM_SOCKET,
    ENV_DEVSHELL_VM_STDIO_TRANSPORT, ENV_DEVSHELL_VM_WORKSPACE_MODE,
};
#[cfg(unix)]
pub use guest_fs_ops::LimaGuestFsOps;
pub use guest_fs_ops::{
    guest_path_is_under_mount, guest_project_dir_on_guest, normalize_guest_path, GuestFsError,
    GuestFsOps, MockGuestFsOps,
};
#[cfg(unix)]
pub use lima_diagnostics::ENV_DEVSHELL_VM_LIMA_HINTS;
#[cfg(unix)]
pub use session_gamma::{
    GammaSession, ENV_DEVSHELL_VM_AUTO_BUILD_ESSENTIAL, ENV_DEVSHELL_VM_AUTO_BUILD_TODO_GUEST,
    ENV_DEVSHELL_VM_AUTO_TODO_PATH, ENV_DEVSHELL_VM_GUEST_HOST_DIR,
    ENV_DEVSHELL_VM_GUEST_TODO_HINT, ENV_DEVSHELL_VM_GUEST_WORKSPACE, ENV_DEVSHELL_VM_LIMACTL,
    ENV_DEVSHELL_VM_STOP_ON_EXIT, ENV_DEVSHELL_VM_WORKSPACE_PARENT,
    ENV_DEVSHELL_VM_WORKSPACE_USE_CARGO_ROOT,
};
pub use session_host::HostSandboxSession;
pub use sync::{pull_workspace_to_vfs, push_full, push_incremental, VmSyncError};
pub use workspace_host::workspace_parent_for_instance;

use std::process::ExitStatus;

use super::sandbox;
use super::vfs::Vfs;

/// Errors from VM session operations.
#[derive(Debug)]
pub enum VmError {
    Sandbox(sandbox::SandboxError),
    Sync(VmSyncError),
    /// Backend not implemented on this OS or not wired yet.
    BackendNotImplemented(&'static str),
    /// Lima / `limactl` or γ orchestration failure (message for stderr).
    Lima(String),
    /// β IPC / `devshell-vm` protocol failure.
    Ipc(String),
}

impl std::fmt::Display for VmError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Sandbox(e) => write!(f, "{e}"),
            Self::Sync(e) => write!(f, "{e}"),
            Self::BackendNotImplemented(s) => write!(f, "vm backend not implemented: {s}"),
            Self::Lima(s) | Self::Ipc(s) => f.write_str(s),
        }
    }
}

impl std::error::Error for VmError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Sandbox(e) => Some(e),
            Self::Sync(e) => Some(e),
            Self::BackendNotImplemented(_) | Self::Lima(_) | Self::Ipc(_) => None,
        }
    }
}

/// Session-construction error already reported to stderr by [`try_session_rc`].
#[derive(Debug, Clone, Copy)]
pub struct VmSessionInitError;

impl std::fmt::Display for VmSessionInitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vm session init failed")
    }
}

impl std::error::Error for VmSessionInitError {}

/// Abstraction for a devshell execution session (host temp dir, γ VM, or β sidecar).
pub trait VmExecutionSession {
    /// Prepare the session (e.g. start VM, initial push). No-op for host temp export.
    ///
    /// # Errors
    /// Returns backend-specific failures while preparing VM/sandbox state.
    fn ensure_ready(&mut self, _vfs: &Vfs, _vfs_cwd: &str) -> Result<(), VmError> {
        Ok(())
    }

    /// Run `rustup` or `cargo` with cwd matching `vfs_cwd`; update `vfs` as defined by the backend.
    ///
    /// # Errors
    /// Returns backend execution or sync failures from the selected session implementation.
    fn run_rust_tool(
        &mut self,
        vfs: &mut Vfs,
        vfs_cwd: &str,
        program: &str,
        args: &[String],
    ) -> Result<ExitStatus, VmError>;

    /// Tear down (e.g. final pull, stop VM).
    ///
    /// # Errors
    /// Returns backend-specific failures during shutdown/sync.
    fn shutdown(&mut self, _vfs: &mut Vfs, _vfs_cwd: &str) -> Result<(), VmError> {
        Ok(())
    }
}

/// Active VM / sandbox backend for one REPL or script run.
#[derive(Debug)]
pub enum SessionHolder {
    Host(HostSandboxSession),
    /// γ: Lima + host workspace sync (Unix only).
    #[cfg(unix)]
    Gamma(GammaSession),
    /// β: JSON-lines IPC to `devshell-vm` (Unix socket or TCP; `beta-vm` feature).
    #[cfg(feature = "beta-vm")]
    Beta(session_beta::BetaSession),
}

/// Single-quoted POSIX shell word (safe for `export PATH=…`).
#[cfg(unix)]
pub(crate) fn bash_single_quoted(s: &str) -> String {
    let mut o = String::from("'");
    for c in s.chars() {
        if c == '\'' {
            o.push_str("'\"'\"'");
        } else {
            o.push(c);
        }
    }
    o.push('\'');
    o
}

#[cfg(all(unix, test))]
mod bash_single_quoted_tests {
    use super::bash_single_quoted;

    #[test]
    fn wraps_plain_path() {
        assert_eq!(
            bash_single_quoted("/workspace/p/target/release"),
            "'/workspace/p/target/release'"
        );
    }
}

impl SessionHolder {
    /// Build session from config.
    ///
    /// # Errors
    /// On Unix, `DEVSHELL_VM_BACKEND=lima` uses [`GammaSession`]; fails with [`VmError::Lima`] if `limactl` is missing.
    /// On non-Unix, `lima` returns [`VmError::BackendNotImplemented`].
    pub fn try_from_config(config: &VmConfig) -> Result<Self, VmError> {
        if !config.enabled {
            return Ok(Self::Host(HostSandboxSession::new()));
        }
        if config.use_host_sandbox() {
            return Ok(Self::Host(HostSandboxSession::new()));
        }
        #[cfg(feature = "beta-vm")]
        if config.backend.eq_ignore_ascii_case("beta") {
            return session_beta::BetaSession::new(config).map(SessionHolder::Beta);
        }
        #[cfg(not(feature = "beta-vm"))]
        if config.backend.eq_ignore_ascii_case("beta") {
            return Err(VmError::BackendNotImplemented(
                "DEVSHELL_VM_BACKEND=beta requires building xtask-todo-lib with `--features beta-vm`",
            ));
        }
        #[cfg(unix)]
        if config.backend.eq_ignore_ascii_case("lima") {
            return GammaSession::new(config).map(SessionHolder::Gamma);
        }
        #[cfg(not(unix))]
        if config.backend.eq_ignore_ascii_case("lima") {
            return Err(VmError::BackendNotImplemented(
                "lima backend is only supported on Linux and macOS",
            ));
        }
        Err(VmError::BackendNotImplemented(
            "unknown DEVSHELL_VM_BACKEND (try host, auto, lima, or beta); see docs/devshell-vm-gamma.md",
        ))
    }

    /// Host sandbox only (tests and callers that do not read `VmConfig`).
    #[must_use]
    pub const fn new_host() -> Self {
        Self::Host(HostSandboxSession::new())
    }

    /// # Errors
    /// Returns backend-specific failures while preparing VM/sandbox state.
    pub fn ensure_ready(&mut self, vfs: &Vfs, vfs_cwd: &str) -> Result<(), VmError> {
        match self {
            Self::Host(s) => VmExecutionSession::ensure_ready(s, vfs, vfs_cwd),
            #[cfg(unix)]
            Self::Gamma(s) => VmExecutionSession::ensure_ready(s, vfs, vfs_cwd),
            #[cfg(feature = "beta-vm")]
            Self::Beta(s) => VmExecutionSession::ensure_ready(s, vfs, vfs_cwd),
        }
    }

    /// # Errors
    /// Returns backend execution or sync failures from the selected session implementation.
    pub fn run_rust_tool(
        &mut self,
        vfs: &mut Vfs,
        vfs_cwd: &str,
        program: &str,
        args: &[String],
    ) -> Result<ExitStatus, VmError> {
        match self {
            Self::Host(s) => VmExecutionSession::run_rust_tool(s, vfs, vfs_cwd, program, args),
            #[cfg(unix)]
            Self::Gamma(s) => VmExecutionSession::run_rust_tool(s, vfs, vfs_cwd, program, args),
            #[cfg(feature = "beta-vm")]
            Self::Beta(s) => VmExecutionSession::run_rust_tool(s, vfs, vfs_cwd, program, args),
        }
    }

    /// # Errors
    /// Returns backend-specific failures during shutdown/sync.
    pub fn shutdown(&mut self, vfs: &mut Vfs, vfs_cwd: &str) -> Result<(), VmError> {
        match self {
            Self::Host(s) => VmExecutionSession::shutdown(s, vfs, vfs_cwd),
            #[cfg(unix)]
            Self::Gamma(s) => VmExecutionSession::shutdown(s, vfs, vfs_cwd),
            #[cfg(feature = "beta-vm")]
            Self::Beta(s) => VmExecutionSession::shutdown(s, vfs, vfs_cwd),
        }
    }

    /// When γ is in guest-primary mode ([`WorkspaceMode::Guest`]), returns the session for direct guest FS ops.
    ///
    /// Returns `None` for host sandbox, β, or Mode S γ (push/pull sync).
    #[cfg(unix)]
    #[must_use]
    pub const fn guest_primary_gamma_mut(&mut self) -> Option<&mut GammaSession> {
        match self {
            Self::Gamma(g) if !g.syncs_vfs_with_host_workspace() => Some(g),
            _ => None,
        }
    }

    /// γ **or** β guest-primary: [`GuestFsOps`] + guest mount for [`crate::devshell::workspace::logical_path_to_guest`].
    ///
    /// Returns `None` for host sandbox, Mode S sync, or non–guest-primary sessions.
    /// Mount is owned so the returned trait object does not alias a borrow of the session.
    #[must_use]
    pub fn guest_primary_fs_ops_mut(&mut self) -> Option<(&mut dyn GuestFsOps, String)> {
        match self {
            #[cfg(unix)]
            Self::Gamma(g) if !g.syncs_vfs_with_host_workspace() => {
                let mount = g.guest_mount().to_string();
                Some((g as &mut dyn GuestFsOps, mount))
            }
            #[cfg(feature = "beta-vm")]
            Self::Beta(b) if !b.syncs_vfs_with_host_workspace() => {
                let mount = b.guest_mount().to_string();
                Some((b as &mut dyn GuestFsOps, mount))
            }
            _ => None,
        }
    }

    /// `true` when **any** VM session runs in guest-primary mode (γ or β: no VFS↔host project-tree sync).
    #[must_use]
    pub const fn is_guest_primary(&self) -> bool {
        match self {
            #[cfg(unix)]
            Self::Gamma(g) if !g.syncs_vfs_with_host_workspace() => true,
            #[cfg(feature = "beta-vm")]
            Self::Beta(b) if !b.syncs_vfs_with_host_workspace() => true,
            _ => false,
        }
    }

    /// `true` when γ runs in guest-primary mode (no VFS↔host project-tree sync).
    #[must_use]
    pub const fn is_guest_primary_gamma(&self) -> bool {
        #[cfg(unix)]
        {
            matches!(
                self,
                Self::Gamma(g) if !g.syncs_vfs_with_host_workspace()
            )
        }
        #[cfg(not(unix))]
        {
            false
        }
    }

    /// `true` when using the host temp sandbox ([`HostSandboxSession`]) rather than γ/β.
    #[must_use]
    pub const fn is_host_only(&self) -> bool {
        matches!(self, Self::Host(_))
    }

    /// Replace this process with an interactive `limactl shell` (`bash -l`) under the guest workspace mount.
    ///
    /// On success, does not return. On failure, returns the [`std::io::Error`] from [`std::os::unix::process::CommandExt::exec`].
    #[cfg(unix)]
    #[must_use]
    pub fn exec_lima_interactive_shell(&self) -> std::io::Error {
        use std::os::unix::process::CommandExt;
        use std::process::Command;
        match self {
            Self::Gamma(g) => {
                let (workdir, inner) = g.lima_interactive_shell_workdir_and_inner();
                Command::new(g.limactl_path())
                    .arg("shell")
                    .arg("-y")
                    .arg("--workdir")
                    .arg(workdir)
                    .arg(g.lima_instance_name())
                    .arg("--")
                    .arg("bash")
                    .arg("-lc")
                    .arg(inner)
                    .exec()
            }
            _ => std::io::Error::other("exec_lima_interactive_shell: not a Lima gamma session"),
        }
    }
}

/// Build [`SessionHolder`] from the environment.
///
/// On failure (e.g. default γ Lima but `limactl` missing), writes to `stderr` and returns an error.
/// Use **`DEVSHELL_VM=off`** or **`DEVSHELL_VM_BACKEND=host`** to force the host temp sandbox.
/// # Errors
/// Returns [`VmSessionInitError`] when backend session construction fails.
pub fn try_session_rc(
    stderr: &mut dyn Write,
) -> Result<Rc<RefCell<SessionHolder>>, VmSessionInitError> {
    let config = VmConfig::from_env();
    match SessionHolder::try_from_config(&config) {
        Ok(s) => Ok(Rc::new(RefCell::new(s))),
        Err(e) => {
            let _ = writeln!(stderr, "dev_shell: {e}");
            Err(VmSessionInitError)
        }
    }
}

/// Like [`try_session_rc`], but on failure uses [`SessionHolder::Host`] so the REPL can run against
/// [`workspace_parent_for_instance`] (same tree as the Lima mount).
pub fn try_session_rc_or_host(stderr: &mut dyn Write) -> Rc<RefCell<SessionHolder>> {
    try_session_rc(stderr).unwrap_or_else(|_| {
            let _ = writeln!(
                stderr,
                "dev_shell: VM unavailable — in-process REPL uses the same host directory as the Lima workspace (DEVSHELL_WORKSPACE_ROOT)."
            );
            Rc::new(RefCell::new(SessionHolder::Host(HostSandboxSession::new())))
        })
}

#[cfg(unix)]
pub fn export_devshell_workspace_root_env() {
    #[cfg(test)]
    let _workspace_env_test_guard = crate::test_support::devshell_workspace_env_mutex();
    let c = config::VmConfig::from_env();
    let p = session_gamma::workspace_parent_for_instance(&c.lima_instance);
    let _ = std::fs::create_dir_all(&p);
    if let Ok(can) = p.canonicalize() {
        std::env::set_var("DEVSHELL_WORKSPACE_ROOT", can.as_os_str());
    }
}

#[cfg(not(unix))]
pub fn export_devshell_workspace_root_env() {}

/// Host directory that Lima mounts at the guest workspace (e.g. `/workspace`).
#[cfg(unix)]
#[must_use]
pub fn vm_workspace_host_root() -> std::path::PathBuf {
    let c = config::VmConfig::from_env();
    session_gamma::workspace_parent_for_instance(&c.lima_instance)
}

/// Stub for non-Unix targets: `devshell/mod.rs` uses `if cfg!(unix) && …` but the branch is still
/// type-checked; this is never called when `cfg!(unix)` is false.
#[cfg(not(unix))]
#[must_use]
pub fn vm_workspace_host_root() -> std::path::PathBuf {
    std::path::PathBuf::new()
}

#[cfg(unix)]
#[must_use]
pub fn should_delegate_lima_shell(
    vm_session: &Rc<RefCell<SessionHolder>>,
    is_tty: bool,
    run_script: bool,
) -> bool {
    if run_script || !is_tty {
        return false;
    }
    if std::env::var("DEVSHELL_VM_INTERNAL_REPL").is_ok_and(|s| {
        let s = s.trim();
        s == "1" || s.eq_ignore_ascii_case("true") || s.eq_ignore_ascii_case("yes")
    }) {
        return false;
    }
    matches!(*vm_session.borrow(), SessionHolder::Gamma(_))
}

#[cfg(test)]
mod tests;