|
| 1 | +""" Python script to validate data |
| 2 | +
|
| 3 | +Run as: |
| 4 | +
|
| 5 | + python3 scripts/validata_data.py data |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +import sys |
| 10 | +import hashlib |
| 11 | + |
| 12 | +def file_hash(filename): |
| 13 | + """ Get byte contents of file `filename`, return SHA1 hash |
| 14 | +
|
| 15 | + Parameters |
| 16 | + ---------- |
| 17 | + filename : str |
| 18 | + Name of file to read |
| 19 | +
|
| 20 | + Returns |
| 21 | + ------- |
| 22 | + hash : str |
| 23 | + SHA1 hexadecimal hash string for contents of `filename`. |
| 24 | + """ |
| 25 | + # Open the file, read contents as bytes. |
| 26 | + # Calculate, return SHA1 has on the bytes from the file. |
| 27 | + with open(filename, 'rb') as fobj: |
| 28 | + contents = fobj.read() |
| 29 | + return hashlib.sha1(contents).hexdigest() |
| 30 | + |
| 31 | + |
| 32 | +def validate_data(data_directory): |
| 33 | + """ Read ``data_hashes.txt`` file in `data_directory`, check hashes |
| 34 | +
|
| 35 | + Parameters |
| 36 | + ---------- |
| 37 | + data_directory : str |
| 38 | + Directory containing data and ``data_hashes.txt`` file. |
| 39 | +
|
| 40 | + Returns |
| 41 | + ------- |
| 42 | + None |
| 43 | +
|
| 44 | + Raises |
| 45 | + ------ |
| 46 | + ValueError: |
| 47 | + If hash value for any file is different from hash value recorded in |
| 48 | + ``data_hashes.txt`` file. |
| 49 | + """ |
| 50 | + # Read lines from ``data_hashes.txt`` file. |
| 51 | + for line in open(os.path.join(data_directory, 'data_hashes.txt'), 'rt'): |
| 52 | + # Split into SHA1 hash and filename |
| 53 | + hash, filename = line.strip().split() |
| 54 | + # Calculate actual hash for given filename. |
| 55 | + actual_hash = file_hash(os.path.join(data_directory, filename)) |
| 56 | + # If hash for filename is not the same as the one in the file, raise |
| 57 | + # ValueError |
| 58 | + if hash != actual_hash: |
| 59 | + raise ValueError("Hash for {} does not match".format(filename)) |
| 60 | + |
| 61 | + |
| 62 | +def main(): |
| 63 | + # This function (main) called when this file run as a script. |
| 64 | + # |
| 65 | + # Get the data directory from the command line arguments |
| 66 | + if len(sys.argv) < 2: |
| 67 | + raise RuntimeError("Please give data directory on " |
| 68 | + "command line") |
| 69 | + data_directory = sys.argv[1] |
| 70 | + # Call function to validate data in data directory |
| 71 | + validate_data(data_directory) |
| 72 | + |
| 73 | + |
| 74 | +if __name__ == '__main__': |
| 75 | + # Python is running this file as a script, not importing it. |
| 76 | + main() |
0 commit comments