miniximg_shell/
session.rs1use std::{
4 fs::{File, OpenOptions},
5 path::{Path, PathBuf},
6};
7
8use anyhow::{Context, Result, anyhow};
9use miniximg::{InodeType, MinixFileSystem, NodeMetadata};
10
11pub struct ShellOptions {
13 pub image: PathBuf,
15 pub readonly: bool,
17 pub history: Option<PathBuf>,
22}
23
24pub struct Session {
27 fs: MinixFileSystem<File>,
29 image_path: PathBuf,
32 image_cwd: String,
34 host_cwd: PathBuf,
37 pub readonly: bool,
39 pub history: Option<PathBuf>,
41}
42
43impl Session {
44 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 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 pub fn image_cwd(&self) -> &str {
81 &self.image_cwd
82 }
83
84 pub fn host_cwd(&self) -> &Path {
86 &self.host_cwd
87 }
88
89 pub fn fs_mut(&mut self) -> &mut MinixFileSystem<File> {
92 &mut self.fs
93 }
94
95 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 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 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 pub fn stat_image(&mut self, path: &str) -> Result<NodeMetadata> {
128 self.fs.stat(path).map_err(Into::into)
129 }
130}