summary refs log tree commit diff stats
path: root/src/file_tree/mod.rs
blob: 84f5ad2d9277a8d1c46f34f9c57d819e1a8b1075 (plain) (blame)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*
* Copyright (C) 2023 - 2024:
* The Trinitrix Project <soispha@vhack.eu, antifallobst@systemausfall.org>
* SPDX-License-Identifier: LGPL-3.0-or-later
*
* This file is part of the Trixy crate for Trinitrix.
*
* Trixy is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* and the Lesser GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
*/

//! [`FileTree`]s are the fundamental data structure used by trixy to present generated data to
//! you.

use std::{
    fs::{self},
    path::{Path, PathBuf},
};

use anyhow::bail;

/// A file tree containing all files that were generated. These are separated into host and
/// auxiliary files. See their respective descriptions about what differentiates them.
#[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FileTree {
    /// Files, that are supposed to be included in the compiled crate.
    pub files: Vec<GeneratedFile>,
}

/// A generated files
#[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct GeneratedFile {
    /// The path this generated file would like to be placed at.
    /// This path is relative to the crate root.
    pub path: PathBuf,

    /// The content of this file.
    ///
    /// This should already be formatted and ready to be used.
    pub value: String,

    /// Whether to override this file silently, if it already exists.
    pub clobber: bool,
}

impl GeneratedFile {
    pub fn new(path: PathBuf, value: String) -> Self {
        Self {
            path,
            value,
            clobber: true,
        }
    }
    pub fn new_clobber(path: PathBuf, value: String, clobber: bool) -> Self {
        Self {
            path,
            value,
            clobber,
        }
    }
    pub fn new_in_out_dir(name: String, value: String, out_dir: &Path) -> Self {
        let path = out_dir.join(name);
        Self {
            path,
            value,
            clobber: true,
        }
    }

    pub fn materialize(self) -> anyhow::Result<()> {
        if !self.clobber {
            // Check if the file exists
            if self.path.try_exists()? {
                bail!(
                    "Path at '{}' already exists,\n       \
                    but I don't want to override the file there!\n       \
                    Please move it out of the way manually.",
                    self.path.display()
                )
            }
        }

        fs::create_dir_all(self.path.parent().expect("This path should have a parent"))?;
        fs::write(self.path, self.value.as_bytes())?;
        Ok(())
    }
}

impl FileTree {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_file(&mut self, file: GeneratedFile) {
        self.files.push(file)
    }

    pub fn extend(&mut self, files: Vec<GeneratedFile>) {
        files.into_iter().for_each(|file| self.add_file(file));
    }

    pub fn materialize(self) -> anyhow::Result<()> {
        self.files
            .into_iter()
            .map(|file| -> anyhow::Result<()> { file.materialize() })
            .collect::<anyhow::Result<()>>()?;
        Ok(())
    }
}