Skip to content

Commit

Permalink
added path is a dir check in Feed::open
Browse files Browse the repository at this point in the history
  • Loading branch information
khodzha committed Jul 3, 2020
1 parent 62a411e commit 8ee485b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/feed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,11 +595,19 @@ where

impl Feed<RandomAccessDisk> {
/// Create a new instance that persists to disk at the location of `dir`.
// TODO: Ensure that dir is always a directory.
// NOTE: Should we `mkdirp` here?
/// If dir was not there, it will be created.
// NOTE: Should we call these `data.bitfield` / `data.tree`?
pub async fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
if let Err(e) = std::fs::create_dir_all(&path) {
return Err(anyhow::Error::msg(format!(
"Failed to create directory {} because of: {}",
path.as_ref().display(),
e
)));
}

let dir = path.as_ref().to_owned();

let storage = Storage::new_disk(&dir).await?;
Self::with_storage(storage).await
}
Expand Down
30 changes: 30 additions & 0 deletions tests/feed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,33 @@ async fn audit_bad_data() {
}
}
}

#[async_std::test]
async fn try_open_missing_dir() {
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};

let rand_string: String = thread_rng().sample_iter(&Alphanumeric).take(5).collect();
let mut dir = std::env::temp_dir();
let path = format!("hypercore_rs_test/nonexistent_paths_test/{}", rand_string);
dir.push(path);

if Feed::open(&dir).await.is_err() {
panic!("Opening nonexistent dir at a path should succeed");
}

if let Ok(d) = std::fs::metadata(dir) {
if !d.is_dir() {
panic!("Opening nonexistent dir at a path must create dir");
}
} else {
panic!("Opening nonexistent dir at a path must create dir");
}
}

#[async_std::test]
async fn try_open_file_as_dir() {
if Feed::open("Cargo.toml").await.is_ok() {
panic!("Opening path that points to a file must result in error");
}
}

0 comments on commit 8ee485b

Please sign in to comment.