Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
 
Implement file.write (#251)
  • Loading branch information
jabbate19 authored Jul 28, 2023
1 parent 2fe15df commit 7499417
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
3 changes: 2 additions & 1 deletion docs/_docs/user-guide/eldritch.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@ The <b>file.timestomp</b> method is very cool, and will be even cooler when Nick
### file.write
`file.write(path: str, content: str) -> None`

The <b>file.write</b> method is very cool, and will be even cooler when Nick documents it.
The <b>file.write</b> method writes to a given file path with the given content.
If a file or directory already exists at this path, the method will fail.

---

Expand Down
57 changes: 53 additions & 4 deletions implants/lib/eldritch/src/file/write_impl.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,54 @@
use anyhow::Result;
use anyhow::{anyhow, Result};
use std::{fs::File, io::Write, path::Path};

pub fn write(_path: String, _content: String) -> Result<()> {
unimplemented!("Method unimplemented")
}
pub fn write(path: String, content: String) -> Result<()> {
if Path::new(&path).exists() {
return Err(anyhow!("File already exists"));
}
let mut f = File::create(&path).map_err(|err| anyhow!("File could not be created: {err}"))?;
f.write_all(content.as_bytes())
.map_err(|err| anyhow!("Failed to write to file: {err}"))?;
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use tempfile::{tempdir, NamedTempFile};

#[test]
fn test_write_file_success() -> anyhow::Result<()> {
// Write to a file where we know it doesn't already exist
let tempdir = tempdir()?;
let path = tempdir
.path()
.join("writetest.txt")
.to_string_lossy()
.to_string();

assert!(write(path, "Hello World!".to_string()).is_ok());
tempdir.close()?;
Ok(())
}

#[test]
fn test_write_fail_file_exists() -> anyhow::Result<()> {
// Attempt to write to a file that already exists and fail
let tmp_file = NamedTempFile::new()?;
let path = String::from(tmp_file.path().to_str().unwrap()).clone();

assert!(write(path, "Hello World!".to_string()).is_err());
tmp_file.close()?;
Ok(())
}

#[test]
fn test_write_fail_directory_exists() -> anyhow::Result<()> {
// Attempt to write to a file that is currently a directory and fail
let dir = tempdir()?;
let path = String::from(dir.path().to_str().unwrap());

assert!(write(path, "Hello World!".to_string()).is_err());
Ok(())
}
}

0 comments on commit 7499417

Please sign in to comment.