Skip to content

Instantly share code, notes, and snippets.

@itsderek23
Created August 22, 2012 17:35
Show Gist options
  • Save itsderek23/3427806 to your computer and use it in GitHub Desktop.
Save itsderek23/3427806 to your computer and use it in GitHub Desktop.

Revisions

  1. itsderek23 created this gist Aug 22, 2012.
    44 changes: 44 additions & 0 deletions find_ununsed_assets.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    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