use std::path::Path;
use tokio::{
fs,
io::{AsyncRead, AsyncWriteExt},
};
pub type File = Box<dyn AsyncRead + Unpin + Send>;
pub async fn open(path: impl AsRef<Path>) -> Result<File, String> {
fs::File::open(path)
.await
.map_err(|err| err.to_string())
.map(|file| Box::new(file) as File)
}
pub async fn exists(path: impl AsRef<Path>) -> bool {
fs::metadata(path).await.is_ok()
}
pub async fn write(path: impl AsRef<Path>, bytes: &[u8]) -> Result<(), String> {
let parent = path.as_ref().parent().ok_or("no parent".to_string())?;
fs::create_dir_all(&parent)
.await
.map_err(|err| err.to_string())?;
let mut file = fs::File::create(&path)
.await
.map_err(|err| err.to_string())?;
file.write_all(&bytes)
.await
.map_err(|err| err.to_string())?;
Ok(())
}
pub async fn read_to_string(path: impl AsRef<Path>) -> std::io::Result<String> {
fs::read_to_string(path).await
}
pub async fn get_file_modified_ts(path: &Path) -> Result<chrono::DateTime<chrono::Utc>, String> {
let modified = tokio::fs::metadata(path)
.await
.map(|m| m.modified())
.map_err(|err| err.to_string())?
.map_err(|err| err.to_string())?;
Ok(chrono::DateTime::<chrono::Utc>::from(modified))
}