dead_code_detector 0.0.8

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: dce82eaea034f691d31a834798cdb2d92cc8fdfb0b204f7e719f82b95a95b95d
4
+ data.tar.gz: dba4ecbc2b237afa42f7c45837455865d85817c26546d7eb03eb0f82cbdb9ed8
5
+ SHA512:
6
+ metadata.gz: 885bfe14c814f7f36782f57230eded98707723154d7efb2843caa97113dd30dea8c1d26634269ab45f4c9c92b4e387cf1956831e7fd26dafff996be39b2b18f3
7
+ data.tar.gz: 71ac7c3bf746b4b18f34a18d6cb78666dadf55f62fe1bfa91625c4cde3ccbfd12e2bf3860bfad5d44d00c4c7589cb1c55e8e0008eef563af04307302159596df
data/.gitignore ADDED
@@ -0,0 +1,3 @@
1
+ *~
2
+ .rspec_status
3
+ .byebug_history
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --colour
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at kyle.doliveira@clio.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in dead_code_detector.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,37 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ dead_code_detector (0.0.7.alpha)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ byebug (11.0.1)
10
+ diff-lcs (1.3)
11
+ rake (10.5.0)
12
+ rspec (3.7.0)
13
+ rspec-core (~> 3.7.0)
14
+ rspec-expectations (~> 3.7.0)
15
+ rspec-mocks (~> 3.7.0)
16
+ rspec-core (3.7.1)
17
+ rspec-support (~> 3.7.0)
18
+ rspec-expectations (3.7.0)
19
+ diff-lcs (>= 1.2.0, < 2.0)
20
+ rspec-support (~> 3.7.0)
21
+ rspec-mocks (3.7.0)
22
+ diff-lcs (>= 1.2.0, < 2.0)
23
+ rspec-support (~> 3.7.0)
24
+ rspec-support (3.7.1)
25
+
26
+ PLATFORMS
27
+ ruby
28
+
29
+ DEPENDENCIES
30
+ bundler (~> 1.17)
31
+ byebug
32
+ rake (~> 10.0)
33
+ rspec (~> 3.0)
34
+ dead_code_detector!
35
+
36
+ BUNDLED WITH
37
+ 1.17.3
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Kyle d'Oliveira
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # DeadCodeDetector
2
+
3
+ DeadCodeDetector is a gem which finds code that hasn't been used in production environments so that it can be removed.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'dead_code_detector'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install dead_code_detector
20
+
21
+ ## How it works
22
+
23
+ DeadCodeDetector takes advantage of Ruby's ability to dynamically define methods. For each class that you want to track, it dynamically rewrites every method on that class to track its usage. Here's a simplified version of what it does:
24
+
25
+ ```ruby
26
+ # Consider a class like this
27
+ class Foo
28
+ def bar
29
+ puts "hello world"
30
+ end
31
+ end
32
+
33
+ # Once DeadCodeDetector wraps the methods (Part 3 - Enabling it) it might look like this
34
+ class Foo
35
+ def bar
36
+ begin
37
+ DeadCodeDetector::InstanceMethodWrapper.track_method(Foo, :bar) # Track that this method was called
38
+ Foo.define_method(:bar) do
39
+ puts "hello world"
40
+ end
41
+ rescue
42
+ # To ensure that if DeadCodeDetector breaks it doesn't break the existing code
43
+ end
44
+ puts "hello world"
45
+ end
46
+ end
47
+
48
+ # That's how the method looks until it is hit once:
49
+ Foo.new.bar
50
+
51
+ # At this point we know that the method has been hit, so we restore the
52
+ # original version of the method.
53
+ ```
54
+
55
+ Because DeadCodeDetector only records method calls once, the performance overhead at runtime is negligible.
56
+
57
+ DeadCodeDetector only tracks method calls and does not track which code is used inside the method. If that is what you are after, consider looking at [coverband](https://github.com/danmayer/coverband). It can track code usage at a more granular level, but it has its own tradeoffs.
58
+
59
+ ## Usage
60
+
61
+ There are four steps to using DeadCodeDetector:
62
+
63
+ ### Part 1 - Configuration
64
+
65
+ This is where you tell DeadCodeDetector what you want to do. In Rails, the configuration could live in `config/initializers`.
66
+
67
+ ```ruby
68
+ DeadCodeDetector.configure do |config|
69
+ # Two possible values:
70
+ # :memory - In-memory storage, not persisted anywhere else. Useful for test environments.
71
+ # :redis - Data is stored as a set in Redis so that it is persisted across processes.
72
+ # config.storage = :redis
73
+ # config.storage = :memory
74
+
75
+ # If using the `redis` storage option, this needs to be set.
76
+ # config.redis = <instance of a Redis client object>
77
+
78
+ # This controls whether DeadCodeDetector is enabled for this particular process, and takes either
79
+ # a boolean or a object that responds to `call` that returns a boolean.
80
+ # There is some overhead whenever DeadCodeDetector enables itself, so you might not want to enable
81
+ # it on all of your processes.
82
+ # config.allowed = true
83
+ # config.allowed = -> { `hostname`.include?("01") }
84
+
85
+ # DeadCodeDetector will filter out methods whose source_location matches this regular expression.
86
+ # This is useful for filtering out methods from gems (such as the methods from ActiveRecord::Base)
87
+ # config.ignore_paths = /\/vendor\//
88
+
89
+ # A list of classes that DeadCodeDetector will monitor method usage on.
90
+ # All descendants of these classes will be included.
91
+ config.classes_to_monitor = [ActiveRecord::Base, ApplicationController]
92
+ end
93
+ ```
94
+
95
+ ### Part 2 - Cache Setup
96
+
97
+ Before DeadCodeDetector can do anything, it needs to calculate and store a list of methods that it's going to track. Call this method from a production console to initialize that database:
98
+
99
+ ```ruby
100
+ DeadCodeDetector::Initializer.refresh_caches
101
+ ```
102
+
103
+ If you add new classes or methods to your code which you want to track, you can call `refresh_caches` again at any time to clear all the accumulated data in Redis and start fresh. Until `refresh_caches` has been called at least once, DeadCodeDetector won't do anything.
104
+
105
+ ### Part 3 - Enabling it
106
+
107
+ Wrap the code that you want to monitor in an `DeadCodeDetector.enable` block. Any code inside that block will record method calls in DeadCodeDetector's storage when they're called for the first time.
108
+
109
+ ```ruby
110
+ DeadCodeDetector.enable do
111
+ # Do some stuff
112
+ end
113
+ ```
114
+
115
+ In Rails controllers, this could look like:
116
+ ```ruby
117
+ around_perform :enable_dead_code_detector
118
+
119
+ def enable_dead_code_detector
120
+ DeadCodeDetector.enable { yield }
121
+ end
122
+ ```
123
+
124
+ ### Part 4 - The Report
125
+
126
+ Once DeadCodeDetector has been running for a while, you can generate a report on what methods have not been called by calling `DeadCodeDetector::Report.unused_methods`
127
+
128
+ **Note**: This report doesn't say that methods are _never_ called, only that they _haven't_ been called. The longer DeadCodeDetector runs for, the more confident you can be that the method is unused.
129
+
130
+ Also, it's possible that some methods are being used, but are only called during the application boot process. DeadCodeDetector is unable to track those and may mis-report them as unused.
131
+
132
+ ## Development
133
+
134
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
135
+
136
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
137
+
138
+ ## Contributing
139
+
140
+ Bug reports and pull requests are welcome on GitHub at https://github.com/clio/dead_code_detector. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
141
+
142
+ ## License
143
+
144
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
145
+
146
+ ## Code of Conduct
147
+
148
+ Everyone interacting in the DeadCodeDetector project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/clio/dead_code_detector/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "dead_code_detector"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,39 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "dead_code_detector/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "dead_code_detector"
8
+ spec.version = DeadCodeDetector::VERSION
9
+ spec.authors = ["Kyle d'Oliveira"]
10
+ spec.email = ["kyle.doliveira@clio.com"]
11
+
12
+ spec.summary = %q{Help find unused code in production.}
13
+ spec.description = %q{This monitors methods being called and can be used to produce a report of all methods that have not been called.}
14
+ spec.homepage = "https://github.com/clio/dead_code_detector"
15
+ spec.license = "MIT"
16
+
17
+ if spec.respond_to?(:metadata)
18
+ spec.metadata["homepage_uri"] = spec.homepage
19
+ spec.metadata["source_code_uri"] = "https://github.com/clio/dead_code_detector"
20
+ # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ # Specify which files should be added to the gem when it is released.
27
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
28
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
29
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_development_dependency "bundler", "~> 1.17"
36
+ spec.add_development_dependency "rake", "~> 10.0"
37
+ spec.add_development_dependency "rspec", "~> 3.0"
38
+ spec.add_development_dependency "byebug"
39
+ end
@@ -0,0 +1,29 @@
1
+ require "dead_code_detector/version"
2
+ require "dead_code_detector/base_method_wrapper"
3
+ require "dead_code_detector/class_method_wrapper"
4
+ require "dead_code_detector/instance_method_wrapper"
5
+ require "dead_code_detector/storage"
6
+ require "dead_code_detector/initializer"
7
+ require "dead_code_detector/configuration"
8
+ require "dead_code_detector/report"
9
+
10
+ module DeadCodeDetector
11
+
12
+ def self.configure(&block)
13
+ block.call(config)
14
+ end
15
+
16
+ def self.config
17
+ @config ||= DeadCodeDetector::Configuration.new
18
+ end
19
+
20
+ def self.enable(&block)
21
+ begin
22
+ DeadCodeDetector::Initializer.enable_for_cached_classes!
23
+ block.call
24
+ ensure
25
+ config.storage.flush
26
+ end
27
+ end
28
+
29
+ end
@@ -0,0 +1,61 @@
1
+ module DeadCodeDetector
2
+ class BaseMethodWrapper
3
+
4
+ attr_reader :klass
5
+
6
+ def initialize(klass)
7
+ @klass = klass
8
+ end
9
+
10
+ class << self
11
+ def track_method(klass, method_name)
12
+ DeadCodeDetector.config.storage.delete(record_key(klass.name), method_name)
13
+ end
14
+
15
+ def unwrap_method(klass, original_method)
16
+ raise NotImplementedError
17
+ end
18
+ end
19
+
20
+ def wrap_methods!
21
+ potentially_unused_methods.each do |method_name|
22
+ wrap_method(get_method(method_name))
23
+ end
24
+ end
25
+
26
+ def clear_cache
27
+ DeadCodeDetector.config.storage.clear(self.class.record_key(klass.name))
28
+ end
29
+
30
+ def refresh_cache
31
+ clear_cache
32
+ DeadCodeDetector.config.storage.add(self.class.record_key(klass.name), default_methods)
33
+ end
34
+
35
+ private
36
+
37
+ def default_methods
38
+ raise NotImplementedError
39
+ end
40
+
41
+ def get_method(method_name)
42
+ raise NotImplementedError
43
+ end
44
+
45
+ def wrap_method(original_method)
46
+ raise NotImplementedError
47
+ end
48
+
49
+ def owned_method?(method_name)
50
+ raise NotImplementedError
51
+ end
52
+
53
+ # Due to caching, new methods won't show up automatically in this call
54
+ def potentially_unused_methods
55
+ stored_methods = DeadCodeDetector.config.storage.get(self.class.record_key(klass.name))
56
+
57
+ stored_methods & default_methods.map(&:to_s)
58
+ end
59
+
60
+ end
61
+ end
@@ -0,0 +1,64 @@
1
+ module DeadCodeDetector
2
+ class ClassMethodWrapper < BaseMethodWrapper
3
+
4
+ class << self
5
+ def unwrap_method(klass, original_method)
6
+ if klass.singleton_class == original_method.owner
7
+ klass.define_singleton_method(original_method.name, original_method)
8
+ else
9
+ klass.singleton_class.send(:remove_method, original_method.name)
10
+ end
11
+ track_method(klass, original_method.name)
12
+ end
13
+
14
+ def record_key(class_name)
15
+ "dead_code_detector/record_keeper/#{class_name}/class_methods"
16
+ end
17
+ end
18
+
19
+ def get_method(method_name)
20
+ klass.method(method_name)
21
+ end
22
+
23
+ private
24
+
25
+ def wrap_method(original_method)
26
+ original_class = klass
27
+ klass.define_singleton_method(original_method.name) do |*args, &block|
28
+ begin
29
+ DeadCodeDetector::ClassMethodWrapper.unwrap_method(original_class, original_method)
30
+ rescue StandardError => e
31
+ if DeadCodeDetector.config.error_handler
32
+ DeadCodeDetector.config.error_handler.call(e)
33
+ end
34
+ end
35
+ # We may have a method like `ActiveRecord::Base.sti_name`
36
+ # that begins bound to `ActiveRecord::Base`
37
+ # However, it may be called from `User.sti_name`
38
+ # We need to bind the original method to the class that
39
+ # is calling the method
40
+ unbound_method = original_method.unbind
41
+ method_bound_to_caller = unbound_method.bind(self)
42
+ method_bound_to_caller.call(*args, &block)
43
+ end
44
+ end
45
+
46
+ def default_methods
47
+ klass.methods.map(&:to_s).select do |method_name|
48
+ owned_method?(method_name) && target_directory?(method_name)
49
+ end
50
+ end
51
+
52
+ def target_directory?(method_name)
53
+ return true if DeadCodeDetector.config.ignore_paths.nil?
54
+ source_location = klass.method(method_name).source_location&.first
55
+ source_location !~ DeadCodeDetector.config.ignore_paths
56
+ end
57
+
58
+ def owned_method?(method_name)
59
+ original_method = klass.method(method_name)
60
+ klass.singleton_class <= original_method.owner && !(klass.superclass.singleton_class <= original_method.owner)
61
+ end
62
+
63
+ end
64
+ end
@@ -0,0 +1,30 @@
1
+ module DeadCodeDetector
2
+ class Configuration
3
+
4
+ attr_accessor :redis, :classes_to_monitor, :error_handler, :allowed, :cache_expiry, :ignore_paths
5
+
6
+ STORAGE_BACKENDS = {
7
+ memory: Storage::MemoryBackend,
8
+ redis: Storage::RedisBackend,
9
+ }
10
+
11
+ def initialize
12
+ @allowed = true
13
+ @classes_to_monitor = []
14
+ @cache_expiry = 60 * 60 * 24 * 14
15
+ end
16
+
17
+ def storage=(backend_type)
18
+ @storage ||= STORAGE_BACKENDS.fetch(backend_type).new
19
+ end
20
+
21
+ def storage
22
+ if @storage
23
+ @storage
24
+ else
25
+ raise "#{self.class.name}#storage is not configured"
26
+ end
27
+ end
28
+
29
+ end
30
+ end
@@ -0,0 +1,75 @@
1
+ module DeadCodeDetector
2
+ class Initializer
3
+
4
+ class << self
5
+
6
+ def refresh_caches
7
+ DeadCodeDetector.config.classes_to_monitor.each do |klass|
8
+ refresh_cache_for(klass)
9
+ end
10
+ end
11
+
12
+ def refresh_cache_for(klass)
13
+ @enabled = false
14
+ classes = [klass, *descendants_of(klass)]
15
+ classes.each do |class_to_enable|
16
+ cache_methods_for(class_to_enable)
17
+ end
18
+ end
19
+
20
+ def clear_cache
21
+ cached_classes.each do |class_name|
22
+ klass = Object.const_get(class_name) rescue nil
23
+ if klass
24
+ DeadCodeDetector::ClassMethodWrapper.new(klass).clear_cache
25
+ DeadCodeDetector::InstanceMethodWrapper.new(klass).clear_cache
26
+ end
27
+ end
28
+ DeadCodeDetector.config.storage.clear(tracked_classes_key)
29
+ end
30
+
31
+ def enable(klass)
32
+ DeadCodeDetector::ClassMethodWrapper.new(klass).wrap_methods!
33
+ DeadCodeDetector::InstanceMethodWrapper.new(klass).wrap_methods!
34
+ end
35
+
36
+ def enable_for_cached_classes!
37
+ return if @enabled
38
+ return unless allowed?
39
+ @enabled = true
40
+ cached_classes.each do |class_name|
41
+ klass = Object.const_get(class_name) rescue nil
42
+ enable(klass) if klass
43
+ end
44
+ end
45
+
46
+ def allowed?
47
+ if DeadCodeDetector.config.allowed.respond_to?(:call)
48
+ DeadCodeDetector.config.allowed.call
49
+ else
50
+ DeadCodeDetector.config.allowed
51
+ end
52
+ end
53
+
54
+ def cached_classes
55
+ DeadCodeDetector.config.storage.get(tracked_classes_key)
56
+ end
57
+
58
+ private
59
+ def descendants_of(parent_class)
60
+ ObjectSpace.each_object(parent_class.singleton_class).select { |klass| klass < parent_class }
61
+ end
62
+
63
+ def cache_methods_for(klass)
64
+ DeadCodeDetector.config.storage.add(tracked_classes_key, klass.name)
65
+ DeadCodeDetector::ClassMethodWrapper.new(klass).refresh_cache
66
+ DeadCodeDetector::InstanceMethodWrapper.new(klass).refresh_cache
67
+ end
68
+
69
+ def tracked_classes_key
70
+ "dead_code_detector/method_wrapper/tracked_classes"
71
+ end
72
+ end
73
+
74
+ end
75
+ end
@@ -0,0 +1,58 @@
1
+ module DeadCodeDetector
2
+ class InstanceMethodWrapper < BaseMethodWrapper
3
+
4
+ class << self
5
+ def unwrap_method(klass, original_method)
6
+ if original_method.owner == klass
7
+ klass.send(:define_method, original_method.name, original_method)
8
+ else
9
+ klass.send(:remove_method, original_method.name)
10
+ end
11
+ track_method(klass, original_method.name)
12
+ end
13
+
14
+ def record_key(class_name)
15
+ "dead_code_detector/record_keeper/#{class_name}/instance_methods"
16
+ end
17
+ end
18
+
19
+ def get_method(method_name)
20
+ klass.instance_method(method_name)
21
+ end
22
+
23
+ private
24
+
25
+ def wrap_method(original_method)
26
+ original_class = klass
27
+ klass.send(:define_method, original_method.name) do |*args, &block|
28
+ begin
29
+ DeadCodeDetector::InstanceMethodWrapper.unwrap_method(original_class, original_method)
30
+ rescue StandardError => e
31
+ if DeadCodeDetector.config.error_handler
32
+ DeadCodeDetector.config.error_handler.call(e)
33
+ end
34
+ end
35
+ method_bound_to_caller = original_method.bind(self)
36
+ method_bound_to_caller.call(*args, &block)
37
+ end
38
+ end
39
+
40
+ def default_methods
41
+ klass.instance_methods.map(&:to_s).select do |method_name|
42
+ owned_method?(method_name) && target_directory?(method_name)
43
+ end
44
+ end
45
+
46
+ def target_directory?(method_name)
47
+ return true if DeadCodeDetector.config.ignore_paths.nil?
48
+ source_location = klass.instance_method(method_name).source_location&.first
49
+ source_location !~ DeadCodeDetector.config.ignore_paths
50
+ end
51
+
52
+ def owned_method?(method_name)
53
+ original_method = klass.instance_method(method_name)
54
+ klass <= original_method.owner && !(klass.superclass <= original_method.owner)
55
+ end
56
+
57
+ end
58
+ end
@@ -0,0 +1,34 @@
1
+ module DeadCodeDetector
2
+ class Report
3
+
4
+ class << self
5
+
6
+ def unused_methods
7
+ Initializer.cached_classes.flat_map do |class_name|
8
+ unused_methods_for(class_name)
9
+ end
10
+ end
11
+
12
+ def unused_methods_for(class_name)
13
+ methods = []
14
+ unused_class_methods_for(class_name).each_with_object(methods) do |method_name, collection|
15
+ collection << "#{class_name}.#{method_name}"
16
+ end
17
+ unused_instance_methods_for(class_name).each_with_object(methods) do |method_name, collection|
18
+ collection << "#{class_name}##{method_name}"
19
+ end
20
+ methods
21
+ end
22
+
23
+ private
24
+ def unused_class_methods_for(class_name)
25
+ DeadCodeDetector.config.storage.get(DeadCodeDetector::ClassMethodWrapper.record_key(class_name))
26
+ end
27
+
28
+ def unused_instance_methods_for(class_name)
29
+ DeadCodeDetector.config.storage.get(DeadCodeDetector::InstanceMethodWrapper.record_key(class_name))
30
+ end
31
+ end
32
+
33
+ end
34
+ end
@@ -0,0 +1,7 @@
1
+ require "dead_code_detector/storage/memory_backend"
2
+ require "dead_code_detector/storage/redis_backend"
3
+
4
+ module DeadCodeDetector
5
+ class Storage
6
+ end
7
+ end
@@ -0,0 +1,43 @@
1
+ module DeadCodeDetector
2
+ class Storage
3
+
4
+ class MemoryBackend
5
+
6
+ attr_accessor :flush_immediately
7
+ attr_reader :pending_deletions
8
+
9
+ def initialize
10
+ @mapping = Hash.new{|h,k| h[k] = Set.new }
11
+ @pending_deletions = Hash.new{|h,k| h[k] = Set.new }
12
+ end
13
+
14
+ def clear(key)
15
+ @mapping.delete(key)
16
+ end
17
+
18
+ def add(key, values)
19
+ @mapping[key].merge(Array(values))
20
+ end
21
+
22
+ def get(key)
23
+ if @pending_deletions.key?(key)
24
+ @mapping[key] - @pending_deletions[key]
25
+ else
26
+ @mapping[key]
27
+ end
28
+ end
29
+
30
+ def delete(key, value)
31
+ @pending_deletions[key] << value.to_s
32
+ flush if flush_immediately
33
+ end
34
+
35
+ def flush
36
+ @pending_deletions.each do |key, values|
37
+ @mapping[key].subtract(values)
38
+ end
39
+ @pending_deletions.clear
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,46 @@
1
+ module DeadCodeDetector
2
+ class Storage
3
+
4
+ class RedisBackend
5
+
6
+ attr_accessor :flush_immediately
7
+
8
+ def initialize
9
+ @pending_deletions = Hash.new{|h,k| h[k] = Set.new }
10
+ end
11
+
12
+ def clear(key)
13
+ DeadCodeDetector.config.redis.del(key)
14
+ end
15
+
16
+ def add(key, values)
17
+ values = Array(values)
18
+ return if values.empty?
19
+ DeadCodeDetector.config.redis.sadd(key, values)
20
+ DeadCodeDetector.config.redis.expire(key, DeadCodeDetector.config.cache_expiry)
21
+ end
22
+
23
+ def get(key)
24
+ members = DeadCodeDetector.config.redis.smembers(key)
25
+ members = Set.new(members) if members.is_a?(Array)
26
+ if @pending_deletions.key?(key)
27
+ members - @pending_deletions[key]
28
+ else
29
+ members
30
+ end
31
+ end
32
+
33
+ def delete(key, value)
34
+ @pending_deletions[key] << value.to_s
35
+ flush if flush_immediately
36
+ end
37
+
38
+ def flush
39
+ @pending_deletions.each do |key, values|
40
+ DeadCodeDetector.config.redis.srem(key, values.to_a)
41
+ end
42
+ @pending_deletions.clear
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,3 @@
1
+ module DeadCodeDetector
2
+ VERSION = "0.0.8"
3
+ end
metadata ADDED
@@ -0,0 +1,124 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dead_code_detector
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.8
5
+ platform: ruby
6
+ authors:
7
+ - Kyle d'Oliveira
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-04-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.17'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.17'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: byebug
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: This monitors methods being called and can be used to produce a report
70
+ of all methods that have not been called.
71
+ email:
72
+ - kyle.doliveira@clio.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - ".gitignore"
78
+ - ".rspec"
79
+ - CODE_OF_CONDUCT.md
80
+ - Gemfile
81
+ - Gemfile.lock
82
+ - LICENSE.txt
83
+ - README.md
84
+ - Rakefile
85
+ - bin/console
86
+ - bin/setup
87
+ - dead_code_detector.gemspec
88
+ - lib/dead_code_detector.rb
89
+ - lib/dead_code_detector/base_method_wrapper.rb
90
+ - lib/dead_code_detector/class_method_wrapper.rb
91
+ - lib/dead_code_detector/configuration.rb
92
+ - lib/dead_code_detector/initializer.rb
93
+ - lib/dead_code_detector/instance_method_wrapper.rb
94
+ - lib/dead_code_detector/report.rb
95
+ - lib/dead_code_detector/storage.rb
96
+ - lib/dead_code_detector/storage/memory_backend.rb
97
+ - lib/dead_code_detector/storage/redis_backend.rb
98
+ - lib/dead_code_detector/version.rb
99
+ homepage: https://github.com/clio/dead_code_detector
100
+ licenses:
101
+ - MIT
102
+ metadata:
103
+ homepage_uri: https://github.com/clio/dead_code_detector
104
+ source_code_uri: https://github.com/clio/dead_code_detector
105
+ post_install_message:
106
+ rdoc_options: []
107
+ require_paths:
108
+ - lib
109
+ required_ruby_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ required_rubygems_version: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - ">="
117
+ - !ruby/object:Gem::Version
118
+ version: '0'
119
+ requirements: []
120
+ rubygems_version: 3.0.3
121
+ signing_key:
122
+ specification_version: 4
123
+ summary: Help find unused code in production.
124
+ test_files: []