-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhardlink.py
executable file
·67 lines (56 loc) · 1.76 KB
/
hardlink.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
67
#!/usr/bin/env python3
"""
Hard link all files in directory that have the same hash
"""
import argparse
import hashlib
import os
import sys
def hash_file(file: str, algorithm: str = "blake2b") -> str:
"""
Hash file
"""
with open(file, "rb") as f:
return hashlib.file_digest(f, algorithm).hexdigest()
def do_dir(directory: str, dry_run: bool = False, quiet: bool = False) -> None:
"""
Process directory
"""
hashes: dict[str, str] = {}
for root, _, files in os.walk(directory):
files.sort()
for file in files:
file = os.path.join(root, file)
if not os.path.isfile(file):
continue
file_hash = hash_file(file)
if file_hash in hashes:
dest_file = hashes[file_hash]
if os.path.samefile(file, dest_file):
continue
if not dry_run:
try:
os.unlink(file)
os.link(dest_file, file)
except OSError as exc:
sys.exit(str(exc))
if not quiet:
print(f"'{file}' => '{dest_file}'")
else:
hashes[file_hash] = file
def main() -> None:
"""
Main function
"""
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--dry-run", action="store_true", help="dry run")
parser.add_argument("-q", "--quiet", action="store_true", help="be quiet")
parser.add_argument("directory", nargs="+")
args = parser.parse_args()
for directory in args.directory:
do_dir(directory, dry_run=args.dry_run, quiet=args.quiet)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(1)