From 1fc0c525bd4962421e27d9c2dffcb24d3ec9e9b0 Mon Sep 17 00:00:00 2001 From: Vitalii Elenhaupt Date: Wed, 9 May 2018 00:14:46 +0300 Subject: [PATCH] Do not report unneeded disable directive if directive is used one line above --- spec/ameba/rule/unneded_disable_directive_spec.cr | 11 ++++++++++- spec/spec_helper.cr | 2 +- src/ameba/inline_comments.cr | 7 +++++++ src/ameba/rule/unneeded_disable_directive.cr | 11 ++++++++++- 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/spec/ameba/rule/unneded_disable_directive_spec.cr b/spec/ameba/rule/unneded_disable_directive_spec.cr index 0061e261..0c50784c 100644 --- a/spec/ameba/rule/unneded_disable_directive_spec.cr +++ b/spec/ameba/rule/unneded_disable_directive_spec.cr @@ -18,7 +18,16 @@ module Ameba::Rule subject.catch(s).should be_valid end - it "passes if there is disable directive and it is needed" do + it "doesn't report if there is disable directive and it is needed" do + s = Source.new %Q( + # ameba:disable #{NamedRule.name} + a = 1 + ) + s.error NamedRule.new, 3, 9, "Useless assignment", :disabled + subject.catch(s).should be_valid + end + + it "passes if there is inline disable directive and it is needed" do s = Source.new %Q( a = 1 # ameba:disable #{NamedRule.name} ) diff --git a/spec/spec_helper.cr b/spec/spec_helper.cr index 93d593a5..b91e5e5d 100644 --- a/spec/spec_helper.cr +++ b/spec/spec_helper.cr @@ -72,7 +72,7 @@ module Ameba def failure_message(source) String.build do |str| str << "Source expected to be valid, but there are errors:\n\n" - source.errors.each do |e| + source.errors.reject(&.disabled?).each do |e| str << " * #{e.rule.name}: #{e.message}\n" end end diff --git a/src/ameba/inline_comments.cr b/src/ameba/inline_comments.cr index 1182d871..a4ea0fa9 100644 --- a/src/ameba/inline_comments.cr +++ b/src/ameba/inline_comments.cr @@ -70,6 +70,13 @@ module Ameba end end + # Returns true if the line at the given `line_number` is a comment. + def comment?(line_number : Int32) + if line = lines[line_number]? + comment?(line) + end + end + private def comment?(line) return true if line.lstrip.starts_with? '#' end diff --git a/src/ameba/rule/unneeded_disable_directive.cr b/src/ameba/rule/unneeded_disable_directive.cr index 4d22f3dc..02ecb7e2 100644 --- a/src/ameba/rule/unneeded_disable_directive.cr +++ b/src/ameba/rule/unneeded_disable_directive.cr @@ -43,9 +43,18 @@ module Ameba::Rule source.errors.any? do |error| error.rule.name == rule_name && error.disabled? && - error.location.try(&.line_number) == location.line_number + error_at_location?(source, error, location) end && rule_name != self.name end end + + private def error_at_location?(source, error, location) + return false unless error_line_number = error.location.try(&.line_number) + + error_line_number == location.line_number || + ((prev_line_number = error_line_number - 1) && + prev_line_number == location.line_number && + source.comment?(prev_line_number - 1)) + end end end