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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//! File tree
use crate::{Error, Etc, FileSystem, Meta, Read, Write};
use std::{
    fs,
    path::{Path, PathBuf},
};

#[cfg(feature = "serde-tree")]
use serde::{Deserialize, Serialize};

/// Here are two file types in `Tree`
///
/// + Dir  - no contents, have children
/// + File - have contents, no children
#[cfg_attr(feature = "serde-tree", derive(Serialize, Deserialize))]
#[derive(Debug, Default, Eq, PartialEq)]
pub struct Tree {
    /// File path
    pub path: PathBuf,
    /// File content
    pub content: Option<Vec<u8>>,
    /// Children files
    pub children: Option<Vec<Tree>>,
}

impl Tree {
    /// Batch all files into a tree, we can use this
    /// to implement some pre build stuffs.
    pub fn batch<Fs>(src: Fs) -> Result<Tree, Error>
    where
        Fs: FileSystem,
    {
        let path = src.real_path()?;
        if path.is_file() {
            Ok(Tree {
                path,
                content: None,
                children: None,
            })
        } else {
            let mut files: Vec<Tree> = vec![];
            for f in fs::read_dir(&path)? {
                files.push(Tree::batch(Etc::from(f?.path()))?);
            }

            // Iter children
            let children = if !files.is_empty() {
                files.sort_by_key(|f| f.path.clone());
                Some(files)
            } else {
                None
            };

            Ok(Tree {
                path,
                content: None,
                children,
            })
        }
    }

    /// Load file contents
    pub fn load(&mut self) -> Result<(), Error> {
        self.map(|t| {
            if t.path.is_file() {
                let stream = Etc::from(t.path.clone()).read();
                if let Ok(ctx) = stream {
                    t.content = Some(ctx);
                } else {
                    t.content = None;
                }
            }
        });
        Ok(())
    }

    /// Map the whole tree
    pub fn map<F>(&mut self, mut f: F)
    where
        F: FnMut(&mut Tree) + Sized + Copy,
    {
        f(self);
        if let Some(children) = &mut self.children {
            for t in children {
                t.map(f);
            }
        }
    }

    /// Redir tree path, just like `cp -r` in `unix`
    pub fn redir<P>(&mut self, path: P) -> Result<(), Error>
    where
        P: AsRef<Path> + Sized,
    {
        if !path.as_ref().exists() {
            fs::create_dir_all(&path)?;
        }

        let mut buf = path.as_ref().to_path_buf();
        buf.push(Etc::from(self.path.clone()).name()?);
        if let Some(children) = &mut self.children {
            for f in children {
                f.redir(&buf)?;
            }
        }

        if let Some(content) = &self.content {
            Etc::from(buf).write(&content)?;
        }

        Ok(())
    }

    /// Refresh children
    pub fn refresh(self) -> Result<Tree, Error> {
        Tree::batch(Etc::from(self.path))
    }
}

macro_rules! into {
    ([$($t:ty),+]) => {
        $(
            // Into `Vec<PathBuf>`
            impl Into<Vec<PathBuf>> for $t {
                fn into(self) -> Vec<PathBuf> {
                    let mut vp: Vec<PathBuf> = vec![];
                    vp.push(self.path.clone());
                    if let Some(children) = &self.children {
                        for f in children {
                            vp.append(&mut f.into());
                        }
                    }

                    vp
                }
            }

            // Into `Vec<tree>`
            impl Into<Vec<Tree>> for $t {
                fn into(self) -> Vec<Tree> {
                    let mut vp: Vec<Tree> = vec![];
                    let mut t = Tree::default();
                    t.path = self.path.clone();
                    t.content = self.content.clone();

                    vp.push(t);
                    if let Some(children) = &self.children {
                        for f in children {
                            vp.append(&mut f.into());
                        }
                    }

                    vp
                }
            }
        )+
    }
}

into!([&Tree, &mut Tree]);