use std::{
fs::{File, OpenOptions},
path::{Path, PathBuf},
};
use anyhow::{Context, Result, anyhow};
use miniximg::{InodeType, MinixFileSystem, NodeMetadata};
pub struct ShellOptions {
pub image: PathBuf,
pub readonly: bool,
pub history: Option<PathBuf>,
}
pub struct Session {
fs: MinixFileSystem<File>,
image_path: PathBuf,
image_cwd: String,
host_cwd: PathBuf,
pub readonly: bool,
pub history: Option<PathBuf>,
}
impl Session {
pub fn open(options: ShellOptions) -> Result<Self> {
let image_path = options.image.clone();
let file = OpenOptions::new()
.read(true)
.write(!options.readonly)
.open(&image_path)
.with_context(|| format!("failed to open image {}", image_path.display()))?;
let fs = MinixFileSystem::open(file).with_context(|| {
format!(
"{} is not a valid Minix v1 filesystem image",
image_path.display()
)
})?;
let host_cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
Ok(Self {
fs,
image_path,
image_cwd: "/".to_string(),
host_cwd,
readonly: options.readonly,
history: options.history,
})
}
pub fn image_label(&self) -> String {
self.image_path
.file_name()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| self.image_path.display().to_string())
}
pub fn image_cwd(&self) -> &str {
&self.image_cwd
}
pub fn host_cwd(&self) -> &Path {
&self.host_cwd
}
pub fn fs_mut(&mut self) -> &mut MinixFileSystem<File> {
&mut self.fs
}
pub fn set_image_cwd(&mut self, new: String) -> Result<()> {
let meta = self.fs.stat(&new).with_context(|| format!("cd: {}", new))?;
if meta.kind != InodeType::Directory {
return Err(anyhow!("cd: {}: not a directory", new));
}
self.image_cwd = new;
Ok(())
}
pub fn set_host_cwd(&mut self, new: PathBuf) -> Result<()> {
let meta = std::fs::metadata(&new).with_context(|| format!("lcd: {}", new.display()))?;
if !meta.is_dir() {
return Err(anyhow!("lcd: {}: not a directory", new.display()));
}
self.host_cwd = new;
Ok(())
}
pub fn require_writable(&self, verb: &str) -> Result<()> {
if self.readonly {
Err(anyhow!("{}: image is open read-only", verb))
} else {
Ok(())
}
}
pub fn stat_image(&mut self, path: &str) -> Result<NodeMetadata> {
self.fs.stat(path).map_err(Into::into)
}
}