shitbox/src/cmd/basename/mod.rs

68 lines
1.8 KiB
Rust
Raw Normal View History

2023-01-08 01:12:36 -05:00
use super::Cmd;
use clap::{Arg, ArgMatches, Command};
use std::io;
#[derive(Debug)]
pub struct Basename {
name: &'static str,
path: Option<crate::Path>,
}
impl Default for Basename {
fn default() -> Self {
Self {
name: "basename",
path: Some(crate::Path::UsrBin),
}
}
}
impl Cmd for Basename {
fn name(&self) -> &str {
self.name
}
fn cli(&self) -> clap::Command {
Command::new(self.name)
.about("Print NAME with any leading directory components removed.")
.long_about(
"Print NAME with any leading directory components removed.\n\
If specified, also remove a trailing SUFFIX.",
)
.author("Nathan Fisher")
.args([
Arg::new("NAME")
.index(1)
.required(true)
.help("the filename to process"),
Arg::new("SUFFIX")
.index(2)
.required(false)
.help("the suffix to be removed"),
])
}
fn run(&self, matches: Option<&ArgMatches>) -> Result<(), Box<dyn std::error::Error>> {
let Some(matches) = matches else {
return Err(Box::new(io::Error::new(io::ErrorKind::Other, "no input")));
};
if let Some(mut base) = matches
.get_one::<String>("NAME")
.and_then(|x| x.split('/').last())
{
if let Some(suffix) = matches.get_one::<String>("SUFFIX") {
base = match base.strip_suffix(suffix) {
Some(b) => b,
None => base,
};
}
println!("{base}");
}
Ok(())
}
fn path(&self) -> Option<crate::Path> {
self.path
}
}