Created
July 31, 2018 17:18
-
-
Save dmolesUC/c6ceaffab06fa53d5f9e031e549e2550 to your computer and use it in GitHub Desktop.
Script for downloading webfont files from Google Web Fonts CSS and converting CSS to point to local copies
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 ruby | |
require 'pathname' | |
infile = ARGV[0] | |
fonts_dir = ARGV[1] | |
unless infile && fonts_dir | |
puts "Usage: webfonts-to-local.rb <INPUT-CSS> <FONTS-DIR>" | |
exit(1) | |
end | |
unless File.exists?(infile) | |
puts "No such input file: #{infile}" | |
exit(1) | |
end | |
unless File.directory?(fonts_dir) | |
puts "No such fonts directory: #{fonts_dir}" | |
exit(1) | |
end | |
workdir_path = Pathname.new(Dir.pwd) | |
fonts_dir = Pathname.new(File.expand_path(fonts_dir)).relative_path_from(workdir_path).to_s | |
original = File.read(infile) | |
entries = original.split(/(?<=}\n)/) | |
entries.each do |e| | |
font_name = e.match(/local\('([^']+-[^']+)'\)/)[1] | |
# weight = font_name.match(/-([^-]+)$/)[1] | |
# next if weight.match(/(Light|Semi|Extra)/) # Filter out light, semibold, extrabold | |
language = e.match(/\/\* ([^ ]+) \*\//)[1] | |
language_qualifier = language.split('-').map(&:capitalize).join('-') | |
url = e.match(/url\(([^)]+)\)/)[1] | |
ext = url.match(/(\.[^.]+)$/)[1] | |
qualified_name = "#{font_name}-#{language_qualifier}#{ext}" | |
local_path = "#{fonts_dir}/#{qualified_name}" | |
unless File.exists?(local_path) | |
`curl #{url} -o #{local_path}` | |
end | |
new_css = e.sub(url, local_path) | |
puts new_css | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment