Improve code stability is checksum checking

- use context manager for dealing with the checksum file
- use loop that can tolerate zero, one, or more items return rather than the previous expression which would break if anything other than exactly one item was returned
This commit is contained in:
Sam Doran 2018-09-12 17:45:45 -04:00 committed by Toshio Kuratomi
parent 2a3f3382fd
commit 03dbb1d9c4

View file

@ -461,11 +461,21 @@ def main():
checksum_url = checksum checksum_url = checksum
# download checksum file to checksum_tmpsrc # download checksum file to checksum_tmpsrc
checksum_tmpsrc, checksum_info = url_get(module, checksum_url, dest, use_proxy, last_mod_time, force, timeout, headers, tmp_dest) checksum_tmpsrc, checksum_info = url_get(module, checksum_url, dest, use_proxy, last_mod_time, force, timeout, headers, tmp_dest)
lines = [line.rstrip('\n') for line in open(checksum_tmpsrc)] with open(checksum_tmpsrc) as f:
os.remove(checksum_tmpsrc) lines = [line.rstrip('\n') for line in f]
lines = dict(s.split(None, 1) for s in lines) lines = dict(s.split(None, 1) for s in lines)
filename = url_filename(url) filename = url_filename(url)
[checksum] = (k for (k, v) in lines.items() if v.strip('./') == filename)
# Look through each line in the checksum file for a hash corresponding to
# the filename in the url, returning the first hash that is found.
for cksum in (s for (s, f) in lines.items() if f.strip('./') == filename):
checksum = cksum
break
else:
checksum = None
if checksum is None:
module.fail_json("Unable to find a checksum for file '%s' in '%s'" % (filename, checksum_url))
# Remove any non-alphanumeric characters, including the infamous # Remove any non-alphanumeric characters, including the infamous
# Unicode zero-width space # Unicode zero-width space
checksum = re.sub(r'\W+', '', checksum).lower() checksum = re.sub(r'\W+', '', checksum).lower()