Skip to content

Commit 37540d2

Browse files
viralpraxisbbatsov
authored andcommitted
Enhance Gemspec/RequireMFA cop autocorrect to insert MFA directive after last metadata assignment
It's a little bit annoying that the `Gemspec/RequireMFA`' cop autocorrection inserts MFA directive at the end, even if I grouped all `metadata=` assignments in one place. This patch tries to find the last `metadata = { ... }` or `metadata[]=` assignment and inserts `spec.metadata['rubygems_mfa_required'] = 'true'` after this node.
1 parent 80aff64 commit 37540d2

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#14314](https://github.com/rubocop/rubocop/pull/14314): Enhance `Gemspec/RequireMFA` cop autocorrect to insert MFA directive after last `metadata` assignment. ([@viralpraxis][])

lib/rubocop/cop/gemspec/require_mfa.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,14 @@ class RequireMFA < Base
7474
}
7575
PATTERN
7676

77+
# @!method metadata_assignment(node)
78+
def_node_search :metadata_assignment, <<~PATTERN
79+
`{
80+
(send _ :metadata= _)
81+
(send (send _ :metadata) :[]= (str _) _)
82+
}
83+
PATTERN
84+
7785
# @!method rubygems_mfa_required(node)
7886
def_node_search :rubygems_mfa_required, <<~PATTERN
7987
(pair (str "rubygems_mfa_required") $_)
@@ -131,9 +139,15 @@ def correct_metadata(corrector, metadata)
131139
end
132140

133141
def insert_mfa_required(corrector, node, block_var)
134-
corrector.insert_before(node.loc.end, <<~RUBY)
142+
require_mfa_directive = <<~RUBY.strip
135143
#{block_var}.metadata['rubygems_mfa_required'] = 'true'
136144
RUBY
145+
146+
if (last_assignment = metadata_assignment(processed_source.ast).to_a.last)
147+
corrector.insert_after(last_assignment, "\n#{require_mfa_directive}")
148+
else
149+
corrector.insert_before(node.loc.end, "#{require_mfa_directive}\n")
150+
end
137151
end
138152

139153
def change_value(corrector, value)

spec/rubocop/cop/gemspec/require_mfa_spec.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,26 @@
121121
end
122122
RUBY
123123
end
124+
125+
context 'when `metadata` assignment is not the last one' do
126+
it 'registers an offense' do
127+
expect_offense(<<~RUBY, 'my.gemspec')
128+
Gem::Specification.new do |spec|
129+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `metadata['rubygems_mfa_required']` must be set to `'true'`.
130+
spec.metadata['foo'] = 'bar'
131+
spec.author = 'viralpraxis'
132+
end
133+
RUBY
134+
135+
expect_correction(<<~RUBY)
136+
Gem::Specification.new do |spec|
137+
spec.metadata['foo'] = 'bar'
138+
spec.metadata['rubygems_mfa_required'] = 'true'
139+
spec.author = 'viralpraxis'
140+
end
141+
RUBY
142+
end
143+
end
124144
end
125145
end
126146

0 commit comments

Comments
 (0)