use std::fmt;
use anyhow::Result;
use crate::session::Session;
mod cat;
mod cd;
mod chmod;
mod clear;
mod cp;
mod diff;
mod edit;
mod exit;
mod fsck;
mod get;
mod help;
mod info;
mod lcd;
mod link;
mod lls;
mod lpwd;
mod ls;
mod mkdir;
mod mknod;
mod mv;
mod put;
mod pwd;
mod rm;
mod rmdir;
mod stat;
mod sync;
mod touch;
mod tree;
pub struct Command {
pub name: &'static str,
pub aliases: &'static [&'static str],
pub summary: &'static str,
pub usage: &'static str,
pub run: fn(&mut Session, &[String]) -> Result<()>,
}
impl fmt::Debug for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Command").field("name", &self.name).finish()
}
}
macro_rules! cmd {
($module:ident) => {
Command {
name: $module::NAME,
aliases: $module::ALIASES,
summary: $module::SUMMARY,
usage: $module::USAGE,
run: $module::run,
}
};
}
pub const COMMANDS: &[Command] = &[
cmd!(cat),
cmd!(cd),
cmd!(chmod),
cmd!(clear),
cmd!(cp),
cmd!(diff),
cmd!(edit),
cmd!(exit),
cmd!(fsck),
cmd!(get),
cmd!(help),
cmd!(info),
cmd!(lcd),
cmd!(link),
cmd!(lls),
cmd!(lpwd),
cmd!(ls),
cmd!(mkdir),
cmd!(mknod),
cmd!(mv),
cmd!(put),
cmd!(pwd),
cmd!(rm),
cmd!(rmdir),
cmd!(stat),
cmd!(sync),
cmd!(touch),
cmd!(tree),
];
pub fn lookup(name: &str) -> Option<&'static Command> {
COMMANDS
.iter()
.find(|c| c.name == name || c.aliases.contains(&name))
}
pub enum Outcome {
Continue,
Quit,
}
pub fn dispatch(session: &mut Session, line: &str) -> Outcome {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
return Outcome::Continue;
}
let tokens = match crate::parser::tokenize(trimmed) {
Ok(t) => t,
Err(err) => {
eprintln!("miniximg: parse error: {err}");
return Outcome::Continue;
}
};
let (name, args) = tokens.split_first().expect("non-empty after trim");
let cmd = match lookup(name) {
Some(c) => c,
None => {
eprintln!("miniximg: unknown command: {name} (try `help`)");
return Outcome::Continue;
}
};
match (cmd.run)(session, args) {
Ok(()) => {
if cmd.name == exit::NAME {
Outcome::Quit
} else {
Outcome::Continue
}
}
Err(err) => {
eprintln!("{name}: {err:#}");
Outcome::Continue
}
}
}
pub fn expect_args(args: &[String], min: usize, max: Option<usize>) -> Result<&[String]> {
if args.len() < min {
anyhow::bail!("missing argument(s)");
}
if let Some(max) = max
&& args.len() > max
{
anyhow::bail!("too many arguments");
}
Ok(args)
}
pub fn now_secs() -> u32 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as u32)
.unwrap_or(0)
}
pub fn default_node_options(mode: u16) -> miniximg::CreateNodeOptions {
miniximg::CreateNodeOptions {
mode,
uid: 0,
gid: 0,
mtime: now_secs(),
}
}
pub fn default_parent_options() -> miniximg::CreateNodeOptions {
default_node_options(0o755)
}