use std::path::{Path, PathBuf};
use crate::{KitError, WorkspaceContext};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FileRead {
path: PathBuf,
content: FileReadContent,
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum FileReadContent {
Text(String),
Binary { bytes: Vec<u8>, mime_type: String },
}
impl FileRead {
pub fn from_bytes(path: PathBuf, bytes: Vec<u8>) -> Result<Self, KitError> {
let path = WorkspaceContext::normalized_relative(&path)?;
let content = match String::from_utf8(bytes) {
Ok(text) => FileReadContent::Text(text),
Err(error) => FileReadContent::Binary {
bytes: error.into_bytes(),
mime_type: "application/octet-stream".to_owned(),
},
};
Ok(Self { path, content })
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn text(&self) -> Option<&str> {
match &self.content {
FileReadContent::Text(text) => Some(text),
FileReadContent::Binary { .. } => None,
}
}
pub fn bytes(&self) -> Option<&[u8]> {
match &self.content {
FileReadContent::Text(_) => None,
FileReadContent::Binary { bytes, .. } => Some(bytes),
}
}
pub fn mime_type(&self) -> Option<&str> {
match &self.content {
FileReadContent::Text(_) => None,
FileReadContent::Binary { mime_type, .. } => Some(mime_type),
}
}
}