This repository has been archived by the owner on Jun 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfhashver
executable file
·55 lines (41 loc) · 1.72 KB
/
fhashver
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
#!/usr/bin/env python
"""Verify file hases generated by fhash"""
import hashlib
import sys
def die(msg: str, header: str = "ERROR", code: int = 1) -> int:
"""Return an exit code and print error"""
sys.stderr.write(f"{header}: {msg}\n")
return code
def main() -> int:
"""Entry/main function"""
if len(sys.argv) < 2:
return die("At least one argument required: hash_file")
for hash_file in sys.argv[1:]:
try:
with open(hash_file, "r", encoding="utf-8") as hashes:
for line in hashes:
hash_name, hash_value, filename = map(
str.rstrip, line.split(" ", 2)
)
try:
sys.stdout.write(f"{hash_name}: ")
with open(filename, "rb") as source:
calc_hash = getattr(hashlib, hash_name)(
source.read()
).hexdigest()
if calc_hash != hash_value:
sys.stdout.write("failed\n")
sys.exit(1)
sys.stdout.write("passed\n")
except (FileNotFoundError, IsADirectoryError):
sys.stdout.write("file_not_found\n")
except (TypeError, AttributeError):
sys.stdout.write("unknown\n")
except IsADirectoryError:
return die(f"{hash_file!r} is a directory")
except FileNotFoundError:
return die(f"{hash_file!r} not found")
return 0
if __name__ == "__main__":
assert main.__annotations__.get("return") is int, "main() should return an integer"
sys.exit(main())