Last active
January 20, 2017 04:09
-
-
Save dmyersturnbull/f0116c52feae3094f66b0c99b586d166 to your computer and use it in GitHub Desktop.
Add and check .sha1 files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Douglas Myers-Turnbull wrote this for the Kokel Lab, which has released it under the Apache Software License, Version 2.0 | |
# See the license file here: https://gist.github.com/dmyersturnbull/bfa1c3371e7449db553aaa1e7cd3cac1 | |
# The list of copyright owners is unknown | |
import hashlib | |
import os | |
import gzip | |
algorithm = hashlib.sha1 | |
extension = '.sha1' | |
def hashsum(file_name: str) -> str: | |
with open(file_name, 'rb') as f: | |
return algorithm(f.read()).hexdigest() | |
def add_hash(file_name: str) -> None: | |
with open(file_name + extension, 'w') as f: | |
f.write(hashsum(file_name)) | |
def check_hash(file_name: str) -> bool: | |
if not os.path.isfile(file_name + extension): return False | |
with open(file_name + extension, 'r') as f: | |
return f.read() == hashsum(file_name) | |
def check_and_open(file_name: str, *args): | |
return __o(file_name, opener=open, *args) | |
def check_and_open_gzip(file_name: str, *args): | |
return __o(file_name, opener=gzip.open, *args) | |
def __o(file_name: str, opener, *args): | |
if not os.path.isfile(file_name + extension): | |
raise ValueError("Hash for file {} does not exist".format(file_name)) | |
with open(file_name + extension, 'r') as f: | |
if f.read() != hashsum(file_name): | |
raise ValueError("Hash for file {} does not match".format(file_name)) | |
return opener(file_name, *args) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment