Created
September 21, 2020 17:34
-
-
Save MaxLap/1f0fb1c0f76a407fe3992362a944b4d3 to your computer and use it in GitHub Desktop.
Rails 3.2 assets usage report
This file contains hidden or 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
# This script will list asset files which are used and those which aren't for a Rails 3.2 application. | |
# | |
# It works by prefixing/suffixing all (js css less scss sass coffee) files. Then, after having run | |
# rake assets:precompile, you can run the script again and it will search in public/assets for | |
# those prefix to know if the file is definetly not used, or if it could be used. | |
root_dirs = %w(app/assets vendor) | |
file_endings = %w(js css less scss sass coffee) | |
file_paths_to_handle = root_dirs.flat_map {|d| file_endings.flat_map {|fe| Dir["#{d}/**/*.#{fe}"] } }.sort | |
# Good old random generated password :) | |
UNIQUE_STRING = "agF0T197HYwWTCXcjTDM46uB" | |
def prefix_each_paths(file_paths) | |
file_paths.each do |file_path| | |
next if File.directory?(file_path) | |
content = File.read(file_path) | |
if file_path.end_with?('.coffee') | |
# Only block comments are kept in coffee files | |
line = "\n###\n#{UNIQUE_STRING}#{file_path}#{UNIQUE_STRING.reverse}\n###\n" | |
else | |
line = "\n/*#{UNIQUE_STRING}#{file_path}#{UNIQUE_STRING.reverse}*/\n" | |
end | |
# For entry-point files, it seems the early comments are ignored, so putting the line at the end solves that | |
content = "#{line}#{content}#{line}" | |
File.write(file_path, content) | |
end | |
end | |
def extract_paths | |
file_paths_to_check = Dir['public/assets/**/*.js'] + Dir['public/assets/**/*.css'] | |
found_file_paths = file_paths_to_check.flat_map do |file_path| | |
content = File.read(file_path) | |
content.scan(%r{#{UNIQUE_STRING}(.*?)#{UNIQUE_STRING.reverse}}).flatten | |
end | |
found_file_paths.uniq.sort | |
end | |
if File.exist?('public/assets') | |
puts "Precompiled assets found, searching for unused files" | |
found_paths = extract_paths | |
unused_paths = file_paths_to_handle - found_paths | |
msg = "#{found_paths.size} used paths, #{unused_paths.size} unused paths" | |
puts msg | |
puts unused_paths.map { |p| "Unused: #{p}"} | |
puts found_paths.map { |p| "Used: #{p}"} | |
puts msg | |
else | |
prefix_each_paths(file_paths_to_handle) | |
puts "Prefixed all the files, now:" | |
puts "1) Make sure config.assets.compress is set to false in config/environments/production.rb" | |
puts "2) Run `rake assets:precompile`" | |
puts "3) Execute this script again" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment