diff --git a/README.md b/README.md index 7d036c4..052e79c 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Provides injectable Filesystem and Network resources to make code more testable. - [x] `std::fs::read_to_string` - `file(path).reader().to_string()` - Read the entire contents of a file into a string. - [x] `std::fs::remove_dir` - `dir(path).remove()` - Removes an empty directory. - [x] `std::fs::remove_dir_all` - `dir(path).remove_all()` - Removes a directory at this path, after removing all its contents. Use carefully! -- [ ] `std::fs::remove_file` - `file(path).remove()` - Removes a file from the filesystem. +- [x] `std::fs::remove_file` - `file(path).remove()` - Removes a file from the filesystem. - [ ] `std::fs::rename` - `path(path).rename()` - Rename a file or directory to a new name, replacing the original file if to already exists. - [ ] `std::fs::set_permissions` - `path(path).set_permissions()` - Changes the permissions found on a file or a directory. - [ ] `std::fs::symlink_metadata` - `link(path).metadata()` - Query the metadata about a file without following symlinks. diff --git a/src/fs/file.rs b/src/fs/file.rs index 2618002..8f30e4e 100644 --- a/src/fs/file.rs +++ b/src/fs/file.rs @@ -58,4 +58,22 @@ impl<'base, 'path> FileHandle<'base, 'path> { self.check_error()?; std::fs::copy(self.as_pathbuf(), dest.as_pathbuf()).map_err(Error::Io) } + + /// Removes a file. + /// + /// Wrapper for [std::fs::remove_file] + /// + /// ``` + /// # fn try_main() -> kxio::fs::Result<()> { + /// let fs = kxio::fs::temp()?; + /// let path = fs.base().join("foo"); + /// let file = fs.file(&path); + /// file.remove()?; + /// # Ok(()) + /// # } + /// ``` + pub fn remove(&self) -> Result<()> { + self.check_error()?; + std::fs::remove_file(self.as_pathbuf()).map_err(Error::Io) + } } diff --git a/tests/fs.rs b/tests/fs.rs index a18f9e8..ef5eb7f 100644 --- a/tests/fs.rs +++ b/tests/fs.rs @@ -466,6 +466,35 @@ mod copy { Ok(()) } } +mod file_remove { + use super::*; + #[test] + fn should_remove_a_file() -> TestResult { + let fs = fs::temp().expect("temp fs"); + let path = fs.base().join("foo"); + let file = fs.file(&path); + file.write("bar").expect("write"); + file.remove().expect("remove"); + let exists = file.exists().expect("exists"); + assert!(!exists); + + Ok(()) + } + + #[test] + fn should_fail_on_path_traversal() -> TestResult { + let fs = fs::temp().expect("temp fs"); + let path = fs.base().join("..").join("foo"); + let_assert!( + Err(fs::Error::PathTraversal { + base: _base, + path: _path + }) = fs.file(&path).remove() + ); + + Ok(()) + } +} mod reader { use super::*; mod bytes {