use std::{
fs,
io::{self, Read, Write},
path::{Path, PathBuf},
};
use crate::error::CliError;
fn extension_of(path: &Path) -> Option<String> {
path.extension()
.map(|ext| ext.to_string_lossy().to_ascii_lowercase())
}
pub enum Source {
Stdin,
File(PathBuf),
}
pub enum Sink {
Stdout,
File(PathBuf),
}
impl Source {
#[must_use]
pub fn from_arg(path: &Path) -> Self {
if path.as_os_str() == "-" {
Self::Stdin
} else {
Self::File(path.to_path_buf())
}
}
#[must_use]
pub fn label(&self) -> String {
match self {
Self::Stdin => "<stdin>".to_owned(),
Self::File(path) => path.display().to_string(),
}
}
#[must_use]
pub fn extension(&self) -> Option<String> {
match self {
Self::Stdin => None,
Self::File(path) => extension_of(path),
}
}
pub fn read(&self) -> Result<Vec<u8>, CliError> {
match self {
Self::Stdin => {
let mut buf = Vec::new();
io::stdin()
.lock()
.read_to_end(&mut buf)
.map_err(|err| CliError::read_input(self.label(), &err))?;
Ok(buf)
},
Self::File(path) => {
fs::read(path).map_err(|err| CliError::read_input(self.label(), &err))
},
}
}
}
impl Sink {
#[must_use]
pub fn from_arg(path: &Path) -> Self {
if path.as_os_str() == "-" {
Self::Stdout
} else {
Self::File(path.to_path_buf())
}
}
#[must_use]
pub fn label(&self) -> String {
match self {
Self::Stdout => "<stdout>".to_owned(),
Self::File(path) => path.display().to_string(),
}
}
#[must_use]
pub fn extension(&self) -> Option<String> {
match self {
Self::Stdout => None,
Self::File(path) => extension_of(path),
}
}
pub fn write(&self, bytes: &[u8]) -> Result<(), CliError> {
match self {
Self::Stdout => io::stdout()
.lock()
.write_all(bytes)
.map_err(|err| CliError::write_output(self.label(), &err)),
Self::File(path) => {
fs::write(path, bytes).map_err(|err| CliError::write_output(self.label(), &err))
},
}
}
}