-
Notifications
You must be signed in to change notification settings - Fork 3
/
path_checksum.py
47 lines (37 loc) · 1.41 KB
/
path_checksum.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
#/usr/bin/env python
"""Compute a checksum for a directory
Copied from http://code.activestate.com/recipes/576973-getting-the-sha-1-or-md5-hash-of-a-directory/
posted by David Moss.
"""
import hashlib
from os.path import normpath, walk, isdir, isfile, dirname, basename, \
exists as path_exists, join as path_join
import sys
def path_checksum(paths):
"""
Recursively calculates a checksum representing the contents of all files
found with a sequence of file and/or directory paths.
"""
if not hasattr(paths, '__iter__'):
raise TypeError('sequence or iterable expected not %r!' % type(paths))
def _update_checksum(checksum, dirname, filenames):
for filename in sorted(filenames):
path = path_join(dirname, filename)
if isfile(path):
print path
fh = open(path, 'rb')
while 1:
buf = fh.read(4096)
if not buf : break
checksum.update(buf)
fh.close()
chksum = hashlib.sha1()
for path in sorted([normpath(f) for f in paths]):
if path_exists(path):
if isdir(path):
walk(path, _update_checksum, chksum)
elif isfile(path):
_update_checksum(chksum, dirname(path), basename(path))
return chksum.hexdigest()
if __name__ == '__main__':
print path_checksum([sys.argv[1]])