momocop 0.1.3

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: 9d823774129843455f368f3dc22991236d0526448998c352736a92db7b4ffe91
4
+ data.tar.gz: c9c43808e8ff31c78c4efdc42bf3ef1a6553467568df304be5cfc800561a985b
5
+ SHA512:
6
+ metadata.gz: dcb5eb8dd8d815f98dcc3acdd726f3256e17689f52a039da8f51e4e77c3a5ebfdc65ee72127a808a9bec11278ce6c7ddaad5fb1ef0df98ce31a60ddf95645a5a
7
+ data.tar.gz: 7d43fd5166f63ccabeb485d89d0dffe635563001d4353f6b5ee820e3690ff7a0d70ab1d906d380cb78c17b00a43d4fb3a513bfde34ebee3b57ae761f22560b4b
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,61 @@
1
+ require:
2
+ - rubocop/cop/internal_affairs
3
+ - rubocop-rake
4
+ - rubocop-rspec
5
+ - ./lib/momocop
6
+
7
+ inherit_from: .rubocop_todo.yml
8
+
9
+ inherit_mode:
10
+ merge:
11
+ - Exclude
12
+
13
+ AllCops:
14
+ TargetRubyVersion: 3.1.1
15
+ DisabledByDefault: true
16
+ Exclude:
17
+ - 'bin/**/*'
18
+ NewCops: enable
19
+
20
+ Gemspec/RequireMFA:
21
+ Enabled: false
22
+
23
+ Bundler:
24
+ Enabled: true
25
+
26
+ Gemspec:
27
+ Enabled: true
28
+
29
+ Layout/LineLength:
30
+ Max: 120
31
+
32
+ Layout:
33
+ Enabled: true
34
+
35
+ Lint:
36
+ Enabled: true
37
+
38
+ Security:
39
+ Enabled: true
40
+
41
+ Style:
42
+ Enabled: true
43
+
44
+ Style/Documentation:
45
+ Enabled: false
46
+
47
+ Style/FrozenStringLiteralComment:
48
+ Enabled: true
49
+ EnforcedStyle: always_true
50
+ SafeAutoCorrect: true
51
+
52
+ Style/RequireOrder:
53
+ Enabled: true
54
+ SafeAutoCorrect: true
55
+
56
+ Style/AccessModifierDeclarations:
57
+ Enabled: true
58
+ EnforcedStyle: inline
59
+
60
+ Style/RedundantReturn:
61
+ Enabled: false
data/.rubocop_todo.yml ADDED
File without changes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-02-11
4
+
5
+ - 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 hi@supermomonga.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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 supermomonga
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,50 @@
1
+ # momocop
2
+
3
+ [![Spec](https://github.com/supermomonga/momocop/actions/workflows/spec.yml/badge.svg)](https://github.com/supermomonga/momocop/actions/workflows/spec.yml) [![Gem Version](https://badge.fury.io/rb/momocop.svg)](https://badge.fury.io/rb/momocop)
4
+
5
+ Momocop is highly opinionated custom cops for [RuboCop](https://github.com/rubocop/rubocop).
6
+
7
+ ## Installation
8
+
9
+ Add `momocop` to your Gemfile.
10
+
11
+ ```rb
12
+ # Gemfile
13
+ gem 'momocop', require: false
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ Edit `.rubocop.yml` to require `momocop` and enable the cops you want.
19
+
20
+ All cops are disabled by default.
21
+
22
+ ```yaml
23
+ # .rubocop.yaml
24
+ require:
25
+ - momocop
26
+
27
+ Momocop/FactoryBotRailsFactoryAssociationsCoverage:
28
+ Enabled: true
29
+ ```
30
+
31
+ ## Cops
32
+
33
+ |Cop|Rails|FactoryBot|
34
+ |---|:-:|:-:|
35
+ |[`Momocop/FactoryBotRailsClassName`](lib/rubocop/cop/momocop/factory_bot_rails_class_name.rb)|:white_check_mark:|:white_check_mark:|
36
+ |[`Momocop/FactoryBotRailsClassOptionSpecified`](lib/rubocop/cop/momocop/factory_bot_rails_class_option_specified.rb)|:white_check_mark:|:white_check_mark:|
37
+ |[`Momocop/FactoryBotRailsFactoryAssociationsCoverage`](lib/rubocop/cop/momocop/factory_bot_rails_factory_associations_coverage.rb)|:white_check_mark:|:white_check_mark:|
38
+ |[`Momocop/FactoryBotRailsFactoryPropertiesCoverage`](lib/rubocop/cop/momocop/factory_bot_rails_factory_properties_coverage.rb)|:white_check_mark:|:white_check_mark:|
39
+
40
+ ## Contributing
41
+
42
+ Bug reports and pull requests are welcome on GitHub at https://github.com/supermomonga/momocop. 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/supermomonga/momocop/blob/main/CODE_OF_CONDUCT.md).
43
+
44
+ ## License
45
+
46
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
47
+
48
+ ## Code of Conduct
49
+
50
+ Everyone interacting in the Momocop project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/supermomonga/momocop/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]
File without changes
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'parser/current'
4
+
5
+ module Momocop
6
+ class AssociationExtractor
7
+ ASSOCIATION_METHODS = %i[has_many belongs_to has_one].freeze
8
+
9
+ def extract(source)
10
+ source_string = source.is_a?(StringIO) ? source.string : source
11
+ parse_content(source_string)
12
+ end
13
+
14
+ private def parse_content(source)
15
+ buffer = Parser::Source::Buffer.new('(string)')
16
+ buffer.source = source
17
+
18
+ parser = Parser::CurrentRuby.new
19
+ ast = parser.parse(buffer)
20
+
21
+ extract_associations(ast).sort_by { |association| [association[:type], association[:name]] }
22
+ end
23
+
24
+ private def extract_associations(node, associations = [])
25
+ if node.type == :send && ASSOCIATION_METHODS.include?(node.children[1])
26
+ association_name = node.children[2].type == :sym ? node.children[2].children[0] : node.children[2]
27
+ associations << { type: node.children[1], name: association_name }
28
+ elsif node.children.is_a? Array
29
+ node.children.each do |child|
30
+ extract_associations(child, associations) if child.is_a? Parser::AST::Node
31
+ end
32
+ end
33
+ associations
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Momocop
4
+ # Because RuboCop doesn't yet support plugins, we have to monkey patch in a
5
+ # bit of our configuration.
6
+ module ConfigInjector
7
+ def self.inject_default_config!
8
+ path = File.expand_path(
9
+ '../../config/default.yml',
10
+ __dir__
11
+ )
12
+ hash = RuboCop::ConfigLoader.send(:load_yaml_configuration, path)
13
+ config = RuboCop::Config.new(hash, path).tap(&:make_excludes_absolute)
14
+ puts "configuration from #{path}" if RuboCop::ConfigLoader.debug?
15
+ config = RuboCop::ConfigLoader.merge_with_default(config, path, unset_nil: false)
16
+ RuboCop::ConfigLoader.instance_variable_set(:@default_configuration, config)
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'parser/current'
4
+
5
+ module Momocop
6
+ class EnumExtractor
7
+ def extract(source)
8
+ source_string = source.is_a?(StringIO) ? source.string : source
9
+ parse_content(source_string)
10
+ end
11
+
12
+ private def parse_content(source)
13
+ buffer = Parser::Source::Buffer.new('(string)')
14
+ buffer.source = source
15
+
16
+ parser = Parser::CurrentRuby.new
17
+ ast = parser.parse(buffer)
18
+
19
+ extract_enums(ast).sort
20
+ end
21
+
22
+ private def extract_enums(node, enums = [])
23
+ if node.type == :send && node.children[1] == :enum
24
+ enum_name = node.children[2].type == :sym ? node.children[2].children[0] : node.children[2]
25
+ enums << enum_name.to_sym
26
+ elsif node.children.is_a? Array
27
+ node.children.each do |child|
28
+ extract_enums(child, enums) if child.is_a? Parser::AST::Node
29
+ end
30
+ end
31
+ enums
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Momocop
4
+ VERSION = '0.1.3'
5
+ end
data/lib/momocop.rb ADDED
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'parser/current'
4
+ require 'rubocop'
5
+
6
+ # rubocop-rails
7
+ require 'rubocop/cop/mixin/active_record_helper'
8
+ require 'rubocop/rails/schema_loader'
9
+ require 'rubocop/rails/schema_loader/schema'
10
+
11
+ # Momocop
12
+ require_relative 'momocop/association_extractor'
13
+ require_relative 'momocop/config_injector'
14
+ require_relative 'momocop/enum_extractor'
15
+ require_relative 'momocop/version'
16
+
17
+ Momocop::ConfigInjector.inject_default_config!
18
+
19
+ Dir[File.join(__dir__, 'rubocop/cop/momocop', '*.rb')].each do |file|
20
+ require file
21
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Momocop
6
+ # Ensures that FactoryBot factories use `ClassName.name` for the class option instead of symbol or string literals.
7
+ #
8
+ # @example
9
+ # # bad
10
+ # factory :user, class: :User do
11
+ # end
12
+ #
13
+ # factory :admin, class: 'Admin' do
14
+ # end
15
+ #
16
+ # factory :moderator, class: Moderator.to_s do
17
+ # end
18
+ #
19
+ # # good
20
+ # factory :user, class: User.name do
21
+ # end
22
+ #
23
+ # factory :admin, class: Admin.name do
24
+ # end
25
+ #
26
+ # factory :moderator, class: Moderator.name do
27
+ # end
28
+ class FactoryBotRailsClassName < RuboCop::Cop::Base
29
+ extend AutoCorrector
30
+
31
+ MSG = 'Use `ClassName.name` for the class option instead of a symbol, string literal, or `ClassName.to_s`.'
32
+
33
+ def_node_matcher :factory_class_option_symbol?, <<~PATTERN
34
+ (send nil? :factory _ (hash <(pair (sym :class) $(sym _)) ...>))
35
+ PATTERN
36
+
37
+ def_node_matcher :factory_class_option_string?, <<~PATTERN
38
+ (send nil? :factory _ (hash <(pair (sym :class) $(str _)) ...>))
39
+ PATTERN
40
+
41
+ def_node_matcher :factory_class_option_to_s?, <<~PATTERN
42
+ (send nil? :factory _ (hash <(pair (sym :class) $(send _ :to_s)) ...>))
43
+ PATTERN
44
+
45
+ def on_send(node)
46
+ factory_class_option_symbol?(node) do |class_option|
47
+ add_offense(class_option) do |corrector|
48
+ corrector.replace(class_option, "#{class_option.value.capitalize}.name")
49
+ end
50
+ end
51
+
52
+ factory_class_option_string?(node) do |class_option|
53
+ class_name = class_option.value.delete_prefix("'").delete_suffix("'").capitalize
54
+ add_offense(class_option) do |corrector|
55
+ corrector.replace(class_option, "#{class_name}.name")
56
+ end
57
+ end
58
+
59
+ factory_class_option_to_s?(node) do |class_option|
60
+ class_name = class_option.receiver.const_name
61
+ add_offense(class_option) do |corrector|
62
+ corrector.replace(class_option, "#{class_name}.name")
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Momocop
6
+ # Ensures that FactoryBot factories explicitly specify a class.
7
+ #
8
+ # @example
9
+ # # bad
10
+ # factory :user do
11
+ # end
12
+ #
13
+ # # good
14
+ # factory :user, class: 'User' do
15
+ # end
16
+ class FactoryBotRailsClassOptionSpecified < RuboCop::Cop::Base
17
+ extend AutoCorrector
18
+
19
+ MSG = 'Specify a class option explicitly in FactoryBot factory.'
20
+
21
+ def_node_matcher :factory_call?, <<~PATTERN
22
+ (send nil? :factory ...)
23
+ PATTERN
24
+
25
+ def on_send(node)
26
+ return unless factory_call?(node)
27
+
28
+ # `factory`メソッドの呼び出しで、ハッシュ引数に`:class`キーが含まれているかを調べる
29
+ class_option_specified = node.arguments.any? do |arg|
30
+ arg.hash_type? && arg.pairs.any? { |pair| pair.key.sym_type? && pair.key.children.first == :class }
31
+ end
32
+ return if class_option_specified
33
+
34
+ add_offense(node.loc.selector) do |corrector|
35
+ # Assuming the factory name matches the class name.
36
+ # You may need a more sophisticated approach for different naming conventions.
37
+ require 'active_support/core_ext/string/inflections'
38
+ class_name = node.first_argument.value.to_s.camelize
39
+ corrector.insert_after(node.first_argument.loc.expression, ", class: '#{class_name}'")
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/inflector'
4
+
5
+ module RuboCop
6
+ module Cop
7
+ module Momocop
8
+ # Ensures that all properties of a Rails model class are defined in a FactoryBot factory,
9
+ # auto-corrects by adding missing properties with sensible defaults based on their types.
10
+ #
11
+ # @example
12
+ # # Assuming User model has one Account
13
+ #
14
+ # # bad
15
+ # FactoryBot.define do
16
+ # factory :user, class: 'User' do
17
+ # end
18
+ # end
19
+ #
20
+ # # good
21
+ # FactoryBot.define do
22
+ # factory :user, class: 'User' do
23
+ # association(:account)
24
+ # end
25
+ # end
26
+ class FactoryBotRailsFactoryAssociationsCoverage < RuboCop::Cop::Base
27
+ include RuboCop::Cop::ActiveRecordHelper
28
+ extend AutoCorrector
29
+
30
+ MSG = 'Ensure all associations of the model class are defined in the factory.'
31
+
32
+ def_node_search :association_definitions, <<~PATTERN
33
+ (send nil? :association ...)
34
+ PATTERN
35
+
36
+ def on_send(node)
37
+ return unless factory_bot_define_block_with_class_option?(node)
38
+
39
+ class_name = get_class_name(node)
40
+ return unless class_name
41
+
42
+ block_node = node.block_node
43
+
44
+ # Check missing associations
45
+ defined_associations = get_defined_association_names(block_node)
46
+ model_associations = get_model_association_names(class_name)
47
+ missing_associations = (model_associations - defined_associations).sort
48
+
49
+ # Add offense for missing associations
50
+ return unless missing_associations.any?
51
+
52
+ add_offense(node, message: MSG) do |corrector|
53
+ next unless block_node
54
+
55
+ # Add newline before closing block if it's a one-liner
56
+ if one_line_block?(block_node)
57
+ indentation = ' ' * node.loc.column
58
+ corrector.insert_before(block_node.loc.end, "\n#{indentation}")
59
+ end
60
+
61
+ missing_associations.each do |property|
62
+ definition = generate_association_definition(property)
63
+ break unless definition
64
+
65
+ # TODO: calculate indentation size
66
+ indentation = ' ' * (node.loc.column + 2)
67
+ corrector.insert_after(block_node.loc.begin, "\n#{indentation}#{definition}")
68
+ end
69
+ end
70
+ end
71
+
72
+ private def model_file_path(class_name)
73
+ "app/models/#{class_name.underscore}.rb"
74
+ end
75
+
76
+ private def one_line_block?(block_node)
77
+ block_node.loc.begin.line == block_node.loc.end.line
78
+ end
79
+
80
+ private def model_file_source(class_name)
81
+ path = model_file_path(class_name)
82
+ return File.read(path) if File.exist?(path)
83
+ end
84
+
85
+ private def get_model_association_names(class_name)
86
+ source = model_file_source(class_name)
87
+ return [] unless source
88
+
89
+ extractor = ::Momocop::AssociationExtractor.new
90
+ associations = extractor.extract(source)
91
+ return associations.map { _1[:name].to_s }
92
+ end
93
+
94
+ private def get_defined_association_names(block_node)
95
+ body_node = block_node&.children&.last
96
+ return [] unless body_node
97
+
98
+ associations = association_definitions(body_node)
99
+ association_names = associations&.map(&:first_argument)&.map(&:value)&.map(&:to_s)
100
+ return association_names
101
+ end
102
+
103
+ private def generate_association_definition(property)
104
+ "association(:#{property})"
105
+ end
106
+
107
+ private def factory_bot_define_block_with_class_option?(node)
108
+ factory_method_call?(node) && inside_factory_bot_define?(node)
109
+ end
110
+
111
+ private def factory_method_call?(node)
112
+ node.method_name == :factory
113
+ end
114
+
115
+ private def inside_factory_bot_define?(node)
116
+ ancestors = node.each_ancestor(:block).to_a
117
+ ancestors.any? { |ancestor| ancestor.method_name == :define && ancestor.receiver&.const_name == 'FactoryBot' }
118
+ end
119
+
120
+ private def get_class_name(node)
121
+ options_hash = node.arguments[1]
122
+ return nil unless options_hash&.type == :hash
123
+
124
+ class_option = options_hash.pairs.find { |pair| pair.key.value == :class }
125
+ return nil unless class_option
126
+
127
+ value = class_option.value
128
+ return nil unless value.str_type? || value.sym_type?
129
+
130
+ return value.value.to_s
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,204 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RuboCop
4
+ module Cop
5
+ module Momocop
6
+ # Ensures that all properties of a Rails model class are defined in a FactoryBot factory,
7
+ # auto-corrects by adding missing properties with sensible defaults based on their types.
8
+ #
9
+ # @example
10
+ # # bad
11
+ # FactoryBot.define do
12
+ # factory :user, class: 'User' do
13
+ # name { 'John Doe' }
14
+ # end
15
+ # end
16
+ #
17
+ # # Assuming User model has :name, :email (string), :age (integer),
18
+ # # :role (enum), and :account (association)
19
+ #
20
+ # # good
21
+ # FactoryBot.define do
22
+ # factory :user, class: 'User' do
23
+ # sequence(:age) { _1 } }
24
+ # sequence(:email) { "user#{_1}@example.com" }
25
+ # role { User.roles.keys.sample }
26
+ # name { 'John Doe' }
27
+ # end
28
+ # end
29
+ class FactoryBotRailsFactoryPropertiesCoverage < RuboCop::Cop::Base
30
+ include RuboCop::Cop::ActiveRecordHelper
31
+ extend AutoCorrector
32
+
33
+ MSG = 'Ensure all properties of the model class are defined in the factory.'
34
+
35
+ def_node_search :sequence_definitions, <<~PATTERN
36
+ (send nil? :sequence ...)
37
+ PATTERN
38
+
39
+ def_node_search :property_definitions, <<~PATTERN
40
+ (send nil? $_)
41
+ PATTERN
42
+
43
+ def on_send(node)
44
+ return unless factory_bot_define_block_with_class_option?(node)
45
+
46
+ class_name = get_class_name(node)
47
+ return unless class_name
48
+
49
+ block_node = node.block_node
50
+
51
+ # Check missing associations
52
+ defined_sequences = get_defined_sequence_names(block_node)
53
+ defined_properties = get_defined_property_names(block_node)
54
+ model_properties = get_model_property_names(class_name)
55
+ model_enum_properties = get_model_enum_property_names(class_name)
56
+ missing_properties = (model_properties - (defined_sequences + defined_properties)).sort
57
+
58
+ # Add offense for missing properties
59
+ return unless missing_properties.any?
60
+
61
+ add_offense(node, message: MSG) do |corrector|
62
+ next unless block_node
63
+
64
+ # Add newline before closing block if it's a one-liner
65
+ if one_line_block?(block_node)
66
+ indentation = ' ' * node.loc.column
67
+ corrector.insert_before(block_node.loc.end, "\n#{indentation}")
68
+ end
69
+
70
+ missing_properties.each do |property|
71
+ definition =
72
+ if model_enum_properties.include?(property)
73
+ generate_enum_property_definition(class_name, property)
74
+ else
75
+ generate_property_definition(class_name, property)
76
+ end
77
+ next unless definition
78
+
79
+ # TODO: calculate indentation size
80
+ indentation = ' ' * (node.loc.column + 2)
81
+ corrector.insert_after(block_node.loc.begin, "\n#{indentation}#{definition}")
82
+ end
83
+ end
84
+ end
85
+
86
+ private def model_file_path(class_name)
87
+ "app/models/#{class_name.underscore}.rb"
88
+ end
89
+
90
+ private def one_line_block?(block_node)
91
+ block_node.loc.begin.line == block_node.loc.end.line
92
+ end
93
+
94
+ private def model_file_source(class_name)
95
+ path = model_file_path(class_name)
96
+ return File.read(path) if File.exist?(path)
97
+ end
98
+
99
+ private def get_model_enum_property_names(class_name)
100
+ source = model_file_source(class_name)
101
+ return [] unless source
102
+
103
+ extractor = ::Momocop::EnumExtractor.new
104
+ associations = extractor.extract(source)
105
+ return associations.map(&:to_sym)
106
+ end
107
+
108
+ RESTRICTED_COLUMNS = %w[created_at updated_at].freeze
109
+
110
+ private def get_model_property_names(class_name)
111
+ table = schema.table_by(name: table_name(class_name))
112
+ return [] unless table
113
+
114
+ column_names = table.columns.reject { _1.type == :references }.map(&:name) - RESTRICTED_COLUMNS
115
+ return column_names.map(&:to_sym)
116
+ end
117
+
118
+ # e.g.)
119
+ # 'User' -> ['users']
120
+ # 'Admin::User' -> ['admin_users', 'users']
121
+ private def table_name(class_name)
122
+ # TODO: parse model class file and try to get table_name_prefix and table_name_suffix
123
+ class_name.tableize.gsub('/', '_')
124
+ end
125
+
126
+ private def get_defined_sequence_names(block_node)
127
+ body_node = block_node&.children&.last
128
+ return [] unless body_node
129
+
130
+ sequences = sequence_definitions(body_node)
131
+ sequence_names = sequences&.map(&:first_argument)&.map(&:value)&.map(&:to_sym)
132
+ return sequence_names
133
+ end
134
+
135
+ private def get_defined_property_names(block_node)
136
+ body_node = block_node&.children&.last
137
+ return [] unless body_node
138
+
139
+ properties = property_definitions(body_node)
140
+ property_names =
141
+ properties
142
+ &.reject { %i[sequence association].include? _1 }
143
+ &.map(&:to_sym)
144
+ return property_names
145
+ end
146
+
147
+ private def factory_bot_define_block_with_class_option?(node)
148
+ factory_method_call?(node) && inside_factory_bot_define?(node)
149
+ end
150
+
151
+ private def factory_method_call?(node)
152
+ node.method_name == :factory
153
+ end
154
+
155
+ private def inside_factory_bot_define?(node)
156
+ ancestors = node.each_ancestor(:block).to_a
157
+ ancestors.any? { |ancestor| ancestor.method_name == :define && ancestor.receiver&.const_name == 'FactoryBot' }
158
+ end
159
+
160
+ private def get_class_name(node)
161
+ options_hash = node.arguments[1]
162
+ return nil unless options_hash&.type == :hash
163
+
164
+ class_option = options_hash.pairs.find { |pair| pair.key.value == :class }
165
+ return nil unless class_option
166
+
167
+ value = class_option.value
168
+ return nil unless value.str_type? || value.sym_type?
169
+
170
+ return value.value.to_s
171
+ end
172
+
173
+ private def generate_property_definition(class_name, property)
174
+ table = schema.table_by(name: table_name(class_name))
175
+ column = table.columns.find { |c| c.name.to_sym == property }
176
+ return nil unless column
177
+
178
+ case column.type
179
+ when :integer, :float, :decimal
180
+ "sequence(:#{column.name}) { _1 }"
181
+ when :string, :text
182
+ "sequence(:#{column.name}) { \"#{column.name.camelize} #\{_1}\" }"
183
+ when :datetime, :timestamp, :time
184
+ "#{column.name} { Time.zone.now }"
185
+ when :date
186
+ "#{column.name} { Date.today }"
187
+ when :boolean
188
+ "#{column.name} { [true, false].sample }"
189
+ when :json, :jsonb
190
+ "#{column.name} { JSON.parse('{}') }"
191
+ else
192
+ # blob, binary, else
193
+ "#{column.name} { }"
194
+ end
195
+ end
196
+
197
+ private def generate_enum_property_definition(class_name, property)
198
+ enum_iteration_method_name = property.to_s.pluralize
199
+ "#{property} { #{class_name}.#{enum_iteration_method_name}.keys.sample }"
200
+ end
201
+ end
202
+ end
203
+ end
204
+ end
data/sig/momocop.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Momocop
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,107 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: momocop
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.3
5
+ platform: ruby
6
+ authors:
7
+ - supermomonga
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-02-18 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
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: rubocop
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: rubocop-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: Convention focused opinionated custom cops for RuboCop.
56
+ email:
57
+ - hi@supermomonga.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - ".rubocop_todo.yml"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - config/default.yml
71
+ - lib/momocop.rb
72
+ - lib/momocop/association_extractor.rb
73
+ - lib/momocop/config_injector.rb
74
+ - lib/momocop/enum_extractor.rb
75
+ - lib/momocop/version.rb
76
+ - lib/rubocop/cop/momocop/factory_bot_rails_class_name.rb
77
+ - lib/rubocop/cop/momocop/factory_bot_rails_class_option_specified.rb
78
+ - lib/rubocop/cop/momocop/factory_bot_rails_factory_associations_coverage.rb
79
+ - lib/rubocop/cop/momocop/factory_bot_rails_factory_properties_coverage.rb
80
+ - sig/momocop.rbs
81
+ homepage: https://github.com/supermomonga/momocop
82
+ licenses:
83
+ - MIT
84
+ metadata:
85
+ homepage_uri: https://github.com/supermomonga/momocop
86
+ source_code_uri: https://github.com/supermomonga/momocop
87
+ changelog_uri: https://github.com/supermomonga/momocop/releases
88
+ post_install_message:
89
+ rdoc_options: []
90
+ require_paths:
91
+ - lib
92
+ required_ruby_version: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: 3.1.1
97
+ required_rubygems_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '0'
102
+ requirements: []
103
+ rubygems_version: 3.3.26
104
+ signing_key:
105
+ specification_version: 4
106
+ summary: Convention focused opinionated custom cops for RuboCop.
107
+ test_files: []