ยปCore Development>Code coverage>Tools/scripts/md5sum.py

Python code coverage for Tools/scripts/md5sum.py

#countcontent
1n/a#! /usr/bin/env python3
2n/a
3n/a"""Python utility to print MD5 checksums of argument files.
4n/a"""
5n/a
6n/a
7n/abufsize = 8096
8n/afnfilter = None
9n/armode = 'rb'
10n/a
11n/ausage = """
12n/ausage: md5sum.py [-b] [-t] [-l] [-s bufsize] [file ...]
13n/a-b : read files in binary mode (default)
14n/a-t : read files in text mode (you almost certainly don't want this!)
15n/a-l : print last pathname component only
16n/a-s bufsize: read buffer size (default %d)
17n/afile ... : files to sum; '-' or no files means stdin
18n/a""" % bufsize
19n/a
20n/aimport io
21n/aimport sys
22n/aimport os
23n/aimport getopt
24n/afrom hashlib import md5
25n/a
26n/adef sum(*files):
27n/a sts = 0
28n/a if files and isinstance(files[-1], io.IOBase):
29n/a out, files = files[-1], files[:-1]
30n/a else:
31n/a out = sys.stdout
32n/a if len(files) == 1 and not isinstance(files[0], str):
33n/a files = files[0]
34n/a for f in files:
35n/a if isinstance(f, str):
36n/a if f == '-':
37n/a sts = printsumfp(sys.stdin, '<stdin>', out) or sts
38n/a else:
39n/a sts = printsum(f, out) or sts
40n/a else:
41n/a sts = sum(f, out) or sts
42n/a return sts
43n/a
44n/adef printsum(filename, out=sys.stdout):
45n/a try:
46n/a fp = open(filename, rmode)
47n/a except IOError as msg:
48n/a sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg))
49n/a return 1
50n/a if fnfilter:
51n/a filename = fnfilter(filename)
52n/a sts = printsumfp(fp, filename, out)
53n/a fp.close()
54n/a return sts
55n/a
56n/adef printsumfp(fp, filename, out=sys.stdout):
57n/a m = md5()
58n/a try:
59n/a while 1:
60n/a data = fp.read(bufsize)
61n/a if not data:
62n/a break
63n/a if isinstance(data, str):
64n/a data = data.encode(fp.encoding)
65n/a m.update(data)
66n/a except IOError as msg:
67n/a sys.stderr.write('%s: I/O error: %s\n' % (filename, msg))
68n/a return 1
69n/a out.write('%s %s\n' % (m.hexdigest(), filename))
70n/a return 0
71n/a
72n/adef main(args = sys.argv[1:], out=sys.stdout):
73n/a global fnfilter, rmode, bufsize
74n/a try:
75n/a opts, args = getopt.getopt(args, 'blts:')
76n/a except getopt.error as msg:
77n/a sys.stderr.write('%s: %s\n%s' % (sys.argv[0], msg, usage))
78n/a return 2
79n/a for o, a in opts:
80n/a if o == '-l':
81n/a fnfilter = os.path.basename
82n/a elif o == '-b':
83n/a rmode = 'rb'
84n/a elif o == '-t':
85n/a rmode = 'r'
86n/a elif o == '-s':
87n/a bufsize = int(a)
88n/a if not args:
89n/a args = ['-']
90n/a return sum(args, out)
91n/a
92n/aif __name__ == '__main__' or __name__ == sys.argv[0]:
93n/a sys.exit(main(sys.argv[1:], sys.stdout))