bulletmark_repairer 0.1.0

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: 90214d67d25519f3e4b352583ad3631773d29444e28ce319d62c89d11fa0149e
4
+ data.tar.gz: 59bda8070c7e775774e6d52af33687f3a1da3e26889fe51a2ce71069fb211498
5
+ SHA512:
6
+ metadata.gz: 2ad6acf09c537b4c283a9404c3518d43f176cc0078406b0371d44f1ea86222e041ddb1f19e9607df95948149f899cc5cda3584753899cc4a85f64232389c2beb
7
+ data.tar.gz: a2f5532b82a8f2d9a60d5a72b986d8c81d0d5709905226fb9a5ceac1ddebe1e325039e2870ecc020293b87ed36b10a4aa0ff97a1bd920f09a83e1c2f63268573
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,33 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.2
3
+ NewCops: enable
4
+ SuggestExtensions: false
5
+
6
+ Layout/LineLength:
7
+ Enabled: false
8
+
9
+ Style/StringLiterals:
10
+ Enabled: true
11
+ EnforcedStyle: single_quotes
12
+
13
+ Style/StringLiteralsInInterpolation:
14
+ Enabled: true
15
+ EnforcedStyle: single_quotes
16
+
17
+ Metrics/MethodLength:
18
+ Enabled: false
19
+
20
+ Metrics/AbcSize:
21
+ Enabled: false
22
+
23
+ Metrics/CyclomaticComplexity:
24
+ Enabled: false
25
+
26
+ Metrics/PerceivedComplexity:
27
+ Enabled: false
28
+
29
+ Metrics/BlockLength:
30
+ Enabled: false
31
+
32
+ Style/Documentation:
33
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## [0.1.0] - 2023-10-10
2
+
3
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at unright@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in bulletmark_repairer.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 13.0'
9
+
10
+ gem 'factory_bot_rails'
11
+ gem 'rails'
12
+ gem 'rspec', '~> 3.0'
13
+ gem 'rspec-rails', '~> 3.0'
14
+ gem 'sqlite3'
15
+
16
+ gem 'byebug'
17
+ gem 'rubocop', '~> 1.21'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 makicamel
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,90 @@
1
+ # BulletmarkRepairer
2
+
3
+ BulletmarkRepairer is an auto corrector for N+1 queries detected at runtime on Ruby on Rails application using [Bullet](https://github.com/flyerhzm/bullet) and [Parser](https://github.com/whitequark/parser).
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'bulletmark_repairer', group :development, :test
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Run rails server or rspec with REPAIR=1 to autocorrect when N+1 queries are caused.
16
+
17
+ ```bash
18
+ REPAIR=1 rails server
19
+ REPAIR=1 rspec
20
+ ```
21
+
22
+ ### How BulletmarkRepairer auto corrects
23
+
24
+ After receiving Bullet's N+1 notification, find the code that the instance variable is assigned and add `includes` to it.
25
+ Currently, only the controller directory is a candidate for auto correct.
26
+ (We plan to implement allow list in the future)
27
+ Also when N+1 occurs in the views, correct the controller.
28
+
29
+ ### Disclaimer
30
+
31
+ #### BulletmarkRepairer is *NOT* safe
32
+
33
+ You must check that auto corrects are correct before you commit.
34
+ For example, when the associations to include depends on the request parameters, human intervention is required.
35
+
36
+ ```ruby
37
+ def index
38
+ # Required associations depend on the parameters
39
+ @plays = Play.ransack(params[:q])
40
+ end
41
+ ```
42
+
43
+ #### BulletmarkRepairer is *NOT* complete
44
+
45
+ You can check `log/bulletmark_repairer.log` for files where N+1 is detected but not auto corrected.
46
+ For example, the following cases are not supported as known cases currently:
47
+
48
+ ```ruby
49
+ def index
50
+ # N+1 is caused but not assigned
51
+ Play.all_actors_name
52
+ end
53
+
54
+ def index
55
+ # N+1 occurs when assigning a local variable
56
+ plays = Play.all.as_json
57
+ @play = plays.last
58
+ end
59
+ ```
60
+
61
+ ### Configuration
62
+
63
+ To customize, add `config/initializers/bulletmark_repairer.rb`:
64
+
65
+ ```ruby
66
+ BulletmarkRepairer.configure do |config|
67
+ # when you want to output log to Rails.logger
68
+ config.logger = Rails.logger
69
+ # when BulletmarkRepairer malfunctions, skip the file
70
+ config.skip_file_list = %w[app/controllers/plays_controller.rb]
71
+ # when you want to debug bulletmark_repairer's errors
72
+ config.debug = true
73
+ end
74
+ ```
75
+
76
+ - `logger`: Injectable logger. In default `Logger.new("#{Rails.root}/log/bulletmark_repairer.log")`
77
+ - `skip_file_list`: File list to skip to auto correct. In default `[]`
78
+ - `debug`: To raise BulletmarkRepairer's error or not. In default `false`
79
+
80
+ ## Contributing
81
+
82
+ Bug reports and pull requests are welcome on GitHub at <https://github.com/makicamel/bulletmark_repairer>. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/makicamel/bulletmark_repairer/blob/main/CODE_OF_CONDUCT.md).
83
+
84
+ ## License
85
+
86
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
87
+
88
+ ## Code of Conduct
89
+
90
+ Everyone interacting in the BulletmarkRepairer project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/makicamel/bulletmark_repairer/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'forwardable'
4
+
5
+ module BulletmarkRepairer
6
+ class AssociationsBuilder
7
+ def build(marker)
8
+ return if marker.skip?
9
+
10
+ if associations[marker.index]
11
+ associations[marker.index].add(marker)
12
+ else
13
+ associations[marker.index] = Associations.new(marker)
14
+ end
15
+ end
16
+
17
+ def associations
18
+ @associations ||= {}
19
+ end
20
+ end
21
+
22
+ class Associations
23
+ extend Forwardable
24
+
25
+ def_delegators :@marker, :file_name, :instance_variable_name
26
+
27
+ def add(child_marker)
28
+ build_associations!(marker: child_marker, associations: @marker.associations, parent_keys: [:base])
29
+ end
30
+
31
+ def corrector(dir)
32
+ BulletmarkRepairer::CorrectorBuilder.new(
33
+ dir:,
34
+ marker: @marker,
35
+ associations: @associations
36
+ ).execute
37
+ end
38
+
39
+ private
40
+
41
+ def initialize(marker)
42
+ @marker = marker
43
+ @associations = { base: marker.associations }
44
+ end
45
+
46
+ # @return [Hash, nil]
47
+ def build_associations!(marker:, associations:, parent_keys:)
48
+ key = formed_key(marker:, associations:)
49
+ if key
50
+ modify_value(key:, marker:, parent_keys:)
51
+ else
52
+ new_parent_keys = parent_keys
53
+ new_parent_keys.append(0) if associations.is_a?(Array)
54
+ associations.each do |association_values|
55
+ next unless association_values.is_a?(Hash)
56
+
57
+ association_values.each do |key, value|
58
+ values = value.is_a?(Array) ? value : [value]
59
+ build_associations!(marker:, associations: { key => values }, parent_keys: new_parent_keys)
60
+ end
61
+ end
62
+ end
63
+ end
64
+
65
+ # @return [Symbol, nil]
66
+ def formed_key(marker:, associations:)
67
+ case associations
68
+ when Hash
69
+ BulletmarkRepairer.key(marker.base_class, @marker.base_class, associations.keys) ||
70
+ BulletmarkRepairer.key(marker.base_class, @marker.base_class, associations.values.flatten)
71
+ when Array
72
+ BulletmarkRepairer.key(marker.base_class, @marker.base_class, associations)
73
+ else # Symbol, String
74
+ BulletmarkRepairer.key(marker.base_class, @marker.base_class, [associations])
75
+ end
76
+ end
77
+
78
+ def modify_value(key:, marker:, parent_keys:)
79
+ case @associations.dig(*parent_keys)
80
+ when Hash
81
+ # when key is in value
82
+ if @associations.dig(*parent_keys)[key].nil?
83
+ last_key = @associations.dig(*parent_keys).keys.first
84
+ if @associations.dig(*parent_keys)[last_key].is_a?(Array)
85
+ @associations.dig(*parent_keys)[last_key].delete(key)
86
+ @associations.dig(*parent_keys)[last_key].append(key => marker.associations)
87
+ else
88
+ @associations.dig(*parent_keys)[last_key] = { key => marker.associations }
89
+ end
90
+ # when key is in key
91
+ else
92
+ value = if @associations.dig(*parent_keys)[key].is_a?(Array)
93
+ @associations.dig(*parent_keys)[key] + marker.associations
94
+ else
95
+ [@associations.dig(*parent_keys)[key], *marker.associations]
96
+ end
97
+ @associations.dig(*parent_keys)[key] = value
98
+ end
99
+ when Array
100
+ @associations.dig(*parent_keys).delete(key)
101
+ @associations.dig(*parent_keys).append(key => marker.associations)
102
+ else # Symbol, String
103
+ last_key = parent_keys.slice!(-1)
104
+ @associations.dig(*parent_keys)[last_key] = { key => marker.associations }
105
+ end
106
+ end
107
+ end
108
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BulletmarkRepairer
4
+ def self.associations
5
+ @associations ||= ApplicationAssociations.new
6
+ end
7
+
8
+ def self.key(target_klass_name, base_klass_name, candidates)
9
+ associations.key(target_klass_name, base_klass_name, candidates)
10
+ end
11
+
12
+ def self.reset_associations
13
+ @associations = nil
14
+ end
15
+
16
+ class ApplicationAssociations
17
+ def key(target_klass_name, base_klass_name, candidates)
18
+ key = target_klass_name.underscore
19
+ matched_candidates = candidates - (candidates - @associations[base_klass_name][:associations])
20
+ if key.pluralize.to_sym.in?(candidates)
21
+ key.pluralize.to_sym
22
+ elsif key.singularize.to_sym.in?(candidates)
23
+ key.singularize.to_sym
24
+ else
25
+ index = matched_candidates.index do |matched_candidate|
26
+ key.pluralize.to_sym.in?(@associations[base_klass_name][:aliases][matched_candidate]) ||
27
+ key.singularize.to_sym.in?(@associations[base_klass_name][:aliases][matched_candidate])
28
+ end
29
+ matched_candidates[index] if index
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ def initialize
36
+ blank_array_hash = Hash.new { |hash, key| hash[key] = [] }
37
+ @associations = Hash.new { |hash, key| hash[key] = { associations: [], aliases: blank_array_hash } }
38
+ ::ActiveRecord::Base
39
+ .descendants
40
+ .select { |klass| klass.respond_to?(:reflect_on_all_associations) }
41
+ .each do |klass|
42
+ klass.reflect_on_all_associations.each do |association_instance|
43
+ association = association_instance.respond_to?(:delegate_reflection) ? association_instance.delegate_reflection : association_instance
44
+ klass_name = association.active_record.name
45
+ association_name = association.name
46
+ @associations[klass_name][:associations] |= [association_name]
47
+ next unless association.options[:source]
48
+
49
+ alias_name = association.instance_of?(::ActiveRecord::Reflection::HasManyReflection) ? association.options[:source].to_s.pluralize.to_sym : association.options[:source]
50
+ @associations[klass_name][:aliases][association.name] |= [alias_name]
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BulletmarkRepairer
4
+ class Configration
5
+ attr_accessor :skip_file_list, :logger
6
+ attr_writer :debug
7
+
8
+ def initialize
9
+ @debug = false
10
+ @skip_file_list = []
11
+ @logger = Logger.new("#{Rails.root}/log/bulletmark_repairer.log")
12
+ end
13
+
14
+ def debug?
15
+ @debug
16
+ end
17
+ end
18
+
19
+ class << self
20
+ def configure
21
+ yield config
22
+ end
23
+
24
+ def config
25
+ @config ||= Configration.new
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ class ControllerCorrector < Parser::TreeRewriter
4
+ def on_class(node)
5
+ node
6
+ .children
7
+ .each do |child_node|
8
+ type, identifier = child_node.to_sexp_array.take(2)
9
+ case type
10
+ when :def
11
+ target_nodes[identifier] = child_node
12
+ when :begin
13
+ child_node.children.each do |grand_child_node|
14
+ type, identifier, callback_type, (_, callback_identifier) = grand_child_node.to_sexp_array
15
+ if type == :def
16
+ target_nodes[identifier] = grand_child_node
17
+ elsif callback_type.in? %i[before_action after_action around_action]
18
+ callbacks.append callback_identifier
19
+ end
20
+ end
21
+ end
22
+ end
23
+ action_node = target_nodes.delete(action)
24
+ insert_includes(node: action_node)
25
+ return if patched?
26
+
27
+ callbacks.each { |callback_identifier| insert_includes(node: target_nodes[callback_identifier]) }
28
+ end
29
+
30
+ private
31
+
32
+ def patched?
33
+ @patched ||= false
34
+ end
35
+
36
+ def target_nodes
37
+ @target_nodes ||= {}
38
+ end
39
+
40
+ def callbacks
41
+ @callbacks ||= []
42
+ end
43
+
44
+ def insert_includes(node:)
45
+ return if patched?
46
+ return unless node.respond_to?(:to_sexp_array)
47
+
48
+ type, identifier = node.to_sexp_array.take(2)
49
+
50
+ if type == :ivasgn && identifier == instance_variable_name
51
+ insert_after node.children.last.location.expression, ".includes(#{associations})"
52
+ @patched = true
53
+ else
54
+ node
55
+ .children
56
+ .reverse
57
+ .each do |child_node|
58
+ child_type, _, child_identifier = child_node.try(:to_sexp_array)
59
+ if child_type == :send && target_nodes.key?(child_identifier)
60
+ target_node = target_nodes.delete(child_node.to_sexp_array.last)
61
+ insert_includes(node: target_node)
62
+ else
63
+ insert_includes(node: child_node)
64
+ end
65
+ end
66
+ end
67
+ end
68
+
69
+ def action
70
+ :__EMBEDDED_ACTION__
71
+ end
72
+
73
+ def instance_variable_name
74
+ :__EMBEDDED_INSTANCE_VARIABLE_NAME__
75
+ end
76
+
77
+ def associations
78
+ '__EMBEDDED_ASSOCIATIONS__'
79
+ end
80
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Corrector < Parser::TreeRewriter
4
+ def on_def(node)
5
+ return if patched?
6
+
7
+ node.children.each { |child_node| insert_includes(node: child_node) }
8
+ return if patched?
9
+
10
+ node.children.each { |child_node| insert_includes_for_vasgn(node: child_node, type: :ivasgn) }
11
+ return if patched?
12
+
13
+ node.children.each { |child_node| insert_includes_for_vasgn(node: child_node, type: :lvasgn) }
14
+ end
15
+
16
+ private
17
+
18
+ def patched?
19
+ @patched ||= false
20
+ end
21
+
22
+ def insert_includes(node:)
23
+ return if patched?
24
+ return if !node.respond_to?(:children) || node.children.empty?
25
+ return unless node.location.expression.line <= line_no && line_no <= node.location.expression.last_line
26
+
27
+ # TODO: Patch Enumerable methods other than each and map
28
+ if node.children.last.in?(%i[each map])
29
+ insert_after node.children[0].location.expression, ".includes(#{associations})"
30
+ @patched = true
31
+ else
32
+ node.children.each { |child_node| insert_includes(node: child_node) }
33
+ end
34
+ end
35
+
36
+ def insert_includes_for_vasgn(node:, type:)
37
+ return if patched?
38
+ return if !node.respond_to?(:children) || node.children.empty?
39
+ return unless node.location.expression.line <= line_no && line_no <= node.location.expression.last_line
40
+
41
+ if node.type == type
42
+ insert_after node.children.last.location.expression, ".includes(#{associations})"
43
+ @patched = true
44
+ else
45
+ node.children.each { |child_node| insert_includes_for_vasgn(node: child_node, type:) }
46
+ end
47
+ end
48
+
49
+ def line_no
50
+ __EMBEDDED_LINE_NO__
51
+ end
52
+
53
+ def associations
54
+ '__EMBEDDED_ASSOCIATIONS__'
55
+ end
56
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BulletmarkRepairer
4
+ class CorrectorBuilder
5
+ ASSOCIATIONS = '__EMBEDDED_ASSOCIATIONS__'
6
+ LINE_NO = '__EMBEDDED_LINE_NO__'
7
+ ACTION = '__EMBEDDED_ACTION__'
8
+ INSTANCE_VARIABLE_NAME = '__EMBEDDED_INSTANCE_VARIABLE_NAME__'
9
+
10
+ def initialize(dir:, marker:, associations:)
11
+ @dir = dir
12
+ @marker = marker
13
+ @associations = associations
14
+ @action = marker.action
15
+ @instance_variable_name = marker.instance_variable_name
16
+ end
17
+
18
+ def execute
19
+ corrector_name = '/controller_corrector.rb'
20
+ File.open("#{@dir}#{corrector_name}", 'w') do |f|
21
+ corrector = Pathname.new(__FILE__).sub('/corrector_builder.rb', corrector_name)
22
+ src = File.read(corrector)
23
+ src
24
+ .sub!(ASSOCIATIONS, @associations[:base].to_s)
25
+ .sub!(ACTION, @action)
26
+ .sub!(INSTANCE_VARIABLE_NAME, @instance_variable_name)
27
+ f.puts src
28
+ f
29
+ end.path
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'forwardable'
4
+
5
+ module BulletmarkRepairer
6
+ class Markers
7
+ extend Forwardable
8
+
9
+ def_delegator :@markers, :each
10
+
11
+ def initialize(notifications, controller:, action:)
12
+ @markers = {}
13
+ notifications.collection.to_a.each do |notification|
14
+ next unless notification.is_a?(::Bullet::Notification::NPlusOneQuery)
15
+
16
+ base_class = notification.instance_variable_get(:@base_class)
17
+ if @markers[base_class]
18
+ @markers[base_class].add_association(notification)
19
+ else
20
+ @markers[base_class] = Marker.new(
21
+ notification,
22
+ controller:,
23
+ action:
24
+ )
25
+ end
26
+ end
27
+ end
28
+ end
29
+
30
+ class Marker
31
+ attr_reader :base_class, :associations, :action, :file_name, :instance_variable_name, :index
32
+
33
+ def initialize(notification, controller:, action:)
34
+ @base_class = notification.instance_variable_get(:@base_class)
35
+ @stacktraces = notification.instance_variable_get(:@callers)
36
+ @associations = notification.instance_variable_get(:@associations)
37
+ @controller = controller
38
+ @action = action
39
+ set_up
40
+ end
41
+
42
+ def add_association(notification)
43
+ @associations += notification.instance_variable_get(:@associations)
44
+ end
45
+
46
+ def skip?
47
+ log_patchable_files_not_be_found
48
+ index.nil? || file_name.remove("#{Rails.root}/").in?(BulletmarkRepairer.config.skip_file_list)
49
+ end
50
+
51
+ def n_plus_one_in_view?
52
+ @n_plus_one_in_view
53
+ end
54
+
55
+ private
56
+
57
+ def log_patchable_files_not_be_found
58
+ return if index
59
+
60
+ BulletmarkRepairer.config.logger.info <<~LOG
61
+ Repairer couldn't patch
62
+ #{"#{@controller}_controller".camelize.constantize}##{@action}
63
+ #{base_class} => #{associations}
64
+ Might be able to add one of the following
65
+ includes(#{associations}) / includes(#{base_class.underscore}: #{associations}) / includes(#{base_class.underscore.pluralize}: #{associations})
66
+ Stacktraces
67
+ #{@stacktraces.join("\n ")}
68
+ LOG
69
+ end
70
+
71
+ def set_up
72
+ @n_plus_one_in_view = @stacktraces.any? { |stacktrace| stacktrace.match?(%r{\A#{Rails.root}/app/views/[./\w]+:\d+:in `[\w]+'\z}) }
73
+
74
+ if n_plus_one_in_view?
75
+ # TODO: Check the action is in the base controller file
76
+ @file_name = "#{Rails.root}/app/controllers/#{@controller}_controller.rb"
77
+ view_file_index = @stacktraces.index do |stacktrace|
78
+ stacktrace =~ %r{\A(#{Rails.root}/app/views/[./\w]+):\d+:in `[\w]+'\z} && !Pathname.new(Regexp.last_match(1)).basename.to_s.start_with?('_')
79
+ end
80
+ view_file, view_yield_index = @stacktraces[view_file_index].scan(%r{\A(/[./\w]+):(\d+):in `[\w]+'\z}).flatten
81
+ view_yield_index = view_yield_index.to_i
82
+ # TODO: Compile views
83
+ File.open(view_file) do |f|
84
+ lines = f.readlines
85
+ loop do
86
+ break if @instance_variable_name || view_yield_index.zero?
87
+
88
+ view_yield_index -= 1
89
+ line = lines[view_yield_index]
90
+ @instance_variable_name = line&.scan(/\b?(@[\w]+)\b?/)&.flatten&.last
91
+ end
92
+ end
93
+ @index = @instance_variable_name ? "#{view_file}:#{view_yield_index}" : nil
94
+ else
95
+ # TODO: Ignore controllers list
96
+ # TODO: Allow directories list
97
+ controller_file_index = @stacktraces.index { |stacktrace| stacktrace.match?(%r{\A(#{Rails.root}/app/controllers[./\w]+):(\d+):in `[()\w\s]+'\z}) }
98
+ @file_name, controller_yield_index = @stacktraces[controller_file_index].scan(%r{\A(#{Rails.root}/app/controllers[./\w]+):(\d+):in `[()\w\s]+'\z}).flatten
99
+ controller_yield_index = controller_yield_index.to_i
100
+ File.open(@file_name) do |f|
101
+ lines = f.readlines
102
+ loop do
103
+ break if @instance_variable_name || controller_yield_index.zero?
104
+
105
+ controller_yield_index -= 1
106
+ line = lines[controller_yield_index]
107
+ # TODO: patch to local variables
108
+ @instance_variable_name = line&.scan(/\b?(@[\w]+)\b?/)&.flatten&.last
109
+ break if line.match?(/^\s+def [()\w\s=]+$/)
110
+ end
111
+ end
112
+ @index = @instance_variable_name ? "#{@file_name}:#{controller_yield_index}" : nil
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'securerandom'
5
+ require 'parser/runner/ruby_rewrite'
6
+
7
+ module BulletmarkRepairer
8
+ class Pathcer
9
+ def self.execute(notifications:, controller:, action:)
10
+ new(notifications:, controller:, action:).execute
11
+ end
12
+
13
+ def execute
14
+ @markers.each do |_base_class, marker|
15
+ @associations_builder.build(marker)
16
+ end
17
+ @associations_builder.associations.each do |_index, associations|
18
+ path = "#{Rails.root}/tmp/#{SecureRandom.hex(10)}"
19
+ FileUtils.mkdir(path)
20
+ Parser::Runner::RubyRewrite.go(%W[-l #{associations.corrector(path)} -m #{associations.file_name}])
21
+ FileUtils.rm_r(path)
22
+ end
23
+ end
24
+
25
+ private
26
+
27
+ def initialize(notifications:, controller:, action:)
28
+ @markers = Markers.new(notifications, controller:, action:)
29
+ @associations_builder = BulletmarkRepairer::AssociationsBuilder.new
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BulletmarkRepairer
4
+ class Rack
5
+ def initialize(app)
6
+ @app = app
7
+ end
8
+
9
+ def call(env)
10
+ BulletmarkRepairer.reset_associations
11
+ @app.call(env)
12
+ ensure
13
+ begin
14
+ if Thread.current[:bullet_notification_collector].notifications_present?
15
+ BulletmarkRepairer::Pathcer.execute(
16
+ notifications: Thread.current[:bullet_notification_collector],
17
+ controller: env['action_dispatch.request.parameters']['controller'],
18
+ action: env['action_dispatch.request.parameters']['action']
19
+ )
20
+ end
21
+ rescue StandardError => e
22
+ raise e if BulletmarkRepairer.config.debug?
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails'
4
+
5
+ module BulletmarkRepairer
6
+ class Railtie < ::Rails::Railtie
7
+ initializer 'bulletmark_repairer' do |app|
8
+ require 'bullet'
9
+ require 'bulletmark_repairer/rack'
10
+ app.middleware.insert_after Bullet::Rack, BulletmarkRepairer::Rack
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BulletmarkRepairer
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bulletmark_repairer/version'
4
+ require 'bulletmark_repairer/railtie' if ENV['REPAIR']
5
+ require 'bulletmark_repairer/bulletmark_repairer'
6
+ require 'bulletmark_repairer/associations_builder'
7
+ require 'bulletmark_repairer/configuration'
8
+ require 'bulletmark_repairer/corrector_builder'
9
+ require 'bulletmark_repairer/markers'
10
+ require 'bulletmark_repairer/patcher'
11
+
12
+ module BulletmarkRepairer
13
+ class Error < StandardError; end
14
+ end
@@ -0,0 +1,4 @@
1
+ module BulletmarkRepairer
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,110 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bulletmark_repairer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - makicamel
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-10-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bullet
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: parser
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rails
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Auto corrector for N+1 queries detected at runtime with Bullet.
56
+ email:
57
+ - unright@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - CHANGELOG.md
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - lib/bulletmark_repairer.rb
71
+ - lib/bulletmark_repairer/associations_builder.rb
72
+ - lib/bulletmark_repairer/bulletmark_repairer.rb
73
+ - lib/bulletmark_repairer/configuration.rb
74
+ - lib/bulletmark_repairer/controller_corrector.rb
75
+ - lib/bulletmark_repairer/corrector.rb
76
+ - lib/bulletmark_repairer/corrector_builder.rb
77
+ - lib/bulletmark_repairer/markers.rb
78
+ - lib/bulletmark_repairer/patcher.rb
79
+ - lib/bulletmark_repairer/rack.rb
80
+ - lib/bulletmark_repairer/railtie.rb
81
+ - lib/bulletmark_repairer/version.rb
82
+ - sig/bulletmark_repairer.rbs
83
+ homepage: https://github.com/makicamel/bulletmark_repairer
84
+ licenses:
85
+ - MIT
86
+ metadata:
87
+ homepage_uri: https://github.com/makicamel/bulletmark_repairer
88
+ source_code_uri: https://github.com/makicamel/bulletmark_repairer
89
+ changelog_uri: https://github.com/makicamel/bulletmark_repairer/blob/main/CHANGELOG.md
90
+ rubygems_mfa_required: 'true'
91
+ post_install_message:
92
+ rdoc_options: []
93
+ require_paths:
94
+ - lib
95
+ required_ruby_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: 2.6.0
100
+ required_rubygems_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ requirements: []
106
+ rubygems_version: 3.4.10
107
+ signing_key:
108
+ specification_version: 4
109
+ summary: Auto corrector for N+1 queries detected at runtime with Bullet
110
+ test_files: []