Last active
August 29, 2015 14:13
-
-
Save sdhull/a72039c03836bf573722 to your computer and use it in GitHub Desktop.
Static analysis to hunt down unused css & js after removing view code. Comment out the haml2html stuff if you are starting with erb/html
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
# script assumes you have already `git rm app/views/foo/bar.haml`, the more removed code the better | |
require 'httparty' | |
# find_deleted_lines | |
deleted_haml = `git diff --cached --diff-filter=D app/views` | |
# remove info about which file | |
cleaned_lines = [] | |
in_head = 0 | |
deleted_haml.each_line do |line| | |
if line.match /^diff --git/ | |
in_head += 1 | |
end | |
case in_head | |
when 6 | |
in_head = 0 | |
when 1..5 | |
in_head += 1 | |
else | |
cleaned_lines << line[1..-1] | |
end | |
end | |
cleaned_lines = cleaned_lines.join | |
cleaned_lines.gsub! /'/, '"' # make all quotes be double quotes | |
cleaned_lines.gsub! /^.*No newline at end of file/, '' # we don't care about these messages | |
cleaned_lines.gsub! /:inlinejavascript/, ":javascript" # custom filter to regular one | |
opts = {body: {converter: 2, haml: cleaned_lines}} | |
# convert haml to erb | |
html = HTTParty.post("https://haml2erb.org/api.html", opts).body | |
# find_classes | |
classes = html.to_enum(:scan, /class=['"].+['"]/).map { Regexp.last_match.to_s.gsub(/class=./,'').gsub(/['"]/,'').split(" ") }.flatten.uniq | |
# find_ids | |
ids = html.to_enum(:scan, /id=['"].+['"]/).map { Regexp.last_match.to_s.gsub(/id=./,'').gsub(/['"]/,'').split(" ") } | |
# count stuff and indicate what's safe to remove | |
{ids: ids, classes: classes}.each do |type, arr| | |
other_uses = arr.map {|c| `git grep #{c} app/views`.split("\n").size} | |
# count css rules | |
css_rules = arr.map {|c| `git grep #{c} app/assets/stylesheets`.split("\n").size} | |
# count js uses | |
js_uses = arr.map {|c| `git grep #{c} app/assets/javascripts`.split("\n")}.size | |
# find classes without other uses but with rules or js | |
things_to_remove = [] | |
arr.each_with_index do |c, i| | |
things_to_remove << c if other_uses[i] == 0 && (css_rules[i] > 0 || js_uses[i] > 0) | |
end | |
if things_to_remove.size > 0 | |
puts "Try removing the following #{type}:" | |
puts "" | |
puts things_to_remove | |
else | |
puts "Looks like all the #{type} are used somewhere else or don't have associated js or css" | |
end | |
end | |
return nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment