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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//! File representation.

use std::path::PathBuf;
use std::collections::HashMap;

/// Structure representing a file path and its content.
#[derive(Debug, Clone)]
pub struct File {
    /// File path.
    pub path: PathBuf,
    /// File content.
    pub content: String
}

impl File {
    /// Creates a new file with the specified path and content.
    pub fn new(path: PathBuf, content: String) -> Self {
        Self { path, content }
    }

    /// Writes the content to the file.
    pub fn write<S: AsRef<str>>(&mut self, content: S) {
        self.content.push_str(content.as_ref());
    }

    /// Writes the content to the file and adds a new line.
    pub fn writeln<S: AsRef<str>>(&mut self, content: S) {
        self.content.push_str(content.as_ref());
        self.content.push('\n');
    }
}

/// Structure representing all the file set to be generated.
#[derive(Debug, Default, Clone)]
pub struct FileSet {
    // FIXME: We need a better API.
    pub(crate) files: HashMap<PathBuf, File>
}

impl FileSet {
    /// Creates a new FileSet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a new file.
    pub fn insert(&mut self, file: File) {
        self.files.insert(file.path.clone(), file);
    }

    /// Gets an existing file.
    pub fn get_mut(&mut self, path: &PathBuf) -> Option<&mut File> {
        self.files.get_mut(path)
    }

    /// Returns an existing File assigned to an entry or creates a new one if it isn't present.
    pub fn entry(&mut self, path: &PathBuf) -> &mut File {
        self.files.entry(path.to_path_buf()).or_insert(File::new(path.clone(), Default::default()))
    }
}