lib/rubocop/cop/cop.rb in rubocop-0.29.1 vs lib/rubocop/cop/cop.rb in rubocop-0.30.0

- old
+ new

@@ -45,10 +45,11 @@ # end class Cop extend AST::Sexp include Util include IgnoredNode + include AutocorrectLogic attr_reader :config, :offenses, :corrections attr_accessor :processed_source # TODO: Bad design. @all = CopStore.new @@ -103,11 +104,11 @@ cop_type == :rails end def initialize(config = nil, options = nil) @config = config || Config.new - @options = options || { auto_correct: false, debug: false } + @options = options || { debug: false } @offenses = [] @corrections = [] end @@ -117,31 +118,29 @@ def cop_config @config.for_cop(self) end - def autocorrect? - @options[:auto_correct] && support_autocorrect? - end - def debug? @options[:debug] end def display_cop_names? debug? || @options[:display_cop_names] || config['AllCops'] && config['AllCops']['DisplayCopNames'] end + def display_style_guide? + style_guide_url && + (@options[:display_style_guide] || + config['AllCops'] && config['AllCops']['DisplayStyleGuide']) + end + def message(_node = nil) self.class::MSG end - def support_autocorrect? - respond_to?(:autocorrect, true) - end - def add_offense(node, loc, message = nil, severity = nil) location = loc.is_a?(Symbol) ? node.loc.send(loc) : loc return unless enabled_line?(location.line) @@ -149,22 +148,28 @@ return if @offenses.find { |o| o.location == location } severity = custom_severity || severity || default_severity message ||= message(node) - message = display_cop_names? ? "#{name}: #{message}" : message + message = annotate_message(message) - corrected = begin - autocorrect(node) if autocorrect? - autocorrect? - rescue CorrectionNotPossible - false - end + corrected = correct(node) + @offenses << Offense.new(severity, location, message, name, corrected) yield if block_given? end + def correct(node) + return nil unless support_autocorrect? + return false unless autocorrect? + + autocorrect(node) + true + rescue CorrectionNotPossible + false + end + def config_to_allow_offenses Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] end def config_to_allow_offenses=(hash) @@ -181,10 +186,21 @@ def relevant_file?(file) file_name_matches_any?(file, 'Include', true) && !file_name_matches_any?(file, 'Exclude', false) end + def style_guide_url + url = cop_config && cop_config['StyleGuide'] + (url.nil? || url.empty?) ? nil : url + end + private + + def annotate_message(message) + message = "#{name}: #{message}" if display_cop_names? + message = "#{message} (#{style_guide_url})" if display_style_guide? + message + end def file_name_matches_any?(file, parameter, default_result) patterns = cop_config && cop_config[parameter] return default_result unless patterns path = nil