Created
September 5, 2023 10:42
-
-
Save Coro365/46457e39518a71721ce1b5bb6e529739 to your computer and use it in GitHub Desktop.
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
require 'digest' | |
require 'base64' | |
WD = ARGV[0] | |
# sha256 sha384 sha512 | |
HASH_ALGO = "sha384" | |
allow_file_type = [".css", ".js"] | |
short_hash_length = 7 | |
def generate_hash(file) | |
case HASH_ALGO | |
when "sha512" | |
Base64.encode64(Digest::SHA512.digest(file)).delete("\n") | |
when "sha384" | |
Base64.encode64(Digest::SHA384.digest(file)).delete("\n") | |
when "sha256" | |
Base64.encode64(Digest::SHA256.digest(file)).delete("\n") | |
else | |
puts("ERROR: unkown hash algo. #{HASH_ALGO}") | |
exit(3) | |
end | |
end | |
def generate_html_tag(path, ext, hash) | |
case ext | |
when ".css" | |
"<link rel=\"stylesheet\" href=\"#{path}\" crossorigin=\"anonymous\" integrity=\"#{HASH_ALGO}-#{hash}\">" | |
when ".js" | |
"<script src=\"#{path}\" crossorigin=\"anonymous\" integrity=\"#{HASH_ALGO}-#{hash}\"></script>" | |
end | |
end | |
files = Dir.glob(WD + "/**/*") | |
hashs = files.map do |file_path| | |
if allow_file_type.include?(File.extname(file_path)) | |
[file_path, generate_hash(File.open(file_path).read)] | |
end | |
end.compact | |
hashs.each do |file_path, hash| | |
file_ext = File.extname(file_path) | |
# delete unnecesaary path | |
file_path = file_path.split(WD).last.gsub(/^\//, '') | |
# add URI query for cache update | |
file_path = file_path + "?#{HASH_ALGO}=#{hash[0, short_hash_length]}" | |
tag = generate_html_tag(file_path, file_ext, hash) | |
puts(tag) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment