use std::fs;
use std::io::{self, Read};
use std::path::Path;
pub fn read_file(path: &str) -> Result<String, io::Error> {
let mut file = fs::File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
pub async fn read_file_async(path: &str) -> Result<String, io::Error> {
tokio::fs::read_to_string(path).await
}
pub async fn file_exists(path: &str) -> bool {
tokio::fs::metadata(path).await.is_ok()
}
pub fn file_get<P: AsRef<Path>>(path: P, base_path: Option<&str>) -> io::Result<String> {
if let Some(base_path) = base_path {
match path.as_ref().to_str() {
Some(path_str) => {
if !path_str.starts_with(base_path) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"File path is not within the base path",
));
}
}
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"File path is not a valid UTF-8 string",
));
}
}
}
fs::read_to_string(path)
}
pub async fn copy_file(src: &str, dst: &str) -> io::Result<()> {
if !Path::new(src).exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("Source file {} not found", src),
));
}
if let Some(parent) = Path::new(dst).parent() {
fs::create_dir_all(parent)?;
}
fs::copy(src, dst)?;
Ok(())
}
pub async fn file_get_async<P: AsRef<Path>>(
path: P,
base_path: Option<&str>,
) -> io::Result<String> {
if let Some(base_path) = base_path {
match path.as_ref().to_str() {
Some(path_str) => {
if !path_str.starts_with(base_path) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"File path is not within the base path",
));
}
}
None => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"File path is not a valid UTF-8 string",
));
}
}
}
tokio::fs::read_to_string(path).await
}