Skip to content

Instantly share code, notes, and snippets.

@igorb
Forked from itsderek23/find_ununsed_assets.rb
Created October 12, 2020 10:29
Show Gist options
  • Save igorb/e2130b798bd5257e088331385d43cac6 to your computer and use it in GitHub Desktop.
Save igorb/e2130b798bd5257e088331385d43cac6 to your computer and use it in GitHub Desktop.
assets_path = File.expand_path("~/projects/rails/scout/public")
log_path = File.expand_path "~/assets.txt"
temp_requested_files_path = File.expand_path "~/processed_assets.txt"
ignore_pattern = /sparkline|datejs/
known_used =[
"javascripts/jquery-1.7.1.min.js",
"javascripts/jquery.extensions.js",
"javascripts/application.js",
"stylesheets/default.css",
"stylesheets/public.css"
]
puts "starting"
Dir.chdir assets_path
files = %w(js png jpg jpeg gif css).map{|ext| Dir.glob("**/*.#{ext}")}.flatten
puts "Found #{files.size} assets"
requested_files =[]
if(File.exist? temp_requested_files_path)
puts "#{temp_requested_files_path} exists -- using it"
requested_files = File.readlines(temp_requested_files_path).map(&:chomp)
else
puts "#{temp_requested_files_path} does not exist -- processing #{log_path}"
log = File.readlines(log_path)
puts "read #{log.size} lines from #{log_path}"
log_entries=log.map{|l| l.match(/GET \/([^? ]+)/)[1]}
requested_files = log_entries.uniq
File.open(temp_requested_files_path,"w") {|f| f.puts requested_files}
end
puts "found #{requested_files.size} requested files in logs"
puts ""
puts "== Local files that aren't requested in production:"
res = files - requested_files
res = res.select{|l| !l.match ignore_pattern }
res = res - known_used
res.sort.each_with_index do |f,i|
cmd = "rm #{assets_path}/#{f}"
puts cmd
# `#{cmd}` # only uncomment when you're satisfied with the list of files it's going to delete
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment