Last active
February 22, 2019 18:16
-
-
Save jbodah/46cce8520b7f711d7f85f596e9ffd7dd to your computer and use it in GitHub Desktop.
finds unreferenced/dead methods
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
# Usage: find app/models -name '*.rb' | xargs -n 1 ruby find_unreferenced.rb | |
require 'parser/current' | |
class ASTProcessor | |
include AST::Processor::Mixin | |
attr_reader :possibly_unreferenced | |
def initialize | |
@possibly_unreferenced = [] | |
end | |
def handler_missing(node) | |
process_all(node.children.select { |child| child.is_a? AST::Node }) | |
end | |
def on_def(node) | |
method_name = node.children[0] | |
maybe_find_method(method_name) | |
end | |
def on_defs(node) | |
method_name = node.children[1] | |
maybe_find_method(method_name, prefix: "self.") | |
end | |
def maybe_find_method(method_name, prefix: "") | |
search_term = Regexp.escape(method_name) | |
search_term.gsub!(/=/, '\s*=') | |
ag_term = "'(?!<\w)#{search_term}(?!\w)'" | |
matches = `ag #{ag_term} -c --case-sensitive app lib`.rstrip | |
lines = matches.each_line | |
return if lines.count > 1 | |
if lines.first.split(':').last == '1' | |
@possibly_unreferenced << (prefix + method_name.to_s) | |
end | |
end | |
end | |
include AST::Sexp | |
$file = ARGV[0] | |
ast = Parser::CurrentRuby.parse(File.read($file)) | |
processor = ASTProcessor.new | |
processor.process(ast) | |
exit(0) if processor.possibly_unreferenced.none? | |
puts "Might be unreferenced (in #{$file}):" | |
processor.possibly_unreferenced.each { |method_name| puts " - #{method_name}" } | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment