update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
[osm/SO.git] / rwlaunchpad / plugins / rwlaunchpadtasklet / rift / package / checksums.py
1
2 #
3 # Copyright 2016 RIFT.IO Inc
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17
18 import hashlib
19 import re
20
21 def checksum_string(s):
22 return hashlib.md5(s.encode('utf-8')).hexdigest()
23
24
25 def checksum(fd):
26 """ Calculate a md5 checksum of fd file handle
27
28 Arguments:
29 fd: A file descriptor return from open() call
30
31 Returns:
32 A md5 checksum of the file
33
34 """
35 pos = fd.tell()
36 try:
37 current = hashlib.md5()
38 while True:
39 data = fd.read(2 ** 16)
40 if len(data) == 0:
41 return current.hexdigest()
42 current.update(data)
43 finally:
44 fd.seek(pos)
45
46
47 class ArchiveChecksums(dict):
48 @classmethod
49 def from_file_desc(cls, fd):
50 checksum_pattern = re.compile(r"(\S+)\s+(\S+)")
51 checksums = dict()
52
53 pos = fd.tell()
54 try:
55 for line in (line.decode('utf-8').strip() for line in fd if line):
56
57 # Skip comments
58 if line.startswith('#'):
59 continue
60
61 # Skip lines that do not contain the pattern we are looking for
62 result = checksum_pattern.search(line)
63 if result is None:
64 continue
65
66 chksum, filepath = result.groups()
67 checksums[filepath] = chksum
68
69 finally:
70 fd.seek(pos)
71
72 return cls(checksums)
73
74 def to_string(self):
75 string = ""
76 for file_name, file_checksum in self.items():
77 string += "{} {}\n".format(file_checksum, file_name)
78
79 return string