Skip to main content

ligen_generator/generator/file_generator/file/
mod.rs

1use std::{fmt::Debug, path::{PathBuf, Path}};
2
3use crate::prelude::*;
4
5pub mod section;
6pub mod set;
7
8pub use section::*;
9pub use set::*;
10
11/// Structure representing a file path and its content.
12#[derive(Debug, Shrinkwrap)]
13#[shrinkwrap(mutable)]
14pub struct File {
15    /// File path.
16    pub path: PathBuf,
17    /// File Section.
18    #[shrinkwrap(main_field)]
19    pub section: FileSection
20}
21
22impl File {
23    /// Creates a new file from a template.
24    pub fn from_template(path: impl AsRef<Path>, template: &SectionTemplate) -> Result<Self> {
25        let path = path.as_ref().to_path_buf();
26        let section = FileSection::from_template(template)?;
27        Ok(Self { path, section })
28    }
29
30    /// Creates a new file with the specified path and content.
31    pub fn new(path: impl AsRef<std::path::Path>) -> Self {
32        let path = path.as_ref().to_path_buf();
33        let section = FileSection::new("root");
34        Self { path, section }
35    }
36
37    /// Saves the file.
38    pub fn save(&self) -> Result<()> {
39        ligen_utils::fs::write_file(&self.path, self.to_string())
40    }
41}