File: create-md5sums.py

package info (click to toggle)
spring 103.0%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,720 kB
  • ctags: 63,685
  • sloc: cpp: 368,283; ansic: 33,988; python: 12,417; java: 12,203; awk: 5,879; sh: 1,846; xml: 655; perl: 405; php: 211; objc: 194; makefile: 77; sed: 2
file content (61 lines) | stat: -rwxr-xr-x 1,422 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python

import prepare
import hashlib, sys, os

path = prepare.TMP_BASE
suffixes = sys.argv[3:] # config + branch are used in prepare.py
suffix = ".md5"

def hashfile(filename, blocksize=4096):
	hasher = hashlib.md5()
	f = open(filename, "rb")
	buf = f.read(blocksize)
	while len(buf) > 0:
		hasher.update(buf)
		buf = f.read(blocksize)
	return hasher.hexdigest()

def createhash(filename, md5):
	f = open(md5, 'wb')
	hexdigest = hashfile(filename)
	line = "%s %s" %(hexdigest, os.path.basename(filename))
	f.write(str.encode(line))
	f.close()
	return hexdigest

def verify(fn, md5):
	f = open(md5, "rb").read().decode("utf-8")
	hexdigest, filename = f.split(" ", 1)
	if filename != os.path.basename(fn):
		print("Invalid file: %s %s"% (filename, fn))
		return False, ""
	h = hashfile(fn)
	return h == hexdigest, h

def handlefile(f, suffixes, suffix):
	if f.endswith(suffix):
		return
	skip = True

	basename = os.path.basename(f)

	for s in suffixes: # check if filename matches suffix
		if basename.endswith(s):
			skip = False
			break
	if skip: return

	md5file = f + suffix
	if os.path.isfile(md5file):
		res, h = verify(f, md5file)
		print("Verifying %s: %s - %s" % (h, f, res))
	else:
		h = createhash(f, md5file)
		print("Creating %s: %s" % (h, md5file))


for root, directories, filenames in os.walk(path):
	for filename in filenames:
		handlefile(os.path.join(root, filename), suffixes, suffix)