From 50d3810677bbfa5fb4fb31726676a9dc23cdc62a Mon Sep 17 00:00:00 2001 From: Ashley Williams Date: Mon, 3 Apr 2023 19:45:47 -0500 Subject: [PATCH] feat(local): add write new --- src/error.rs | 13 +++++++++++++ src/local.rs | 13 +++++++++++++ tests/local_write.rs | 16 ++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/src/error.rs b/src/error.rs index a474e4f..3b7a60f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -220,6 +220,19 @@ pub enum AxoassetError { details: std::io::Error, }, + /// This error indicates that axoasset failed to write a new asset + #[error("failed to write a new asset to {dest_path}.")] + #[diagnostic(help( + "Make sure your destination path is relative to your oranda config or project manifest file." + ))] + LocalAssetWriteNewFailed { + /// The path where the asset was being written to + dest_path: String, + /// Details of the error + #[source] + details: std::io::Error, + }, + /// This error indicates that axoasset could not determine the filename for /// a local asset. #[error("could not determine file name for asset at {origin_path}")] diff --git a/src/local.rs b/src/local.rs index 971b72b..2dbed2c 100644 --- a/src/local.rs +++ b/src/local.rs @@ -98,6 +98,19 @@ impl LocalAsset { } } + /// Writes an asset to a path on the local filesystem, determines the + /// filename from the origin path + pub fn write_new(contents: &str, filename: &str, dest_dir: &str) -> Result { + let dest_path = Path::new(dest_dir).join(filename); + match fs::write(&dest_path, contents) { + Ok(_) => Ok(dest_path), + Err(details) => Err(AxoassetError::LocalAssetWriteNewFailed { + dest_path: dest_path.display().to_string(), + details, + }), + } + } + /// Copies an asset from one location on the local filesystem to another pub fn copy(origin_path: &str, dest_dir: &str) -> Result { LocalAsset::load(origin_path)?.write(dest_dir) diff --git a/tests/local_write.rs b/tests/local_write.rs index 8271968..c816a77 100644 --- a/tests/local_write.rs +++ b/tests/local_write.rs @@ -7,6 +7,22 @@ use std::path::Path; use assert_fs::prelude::*; use image::ImageFormat; +#[test] +fn it_writes_a_new_file_from_string() { + let dest = assert_fs::TempDir::new().unwrap(); + let dest_dir = Path::new(dest.to_str().unwrap()); + + let filename = "contents.txt"; + let contents = "CONTENTS"; + axoasset::LocalAsset::write_new(contents, filename, &dest_dir.display().to_string()).unwrap(); + let written_file = dest_dir.join(filename); + assert!(written_file.exists()); + + let loaded_contents = + axoasset::LocalAsset::load_string(&written_file.display().to_string()).unwrap(); + assert!(loaded_contents.contains(contents)); +} + #[tokio::test] async fn it_writes_local_assets() { let origin = assert_fs::TempDir::new().unwrap();