Skip to main content

miniximg_shell/
session.rs

1//! Per-shell state: the loaded image, both cwds, and config knobs.
2
3use std::{
4    fs::{File, OpenOptions},
5    path::{Path, PathBuf},
6};
7
8use anyhow::{Context, Result, anyhow};
9use miniximg::{InodeType, MinixFileSystem, NodeMetadata};
10
11/// Configuration passed to [`crate::run`].
12pub struct ShellOptions {
13    /// Path to the Minix v1 filesystem image to operate on.
14    pub image: PathBuf,
15    /// When true, every mutating command is refused with a friendly error.
16    pub readonly: bool,
17    /// Where to read / write line-edit history.
18    ///
19    /// `None` keeps history in memory only; `Some(path)` persists across
20    /// sessions, creating the file (and any missing parents) on save.
21    pub history: Option<PathBuf>,
22}
23
24/// The image plus the two working directories, plus the bits commands
25/// need to render diagnostics consistently.
26pub struct Session {
27    /// Loaded image filesystem.
28    fs: MinixFileSystem<File>,
29    /// Source path of the image, retained for the prompt and for error
30    /// messages.
31    image_path: PathBuf,
32    /// Image-side current directory, always absolute and normalised.
33    image_cwd: String,
34    /// Host-side current directory, used to anchor `@`-prefixed relative
35    /// paths and `lcd` / `lls`.
36    host_cwd: PathBuf,
37    /// Refuse modifications when set.
38    pub readonly: bool,
39    /// Pre-resolved history path passed through to [`crate::editor`].
40    pub history: Option<PathBuf>,
41}
42
43impl Session {
44    /// Opens the image and prepares a session.
45    pub fn open(options: ShellOptions) -> Result<Self> {
46        let image_path = options.image.clone();
47        let file = OpenOptions::new()
48            .read(true)
49            .write(!options.readonly)
50            .open(&image_path)
51            .with_context(|| format!("failed to open image {}", image_path.display()))?;
52        let fs = MinixFileSystem::open(file).with_context(|| {
53            format!(
54                "{} is not a valid Minix v1 filesystem image",
55                image_path.display()
56            )
57        })?;
58        let host_cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
59
60        Ok(Self {
61            fs,
62            image_path,
63            image_cwd: "/".to_string(),
64            host_cwd,
65            readonly: options.readonly,
66            history: options.history,
67        })
68    }
69
70    /// Image filename used in the prompt — basename only so a long
71    /// absolute path doesn't dominate the line.
72    pub fn image_label(&self) -> String {
73        self.image_path
74            .file_name()
75            .map(|s| s.to_string_lossy().into_owned())
76            .unwrap_or_else(|| self.image_path.display().to_string())
77    }
78
79    /// Returns the image-side working directory.
80    pub fn image_cwd(&self) -> &str {
81        &self.image_cwd
82    }
83
84    /// Returns the host-side working directory.
85    pub fn host_cwd(&self) -> &Path {
86        &self.host_cwd
87    }
88
89    /// Borrow the underlying filesystem mutably (every operation on the
90    /// core lib takes `&mut self`).
91    pub fn fs_mut(&mut self) -> &mut MinixFileSystem<File> {
92        &mut self.fs
93    }
94
95    /// Sets the image-side cwd after validating it exists and is a
96    /// directory.
97    pub fn set_image_cwd(&mut self, new: String) -> Result<()> {
98        let meta = self.fs.stat(&new).with_context(|| format!("cd: {}", new))?;
99        if meta.kind != InodeType::Directory {
100            return Err(anyhow!("cd: {}: not a directory", new));
101        }
102        self.image_cwd = new;
103        Ok(())
104    }
105
106    /// Sets the host-side cwd after validating it exists and is a directory.
107    pub fn set_host_cwd(&mut self, new: PathBuf) -> Result<()> {
108        let meta = std::fs::metadata(&new).with_context(|| format!("lcd: {}", new.display()))?;
109        if !meta.is_dir() {
110            return Err(anyhow!("lcd: {}: not a directory", new.display()));
111        }
112        self.host_cwd = new;
113        Ok(())
114    }
115
116    /// Helper used by mutating commands: returns `Err` in readonly mode
117    /// with a clear message naming the offending verb.
118    pub fn require_writable(&self, verb: &str) -> Result<()> {
119        if self.readonly {
120            Err(anyhow!("{}: image is open read-only", verb))
121        } else {
122            Ok(())
123        }
124    }
125
126    /// Convenience: stat an image path through the active filesystem.
127    pub fn stat_image(&mut self, path: &str) -> Result<NodeMetadata> {
128        self.fs.stat(path).map_err(Into::into)
129    }
130}