forked from claranet/terraform-path-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.py
executable file
·96 lines (67 loc) · 2.01 KB
/
hash.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env python
#
# Generates a content hash of a path,
# ignoring file modification and access times.
#
import hashlib
import json
import os
import sys
def abort(message):
"""
Exits with an error message.
"""
sys.stderr.write(message + '\n')
sys.exit(1)
def list_files(top_path):
"""
Returns a sorted list of all files in a directory.
"""
results = []
for root, dirs, files in os.walk(top_path, topdown=True):
# Exclude dot files like .git
dirs[:] = [name for name in dirs if not name.startswith('.')]
files[:] = [name for name in files if not name.startswith('.')]
for file_name in files:
results.append(os.path.join(root, file_name))
results.sort()
return results
def generate_content_hash(source_path):
"""
Generate a content hash of the source path.
"""
sha256 = hashlib.sha256()
if os.path.isdir(source_path):
source_dir = source_path
for source_file in list_files(source_dir):
update_hash(sha256, source_dir, source_file)
else:
source_dir = os.path.dirname(source_path)
source_file = source_path
update_hash(sha256, source_dir, source_file)
return sha256
def update_hash(hash_obj, file_root, file_path):
"""
Update a hashlib object with the relative path and contents of a file.
"""
relative_path = os.path.relpath(file_path, file_root)
hash_obj.update(relative_path.encode())
with open(file_path, 'rb') as open_file:
while True:
data = open_file.read(1024)
if not data:
break
hash_obj.update(data)
# Parse the query.
query = json.load(sys.stdin)
path = query['path']
# Validate the query.
if not path:
abort('path must be set')
# Generate a hash based on file names and content.
content_hash = generate_content_hash(path)
# Output the result to Terraform.
json.dump({
'result': content_hash.hexdigest(),
}, sys.stdout, indent=2)
sys.stdout.write('\n')