Class: Debride

Inherits:
MethodBasedSexpProcessor
  • Object
show all
Defined in:
lib/debride.rb

Overview

A static code analyzer that points out possible dead methods.

Constant Summary collapse

VERSION =

:nodoc:

"1.14.0"
PROJECT =
"debride"
RAILS_DSL_METHODS =

Rails’ macro-style methods that setup method calls to happen during a rails app’s execution.

[
  :after_action,
  :around_action,
  :before_action,

  # https://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html (at bottom)
  :after_commit,
  :after_create,
  :after_destroy,
  :after_find,
  :after_initialize,
  :after_rollback,
  :after_save,
  :after_touch,
  :after_update,
  :after_validation,
  :around_create,
  :around_destroy,
  :around_save,
  :around_update,
  :before_create,
  :before_destroy,
  :before_save,
  :before_update,
  :before_validation,

  # https://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validate
  :validate,
]
RAILS_VALIDATION_METHODS =

Rails’ macro-style methods that count as method calls if their options include :if or :unless.

[
  # http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html
  :validates,
  :validates_absence_of,
  :validates_acceptance_of,
  :validates_comparison_of,
  :validates_confirmation_of,
  :validates_exclusion_of,
  :validates_format_of,
  :validates_inclusion_of,
  :validates_length_of,
  :validates_numericality_of,
  :validates_presence_of,
  :validates_size_of,
]
RAILS_MACRO_METHODS =

Rails’ macro-style methods that define methods dynamically.

[
  :belongs_to,
  :has_and_belongs_to_many,
  :has_many,
  :has_one,
  :scope,
]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Debride

Create a new Debride instance w/ options



223
224
225
226
227
228
229
230
231
# File 'lib/debride.rb', line 223

def initialize options = {}
  self.option = { :whitelist => [] }.merge options
  self.known  = Hash.new { |h,k| h[k] = Set.new }
  self.called = Set.new

  option[:parser] ||= NotRubyParser

  super()
end

Instance Attribute Details

#calledObject

A set of called method names.



213
214
215
# File 'lib/debride.rb', line 213

def called
  @called
end

#knownObject

A collection of know methods, mapping method name to implementing classes.



208
209
210
# File 'lib/debride.rb', line 208

def known
  @known
end

#optionObject

Command-line options.



218
219
220
# File 'lib/debride.rb', line 218

def option
  @option
end

Class Method Details

.file_extensionsObject



54
55
56
# File 'lib/debride.rb', line 54

def self.file_extensions
  %w[rb rake jbuilder] + load_plugins
end

.load_plugins(proj = PROJECT) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/debride.rb', line 30

def self.load_plugins proj = PROJECT
  unless defined? @@plugins then
    @@plugins = []

    task_re = /#{PROJECT}_task/o
    plugins = Gem.find_files("#{PROJECT}_*.rb").reject { |p| p =~ task_re }

    plugins.each do |plugin|
      plugin_name = File.basename(plugin, ".rb").sub(/^#{PROJECT}_/o, "")
      next if @@plugins.include? plugin_name
      begin
        load plugin
        @@plugins << plugin_name
      rescue RuntimeError, LoadError => e
        warn "error loading #{plugin.inspect}: #{e.message}. skipping..."
      end
    end
  end

  @@plugins
rescue
  []
end

.parse_options(args) ⇒ Object

Parse command line options and return a hash of parsed option values.



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/debride.rb', line 122

def self.parse_options args
  options = {
    :whitelist => i[
                     extended
                     included
                     inherited
                     method_added
                     method_missing
                     prepended
                    ],
    :exclude => [],
    :format => :text,
  }

  op = OptionParser.new do |opts|
    opts.banner  = "debride [options] files_or_dirs"
    opts.version = Debride::VERSION

    opts.separator ""
    opts.separator "Specific options:"
    opts.separator ""

    opts.on("-h", "--help", "Display this help.") do
      puts opts
      exit
    end

    opts.on("-e", "--exclude FILE1,FILE2,ETC", Array, "Exclude files or directories in comma-separated list.") do |list|
      options[:exclude].concat list
    end

    opts.on("-w", "--whitelist FILE", String, "Whitelist these messages.") do |s|
      options[:whitelist] = File.read(s).split(/\n+/) rescue []
    end

    opts.on("-f", "--focus PATH", String, "Only report against this path") do |s|
      unless File.exist? s then
        abort "ERROR: --focus path #{s} doesn't exist."
      end

      s = "#{s.chomp "/"}/*" if File.directory?(s)

      options[:focus] = s
    end

    opts.on("-r", "--rails", "Add some rails call conversions.") do
      options[:rails] = true
    end

    opts.on("-m", "--minimum N", Integer, "Don't show hits less than N locs.") do |n|
      options[:minimum] = n
    end

    opts.on "--legacy" "Use RubyParser for parsing." do
      require "ruby_parser"
      option[:parser] = RubyParser
    end

    opts.on("-v", "--verbose", "Verbose. Show progress processing files.") do
      options[:verbose] = true
    end

    opts.on "--json" do
      options[:format] = :json
    end

    opts.on "--yaml" do
      options[:format] = :yaml
    end
  end

  op.parse! args

  abort op.to_s if args.empty?

  options
rescue OptionParser::InvalidOption => e
  warn op.to_s
  warn ""
  warn e.message
  exit 1
end

.run(args) ⇒ Object

Top level runner for bin/debride.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/debride.rb', line 61

def self.run args
  debride = Debride.new parse_options args

  extensions = self.file_extensions
  glob = "**/*.{#{extensions.join(",")}}"
  expander = PathExpander.new(args, glob)
  files = expander.process.to_a
  excl  = debride.option[:exclude]
  excl.map! { |fd| File.directory?(fd) ? "#{fd}/**/*" : fd } if excl

  files = expander.filter_files files, StringIO.new(excl.join "\n") if excl

  debride.run(files)
  debride
end

Instance Method Details

#inspectObject



615
616
617
# File 'lib/debride.rb', line 615

def inspect
  "Debride[current=%s]" % [signature]
end

#klass_nameObject

:nodoc:



233
234
235
# File 'lib/debride.rb', line 233

def klass_name # :nodoc:
  super.to_s
end

#missingObject

Calculate the difference between known methods and called methods.



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/debride.rb', line 488

def missing
  whitelist_regexps = []

  option[:whitelist].each do |s|
    if s =~ /^\/.+?\/$/ then
      whitelist_regexps << Regexp.new(s[1..-2])
    else
      called << s.to_sym
    end
  end

  not_called = known.keys - called.to_a

  whitelist_regexp = Regexp.union whitelist_regexps

  not_called.reject! { |s| whitelist_regexp =~ s.to_s }

  by_class = Hash.new { |h,k| h[k] = [] }

  not_called.each do |meth|
    known[meth].each do |klass|
      by_class[klass] << meth
    end
  end

  by_class.each do |klass, meths|
    by_class[klass] = meths.sort_by(&:to_s)
  end

  by_class.sort_by { |k,v| k }
end

#missing_locationsObject



520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'lib/debride.rb', line 520

def missing_locations
  focus = option[:focus]

  missing.map { |klass, meths|
    bad = meths.map { |meth|
      location =
        method_locations["#{klass}##{meth}"] ||
        method_locations["#{klass}::#{meth}"]

      if focus then
        path = location[/(.+):\d+/, 1]

        next unless File.fnmatch(focus, path)
      end

      [meth, location]
    }.compact

    [klass, bad]
  }
    .to_h
    .reject { |k,v| v.empty? }
end

#name_to_string(exp) ⇒ Object



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/debride.rb', line 427

def name_to_string exp
  case exp.sexp_type
  when :const, :lit, :str then
    exp.last.to_s
  when :colon2 then
    _, lhs, rhs = exp
    "#{name_to_string lhs}::#{rhs}"
  when :colon3 then
    _, rhs = exp
    "::#{rhs}"
  when :self then # wtf?
    "self"
  else
    raise "Not handled: #{exp.inspect}"
  end
end

#plain_method_nameObject

:nodoc:



237
238
239
# File 'lib/debride.rb', line 237

def plain_method_name # :nodoc:
  method_name.to_s.sub(/^::|#/, "").to_sym
end

#process_alias(exp) ⇒ Object



383
384
385
386
387
388
389
390
391
# File 'lib/debride.rb', line 383

def process_alias exp
  _, (_, lhs), (_, rhs) = exp

  record_method lhs, exp.file, exp.line

  called << rhs

  exp
end

#process_attrasgn(sexp) ⇒ Object



241
242
243
244
245
246
247
# File 'lib/debride.rb', line 241

def process_attrasgn(sexp)
  _, _, method_name, * = sexp
  method_name = method_name.last if Sexp === method_name
  called << method_name
  process_until_empty sexp
  sexp
end

#process_block_pass(exp) ⇒ Object

:nodoc:



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/debride.rb', line 393

def process_block_pass exp # :nodoc:
  _, name = exp

  return exp unless name

  case name.sexp_type
  when :lit then              # eg &:to_sym
    called << name.last
  else                        # eg &lvar or &method(:x)
    # do nothing, body will get processed below
  end

  process_until_empty exp

  exp
end

#process_call(sexp) ⇒ Object Also known as: process_safe_call

:nodoc:



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/debride.rb', line 263

def process_call sexp # :nodoc:
  _, _, method_name, * = sexp

  case method_name
  when :new then
    method_name = :initialize
  when :alias_method_chain then
    # s(:call, nil, :alias_method_chain, s(:lit, :royale), s(:lit, :cheese))
    _, _, _, (_, new_name), _ = sexp
    if option[:rails] then
      file, line = sexp.file, sexp.line
      record_method new_name, file, line
    end
  when :attr_accessor then
    # s(:call, nil, :attr_accessor, s(:lit, :a1), ...)
    _, _, _, *args = sexp
    file, line = sexp.file, sexp.line
    args.each do |(_, name)|
      if Sexp === name then
        process name
        next
      end
      record_method name, file, line
      record_method "#{name}=".to_sym, file, line
    end
  when :attr_writer then
    # s(:call, nil, :attr_writer, s(:lit, :w1), ...)
    _, _, _, *args = sexp
    file, line = sexp.file, sexp.line
    args.each do |(_, name)|
      if Sexp === name then
        process name
        next
      end
      record_method "#{name}=".to_sym, file, line
    end
  when :attr_reader then
    # s(:call, nil, :attr_reader, s(:lit, :r1), ...)
    _, _, _, *args = sexp
    file, line = sexp.file, sexp.line
    args.each do |(_, name)|
      if Sexp === name then
        process name
        next
      end
      record_method name, file, line
    end
  when :send, :public_send, :__send__, :try, :const_get then
    # s(:call, s(:const, :Seattle), :send, s(:lit, :raining?))
    _, _, _, msg_arg, * = sexp
    if Sexp === msg_arg && [:lit, :str].include?(msg_arg.sexp_type) then
      called << msg_arg.last.to_sym
    end
  when :delegate then
    # s(:call, nil, :delegate, ..., s(:hash, s(:lit, :to), s(:lit, :delegator)))
    possible_hash = sexp.last
    if Sexp === possible_hash && possible_hash.sexp_type == :hash
      possible_hash.sexp_body.each_slice(2) do |key, val|
        next unless key == s(:lit, :to)
        next unless Sexp === val

        called << val.last        if val.sexp_type == :lit
        called << val.last.to_sym if val.sexp_type == :str
      end
    end
  when :method then
    # s(:call, nil, :method, s(:lit, :foo))
    _, _, _, msg_arg, * = sexp
    if Sexp === msg_arg && [:lit, :str].include?(msg_arg.sexp_type) then
      called << msg_arg.last.to_sym
    end
  when *RAILS_DSL_METHODS, *RAILS_VALIDATION_METHODS then
    if option[:rails]
      # s(:call, nil, :before_save, s(:lit, :save_callback), s(:hash, ...))
      if RAILS_DSL_METHODS.include?(method_name)
        _, _, _, (_, new_name), * = sexp
        called << new_name if new_name
      end
      possible_hash = sexp.last
      if Sexp === possible_hash && possible_hash.sexp_type == :hash
        possible_hash.sexp_body.each_slice(2) do |key, val|
          next unless Sexp === val
          called << val.last        if val.sexp_type == :lit
          called << val.last.to_sym if val.sexp_type == :str
        end
      end
    end
  when *RAILS_MACRO_METHODS
    # s(:call, nil, :has_one, s(:lit, :has_one_relation), ...)
    _, _, _, (_, name), * = sexp

    # try to detect route scope vs model scope
    if context.include? :module or context.include? :class then
      file, line = sexp.file, sexp.line
      record_method name, file, line
    end
  when /_path$/ then
    method_name = method_name.to_s.delete_suffix("_path").to_sym if option[:rails]
  when /^deliver_/ then
    method_name = method_name.to_s.delete_prefix("deliver_").to_sym if option[:rails]
  when :alias_method then
    _, _, _, lhs, rhs = sexp

    if Sexp === lhs and Sexp === rhs then
      lhs = lhs.last
      rhs = rhs.last

      record_method lhs, sexp.file, sexp.line

      called << rhs
    end
  end

  called << method_name

  process_until_empty sexp

  sexp
end

#process_cdecl(exp) ⇒ Object

:nodoc:



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/debride.rb', line 410

def process_cdecl exp # :nodoc:
  _, name, val = exp

  name = name_to_string process name if Sexp === name

  process val

  signature = "#{klass_name}::#{name}"

  known[name] << klass_name

  file, line = exp.file, exp.line
  method_locations[signature] = "#{file}:#{line}"

  exp
end

#process_colon2(exp) ⇒ Object

:nodoc:



444
445
446
447
448
449
450
451
# File 'lib/debride.rb', line 444

def process_colon2 exp # :nodoc:
  _, lhs, name = exp
  process lhs

  called << name

  exp
end

#process_colon3(exp) ⇒ Object

:nodoc:



453
454
455
456
457
458
459
# File 'lib/debride.rb', line 453

def process_colon3 exp # :nodoc:
  _, name = exp

  called << name

  exp
end

#process_const(exp) ⇒ Object

:nodoc:



461
462
463
464
465
466
467
# File 'lib/debride.rb', line 461

def process_const exp # :nodoc:
  _, name = exp

  called << name

  exp
end

#process_defn(sexp) ⇒ Object

:nodoc:



469
470
471
472
473
474
# File 'lib/debride.rb', line 469

def process_defn sexp # :nodoc:
  super do
    known[plain_method_name] << klass_name
    process_until_empty sexp
  end
end

#process_defs(sexp) ⇒ Object

:nodoc:



476
477
478
479
480
481
# File 'lib/debride.rb', line 476

def process_defs sexp # :nodoc:
  super do
    known[plain_method_name] << klass_name
    process_until_empty sexp
  end
end

#process_op_asgn2(sexp) ⇒ Object

handle &&=, ||=, etc



250
251
252
253
254
255
# File 'lib/debride.rb', line 250

def process_op_asgn2(sexp)
  _, _, method_name, * = sexp
  called << method_name
  process_until_empty sexp
  sexp
end

#process_rb(path_or_io) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/debride.rb', line 98

def process_rb path_or_io
  warn "Processing ruby: #{path_or_io}" if option[:verbose]

  case path_or_io
  when String then
    path, file = path_or_io, File.binread(path_or_io)
  when IO, StringIO then
    path, file = "(io)", path_or_io.read
  else
    raise "Unhandled type: #{path_or_io.class}:#{path_or_io.inspect}"
  end

  parser = option[:parser].new
  parser.process(file, path, option[:timeout])
rescue Racc::ParseError, RegexpError => e
  warn "Parse Error parsing #{path}. Skipping."
  warn "  #{e.message}"
rescue Timeout::Error
  warn "TIMEOUT parsing #{path}. Skipping."
end

#record_method(name, file, line) ⇒ Object



257
258
259
260
261
# File 'lib/debride.rb', line 257

def record_method name, file, line
  signature = "#{klass_name}##{name}"
  method_locations[signature] = "#{file}:#{line}"
  known[name] << klass_name
end

#report(io = $stdout) ⇒ Object

Print out a report of suspects.



547
548
549
550
551
552
# File 'lib/debride.rb', line 547

def report io = $stdout
  focus = option[:focus]
  type  = option[:format] || :text

  send "report_#{type}", io, focus, missing_locations
end

#report_json(io, focus, missing) ⇒ Object



591
592
593
594
595
596
597
598
599
600
601
# File 'lib/debride.rb', line 591

def report_json io, focus, missing
  require "json"

  data = {
    :missing => missing
  }

  data[:focus] = focus if focus

  JSON.dump data, io
end

#report_text(io, focus, missing) ⇒ Object



554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/debride.rb', line 554

def report_text io, focus, missing
  if focus then
    io.puts "Focusing on #{focus}"
    io.puts
  end

  io.puts "These methods MIGHT not be called:"

  total = 0

  missing.each do |klass, meths|
    bad = meths.map { |(meth, location)|
      loc = if location then
              l0, l1 = location.split(/:/).last.scan(/\d+/).flatten.map(&:to_i)
              l1 ||= l0
              l1 - l0 + 1
            else
              1
            end

      next if option[:minimum] && loc < option[:minimum]

      total += loc

      "  %-35s %s (%d)" % [meth, location, loc]
    }.compact

    next if bad.empty?

    io.puts
    io.puts klass
    io.puts bad.join "\n"
  end
  io.puts
  io.puts "Total suspect LOC: %d" % [total]
end

#report_yaml(io, focus, missing) ⇒ Object



603
604
605
606
607
608
609
610
611
612
613
# File 'lib/debride.rb', line 603

def report_yaml io, focus, missing
  require "yaml"

  data = {
    :missing => missing
  }

  data[:focus] = focus if focus

  YAML.dump data, io
end

#run(*files) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/debride.rb', line 77

def run(*files)
  files.flatten.each do |file|
    warn "Processing #{file}" if option[:verbose]

    ext = File.extname(file).sub(/^\./, "")
    ext = "rb" if ext.nil? || ext.empty?
    msg = "process_#{ext}"

    unless respond_to? msg then
      warn "  Unknown file type: #{ext}, defaulting to ruby" if option[:verbose]
      msg = "process_rb"
    end

    begin
      process send(msg, file)
    rescue RuntimeError, SyntaxError => e
      warn "  skipping #{file}: #{e.message}"
    end
  end
end