zombie_scout icon indicating copy to clipboard operation
zombie_scout copied to clipboard

Feature idea: Suppress warnings

Open mjacobus opened this issue 6 years ago • 1 comments

Hello there. Thank you for this tool, I am having so much fun removing code today!

One nice new feature could be suppressing entries. For instance I found several false positives - mostly view helpers and presenters method calls that end up "magically" on view files.

Right now I am manually adding a comment on the methods that are marked as unused but are actually used, so next time I can quickly ignore them.

Perhaps they could be suppressed by doing something like

# zombie_scout: ignore
def actually_used_method
end

Or something.

mjacobus avatar Jul 19 '18 06:07 mjacobus

This was my workaround for anyone who could be interested:

rake code:unused
# frozen_string_literal: true

module Code
  module Unused
    class OutputLine
      def initialize(contents)
        @contents = contents.to_s
      end

      def display?
        not_file_entry? || !ignore_entry
      end

      def to_s
        @contents
      end

      def ignore_entry
        method_suppressed? || file_ignored?
      end

      def file_ignored?
        File.new(filename).each_line do |line|
          if line.match?(/# zombie_scout ignore_all/)
            return true
          end
        end

        false
      end

      private

      def not_file_entry?
        !filename_and_line_match
      end

      def method_suppressed?
        previews_line = File.new(filename).readlines[line - 2]
        previews_line.match(/# zombie_scout ignore/)
      end

      def filename_and_line_match
        to_s.match(/[^\s]+\.rb:\d+/)
      end

      def filename
        @filename ||= filename_and_line_match.to_s.split(':').first
      end

      def line
        @line ||= Integer(filename_and_line_match.to_s.split(':').last)
      end
    end
  end
end

namespace :code do
  desc 'Find unused code'
  task :unused do
    tmp_file = './tmp/rake_code_unused_tmp'
    output_file = './log/unused_code'
    sh "bundle exec zombie_scout scout > #{tmp_file}"
    all_lines = File.readlines(tmp_file)
    contents = all_lines.select do |line|
      Code::Unused::OutputLine.new(line).display?
    end

    suppressed = all_lines.length - contents.length

    puts '-' * 80
    puts "Suppressed entries: #{suppressed}"
    puts '-' * 80
    puts contents.join('')

    File.open(output_file, 'w') do |file|
      contents.map do |line|
        file.puts(line)
      end
    end

    puts
    puts
    puts 'Suppress entries with:'
    puts '  # zombie_scout ignore'
    puts '  # zombie_scout ignore_all'
  end
end

mjacobus avatar Jul 19 '18 12:07 mjacobus