Last active
January 23, 2019 21:37
-
-
Save mundry/8045987 to your computer and use it in GitHub Desktop.
Generate a file's fingerprint from its content.
This file contains 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
#!/usr/bin/env python2.7 | |
from os import rename | |
from hashlib import sha1 | |
INPUT_PATH = 'data' | |
INPUT_FILES = ['all.min.css', 'all.css'] | |
OUTPUT_PATH = 'output' | |
def get_sha1(data): | |
""" | |
Returns a 40 hexadecimal-character hash string of the given data. | |
""" | |
return sha1(data).hexdigest() | |
def split(filename): | |
""" | |
Split the given filename into its basename and extension. | |
The separate components will be returned as in list with the | |
basename at index 0 and the extension at index 1. | |
If the filename belongs to a file that has been minified the "min" | |
extension will be included in the extension part. | |
filename: | |
The filename to split into basename and extension. | |
""" | |
components = filename.split('.') | |
components_count = len(components) | |
if components_count == 1: # filename | |
return [filename, ''] # => ['filename', ''] | |
elif components_count == 2: # filename.ext | |
return components # => ['filename', 'ext'] | |
elif components[-2] == "min": # filename.min.ext or filename.whole.lota.dots.min.ext | |
return ['.'.join(components[:-2]), '.'.join(components[-2:])] # => ['filename.whole.lota.dots', 'min.ext'] | |
else: # filename.whole.lota.dots.ext | |
return ['.'.join(components[:-1]), '.'.join(components[-1:])] # => ['filename.whole.lota.dots', 'ext'] | |
def main(): | |
for input_file in INPUT_FILES: | |
data = None | |
phile = '{}/{}'.format(INPUT_PATH, input_file) | |
with open(phile) as fin: | |
data = fin.read() | |
sha = get_sha1(data) | |
input_file_components = split(input_file) | |
rename(phile, '{}/{}-{}.{}'.format(OUTPUT_PATH, input_file_components[0], sha, input_file_components[1])) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment