diff --git a/lib/pronto/rubocop/patch_cop.rb b/lib/pronto/rubocop/patch_cop.rb index ca52588..6655d39 100644 --- a/lib/pronto/rubocop/patch_cop.rb +++ b/lib/pronto/rubocop/patch_cop.rb @@ -13,12 +13,9 @@ def initialize(patch, runner) def messages return [] unless valid? - offenses.flat_map do |offense| - patch - .added_lines - .select { |line| line.new_lineno == offense.line } - .map { |line| OffenseLine.new(self, offense, line).message } - end + offenses + .map { |offense| first_relevant_message(patch, offense) } + .compact end def processed_source @@ -67,6 +64,11 @@ def offenses .reject(&:disabled?) end + def offense_includes?(offense, line_number) + offense_range = (offense.location.first_line..offense.location.last_line) + offense_range.include?(line_number) + end + def team @team ||= if ::RuboCop::Cop::Team.respond_to?(:mobilize) @@ -76,6 +78,19 @@ def team ::RuboCop::Cop::Team.new(registry, rubocop_config) end end + + def first_relevant_line(patch, offense) + patch.added_lines.detect do |line| + offense_includes?(offense, line.new_lineno) + end + end + + def first_relevant_message(patch, offense) + offending_line = first_relevant_line(patch, offense) + return nil unless offending_line + + OffenseLine.new(self, offense, offending_line).message + end end end end diff --git a/spec/pronto/rubocop/patch_cop_spec.rb b/spec/pronto/rubocop/patch_cop_spec.rb index 841f59c..0cbf83a 100644 --- a/spec/pronto/rubocop/patch_cop_spec.rb +++ b/spec/pronto/rubocop/patch_cop_spec.rb @@ -12,7 +12,8 @@ let(:ast) { double :ast, each_node: nil } let(:processed_source) { double :processed_source, ast: ast } let(:team) { double :team, inspect_file: [offense] } - let(:offense) { double :offense, disabled?: false, line: 42 } + let(:offense_location) { double :location, first_line: 42, last_line: 43 } + let(:offense) { double :offense, disabled?: false, location: offense_location } let(:offense_line) { double :offense_line, message: 'Err' } before do @@ -31,5 +32,13 @@ it do expect(patch_cop.messages).to eq(['Err']) end + + context 'when there is an error including the patch, but not starting inside it' do + let(:offense_location) { double :location, first_line: 40, last_line: 43 } + + it do + expect(patch_cop.messages).to eq(['Err']) + end + end end end