Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 95 lines (78 sloc) 2.06 KB
#!/usr/bin/env ruby
DESTINATION = '_site'
DOC_EXTS = %w(atom html)
OBJECT_KEYS = {
'index.html' => '.index',
'404.html' => '.404',
}
require 'digest'
require 'pathname'
require 'bundler/setup'
require 'aws-sdk'
require 'rack'
def get_object_key(path)
if (object_key = OBJECT_KEYS[path.to_s])
object_key
elsif DOC_EXTS.include?(path.extname[1..-1])
path = path.to_s
path[0, path.rindex('.')]
else
path.to_s
end
end
def get_content_type(path)
Rack::Mime.mime_type(path.extname)
end
def has_digest?(path)
/-[\da-f]{32,64}\./i =~ path.to_s
end
def deploy_to_s3(bucket_name)
bucket = Aws::S3::Resource.new.bucket(bucket_name)
Dir.chdir(DESTINATION) do
paths_by_object_key = Pathname('.').find
.select(&:file?)
.map { |path| [get_object_key(path), path] }
.to_h
# delete objects
bucket.objects.each do |object|
next if paths_by_object_key.key?(object.key)
puts "DELETE #{object.key}"
object.delete
end
# upload files
paths_by_object_key.each do |object_key, path|
content = path.read(encoding: Encoding::BINARY)
object = bucket.object(object_key)
if object.exists? && (has_digest?(path) ||
object.etag == Digest::MD5.hexdigest(content).inspect)
puts "EXISTS #{object_key}"
next
end
content_type = get_content_type(path)
options = {
body: content,
content_type: content_type,
}
if has_digest?(path)
options[:cache_control] = "public, max-age=#{365 * 24 * 60 * 60}"
end
puts "UPLOAD #{path} => #{object_key} (#{content_type})"
object.put(options)
end
end
end
def invalidate(distribution_id)
Aws::CloudFront::Client.new.create_invalidation(
distribution_id: distribution_id,
invalidation_batch: {
paths: {
quantity: 1,
items: ['/*'],
},
caller_reference: (Time.now.to_f * 1000).to_i.to_s,
}
)
end
Dir.chdir(__dir__ + '/..')
deploy_to_s3(ENV.fetch('S3_BUCKET_NAME'))
invalidate(ENV.fetch('CLOUDFRONT_DISTRIBUTION_ID'))