-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhash.rs
119 lines (89 loc) · 2.57 KB
/
hash.rs
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
use super::*;
pub(crate) trait Hash {
fn hash(&self) -> Result<Vec<u8>>;
}
impl Hash for PathBuf {
fn hash(&self) -> Result<Vec<u8>> {
let mut hasher = Sha256::new();
let read = |path: &PathBuf| -> Result<Vec<u8>> {
let mut file = File::open(path)?;
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)?;
Ok(buffer)
};
match (self.is_dir(), self.is_file()) {
(true, false) => {
for entry in WalkDir::new(self)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_file())
{
hasher.update(read(&entry.path().to_path_buf())?);
}
}
(false, true) => {
hasher.update(read(self)?);
}
_ => {
return Err(Error(anyhow!(
"{} is neither a file nor a directory",
self.display()
)))
}
}
Ok(hasher.finalize().to_vec())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::tempdir;
#[test]
fn hash_file() {
let directory = tempdir().unwrap();
let path = directory.path().join("test.txt");
let mut file = File::create(&path).unwrap();
writeln!(file, "Hello, world!").unwrap();
let hash_a = path.hash().unwrap();
assert!(!hash_a.is_empty());
let hash_b = path.hash().unwrap();
assert!(!hash_b.is_empty());
assert_eq!(hash_a, hash_b);
writeln!(file, "yeet").unwrap();
let hash_c = path.hash().unwrap();
assert!(!hash_c.is_empty());
assert_ne!(hash_c, hash_a);
directory.close().unwrap();
}
#[test]
fn hash_directory() {
let directory = tempdir().unwrap();
let path = directory.path().join("test.txt");
let mut file = File::create(path).unwrap();
writeln!(file, "Hello, world!").unwrap();
let hash_a = directory.path().to_path_buf().hash().unwrap();
assert!(!hash_a.is_empty());
let hash_b = directory.path().to_path_buf().hash().unwrap();
assert!(!hash_b.is_empty());
assert_eq!(hash_a, hash_b);
writeln!(file, "yeet").unwrap();
let hash_c = directory.path().to_path_buf().hash().unwrap();
assert!(!hash_c.is_empty());
assert_ne!(hash_c, hash_a);
directory.close().unwrap();
}
#[test]
fn hash_neither_file_nor_directory() {
let directory = tempdir().unwrap();
let result = directory.path().join("invalid").hash();
assert_eq!(
result.unwrap_err().to_string(),
format!(
"{} is neither a file nor a directory",
directory.path().join("invalid").display()
)
);
directory.close().unwrap();
}
}