below_common/
fileutil.rs

1// Copyright (c) Facebook, Inc. and its affiliates.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::path::Path;
16
17use walkdir::WalkDir;
18
19// Get directory size recursively
20pub fn get_dir_size<P: AsRef<Path>>(path: P) -> u64 {
21    WalkDir::new(path)
22        .into_iter()
23        .filter_map(|entry| entry.ok())
24        .filter_map(|entry| entry.metadata().ok())
25        .filter(|metadata| metadata.is_file())
26        .fold(0, |acc, m| acc + m.len())
27}
28
29#[cfg(test)]
30mod tests {
31    use std::fs;
32    use std::fs::File;
33    use std::io::BufWriter;
34    use std::io::Write;
35
36    use tempfile::TempDir;
37
38    use super::*;
39
40    fn make_file<P: AsRef<Path>>(path: P, size: u64) {
41        let file = File::create(&path).expect("Failed to create file");
42        let mut writer = BufWriter::new(file);
43        for _ in 0..size {
44            writer.write_all(&[0]).expect("Failed to write");
45        }
46        writer.flush().expect("Failed to flush writer");
47    }
48
49    #[test]
50    fn test_get_dir_size() {
51        // Empty directory
52        {
53            let dir = TempDir::with_prefix("below_fileutil_test.").expect("tempdir failed");
54            let size = get_dir_size(dir.path());
55            assert_eq!(size, 0);
56        }
57        // Directory with files and files in nested directories
58        {
59            let dir = TempDir::with_prefix("below_fileutil_test.").expect("tempdir failed");
60            fs::create_dir(dir.path().join("dir_A")).expect("Failed to create directory");
61            fs::create_dir(dir.path().join("dir_B")).expect("Failed to create directory");
62            make_file(dir.path().join("A"), 1000);
63            make_file(dir.path().join("B"), 100);
64            make_file(dir.path().join("dir_A/A"), 10);
65            make_file(dir.path().join("dir_B/A"), 1);
66            make_file(dir.path().join("dir_B/B"), 0);
67
68            let size = get_dir_size(dir.path());
69            assert_eq!(size, 1111);
70        }
71    }
72}