ligen_core/generator/
file.rs

1//! File representation.
2
3use std::path::PathBuf;
4use std::collections::HashMap;
5
6/// Structure representing a file path and its content.
7#[derive(Debug, Clone)]
8pub struct File {
9    /// File path.
10    pub path: PathBuf,
11    /// File content.
12    pub content: String
13}
14
15impl File {
16    /// Creates a new file with the specified path and content.
17    pub fn new(path: PathBuf, content: String) -> Self {
18        Self { path, content }
19    }
20
21    /// Writes the content to the file.
22    pub fn write<S: AsRef<str>>(&mut self, content: S) {
23        self.content.push_str(content.as_ref());
24    }
25
26    /// Writes the content to the file and adds a new line.
27    pub fn writeln<S: AsRef<str>>(&mut self, content: S) {
28        self.content.push_str(content.as_ref());
29        self.content.push('\n');
30    }
31}
32
33/// Structure representing all the file set to be generated.
34#[derive(Debug, Default, Clone)]
35pub struct FileSet {
36    // FIXME: We need a better API.
37    pub(crate) files: HashMap<PathBuf, File>
38}
39
40impl FileSet {
41    /// Creates a new FileSet.
42    pub fn new() -> Self {
43        Self::default()
44    }
45
46    /// Adds a new file.
47    pub fn insert(&mut self, file: File) {
48        self.files.insert(file.path.clone(), file);
49    }
50
51    /// Gets an existing file.
52    pub fn get_mut(&mut self, path: &PathBuf) -> Option<&mut File> {
53        self.files.get_mut(path)
54    }
55
56    /// Returns an existing File assigned to an entry or creates a new one if it isn't present.
57    pub fn entry(&mut self, path: &PathBuf) -> &mut File {
58        self.files.entry(path.to_path_buf()).or_insert(File::new(path.clone(), Default::default()))
59    }
60}