Skip to content

Commit

Permalink
Merge pull request #28 from axodotdev/write_new
Browse files Browse the repository at this point in the history
feat(local): add write new
  • Loading branch information
ashleygwilliams authored Apr 4, 2023
2 parents 87d7315 + 50d3810 commit 2b8825e
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}")]
Expand Down
13 changes: 13 additions & 0 deletions src/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<PathBuf> {
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<PathBuf> {
LocalAsset::load(origin_path)?.write(dest_dir)
Expand Down
16 changes: 16 additions & 0 deletions tests/local_write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 2b8825e

Please sign in to comment.