ffh 0.1.0

ffh makes it easy to read and write files
Documentation
use std::fs; 
use std::io::Error;

// read the file at the given path and return its content
pub fn read(path: &str) -> Result<String, Error> {
    fs::read_to_string(path)
}

// overwrite the file at the given path with the given content
pub fn overwrite(path: &str, content: &str) -> Result<(), Error> {
    fs::write(path, content)
}

// append the given content to the file at the given path
pub fn append_line(path: &str, content: &str) -> Result<String, Error> {
    let current_content = read(path);
    if current_content.is_err() {
        return Err(current_content.err().unwrap());
    }
    let new_content = current_content.unwrap() + "\n" + content;
    let result = overwrite(path, &new_content);
    if result.is_err() {
        return Err(result.err().unwrap());
    }
    Ok(new_content)
}

// clear the file at the given path, but do not delete it
pub fn clear(path: &str) -> Result<(), Error> {
    fs::write(path, "")
}

// delete the file at the given path
pub fn delete(path: &str) -> Result<(), Error> {
    fs::remove_file(path)
}

pub fn work_on_lines(path: &str, f: fn(&str) -> String) -> Result<(), Error> {
    let content = read(path);
    if content.is_err() {
        return Err(content.err().unwrap());
    }
    let content = content.unwrap();
    let new_content = content.lines().map(f).collect::<Vec<String>>().join("\n");
    overwrite(path, &new_content)
}



#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_read() {
        let path = String::from("./test.txt");
        let result = read(&path);
        assert!(result.is_ok());
        let result = overwrite(&path, "Hello, World!");
        assert!(result.is_ok());
        let result = read(&path);
        assert!(result.unwrap() == "Hello, World!");
        let result = append_line(&path, "Hello, World!");
        assert!(result.is_ok());
        let result = read(&path);
        assert!(result.unwrap() == "Hello, World!\nHello, World!");
        let result = work_on_lines(&path, |line| line.to_uppercase());
        assert!(result.is_ok());
        let result = read(&path);
        assert!(result.unwrap() == "HELLO, WORLD!\nHELLO, WORLD!");

    }
}