-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash-digest-rename.py
executable file
·66 lines (47 loc) · 1.64 KB
/
hash-digest-rename.py
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
#!/usr/bin/env python3
import hashlib
import os
import sys
def normalize_algorithm(name):
# Since the name might be caps or have dashes,
# we normalize to lowercase as used by Python's hashlib.
return name.lower().replace("-", "")
def plural(number):
return "" if number == 1 else "s"
def hash_rename(algorithm, path, errors):
try:
if not os.path.isfile(path):
raise RuntimeError(f"Source path '{path}' not a regular file")
with open(path, "rb") as file:
data = file.read()
hasher = hashlib.new(algorithm, data)
digest = hasher.hexdigest()
directory = os.path.dirname(path)
_, ext = os.path.splitext(path)
new_path = os.path.join(directory, digest + ext)
if path == new_path:
print(f"File {path} already renamed.")
elif os.path.exists(new_path):
os.remove(path)
raise RuntimeError(
f"Destination path '{new_path}' (from '{path}') already exists, deleting",
)
else:
print(f"Renaming {path} -> {new_path}")
os.rename(path, new_path)
except Exception as error:
errors.append(error)
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <algorithm> <path...>")
sys.exit(1)
algorithm = normalize_algorithm(sys.argv[1])
paths = sys.argv[2:]
print(f"Hashing {len(paths)} file{plural(len(paths))} with {algorithm}")
errors = []
for path in paths:
hash_rename(algorithm, path, errors)
if errors:
for error in errors:
print(error)
sys.exit(1)