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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*!
dirinfo
=======

Crate `dirinfo` provides easy to use API for collecting various information about a
directory hierarchy.

To use this crate, add `dirinfo` as a dependency to your project's `Cargo.toml`:

``` toml
[dependencies]
dirinfo = { git = "https://github.com/renl/dirinfo" }
```

# Example

The following code calculates the total size in bytes of all files found in the
directory hierarchy with the root directory specified by the pull function.

```
use dirinfo::DirInfo;

println!("{}", DirInfo::new().pull(".").get_files_size());
```
*/
use walkdir::{DirEntry, WalkDir};
#[cfg(test)]
mod tests;

pub enum BlockSize {
    Kb100,
    Kb500,
    Mb(usize),
}

#[derive(Debug)]
struct Error {
    error: Option<std::io::Error>,
    path: Option<String>,
    depth: usize,
}

impl Error {
    fn new(path: Option<String>, depth: usize, error: Option<std::io::Error>) -> Error {
        Error {
            path: path,
            depth: depth,
            error: error,
        }
    }

    fn from(e: walkdir::Error) -> Error {
        let kind = match &e.io_error() {
            Some(ref err) => err.kind(),
            _ => std::io::ErrorKind::Other,
        };
        let d = e.depth();
        let s = String::from(e.path().unwrap().to_str().unwrap());
        let new_e = std::io::Error::new(kind, e);
        Error::new(Some(s), d, Some(new_e))
    }
}

#[derive(Debug)]
pub struct DirInfo {
    all: Option<Vec<DirEntry>>,
    errors: Option<Vec<Error>>,
    directories: Option<Vec<DirEntry>>,
    files: Option<Vec<DirEntry>>,
    symlinks: Option<Vec<DirEntry>>,
}

impl DirInfo {
    /// Create a new empty DirInfo struct

    pub fn new() -> DirInfo {
        DirInfo {
            all: None,
            errors: None,
            directories: None,
            files: None,
            symlinks: None,
        }
    }

    /// Populate DirInfo fields with directory information pulled with root_dir arg
    /// directory specifying the root directory to pull from

    pub fn pull(self, root_dir: &str) -> DirInfo {
        self.all(root_dir)
            .all_directories()
            .all_files()
            .all_symlinks()
    }

    fn all(mut self, root: &str) -> DirInfo {
        let mut direntries: Vec<DirEntry> = Vec::new();
        let mut errors: Vec<Error> = Vec::new();
        WalkDir::new(root).into_iter().for_each(|de| match de {
            Ok(d) => direntries.push(d),
            Err(e) => errors.push(Error::from(e)),
        });
        self.all = Some(direntries);
        self.errors = Some(errors);
        self
    }

    /// For all files found in the directory hierarchy, create a histogram of file
    /// sizes with the bin size of histogram specified by blocksize arg

    pub fn get_file_size_distribution(&self, blocksize: BlockSize) -> Vec<usize> {
        let blk: usize = match blocksize {
            BlockSize::Kb100 => 100_000usize,
            BlockSize::Kb500 => 500_000usize,
            BlockSize::Mb(x) => x * 1000_000usize,
        };
        let biggest = if let Some(ref files) = self.files {
            files.into_iter().fold(0, |max, d| {
                if d.metadata().unwrap().len() > max {
                    d.metadata().unwrap().len()
                } else {
                    max
                }
            })
        } else {
            0
        };
        let mut distribution: Vec<usize> = vec![0; (biggest as usize / blk) + 1];
        if let Some(ref files) = self.files {
            files.into_iter().for_each(|f| {
                distribution[f.metadata().unwrap().len() as usize / blk as usize] += 1
            });
        }
        distribution
    }

    /// Calculate the total file size in bytes for all the files found in directory
    /// hierarchy

    pub fn get_files_size(&self) -> usize {
        match self.files {
            Some(ref files) => files
                .iter()
                .fold(0, |acc, s| acc + s.metadata().unwrap().len() as usize),
            _ => 0,
        }
    }

    /// Calculate the total file size in bytes for all files with file extension
    /// of ext arg found in directory hierarchy

    pub fn get_files_size_by_file_ext(&self, ext: &str) -> usize {
        match self.files {
            Some(ref files) => files
                .iter()
                .filter(|f| f.file_name().to_str().unwrap().ends_with(ext))
                .fold(0, |acc, f| acc + f.metadata().unwrap().len() as usize),
            _ => 0,
        }
    }

    /// Calculate the total number of files with the extension specified by ext arg
    /// found in directory hierarchy

    pub fn get_num_files_by_file_ext(&self, ext: &str) -> usize {
        match self.files {
            Some(ref files) => files
                .iter()
                .filter(|f| f.file_name().to_str().unwrap().ends_with(ext))
                .fold(0, |acc, _f| acc + 1),
            _ => 0,
        }
    }

    /// Calculate the total file size in bytes for all hidden files found in directory
    /// hierarchy

    pub fn get_hidden_files_size(&self) -> usize {
        match self.files {
            Some(ref files) => files
                .iter()
                .filter(|f| f.file_name().to_str().unwrap().starts_with("."))
                .fold(0, |acc, f| acc + f.metadata().unwrap().len() as usize),
            _ => 0,
        }
    }

    /// Calculate the total number of files found in directory hierarchy

    pub fn get_num_files(&self) -> usize {
        match self.files {
            Some(ref files) => files.iter().fold(0, |acc, _f| acc + 1),
            _ => 0,
        }
    }

    /// Calculate the total number of hidden files found in directory hierarchy

    pub fn get_num_hidden_files(&self) -> usize {
        match self.files {
            Some(ref files) => files
                .iter()
                .filter(|f| f.file_name().to_str().unwrap().starts_with("."))
                .fold(0, |acc, _f| acc + 1),
            _ => 0,
        }
    }

    /// Calculate the total number of sub directories found in directory hierarchy

    pub fn get_num_directories(&self) -> usize {
        match self.directories {
            Some(ref directories) => directories.iter().fold(0, |acc, _f| acc + 1),
            _ => 0,
        }
    }

    /// Calculate the total number of hidden sub directories found in the directory
    /// hierarchy

    pub fn get_num_hidden_directories(&self) -> usize {
        match self.directories {
            Some(ref directories) => directories
                .iter()
                .filter(|f| f.file_name().to_str().unwrap().starts_with("."))
                .fold(0, |acc, _f| acc + 1),
            _ => 0,
        }
    }

    /// Calculate the total number of symbolic links found in the directory hierarchy

    pub fn get_num_symlinks(&self) -> usize {
        match self.symlinks {
            Some(ref symlinks) => symlinks.iter().fold(0, |acc, _f| acc + 1),
            _ => 0,
        }
    }

    fn deepest_depth(files: &Vec<DirEntry>) -> usize {
        files
            .iter()
            .fold(0, |max, d| if d.depth() > max { d.depth() } else { max })
    }

    /// Identify maximum depth of directory hierarchy

    pub fn get_deepest_depth(&self) -> usize {
        if let Some(ref files) = self.files {
            Self::deepest_depth(files)
        } else {
            0
        }
    }

    fn entry_depth_distri(entries: &Vec<DirEntry>) -> Vec<u32> {
        let deepest = Self::deepest_depth(entries);
        let mut depth_distri = vec![0u32; deepest];
        entries.iter().for_each(|f| {
            if f.depth() > 0 {
                depth_distri[f.depth() - 1] += 1
            }
        });
        depth_distri
    }

    /// Calculate distribution of number of files by depth level in directory hierarchy

    pub fn get_num_files_by_depth(&self) -> Vec<u32> {
        if let Some(ref files) = self.files {
            Self::entry_depth_distri(files)
        } else {
            vec![0]
        }
    }

    /// Calculate distribution of number of sub directories by depth level in directory
    /// hierarchy

    pub fn get_num_directories_by_depth(&self) -> Vec<u32> {
        if let Some(ref directories) = self.directories {
            Self::entry_depth_distri(directories)
        } else {
            vec![0]
        }
    }

    /// Calculate distribution of number of symbolic links by depth level in directory
    /// hierarchy

    pub fn get_num_symlinks_by_depth(&self) -> Vec<u32> {
        if let Some(ref symlinks) = self.symlinks {
            Self::entry_depth_distri(symlinks)
        } else {
            vec![0]
        }
    }

    /// Calculate distribution of file size by depth level in directory hierarchy

    pub fn get_files_size_by_depth(&self) -> Vec<usize> {
        if let Some(ref files) = self.files {
            let deepest = Self::deepest_depth(files);
            files.iter().fold(vec![0usize; deepest], |mut acc, f| {
                acc[f.depth() - 1] += f.metadata().unwrap().len() as usize;
                acc
            })
        } else {
            vec![0]
        }
    }

    /// Calculate distribution of hidden file size by depth level in directory hierarchy

    pub fn get_hidden_files_size_by_depth(&self) -> Vec<usize> {
        if let Some(ref files) = self.files {
            let deepest = Self::deepest_depth(files);
            files.iter().fold(vec![0usize; deepest], |mut acc, f| {
                if f.file_name().to_str().unwrap().starts_with(".") {
                    acc[f.depth() - 1] += f.metadata().unwrap().len() as usize;
                }
                acc
            })
        } else {
            vec![0]
        }
    }

    /// Calculate distribution of number of hidden files by depth level in directory
    /// hierarchy

    pub fn get_num_hidden_files_by_depth(&self) -> Vec<u32> {
        if let Some(ref files) = self.files {
            let deepest = Self::deepest_depth(files);
            let mut depth_distri = vec![0u32; deepest];
            files
                .iter()
                .filter(|f| f.file_name().to_str().unwrap().starts_with("."))
                .for_each(|f| {
                    if f.depth() > 0 {
                        depth_distri[f.depth() - 1] += 1
                    }
                });
            depth_distri
        } else {
            vec![0]
        }
    }

    fn all_directories(mut self) -> DirInfo {
        let mut entries: Vec<DirEntry> = Vec::new();
        if let Some(ref all) = self.all {
            for entry in all {
                if entry.file_type().is_dir() {
                    entries.push(entry.clone());
                }
            }
            self.directories = Some(entries);
        };
        self
    }

    fn all_files(mut self) -> DirInfo {
        let mut entries: Vec<DirEntry> = Vec::new();
        if let Some(ref all) = self.all {
            for entry in all {
                if entry.file_type().is_file() {
                    entries.push(entry.clone());
                }
            }
            self.files = Some(entries);
        }
        self
    }

    fn all_symlinks(mut self) -> DirInfo {
        let mut entries: Vec<DirEntry> = Vec::new();
        if let Some(ref all) = self.all {
            for entry in all {
                if entry.file_type().is_symlink() {
                    entries.push(entry.clone());
                }
            }
            self.symlinks = Some(entries);
        }
        self
    }
}