/
pub.py
executable file
·174 lines (123 loc) · 4.5 KB
/
pub.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python3
import argparse
import hashlib
import os
import subprocess
import sys
from functools import cache
import boto3
BUCKET='ski.aarongutierrez.com'
DISTRIBUTION='ELFNI2LSHJUNK'
session = boto3.Session(profile_name='push')
s3 = session.client('s3')
cloudfront = session.client('cloudfront')
TYPE_MAP = {
'css': 'text/css',
'gif': 'image/gif',
'html': 'text/html; charset=utf8',
'jpg': 'image/jpeg',
'js': 'application/javascript',
'json': 'application/json',
'png': 'image/png',
'webp': 'image/webp',
}
CSS_FILE = 'site.css'
BUNDLE_FILE = 'dist/bundle.js'
def cache_length(ext):
if ext == 'html':
return '86400'
elif ext == 'json':
return '3600'
else:
return '31536000'
@cache
def current_keys():
print('Fetching existing keys in {}'.format(BUCKET))
existing = s3.list_objects_v2(Bucket=BUCKET)
keys = set([content['Key'] for content in existing['Contents']])
while existing['IsTruncated']:
existing = s3.list_objects_v2(Bucket=BUCKET, ContinuationToken=existing['NextContinuationToken'])
keys = keys.union(set([content['Key'] for content in existing['Contents']]))
return keys
def upload_file(filename, overwrite=True):
ext = filename.split('.')[-1]
if not overwrite and filename in current_keys():
print('Skipping existing key {}'.format(filename))
return
print('Uploading {} to {}/{}'.format(filename, BUCKET, filename))
s3.upload_file(filename, BUCKET, filename, ExtraArgs={
'ACL': 'public-read',
'ContentType': TYPE_MAP[ext],
'CacheControl': 'public, max-age={}'.format(cache_length(ext))
})
print('\tDone.')
def set_default_object(key):
config = cloudfront.get_distribution_config(Id=DISTRIBUTION)
etag = config['ETag']
distributionConfig = config['DistributionConfig']
distributionConfig['DefaultRootObject'] = key
print('Setting distribution {} to have root object {}'.format(DISTRIBUTION, key))
cloudfront.update_distribution(Id=DISTRIBUTION,
IfMatch=etag,
DistributionConfig=distributionConfig)
print('\tDone.')
def filter_filenames(filenames, ext):
for f in filenames:
if (isinstance(ext, (list,)) and (f.split('.')[-1] in ext) \
or f.split('.')[-1] == ext):
yield f
def file_sha(filename):
output = subprocess.check_output(['shasum', '-a', '256', filename])
return output.decode().split(' ')[0]
def upload_root():
subprocess.check_call(['webpack'])
css_sha = file_sha(CSS_FILE)
css_filename = '{}.css'.format(css_sha)
bundle_sha = file_sha(BUNDLE_FILE)
bundle_filename = '{}.js'.format(bundle_sha)
subprocess.check_call(['cp', CSS_FILE, css_filename])
subprocess.check_call(['cp', BUNDLE_FILE, bundle_filename])
with open('template.html', 'r') as f:
template = f.read()
index = template.format(css_filename, bundle_filename)
h = hashlib.sha256()
h.update(bytes(index, 'utf-8'))
index_sha = h.hexdigest()
index_filename = '{}.html'.format(index_sha)
with open(index_filename, 'w') as f:
f.write(index)
upload_file(css_filename)
upload_file(bundle_filename)
upload_file(index_filename)
subprocess.check_call(['rm', '-f', css_filename])
subprocess.check_call(['rm', '-f', bundle_filename])
subprocess.check_call(['rm', '-f', index_filename])
set_default_object(index_filename)
def upload_original():
files = filter_filenames(os.listdir('img'), ['jpg', 'webp'])
for f in files:
upload_file('img/{}'.format(f), overwrite=False)
def upload_thumbnail(size):
files = filter_filenames(os.listdir('img/{}'.format(size)), ['jpg', 'webp'])
for f in files:
upload_file('img/{0}/{1}'.format(size, f), overwrite=False)
def upload_images():
upload_original()
upload_thumbnail(200)
upload_thumbnail(400)
upload_thumbnail(600)
upload_thumbnail(800)
upload_thumbnail(1200)
upload_thumbnail(1600)
upload_thumbnail(2400)
upload_file('img/data.json')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Publish ski.aarongutierrez.com')
pub_help = 'What to publish'
pub_choices = ['all', 'root', 'img']
parser.add_argument('pub', choices=pub_choices, help=pub_help)
args = parser.parse_args()
if args.pub == 'root' or args.pub == 'all':
upload_root()
if args.pub == 'img' or args.pub == 'all':
upload_images()