Skip to content

Commit 3b316f6

Browse files
committed
Suggestion code blocks in messages
1 parent dc71585 commit 3b316f6

2 files changed

Lines changed: 50 additions & 1 deletion

File tree

lib/pronto/rubocop/patch_cop.rb

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,16 @@ def team
5050
@team ||= ::RuboCop::Cop::Team.new(registry, config)
5151
end
5252

53+
def autocorrect_team
54+
@autocorrect_team ||=
55+
::RuboCop::Cop::Team.new(
56+
registry,
57+
config,
58+
auto_correct: true,
59+
stdin: true,
60+
)
61+
end
62+
5363
def registry
5464
@registry ||= ::RuboCop::Cop::Registry.new(RuboCop::Cop::Cop.all)
5565
end
@@ -62,8 +72,34 @@ def processed_source
6272
def new_message(offence, line)
6373
path = line.patch.delta.new_file[:path]
6474
level = level(offence.severity.name)
75+
message = message_text(offence)
76+
77+
Message.new(path, line, level, message, nil, runner.class)
78+
end
79+
80+
def message_text(offence)
81+
message = offence.message
82+
83+
return message unless suggestion_cop_names.include?(offence.cop_name)
84+
return message unless corrected
85+
86+
suggestion = corrected.lines[offence.line - 1]
87+
"#{message}\n\n```suggestion\n#{suggestion}```"
88+
end
89+
90+
def corrected
91+
@corrected ||= begin
92+
autocorrect_team.inspect_file(processed_source)
93+
corrector = RuboCop::Cop::Corrector.new(processed_source.buffer)
94+
autocorrect_team.cops.each do |cop|
95+
corrector.corrections.concat(cop.corrections)
96+
end
97+
corrector.rewrite unless corrector.corrections.empty?
98+
end
99+
end
65100

66-
Message.new(path, line, level, offence.message, nil, runner.class)
101+
def suggestion_cop_names
102+
@suggestion_cop_names ||= ENV['RUBOCOP_SUGGESTION_COPS'].to_s.split(',')
67103
end
68104

69105
def level(severity)

spec/pronto/rubocop_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,19 @@ module Pronto
2626
its(:'first.msg') do
2727
should =~ /Prefer single-quoted strings/
2828
end
29+
30+
context 'with a RUBOCOP_SUGGESTION_COPS environment variable' do
31+
before do
32+
allow(ENV).to receive(:[]).with('RUBOCOP_CONFIG') { nil }
33+
allow(ENV)
34+
.to receive(:[]).with('RUBOCOP_SUGGESTION_COPS') { cop_names }
35+
end
36+
let(:cop_names) { 'Layout/TrailingWhitespace,Style/StringLiterals' }
37+
38+
it 'adds a block of code with the suggestion' do
39+
expect(subject.first.msg).to match(/```suggestion\n 'bar'\n```/)
40+
end
41+
end
2942
end
3043
end
3144
end

0 commit comments

Comments
 (0)