build_fs_tree/
build.rs

1mod error;
2mod impl_mergeable_tree;
3mod impl_tree;
4
5pub use error::*;
6
7use crate::{Node, NodeContent};
8
9/// Applying [`FileSystemTree`](crate::FileSystemTree) to the filesystem.
10///
11/// **Generic parameters:**
12/// * `Name`: Identification of a child item.
13/// * `Error`: Error type used by the other functions.
14pub trait Build<Name, Error>: Node + Sized
15where
16    Self::DirectoryContent: IntoIterator<Item = (Name, Self)>,
17{
18    /// Build target.
19    type BorrowedPath: ToOwned<Owned = Self::OwnedPath> + ?Sized;
20    /// Locations of the items in the filesystem.
21    type OwnedPath: AsRef<Self::BorrowedPath>;
22    /// Add prefix to the root of the tree.
23    fn join(prefix: &Self::BorrowedPath, name: &Name) -> Self::OwnedPath;
24    /// Write content to a file.
25    fn write_file(path: &Self::BorrowedPath, content: &Self::FileContent) -> Result<(), Error>;
26    /// Create a directory at root.
27    fn create_dir(path: &Self::BorrowedPath) -> Result<(), Error>;
28
29    /// Build the tree into the filesystem.
30    fn build<Path>(self, path: Path) -> Result<(), BuildError<Self::OwnedPath, Error>>
31    where
32        Path: AsRef<Self::BorrowedPath>,
33    {
34        let path = path.as_ref();
35
36        let children = match self.read() {
37            NodeContent::File(content) => {
38                return Self::write_file(path, &content).map_err(|error| BuildError {
39                    operation: FailedOperation::WriteFile,
40                    path: path.to_owned(),
41                    error,
42                })
43            }
44            NodeContent::Directory(children) => children,
45        };
46
47        Self::create_dir(path).map_err(|error| BuildError {
48            operation: FailedOperation::CreateDir,
49            path: path.to_owned(),
50            error,
51        })?;
52
53        for (name, child) in children {
54            child.build(Self::join(path, &name))?;
55        }
56
57        Ok(())
58    }
59}