1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use core::fmt;
use std::{path::PathBuf, fs, error::Error, fmt::{Formatter, Display}};

pub const FORBIDDEN_FILENAME_CHARS: [char; 10] = ['\0', '\\', '/', ':', '*', '?', '"', '<', '>', '|'];

pub fn create(path: &PathBuf, content: &[u8]) -> Result<(), Box<dyn Error>> {
    if let Some(parents) = path.parent() {
        fs::create_dir_all(parents)?;
    }

    if path.exists() {
        return Err(Box::new(FileHelperError::new(String::from("File already exists"))));
    }

    fs::write(path, content)?;

    Ok(())
}

#[derive(Debug)]
pub struct FileHelperError {
    message: String
}

impl std::error::Error for FileHelperError {}

impl FileHelperError {
    pub fn new(message: String) -> FileHelperError {
        FileHelperError { message: message }
    }
}

impl Display for FileHelperError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", &self.message)
    }
}