Class: RuboCop::Cop::Cop

Inherits:
Object
  • Object
show all
Extended by:
AST::Sexp, NodePattern::Macros
Includes:
AST::Sexp, AutocorrectLogic, IgnoredNode, Util
Defined in:
lib/rubocop/cop/cop.rb,
lib/rubocop/rspec/cop_helper.rb

Overview

Monkey-patch Cop for tests to provide easy access to messages and highlights.

Direct Known Subclasses

Bundler::DuplicatedGem, Bundler::OrderedGems, Lint::AmbiguousOperator, Lint::AmbiguousRegexpLiteral, Lint::AssignmentInCondition, Lint::BlockAlignment, Lint::CircularArgumentReference, Lint::ConditionPosition, Lint::Debugger, Lint::DefEndAlignment, Lint::DeprecatedClassMethods, Lint::DuplicateCaseCondition, Lint::DuplicateMethods, Lint::DuplicatedKey, Lint::EachWithObjectArgument, Lint::ElseLayout, Lint::EmptyEnsure, Lint::EmptyExpression, Lint::EmptyInterpolation, Lint::EmptyWhen, Lint::EndAlignment, Lint::EndInMethod, Lint::EnsureReturn, Lint::FloatOutOfRange, Lint::FormatParameterMismatch, Lint::HandleExceptions, Lint::ImplicitStringConcatenation, Lint::IneffectiveAccessModifier, Lint::InheritException, Lint::InvalidCharacterLiteral, Lint::LiteralInCondition, Lint::LiteralInInterpolation, Lint::Loop, Lint::MultipleCompare, Lint::NestedMethodDefinition, Lint::NextWithoutAccumulator, Lint::NonLocalExitFromIterator, Lint::ParenthesesAsGroupedExpression, Lint::PercentStringArray, Lint::PercentSymbolArray, Lint::RandOne, Lint::RequireParentheses, Lint::RescueException, Lint::SafeNavigationChain, Lint::ShadowedException, Lint::ShadowingOuterLocalVariable, Lint::StringConversionInInterpolation, Lint::UnderscorePrefixedVariableName, Lint::UnifiedInteger, Lint::UnneededDisable, Lint::UnneededSplatExpansion, Lint::UnreachableCode, Lint::UnusedBlockArgument, Lint::UnusedMethodArgument, Lint::UselessAccessModifier, Lint::UselessAssignment, Lint::UselessComparison, Lint::UselessElseWithoutRescue, Lint::UselessSetterCall, Lint::Void, Metrics::AbcSize, Metrics::BlockLength, Metrics::BlockNesting, Metrics::ClassLength, Metrics::CyclomaticComplexity, Metrics::LineLength, Metrics::MethodLength, Metrics::ModuleLength, Metrics::ParameterLists, Metrics::PerceivedComplexity, Performance::CaseWhenSplat, Performance::Casecmp, Performance::CompareWithBlock, Performance::Count, Performance::Detect, Performance::DoubleStartEndWith, Performance::EndWith, Performance::FixedSize, Performance::FlatMap, Performance::HashEachMethods, Performance::LstripRstrip, Performance::RangeInclude, Performance::RedundantBlockCall, Performance::RedundantMatch, Performance::RedundantMerge, Performance::RedundantSortBy, Performance::RegexpMatch, Performance::ReverseEach, Performance::Sample, Performance::Size, Performance::StartWith, Performance::StringReplacement, Performance::TimesMap, Rails::ActionFilter, Rails::Date, Rails::Delegate, Rails::DelegateAllowBlank, Rails::DynamicFindBy, Rails::EnumUniqueness, Rails::Exit, Rails::FilePath, Rails::FindBy, Rails::FindEach, Rails::HasAndBelongsToMany, Rails::HttpPositionalArguments, Rails::NotNullColumn, Rails::Output, Rails::OutputSafety, Rails::PluralizationGrammar, Rails::ReadWriteAttribute, Rails::RequestReferer, Rails::ReversibleMigration, Rails::SafeNavigation, Rails::SaveBang, Rails::ScopeArgs, Rails::SkipsModelValidations, Rails::TimeZone, Rails::UniqBeforePluck, Rails::Validation, Security::Eval, Security::JSONLoad, Security::MarshalLoad, Security::YAMLLoad, Style::AccessModifierIndentation, Style::AccessorMethodName, Style::Alias, Style::AlignArray, Style::AlignHash, Style::AlignParameters, Style::AndOr, Style::ArrayJoin, Style::AsciiComments, Style::AsciiIdentifiers, Style::Attr, Style::AutoResourceCleanup, Style::BarePercentLiterals, Style::BeginBlock, Style::BlockComments, Style::BlockDelimiters, Style::BlockEndNewline, Style::BracesAroundHashParameters, Style::CaseEquality, Style::CaseIndentation, Style::CharacterLiteral, Style::ClassAndModuleCamelCase, Style::ClassAndModuleChildren, Style::ClassCheck, Style::ClassMethods, Style::ClassVars, Style::ClosingParenthesisIndentation, Style::CollectionMethods, Style::ColonMethodCall, Style::CommandLiteral, Style::CommentAnnotation, Style::CommentIndentation, Style::ConditionalAssignment, Style::ConstantName, Style::Copyright, Style::DefWithParentheses, Style::Documentation, Style::DocumentationMethod, Style::DotPosition, Style::DoubleNegation, Style::EachForSimpleLoop, Style::EachWithObject, Style::ElseAlignment, Style::EmptyCaseCondition, Style::EmptyElse, Style::EmptyLineBetweenDefs, Style::EmptyLines, Style::EmptyLinesAroundAccessModifier, Style::EmptyLinesAroundBlockBody, Style::EmptyLinesAroundClassBody, Style::EmptyLinesAroundMethodBody, Style::EmptyLinesAroundModuleBody, Style::EmptyLiteral, Style::EmptyMethod, Style::Encoding, Style::EndBlock, Style::EndOfLine, Style::EvenOdd, Style::ExtraSpacing, Style::FileName, Style::FirstArrayElementLineBreak, Style::FirstHashElementLineBreak, Style::FirstMethodArgumentLineBreak, Style::FirstMethodParameterLineBreak, Style::FirstParameterIndentation, Style::FlipFlop, Style::For, Style::FormatString, Style::FrozenStringLiteralComment, Style::GlobalVars, Style::GuardClause, Style::HashSyntax, Style::IdenticalConditionalBranches, Style::IfInsideElse, Style::IfUnlessModifier, Style::IfUnlessModifierOfIfUnless, Style::IfWithSemicolon, Style::ImplicitRuntimeError, Style::IndentArray, Style::IndentAssignment, Style::IndentHash, Style::IndentationConsistency, Style::IndentationWidth, Style::InfiniteLoop, Style::InitialIndentation, Style::InlineComment, Style::Lambda, Style::LambdaCall, Style::LeadingCommentSpace, Style::LineEndConcatenation, Style::MethodCallWithArgsParentheses, Style::MethodCallWithoutArgsParentheses, Style::MethodCalledOnDoEndBlock, Style::MethodDefParentheses, Style::MethodMissing, Style::MethodName, Style::MissingElse, Style::ModuleFunction, Style::MultilineArrayBraceLayout, Style::MultilineAssignmentLayout, Style::MultilineBlockChain, Style::MultilineBlockLayout, Style::MultilineHashBraceLayout, Style::MultilineIfModifier, Style::MultilineIfThen, Style::MultilineMemoization, Style::MultilineMethodCallBraceLayout, Style::MultilineMethodCallIndentation, Style::MultilineMethodDefinitionBraceLayout, Style::MultilineOperationIndentation, Style::MultilineTernaryOperator, Style::MutableConstant, Style::NegatedIf, Style::NegatedWhile, Style::NestedModifier, Style::NestedParenthesizedCalls, Style::NestedTernaryOperator, Style::Next, Style::NilComparison, Style::NonNilCheck, Style::Not, Style::NumericLiteralPrefix, Style::NumericLiterals, Style::NumericPredicate, Style::OneLineConditional, Style::OpMethod, Style::OptionHash, Style::OptionalArguments, Style::ParallelAssignment, Style::ParenthesesAroundCondition, Style::PercentLiteralDelimiters, Style::PercentQLiterals, Style::PerlBackrefs, Style::PredicateName, Style::PreferredHashMethods, Style::Proc, Style::RaiseArgs, Style::RedundantBegin, Style::RedundantException, Style::RedundantFreeze, Style::RedundantParentheses, Style::RedundantReturn, Style::RedundantSelf, Style::RegexpLiteral, Style::RescueEnsureAlignment, Style::RescueModifier, Style::SafeNavigation, Style::SelfAssignment, Style::Semicolon, Style::Send, Style::SignalException, Style::SingleLineBlockParams, Style::SingleLineMethods, Style::SpaceAfterColon, Style::SpaceAfterComma, Style::SpaceAfterMethodName, Style::SpaceAfterNot, Style::SpaceAfterSemicolon, Style::SpaceAroundBlockParameters, Style::SpaceAroundEqualsInParameterDefault, Style::SpaceAroundKeyword, Style::SpaceAroundOperators, Style::SpaceBeforeBlockBraces, Style::SpaceBeforeComma, Style::SpaceBeforeComment, Style::SpaceBeforeFirstArg, Style::SpaceBeforeSemicolon, Style::SpaceInLambdaLiteral, Style::SpaceInsideArrayPercentLiteral, Style::SpaceInsideBlockBraces, Style::SpaceInsideBrackets, Style::SpaceInsideHashLiteralBraces, Style::SpaceInsideParens, Style::SpaceInsidePercentLiteralDelimiters, Style::SpaceInsideRangeLiteral, Style::SpaceInsideStringInterpolation, Style::SpecialGlobalVars, Style::StabbyLambdaParentheses, Style::StringLiterals, Style::StringLiteralsInInterpolation, Style::StringMethods, Style::StructInheritance, Style::SymbolArray, Style::SymbolLiteral, Style::SymbolProc, Style::Tab, Style::TernaryParentheses, Style::TrailingBlankLines, Style::TrailingCommaInArguments, Style::TrailingCommaInLiteral, Style::TrailingUnderscoreVariable, Style::TrailingWhitespace, Style::TrivialAccessors, Style::UnlessElse, Style::UnneededCapitalW, Style::UnneededInterpolation, Style::UnneededPercentQ, Style::VariableInterpolation, Style::VariableName, Style::VariableNumber, Style::WhenThen, Style::WhileUntilDo, Style::WhileUntilModifier, Style::WordArray, Style::ZeroLengthPredicate

Constant Summary

Constants included from Util

Util::ASGN_NODES, Util::BYTE_ORDER_MARK, Util::CONDITIONAL_NODES, Util::EQUALS_ASGN_NODES, Util::LITERAL_REGEX, Util::LOGICAL_OPERATOR_NODES, Util::MODIFIER_NODES, Util::OPERATOR_METHODS, Util::SHORTHAND_ASGN_NODES

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AST::Sexp

s

Methods included from NodePattern::Macros

def_node_matcher, def_node_search, node_search, node_search_all, node_search_body, node_search_first

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #support_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

begins_its_line?, block_length, comment_line?, compatible_external_encoding_for?, directions, double_quotes_acceptable?, double_quotes_required?, effective_column, ends_its_line?, escape_string, first_part_of_call_chain, hard_to_type?, interpret_string_escapes, line_distance, line_range, move_pos, needs_escaping?, numeric_range_size, on_node, operator?, parentheses?, parenthesized_call?, preceed?, range_between, range_with_surrounding_comma, range_with_surrounding_space, same_line?, source_range, strip_quotes, stripped_source_upto, to_string_literal, to_supported_styles, to_symbol_literal, within_node?

Methods included from PathUtil

absolute?, match_path?, relative_path

Constructor Details

#initialize(config = nil, options = nil) ⇒ Cop

Returns a new instance of Cop.



83
84
85
86
87
88
89
90
# File 'lib/rubocop/cop/cop.rb', line 83

def initialize(config = nil, options = nil)
  @config = config || Config.new
  @options = options || { debug: false }

  @offenses = []
  @corrections = []
  @processed_source = nil
end

Class Attribute Details

.registryObject (readonly)

Returns the value of attribute registry.



39
40
41
# File 'lib/rubocop/cop/cop.rb', line 39

def registry
  @registry
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



33
34
35
# File 'lib/rubocop/cop/cop.rb', line 33

def config
  @config
end

#correctionsObject (readonly)

Returns the value of attribute corrections.



33
34
35
# File 'lib/rubocop/cop/cop.rb', line 33

def corrections
  @corrections
end

#offensesObject (readonly)

Returns the value of attribute offenses.



33
34
35
# File 'lib/rubocop/cop/cop.rb', line 33

def offenses
  @offenses
end

#processed_sourceObject

TODO: Bad design.



34
35
36
# File 'lib/rubocop/cop/cop.rb', line 34

def processed_source
  @processed_source
end

Class Method Details

.allObject



42
43
44
# File 'lib/rubocop/cop/cop.rb', line 42

def self.all
  registry.without_department(:Test).cops
end

.badgeObject



58
59
60
# File 'lib/rubocop/cop/cop.rb', line 58

def self.badge
  @badge ||= Badge.for(name)
end

.cop_nameObject



62
63
64
# File 'lib/rubocop/cop/cop.rb', line 62

def self.cop_name
  badge.to_s
end

.departmentObject



66
67
68
# File 'lib/rubocop/cop/cop.rb', line 66

def self.department
  badge.department
end

.inherited(subclass) ⇒ Object



54
55
56
# File 'lib/rubocop/cop/cop.rb', line 54

def self.inherited(subclass)
  registry.enlist(subclass)
end

.lint?Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/rubocop/cop/cop.rb', line 70

def self.lint?
  department == :Lint
end

.match?(given_names) ⇒ Boolean

Returns true if the cop name or the cop namespace matches any of the given names.

Returns:

  • (Boolean)


76
77
78
79
80
81
# File 'lib/rubocop/cop/cop.rb', line 76

def self.match?(given_names)
  return false unless given_names

  given_names.include?(cop_name) ||
    given_names.include?(department.to_s)
end

.non_railsObject



50
51
52
# File 'lib/rubocop/cop/cop.rb', line 50

def self.non_rails
  registry.without_department(:Rails)
end

.qualified_cop_name(name, origin) ⇒ Object



46
47
48
# File 'lib/rubocop/cop/cop.rb', line 46

def self.qualified_cop_name(name, origin)
  registry.qualified_cop_name(name, origin)
end

Instance Method Details

#add_offense(node, loc, message = nil, severity = nil) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/rubocop/cop/cop.rb', line 104

def add_offense(node, loc, message = nil, severity = nil)
  location = find_location(node, loc)

  return if duplicate_location?(location)

  severity = custom_severity || severity || default_severity

  message ||= message(node)
  message = annotate(message)

  status = enabled_line?(location.line) ? correct(node) : :disabled

  @offenses << Offense.new(severity, location, message, name, status)
  yield if block_given? && status != :disabled
end

#config_to_allow_offensesObject



139
140
141
142
# File 'lib/rubocop/cop/cop.rb', line 139

def config_to_allow_offenses
  Formatter::DisabledConfigFormatter
    .config_to_allow_offenses[cop_name] ||= {}
end

#config_to_allow_offenses=(hash) ⇒ Object



144
145
146
147
# File 'lib/rubocop/cop/cop.rb', line 144

def config_to_allow_offenses=(hash)
  Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] =
    hash
end

#cop_configObject



96
97
98
# File 'lib/rubocop/cop/cop.rb', line 96

def cop_config
  @cop_config ||= @config.for_cop(self)
end

#cop_nameObject Also known as: name



157
158
159
# File 'lib/rubocop/cop/cop.rb', line 157

def cop_name
  @cop_name ||= self.class.cop_name
end

#correct(node) ⇒ Object



129
130
131
132
133
134
135
136
137
# File 'lib/rubocop/cop/cop.rb', line 129

def correct(node)
  return :unsupported unless support_autocorrect?
  return :uncorrected unless autocorrect?

  correction = autocorrect(node)
  return :uncorrected unless correction
  @corrections << correction
  :corrected
end

#duplicate_location?(location) ⇒ Boolean

Returns:

  • (Boolean)


125
126
127
# File 'lib/rubocop/cop/cop.rb', line 125

def duplicate_location?(location)
  @offenses.any? { |o| o.location == location }
end

#excluded_file?(file) ⇒ Boolean

Returns:

  • (Boolean)


168
169
170
# File 'lib/rubocop/cop/cop.rb', line 168

def excluded_file?(file)
  !relevant_file?(file)
end

#find_location(node, loc) ⇒ Object



120
121
122
123
# File 'lib/rubocop/cop/cop.rb', line 120

def find_location(node, loc)
  # Location can be provided as a symbol, e.g.: `:keyword`
  loc.is_a?(Symbol) ? node.loc.public_send(loc) : loc
end

#highlightsObject



87
88
89
# File 'lib/rubocop/rspec/cop_helper.rb', line 87

def highlights
  offenses.sort.map { |o| o.location.source }
end

#join_force?(_force_class) ⇒ Boolean

Returns:

  • (Boolean)


92
93
94
# File 'lib/rubocop/cop/cop.rb', line 92

def join_force?(_force_class)
  false
end

#message(_node = nil) ⇒ Object



100
101
102
# File 'lib/rubocop/cop/cop.rb', line 100

def message(_node = nil)
  self.class::MSG
end

#messagesObject



83
84
85
# File 'lib/rubocop/rspec/cop_helper.rb', line 83

def messages
  offenses.sort.map(&:message)
end

#parse(source, path = nil) ⇒ Object



153
154
155
# File 'lib/rubocop/cop/cop.rb', line 153

def parse(source, path = nil)
  ProcessedSource.new(source, target_ruby_version, path)
end

#relevant_file?(file) ⇒ Boolean

Returns:

  • (Boolean)


163
164
165
166
# File 'lib/rubocop/cop/cop.rb', line 163

def relevant_file?(file)
  file_name_matches_any?(file, 'Include', true) &&
    !file_name_matches_any?(file, 'Exclude', false)
end

#target_ruby_versionObject



149
150
151
# File 'lib/rubocop/cop/cop.rb', line 149

def target_ruby_version
  @config.target_ruby_version
end