repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/warning.rb | lib/rubocop/warning.rb | # frozen_string_literal: true
module RuboCop
# A Warning exception is different from an Offense with severity 'warning'
# When a Warning is raised, this means that RuboCop was unable to perform a
# requested operation (such as inspecting or correcting a source file) due to
# user error
# For example, a configuration value in .rubocop.yml might be malformed
class Warning < StandardError
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/plugin.rb | lib/rubocop/plugin.rb | # frozen_string_literal: true
require_relative 'plugin/configuration_integrator'
require_relative 'plugin/loader'
module RuboCop
# Provides a plugin for RuboCop extensions that conform to lint_roller.
# https://github.com/standardrb/lint_roller
# @api private
module Plugin
BUILTIN_INTERNAL_PLUGINS = {
'rubocop-internal_affairs' => {
'enabled' => true,
'require_path' => 'rubocop/cop/internal_affairs/plugin',
'plugin_class_name' => 'RuboCop::InternalAffairs::Plugin'
}
}.freeze
INTERNAL_AFFAIRS_PLUGIN_NAME = Plugin::BUILTIN_INTERNAL_PLUGINS.keys.first
OBSOLETE_INTERNAL_AFFAIRS_PLUGIN_NAME = 'rubocop/cop/internal_affairs'
class << self
def plugin_capable?(feature_name)
return true if BUILTIN_INTERNAL_PLUGINS.key?(feature_name)
return true if feature_name == OBSOLETE_INTERNAL_AFFAIRS_PLUGIN_NAME
begin
# When not using Bundler. Makes the spec available but does not require it.
gem feature_name
rescue Gem::LoadError
# The user requested a gem that they do not have installed
end
return false unless (spec = Gem.loaded_specs[feature_name])
!!spec.metadata['default_lint_roller_plugin']
end
def integrate_plugins(rubocop_config, plugins)
plugins = Plugin::Loader.load(plugins)
ConfigurationIntegrator.integrate_plugins_into_rubocop_config(rubocop_config, plugins)
plugins
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/ast_aliases.rb | lib/rubocop/ast_aliases.rb | # frozen_string_literal: true
# These aliases are for compatibility.
module RuboCop
NodePattern = AST::NodePattern
ProcessedSource = AST::ProcessedSource
Token = AST::Token
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cache_config.rb | lib/rubocop/cache_config.rb | # frozen_string_literal: true
module RuboCop
# This class represents the cache config of the caching RuboCop runs.
# @api private
class CacheConfig
def self.root_dir
root = ENV.fetch('RUBOCOP_CACHE_ROOT', nil)
root ||= yield
root ||= if ENV.key?('XDG_CACHE_HOME')
# Include user ID in the path to make sure the user has write
# access.
File.join(ENV.fetch('XDG_CACHE_HOME'), Process.uid.to_s)
else
# On FreeBSD, the /home path is a symbolic link to /usr/home
# and the $HOME environment variable returns the /home path.
#
# As $HOME is a built-in environment variable, FreeBSD users
# always get a warning message.
#
# To avoid raising warn log messages on FreeBSD, we retrieve
# the real path of the home folder.
File.join(File.realpath(Dir.home), '.cache')
end
File.join(root, 'rubocop_cache')
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/name_similarity.rb | lib/rubocop/name_similarity.rb | # frozen_string_literal: true
module RuboCop
# Common functionality for finding names that are similar to a given name.
# @api private
module NameSimilarity
module_function
def find_similar_name(target_name, names)
similar_names = find_similar_names(target_name, names)
similar_names.first
end
def find_similar_names(target_name, names)
# DidYouMean::SpellChecker is not available in all versions of Ruby, and
# even on versions where it *is* available (>= 2.3), it is not always
# required correctly. So we do a feature check first.
# See: https://github.com/rubocop/rubocop/issues/7979
return [] unless defined?(DidYouMean::SpellChecker)
names = names.dup
names.delete(target_name)
spell_checker = DidYouMean::SpellChecker.new(dictionary: names)
spell_checker.correct(target_name)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/comment_config.rb | lib/rubocop/comment_config.rb | # frozen_string_literal: true
module RuboCop
# This class parses the special `rubocop:disable` comments in a source
# and provides a way to check if each cop is enabled at arbitrary line.
class CommentConfig
extend SimpleForwardable
CONFIG_DISABLED_LINE_RANGE_MIN = -Float::INFINITY
# This class provides an API compatible with RuboCop::DirectiveComment
# to be used for cops that are disabled in the config file
class ConfigDisabledCopDirectiveComment
include RuboCop::Ext::Comment
attr_reader :text, :loc, :line_number
Loc = Struct.new(:expression)
Expression = Struct.new(:line)
def initialize(cop_name)
@text = "# rubocop:disable #{cop_name}"
@line_number = CONFIG_DISABLED_LINE_RANGE_MIN
@loc = Loc.new(Expression.new(CONFIG_DISABLED_LINE_RANGE_MIN))
end
end
CopAnalysis = Struct.new(:line_ranges, :start_line_number)
attr_reader :processed_source
def_delegators :@processed_source, :config, :registry
def initialize(processed_source)
@processed_source = processed_source
@no_directives = !processed_source.raw_source.include?('rubocop')
@stack = []
end
def cop_enabled_at_line?(cop, line_number)
cop = cop.cop_name if cop.respond_to?(:cop_name)
disabled_line_ranges = cop_disabled_line_ranges[cop]
return true unless disabled_line_ranges
disabled_line_ranges.none? { |range| range.include?(line_number) }
end
def cop_opted_in?(cop)
opt_in_cops.include?(cop.cop_name)
end
def cop_disabled_line_ranges
@cop_disabled_line_ranges ||= analyze
end
def extra_enabled_comments
disable_count = Hash.new(0)
registry.disabled(config).each do |cop|
disable_count[cop.cop_name] += 1
end
extra_enabled_comments_with_names(extras: Hash.new { |h, k| h[k] = [] }, names: disable_count)
end
def comment_only_line?(line_number)
non_comment_token_line_numbers.none?(line_number)
end
private
def extra_enabled_comments_with_names(extras:, names:)
each_directive do |directive|
next unless comment_only_line?(directive.line_number)
if directive.enabled_all?
handle_enable_all(directive, names, extras)
else
handle_switch(directive, names, extras)
end
end
extras
end
def opt_in_cops
@opt_in_cops ||= begin
cops = Set.new
each_directive do |directive|
next unless directive.enabled?
next if directive.all_cops?
cops.merge(directive.raw_cop_names)
end
cops
end
end
def analyze # rubocop:todo Metrics/AbcSize, Metrics/MethodLength
return {} if @no_directives
analyses = Hash.new { |hash, key| hash[key] = CopAnalysis.new([], nil) }
inject_disabled_cops_directives(analyses)
each_directive do |directive|
if directive.push?
@stack.push(snapshot_analyses(analyses))
apply_push_args(analyses, directive)
elsif directive.pop?
pop_state(analyses, directive.line_number) if @stack.any?
else
directive.cop_names.each do |cop_name|
cop_name = qualified_cop_name(cop_name)
analyses[cop_name] = analyze_cop(analyses[cop_name], directive)
end
end
end
analyses.each_with_object({}) do |element, hash|
cop_name, analysis = *element
hash[cop_name] = cop_line_ranges(analysis)
end
end
def snapshot_analyses(analyses)
analyses.transform_values { |a| CopAnalysis.new(a.line_ranges.dup, a.start_line_number) }
end
def pop_state(analyses, pop_line)
analyses.each do |cop_name, analysis|
next unless analysis.start_line_number
analyses[cop_name] = CopAnalysis.new(
analysis.line_ranges + [analysis.start_line_number...pop_line], nil
)
end
@stack.pop.each do |cop_name, saved_analysis|
current = analyses[cop_name]
new_start = saved_analysis.start_line_number ? pop_line : nil
analyses[cop_name] = CopAnalysis.new(current.line_ranges, new_start)
end
end
def apply_push_args(analyses, directive)
directive.push_args.each do |operation, cop_names|
cop_names.each do |cop_name|
apply_cop_operation(analyses, operation, qualified_cop_name(cop_name),
directive.line_number)
end
end
end
def apply_cop_operation(analyses, operation, cop_name, line)
analysis = analyses[cop_name]
start_line = analysis.start_line_number
case operation
when '+' # Enable cop
return unless start_line
analyses[cop_name] = CopAnalysis.new(analysis.line_ranges + [start_line..line], nil)
when '-' # Disable cop
return if start_line
analyses[cop_name] = CopAnalysis.new(analysis.line_ranges, line)
end
end
def inject_disabled_cops_directives(analyses)
registry.disabled(config).each do |cop|
analyses[cop.cop_name] = analyze_cop(
analyses[cop.cop_name],
DirectiveComment.new(ConfigDisabledCopDirectiveComment.new(cop.cop_name))
)
end
end
def analyze_cop(analysis, directive)
# Disabling cops after comments like `#=SomeDslDirective` does not related to single line
if !comment_only_line?(directive.line_number) || directive.single_line?
analyze_single_line(analysis, directive)
elsif directive.disabled?
analyze_disabled(analysis, directive)
else
analyze_rest(analysis, directive)
end
end
def analyze_single_line(analysis, directive)
return analysis unless directive.disabled?
line = directive.line_number
CopAnalysis.new(analysis.line_ranges + [(line..line)], analysis.start_line_number)
end
def analyze_disabled(analysis, directive)
line = directive.line_number
start_line = analysis.start_line_number
new_ranges = start_line ? analysis.line_ranges + [start_line..line] : analysis.line_ranges
CopAnalysis.new(new_ranges, line)
end
def analyze_rest(analysis, directive)
line = directive.line_number
start_line = analysis.start_line_number
new_ranges = start_line ? analysis.line_ranges + [start_line..line] : analysis.line_ranges
CopAnalysis.new(new_ranges, nil)
end
def cop_line_ranges(analysis)
return analysis.line_ranges unless analysis.start_line_number
analysis.line_ranges + [(analysis.start_line_number..Float::INFINITY)]
end
def each_directive
return if @no_directives
processed_source.comments.each do |comment|
directive = DirectiveComment.new(comment)
yield directive if directive.cop_names
end
end
def qualified_cop_name(cop_name)
Cop::Registry.qualified_cop_name(cop_name.strip, processed_source.file_path)
end
def non_comment_token_line_numbers
@non_comment_token_line_numbers ||= begin
non_comment_tokens = processed_source.tokens.reject(&:comment?)
non_comment_tokens.map(&:line).uniq
end
end
def handle_enable_all(directive, names, extras)
enabled_cops = 0
names.each do |name, counter|
next unless counter.positive?
names[name] -= 1
enabled_cops += 1
end
extras[directive.comment] << 'all' if enabled_cops.zero?
end
# Collect cops that have been disabled or enabled by name in a directive comment
# so that `Lint/RedundantCopEnableDirective` can register offenses correctly.
def handle_switch(directive, names, extras)
directive.cop_names.each do |name|
if directive.disabled?
names[name] += 1
elsif names[name].positive?
names[name] -= 1
else
extras[directive.comment] << name
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/rake_task.rb | lib/rubocop/rake_task.rb | # frozen_string_literal: true
require 'rake'
require 'rake/tasklib'
module RuboCop
# Provides a custom rake task.
#
# require 'rubocop/rake_task'
# RuboCop::RakeTask.new
#
# Use global Rake namespace here to avoid namespace issues with custom
# rubocop-rake tasks
class RakeTask < ::Rake::TaskLib
attr_accessor :name, :verbose, :fail_on_error, :patterns, :formatters, :plugins, :requires,
:options
def initialize(name = :rubocop, *args, &task_block)
super()
setup_ivars(name)
desc 'Run RuboCop' unless ::Rake.application.last_description
task(name, *args) do |_, task_args|
RakeFileUtils.verbose(verbose) do
yield(*[self, task_args].slice(0, task_block.arity)) if task_block
run_cli(verbose, full_options)
end
end
setup_subtasks(name, *args, &task_block)
end
private
def perform(option)
options = full_options.unshift(option)
# `parallel` will automatically be removed from the options internally.
# This is a nice to have to suppress the warning message
# about --parallel and --autocorrect not being compatible.
options.delete('--parallel')
run_cli(verbose, options)
end
def run_cli(verbose, options)
# We lazy-load RuboCop so that the task doesn't dramatically impact the
# load time of your Rakefile.
require_relative '../rubocop'
cli = CLI.new
puts 'Running RuboCop...' if verbose
result = cli.run(options)
abort('RuboCop failed!') if result.nonzero? && fail_on_error
end
def full_options
formatters.map { |f| ['--format', f] }.flatten
.concat(plugins.map { |plugin| ['--plugin', plugin] }.flatten)
.concat(requires.map { |r| ['--require', r] }.flatten)
.concat(options.flatten)
.concat(patterns)
end
def setup_ivars(name)
@name = name
@verbose = true
@fail_on_error = true
@patterns = []
@plugins = []
@requires = []
@options = []
@formatters = []
end
def setup_subtasks(name, *args, &task_block) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
namespace(name) do
# rubocop:todo Naming/InclusiveLanguage
task(:auto_correct, *args) do |_, task_args|
require 'rainbow'
warn Rainbow(
'rubocop:auto_correct task is deprecated; ' \
'use rubocop:autocorrect task or rubocop:autocorrect_all task instead.'
).yellow
RakeFileUtils.verbose(verbose) do
yield(*[self, task_args].slice(0, task_block.arity)) if task_block
perform('--autocorrect')
end
end
# rubocop:enable Naming/InclusiveLanguage
desc "Autocorrect RuboCop offenses (only when it's safe)."
task(:autocorrect, *args) do |_, task_args|
RakeFileUtils.verbose(verbose) do
yield(*[self, task_args].slice(0, task_block.arity)) if task_block
perform('--autocorrect')
end
end
desc 'Autocorrect RuboCop offenses (safe and unsafe).'
task(:autocorrect_all, *args) do |_, task_args|
RakeFileUtils.verbose(verbose) do
yield(*[self, task_args].slice(0, task_block.arity)) if task_block
perform('--autocorrect-all')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/yaml_duplication_checker.rb | lib/rubocop/yaml_duplication_checker.rb | # frozen_string_literal: true
module RuboCop
# Find duplicated keys from YAML.
# @api private
module YAMLDuplicationChecker
def self.check(yaml_string, filename, &on_duplicated)
handler = DuplicationCheckHandler.new(&on_duplicated)
parser = Psych::Parser.new(handler)
parser.parse(yaml_string, filename)
parser.handler.root.children[0]
end
class DuplicationCheckHandler < Psych::TreeBuilder # :nodoc:
def initialize(&block)
super()
@block = block
end
def end_mapping
mapping_node = super
# OPTIMIZE: Use a hash for faster lookup since there can
# be quite a few keys at the top-level.
keys = {}
mapping_node.children.each_slice(2) do |key, _value|
duplicate = keys[key.value]
@block.call(duplicate, key) if duplicate
keys[key.value] = key
end
mapping_node
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_store.rb | lib/rubocop/config_store.rb | # frozen_string_literal: true
module RuboCop
# Handles caching of configurations and association of inspected
# ruby files to configurations.
class ConfigStore
attr_reader :validated
alias validated? validated
def initialize
# @options_config stores a config that is specified in the command line.
# This takes precedence over configs located in any directories
@options_config = nil
# @path_cache maps directories to configuration paths. We search
# for .rubocop.yml only if we haven't already found it for the
# given directory.
@path_cache = {}
# @object_cache maps configuration file paths to
# configuration objects so we only need to load them once.
@object_cache = {}
# By default the config is validated before it can be used.
@validated = true
end
def apply_options!(options)
self.options_config = options[:config] if options[:config]
force_default_config! if options[:force_default_config]
end
def options_config=(options_config)
loaded_config = ConfigLoader.load_file(options_config)
@options_config = ConfigLoader.merge_with_default(loaded_config, options_config)
end
def force_default_config!
@options_config = ConfigLoader.default_configuration
end
def unvalidated
@validated = false
self
end
def for_file(file)
for_dir(File.dirname(file))
end
def for_pwd
for_dir(Dir.pwd)
end
# If type (file/dir) is known beforehand,
# prefer using #for_file or #for_dir for improved performance
def for(file_or_dir)
dir = if File.directory?(file_or_dir)
file_or_dir
else
File.dirname(file_or_dir)
end
for_dir(dir)
end
def for_dir(dir)
return @options_config if @options_config
@path_cache[dir] ||= ConfigLoader.configuration_file_for(dir)
path = @path_cache[dir]
@object_cache[path] ||= begin
print "For #{dir}: " if ConfigLoader.debug?
ConfigLoader.configuration_from_file(path, check: validated?)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/runner.rb | lib/rubocop/runner.rb | # frozen_string_literal: true
require 'parallel'
module RuboCop
# This class handles the processing of files, which includes dealing with
# formatters and letting cops inspect the files.
class Runner # rubocop:disable Metrics/ClassLength
# An exception indicating that the inspection loop got stuck correcting
# offenses back and forth.
class InfiniteCorrectionLoop < StandardError
attr_reader :offenses
def initialize(path, offenses_by_iteration, loop_start: -1)
@offenses = offenses_by_iteration.flatten.uniq
root_cause = offenses_by_iteration[loop_start..]
.map { |x| x.map(&:cop_name).uniq.join(', ') }
.join(' -> ')
message = 'Infinite loop detected'
message += " in #{path}" if path
message += " and caused by #{root_cause}" if root_cause
super(message)
end
end
class << self
# @return [Array<#call>]
def ruby_extractors
@ruby_extractors ||= [default_ruby_extractor]
end
private
# @return [#call]
def default_ruby_extractor
lambda do |processed_source|
[
{
offset: 0,
processed_source: processed_source
}
]
end
end
end
# @api private
MAX_ITERATIONS = 200
# @api private
REDUNDANT_COP_DISABLE_DIRECTIVE_RULES = %w[
Lint/RedundantCopDisableDirective RedundantCopDisableDirective Lint
].freeze
attr_reader :errors, :warnings
attr_writer :aborting
def initialize(options, config_store)
@options = options
@config_store = config_store
@errors = []
@warnings = []
@aborting = false
end
def run(paths)
# Compute the cache source checksum once to avoid potential
# inconsistencies between workers.
ResultCache.source_checksum
target_files = find_target_files(paths)
if @options[:list_target_files]
list_files(target_files)
else
warm_cache(target_files) if @options[:parallel]
inspect_files(target_files)
end
rescue Interrupt
self.aborting = true
warn ''
warn 'Exiting...'
false
end
def aborting?
@aborting
end
private
# Warms up the RuboCop cache by forking a suitable number of RuboCop
# instances that each inspects its allotted group of files.
def warm_cache(target_files)
saved_options = @options.dup
if target_files.length <= 1
puts 'Skipping parallel inspection: only a single file needs inspection' if @options[:debug]
return
end
puts 'Running parallel inspection' if @options[:debug]
%i[autocorrect safe_autocorrect].each { |opt| @options[opt] = false }
Parallel.each(target_files) { |target_file| file_offenses(target_file) }
ensure
@options = saved_options
end
def find_target_files(paths)
target_finder = TargetFinder.new(@config_store, @options)
mode = if @options[:only_recognized_file_types]
:only_recognized_file_types
else
:all_file_types
end
target_files = target_finder.find(paths, mode)
target_files.each(&:freeze).freeze
end
def inspect_files(files)
inspected_files = []
formatter_set.started(files)
each_inspected_file(files) { |file| inspected_files << file }
ensure
# OPTIMIZE: Calling `ResultCache.cleanup` takes time. This optimization
# mainly targets editors that integrates RuboCop. When RuboCop is run
# by an editor, it should be inspecting only one file.
if files.size > 1 && cached_run?
ResultCache.cleanup(@config_store, @options[:debug], @options[:cache_root])
end
formatter_set.finished(inspected_files.freeze)
formatter_set.close_output_files
end
def each_inspected_file(files)
files.reduce(true) do |all_passed, file|
offenses = process_file(file)
yield file
if offenses.any? { |o| considered_failure?(o) && offense_displayed?(o) }
break false if @options[:fail_fast]
next false
end
all_passed
end
end
def list_files(paths)
paths.each { |path| puts PathUtil.relative_path(path) }
end
def process_file(file)
file_started(file)
offenses = file_offenses(file)
rescue InfiniteCorrectionLoop => e
raise e if @options[:raise_cop_error]
errors << e
warn Rainbow(e.message).red
offenses = e.offenses.compact.sort.freeze
ensure
file_finished(file, offenses || [])
end
def file_offenses(file)
file_offense_cache(file) do
source, offenses = do_inspection_loop(file)
offenses = add_redundant_disables(file, offenses.compact.sort, source)
offenses.sort.reject(&:disabled?).freeze
end
end
def cached_result(file, team)
ResultCache.new(file, team, @options, @config_store)
end
def file_offense_cache(file)
config = @config_store.for_file(file)
cache = cached_result(file, standby_team(config)) if cached_run?
if cache&.valid?
offenses = cache.load
# If we're running --autocorrect and the cache says there are
# offenses, we need to actually inspect the file. If the cache shows no
# offenses, we're good.
real_run_needed = @options[:autocorrect] && offenses.any?
else
real_run_needed = true
end
if real_run_needed
offenses = yield
save_in_cache(cache, offenses)
end
offenses
end
def add_redundant_disables(file, offenses, source)
team_for_redundant_disables(file, offenses, source) do |team|
new_offenses, redundant_updated = inspect_file(source, team)
offenses += new_offenses
if redundant_updated
# Do one extra inspection loop if any redundant disables were
# removed. This is done in order to find rubocop:enable directives that
# have now become useless.
_source, new_offenses = do_inspection_loop(file)
offenses |= new_offenses
end
end
offenses
end
def team_for_redundant_disables(file, offenses, source)
return unless check_for_redundant_disables?(source)
config = @config_store.for_file(file)
team = Cop::Team.mobilize([Cop::Lint::RedundantCopDisableDirective], config, @options)
return if team.cops.empty?
team.cops.first.offenses_to_check = offenses
yield team
end
def check_for_redundant_disables?(source)
return false if source.disabled_line_ranges.empty? || except_redundant_cop_disable_directive?
!@options[:only]
end
def redundant_cop_disable_directive(file)
config = @config_store.for_file(file)
return unless config.for_cop(Cop::Lint::RedundantCopDisableDirective).fetch('Enabled')
cop = Cop::Lint::RedundantCopDisableDirective.new(config, @options)
yield cop if cop.relevant_file?(file)
end
def except_redundant_cop_disable_directive?
@options[:except] && (@options[:except] & REDUNDANT_COP_DISABLE_DIRECTIVE_RULES).any?
end
def file_started(file)
puts "Scanning #{file}" if @options[:debug]
formatter_set.file_started(file, cli_options: @options, config_store: @config_store)
end
def file_finished(file, offenses)
offenses = offenses_to_report(offenses)
formatter_set.file_finished(file, offenses)
end
def cached_run?
@cached_run ||=
(@options[:cache] == 'true' ||
(@options[:cache] != 'false' && @config_store.for_pwd.for_all_cops['UseCache'])) &&
# When running --auto-gen-config, there's some processing done in the
# cops related to calculating the Max parameters for Metrics cops. We
# need to do that processing and cannot use caching.
!@options[:auto_gen_config] &&
# We can't cache results from code which is piped in to stdin
!@options[:stdin]
end
def save_in_cache(cache, offenses)
return unless cache
# Caching results when a cop has crashed would prevent the crash in the
# next run, since the cop would not be called then. We want crashes to
# show up the same in each run.
return if errors.any? || warnings.any?
cache.save(offenses)
end
def do_inspection_loop(file)
# We can reuse the prism result since the source did not change yet.
processed_source = get_processed_source(file, @prism_result)
# This variable is 2d array used to track corrected offenses after each
# inspection iteration. This is used to output meaningful infinite loop
# error message.
offenses_by_iteration = []
# When running with --autocorrect, we need to inspect the file (which
# includes writing a corrected version of it) until no more corrections
# are made. This is because automatic corrections can introduce new
# offenses. In the normal case the loop is only executed once.
iterate_until_no_changes(processed_source, offenses_by_iteration) do
# The offenses that couldn't be corrected will be found again so we
# only keep the corrected ones in order to avoid duplicate reporting.
!offenses_by_iteration.empty? && offenses_by_iteration.last.select!(&:corrected?)
new_offenses, updated_source_file = inspect_file(processed_source)
offenses_by_iteration.push(new_offenses)
# We have to reprocess the source to pickup the changes. Since the
# change could (theoretically) introduce parsing errors, we break the
# loop if we find any.
break unless updated_source_file
# Autocorrect has happened, don't use the prism result since it is stale.
processed_source = get_processed_source(file, nil)
end
# Return summary of corrected offenses after all iterations
offenses = offenses_by_iteration.flatten.uniq
[processed_source, offenses]
end
def iterate_until_no_changes(source, offenses_by_iteration)
# Keep track of the state of the source. If a cop modifies the source
# and another cop undoes it producing identical source we have an
# infinite loop.
@processed_sources = []
# It is also possible for a cop to keep adding indefinitely to a file,
# making it bigger and bigger. If the inspection loop runs for an
# excessively high number of iterations, this is likely happening.
iterations = 0
loop do
check_for_infinite_loop(source, offenses_by_iteration)
if (iterations += 1) > MAX_ITERATIONS
raise InfiniteCorrectionLoop.new(source.path, offenses_by_iteration)
end
source = yield
break unless source
end
end
# Check whether a run created source identical to a previous run, which
# means that we definitely have an infinite loop.
def check_for_infinite_loop(processed_source, offenses_by_iteration)
checksum = processed_source.checksum
if (loop_start_index = @processed_sources.index(checksum))
raise InfiniteCorrectionLoop.new(
processed_source.path,
offenses_by_iteration,
loop_start: loop_start_index
)
end
@processed_sources << checksum
end
def inspect_file(processed_source, team = mobilize_team(processed_source))
extracted_ruby_sources = extract_ruby_sources(processed_source)
offenses = extracted_ruby_sources.flat_map do |extracted_ruby_source|
report = team.investigate(
extracted_ruby_source[:processed_source],
offset: extracted_ruby_source[:offset],
original: processed_source
)
@errors.concat(team.errors)
@warnings.concat(team.warnings)
report.offenses
end
[offenses, team.updated_source_file?]
end
def extract_ruby_sources(processed_source)
self.class.ruby_extractors.find do |ruby_extractor|
result = ruby_extractor.call(processed_source)
break result if result
rescue StandardError
location = if ruby_extractor.is_a?(Proc)
ruby_extractor.source_location
else
ruby_extractor.method(:call).source_location
end
raise Error, "Ruby extractor #{location[0]} failed to process #{processed_source.path}."
end
end
def mobilize_team(processed_source)
config = @config_store.for_file(processed_source.path)
Cop::Team.mobilize(mobilized_cop_classes(config), config, @options)
end
def mobilized_cop_classes(config) # rubocop:disable Metrics/AbcSize
@mobilized_cop_classes ||= {}.compare_by_identity
@mobilized_cop_classes[config] ||= begin
cop_classes = Cop::Registry.all
# `@options[:only]` and `@options[:except]` are not qualified until
# needed so that the Registry can be fully loaded, including any
# cops added by `require`s.
qualify_option_cop_names
OptionsValidator.new(@options).validate_cop_options
if @options[:only]
cop_classes.select! { |c| c.match?(@options[:only]) }
else
filter_cop_classes(cop_classes, config)
end
cop_classes.reject! { |c| c.match?(@options[:except]) }
Cop::Registry.new(cop_classes, @options)
end
end
def qualify_option_cop_names
%i[only except].each do |option|
next unless @options[option]
@options[option].map! do |cop_name|
Cop::Registry.qualified_cop_name(cop_name, "--#{option} option")
end
end
end
def filter_cop_classes(cop_classes, config)
# use only cops that link to a style guide if requested
return unless style_guide_cops_only?(config)
cop_classes.select! { |cop| config.for_cop(cop)['StyleGuide'] }
end
def style_guide_cops_only?(config)
@options[:only_guide_cops] || config.for_all_cops['StyleGuideCopsOnly']
end
def formatter_set
@formatter_set ||= begin
set = Formatter::FormatterSet.new(@options)
pairs = @options[:formatters] || [['progress']]
pairs.each { |formatter_key, output_path| set.add_formatter(formatter_key, output_path) }
set
end
end
def considered_failure?(offense)
return false if offense.disabled?
# For :autocorrect level, any correctable offense is a failure, regardless of severity
return true if @options[:fail_level] == :autocorrect && offense.correctable?
!offense.corrected? && offense.severity >= minimum_severity_to_fail
end
def offense_displayed?(offense)
if @options[:display_only_fail_level_offenses]
considered_failure?(offense)
elsif @options[:display_only_safe_correctable]
supports_safe_autocorrect?(offense)
elsif @options[:display_only_correctable]
offense.correctable?
else
true
end
end
def offenses_to_report(offenses)
offenses.select { |o| offense_displayed?(o) }
end
def supports_safe_autocorrect?(offense)
cop_class = Cop::Registry.global.find_by_cop_name(offense.cop_name)
default_cfg = default_config(offense.cop_name)
offense.correctable? &&
cop_class&.support_autocorrect? && mark_as_safe_by_config?(default_cfg)
end
def mark_as_safe_by_config?(config)
config.nil? || (config.fetch('Safe', true) && config.fetch('SafeAutoCorrect', true))
end
def default_config(cop_name)
RuboCop::ConfigLoader.default_configuration[cop_name]
end
def minimum_severity_to_fail
@minimum_severity_to_fail ||= begin
# Unless given explicitly as `fail_level`, `:info` severity offenses do not fail
name = @options[:fail_level] || :refactor
# autocorrect is a fake level - use the default
RuboCop::Cop::Severity.new(name == :autocorrect ? :refactor : name)
end
end
# rubocop:disable Metrics/MethodLength
def get_processed_source(file, prism_result)
config = @config_store.for_file(file)
ruby_version = config.target_ruby_version
parser_engine = config.parser_engine
processed_source = if @options[:stdin]
ProcessedSource.new(
@options[:stdin],
ruby_version,
file,
parser_engine: parser_engine,
prism_result: prism_result
)
else
begin
ProcessedSource.from_file(
file, ruby_version, parser_engine: parser_engine
)
rescue Errno::ENOENT
raise RuboCop::Error, "No such file or directory: #{file}"
end
end
processed_source.config = config
processed_source.registry = mobilized_cop_classes(config)
processed_source
end
# rubocop:enable Metrics/MethodLength
# A Cop::Team instance is stateful and may change when inspecting.
# The "standby" team for a given config is an initialized but
# otherwise dormant team that can be used for config- and option-
# level caching in ResultCache.
def standby_team(config)
@team_by_config ||= {}.compare_by_identity
@team_by_config[config] ||=
Cop::Team.mobilize(mobilized_cop_classes(config), config, @options)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/magic_comment.rb | lib/rubocop/magic_comment.rb | # frozen_string_literal: true
module RuboCop
# Parse different formats of magic comments.
#
# @abstract parent of three different magic comment handlers
class MagicComment
# IRB's pattern for matching magic comment tokens.
# @see https://github.com/ruby/ruby/blob/b4a55c1/lib/irb/magic-file.rb#L5
TOKEN = '(?<token>[[:alnum:]\-_]+)'
KEYWORDS = {
encoding: '(?:en)?coding',
frozen_string_literal: 'frozen[_-]string[_-]literal',
rbs_inline: 'rbs_inline',
shareable_constant_value: 'shareable[_-]constant[_-]value',
typed: 'typed'
}.freeze
# Detect magic comment format and pass it to the appropriate wrapper.
#
# @param comment [String]
#
# @return [RuboCop::MagicComment]
def self.parse(comment)
case comment
when EmacsComment::REGEXP then EmacsComment.new(comment)
when VimComment::REGEXP then VimComment.new(comment)
else
SimpleComment.new(comment)
end
end
def initialize(comment)
@comment = comment
end
def any?
frozen_string_literal_specified? ||
encoding_specified? ||
rbs_inline_specified? ||
shareable_constant_value_specified? ||
typed_specified?
end
def valid?
@comment.start_with?('#') && any?
end
# Does the magic comment enable the frozen string literal feature.
#
# Test whether the frozen string literal value is `true`. Cannot
# just return `frozen_string_literal` since an invalid magic comment
# like `# frozen_string_literal: yes` is possible and the truthy value
# `'yes'` does not actually enable the feature
#
# @return [Boolean]
def frozen_string_literal?
frozen_string_literal == true
end
def valid_literal_value?
[true, false].include?(frozen_string_literal)
end
def valid_rbs_inline_value?
%w[enabled disabled].include?(extract_rbs_inline_value)
end
def valid_shareable_constant_value?
%w[none literal experimental_everything experimental_copy].include?(shareable_constant_value)
end
# Was a magic comment for the frozen string literal found?
#
# @return [Boolean]
def frozen_string_literal_specified?
specified?(frozen_string_literal)
end
# Was a shareable_constant_value specified?
#
# @return [Boolean]
def shareable_constant_value_specified?
specified?(shareable_constant_value)
end
# Expose the `frozen_string_literal` value coerced to a boolean if possible.
#
# @return [Boolean] if value is `true` or `false` in any case
# @return [nil] if frozen_string_literal comment isn't found
# @return [String] if comment is found but isn't true or false
def frozen_string_literal
return unless (setting = extract_frozen_string_literal)
case setting.downcase
when 'true' then true
when 'false' then false
else
setting
end
end
# Expose the `shareable_constant_value` value coerced to a boolean if possible.
#
# @return [String] for shareable_constant_value config
def shareable_constant_value
extract_shareable_constant_value
end
def encoding_specified?
specified?(encoding)
end
def rbs_inline_specified?
valid_rbs_inline_value?
end
# Was the Sorbet `typed` sigil specified?
#
# @return [Boolean]
def typed_specified?
specified?(extract_typed)
end
def typed
extract_typed
end
private
def specified?(value)
!value.nil?
end
# Match the entire comment string with a pattern and take the first capture.
#
# @param pattern [Regexp]
#
# @return [String] if pattern matched
# @return [nil] otherwise
def extract(pattern)
@comment[pattern, :token]
end
# Parent to Vim and Emacs magic comment handling.
#
# @abstract
class EditorComment < MagicComment
def encoding
match(self.class::KEYWORDS[:encoding])
end
# Rewrite the comment without a given token type
def without(type)
remaining = tokens.grep_v(/\A#{self.class::KEYWORDS[type.to_sym]}/)
return '' if remaining.empty?
self.class::FORMAT % remaining.join(self.class::SEPARATOR)
end
private
# Find a token starting with the provided keyword and extract its value.
#
# @param keyword [String]
#
# @return [String] extracted value if it is found
# @return [nil] otherwise
def match(keyword)
pattern = /\A#{keyword}\s*#{self.class::OPERATOR}\s*#{TOKEN}\z/
tokens.each do |token|
next unless (value = token[pattern, :token])
return value.downcase
end
nil
end
# Individual tokens composing an editor specific comment string.
#
# @return [Array<String>]
def tokens
extract(self.class::REGEXP).split(self.class::SEPARATOR).map(&:strip)
end
end
# Wrapper for Emacs style magic comments.
#
# @example Emacs style comment
# comment = RuboCop::MagicComment.parse(
# '# -*- encoding: ASCII-8BIT -*-'
# )
#
# comment.encoding # => 'ascii-8bit'
#
# @see https://www.gnu.org/software/emacs/manual/html_node/emacs/Specify-Coding.html
# @see https://github.com/ruby/ruby/blob/3f306dc/parse.y#L6873-L6892 Emacs handling in parse.y
class EmacsComment < EditorComment
REGEXP = /-\*-(?<token>.+)-\*-/.freeze
FORMAT = '# -*- %s -*-'
SEPARATOR = ';'
OPERATOR = ':'
def new_frozen_string_literal(value)
"# -*- frozen_string_literal: #{value} -*-"
end
private
def extract_frozen_string_literal
match(KEYWORDS[:frozen_string_literal])
end
# Emacs comments cannot specify RBS::inline behavior.
def extract_rbs_inline_value; end
def extract_shareable_constant_value
match(KEYWORDS[:shareable_constant_value])
end
# Emacs comments cannot specify Sorbet typechecking behavior.
def extract_typed; end
end
# Wrapper for Vim style magic comments.
#
# @example Vim style comment
# comment = RuboCop::MagicComment.parse(
# '# vim: filetype=ruby, fileencoding=ascii-8bit'
# )
#
# comment.encoding # => 'ascii-8bit'
class VimComment < EditorComment
REGEXP = /#\s*vim:\s*(?<token>.+)/.freeze
FORMAT = '# vim: %s'
SEPARATOR = ', '
OPERATOR = '='
KEYWORDS = MagicComment::KEYWORDS.merge(encoding: 'fileencoding').freeze
# For some reason the fileencoding keyword only works if there
# is at least one other token included in the string. For example
#
# # works
# # vim: foo=bar, fileencoding=ascii-8bit
#
# # does nothing
# # vim: foo=bar, fileencoding=ascii-8bit
#
def encoding
super if tokens.size > 1
end
# Vim comments cannot specify frozen string literal behavior.
def frozen_string_literal; end
# Vim comments cannot specify RBS::inline behavior.
def extract_rbs_inline_value; end
# Vim comments cannot specify shareable constant values behavior.
def shareable_constant_value; end
# Vim comments cannot specify Sorbet typechecking behavior.
def extract_typed; end
end
# Wrapper for regular magic comments not bound to an editor.
#
# Simple comments can only specify one setting per comment.
#
# @example frozen string literal comments
# comment1 = RuboCop::MagicComment.parse('# frozen_string_literal: true')
# comment1.frozen_string_literal # => true
# comment1.encoding # => nil
#
# @example encoding comments
# comment2 = RuboCop::MagicComment.parse('# encoding: utf-8')
# comment2.frozen_string_literal # => nil
# comment2.encoding # => 'utf-8'
class SimpleComment < MagicComment
FSTRING_LITERAL_COMMENT = 'frozen_string_literal:\s*(true|false)'
# Match `encoding` or `coding`
def encoding
extract(/\A\s*\#\s*(#{FSTRING_LITERAL_COMMENT})?\s*#{KEYWORDS[:encoding]}: (#{TOKEN})/io)
end
# Rewrite the comment without a given token type
def without(type)
if @comment.match?(/\A#\s*#{self.class::KEYWORDS[type.to_sym]}/io)
''
else
@comment
end
end
def new_frozen_string_literal(value)
"# frozen_string_literal: #{value}"
end
private
# Extract `frozen_string_literal`.
#
# The `frozen_string_literal` magic comment only works if it
# is the only text in the comment.
#
# Case-insensitive and dashes/underscores are acceptable.
# @see https://github.com/ruby/ruby/blob/78b95b49f8/parse.y#L7134-L7138
def extract_frozen_string_literal
extract(/\A\s*#\s*#{KEYWORDS[:frozen_string_literal]}:\s*#{TOKEN}\s*\z/io)
end
def extract_rbs_inline_value
extract(/\A\s*#\s*#{KEYWORDS[:rbs_inline]}:\s*#{TOKEN}\s*\z/io)
end
def extract_shareable_constant_value
extract(/\A\s*#\s*#{KEYWORDS[:shareable_constant_value]}:\s*#{TOKEN}\s*\z/io)
end
def extract_typed
extract(/\A\s*#\s*#{KEYWORDS[:typed]}:\s*#{TOKEN}\s*\z/io)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/string_interpreter.rb | lib/rubocop/string_interpreter.rb | # frozen_string_literal: true
module RuboCop
# Take a string with embedded escapes, and convert the escapes as the Ruby
# interpreter would when reading a double-quoted string literal.
# For example, "\\n" will be converted to "\n".
class StringInterpreter
STRING_ESCAPES = {
'\a' => "\a", '\b' => "\b", '\e' => "\e", '\f' => "\f", '\n' => "\n",
'\r' => "\r", '\s' => ' ', '\t' => "\t", '\v' => "\v", "\\\n" => ''
}.freeze
STRING_ESCAPE_REGEX = /\\(?:
[abefnrstv\n] | # simple escapes (above)
\d{1,3} | # octal byte escape
x[0-9a-fA-F]{1,2} | # hex byte escape
u[0-9a-fA-F]{4} | # unicode char escape
u\{[^}]*\} | # extended unicode escape
. # any other escaped char
)/x.freeze
private_constant :STRING_ESCAPES, :STRING_ESCAPE_REGEX
class << self
def interpret(string)
# We currently don't handle \cx, \C-x, and \M-x
string.gsub(STRING_ESCAPE_REGEX) do |escape|
STRING_ESCAPES[escape] || interpret_string_escape(escape)
end
end
private
def interpret_string_escape(escape)
case escape[1]
when 'u' then interpret_unicode(escape)
when 'x' then interpret_hex(escape)
when /\d/ then interpret_octal(escape)
else
escape[1] # literal escaped char, like \\
end
end
def interpret_unicode(escape)
if escape[2] == '{'
escape[3..].split(/\s+/).map(&:hex).pack('U*')
else
[escape[2..].hex].pack('U')
end
end
def interpret_hex(escape)
[escape[2..].hex].pack('C')
end
def interpret_octal(escape)
[escape[1..].to_i(8)].pack('C')
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/target_ruby.rb | lib/rubocop/target_ruby.rb | # frozen_string_literal: true
module RuboCop
# The kind of Ruby that code inspected by RuboCop is written in.
# @api private
class TargetRuby
KNOWN_RUBIES = [
2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, 4.0, 4.1
].freeze
DEFAULT_VERSION = 2.7
OBSOLETE_RUBIES = {
1.9 => '0.41',
2.0 => '0.50',
2.1 => '0.57',
2.2 => '0.68',
2.3 => '0.81',
2.4 => '1.12',
2.5 => '1.28',
2.6 => '1.50'
}.freeze
private_constant :KNOWN_RUBIES, :OBSOLETE_RUBIES
# A place where information about a target ruby version is found.
# @api private
class Source
attr_reader :version, :name
def initialize(config)
@config = config
@version = find_version
end
def to_s
name
end
end
# The target ruby version may be configured by setting the
# `RUBOCOP_TARGET_RUBY_VERSION` environment variable.
class RuboCopEnvVar < Source
def name
'`RUBOCOP_TARGET_RUBY_VERSION` environment variable'
end
private
def find_version
ENV.fetch('RUBOCOP_TARGET_RUBY_VERSION', nil)&.to_f
end
end
# The target ruby version may be configured in RuboCop's config.
# @api private
class RuboCopConfig < Source
def name
"`TargetRubyVersion` parameter (in #{@config.smart_loaded_path})"
end
private
def find_version
@config.for_all_cops['TargetRubyVersion']&.to_f
end
end
# The target ruby version may be found in a .gemspec file.
# @api private
class GemspecFile < Source
extend NodePattern::Macros
# @!method required_ruby_version(node)
def_node_search :required_ruby_version, <<~PATTERN
(send _ :required_ruby_version= $_)
PATTERN
# @!method gem_requirement_versions(node)
def_node_matcher :gem_requirement_versions, <<~PATTERN
(send (const(const _ :Gem):Requirement) :new
{$str+ | (send $str :freeze)+ | (array $str+) | (array (send $str :freeze)+)}
)
PATTERN
def name
"`required_ruby_version` parameter (in #{gemspec_filepath})"
end
private
def find_version
file = gemspec_filepath
return unless file && File.file?(file)
right_hand_side = version_from_gemspec_file(file)
return if right_hand_side.nil?
find_minimal_known_ruby(right_hand_side)
end
def gemspec_filepath
return @gemspec_filepath if defined?(@gemspec_filepath)
@gemspec_filepath =
@config.traverse_directories_upwards(@config.base_dir_for_path_parameters) do |dir|
# NOTE: Can't use `dir.glob` because of JRuby 9.4.8.0 incompatibility:
# https://github.com/jruby/jruby/issues/8358
candidates = Pathname.glob("#{dir}/*.gemspec")
# Bundler will use a gemspec whatever the filename is, as long as its the only one in
# the folder.
break candidates.first if candidates.one?
end
end
def version_from_gemspec_file(file)
# When using parser_prism, we need to use a Ruby version that Prism supports (3.3+)
# for parsing the gemspec file. This doesn't affect the detected Ruby version,
# it's just for the parsing step.
ruby_version_for_parsing = if @config.parser_engine == :parser_prism
3.3
else
DEFAULT_VERSION
end
processed_source = ProcessedSource.from_file(
file, ruby_version_for_parsing, parser_engine: @config.parser_engine
)
return unless processed_source.valid_syntax?
required_ruby_version(processed_source.ast).first
end
def version_from_right_hand_side(right_hand_side)
gem_requirement_versions = gem_requirement_versions(right_hand_side)
if right_hand_side.array_type? && right_hand_side.children.all?(&:str_type?)
version_from_array(right_hand_side)
elsif gem_requirement_versions
gem_requirement_versions.map(&:value)
elsif right_hand_side.str_type?
right_hand_side.value
end
end
def version_from_array(array)
array.children.map(&:value)
end
def find_minimal_known_ruby(right_hand_side)
version = version_from_right_hand_side(right_hand_side)
return unless version
requirement = Gem::Requirement.new(version)
KNOWN_RUBIES.detect do |v|
requirement.satisfied_by?(Gem::Version.new("#{v}.99"))
end
end
end
# The target ruby version may be found in a .ruby-version file.
# @api private
class RubyVersionFile < Source
RUBY_VERSION_FILENAME = '.ruby-version'
RUBY_VERSION_PATTERN = /\A(?:ruby-)?(?<version>\d+\.\d+)/.freeze
def name
"`#{RUBY_VERSION_FILENAME}`"
end
private
def filename
RUBY_VERSION_FILENAME
end
def pattern
RUBY_VERSION_PATTERN
end
def find_version
file = version_file
return unless file && File.file?(file)
File.read(file).match(pattern) { |md| md[:version].to_f }
end
def version_file
@version_file ||= @config.find_file_upwards(filename, @config.base_dir_for_path_parameters)
end
end
# The target ruby version may be found in a .tool-versions file, in a line
# starting with `ruby`.
# @api private
class ToolVersionsFile < RubyVersionFile
TOOL_VERSIONS_FILENAME = '.tool-versions'
TOOL_VERSIONS_PATTERN = /^(?:ruby )(?<version>\d+\.\d+)/.freeze
def name
"`#{TOOL_VERSIONS_FILENAME}`"
end
private
def filename
TOOL_VERSIONS_FILENAME
end
def pattern
TOOL_VERSIONS_PATTERN
end
end
# The lock file of Bundler may identify the target ruby version.
# @api private
class BundlerLockFile < Source
def name
"`#{bundler_lock_file_path}`"
end
private
def find_version
lock_file_path = bundler_lock_file_path
return nil unless lock_file_path
in_ruby_section = false
File.foreach(lock_file_path) do |line|
# If ruby is in Gemfile.lock or gems.lock, there should be two lines
# towards the bottom of the file that look like:
# RUBY VERSION
# ruby W.X.YpZ
# We ultimately want to match the "ruby W.X.Y.pZ" line, but there's
# extra logic to make sure we only start looking once we've seen the
# "RUBY VERSION" line.
in_ruby_section ||= line.match(/^\s*RUBY\s*VERSION\s*$/)
next unless in_ruby_section
# We currently only allow this feature to work with MRI ruby. If
# jruby (or something else) is used by the project, it's lock file
# will have a line that looks like:
# RUBY VERSION
# ruby W.X.YpZ (jruby x.x.x.x)
# The regex won't match in this situation.
result = line.match(/^\s*ruby\s+(\d+\.\d+)[p.\d]*\s*$/)
return result.captures.first.to_f if result
end
end
def bundler_lock_file_path
@config.bundler_lock_file_path
end
end
# If all else fails, a default version will be picked.
# @api private
class Default < Source
def name
'default'
end
private
def find_version
DEFAULT_VERSION
end
end
def self.supported_versions
KNOWN_RUBIES
end
SOURCES = [
RuboCopEnvVar,
RuboCopConfig,
GemspecFile,
RubyVersionFile,
ToolVersionsFile,
BundlerLockFile,
Default
].freeze
private_constant :SOURCES
def initialize(config)
@config = config
end
def source
@source ||= SOURCES.each.lazy.map { |c| c.new(@config) }.detect(&:version)
end
def version
source.version
end
def supported?
KNOWN_RUBIES.include?(version)
end
def rubocop_version_with_support
if supported?
RuboCop::Version::STRING
else
OBSOLETE_RUBIES[version]
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cli.rb | lib/rubocop/cli.rb | # frozen_string_literal: true
require 'fileutils'
module RuboCop
# The CLI is a class responsible of handling all the command line interface
# logic.
class CLI
STATUS_SUCCESS = 0
STATUS_OFFENSES = 1
STATUS_ERROR = 2
STATUS_INTERRUPTED = Signal.list['INT'] + 128
DEFAULT_PARALLEL_OPTIONS = %i[
color config debug display_style_guide display_time display_only_fail_level_offenses
display_only_failed editor_mode except extra_details fail_level fix_layout format formatters
ignore_disable_comments lint only only_guide_cops require safe
autocorrect safe_autocorrect autocorrect_all
].freeze
class Finished < StandardError; end
attr_reader :options, :config_store
def initialize
@options = {}
@config_store = ConfigStore.new
end
# @api public
#
# Entry point for the application logic. Here we
# do the command line arguments processing and inspect
# the target files.
#
# @param args [Array<String>] command line arguments
# @return [Integer] UNIX exit code
#
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize
def run(args = ARGV)
time_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
@options, paths = Options.new.parse(args)
@env = Environment.new(@options, @config_store, paths)
profile_if_needed do
if @options[:init]
run_command(:init)
else
act_on_options
validate_options_vs_config
parallel_by_default!
apply_default_formatter
report_pending_cops
execute_runners
end
end
rescue ConfigNotFoundError, IncorrectCopNameError, OptionArgumentError => e
warn Rainbow(e.message).red
STATUS_ERROR
rescue RuboCop::Error => e
warn Rainbow("Error: #{e.message}").red
STATUS_ERROR
rescue Interrupt
warn ''
warn 'Exiting...'
STATUS_INTERRUPTED
rescue Finished
STATUS_SUCCESS
rescue OptionParser::ParseError => e
warn e.message
warn 'For usage information, use --help'
STATUS_ERROR
rescue StandardError, SyntaxError, LoadError => e
warn e.message
warn e.backtrace
STATUS_ERROR
ensure
elapsed_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - time_start
puts "Finished in #{elapsed_time} seconds" if @options[:debug] || @options[:display_time]
end
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
private
# rubocop:disable Metrics/MethodLength, Metrics/AbcSize
def profile_if_needed
return yield unless @options[:profile]
return STATUS_ERROR unless require_gem('stackprof')
with_memory = @options[:memory]
if with_memory
return STATUS_ERROR unless require_gem('memory_profiler')
MemoryProfiler.start
end
tmp_dir = File.join(ConfigFinder.project_root, 'tmp')
FileUtils.mkdir_p(tmp_dir)
cpu_profile_file = File.join(tmp_dir, 'rubocop-stackprof.dump')
status = nil
StackProf.run(out: cpu_profile_file) do
status = yield
end
puts "Profile report generated at #{cpu_profile_file}"
if with_memory
puts 'Building memory report...'
report = MemoryProfiler.stop
memory_profile_file = File.join(tmp_dir, 'rubocop-memory_profiler.txt')
report.pretty_print(to_file: memory_profile_file, scale_bytes: true)
puts "Memory report generated at #{memory_profile_file}"
end
status
end
# rubocop:enable Metrics/MethodLength, Metrics/AbcSize
def require_gem(name)
require name
true
rescue LoadError
warn("You don't have #{name} installed. Add it to your Gemfile and run `bundle install`")
false
end
def run_command(name)
@env.run(name)
end
def execute_runners
if @options[:auto_gen_config]
run_command(:auto_gen_config)
else
run_command(:execute_runner).tap { suggest_extensions }
end
end
def suggest_extensions
run_command(:suggest_extensions)
end
def validate_options_vs_config
return unless @options[:parallel] && !@config_store.for_pwd.for_all_cops['UseCache']
raise OptionArgumentError, '-P/--parallel uses caching to speed up execution, so combining ' \
'with AllCops: UseCache: false is not allowed.'
end
def parallel_by_default!
# See https://github.com/rubocop/rubocop/pull/4537 for JRuby and Windows constraints.
return if RUBY_ENGINE != 'ruby' || RuboCop::Platform.windows?
if (@options.keys - DEFAULT_PARALLEL_OPTIONS).empty? &&
@config_store.for_pwd.for_all_cops['UseCache'] != false
puts 'Use parallel by default.' if @options[:debug]
@options[:parallel] = true
end
end
def act_on_options
set_options_to_config_loader
set_options_to_pending_cops_reporter
handle_editor_mode
@config_store.apply_options!(@options)
# Set cache root after apply_options! to ensure force_default_config is applied first.
ConfigLoader.cache_root = ResultCache.cache_root(@config_store, @options[:cache_root])
handle_exiting_options
if @options[:color]
# color output explicitly forced on
Rainbow.enabled = true
elsif @options[:color] == false
# color output explicitly forced off
Rainbow.enabled = false
end
end
def set_options_to_config_loader
ConfigLoader.debug = @options[:debug]
ConfigLoader.disable_pending_cops = @options[:disable_pending_cops]
ConfigLoader.enable_pending_cops = @options[:enable_pending_cops]
ConfigLoader.ignore_parent_exclusion = @options[:ignore_parent_exclusion]
ConfigLoader.ignore_unrecognized_cops = @options[:ignore_unrecognized_cops]
end
def set_options_to_pending_cops_reporter
PendingCopsReporter.disable_pending_cops = @options[:disable_pending_cops]
PendingCopsReporter.enable_pending_cops = @options[:enable_pending_cops]
end
def handle_editor_mode
RuboCop::LSP.enable if @options[:editor_mode]
end
# rubocop:disable Metrics/CyclomaticComplexity
def handle_exiting_options
return unless Options::EXITING_OPTIONS.any? { |o| @options.key? o }
run_command(:version) if @options[:version] || @options[:verbose_version]
run_command(:show_cops) if @options[:show_cops]
run_command(:show_docs_url) if @options[:show_docs_url]
run_command(:lsp) if @options[:lsp]
raise Finished
end
# rubocop:enable Metrics/CyclomaticComplexity
def apply_default_formatter
# This must be done after the options have already been processed,
# because they can affect how ConfigStore behaves
@options[:formatters] ||= begin
if @options[:auto_gen_config]
formatter = 'autogenconf'
else
cfg = @config_store.for_pwd.for_all_cops
formatter = cfg['DefaultFormatter'] || 'progress'
end
[[formatter, @options[:output_path]]]
end
end
def report_pending_cops
PendingCopsReporter.warn_if_needed(@config_store.for_pwd)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/file_patterns.rb | lib/rubocop/file_patterns.rb | # frozen_string_literal: true
module RuboCop
# A wrapper around patterns array to perform optimized search.
#
# For projects with a large set of rubocop todo files, most items in `Exclude`/`Include`
# are exact file names. It is wasteful to linearly check the list of patterns over and over
# to check if the file is relevant to the cop.
#
# This class partitions an array of patterns into a set of exact match strings and the rest
# of the patterns. This way we can firstly do a cheap check in the set and then proceed via
# the costly patterns check, if needed.
# @api private
class FilePatterns
@cache = {}.compare_by_identity
def self.from(patterns)
@cache[patterns] ||= new(patterns)
end
def initialize(patterns)
@strings = Set.new
@patterns = []
partition_patterns(patterns)
end
def match?(path)
@strings.include?(path) || @patterns.any? { |pattern| PathUtil.match_path?(pattern, path) }
end
private
def partition_patterns(patterns)
patterns.each do |pattern|
if pattern.is_a?(String) && !pattern.match?(/[*{\[?]/)
@strings << pattern
else
@patterns << pattern
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/directive_comment.rb | lib/rubocop/directive_comment.rb | # frozen_string_literal: true
module RuboCop
# This class wraps the `Parser::Source::Comment` object that represents a
# special `rubocop:disable` and `rubocop:enable` comment and exposes what
# cops it contains.
class DirectiveComment
# @api private
LINT_DEPARTMENT = 'Lint'
# @api private
LINT_REDUNDANT_DIRECTIVE_COP = "#{LINT_DEPARTMENT}/RedundantCopDisableDirective"
# @api private
LINT_SYNTAX_COP = "#{LINT_DEPARTMENT}/Syntax"
# @api private
COP_NAME_PATTERN = '([A-Za-z]\w+/)*(?:[A-Za-z]\w+)'
# @api private
COP_NAME_PATTERN_NC = '(?:[A-Za-z]\w+/)*[A-Za-z]\w+'
# @api private
COP_NAMES_PATTERN_NC = "(?:#{COP_NAME_PATTERN_NC} , )*#{COP_NAME_PATTERN_NC}"
# @api private
COP_NAMES_PATTERN = "(?:#{COP_NAME_PATTERN} , )*#{COP_NAME_PATTERN}"
# @api private
COPS_PATTERN = "(all|#{COP_NAMES_PATTERN})"
# @api private
PUSH_POP_ARGS_PATTERN = "([+\\-]#{COP_NAME_PATTERN_NC}(?:\\s+[+\\-]#{COP_NAME_PATTERN_NC})*)"
# @api private
AVAILABLE_MODES = %w[disable enable todo push pop].freeze
# @api private
DIRECTIVE_MARKER_PATTERN = '# rubocop : '
# @api private
DIRECTIVE_MARKER_REGEXP = Regexp.new(DIRECTIVE_MARKER_PATTERN.gsub(' ', '\s*'))
# @api private
DIRECTIVE_HEADER_PATTERN = "#{DIRECTIVE_MARKER_PATTERN}((?:#{AVAILABLE_MODES.join('|')}))\\b"
# @api private
DIRECTIVE_COMMENT_REGEXP = Regexp.new(
"#{DIRECTIVE_HEADER_PATTERN}(?:\\s+#{COPS_PATTERN}|\\s+#{PUSH_POP_ARGS_PATTERN})?"
.gsub(' ', '\s*')
)
# @api private
TRAILING_COMMENT_MARKER = '--'
# @api private
MALFORMED_DIRECTIVE_WITHOUT_COP_NAME_REGEXP = Regexp.new(
"\\A#{DIRECTIVE_HEADER_PATTERN}\\s*\\z".gsub(' ', '\s*')
)
def self.before_comment(line)
line.split(DIRECTIVE_COMMENT_REGEXP).first
end
attr_reader :comment, :cop_registry, :mode, :cops
def initialize(comment, cop_registry = Cop::Registry.global)
@comment = comment
@cop_registry = cop_registry
@match_data = comment.text.match(DIRECTIVE_COMMENT_REGEXP)
@mode, @cops = match_captures
end
# Checks if the comment starts with `# rubocop:` marker
def start_with_marker?
comment.text.start_with?(DIRECTIVE_MARKER_REGEXP)
end
# Checks if the comment is malformed as a `# rubocop:` directive
def malformed?
return true if !start_with_marker? || @match_data.nil?
return true if missing_cop_name?
tail = @match_data.post_match.lstrip
!(tail.empty? || tail.start_with?(TRAILING_COMMENT_MARKER))
end
# Checks if the directive comment is missing a cop name
def missing_cop_name?
return false if push? || pop?
MALFORMED_DIRECTIVE_WITHOUT_COP_NAME_REGEXP.match?(comment.text)
end
# Checks if this directive relates to single line
def single_line?
!comment.text.start_with?(DIRECTIVE_COMMENT_REGEXP)
end
# Checks if this directive contains all the given cop names
def match?(cop_names)
parsed_cop_names.uniq.sort == cop_names.uniq.sort
end
def range
match = comment.text.match(DIRECTIVE_COMMENT_REGEXP)
begin_pos = comment.source_range.begin_pos
Parser::Source::Range.new(
comment.source_range.source_buffer, begin_pos + match.begin(0), begin_pos + match.end(0)
)
end
# Returns match captures to directive comment pattern
def match_captures
@match_captures ||= @match_data && begin
captures = @match_data.captures
mode = captures[0]
# COPS_PATTERN is at captures[1], PUSH_POP_ARGS_PATTERN is at captures[4]
cops = captures[1] || captures[4]
[mode, cops]
end
end
# Checks if this directive disables cops
def disabled?
%w[disable todo].include?(mode)
end
# Checks if this directive enables cops
def enabled?
mode == 'enable'
end
# Checks if this directive is a push
def push?
mode == 'push'
end
# Checks if this directive is a pop
def pop?
mode == 'pop'
end
# Returns the push arguments as a hash of cop names with their operations
def push_args
@push_args ||= parse_push_args
end
# Checks if this directive enables all cops
def enabled_all?
!disabled? && all_cops?
end
# Checks if this directive disables all cops
def disabled_all?
disabled? && all_cops?
end
# Checks if all cops specified in this directive
def all_cops?
cops == 'all'
end
# Returns array of specified in this directive cop names
def cop_names
@cop_names ||= all_cops? ? all_cop_names : parsed_cop_names
end
# Returns an array of cops for this directive comment, without resolving departments
def raw_cop_names
@raw_cop_names ||= (cops || '').split(/,\s*/)
end
# Returns array of specified in this directive department names
# when all department disabled
def department_names
raw_cop_names.select { |cop| department?(cop) }
end
# Checks if directive departments include cop
def in_directive_department?(cop)
department_names.any? { |department| cop.start_with?(department) }
end
# Checks if cop department has already used in directive comment
def overridden_by_department?(cop)
in_directive_department?(cop) && raw_cop_names.include?(cop)
end
def directive_count
raw_cop_names.count
end
# Returns line number for directive
def line_number
comment.source_range.line
end
private
def parsed_cop_names
cops = raw_cop_names.map do |name|
department?(name) ? cop_names_for_department(name) : name
end.flatten
cops - [LINT_SYNTAX_COP]
end
def department?(name)
cop_registry.department?(name)
end
def all_cop_names
exclude_lint_department_cops(cop_registry.names)
end
def cop_names_for_department(department)
names = cop_registry.names_for_department(department)
department == LINT_DEPARTMENT ? exclude_lint_department_cops(names) : names
end
def exclude_lint_department_cops(cops)
cops - [LINT_REDUNDANT_DIRECTIVE_COP, LINT_SYNTAX_COP]
end
def parse_push_args
return {} unless push? && cops
args = {}
cops.split.each do |cop_spec|
op = cop_spec[0]
cop_name = cop_spec[1..]
args[op] ||= []
args[op] << cop_name
end
args
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cached_data.rb | lib/rubocop/cached_data.rb | # frozen_string_literal: true
require 'json'
module RuboCop
# Converts RuboCop objects to and from the serialization format JSON.
# @api private
class CachedData
def initialize(filename)
@filename = filename
end
def from_json(text)
deserialize_offenses(JSON.parse(text))
end
def to_json(offenses)
JSON.dump(offenses.map { |o| serialize_offense(o) })
end
private
def serialize_offense(offense)
status = :uncorrected if %i[corrected corrected_with_todo].include?(offense.status)
{
# Calling #to_s here ensures that the serialization works when using
# other json serializers such as Oj. Some of these gems do not call
# #to_s implicitly.
severity: offense.severity.to_s,
location: {
begin_pos: offense.location.begin_pos,
end_pos: offense.location.end_pos
},
message: message(offense),
cop_name: offense.cop_name,
status: status || offense.status
}
end
def message(offense)
# JSON.dump will fail if the offense message contains text which is not
# valid UTF-8
offense.message.dup.force_encoding(::Encoding::UTF_8).scrub
end
# Restore an offense object loaded from a JSON file.
def deserialize_offenses(offenses)
offenses.map! do |o|
location = location_from_source_buffer(o)
Cop::Offense.new(o['severity'], location, o['message'], o['cop_name'], o['status'].to_sym)
end
end
def location_from_source_buffer(offense)
begin_pos = offense['location']['begin_pos']
end_pos = offense['location']['end_pos']
if begin_pos.zero? && end_pos.zero?
Cop::Offense::NO_LOCATION
else
Parser::Source::Range.new(source_buffer, begin_pos, end_pos)
end
end
# Delay creation until needed. Some type of offenses will have no buffer associated with them
# and be global only. For these, trying to create the buffer will likely fail, for example
# because of unknown encoding comments.
def source_buffer
@source_buffer ||= begin
source = File.read(@filename, encoding: Encoding::UTF_8)
Parser::Source::Buffer.new(@filename, source: source)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config.rb | lib/rubocop/config.rb | # frozen_string_literal: true
# FIXME: Moving Rails department code to RuboCop Rails will remove
# the following rubocop:disable comment.
# rubocop:disable Metrics/ClassLength
module RuboCop
# This class represents the configuration of the RuboCop application
# and all its cops. A Config is associated with a YAML configuration
# file from which it was read. Several different Configs can be used
# during a run of the rubocop program, if files in several
# directories are inspected.
class Config
include PathUtil
include FileFinder
extend SimpleForwardable
CopConfig = Struct.new(:name, :metadata)
EMPTY_CONFIG = {}.freeze
DEFAULT_RAILS_VERSION = 5.0
attr_reader :loaded_path
def self.create(hash, path, check: true)
config = new(hash, path)
config.check if check
config
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def initialize(hash = RuboCop::ConfigLoader.default_configuration, loaded_path = nil)
@loaded_path = loaded_path
@for_cop = Hash.new do |h, cop|
cop_name = cop.respond_to?(:cop_name) ? cop.cop_name : cop
if ConfigObsoletion.deprecated_cop_name?(cop)
# Since a deprecated cop will no longer have a qualified name (as the badge is no
# longer valid), and since we do not want to automatically enable the cop, we just
# set the configuration to an empty hash if it is unset.
# This is necessary to allow a renamed cop have its old configuration merged in
# before being used (which is necessary to allow it to be disabled via config).
cop_options = self[cop_name].dup || {}
else
qualified_cop_name = Cop::Registry.qualified_cop_name(cop_name, loaded_path, warn: false)
cop_options = self[qualified_cop_name].dup || {}
cop_options['Enabled'] = enable_cop?(qualified_cop_name, cop_options)
# If the cop has deprecated names (ie. it has been renamed), it is possible that
# users will still have old configuration for the cop's old name. In this case,
# if `ConfigObsoletion` is configured to warn rather than error (and therefore
# RuboCop runs), we want to respect the old configuration, so merge it in.
#
# NOTE: If there is configuration for both the cop and a deprecated names, the old
# configuration will be merged on top of the new configuration!
ConfigObsoletion.deprecated_names_for(cop).each do |deprecated_cop_name|
deprecated_config = @for_cop[deprecated_cop_name]
next if deprecated_config.empty?
warn Rainbow(<<~WARNING).yellow
Warning: Using `#{deprecated_cop_name}` configuration in #{loaded_path} for `#{cop}`.
WARNING
cop_options.merge!(@for_cop[deprecated_cop_name])
end
end
h[cop] = h[cop_name] = cop_options
end
@hash = hash
@validator = ConfigValidator.new(self)
@badge_config_cache = {}.compare_by_identity
@clusivity_config_exists_cache = {}
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
def loaded_plugins
@loaded_plugins ||= ConfigLoader.loaded_plugins
end
def loaded_features
@loaded_features ||= ConfigLoader.loaded_features
end
def check
deprecation_check { |deprecation_message| warn("#{loaded_path} - #{deprecation_message}") }
@validator.validate
make_excludes_absolute
self
end
def validate_after_resolution
@validator.validate_after_resolution
self
end
def_delegators :@hash, :[], :[]=, :delete, :dig, :each, :key?, :keys, :each_key,
:fetch, :map, :merge, :replace, :to_h, :to_hash, :transform_values
def_delegators :@validator, :validate, :target_ruby_version
def to_s
@to_s ||= @hash.to_s
end
def signature
@signature ||= Digest::SHA1.hexdigest(to_s)
end
# True if this is a config file that is shipped with RuboCop
def internal?
base_config_path = File.expand_path(File.join(ConfigLoader::RUBOCOP_HOME, 'config'))
File.expand_path(loaded_path).start_with?(base_config_path)
end
def make_excludes_absolute
each_key do |key|
dig(key, 'Exclude')&.map! do |exclude_elem|
if exclude_elem.is_a?(String) && !absolute?(exclude_elem)
File.expand_path(File.join(base_dir_for_path_parameters, exclude_elem))
else
exclude_elem
end
end
end
end
def add_excludes_from_higher_level(highest_config)
return unless highest_config.for_all_cops['Exclude']
excludes = for_all_cops['Exclude'] ||= []
highest_config.for_all_cops['Exclude'].each do |path|
unless path.is_a?(Regexp) || absolute?(path)
path = File.join(File.dirname(highest_config.loaded_path), path)
end
excludes << path unless excludes.include?(path)
end
end
def deprecation_check
%w[Exclude Include].each do |key|
plural = "#{key}s"
next unless for_all_cops[plural]
for_all_cops[key] = for_all_cops[plural] # Stay backwards compatible.
for_all_cops.delete(plural)
yield "AllCops/#{plural} was renamed to AllCops/#{key}"
end
end
# @return [Config] for the given cop / cop name.
# Note: the 'Enabled' attribute is calculated according to the department's
# and 'AllCops' configuration; other attributes are not inherited.
def for_cop(cop)
@for_cop[cop]
end
# @return [Config, Hash] for the given cop / cop name.
# If the given cop is enabled, returns its configuration hash.
# Otherwise, returns an empty hash.
def for_enabled_cop(cop)
cop_enabled?(cop) ? for_cop(cop) : EMPTY_CONFIG
end
# @return [Config] for the given cop merged with that of its department (if any)
# Note: the 'Enabled' attribute is same as that returned by `for_cop`
def for_badge(badge)
@badge_config_cache[badge] ||= begin
department_config = self[badge.department_name]
cop_config = for_cop(badge.to_s)
if department_config
department_config.merge(cop_config)
else
cop_config
end
end
end
# @return [Boolean] whether config for this badge has 'Include' or 'Exclude' keys
# @api private
def clusivity_config_for_badge?(badge)
exists = @clusivity_config_exists_cache[badge.to_s]
return exists unless exists.nil?
cop_config = for_badge(badge)
@clusivity_config_exists_cache[badge.to_s] = cop_config['Include'] || cop_config['Exclude']
end
# @return [Config] for the given department name.
# Note: the 'Enabled' attribute will be present only if specified
# at the department's level
def for_department(department_name)
@for_department ||= Hash.new { |h, dept| h[dept] = self[dept] || {} }
@for_department[department_name.to_s]
end
def for_all_cops
@for_all_cops ||= self['AllCops'] || {}
end
def cop_enabled?(name)
!!for_cop(name)['Enabled']
end
def disabled_new_cops?
for_all_cops['NewCops'] == 'disable'
end
def enabled_new_cops?
for_all_cops['NewCops'] == 'enable'
end
def active_support_extensions_enabled?
for_all_cops['ActiveSupportExtensionsEnabled']
end
def string_literals_frozen_by_default?
for_all_cops['StringLiteralsFrozenByDefault']
end
def file_to_include?(file)
relative_file_path = path_relative_to_config(file)
# Optimization to quickly decide if the given file is hidden (on the top
# level) and cannot be matched by any pattern.
is_hidden = relative_file_path.start_with?('.') && !relative_file_path.start_with?('..')
return false if is_hidden && !possibly_include_hidden?
absolute_file_path = File.expand_path(file)
patterns_to_include.any? do |pattern|
if block_given?
yield pattern, relative_file_path, absolute_file_path
else
match_path?(pattern, relative_file_path) || match_path?(pattern, absolute_file_path)
end
end
end
def allowed_camel_case_file?(file)
# Gemspecs are allowed to have dashes because that fits with bundler best
# practices in the case when the gem is nested under a namespace (e.g.,
# `bundler-console` conveys `Bundler::Console`).
return true if File.extname(file) == '.gemspec'
file_to_include?(file) do |pattern, relative_path, absolute_path|
/[A-Z]/.match?(pattern.to_s) &&
(match_path?(pattern, relative_path) || match_path?(pattern, absolute_path))
end
end
# Returns true if there's a chance that an Include pattern matches hidden
# files, false if that's definitely not possible.
def possibly_include_hidden?
return @possibly_include_hidden if defined?(@possibly_include_hidden)
@possibly_include_hidden = patterns_to_include.any? do |s|
s.is_a?(Regexp) || s.start_with?('.') || s.include?('/.')
end
end
def file_to_exclude?(file)
file = File.expand_path(file)
patterns_to_exclude.any? { |pattern| match_path?(pattern, file) }
end
def patterns_to_include
for_all_cops['Include'] || []
end
def patterns_to_exclude
for_all_cops['Exclude'] || []
end
def path_relative_to_config(path)
relative_path(path, base_dir_for_path_parameters)
end
# Paths specified in configuration files starting with .rubocop are
# relative to the directory where that file is. Paths in other config files
# are relative to the current directory. This is so that paths in
# config/default.yml, for example, are not relative to RuboCop's config
# directory since that wouldn't work.
def base_dir_for_path_parameters
@base_dir_for_path_parameters ||=
if loaded_path && File.basename(loaded_path).start_with?('.rubocop') &&
loaded_path != File.join(Dir.home, ConfigLoader::DOTFILE)
File.expand_path(File.dirname(loaded_path))
else
Dir.pwd
end
end
def parser_engine
@parser_engine ||= for_all_cops.fetch('ParserEngine', :default).to_sym
end
def target_rails_version
@target_rails_version ||=
if for_all_cops['TargetRailsVersion']
for_all_cops['TargetRailsVersion'].to_f
elsif target_rails_version_from_bundler_lock_file
target_rails_version_from_bundler_lock_file
else
DEFAULT_RAILS_VERSION
end
end
def smart_loaded_path
PathUtil.smart_path(@loaded_path)
end
# @return [String, nil]
def bundler_lock_file_path
return nil unless loaded_path
base_path = base_dir_for_path_parameters
['Gemfile.lock', 'gems.locked'].each do |file_name|
path = find_file_upwards(file_name, base_path)
return path if path
end
nil
end
def pending_cops
keys.each_with_object([]) do |qualified_cop_name, pending_cops|
department = department_of(qualified_cop_name)
next if department && department['Enabled'] == false
cop_metadata = self[qualified_cop_name]
next unless cop_metadata['Enabled'] == 'pending'
pending_cops << CopConfig.new(qualified_cop_name, cop_metadata)
end
end
# Returns target's locked gem versions (i.e. from Gemfile.lock or gems.locked)
# @returns [Hash{String => Gem::Version}] The locked gem versions, keyed by the gems' names.
def gem_versions_in_target
@gem_versions_in_target ||= read_gem_versions_from_target_lockfile
end
def inspect # :nodoc:
"#<#{self.class.name}:#{object_id} @loaded_path=#{loaded_path}>"
end
private
# @return [Float, nil] The Rails version as a `major.minor` Float.
def target_rails_version_from_bundler_lock_file
@target_rails_version_from_bundler_lock_file ||= read_rails_version_from_bundler_lock_file
end
# @return [Float, nil] The Rails version as a `major.minor` Float.
def read_rails_version_from_bundler_lock_file
return nil unless gem_versions_in_target
# Look for `railties` instead of `rails`, to support apps that only use a subset of `rails`
# See https://github.com/rubocop/rubocop/pull/11289
rails_version_in_target = gem_versions_in_target['railties']
return nil unless rails_version_in_target
gem_version_to_major_minor_float(rails_version_in_target)
end
# @param [Gem::Version] gem_version an object like `Gem::Version.new("7.1.2.3")`
# @return [Float] The major and minor version, like `7.1`
def gem_version_to_major_minor_float(gem_version)
segments = gem_version.segments
Float("#{segments[0]}.#{segments[1]}")
end
# @returns [Hash{String => Gem::Version}] The locked gem versions, keyed by the gems' names.
def read_gem_versions_from_target_lockfile
lockfile_path = bundler_lock_file_path
return nil unless lockfile_path
Lockfile.new(lockfile_path).gem_versions
end
def enable_cop?(qualified_cop_name, cop_options)
# If the cop is explicitly enabled or `Lint/Syntax`, the other checks can be skipped.
return true if cop_options['Enabled'] == true || qualified_cop_name == 'Lint/Syntax'
department = department_of(qualified_cop_name)
cop_enabled = cop_options.fetch('Enabled') { !for_all_cops['DisabledByDefault'] }
return true if cop_enabled == 'override_department'
return false if department && department['Enabled'] == false
cop_enabled
end
def department_of(qualified_cop_name)
*cop_department, _ = qualified_cop_name.split('/')
return nil if cop_department.empty?
self[cop_department.join('/')]
end
end
end
# rubocop:enable Metrics/ClassLength
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/server.rb | lib/rubocop/server.rb | # frozen_string_literal: true
require_relative 'platform'
#
# This code is based on https://github.com/fohte/rubocop-daemon.
#
# Copyright (c) 2018 Hayato Kawai
#
# The MIT License (MIT)
#
# https://github.com/fohte/rubocop-daemon/blob/master/LICENSE.txt
#
module RuboCop
# The bootstrap module for server.
# @api private
module Server
TIMEOUT = 20
autoload :CLI, 'rubocop/server/cli'
autoload :Cache, 'rubocop/server/cache'
autoload :ClientCommand, 'rubocop/server/client_command'
autoload :Helper, 'rubocop/server/helper'
autoload :Core, 'rubocop/server/core'
autoload :ServerCommand, 'rubocop/server/server_command'
autoload :SocketReader, 'rubocop/server/socket_reader'
class << self
def support_server?
RUBY_ENGINE == 'ruby' && !RuboCop::Platform.windows?
end
def running?
return false unless support_server? # Never running.
Cache.pid_running?
end
def wait_for_running_status!(expected)
start_time = Time.now
while Server.running? != expected
sleep 0.1
next unless Time.now - start_time > TIMEOUT
warn "running? was not #{expected} after #{TIMEOUT} seconds!"
exit 1
end
end
end
end
end
require_relative 'server/errors'
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/arguments_file.rb | lib/rubocop/arguments_file.rb | # frozen_string_literal: true
module RuboCop
# This is a class that reads optional command line arguments to rubocop from .rubocop file.
# @api private
class ArgumentsFile
def self.read_as_arguments
if File.exist?('.rubocop') && !File.directory?('.rubocop')
require 'shellwords'
File.read('.rubocop').shellsplit
else
[]
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_finder.rb | lib/rubocop/config_finder.rb | # frozen_string_literal: true
require_relative 'file_finder'
module RuboCop
# This class has methods related to finding configuration path.
# @api private
class ConfigFinder
DOTFILE = '.rubocop.yml'
XDG_CONFIG = 'config.yml'
RUBOCOP_HOME = File.realpath(File.join(File.dirname(__FILE__), '..', '..'))
DEFAULT_FILE = File.join(RUBOCOP_HOME, 'config', 'default.yml')
class << self
include FileFinder
attr_writer :project_root
def find_config_path(target_dir)
find_project_dotfile(target_dir) || find_project_root_dot_config ||
find_user_dotfile || find_user_xdg_config || DEFAULT_FILE
end
# Returns the path RuboCop inferred as the root of the project. No file
# searches will go past this directory.
def project_root
@project_root ||= find_project_root
end
private
def find_project_root
pwd = Dir.pwd
gems_file = find_last_file_upwards('Gemfile', pwd) || find_last_file_upwards('gems.rb', pwd)
return unless gems_file
File.dirname(gems_file)
end
def find_project_dotfile(target_dir)
find_file_upwards(DOTFILE, target_dir, project_root)
end
def find_project_root_dot_config
return unless project_root
dotfile = File.join(project_root, '.config', DOTFILE)
return dotfile if File.exist?(dotfile)
xdg_config = File.join(project_root, '.config', 'rubocop', XDG_CONFIG)
xdg_config if File.exist?(xdg_config)
end
def find_user_dotfile
return unless ENV.key?('HOME')
file = File.join(Dir.home, DOTFILE)
file if File.exist?(file)
end
def find_user_xdg_config
xdg_config_home = expand_path(ENV.fetch('XDG_CONFIG_HOME', '~/.config'))
xdg_config = File.join(xdg_config_home, 'rubocop', XDG_CONFIG)
xdg_config if File.exist?(xdg_config)
end
def expand_path(path)
File.expand_path(path)
rescue ArgumentError
# Could happen because HOME or ID could not be determined. Fall back on
# using the path literally in that case.
path
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter.rb | lib/rubocop/formatter.rb | # frozen_string_literal: true
module RuboCop
# The bootstrap module for formatter.
module Formatter
require_relative 'formatter/text_util'
require_relative 'formatter/base_formatter'
require_relative 'formatter/simple_text_formatter'
# relies on simple text
require_relative 'formatter/clang_style_formatter'
require_relative 'formatter/disabled_config_formatter'
require_relative 'formatter/emacs_style_formatter'
require_relative 'formatter/file_list_formatter'
require_relative 'formatter/fuubar_style_formatter'
require_relative 'formatter/github_actions_formatter'
require_relative 'formatter/html_formatter'
require_relative 'formatter/json_formatter'
require_relative 'formatter/junit_formatter'
require_relative 'formatter/markdown_formatter'
require_relative 'formatter/offense_count_formatter'
require_relative 'formatter/pacman_formatter'
require_relative 'formatter/progress_formatter'
require_relative 'formatter/quiet_formatter'
require_relative 'formatter/tap_formatter'
require_relative 'formatter/worst_offenders_formatter'
# relies on progress formatter
require_relative 'formatter/auto_gen_config_formatter'
require_relative 'formatter/formatter_set'
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/result_cache.rb | lib/rubocop/result_cache.rb | # frozen_string_literal: true
require 'digest/sha1'
require 'find'
require 'zlib'
require_relative 'cache_config'
module RuboCop
# Provides functionality for caching RuboCop runs.
# @api private
class ResultCache
NON_CHANGING = %i[color format formatters out debug display_time fail_level
fix_layout autocorrect safe_autocorrect autocorrect_all
cache fail_fast stdin parallel].freeze
DL_EXTENSIONS = ::RbConfig::CONFIG
.values_at('DLEXT', 'DLEXT2')
.reject { |ext| !ext || ext.empty? }
.map { |ext| ".#{ext}" }
.freeze
# Remove old files so that the cache doesn't grow too big. When the
# threshold MaxFilesInCache has been exceeded, the oldest 50% of all the
# files in the cache are removed. The reason for removing so much is that
# removing should be done relatively seldom, since there is a slight risk
# that some other RuboCop process was just about to read the file, when
# there's parallel execution and the cache is shared.
def self.cleanup(config_store, verbose, cache_root_override = nil)
return if inhibit_cleanup # OPTIMIZE: For faster testing
rubocop_cache_dir = cache_root(config_store, cache_root_override)
return unless File.exist?(rubocop_cache_dir)
# We know the cache entries are 3 level deep, so globing
# for `*/*/*` only returns files.
files = Dir[File.join(rubocop_cache_dir, '*/*/*')]
return unless requires_file_removal?(files.length, config_store)
remove_oldest_files(files, rubocop_cache_dir, verbose)
end
class << self
# @api private
attr_accessor :rubocop_required_features
ResultCache.rubocop_required_features = []
private
def requires_file_removal?(file_count, config_store)
file_count > 1 && file_count > config_store.for_pwd.for_all_cops['MaxFilesInCache']
end
def remove_oldest_files(files, rubocop_cache_dir, verbose)
# Add 1 to half the number of files, so that we remove the file if
# there's only 1 left.
remove_count = (files.length / 2) + 1
puts "Removing the #{remove_count} oldest files from #{rubocop_cache_dir}" if verbose
sorted = files.sort_by { |path| File.mtime(path) }
remove_files(sorted, remove_count)
rescue Errno::ENOENT
# This can happen if parallel RuboCop invocations try to remove the
# same files. No problem.
puts $ERROR_INFO if verbose
end
def remove_files(files, remove_count)
# Batch file deletions, deleting over 130,000+ files will crash
# File.delete.
files[0, remove_count].each_slice(10_000).each do |files_slice|
File.delete(*files_slice)
end
dirs = files.map { |f| File.dirname(f) }.uniq
until dirs.empty?
dirs.select! do |dir|
Dir.rmdir(dir)
true
rescue SystemCallError # ENOTEMPTY etc
false
end
dirs = dirs.map { |f| File.dirname(f) }.uniq
end
end
end
def self.cache_root(config_store, cache_root_override = nil)
CacheConfig.root_dir do
cache_root_override || config_store.for_pwd.for_all_cops['CacheRootDirectory']
end
end
def self.allow_symlinks_in_cache_location?(config_store)
config_store.for_pwd.for_all_cops['AllowSymlinksInCacheRootDirectory']
end
attr_reader :path
def initialize(file, team, options, config_store, cache_root_override = nil)
cache_root_override ||= options[:cache_root] if options[:cache_root]
rubocop_cache_dir = ResultCache.cache_root(config_store, cache_root_override)
@allow_symlinks_in_cache_location =
ResultCache.allow_symlinks_in_cache_location?(config_store)
@path = File.join(rubocop_cache_dir,
self.class.source_checksum,
context_checksum(team, options),
file_checksum(file, config_store))
@cached_data = CachedData.new(file)
@debug = options[:debug]
end
def debug?
@debug
end
def valid?
File.exist?(@path)
end
def load
puts "Loading cache from #{@path}" if debug?
@cached_data.from_json(File.read(@path, encoding: Encoding::UTF_8))
end
def save(offenses)
dir = File.dirname(@path)
begin
FileUtils.mkdir_p(dir)
rescue Errno::EACCES, Errno::EROFS => e
warn "Couldn't create cache directory. Continuing without cache.\n #{e.message}"
return
end
preliminary_path = "#{@path}_#{rand(1_000_000_000)}"
# RuboCop must be in control of where its cached data is stored. A
# symbolic link anywhere in the cache directory tree can be an
# indication that a symlink attack is being waged.
return if symlink_protection_triggered?(dir)
File.open(preliminary_path, 'w', encoding: Encoding::UTF_8) do |f|
f.write(@cached_data.to_json(offenses))
end
# The preliminary path is used so that if there are multiple RuboCop
# processes trying to save data for the same inspected file
# simultaneously, the only problem we run in to is a competition who gets
# to write to the final file. The contents are the same, so no corruption
# of data should occur.
FileUtils.mv(preliminary_path, @path)
end
private
def symlink_protection_triggered?(path)
!@allow_symlinks_in_cache_location && any_symlink?(path)
end
def any_symlink?(path)
while path != File.dirname(path)
if File.symlink?(path)
warn "Warning: #{path} is a symlink, which is not allowed."
return true
end
path = File.dirname(path)
end
false
end
def file_checksum(file, config_store)
digester = Digest::SHA1.new
mode = File.stat(file).mode
digester.update("#{file}#{mode}#{config_store.for_file(file).signature}")
digester.file(file)
digester.hexdigest
rescue Errno::ENOENT
# Spurious files that come and go should not cause a crash, at least not
# here.
'_'
end
class << self
attr_accessor :inhibit_cleanup
# The checksum of the RuboCop program running the inspection.
def source_checksum
@source_checksum ||= begin
digest = Digest::SHA1.new
rubocop_extra_features
.select { |path| File.file?(path) }
.sort!
.each do |path|
digest << digest(path)
end
digest << RuboCop::Version::STRING << RuboCop::AST::Version::STRING
digest.hexdigest
end
end
private
def digest(path)
content = if path.end_with?(*DL_EXTENSIONS)
# Shared libraries often contain timestamps of when
# they were compiled and other non-stable data.
File.basename(path)
else
File.binread(path) # mtime not reliable
end
Zlib.crc32(content).to_s
end
def rubocop_extra_features
lib_root = File.join(File.dirname(__FILE__), '..')
exe_root = File.join(lib_root, '..', 'exe')
# Make sure to use an absolute path to prevent errors on Windows
# when traversing the relative paths with symlinks.
exe_root = File.absolute_path(exe_root)
# These are all the files we have `require`d plus everything in the
# exe directory. A change to any of them could affect the cop output
# so we include them in the cache hash.
source_files = $LOADED_FEATURES + Find.find(exe_root).to_a
source_files -= ResultCache.rubocop_required_features # Rely on gem versions
source_files
end
end
# Return a hash of the options given at invocation, minus the ones that have
# no effect on which offenses and disabled line ranges are found, and thus
# don't affect caching.
def relevant_options_digest(options)
options = options.reject { |key, _| NON_CHANGING.include?(key) }
options.to_s.gsub(/[^a-z]+/i, '_')
end
# We combine team and options into a single "context" checksum to avoid
# making file names that are too long for some filesystems to handle.
# This context is for anything that's not (1) the RuboCop executable
# checksum or (2) the inspected file checksum.
def context_checksum(team, options)
keys = [team.external_dependency_checksum, relevant_options_digest(options)]
Digest::SHA1.hexdigest(keys.join)
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/target_finder.rb | lib/rubocop/target_finder.rb | # frozen_string_literal: true
module RuboCop
# This class finds target files to inspect by scanning the directory tree and picking ruby files.
# @api private
class TargetFinder
HIDDEN_PATH_SUBSTRING = "#{File::SEPARATOR}."
def initialize(config_store, options = {})
@config_store = config_store
@options = options
end
# Generate a list of target files by expanding globbing patterns (if any). If args is empty,
# recursively find all Ruby source files under the current directory
# @return [Array] array of file paths
def find(args, mode)
return target_files_in_dir if args.empty?
files = []
args.uniq.each do |arg|
files += if File.directory?(arg)
target_files_in_dir(arg.chomp(File::SEPARATOR))
else
process_explicit_path(arg, mode)
end
end
files.map { |f| File.expand_path(f) }.uniq
end
# Finds all Ruby source files under the current or other supplied directory. A Ruby source file
# is defined as a file with the `.rb` extension or a file with no extension that has a ruby
# shebang line as its first line.
# It is possible to specify includes and excludes using the config file, so you can include
# other Ruby files like Rakefiles and gemspecs.
# @param base_dir Root directory under which to search for
# ruby source files
# @return [Array] Array of filenames
def target_files_in_dir(base_dir = Dir.pwd)
# Support Windows: Backslashes from command-line -> forward slashes
base_dir = base_dir.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
all_files = find_files(base_dir, File::FNM_DOTMATCH)
base_dir_config = @config_store.for(base_dir)
target_files = if hidden_path?(base_dir)
all_files.select { |file| ruby_file?(file) }
else
all_files.select { |file| to_inspect?(file, base_dir_config) }
end
target_files.sort_by!(&order)
end
# Search for files recursively starting at the given base directory using the given flags that
# determine how the match is made. Excluded files will be removed later by the caller, but as an
# optimization find_files removes the top level directories that are excluded in configuration
# in the normal way (dir/**/*).
def find_files(base_dir, flags)
# get all wanted directories first to improve speed of finding all files
exclude_pattern = combined_exclude_glob_patterns(base_dir)
dir_flags = flags | File::FNM_PATHNAME | File::FNM_EXTGLOB
patterns = wanted_dir_patterns(base_dir, exclude_pattern, dir_flags)
patterns.map! { |dir| File.join(dir, '*') }
# We need this special case to avoid creating the pattern
# /**/* which searches the entire file system.
patterns = [File.join(base_dir, '**/*')] if patterns.empty?
Dir.glob(patterns, flags).select { |path| FileTest.file?(path) }
end
private
def to_inspect?(file, base_dir_config)
return false if base_dir_config.file_to_exclude?(file)
return true if !hidden_path?(file) && ruby_file?(file)
base_dir_config.file_to_include?(file)
end
def hidden_path?(path)
path.include?(HIDDEN_PATH_SUBSTRING)
end
def wanted_dir_patterns(base_dir, exclude_pattern, flags)
# Escape glob characters in base_dir to avoid unwanted behavior.
base_dir = base_dir.gsub(/[\\{}\[\]*?]/) do |reserved_glob_character|
"\\#{reserved_glob_character}"
end
dirs = Dir.glob(File.join(base_dir, '*/'), flags)
.reject do |dir|
next true if dir.end_with?('/./', '/../')
next true if File.fnmatch?(exclude_pattern, dir, flags)
symlink_excluded_or_infinite_loop?(base_dir, dir, exclude_pattern, flags)
end
dirs.flat_map { |dir| wanted_dir_patterns(dir, exclude_pattern, flags) }.unshift(base_dir)
end
def symlink_excluded_or_infinite_loop?(base_dir, current_dir, exclude_pattern, flags)
dir_realpath = File.realpath(current_dir)
File.symlink?(current_dir.chomp('/')) && (
File.fnmatch?(exclude_pattern, "#{dir_realpath}/", flags) ||
File.realpath(base_dir).start_with?(dir_realpath)
)
end
def combined_exclude_glob_patterns(base_dir)
exclude = @config_store.for(base_dir).for_all_cops['Exclude'] || []
patterns = exclude.select { |pattern| pattern.is_a?(String) && pattern.end_with?('/**/*') }
.map { |pattern| pattern.sub("#{base_dir}/", '') }
"#{base_dir}/{#{patterns.join(',')}}"
end
def ruby_filenames
@ruby_filenames ||= begin
file_patterns = all_cops_include.reject { |pattern| pattern.start_with?('**/*.') }
file_patterns.map { |pattern| pattern.sub('**/', '') }
end
end
def all_cops_include
@all_cops_include ||= @config_store.for_pwd.for_all_cops['Include'].map(&:to_s)
end
def process_explicit_path(path, mode)
files = path.include?('*') ? Dir[path] : [path]
if mode == :only_recognized_file_types || force_exclusion?
files.select! { |file| included_file?(file) }
end
files.reject! { |file| FileTest.directory?(file) }
force_exclusion? ? without_excluded(files) : files
end
def without_excluded(files)
files.reject do |file|
# When --ignore-parent-exclusion is given, we must look at the configuration associated with
# the file, but in the default case when --ignore-parent-exclusion is not given, can safely
# look only at the configuration for the current directory, since it's only the Exclude
# parameters we're going to check.
config = @config_store.for(ignore_parent_exclusion? ? file : '.')
config.file_to_exclude?(file)
end
end
def included_file?(file)
ruby_file?(file) || configured_include?(file)
end
def ruby_file?(file)
stdin? || ruby_extension?(file) || ruby_filename?(file) || ruby_executable?(file)
end
def stdin?
@options.key?(:stdin)
end
def ruby_extension?(file)
ruby_extensions.include?(File.extname(file))
end
def ruby_extensions
@ruby_extensions ||= begin
ext_patterns = all_cops_include.select { |pattern| pattern.start_with?('**/*.') }
ext_patterns.map { |pattern| pattern.sub('**/*', '') }
end
end
def ruby_filename?(file)
ruby_filenames.include?(File.basename(file))
end
def configured_include?(file)
@config_store.for_pwd.file_to_include?(file)
end
def ruby_executable?(file)
return false if !File.extname(file).empty? || !File.exist?(file) || File.empty?(file)
first_line = File.open(file, &:readline)
/#!.*(#{ruby_interpreters(file).join('|')})/.match?(first_line)
rescue EOFError, ArgumentError => e
warn("Unprocessable file #{file}: #{e.class}, #{e.message}") if debug?
false
end
def ruby_interpreters(file)
@config_store.for(file).for_all_cops['RubyInterpreters']
end
def order
if fail_fast?
# Most recently modified file first.
->(path) { -Integer(File.mtime(path)) }
else
:itself
end
end
def force_exclusion?
@options[:force_exclusion]
end
def ignore_parent_exclusion?
@options[:ignore_parent_exclusion]
end
def debug?
@options[:debug]
end
def fail_fast?
@options[:fail_fast]
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cops_documentation_generator.rb | lib/rubocop/cops_documentation_generator.rb | # frozen_string_literal: true
require 'fileutils'
require 'yard'
# Class for generating documentation of all cops departments
# @api private
class CopsDocumentationGenerator # rubocop:disable Metrics/ClassLength
include ::RuboCop::Cop::Documentation
CopData = Struct.new(
:cop, :description, :example_objects, :safety_objects, :see_objects, :config, keyword_init: true
)
STRUCTURE = {
name: ->(data) { cop_header(data.cop) },
required_ruby_version: ->(data) { required_ruby_version(data.cop) },
properties: ->(data) { properties(data.cop) },
description: ->(data) { "#{data.description}\n" },
safety: ->(data) { safety_object(data.safety_objects, data.cop) },
examples: ->(data) { examples(data.example_objects, data.cop) },
configuration: ->(data) { configurations(data.cop.department, data.cop, data.config) },
references: ->(data) { references(data.cop, data.see_objects) }
}.freeze
# This class will only generate documentation for cops that belong to one of
# the departments given in the `departments` array. E.g. if we only wanted
# documentation for Lint cops:
#
# CopsDocumentationGenerator.new(departments: ['Lint']).call
#
# For plugin extensions, specify `:plugin_name` keyword as follows:
#
# CopsDocumentationGenerator.new(
# departments: ['Performance'], plugin_name: 'rubocop-performance'
# ).call
#
# You can append additional information:
#
# callback = ->(data) { required_rails_version(data.cop) }
# CopsDocumentationGenerator.new(extra_info: { ruby_version: callback }).call
#
# This will insert the string returned from the lambda _after_ the section from RuboCop itself.
# See `CopsDocumentationGenerator::STRUCTURE` for available sections.
#
def initialize(departments: [], extra_info: {}, base_dir: Dir.pwd, plugin_name: nil)
@departments = departments.map(&:to_sym).sort!
@extra_info = extra_info
@cops = RuboCop::Cop::Registry.global
@config = RuboCop::ConfigLoader.default_configuration
# NOTE: For example, this prevents excessive plugin loading before another task executes,
# in cases where plugins are already loaded by `internal_investigation`.
if plugin_name && @config.loaded_plugins.none? { |plugin| plugin.about.name == plugin_name }
RuboCop::Plugin.integrate_plugins(RuboCop::Config.new, [plugin_name])
end
@base_dir = base_dir
@docs_path = "#{base_dir}/docs/modules/ROOT"
FileUtils.mkdir_p("#{@docs_path}/pages")
end
def call
YARD::Registry.load!
departments.each { |department| print_cops_of_department(department) }
print_table_of_contents
ensure
RuboCop::ConfigLoader.default_configuration = nil
end
private
attr_reader :departments, :cops, :config, :docs_path
def cops_of_department(department)
cops.with_department(department).sort!
end
def cops_body(data)
check_examples_to_have_the_default_enforced_style!(data.example_objects, data.cop)
content = +''
STRUCTURE.each do |section, block|
content << instance_exec(data, &block)
content << @extra_info[section].call(data) if @extra_info[section]
end
content
end
def check_examples_to_have_the_default_enforced_style!(example_objects, cop)
return if example_objects.none?
examples_describing_enforced_style = example_objects.map(&:name).grep(/EnforcedStyle:/)
return if examples_describing_enforced_style.none?
if examples_describing_enforced_style.index { |name| name.match?('default') }.nonzero?
raise "Put the example with the default EnforcedStyle on top for #{cop.cop_name}"
end
return if examples_describing_enforced_style.any? { |name| name.match?('default') }
raise "Specify the default EnforcedStyle for #{cop.cop_name}"
end
def examples(example_objects, cop)
return '' if example_objects.none?
example_objects.each_with_object(cop_subsection('Examples', cop).dup) do |example, content|
content << "\n" unless content.end_with?("\n\n")
content << example_header(example.name, cop) unless example.name == ''
content << code_example(example)
end
end
def safety_object(safety_objects, cop)
return '' if safety_objects.all? { |s| s.text.blank? }
safety_objects.each_with_object(cop_subsection('Safety', cop).dup) do |safety_object, content|
next if safety_object.text.blank?
content << "\n" unless content.end_with?("\n\n")
content << safety_object.text
content << "\n"
end
end
def required_ruby_version(cop)
return '' unless cop.respond_to?(:required_minimum_ruby_version)
if cop.required_minimum_ruby_version
requirement = cop.required_minimum_ruby_version
elsif cop.required_maximum_ruby_version
requirement = "<= #{cop.required_maximum_ruby_version}"
else
return ''
end
"NOTE: Requires Ruby version #{requirement}\n\n"
end
# rubocop:disable Metrics/MethodLength
def properties(cop)
header = [
'Enabled by default', 'Safe', 'Supports autocorrection', 'Version Added',
'Version Changed'
]
autocorrect = if cop.support_autocorrect?
context = cop.new.always_autocorrect? ? 'Always' : 'Command-line only'
"#{context}#{' (Unsafe)' unless cop.new(config).safe_autocorrect?}"
else
'No'
end
cop_config = config.for_cop(cop)
content = [[
cop_status(cop_config.fetch('Enabled')),
cop_config.fetch('Safe', true) ? 'Yes' : 'No',
autocorrect,
cop_config.fetch('VersionAdded', '-'),
cop_config.fetch('VersionChanged', '-')
]]
"#{to_table(header, content)}\n"
end
# rubocop:enable Metrics/MethodLength
def cop_header(cop)
content = +"\n"
content << "[##{to_anchor(cop.cop_name)}]\n"
content << "== #{cop.cop_name}\n"
content << "\n"
content
end
def cop_subsection(title, cop)
content = +"\n"
content << "[##{to_anchor(title)}-#{to_anchor(cop.cop_name)}]\n"
content << "=== #{title}\n"
content << "\n"
content
end
def example_header(title, cop)
content = +"[##{to_anchor(title)}-#{to_anchor(cop.cop_name)}]\n"
content << "==== #{title}\n"
content << "\n"
content
end
def code_example(ruby_code)
content = +"[source,ruby]\n----\n"
content << ruby_code.text.gsub('@good', '# good').gsub('@bad', '# bad').strip
content << "\n----\n"
content
end
def configurations(department, cop, cop_config)
header = ['Name', 'Default value', 'Configurable values']
configs = cop_config.each_key.reject do |key|
key == 'AllowMultipleStyles' ||
(key != 'SupportedTypes' && key.start_with?('Supported'))
end
return '' if configs.empty?
content = configs.map do |name|
configurable = configurable_values(cop_config, name)
default = format_table_value(cop_config[name])
[configuration_name(department, name), default, configurable]
end
cop_subsection('Configurable attributes', cop) + to_table(header, content)
end
def configuration_name(department, name)
return name unless name == 'AllowMultilineFinalElement'
filename = "#{department_to_basename(department)}.adoc"
"xref:#{filename}#allowmultilinefinalelement[AllowMultilineFinalElement]"
end
# rubocop:disable Metrics/CyclomaticComplexity,Metrics/MethodLength
def configurable_values(cop_config, name)
case name
when /^Enforced/
supported_style_name = RuboCop::Cop::Util.to_supported_styles(name)
format_table_value(cop_config[supported_style_name])
when 'IndentationWidth'
'Integer'
when 'Database'
format_table_value(cop_config['SupportedDatabases'])
else
case cop_config[name]
when String
'String'
when Integer
'Integer'
when Float
'Float'
when true, false
'Boolean'
when Array
'Array'
else
''
end
end
end
# rubocop:enable Metrics/CyclomaticComplexity,Metrics/MethodLength
def to_table(header, content)
table = ['|===', "| #{header.join(' | ')}\n\n"].join("\n")
marked_contents = content.map do |plain_content|
# Escape `|` with backslash to prevent the regexp `|` is not used as a table separator.
plain_content.map { |c| "| #{c.gsub('|', '\|')}" }.join("\n")
end
table << marked_contents.join("\n\n")
table << "\n|===\n"
end
def format_table_value(val)
value =
case val
when Array
if val.empty?
'`[]`'
else
val.map { |config| format_table_value(config) }.join(', ')
end
else
wrap_backtick(val.nil? ? '<none>' : val)
end
value.gsub("#{@base_dir}/", '').rstrip
end
def wrap_backtick(value)
if value.is_a?(String)
# Use `+` to prevent text like `**/*.gemspec`, `spec/**/*` from being bold.
value.include?('*') ? "`+#{value}+`" : "`#{value}`"
else
"`#{value}`"
end
end
def references(cop, see_objects) # rubocop:disable Metrics/AbcSize
cop_config = config.for_cop(cop)
urls = RuboCop::Cop::MessageAnnotator.new(config, cop.name, cop_config, {}).urls
return '' if urls.empty? && see_objects.empty?
content = cop_subsection('References', cop)
content << urls.map { |url| "* #{url}" }.join("\n")
content << "\n" unless urls.empty?
content << see_objects.map { |see| "* #{see.name}" }.join("\n")
content << "\n" unless see_objects.empty?
content
end
def footer_for_department(department)
return '' unless department == :Layout
filename = "#{department_to_basename(department)}_footer.adoc"
file = "#{docs_path}/partials/#{filename}"
return '' unless File.exist?(file)
"\ninclude::../partials/#{filename}[]\n"
end
# rubocop:disable Metrics/MethodLength
def print_cops_of_department(department)
selected_cops = cops_of_department(department)
content = +<<~HEADER
////
Do NOT edit this file by hand directly, as it is automatically generated.
Please make any necessary changes to the cop documentation within the source files themselves.
////
= #{department}
HEADER
selected_cops.each { |cop| content << print_cop_with_doc(cop) }
content << footer_for_department(department)
file_name = "#{docs_path}/pages/#{department_to_basename(department)}.adoc"
File.open(file_name, 'w') do |file|
puts "* generated #{file_name}"
file.write("#{content.strip}\n")
end
end
# rubocop:enable Metrics/MethodLength
def print_cop_with_doc(cop) # rubocop:todo Metrics/AbcSize, Metrics/MethodLength
cop_config = config.for_cop(cop)
non_display_keys = %w[
Enabled
Description
StyleGuide
Reference References
Safe SafeAutoCorrect AutoCorrect
VersionAdded VersionChanged
]
parameters = cop_config.reject { |k| non_display_keys.include? k }
description = 'No documentation'
example_objects = safety_objects = see_objects = []
cop_code(cop) do |code_object|
description = code_object.docstring unless code_object.docstring.blank?
example_objects = code_object.tags('example')
safety_objects = code_object.tags('safety')
see_objects = code_object.tags('see')
end
data = CopData.new(cop: cop, description: description, example_objects: example_objects,
safety_objects: safety_objects, see_objects: see_objects, config: parameters)
cops_body(data)
end
def cop_code(cop)
YARD::Registry.all(:class).detect do |code_object|
next unless RuboCop::Cop::Badge.for(code_object.to_s) == cop.badge
yield code_object
end
end
def table_of_content_for_department(department)
type_title = department[0].upcase + department[1..]
filename = "#{department_to_basename(department)}.adoc"
content = +"=== Department xref:#{filename}[#{type_title}]\n\n"
cops_of_department(department).each do |cop|
anchor = to_anchor(cop.cop_name)
content << "* xref:#{filename}##{anchor}[#{cop.cop_name}]\n"
end
content
end
def print_table_of_contents
path = "#{docs_path}/pages/cops.adoc"
File.write(path, table_contents) and return unless File.exist?(path)
original = File.read(path)
content = +"// START_COP_LIST\n\n"
content << table_contents
content << "\n// END_COP_LIST"
content = original.sub(%r{// START_COP_LIST.+// END_COP_LIST}m, content)
File.write(path, content)
end
def table_contents
departments.map { |department| table_of_content_for_department(department) }.join("\n")
end
def cop_status(status)
return 'Disabled' unless status
status == 'pending' ? 'Pending' : 'Enabled'
end
# HTML anchor are somewhat limited in what characters they can contain, just
# accept a known-good subset. As long as it's consistent it doesn't matter.
#
# Style/AccessModifierDeclarations => styleaccessmodifierdeclarations
# OnlyFor: [] (default) => onlyfor_-__-_default_
def to_anchor(title)
title.delete('/').tr(' ', '-').gsub(/[^a-zA-Z0-9-]/, '_').downcase
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/error.rb | lib/rubocop/error.rb | # frozen_string_literal: true
module RuboCop
# An Error exception is different from an Offense with severity 'error'
# When this exception is raised, it means that RuboCop is unable to perform
# a requested action (probably due to misconfiguration) and must stop
# immediately, rather than carrying on
class Error < StandardError; end
class ValidationError < Error; end
# A wrapper to display errored location of analyzed file.
class ErrorWithAnalyzedFileLocation < Error
def initialize(cause:, node:, cop:)
super()
@cause = cause
@cop = cop
@location = node.is_a?(RuboCop::AST::Node) ? node.loc : node
end
attr_reader :cause, :cop
def line
@location&.line
end
def column
@location&.column
end
def message
"cause: #{cause.inspect}"
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/util.rb | lib/rubocop/util.rb | # frozen_string_literal: true
module RuboCop
# This module contains a collection of useful utility methods.
module Util
def self.silence_warnings
# Replaces Kernel::silence_warnings since it hides any warnings,
# including the RuboCop ones
old_verbose = $VERBOSE
$VERBOSE = nil
yield
ensure
$VERBOSE = old_verbose
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/rspec/shared_contexts.rb | lib/rubocop/rspec/shared_contexts.rb | # frozen_string_literal: true
require 'tmpdir'
RSpec.shared_context 'isolated environment' do # rubocop:disable Metrics/BlockLength
around do |example|
Dir.mktmpdir do |tmpdir|
original_home = Dir.home
original_xdg_config_home = ENV.fetch('XDG_CONFIG_HOME', nil)
# Make sure to expand all symlinks in the path first. Otherwise we may
# get mismatched pathnames when loading config files later on.
tmpdir = File.realpath(tmpdir)
# Make upwards search for .rubocop.yml files stop at this directory.
RuboCop::FileFinder.root_level = tmpdir
virtual_home = File.expand_path(File.join(tmpdir, 'home'))
Dir.mkdir(virtual_home)
ENV['HOME'] = virtual_home
ENV.delete('XDG_CONFIG_HOME')
base_dir = example.metadata[:project_inside_home] ? virtual_home : tmpdir
root = example.metadata[:root]
working_dir = root ? File.join(base_dir, 'work', root) : File.join(base_dir, 'work')
begin
FileUtils.mkdir_p(working_dir)
Dir.chdir(working_dir) { example.run }
ensure
ENV['HOME'] = original_home
ENV['XDG_CONFIG_HOME'] = original_xdg_config_home
RuboCop::FileFinder.root_level = nil
end
end
end
if RuboCop.const_defined?(:Server)
around do |example|
RuboCop::Server::Cache.cache_root_path = nil
RuboCop::Server::Cache.instance_variable_set(:@project_dir_cache_key, nil)
begin
example.run
ensure
RuboCop::Server::Cache.cache_root_path = nil
RuboCop::Server::Cache.instance_variable_set(:@project_dir_cache_key, nil)
end
end
end
end
# Workaround for https://github.com/rubocop/rubocop/issues/12978,
# there should already be no gemfile in the temp directory
RSpec.shared_context 'isolated bundler' do
around do |example|
# No bundler env and reset cached gemfile path
Bundler.with_unbundled_env do
old_values = Bundler.instance_variables.to_h do |name|
[name, Bundler.instance_variable_get(name)]
end
Bundler.instance_variables.each { |name| Bundler.remove_instance_variable(name) }
example.call
ensure
Bundler.instance_variables.each { |name| Bundler.remove_instance_variable(name) }
old_values.each do |name, value|
Bundler.instance_variable_set(name, value)
end
end
end
end
RSpec.shared_context 'maintain registry' do
around(:each) { |example| RuboCop::Cop::Registry.with_temporary_global { example.run } }
def stub_cop_class(name, inherit: RuboCop::Cop::Base, &block)
klass = Class.new(inherit, &block)
stub_const(name, klass)
klass
end
end
RSpec.shared_context 'maintain default configuration' do
around(:each) do |example|
# Make a copy of the current configuration that will not change when source hash changes
default_configuration = RuboCop::ConfigLoader.default_configuration
config = RuboCop::Config.create(
default_configuration.to_h.clone,
default_configuration.loaded_path
)
example.run
RuboCop::ConfigLoader.instance_variable_set(:@default_configuration, config)
end
end
# This context assumes nothing and defines `cop`, among others.
RSpec.shared_context 'config' do # rubocop:disable Metrics/BlockLength
### Meant to be overridden at will
let(:cop_class) do
unless described_class.is_a?(Class) && described_class < RuboCop::Cop::Base
raise 'Specify which cop class to use (e.g `let(:cop_class) { RuboCop::Cop::Base }`)'
end
described_class
end
let(:cop_config) { {} }
let(:other_cops) { {} }
let(:cop_options) { {} }
let(:gem_versions) { {} }
### Utilities
def source_range(range, buffer: source_buffer)
Parser::Source::Range.new(buffer, range.begin,
range.exclude_end? ? range.end : range.end + 1)
end
### Useful intermediary steps (less likely to be overridden)
let(:processed_source) { parse_source(source, 'test') }
let(:source_buffer) { processed_source.buffer }
let(:all_cops_config) do
rails = { 'TargetRubyVersion' => ruby_version }
rails['TargetRailsVersion'] = rails_version if rails_version
rails
end
let(:cur_cop_config) do
RuboCop::ConfigLoader
.default_configuration.for_cop(cop_class)
.merge(
'Enabled' => true, # in case it is 'pending'
'AutoCorrect' => 'always' # in case defaults set it to 'disabled' or false
)
.merge(cop_config)
end
let(:config) do
hash = { 'AllCops' => all_cops_config, cop_class.cop_name => cur_cop_config }.merge!(other_cops)
config = RuboCop::Config.new(hash, "#{Dir.pwd}/.rubocop.yml")
rails_version_in_gemfile = Gem::Version.new(
rails_version || RuboCop::Config::DEFAULT_RAILS_VERSION
)
allow(config).to receive(:gem_versions_in_target).and_return(
{
'railties' => rails_version_in_gemfile,
**gem_versions.transform_values { |value| Gem::Version.new(value) }
}
)
config
end
let(:cop) { cop_class.new(config, cop_options) }
end
RSpec.shared_context 'mock console output' do
before do
$stdout = StringIO.new
$stderr = StringIO.new
end
after do
$stdout = STDOUT
$stderr = STDERR
end
end
RSpec.shared_context 'mock obsoletion' do
include_context 'mock console output'
let(:obsoletion_configuration_path) { 'obsoletions.yml' }
before do
RuboCop::ConfigObsoletion.reset!
allow(RuboCop::ConfigObsoletion).to receive(:files).and_return([obsoletion_configuration_path])
end
after do
RuboCop::ConfigObsoletion.reset!
end
end
RSpec.shared_context 'lsp' do
before do
RuboCop::LSP.enable
end
after do
RuboCop::LSP.disable
end
end
RSpec.shared_context 'ruby 2.0' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.0 }
end
RSpec.shared_context 'ruby 2.1' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.1 }
end
RSpec.shared_context 'ruby 2.2' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.2 }
end
RSpec.shared_context 'ruby 2.3' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.3 }
end
RSpec.shared_context 'ruby 2.4' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.4 }
end
RSpec.shared_context 'ruby 2.5' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.5 }
end
RSpec.shared_context 'ruby 2.6' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.6 }
end
RSpec.shared_context 'ruby 2.7' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 2.7 }
end
RSpec.shared_context 'ruby 3.0' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 3.0 }
end
RSpec.shared_context 'ruby 3.1' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 3.1 }
end
RSpec.shared_context 'ruby 3.2' do
# Prism supports parsing Ruby 3.3+.
let(:ruby_version) { ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : 3.2 }
end
RSpec.shared_context 'ruby 3.3' do
let(:ruby_version) { 3.3 }
end
RSpec.shared_context 'ruby 3.4' do
let(:ruby_version) { 3.4 }
end
RSpec.shared_context 'ruby 4.0' do
let(:ruby_version) { 4.0 }
end
RSpec.shared_context 'ruby 4.1' do
let(:ruby_version) { 4.1 }
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/rspec/cop_helper.rb | lib/rubocop/rspec/cop_helper.rb | # frozen_string_literal: true
require 'tempfile'
# This module provides methods that make it easier to test Cops.
module CopHelper
extend RSpec::SharedContext
let(:ruby_version) do
# The minimum version Prism can parse is 3.3.
ENV['PARSER_ENGINE'] == 'parser_prism' ? 3.3 : RuboCop::TargetRuby::DEFAULT_VERSION
end
let(:parser_engine) do
# The maximum version Parser can correctly parse is 3.3.
ruby_version >= 3.4 ? :parser_prism : ENV.fetch('PARSER_ENGINE', :parser_whitequark).to_sym
end
let(:rails_version) { false }
before(:all) do
next if ENV['RUBOCOP_CORE_DEVELOPMENT']
plugins = Gem.loaded_specs.filter_map do |feature_name, feature_specification|
feature_name if feature_specification.metadata['default_lint_roller_plugin']
end
RuboCop::Plugin.integrate_plugins(RuboCop::Config.new, plugins)
end
def inspect_source(source, file = nil)
RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
processed_source = parse_source(source, file)
unless processed_source.valid_syntax?
raise 'Error parsing example code: ' \
"#{processed_source.diagnostics.map(&:render).join("\n")}"
end
_investigate(cop, processed_source)
end
def parse_source(source, file = nil)
if file.respond_to?(:write)
file.write(source)
file.rewind
file = file.path
end
processed_source = RuboCop::ProcessedSource.new(
source, ruby_version, file, parser_engine: parser_engine
)
processed_source.config = configuration
processed_source.registry = registry
processed_source
end
def configuration
@configuration ||= if defined?(config)
config
else
RuboCop::Config.new({}, "#{Dir.pwd}/.rubocop.yml")
end
end
def registry
@registry ||= begin
keys = configuration.keys
cops =
keys.map { |directive| RuboCop::Cop::Registry.global.find_cops_by_directive(directive) }
.flatten
cops << cop_class if defined?(cop_class) && !cops.include?(cop_class)
cops.compact!
RuboCop::Cop::Registry.new(cops)
end
end
def autocorrect_source_file(source)
Tempfile.open('tmp') { |f| autocorrect_source(source, f) }
end
def autocorrect_source(source, file = nil)
RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
cop.instance_variable_get(:@options)[:autocorrect] = true
processed_source = parse_source(source, file)
_investigate(cop, processed_source)
@last_corrector.rewrite
end
def _investigate(cop, processed_source)
team = RuboCop::Cop::Team.new([cop], configuration, raise_error: true)
report = team.investigate(processed_source)
@last_corrector = report.correctors.first || RuboCop::Cop::Corrector.new(processed_source)
report.offenses.reject(&:disabled?)
end
end
module RuboCop
module Cop
# Monkey-patch Cop for tests to provide easy access to messages and
# highlights.
class Cop
def messages
offenses.sort.map(&:message)
end
def highlights
offenses.sort.map { |o| o.location.source }
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/rspec/parallel_formatter.rb | lib/rubocop/rspec/parallel_formatter.rb | # frozen_string_literal: true
RSpec::Support.require_rspec_core 'formatters/base_text_formatter'
RSpec::Support.require_rspec_core 'formatters/console_codes'
module RuboCop
module RSpec
# RSpec formatter for use with running `rake spec` in parallel. This formatter
# removes much of the noise from RSpec so that only the important information
# will be surfaced by test-queue.
# It also adds metadata to the output in order to more easily find the text
# needed for outputting after the parallel run completes.
class ParallelFormatter < ::RSpec::Core::Formatters::BaseTextFormatter
::RSpec::Core::Formatters.register self, :dump_pending, :dump_failures, :dump_summary
# Don't show pending tests
def dump_pending(*); end
# The BEGIN/END comments are used by `spec_runner.rake` to determine what
# output goes where in the final parallelized output, and should not be
# removed!
def dump_failures(notification)
return if notification.failure_notifications.empty?
output.puts '# FAILURES BEGIN'
notification.failure_notifications.each do |failure|
output.puts failure.fully_formatted('*', colorizer)
end
output.puts
output.puts '# FAILURES END'
end
def dump_summary(summary)
output_summary(summary)
output_rerun_commands(summary)
end
private
def colorizer
@colorizer ||= ::RSpec::Core::Formatters::ConsoleCodes
end
# The BEGIN/END comments are used by `spec_runner.rake` to determine what
# output goes where in the final parallelized output, and should not be
# removed!
def output_summary(summary)
output.puts '# SUMMARY BEGIN'
output.puts colorize_summary(summary)
output.puts '# SUMMARY END'
end
def colorize_summary(summary)
totals = totals(summary)
if summary.failure_count.positive? || summary.errors_outside_of_examples_count.positive?
colorizer.wrap(totals, ::RSpec.configuration.failure_color)
else
colorizer.wrap(totals, ::RSpec.configuration.success_color)
end
end
# The BEGIN/END comments are used by `spec_runner.rake` to determine what
# output goes where in the final parallelized output, and should not be
# removed!
def output_rerun_commands(summary)
output.puts '# RERUN BEGIN'
output.puts summary.colorized_rerun_commands.lines[3..].join
output.puts '# RERUN END'
end
def totals(summary)
output = pluralize(summary.example_count, 'example')
output += ", #{summary.pending_count} pending" if summary.pending_count.positive?
output += ", #{pluralize(summary.failure_count, 'failure')}"
if summary.errors_outside_of_examples_count.positive?
error_count = pluralize(summary.errors_outside_of_examples_count, 'error')
output += ", #{error_count} occurred outside of examples"
end
output
end
def pluralize(*args)
::RSpec::Core::Formatters::Helpers.pluralize(*args)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/rspec/expect_offense.rb | lib/rubocop/rspec/expect_offense.rb | # frozen_string_literal: true
module RuboCop
module RSpec
# Mixin for `expect_offense` and `expect_no_offenses`
#
# This mixin makes it easier to specify strict offense expectations
# in a declarative and visual fashion. Just type out the code that
# should generate an offense, annotate code by writing '^'s
# underneath each character that should be highlighted, and follow
# the carets with a string (separated by a space) that is the
# message of the offense. You can include multiple offenses in
# one code snippet.
#
# @example Usage
#
# expect_offense(<<~RUBY)
# a do
# b
# end.c
# ^^^^^ Avoid chaining a method call on a do...end block.
# RUBY
#
# @example Equivalent assertion without `expect_offense`
#
# inspect_source(<<~RUBY)
# a do
# b
# end.c
# RUBY
#
# expect(cop.offenses.size).to be(1)
#
# offense = cop.offenses.first
# expect(offense.line).to be(3)
# expect(offense.column_range).to be(0...5)
# expect(offense.message).to eql(
# 'Avoid chaining a method call on a do...end block.'
# )
#
# Autocorrection can be tested using `expect_correction` after
# `expect_offense`.
#
# @example `expect_offense` and `expect_correction`
#
# expect_offense(<<~RUBY)
# x % 2 == 0
# ^^^^^^^^^^ Replace with `Integer#even?`.
# RUBY
#
# expect_correction(<<~RUBY)
# x.even?
# RUBY
#
# If you do not want to specify an offense then use the
# companion method `expect_no_offenses`. This method is a much
# simpler assertion since it just inspects the source and checks
# that there were no offenses. The `expect_offense` method has
# to do more work by parsing out lines that contain carets.
#
# If the code produces an offense that could not be autocorrected, you can
# use `expect_no_corrections` after `expect_offense`.
#
# @example `expect_offense` and `expect_no_corrections`
#
# expect_offense(<<~RUBY)
# a do
# b
# end.c
# ^^^^^ Avoid chaining a method call on a do...end block.
# RUBY
#
# expect_no_corrections
#
# If your code has variables of different lengths, you can use the
# following markers to format your template by passing the variables as a
# keyword arguments:
#
# - `%{foo}`: Interpolates `foo`
# - `^{foo}`: Inserts `'^' * foo.size` for dynamic offense range length
# - `_{foo}`: Inserts `' ' * foo.size` for dynamic offense range indentation
#
# You can also abbreviate offense messages with `[...]`.
#
# %w[raise fail].each do |keyword|
# expect_offense(<<~RUBY, keyword: keyword)
# %{keyword}(RuntimeError, msg)
# ^{keyword}^^^^^^^^^^^^^^^^^^^ Redundant `RuntimeError` argument [...]
# RUBY
#
# %w[has_one has_many].each do |type|
# expect_offense(<<~RUBY, type: type)
# class Book
# %{type} :chapter, foreign_key: 'book_id'
# _{type} ^^^^^^^^^^^^^^^^^^^^^^ Specifying the default [...]
# end
# RUBY
# end
#
# If you need to specify an offense on a blank line, use the empty `^{}` marker:
#
# @example `^{}` empty line offense
#
# expect_offense(<<~RUBY)
#
# ^{} Missing frozen string literal comment.
# puts 1
# RUBY
module ExpectOffense
def format_offense(source, **replacements)
replacements.each do |keyword, value|
value = value.to_s
source = source.gsub("%{#{keyword}}", value)
.gsub("^{#{keyword}}", '^' * value.size)
.gsub("_{#{keyword}}", ' ' * value.size)
end
source
end
# rubocop:disable Metrics/AbcSize
def expect_offense(source, file = nil, severity: nil, chomp: false, **replacements)
expected_annotations = parse_annotations(source, **replacements)
source = expected_annotations.plain_source
source = source.chomp if chomp
@processed_source = parse_processed_source(source, file)
@offenses = _investigate(cop, @processed_source)
actual_annotations = expected_annotations.with_offense_annotations(@offenses)
expect(actual_annotations).to eq(expected_annotations), ''
expect(@offenses.map(&:severity).uniq).to eq([severity]) if severity
# Validate that all offenses have a range that formatters can display
expect do
@offenses.each { |offense| offense.location.source_line }
end.not_to raise_error, 'One of the offenses has a misconstructed range, for ' \
'example if the offense is on line 1 and the source is empty'
@offenses
end
# rubocop:enable Metrics/AbcSize
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity
def expect_correction(correction, loop: true, source: nil)
if source
expected_annotations = parse_annotations(source, raise_error: false)
@processed_source = parse_processed_source(expected_annotations.plain_source)
_investigate(cop, @processed_source)
end
raise '`expect_correction` must follow `expect_offense`' unless @processed_source
source = @processed_source.raw_source
raise 'Use `expect_no_corrections` if the code will not change' if correction == source
iteration = 0
new_source = loop do
iteration += 1
corrected_source = @last_corrector.rewrite
break corrected_source unless loop
break corrected_source if @last_corrector.empty?
if iteration > RuboCop::Runner::MAX_ITERATIONS
raise RuboCop::Runner::InfiniteCorrectionLoop.new(@processed_source.path, [@offenses])
end
# Prepare for next loop
@processed_source = parse_source(corrected_source, @processed_source.path)
_investigate(cop, @processed_source)
end
raise 'Expected correction but no corrections were made' if new_source == source
expect(new_source).to eq(correction)
expect(@processed_source).to be_valid_syntax, 'Expected correction to be valid syntax'
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity
def expect_no_corrections
raise '`expect_no_corrections` must follow `expect_offense`' unless @processed_source
return if @last_corrector.empty?
# This is just here for a pretty diff if the source actually got changed
new_source = @last_corrector.rewrite
expect(new_source).to eq(@processed_source.buffer.source)
# There is an infinite loop if a corrector is present that did not make
# any changes. It will cause the same offense/correction on the next loop.
raise RuboCop::Runner::InfiniteCorrectionLoop.new(@processed_source.path, [@offenses])
end
def expect_no_offenses(source, file = nil)
offenses = inspect_source(source, file)
# Since source given `expect_no_offenses` does not have annotations, we do not need to parse
# for them, and can just build an `AnnotatedSource` object from the source lines.
# This also prevents treating source lines that begin with a caret as an annotation.
expected_annotations = AnnotatedSource.new(source.each_line.to_a, [])
actual_annotations = expected_annotations.with_offense_annotations(offenses)
expect(actual_annotations.to_s).to eq(source)
end
def parse_annotations(source, raise_error: true, **replacements)
set_formatter_options
source = format_offense(source, **replacements)
annotations = AnnotatedSource.parse(source)
return annotations unless raise_error && annotations.plain_source == source
raise 'Use `expect_no_offenses` to assert that no offenses are found'
end
def parse_processed_source(source, file = nil)
processed_source = parse_source(source, file)
return processed_source if processed_source.valid_syntax?
raise 'Error parsing example code: ' \
"#{processed_source.diagnostics.map(&:render).join("\n")}"
end
def set_formatter_options
RuboCop::Formatter::DisabledConfigFormatter.config_to_allow_offenses = {}
RuboCop::Formatter::DisabledConfigFormatter.detected_styles = {}
cop.instance_variable_get(:@options)[:autocorrect] = true
end
# Parsed representation of code annotated with the `^^^ Message` style
class AnnotatedSource
# Ignore escaped carets, don't treat as annotations
ANNOTATION_PATTERN = /\A\s*((?<!\\)\^+|\^{}) ?/.freeze
ABBREV = "[...]\n"
# @param annotated_source [String] string passed to the matchers
#
# Separates annotation lines from source lines. Tracks the real
# source line number that each annotation corresponds to.
#
# @return [AnnotatedSource]
def self.parse(annotated_source)
source = []
annotations = []
annotated_source.each_line do |source_line|
if ANNOTATION_PATTERN.match?(source_line)
annotations << [source.size, source_line]
else
source << source_line
end
end
annotations.each { |a| a[0] = 1 } if source.empty?
new(source, annotations)
end
# @param lines [Array<String>]
# @param annotations [Array<(Integer, String)>]
# each entry is the annotated line number and the annotation text
#
# @note annotations are sorted so that reconstructing the annotation
# text via {#to_s} is deterministic
def initialize(lines, annotations)
@lines = lines.freeze
@annotations = annotations.sort.freeze
end
def ==(other)
other.is_a?(self.class) && other.lines == lines && match_annotations?(other)
end
# Dirty hack: expectations with [...] are rewritten when they match
# This way the diff is clean.
def match_annotations?(other)
annotations.zip(other.annotations) do |(_actual_line, actual_annotation),
(_expected_line, expected_annotation)|
if expected_annotation&.end_with?(ABBREV) &&
actual_annotation.start_with?(expected_annotation[0...-ABBREV.length])
expected_annotation.replace(actual_annotation)
end
end
annotations == other.annotations
end
# Construct annotated source string (like what we parse)
#
# Reconstruct a deterministic annotated source string. This is
# useful for eliminating semantically irrelevant annotation
# ordering differences.
#
# @example standardization
#
# source1 = AnnotatedSource.parse(<<-RUBY)
# line1
# ^ Annotation 1
# ^^ Annotation 2
# RUBY
#
# source2 = AnnotatedSource.parse(<<-RUBY)
# line1
# ^^ Annotation 2
# ^ Annotation 1
# RUBY
#
# source1.to_s == source2.to_s # => true
#
# @return [String]
def to_s
reconstructed = lines.dup
annotations.reverse_each do |line_number, annotation|
reconstructed.insert(line_number, annotation)
end
reconstructed.join
end
alias inspect to_s
# Return the plain source code without annotations
#
# @return [String]
def plain_source
lines.join
end
# Annotate the source code with the RuboCop offenses provided
#
# @param offenses [Array<RuboCop::Cop::Offense>]
#
# @return [self]
def with_offense_annotations(offenses)
offense_annotations =
offenses.map do |offense|
indent = ' ' * offense.column
carets = '^' * offense.column_length
carets = '^{}' if offense.column_length.zero?
[offense.line, "#{indent}#{carets} #{offense.message}\n"]
end
self.class.new(lines, offense_annotations)
end
protected
attr_reader :lines, :annotations
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/rspec/support.rb | lib/rubocop/rspec/support.rb | # frozen_string_literal: true
# Require this file to load code that supports testing using RSpec.
require_relative 'cop_helper'
require_relative 'expect_offense'
require_relative 'parallel_formatter'
require_relative 'shared_contexts'
RSpec.configure do |config|
config.include CopHelper
config.include RuboCop::RSpec::ExpectOffense
config.include_context 'config', :config
config.include_context 'isolated environment', :isolated_environment
config.include_context 'isolated bundler', :isolated_bundler
config.include_context 'lsp', :lsp
config.include_context 'maintain registry', :restore_registry
config.include_context 'maintain default configuration', :restore_configuration
config.include_context 'mock obsoletion', :mock_obsoletion
config.include_context 'ruby 2.0', :ruby20
config.include_context 'ruby 2.1', :ruby21
config.include_context 'ruby 2.2', :ruby22
config.include_context 'ruby 2.3', :ruby23
config.include_context 'ruby 2.4', :ruby24
config.include_context 'ruby 2.5', :ruby25
config.include_context 'ruby 2.6', :ruby26
config.include_context 'ruby 2.7', :ruby27
config.include_context 'ruby 3.0', :ruby30
config.include_context 'ruby 3.1', :ruby31
config.include_context 'ruby 3.2', :ruby32
config.include_context 'ruby 3.3', :ruby33
config.include_context 'ruby 3.4', :ruby34
config.include_context 'ruby 4.0', :ruby40
config.include_context 'ruby 4.1', :ruby41
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/plugin/load_error.rb | lib/rubocop/plugin/load_error.rb | # frozen_string_literal: true
module RuboCop
module Plugin
# An exception raised when a plugin fails to load.
# @api private
class LoadError < Error
def initialize(plugin_name)
super
@plugin_name = plugin_name
end
def message
<<~MESSAGE
Failed to load plugin `#{@plugin_name}` because the corresponding plugin class could not be determined for instantiation.
Try upgrading it first (e.g., `bundle update #{@plugin_name}`).
If `#{@plugin_name}` is not yet a plugin, use `require: #{@plugin_name}` instead of `plugins: #{@plugin_name}` in your configuration.
For further assistance, check with the developer regarding the following points:
https://docs.rubocop.org/rubocop/plugin_migration_guide.html
MESSAGE
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/plugin/loader.rb | lib/rubocop/plugin/loader.rb | # frozen_string_literal: true
require_relative '../feature_loader'
require_relative 'load_error'
module RuboCop
module Plugin
# A class for loading and resolving plugins.
# @api private
class Loader
# rubocop:disable Layout/LineLength
DEFAULT_PLUGIN_CONFIG = {
'enabled' => true,
'require_path' => nil, # If not set, will be set to the plugin name
'plugin_class_name' => nil # If not set, looks for gemspec `spec.metadata["default_lint_roller_plugin"]`
}.freeze
# rubocop:enable Layout/LineLength
class << self
def load(plugins)
normalized_plugin_configs = normalize(plugins)
normalized_plugin_configs.filter_map do |plugin_name, plugin_config|
next unless plugin_config['enabled']
plugin_class = constantize_plugin_from(plugin_name, plugin_config)
plugin_class.new(plugin_config)
end
end
private
# rubocop:disable Metrics/MethodLength
def normalize(plugin_configs)
plugin_configs.to_h do |plugin_config|
if plugin_config == Plugin::OBSOLETE_INTERNAL_AFFAIRS_PLUGIN_NAME
warn Rainbow(<<~MESSAGE).yellow
Specify `rubocop-internal_affairs` instead of `rubocop/cop/internal_affairs` in your configuration.
MESSAGE
plugin_config = Plugin::INTERNAL_AFFAIRS_PLUGIN_NAME
end
if plugin_config.is_a?(Hash)
plugin_name = plugin_config.keys.first
[
plugin_name, DEFAULT_PLUGIN_CONFIG.merge(
{ 'require_path' => plugin_name }, plugin_config.values.first
)
]
# NOTE: Compatibility is maintained when `require: rubocop/cop/internal_affairs` remains
# specified in `.rubocop.yml`.
elsif (builtin_plugin_config = Plugin::BUILTIN_INTERNAL_PLUGINS[plugin_config])
[plugin_config, builtin_plugin_config]
else
[plugin_config, DEFAULT_PLUGIN_CONFIG.merge('require_path' => plugin_config)]
end
end
end
def constantize_plugin_from(plugin_name, plugin_config)
if plugin_name.is_a?(String) || plugin_name.is_a?(Symbol)
constantize(plugin_name, plugin_config)
else
plugin_name
end
end
# rubocop:enable Metrics/MethodLength
def constantize(plugin_name, plugin_config)
require_plugin(plugin_config['require_path'])
if (constant_name = plugin_config['plugin_class_name'])
begin
Kernel.const_get(constant_name)
rescue StandardError
raise <<~MESSAGE
Failed while configuring plugin `#{plugin_name}': no constant with name `#{constant_name}' was found.
MESSAGE
end
else
constantize_plugin_from_gemspec_metadata(plugin_name)
end
end
def require_plugin(require_path)
FeatureLoader.load(config_directory_path: Dir.pwd, feature: require_path)
end
def constantize_plugin_from_gemspec_metadata(plugin_name)
plugin_class_name = Gem.loaded_specs[plugin_name].metadata['default_lint_roller_plugin']
Kernel.const_get(plugin_class_name)
rescue LoadError, StandardError
raise Plugin::LoadError, plugin_name
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/plugin/not_supported_error.rb | lib/rubocop/plugin/not_supported_error.rb | # frozen_string_literal: true
module RuboCop
module Plugin
# An exception raised when a plugin is not supported by the RuboCop engine.
# @api private
class NotSupportedError < Error
def initialize(unsupported_plugins)
super
@unsupported_plugins = unsupported_plugins
end
def message
if @unsupported_plugins.one?
about = @unsupported_plugins.first.about
"#{about.name} #{about.version} is not a plugin supported by RuboCop engine."
else
unsupported_plugin_names = @unsupported_plugins.map do |plugin|
"#{plugin.about.name} #{plugin.about.version}"
end.join(', ')
"#{unsupported_plugin_names} are not plugins supported by RuboCop engine."
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/plugin/configuration_integrator.rb | lib/rubocop/plugin/configuration_integrator.rb | # frozen_string_literal: true
require 'lint_roller/context'
require_relative 'not_supported_error'
module RuboCop
module Plugin
# A class for integrating plugin configurations into RuboCop.
# Handles configuration merging, validation, and compatibility for plugins.
# @api private
class ConfigurationIntegrator
class << self
def integrate_plugins_into_rubocop_config(rubocop_config, plugins)
default_config = ConfigLoader.default_configuration
runner_context = create_context(rubocop_config)
validate_plugins!(plugins, runner_context)
plugin_config = combine_rubocop_configs(default_config, runner_context, plugins).to_h
merge_plugin_config_into_all_cops!(default_config, plugin_config)
merge_plugin_config_into_default_config!(default_config, plugin_config)
end
private
def create_context(rubocop_config)
LintRoller::Context.new(
runner: :rubocop,
runner_version: Version.version,
engine: :rubocop,
engine_version: Version.version,
target_ruby_version: rubocop_config.target_ruby_version
)
end
def validate_plugins!(plugins, runner_context)
unsupported_plugins = plugins.reject { |plugin| plugin.supported?(runner_context) }
return if unsupported_plugins.none?
raise Plugin::NotSupportedError, unsupported_plugins
end
def combine_rubocop_configs(default_config, runner_context, plugins)
fake_out_rubocop_default_configuration(default_config) do |fake_config|
all_cop_keys_configured_by_plugins = []
plugins.reduce(fake_config) do |combined_config, plugin|
RuboCop::ConfigLoader.instance_variable_set(:@default_configuration, combined_config)
print 'Plugin ' if ConfigLoader.debug
plugin_config, plugin_config_path = load_plugin_rubocop_config(plugin, runner_context)
plugin_config['AllCops'], all_cop_keys_configured_by_plugins = merge_all_cop_settings(
combined_config['AllCops'], plugin_config['AllCops'],
all_cop_keys_configured_by_plugins
)
plugin_config.make_excludes_absolute
ConfigLoader.merge_with_default(plugin_config, plugin_config_path)
end
end
end
def merge_plugin_config_into_all_cops!(rubocop_config, plugin_config)
rubocop_config['AllCops'].merge!(plugin_config['AllCops'])
end
def merge_plugin_config_into_default_config!(default_config, plugin_config)
plugin_config.each do |key, value|
default_config[key] = if default_config[key].is_a?(Hash)
resolver.merge(default_config[key], value)
else
value
end
end
end
def fake_out_rubocop_default_configuration(default_config)
orig_default_config = ConfigLoader.instance_variable_get(:@default_configuration)
result = yield default_config
ConfigLoader.instance_variable_set(:@default_configuration, orig_default_config)
result
end
# rubocop:disable Metrics/AbcSize
def load_plugin_rubocop_config(plugin, runner_context)
rules = plugin.rules(runner_context)
case rules.type
when :path
[ConfigLoader.load_file(rules.value, check: false), rules.value]
when :object
path = plugin.method(:rules).source_location[0]
[Config.create(rules.value, path, check: true), path]
when :error
plugin_name = plugin.about&.name || plugin.inspect
error_message = rules.value.respond_to?(:message) ? rules.value.message : rules.value
raise "Plugin `#{plugin_name}' failed to load with error: #{error_message}"
end
end
# rubocop:enable Metrics/AbcSize
# This is how we ensure "first-in wins": plugins can override AllCops settings that are
# set by RuboCop's default configuration, but once a plugin sets an AllCop setting, they
# have exclusive first-in-wins rights to that setting.
#
# The one exception to this are array fields, because we don't want to
# overwrite the AllCops defaults but rather munge the arrays (`existing |
# new`) to allow plugins to add to the array, for example Include and
# Exclude paths and patterns.
def merge_all_cop_settings(existing_all_cops, new_all_cops, already_configured_keys)
return [existing_all_cops, already_configured_keys] unless new_all_cops.is_a?(Hash)
combined_all_cops = existing_all_cops.dup
combined_configured_keys = already_configured_keys.dup
new_all_cops.each do |key, value|
if combined_all_cops[key].is_a?(Array) && value.is_a?(Array)
combined_all_cops[key] |= value
combined_configured_keys |= [key]
elsif !combined_configured_keys.include?(key)
combined_all_cops[key] = value
combined_configured_keys << key
end
end
[combined_all_cops, combined_configured_keys]
end
def resolver
@resolver ||= ConfigLoaderResolver.new
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp/stdin_runner.rb | lib/rubocop/lsp/stdin_runner.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/standardrb/standard.
#
# Copyright (c) 2023 Test Double, Inc.
#
# The MIT License (MIT)
#
# https://github.com/standardrb/standard/blob/main/LICENSE.txt
#
module RuboCop
module Lsp
# Originally lifted from:
# https://github.com/Shopify/ruby-lsp/blob/8d4c17efce4e8ecc8e7c557ab2981db6b22c0b6d/lib/ruby_lsp/requests/support/rubocop_runner.rb#L20
# @api private
class StdinRunner < RuboCop::Runner
class ConfigurationError < StandardError; end
attr_reader :offenses, :config_for_working_directory
DEFAULT_RUBOCOP_OPTIONS = {
stderr: true,
force_exclusion: true,
formatters: ['RuboCop::Formatter::BaseFormatter'],
raise_cop_error: true,
todo_file: nil,
todo_ignore_files: []
}.freeze
def initialize(config_store)
@options = {}
@offenses = []
@warnings = []
@errors = []
@config_for_working_directory = config_store.for_pwd
super(@options, config_store)
end
def run(path, contents, options, prism_result: nil)
@options = options.merge(DEFAULT_RUBOCOP_OPTIONS)
@options[:stdin] = contents
@prism_result = prism_result
@offenses = []
@warnings = []
@errors = []
super([path])
raise Interrupt if aborting?
end
def formatted_source
@options[:stdin]
end
private
def file_finished(_file, offenses)
@offenses = offenses
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp/severity.rb | lib/rubocop/lsp/severity.rb | # frozen_string_literal: true
module RuboCop
module LSP
# Severity for Language Server Protocol of RuboCop.
# @api private
class Severity
SEVERITIES = {
fatal: LanguageServer::Protocol::Constant::DiagnosticSeverity::ERROR,
error: LanguageServer::Protocol::Constant::DiagnosticSeverity::ERROR,
warning: LanguageServer::Protocol::Constant::DiagnosticSeverity::WARNING,
convention: LanguageServer::Protocol::Constant::DiagnosticSeverity::INFORMATION,
refactor: LanguageServer::Protocol::Constant::DiagnosticSeverity::HINT,
info: LanguageServer::Protocol::Constant::DiagnosticSeverity::HINT
}.freeze
def self.find_by(rubocop_severity)
if (severity = SEVERITIES[rubocop_severity.to_sym])
return severity
end
Logger.log("Unknown severity: #{rubocop_severity}")
LanguageServer::Protocol::Constant::DiagnosticSeverity::HINT
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp/logger.rb | lib/rubocop/lsp/logger.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/standardrb/standard.
#
# Copyright (c) 2023 Test Double, Inc.
#
# The MIT License (MIT)
#
# https://github.com/standardrb/standard/blob/main/LICENSE.txt
#
module RuboCop
module LSP
# Log for Language Server Protocol of RuboCop.
# @api private
class Logger
def self.log(message, prefix: '[server]')
warn("#{prefix} #{message}")
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp/routes.rb | lib/rubocop/lsp/routes.rb | # frozen_string_literal: true
require_relative 'severity'
#
# This code is based on https://github.com/standardrb/standard.
#
# Copyright (c) 2023 Test Double, Inc.
#
# The MIT License (MIT)
#
# https://github.com/standardrb/standard/blob/main/LICENSE.txt
#
module RuboCop
module LSP
# Routes for Language Server Protocol of RuboCop.
# @api private
class Routes
CONFIGURATION_FILE_PATTERNS = [
RuboCop::ConfigFinder::DOTFILE,
RuboCop::CLI::Command::AutoGenerateConfig::AUTO_GENERATED_FILE
].freeze
def self.handle(name, &block)
define_method(:"handle_#{name}", &block)
end
private_class_method :handle
def initialize(server)
@server = server
@text_cache = {}
end
def for(name)
name = "handle_#{name}"
return unless respond_to?(name)
method(name)
end
handle 'initialize' do |request|
initialization_options = extract_initialization_options_from(request)
@server.configure(initialization_options)
@server.write(
id: request[:id],
result: LanguageServer::Protocol::Interface::InitializeResult.new(
capabilities: LanguageServer::Protocol::Interface::ServerCapabilities.new(
document_formatting_provider: true,
text_document_sync: LanguageServer::Protocol::Interface::TextDocumentSyncOptions.new(
change: LanguageServer::Protocol::Constant::TextDocumentSyncKind::INCREMENTAL,
open_close: true
)
)
)
)
end
handle 'initialized' do |_request|
version = RuboCop::Version::STRING
yjit = Object.const_defined?('RubyVM::YJIT') && RubyVM::YJIT.enabled? ? ' +YJIT' : ''
Logger.log("RuboCop #{version} language server#{yjit} initialized, PID #{Process.pid}")
end
handle 'shutdown' do |request|
Logger.log('Client asked to shutdown RuboCop language server.')
@server.stop do
@server.write(id: request[:id], result: nil)
Logger.log('Exiting...')
end
end
handle 'textDocument/didChange' do |request|
params = request[:params]
file_uri = params[:textDocument][:uri]
text = @text_cache[file_uri]
params[:contentChanges].each do |content|
text = change_text(text, content[:text], content[:range])
end
result = diagnostic(file_uri, text)
@server.write(result)
end
handle 'textDocument/didOpen' do |request|
doc = request[:params][:textDocument]
result = diagnostic(doc[:uri], doc[:text])
@server.write(result)
end
handle 'textDocument/didClose' do |request|
@text_cache.delete(request.dig(:params, :textDocument, :uri))
end
handle 'textDocument/formatting' do |request|
uri = request[:params][:textDocument][:uri]
@server.write(id: request[:id], result: format_file(uri))
end
handle 'workspace/didChangeConfiguration' do |_request|
Logger.log('Ignoring workspace/didChangeConfiguration')
end
handle 'workspace/didChangeWatchedFiles' do |request|
changed = request[:params][:changes].any? do |change|
CONFIGURATION_FILE_PATTERNS.any? { |path| change[:uri].end_with?(path) }
end
if changed
Logger.log('Configuration file changed; restart required')
@server.stop
end
end
handle 'workspace/executeCommand' do |request|
case (command = request[:params][:command])
when 'rubocop.formatAutocorrects'
label = 'Format with RuboCop autocorrects'
when 'rubocop.formatAutocorrectsAll'
label = 'Format all with RuboCop autocorrects'
else
handle_unsupported_method(request, command)
return
end
uri = request[:params][:arguments][0][:uri]
formatted = nil
# The `workspace/executeCommand` is an LSP method triggered by intentional user actions,
# so the user's intention for autocorrection is respected.
LSP.disable { formatted = format_file(uri, command: command) }
@server.write(
id: request[:id],
method: 'workspace/applyEdit',
params: {
label: label,
edit: {
changes: {
uri => formatted
}
}
}
)
end
handle 'textDocument/willSave' do |_request|
# Nothing to do
end
handle 'textDocument/didSave' do |_request|
# Nothing to do
end
handle '$/cancelRequest' do |_request|
# Can't cancel anything because single-threaded
end
handle '$/setTrace' do |_request|
# No-op, we log everything
end
def handle_unsupported_method(request, method = request[:method])
@server.write(
id: request[:id],
error: LanguageServer::Protocol::Interface::ResponseError.new(
code: LanguageServer::Protocol::Constant::ErrorCodes::METHOD_NOT_FOUND,
message: "Unsupported Method: #{method}"
)
)
Logger.log("Unsupported Method: #{method}")
end
def handle_method_missing(request)
return unless request.key?(:id)
@server.write(id: request[:id], result: nil)
end
private
def extract_initialization_options_from(request)
safe_autocorrect = request.dig(:params, :initializationOptions, :safeAutocorrect)
{
safe_autocorrect: safe_autocorrect.nil? || safe_autocorrect == true,
lint_mode: request.dig(:params, :initializationOptions, :lintMode) == true,
layout_mode: request.dig(:params, :initializationOptions, :layoutMode) == true
}
end
def format_file(file_uri, command: nil)
unless (text = @text_cache[file_uri])
Logger.log("Format request arrived before text synchronized; skipping: `#{file_uri}'")
return []
end
new_text = @server.format(convert_file_uri_to_path(file_uri), text, command: command)
return [] if new_text == text
[
newText: new_text,
range: {
start: { line: 0, character: 0 },
end: { line: text.count("\n") + 1, character: 0 }
}
]
end
def diagnostic(file_uri, text)
@text_cache[file_uri] = text
{
method: 'textDocument/publishDiagnostics',
params: {
uri: file_uri,
diagnostics: @server.offenses(convert_file_uri_to_path(file_uri), text)
}
}
end
def change_text(orig_text, text, range)
return text unless range
start_pos = text_pos(orig_text, range[:start])
end_pos = text_pos(orig_text, range[:end])
text_bin = orig_text.b
text_bin[start_pos...end_pos] = text.b
text_bin.force_encoding(orig_text.encoding)
end
def text_pos(text, range)
line = range[:line]
char = range[:character]
pos = 0
text.each_line.with_index do |l, i|
if i == line
pos += l.encode('utf-16be').b[0, char * 2].encode('utf-8', 'utf-16be').bytesize
return pos
end
pos += l.bytesize
end
pos
end
def convert_file_uri_to_path(uri)
URI.decode_www_form_component(uri.delete_prefix('file://'))
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp/diagnostic.rb | lib/rubocop/lsp/diagnostic.rb | # frozen_string_literal: true
require_relative 'severity'
#
# This code is based on https://github.com/standardrb/standard.
#
# Copyright (c) 2023 Test Double, Inc.
#
# The MIT License (MIT)
#
# https://github.com/standardrb/standard/blob/main/LICENSE.txt
#
module RuboCop
module LSP
# Diagnostic for Language Server Protocol of RuboCop.
# @api private
class Diagnostic
def initialize(document_encoding, offense, uri, cop_class)
@document_encoding = document_encoding
@offense = offense
@uri = uri
@cop_class = cop_class
end
def to_lsp_code_actions
code_actions = []
code_actions << autocorrect_action if correctable?
code_actions << disable_line_action
code_actions
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def to_lsp_diagnostic(config)
highlighted = @offense.highlighted_area
LanguageServer::Protocol::Interface::Diagnostic.new(
message: message,
source: 'RuboCop',
code: @offense.cop_name,
code_description: code_description(config),
severity: severity,
range: LanguageServer::Protocol::Interface::Range.new(
start: LanguageServer::Protocol::Interface::Position.new(
line: @offense.line - 1,
character: to_position_character(highlighted.begin_pos)
),
end: LanguageServer::Protocol::Interface::Position.new(
line: @offense.line - 1,
character: to_position_character(highlighted.end_pos)
)
),
data: {
correctable: correctable?,
code_actions: to_lsp_code_actions
}
)
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
private
def message
message = @offense.message
message += "\n\nThis offense is not autocorrectable.\n" unless correctable?
message
end
def severity
Severity.find_by(@offense.severity.name)
end
def code_description(config)
return unless @cop_class
return unless (doc_url = @cop_class.documentation_url(config))
LanguageServer::Protocol::Interface::CodeDescription.new(href: doc_url)
end
# rubocop:disable Metrics/MethodLength
def autocorrect_action
LanguageServer::Protocol::Interface::CodeAction.new(
title: "Autocorrect #{@offense.cop_name}",
kind: LanguageServer::Protocol::Constant::CodeActionKind::QUICK_FIX,
edit: LanguageServer::Protocol::Interface::WorkspaceEdit.new(
document_changes: [
LanguageServer::Protocol::Interface::TextDocumentEdit.new(
text_document: LanguageServer::Protocol::Interface::OptionalVersionedTextDocumentIdentifier.new(
uri: ensure_uri_scheme(@uri.to_s).to_s,
version: nil
),
edits: correctable? ? offense_replacements : []
)
]
),
is_preferred: true
)
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
def offense_replacements
@offense.corrector.as_replacements.map do |range, replacement|
LanguageServer::Protocol::Interface::TextEdit.new(
range: LanguageServer::Protocol::Interface::Range.new(
start: LanguageServer::Protocol::Interface::Position.new(
line: range.line - 1,
character: to_position_character(range.column)
),
end: LanguageServer::Protocol::Interface::Position.new(
line: range.last_line - 1,
character: to_position_character(range.last_column)
)
),
new_text: replacement
)
end
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
def disable_line_action
LanguageServer::Protocol::Interface::CodeAction.new(
title: "Disable #{@offense.cop_name} for this line",
kind: LanguageServer::Protocol::Constant::CodeActionKind::QUICK_FIX,
edit: LanguageServer::Protocol::Interface::WorkspaceEdit.new(
document_changes: [
LanguageServer::Protocol::Interface::TextDocumentEdit.new(
text_document: LanguageServer::Protocol::Interface::OptionalVersionedTextDocumentIdentifier.new(
uri: ensure_uri_scheme(@uri.to_s).to_s,
version: nil
),
edits: line_disable_comment
)
]
)
)
end
# rubocop:enable Metrics/MethodLength
def line_disable_comment
new_text = if @offense.source_line.include?(' # rubocop:disable ')
",#{@offense.cop_name}"
else
" # rubocop:disable #{@offense.cop_name}"
end
eol = LanguageServer::Protocol::Interface::Position.new(
line: @offense.line - 1,
character: to_position_character(@offense.source_line.length)
)
# TODO: fails for multiline strings - may be preferable to use block
# comments to disable some offenses
inline_comment = LanguageServer::Protocol::Interface::TextEdit.new(
range: LanguageServer::Protocol::Interface::Range.new(start: eol, end: eol),
new_text: new_text
)
[inline_comment]
end
def to_position_character(utf8_index)
str = @offense.source_line[0, utf8_index]
if @document_encoding == Encoding::UTF_16LE || @document_encoding.nil?
str.length + str.b.count("\xf0-\xff".b)
else
str.length
end
end
def correctable?
!@offense.corrector.nil?
end
def ensure_uri_scheme(uri)
uri = URI.parse(uri)
uri.scheme = 'file' if uri.scheme.nil?
uri
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp/runtime.rb | lib/rubocop/lsp/runtime.rb | # frozen_string_literal: true
require_relative 'diagnostic'
require_relative 'stdin_runner'
#
# This code is based on https://github.com/standardrb/standard.
#
# Copyright (c) 2023 Test Double, Inc.
#
# The MIT License (MIT)
#
# https://github.com/standardrb/standard/blob/main/LICENSE.txt
#
module RuboCop
module LSP
# Runtime for Language Server Protocol of RuboCop.
# @api private
class Runtime
attr_writer :safe_autocorrect, :lint_mode, :layout_mode
def initialize(config_store)
RuboCop::LSP.enable
@runner = RuboCop::Lsp::StdinRunner.new(config_store)
@cop_registry = RuboCop::Cop::Registry.global.to_h
@safe_autocorrect = true
@lint_mode = false
@layout_mode = false
end
def format(path, text, command:, prism_result: nil)
safe_autocorrect = if command
command == 'rubocop.formatAutocorrects'
else
@safe_autocorrect
end
formatting_options = { autocorrect: true, safe_autocorrect: safe_autocorrect }
formatting_options[:only] = config_only_options if @lint_mode || @layout_mode
@runner.run(path, text, formatting_options, prism_result: prism_result)
@runner.formatted_source
end
def offenses(path, text, document_encoding = nil, prism_result: nil)
diagnostic_options = {}
diagnostic_options[:only] = config_only_options if @lint_mode || @layout_mode
@runner.run(path, text, diagnostic_options, prism_result: prism_result)
@runner.offenses.map do |offense|
Diagnostic.new(
document_encoding, offense, path, @cop_registry[offense.cop_name]&.first
).to_lsp_diagnostic(@runner.config_for_working_directory)
end
end
private
def config_only_options
only_options = []
only_options << 'Lint' if @lint_mode
only_options << 'Layout' if @layout_mode
only_options
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/lsp/server.rb | lib/rubocop/lsp/server.rb | # frozen_string_literal: true
require 'language_server-protocol'
require_relative 'logger'
require_relative 'routes'
require_relative 'runtime'
#
# This code is based on https://github.com/standardrb/standard.
#
# Copyright (c) 2023 Test Double, Inc.
#
# The MIT License (MIT)
#
# https://github.com/standardrb/standard/blob/main/LICENSE.txt
#
module RuboCop
module LSP
# Language Server Protocol of RuboCop.
# @api private
class Server
def initialize(config_store)
$PROGRAM_NAME = "rubocop --lsp #{ConfigFinder.project_root}"
@reader = LanguageServer::Protocol::Transport::Io::Reader.new($stdin)
@writer = LanguageServer::Protocol::Transport::Io::Writer.new($stdout)
@runtime = RuboCop::LSP::Runtime.new(config_store)
@routes = Routes.new(self)
end
def start
@reader.read do |request|
if !request.key?(:method)
@routes.handle_method_missing(request)
elsif (route = @routes.for(request[:method]))
route.call(request)
else
@routes.handle_unsupported_method(request)
end
rescue StandardError => e
Logger.log("Error #{e.class} #{e.message[0..100]}")
Logger.log(e.backtrace.inspect)
end
end
def write(response)
@writer.write(response)
end
def format(path, text, command:)
@runtime.format(path, text, command: command)
end
def offenses(path, text)
@runtime.offenses(path, text)
end
def configure(options)
@runtime.safe_autocorrect = options[:safe_autocorrect]
@runtime.lint_mode = options[:lint_mode]
@runtime.layout_mode = options[:layout_mode]
end
def stop(&block)
at_exit(&block) if block
exit
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/file_list_formatter.rb | lib/rubocop/formatter/file_list_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter displays just a list of the files with offenses in them,
# separated by newlines. The output is machine-parsable.
#
# Here's the format:
#
# /some/file
# /some/other/file
class FileListFormatter < BaseFormatter
def file_finished(file, offenses)
return if offenses.empty?
output.printf("%<path>s\n", path: file)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/json_formatter.rb | lib/rubocop/formatter/json_formatter.rb | # frozen_string_literal: true
require 'json'
module RuboCop
module Formatter
# This formatter formats the report data in JSON format.
class JSONFormatter < BaseFormatter
include PathUtil
attr_reader :output_hash
def initialize(output, options = {})
super
@output_hash = { metadata: metadata_hash, files: [], summary: { offense_count: 0 } }
end
def started(target_files)
output_hash[:summary][:target_file_count] = target_files.count
end
def file_finished(file, offenses)
output_hash[:files] << hash_for_file(file, offenses)
output_hash[:summary][:offense_count] += offenses.count
end
def finished(inspected_files)
output_hash[:summary][:inspected_file_count] = inspected_files.count
output.write output_hash.to_json
end
def metadata_hash
{
rubocop_version: RuboCop::Version::STRING,
ruby_engine: RUBY_ENGINE,
ruby_version: RUBY_VERSION,
ruby_patchlevel: RUBY_PATCHLEVEL.to_s,
ruby_platform: RUBY_PLATFORM
}
end
def hash_for_file(file, offenses)
{
path: smart_path(file),
offenses: offenses.map { |o| hash_for_offense(o) }
}
end
def hash_for_offense(offense)
{
severity: offense.severity.name,
message: offense.message,
cop_name: offense.cop_name,
corrected: offense.corrected?,
correctable: offense.correctable?,
location: hash_for_location(offense)
}
end
# TODO: Consider better solution for Offense#real_column.
# The minimum value of `start_column: real_column` is 1.
# So, the minimum value of `last_column` should be 1.
# And non-zero value of `last_column` should be used as is.
def hash_for_location(offense)
{
start_line: offense.line,
start_column: offense.real_column,
last_line: offense.last_line,
last_column: offense.last_column.zero? ? 1 : offense.last_column,
length: offense.location.length,
# `line` and `column` exist for compatibility.
# Use `start_line` and `start_column` instead.
line: offense.line,
column: offense.real_column
}
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/text_util.rb | lib/rubocop/formatter/text_util.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# Common logic for UI texts.
module TextUtil
module_function
def pluralize(number, thing, options = {})
if number.zero? && options[:no_for_zero]
"no #{thing}s"
elsif number == 1
"1 #{thing}"
else
"#{number} #{thing}s"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/fuubar_style_formatter.rb | lib/rubocop/formatter/fuubar_style_formatter.rb | # frozen_string_literal: true
require 'ruby-progressbar'
module RuboCop
module Formatter
# This formatter displays a progress bar and shows details of offenses as
# soon as they are detected.
# This is inspired by the Fuubar formatter for RSpec by Jeff Kreeftmeijer.
# https://github.com/jeffkreeftmeijer/fuubar
class FuubarStyleFormatter < ClangStyleFormatter
RESET_SEQUENCE = "\e[0m"
def initialize(*output)
@severest_offense = nil
super
end
def started(target_files)
super
@severest_offense = nil
file_phrase = target_files.one? ? 'file' : 'files'
# 185/407 files |====== 45 ======> | ETA: 00:00:04
# %c / %C | %w > %i | %e
bar_format = " %c/%C #{file_phrase} |%w>%i| %e "
@progressbar = ProgressBar.create(
output: output,
total: target_files.count,
format: bar_format,
autostart: false
)
with_color { @progressbar.start }
end
def file_finished(file, offenses)
count_stats(offenses)
unless offenses.empty?
@progressbar.clear
report_file(file, offenses)
end
with_color { @progressbar.increment }
end
def count_stats(offenses)
super
offenses = offenses.reject(&:corrected?)
return if offenses.empty?
offenses << @severest_offense if @severest_offense
@severest_offense = offenses.max_by(&:severity)
end
def with_color
if rainbow.enabled
output.write colorize('', progressbar_color).chomp(RESET_SEQUENCE)
yield
output.write RESET_SEQUENCE
else
yield
end
end
def progressbar_color
if @severest_offense
COLOR_FOR_SEVERITY[@severest_offense.severity.name]
else
:green
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/clang_style_formatter.rb | lib/rubocop/formatter/clang_style_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter formats report data in clang style.
# The precise location of the problem is shown together with the
# relevant source code.
class ClangStyleFormatter < SimpleTextFormatter
ELLIPSES = '...'
def report_file(file, offenses)
offenses.each { |offense| report_offense(file, offense) }
end
private
def report_offense(file, offense)
output.printf(
"%<path>s:%<line>d:%<column>d: %<severity>s: %<message>s\n",
path: cyan(smart_path(file)),
line: offense.line,
column: offense.real_column,
severity: colored_severity_code(offense),
message: message(offense)
)
return unless valid_line?(offense)
report_line(offense.location)
report_highlighted_area(offense.highlighted_area)
end
def valid_line?(offense)
!offense.location.source_line.blank?
end
def report_line(location)
source_line = location.source_line
if location.single_line?
output.puts(source_line)
else
output.puts("#{source_line} #{yellow(ELLIPSES)}")
end
end
def report_highlighted_area(highlighted_area)
space_area = highlighted_area.source_buffer.slice(0...highlighted_area.begin_pos)
source_area = highlighted_area.source
output.puts("#{' ' * Unicode::DisplayWidth.of(space_area)}" \
"#{'^' * Unicode::DisplayWidth.of(source_area)}")
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/formatter_set.rb | lib/rubocop/formatter/formatter_set.rb | # frozen_string_literal: true
require 'fileutils'
module RuboCop
module Formatter
# This is a collection of formatters. A FormatterSet can hold multiple
# formatter instances and provides transparent formatter API methods
# which invoke same method of each formatters.
class FormatterSet < Array
BUILTIN_FORMATTERS_FOR_KEYS = {
'[a]utogenconf' => 'AutoGenConfigFormatter',
'[c]lang' => 'ClangStyleFormatter',
'[e]macs' => 'EmacsStyleFormatter',
'[fi]les' => 'FileListFormatter',
'[fu]ubar' => 'FuubarStyleFormatter',
'[g]ithub' => 'GitHubActionsFormatter',
'[h]tml' => 'HTMLFormatter',
'[j]son' => 'JSONFormatter',
'[ju]nit' => 'JUnitFormatter',
'[m]arkdown' => 'MarkdownFormatter',
'[o]ffenses' => 'OffenseCountFormatter',
'[pa]cman' => 'PacmanFormatter',
'[p]rogress' => 'ProgressFormatter',
'[q]uiet' => 'QuietFormatter',
'[s]imple' => 'SimpleTextFormatter',
'[t]ap' => 'TapFormatter',
'[w]orst' => 'WorstOffendersFormatter'
}.freeze
BUILTIN_FORMATTER_NAMES = BUILTIN_FORMATTERS_FOR_KEYS.keys.map { |key| key.delete('[]') }
FORMATTER_APIS = %i[started finished].freeze
FORMATTER_APIS.each do |method_name|
define_method(method_name) do |*args|
each { |f| f.public_send(method_name, *args) }
end
end
def initialize(options = {})
super()
@options = options # CLI options
end
def file_started(file, options)
@options = options[:cli_options]
@config_store = options[:config_store]
each { |f| f.file_started(file, options) }
end
def file_finished(file, offenses)
each { |f| f.file_finished(file, offenses) }
offenses
end
def add_formatter(formatter_type, output_path = nil)
if output_path
dir_path = File.dirname(output_path)
FileUtils.mkdir_p(dir_path)
output = File.open(output_path, 'w')
else
output = $stdout
end
self << formatter_class(formatter_type).new(output, @options)
end
def close_output_files
each do |formatter|
formatter.output.close if formatter.output.is_a?(File)
end
end
private
def formatter_class(formatter_type)
case formatter_type
when Class
formatter_type
when /\A(::)?[A-Z]/
custom_formatter_class(formatter_type)
else
builtin_formatter_class(formatter_type)
end
end
def builtin_formatter_class(specified_key)
matching_keys = BUILTIN_FORMATTERS_FOR_KEYS.keys.select do |key|
/^\[#{specified_key}\]/.match?(key) || specified_key == key.delete('[]')
end
if matching_keys.empty?
similar_name = NameSimilarity.find_similar_name(specified_key, BUILTIN_FORMATTER_NAMES)
suggestion = %( Did you mean? "#{similar_name}") if similar_name
raise Rainbow(%(Formatter "#{specified_key}" not found.#{suggestion})).red
end
raise %(Cannot determine formatter for "#{specified_key}") if matching_keys.size > 1
formatter_name = BUILTIN_FORMATTERS_FOR_KEYS[matching_keys.first]
RuboCop::Formatter.const_get(formatter_name)
end
def custom_formatter_class(specified_class_name)
constant_names = specified_class_name.split('::')
constant_names.shift if constant_names.first.empty?
constant_names.reduce(Object) do |namespace, constant_name|
namespace.const_get(constant_name, false)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/emacs_style_formatter.rb | lib/rubocop/formatter/emacs_style_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter displays the report data in format that's
# easy to process in the Emacs text editor.
# The output is machine-parsable.
class EmacsStyleFormatter < BaseFormatter
def file_finished(file, offenses)
offenses.each do |o|
output.printf(
"%<path>s:%<line>d:%<column>d: %<severity>s: %<message>s\n",
path: file,
line: o.line,
column: o.real_column,
severity: o.severity.code,
message: message(o)
)
end
end
private
def message(offense)
message =
if offense.corrected_with_todo?
"[Todo] #{offense.message}"
elsif offense.corrected?
"[Corrected] #{offense.message}"
elsif offense.correctable?
"[Correctable] #{offense.message}"
else
offense.message
end
message.tr("\n", ' ')
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/worst_offenders_formatter.rb | lib/rubocop/formatter/worst_offenders_formatter.rb | # frozen_string_literal: true
require 'pathname'
module RuboCop
module Formatter
# This formatter displays the list of offensive files, sorted by number of
# offenses with the worst offenders first.
#
# Here's the format:
#
# 26 this/file/is/really/bad.rb
# 3 just/ok.rb
# --
# 29 Total in 2 files
class WorstOffendersFormatter < BaseFormatter
attr_reader :offense_counts
def started(target_files)
super
@offense_counts = {}
end
def file_finished(file, offenses)
return if offenses.empty?
path = Pathname.new(file).relative_path_from(Pathname.new(Dir.pwd))
@offense_counts[path] = offenses.size
end
def finished(_inspected_files)
report_summary(@offense_counts)
end
# rubocop:disable Metrics/AbcSize
def report_summary(offense_counts)
per_file_counts = ordered_offense_counts(offense_counts)
total_count = total_offense_count(offense_counts)
file_count = per_file_counts.size
output.puts
column_width = total_count.to_s.length + 2
per_file_counts.each do |file_name, count|
output.puts "#{count.to_s.ljust(column_width)}#{file_name}\n"
end
output.puts '--'
output.puts "#{total_count} Total in #{file_count} files"
output.puts
end
# rubocop:enable Metrics/AbcSize
def ordered_offense_counts(offense_counts)
offense_counts.sort_by { |k, v| [-v, k] }.to_h
end
def total_offense_count(offense_counts)
offense_counts.values.sum
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/html_formatter.rb | lib/rubocop/formatter/html_formatter.rb | # frozen_string_literal: true
require 'cgi/escape'
require 'erb'
module RuboCop
module Formatter
# This formatter saves the output as an html file.
class HTMLFormatter < BaseFormatter
ELLIPSES = '<span class="extra-code">...</span>'
TEMPLATE_PATH = File.expand_path('../../../assets/output.html.erb', __dir__)
CSS_PATH = File.expand_path('../../../assets/output.css.erb', __dir__)
Color = Struct.new(:red, :green, :blue, :alpha) do
def to_s
"rgba(#{values.join(', ')})"
end
def fade_out(amount)
dup.tap { |color| color.alpha -= amount }
end
end
Summary = Struct.new(:offense_count, :inspected_files, :target_files, keyword_init: true)
FileOffenses = Struct.new(:path, :offenses, keyword_init: true)
attr_reader :files, :summary
def initialize(output, options = {})
super
@files = []
@summary = Summary.new(offense_count: 0)
end
def started(target_files)
summary.target_files = target_files
end
def file_finished(file, offenses)
files << FileOffenses.new(path: file, offenses: offenses)
summary.offense_count += offenses.count
end
def finished(inspected_files)
summary.inspected_files = inspected_files
render_html
end
def render_html
context = ERBContext.new(files, summary)
template = File.read(TEMPLATE_PATH, encoding: Encoding::UTF_8)
erb = ERB.new(template)
html = erb.result(context.binding).lines.map do |line|
line.match?(/\A\s*\z/) ? "\n" : line
end.join
output.write html
end
# This class provides helper methods used in the ERB template.
class ERBContext
include PathUtil
include TextUtil
LOGO_IMAGE_PATH = File.expand_path('../../../assets/logo.png', __dir__)
attr_reader :files, :summary
def initialize(files, summary)
@files = files.sort_by(&:path)
@summary = summary
end
# Make Kernel#binding public.
# rubocop:disable Lint/UselessMethodDefinition
def binding
super
end
# rubocop:enable Lint/UselessMethodDefinition
def decorated_message(offense)
offense.message.gsub(/`(.+?)`/) { "<code>#{escape(Regexp.last_match(1))}</code>" }
end
def highlighted_source_line(offense)
source_before_highlight(offense) +
highlight_source_tag(offense) +
source_after_highlight(offense) +
possible_ellipses(offense.location)
end
def highlight_source_tag(offense)
"<span class=\"highlight #{offense.severity}\">" \
"#{escape(offense.highlighted_area.source)}" \
'</span>'
end
def source_before_highlight(offense)
source_line = offense.location.source_line
escape(source_line[0...offense.highlighted_area.begin_pos])
end
def source_after_highlight(offense)
source_line = offense.location.source_line
escape(source_line[offense.highlighted_area.end_pos..])
end
def possible_ellipses(location)
location.single_line? ? '' : " #{ELLIPSES}"
end
def escape(string)
CGI.escapeHTML(string)
end
def base64_encoded_logo_image
image = File.read(LOGO_IMAGE_PATH, binmode: true)
# `Base64.encode64` compatible:
# https://github.com/ruby/base64/blob/v0.1.1/lib/base64.rb#L27-L40
[image].pack('m')
end
def render_css
context = CSSContext.new
template = File.read(CSS_PATH, encoding: Encoding::UTF_8)
erb = ERB.new(template, trim_mode: '-')
erb.result(context.binding).lines.map do |line|
line == "\n" ? line : " #{line}"
end.join
end
end
# This class provides helper methods used in the ERB CSS template.
class CSSContext
SEVERITY_COLORS = {
refactor: Color.new(0xED, 0x9C, 0x28, 1.0),
convention: Color.new(0xED, 0x9C, 0x28, 1.0),
warning: Color.new(0x96, 0x28, 0xEF, 1.0),
error: Color.new(0xD2, 0x32, 0x2D, 1.0),
fatal: Color.new(0xD2, 0x32, 0x2D, 1.0)
}.freeze
# Make Kernel#binding public.
# rubocop:disable Lint/UselessMethodDefinition
def binding
super
end
# rubocop:enable Lint/UselessMethodDefinition
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/colorizable.rb | lib/rubocop/formatter/colorizable.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This mix-in module provides string coloring methods for terminals.
# It automatically disables coloring if coloring is disabled in the process
# globally or the formatter's output is not a terminal.
module Colorizable
def rainbow
@rainbow ||= begin
rainbow = Rainbow.new
if options[:color]
rainbow.enabled = true
elsif options[:color] == false || !output.tty?
rainbow.enabled = false
end
rainbow
end
end
def colorize(string, *args)
rainbow.wrap(string).color(*args)
end
%i[
black
red
green
yellow
blue
magenta
cyan
white
].each do |color|
define_method(color) do |string|
colorize(string, color)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/auto_gen_config_formatter.rb | lib/rubocop/formatter/auto_gen_config_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# Does not show individual offenses in the console.
class AutoGenConfigFormatter < ProgressFormatter
def finished(inspected_files)
output.puts
report_summary(inspected_files.size,
@total_offense_count,
@total_correction_count,
@total_correctable_count)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/quiet_formatter.rb | lib/rubocop/formatter/quiet_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# If no offenses are found, no output is displayed.
# Otherwise, SimpleTextFormatter's output is displayed.
class QuietFormatter < SimpleTextFormatter
def report_summary(file_count, offense_count, correction_count, correctable_count)
super unless offense_count.zero?
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/markdown_formatter.rb | lib/rubocop/formatter/markdown_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter displays the report data in markdown
class MarkdownFormatter < BaseFormatter
include TextUtil
include PathUtil
attr_reader :files, :summary
def initialize(output, options = {})
super
@files = []
@summary = Struct.new(:offense_count, :inspected_files, :target_files).new(0)
end
def started(target_files)
summary.target_files = target_files
end
def file_finished(file, offenses)
files << Struct.new(:path, :offenses).new(file, offenses)
summary.offense_count += offenses.count
end
def finished(inspected_files)
summary.inspected_files = inspected_files
render_markdown
end
private
def render_markdown
n_files = pluralize(summary.inspected_files.count, 'file')
n_offenses = pluralize(summary.offense_count, 'offense', no_for_zero: true)
output.write "# RuboCop Inspection Report\n\n"
output.write "#{n_files} inspected, #{n_offenses} detected:\n\n"
write_file_messages
end
def write_file_messages
files.each do |file|
next if file.offenses.empty?
write_heading(file)
file.offenses.each do |offense|
write_context(offense)
write_code(offense)
end
end
end
def write_heading(file)
filename = relative_path(file.path)
n_offenses = pluralize(file.offenses.count, 'offense')
output.write "### #{filename} - (#{n_offenses})\n"
end
def write_context(offense)
output.write(
" * **Line # #{offense.location.line} - #{offense.severity}:** #{offense.message}\n\n"
)
end
def write_code(offense)
code = offense.location.source_line + possible_ellipses(offense.location)
output.write " ```rb\n #{code}\n ```\n\n" unless code.blank?
end
def possible_ellipses(location)
location.single_line? ? '' : ' ...'
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/base_formatter.rb | lib/rubocop/formatter/base_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# Abstract base class for formatter, implements all public API methods.
#
# ## Creating Custom Formatter
#
# You can create a custom formatter by subclassing
# `RuboCop::Formatter::BaseFormatter` and overriding some methods
# or by implementing all the methods by duck typing.
#
# ## Using Custom Formatter in Command Line
#
# You can tell RuboCop to use your custom formatter with a combination of
# `--format` and `--require` option.
# For example, when you have defined `MyCustomFormatter` in
# `./path/to/my_custom_formatter.rb`, you would type this command:
#
# rubocop --require ./path/to/my_custom_formatter --format MyCustomFormatter
#
# Note: The path passed to `--require` is directly passed to
# `Kernel.require`.
# If your custom formatter file is not in `$LOAD_PATH`,
# you need to specify the path as relative path prefixed with `./`
# explicitly or absolute path.
#
# ## Method Invocation Order
#
# For example, when RuboCop inspects 2 files,
# the invocation order should be like this:
#
# * `#initialize`
# * `#started`
# * `#file_started`
# * `#file_finished`
# * `#file_started`
# * `#file_finished`
# * `#finished`
#
class BaseFormatter
# @api public
#
# @!attribute [r] output
#
# @return [IO]
# the IO object passed to `#initialize`
#
# @see #initialize
attr_reader :output
# @api public
#
# @!attribute [r] options
#
# @return [Hash]
attr_reader :options
# @api public
#
# @param output [IO]
# `$stdout` or opened file
def initialize(output, options = {})
@output = output
@options = options
end
# @api public
#
# Invoked once before any files are inspected.
#
# @param target_files [Array(String)]
# all target file paths to be inspected
#
# @return [void]
def started(target_files); end
# @api public
#
# Invoked at the beginning of inspecting each files.
#
# @param file [String]
# the file path
#
# @param options [Hash]
# file specific information, currently this is always empty.
#
# @return [void]
def file_started(file, options); end
# @api public
#
# Invoked at the end of inspecting each files.
#
# @param file [String]
# the file path
#
# @param offenses [Array(RuboCop::Cop::Offense)]
# all detected offenses for the file
#
# @return [void]
#
# @see RuboCop::Cop::Offense
def file_finished(file, offenses); end
# @api public
#
# Invoked after all files are inspected or interrupted by user.
#
# @param inspected_files [Array(String)]
# the inspected file paths.
# This would be same as `target_files` passed to `#started`
# unless RuboCop is interrupted by user.
#
# @return [void]
def finished(inspected_files); end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/github_actions_formatter.rb | lib/rubocop/formatter/github_actions_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter formats report data as GitHub Workflow commands resulting
# in GitHub check annotations when run within GitHub Actions.
class GitHubActionsFormatter < BaseFormatter
ESCAPE_MAP = { '%' => '%25', "\n" => '%0A', "\r" => '%0D' }.freeze
def started(_target_files)
@offenses_for_files = {}
end
def file_finished(file, offenses)
@offenses_for_files[file] = offenses unless offenses.empty?
end
def finished(_inspected_files)
@offenses_for_files.each do |file, offenses|
offenses.each do |offense|
report_offense(file, offense)
end
end
output.puts
end
private
def github_escape(string)
string.gsub(Regexp.union(ESCAPE_MAP.keys), ESCAPE_MAP)
end
def minimum_severity_to_fail
@minimum_severity_to_fail ||= begin
# Unless given explicitly as `fail_level`, `:info` severity offenses do not fail
name = options.fetch(:fail_level, :refactor)
RuboCop::Cop::Severity.new(name)
end
end
def github_severity(offense)
offense.severity < minimum_severity_to_fail ? 'warning' : 'error'
end
def report_offense(file, offense)
output.printf(
"\n::%<severity>s file=%<file>s,line=%<line>d,col=%<column>d::%<message>s",
severity: github_severity(offense),
file: PathUtil.smart_path(file),
line: offense.line,
column: offense.real_column,
message: github_escape(offense.message)
)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/junit_formatter.rb | lib/rubocop/formatter/junit_formatter.rb | # frozen_string_literal: true
#
# This code is based on https://github.com/mikian/rubocop-junit-formatter.
#
# Copyright (c) 2015 Mikko Kokkonen
#
# MIT License
#
# https://github.com/mikian/rubocop-junit-formatter/blob/master/LICENSE.txt
#
module RuboCop
module Formatter
# This formatter formats the report data in JUnit format.
class JUnitFormatter < BaseFormatter
ESCAPE_MAP = {
'"' => '"',
"'" => ''',
'<' => '<',
'>' => '>',
'&' => '&'
}.freeze
def initialize(output, options = {})
super
@test_case_elements = []
reset_count
end
def file_finished(file, offenses)
@inspected_file_count += 1
# TODO: Returns all cops with the same behavior as
# the original rubocop-junit-formatter.
# https://github.com/mikian/rubocop-junit-formatter/blob/v0.1.4/lib/rubocop/formatter/junit_formatter.rb#L9
#
# In the future, it would be preferable to return only enabled cops.
Cop::Registry.all.each do |cop|
target_offenses = offenses_for_cop(offenses, cop)
@offense_count += target_offenses.count
next unless relevant_for_output?(options, target_offenses)
add_testcase_element_to_testsuite_element(file, target_offenses, cop)
end
end
# rubocop:disable Layout/LineLength,Metrics/AbcSize,Metrics/MethodLength
def finished(_inspected_files)
output.puts %(<?xml version='1.0'?>)
output.puts %(<testsuites>)
output.puts %( <testsuite name='rubocop' tests='#{@inspected_file_count}' failures='#{@offense_count}'>)
@test_case_elements.each do |test_case_element|
if test_case_element.failures.empty?
output.puts %( <testcase classname='#{xml_escape test_case_element.classname}' name='#{test_case_element.name}'/>)
else
output.puts %( <testcase classname='#{xml_escape test_case_element.classname}' name='#{test_case_element.name}'>)
test_case_element.failures.each do |failure_element|
output.puts %( <failure type='#{failure_element.type}' message='#{xml_escape failure_element.message}'>)
output.puts %( #{xml_escape failure_element.text})
output.puts %( </failure>)
end
output.puts %( </testcase>)
end
end
output.puts %( </testsuite>)
output.puts %(</testsuites>)
end
# rubocop:enable Layout/LineLength,Metrics/AbcSize,Metrics/MethodLength
private
def relevant_for_output?(options, target_offenses)
!options[:display_only_failed] || target_offenses.any?
end
def offenses_for_cop(all_offenses, cop)
all_offenses.select { |offense| offense.cop_name == cop.cop_name }
end
def add_testcase_element_to_testsuite_element(file, target_offenses, cop)
@test_case_elements << TestCaseElement.new(
classname: classname_attribute_value(file),
name: cop.cop_name
).tap do |test_case_element|
add_failure_to(test_case_element, target_offenses, cop.cop_name)
end
end
def classname_attribute_value(file)
@classname_attribute_value_cache ||= Hash.new do |hash, key|
hash[key] = key.delete_suffix('.rb').gsub("#{Dir.pwd}/", '').tr('/', '.')
end
@classname_attribute_value_cache[file]
end
def reset_count
@inspected_file_count = 0
@offense_count = 0
end
def add_failure_to(testcase, offenses, cop_name)
# One failure per offense. Zero failures is a passing test case,
# for most surefire/nUnit parsers.
offenses.each do |offense|
testcase.failures << FailureElement.new(
type: cop_name,
message: offense.message,
text: offense.location.to_s
)
end
end
def xml_escape(string)
string.gsub(Regexp.union(ESCAPE_MAP.keys), ESCAPE_MAP)
end
class TestCaseElement # :nodoc:
attr_reader :classname, :name, :failures
def initialize(classname:, name:)
@classname = classname
@name = name
@failures = []
end
end
class FailureElement # :nodoc:
attr_reader :type, :message, :text
def initialize(type:, message:, text:)
@type = type
@message = message
@text = text
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/progress_formatter.rb | lib/rubocop/formatter/progress_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter display dots for files with no offenses and
# letters for files with problems in the them. In the end it
# appends the regular report data in the clang style format.
class ProgressFormatter < ClangStyleFormatter
include TextUtil
DOT = '.'
def initialize(output, options = {})
super
@dot = green(DOT)
end
def started(target_files)
super
@offenses_for_files = {}
output.puts "Inspecting #{pluralize(target_files.size, 'file')}"
end
def file_finished(file, offenses)
unless offenses.empty?
count_stats(offenses)
@offenses_for_files[file] = offenses
end
report_file_as_mark(offenses)
end
def finished(inspected_files)
output.puts
unless @offenses_for_files.empty?
output.puts
output.puts 'Offenses:'
output.puts
@offenses_for_files.each { |file, offenses| report_file(file, offenses) }
end
report_summary(inspected_files.size,
@total_offense_count,
@total_correction_count,
@total_correctable_count)
end
def report_file_as_mark(offenses)
mark = if offenses.empty?
@dot
else
highest_offense = offenses.max_by(&:severity)
colored_severity_code(highest_offense)
end
output.write mark
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/pacman_formatter.rb | lib/rubocop/formatter/pacman_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter prints a PACDOT per every file to be analyzed.
# Pacman will "eat" one PACDOT per file when no offense is detected.
# Otherwise it will print a Ghost.
# This is inspired by the Pacman formatter for RSpec by Carlos Rojas.
# https://github.com/go-labs/rspec_pacman_formatter
class PacmanFormatter < ClangStyleFormatter
include TextUtil
attr_accessor :progress_line
FALLBACK_TERMINAL_WIDTH = 80
GHOST = 'ᗣ'
PACMAN = Rainbow('ᗧ').yellow.bright
PACDOT = Rainbow('•').yellow.bright
def initialize(output, options = {})
super
@progress_line = ''
@total_files = 0
@repetitions = 0
end
def started(target_files)
super
@total_files = target_files.size
output.puts "Eating #{pluralize(target_files.size, 'file')}"
update_progress_line
end
def file_started(_file, _options)
step(PACMAN)
end
def file_finished(file, offenses)
count_stats(offenses) unless offenses.empty?
next_step(offenses)
report_file(file, offenses)
end
def next_step(offenses)
return step('.') if offenses.empty?
ghost_color = COLOR_FOR_SEVERITY[offenses.last.severity.name]
step(colorize(GHOST, ghost_color))
end
def cols
@cols ||= begin
_height, width = $stdout.winsize
width.nil? || width.zero? ? FALLBACK_TERMINAL_WIDTH : width
end
end
def update_progress_line
return pacdots(@total_files) unless @total_files > cols
return pacdots(cols) unless (@total_files / cols).eql?(@repetitions)
pacdots(@total_files - (cols * @repetitions))
end
def pacdots(number)
@progress_line = PACDOT * number
end
def step(character)
regex = /#{Regexp.quote(PACMAN)}|#{Regexp.quote(PACDOT)}/
@progress_line = @progress_line.sub(regex, character)
output.printf("%<line>s\r", line: @progress_line)
return unless /ᗣ|\./.match?(@progress_line[-1])
@repetitions += 1
output.puts
update_progress_line
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/offense_count_formatter.rb | lib/rubocop/formatter/offense_count_formatter.rb | # frozen_string_literal: true
require 'ruby-progressbar'
module RuboCop
module Formatter
# This formatter displays the list of offended cops with a count of how
# many offenses of their kind were found. Ordered by desc offense count
#
# Here's the format:
#
# 26 LineLength
# 3 OneLineConditional
# --
# 29 Total in 5 files
class OffenseCountFormatter < BaseFormatter
attr_reader :offense_counts
def started(target_files)
super
@offense_counts = Hash.new(0)
@offending_files_count = 0
@style_guide_links = {}
return unless output.tty?
file_phrase = target_files.one? ? 'file' : 'files'
# 185/407 files |====== 45 ======> | ETA: 00:00:04
# %c / %C | %w > %i | %e
bar_format = " %c/%C #{file_phrase} |%w>%i| %e "
@progressbar = ProgressBar.create(
output: output,
total: target_files.count,
format: bar_format,
autostart: false
)
@progressbar.start
end
def file_finished(_file, offenses)
offenses.each { |o| @offense_counts[o.cop_name] += 1 }
if options[:display_style_guide]
offenses.each { |o| @style_guide_links[o.cop_name] ||= o.message[/ \(http\S+\)\Z/] }
end
@offending_files_count += 1 unless offenses.empty?
@progressbar.increment if instance_variable_defined?(:@progressbar)
end
def finished(_inspected_files)
report_summary(@offense_counts, @offending_files_count)
end
# rubocop:disable Metrics/AbcSize
def report_summary(offense_counts, offending_files_count)
per_cop_counts = ordered_offense_counts(offense_counts)
total_count = total_offense_count(offense_counts)
output.puts
column_width = total_count.to_s.length + 2
per_cop_counts.each do |cop_name, count|
output.puts "#{count.to_s.ljust(column_width)}#{cop_information(cop_name)}"
end
output.puts '--'
output.puts "#{total_count} Total in #{offending_files_count} files"
output.puts
end
# rubocop:enable Metrics/AbcSize
def ordered_offense_counts(offense_counts)
offense_counts.sort_by { |k, v| [-v, k] }.to_h
end
def total_offense_count(offense_counts)
offense_counts.values.sum
end
def cop_information(cop_name)
cop = RuboCop::Cop::Registry.global.find_by_cop_name(cop_name).new
if cop.correctable?
safety = cop.safe_autocorrect? ? 'Safe' : 'Unsafe'
correctable = Rainbow(" [#{safety} Correctable]").yellow
end
"#{cop_name}#{correctable}#{@style_guide_links[cop_name]}"
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/simple_text_formatter.rb | lib/rubocop/formatter/simple_text_formatter.rb | # frozen_string_literal: true
require_relative 'colorizable'
module RuboCop
module Formatter
# A basic formatter that displays only files with offenses.
# Offenses are displayed at compact form - just the
# location of the problem and the associated message.
class SimpleTextFormatter < BaseFormatter
include Colorizable
include PathUtil
COLOR_FOR_SEVERITY = {
info: :gray,
refactor: :yellow,
convention: :yellow,
warning: :magenta,
error: :red,
fatal: :red
}.freeze
def started(_target_files)
@total_offense_count = 0
@total_correction_count = 0
@total_correctable_count = 0
end
def file_finished(file, offenses)
return if offenses.empty?
count_stats(offenses)
report_file(file, offenses)
end
def finished(inspected_files)
report_summary(inspected_files.count,
@total_offense_count,
@total_correction_count,
@total_correctable_count)
end
def report_file(file, offenses)
output.puts yellow("== #{smart_path(file)} ==")
offenses.each do |o|
output.printf(
"%<severity>s:%3<line>d:%3<column>d: %<message>s\n",
severity: colored_severity_code(o),
line: o.line,
column: o.real_column,
message: message(o)
)
end
end
def report_summary(file_count, offense_count, correction_count, correctable_count)
report = Report.new(file_count,
offense_count,
correction_count,
correctable_count,
rainbow,
# :safe_autocorrect is a derived option based on several command-line
# arguments - see RuboCop::Options#add_autocorrection_options
safe_autocorrect: @options[:safe_autocorrect])
output.puts
output.puts report.summary
end
private
def count_stats(offenses)
@total_offense_count += offenses.count
corrected = offenses.count(&:corrected?)
@total_correction_count += corrected
@total_correctable_count += offenses.count(&:correctable?) - corrected
end
def colored_severity_code(offense)
color = COLOR_FOR_SEVERITY.fetch(offense.severity.name)
colorize(offense.severity.code, color)
end
def annotate_message(msg)
msg.gsub(/`(.*?)`/m, yellow('\1'))
end
def message(offense)
message =
if offense.corrected_with_todo?
green('[Todo] ')
elsif offense.corrected?
green('[Corrected] ')
elsif offense.correctable?
yellow('[Correctable] ')
else
''
end
"#{message}#{annotate_message(offense.message)}"
end
# A helper class for building the report summary text.
class Report
include Colorizable
include TextUtil
# rubocop:disable Metrics/ParameterLists
def initialize(
file_count, offense_count, correction_count, correctable_count, rainbow,
safe_autocorrect: false
)
@file_count = file_count
@offense_count = offense_count
@correction_count = correction_count
@correctable_count = correctable_count
@rainbow = rainbow
@safe_autocorrect = safe_autocorrect
end
# rubocop:enable Metrics/ParameterLists
def summary
if @correction_count.positive?
if @correctable_count.positive?
"#{files} inspected, #{offenses} detected, #{corrections} corrected, " \
"#{correctable}"
else
"#{files} inspected, #{offenses} detected, #{corrections} corrected"
end
elsif @correctable_count.positive?
"#{files} inspected, #{offenses} detected, #{correctable}"
else
"#{files} inspected, #{offenses} detected"
end
end
private
attr_reader :rainbow
def files
pluralize(@file_count, 'file')
end
def offenses
text = pluralize(@offense_count, 'offense', no_for_zero: true)
color = @offense_count.zero? ? :green : :red
colorize(text, color)
end
def corrections
text = pluralize(@correction_count, 'offense')
color = @correction_count == @offense_count ? :green : :cyan
colorize(text, color)
end
def correctable
if @safe_autocorrect
text = pluralize(@correctable_count, 'more offense')
"#{colorize(text, :yellow)} can be corrected with `rubocop -A`"
else
text = pluralize(@correctable_count, 'offense')
"#{colorize(text, :yellow)} autocorrectable"
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/tap_formatter.rb | lib/rubocop/formatter/tap_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter formats report data using the Test Anything Protocol.
# TAP allows for to communicate tests results in a language agnostics way.
class TapFormatter < ClangStyleFormatter
def started(target_files)
super
@progress_count = 1
output.puts "1..#{target_files.size}"
end
def file_finished(file, offenses)
if offenses.empty?
output.puts "ok #{@progress_count} - #{smart_path(file)}"
else
output.puts "not ok #{@progress_count} - #{smart_path(file)}"
count_stats(offenses)
report_file(file, offenses)
end
@progress_count += 1
end
private
def report_line(location)
source_line = location.source_line
if location.single_line?
output.puts("# #{source_line}")
else
output.puts("# #{source_line} #{yellow(ELLIPSES)}")
end
end
def report_highlighted_area(highlighted_area)
space_area = highlighted_area.source_buffer.slice(0...highlighted_area.begin_pos)
source_area = highlighted_area.source
output.puts("# #{' ' * Unicode::DisplayWidth.of(space_area)}" \
"#{'^' * Unicode::DisplayWidth.of(source_area)}")
end
def report_offense(file, offense)
output.printf(
"# %<path>s:%<line>d:%<column>d: %<severity>s: %<message>s\n",
path: cyan(smart_path(file)),
line: offense.line,
column: offense.real_column,
severity: colored_severity_code(offense),
message: message(offense)
)
return unless valid_line?(offense)
report_line(offense.location)
report_highlighted_area(offense.highlighted_area)
end
def annotate_message(msg)
msg.gsub(/`(.*?)`/, '\1')
end
def message(offense)
message =
if offense.corrected_with_todo?
'[Todo] '
elsif offense.corrected?
'[Corrected] '
elsif offense.correctable?
'[Correctable] '
else
''
end
"#{message}#{annotate_message(offense.message)}"
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/formatter/disabled_config_formatter.rb | lib/rubocop/formatter/disabled_config_formatter.rb | # frozen_string_literal: true
module RuboCop
module Formatter
# This formatter displays a YAML configuration file where all cops that
# detected any offenses are configured to not detect the offense.
class DisabledConfigFormatter < BaseFormatter # rubocop:disable Metrics/ClassLength
include PathUtil
HEADING = <<~COMMENTS
# This configuration was generated by
# `%<command>s`
# %<timestamp>susing RuboCop version #{Version::STRING}.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
COMMENTS
EXCLUDED_CONFIG_KEYS = %w[
AutoCorrect
Description
Enabled
Exclude
Include
Reference
References
Safe
SafeAutoCorrect
Severity
StyleGuide
VersionAdded
VersionChanged
VersionRemoved
].freeze
@config_to_allow_offenses = {}
@detected_styles = {}
class << self
attr_accessor :config_to_allow_offenses, :detected_styles
end
def initialize(output, options = {})
super
@cops_with_offenses ||= Hash.new(0)
@files_with_offenses ||= {}
end
def file_started(_file, options)
@config_for_pwd = options[:config_store].for_pwd
@exclude_limit_option = @options[:exclude_limit]
@exclude_limit = Integer(@exclude_limit_option ||
RuboCop::Options::DEFAULT_MAXIMUM_EXCLUSION_ITEMS)
end
def file_finished(file, offenses)
offenses.each do |o|
@cops_with_offenses[o.cop_name] += 1
@files_with_offenses[o.cop_name] ||= Set.new
@files_with_offenses[o.cop_name] << file
end
end
def finished(_inspected_files)
output.puts format(HEADING, command: command, timestamp: timestamp)
# Syntax isn't a real cop and it can't be disabled.
@cops_with_offenses.delete('Lint/Syntax')
output_offenses
puts "Created #{output.path}."
end
private
def show_timestamp?
@options.fetch(:auto_gen_timestamp, true)
end
def show_offense_counts?
@options.fetch(:offense_counts, true)
end
def auto_gen_enforced_style?
@options.fetch(:auto_gen_enforced_style, true)
end
def command
command = 'rubocop --auto-gen-config'
command += ' --auto-gen-only-exclude' if @options[:auto_gen_only_exclude]
if no_exclude_limit?
command += ' --no-exclude-limit'
elsif @exclude_limit_option
command += format(' --exclude-limit %<limit>d', limit: Integer(@exclude_limit_option))
end
command += ' --no-offense-counts' unless show_offense_counts?
command += ' --no-auto-gen-timestamp' unless show_timestamp?
command += ' --no-auto-gen-enforced-style' unless auto_gen_enforced_style?
command
end
def timestamp
show_timestamp? ? "on #{Time.now.utc} " : ''
end
def output_offenses
@cops_with_offenses.sort.each do |cop_name, offense_count|
output_cop(cop_name, offense_count)
end
end
def output_cop(cop_name, offense_count)
output.puts
cfg = self.class.config_to_allow_offenses[cop_name] || {}
set_max(cfg, cop_name)
# To avoid malformed YAML when potentially reading the config in
# #excludes, we use an output buffer and append it to the actual output
# only when it results in valid YAML.
output_buffer = StringIO.new
output_cop_comments(output_buffer, cfg, cop_name, offense_count)
output_cop_config(output_buffer, cfg, cop_name)
output.puts(output_buffer.string)
end
def set_max(cfg, cop_name)
return unless cfg[:exclude_limit]
cfg.merge!(cfg[:exclude_limit]) if should_set_max?(cop_name)
# Remove already used exclude_limit.
cfg.reject! { |key| key == :exclude_limit }
end
def should_set_max?(cop_name)
max_set_in_user_config =
@config_for_pwd.for_cop(cop_name)['Max'] != default_config(cop_name)['Max']
max_allowed = !max_set_in_user_config && !no_exclude_limit?
return false unless max_allowed
# In case auto_gen_only_exclude is set, only modify the maximum if the files are not
# excluded one by one.
!@options[:auto_gen_only_exclude] || @files_with_offenses[cop_name].size > @exclude_limit
end
def output_cop_comments(output_buffer, cfg, cop_name, offense_count)
output_buffer.puts "# Offense count: #{offense_count}" if show_offense_counts?
cop_class = Cop::Registry.global.find_by_cop_name(cop_name)
default_cfg = default_config(cop_name)
if supports_safe_autocorrect?(cop_class, default_cfg)
output_buffer.puts '# This cop supports safe autocorrection (--autocorrect).'
elsif supports_unsafe_autocorrect?(cop_class, default_cfg)
output_buffer.puts '# This cop supports unsafe autocorrection (--autocorrect-all).'
end
return unless default_cfg
params = cop_config_params(default_cfg, cfg)
return if params.empty?
output_cop_param_comments(output_buffer, params, default_cfg)
end
def supports_safe_autocorrect?(cop_class, default_cfg)
cop_class&.support_autocorrect? && (default_cfg.nil? || safe_autocorrect?(default_cfg))
end
def supports_unsafe_autocorrect?(cop_class, default_cfg)
cop_class&.support_autocorrect? && !safe_autocorrect?(default_cfg)
end
def cop_config_params(default_cfg, cfg)
default_cfg.keys - EXCLUDED_CONFIG_KEYS - cfg.keys
end
def output_cop_param_comments(output_buffer, params, default_cfg)
config_params = params.reject { |p| p.start_with?('Supported') }
output_buffer.puts("# Configuration parameters: #{config_params.join(', ')}.")
params.each do |param|
value = default_cfg[param]
next unless value.is_a?(Array)
next if value.empty?
value.map! { |v| v.nil? ? '~' : v } # Change nil back to ~ as in the YAML file.
output_buffer.puts "# #{param}: #{value.uniq.join(', ')}"
end
end
def default_config(cop_name)
RuboCop::ConfigLoader.default_configuration[cop_name]
end
def output_cop_config(output_buffer, cfg, cop_name)
filtered_cfg = filtered_config(cfg)
output_buffer.puts "#{cop_name}:"
filtered_cfg.each do |key, value|
value = value[0] if value.is_a?(Array)
output_buffer.puts " #{key}: #{value}"
end
output_offending_files(output_buffer, filtered_cfg, cop_name)
end
def filtered_config(cfg)
# 'Enabled' option will be put into file only if exclude
# limit is exceeded.
rejected_keys = ['Enabled']
rejected_keys << /\AEnforcedStyle\w*/ unless auto_gen_enforced_style?
cfg.reject { |key| include_or_match?(rejected_keys, key) }
end
def output_offending_files(output_buffer, cfg, cop_name)
return unless cfg.empty?
offending_files = @files_with_offenses[cop_name].sort
if !no_exclude_limit? && offending_files.count > @exclude_limit
output_buffer.puts ' Enabled: false'
else
output_exclude_list(output_buffer, offending_files, cop_name)
end
end
def output_exclude_list(output_buffer, offending_files, cop_name)
require 'pathname'
parent = Pathname.new(Dir.pwd)
output_buffer.puts ' Exclude:'
excludes(offending_files, cop_name, parent).each do |exclude_path|
output_exclude_path(output_buffer, exclude_path, parent)
end
end
def excludes(offending_files, cop_name, parent)
# Exclude properties in .rubocop_todo.yml override default ones, as well as any custom
# excludes in .rubocop.yml, so in order to retain those excludes we must copy them.
# There can be multiple .rubocop.yml files in subdirectories, but we just look at the
# current working directory.
config = ConfigStore.new.for(parent)
cfg = config[cop_name] || {}
if merge_mode_for_exclude?(config) || merge_mode_for_exclude?(cfg)
offending_files
else
cop_exclude = cfg['Exclude']
if cop_exclude && cop_exclude != default_config(cop_name)['Exclude']
warn "`#{cop_name}: Exclude` in `#{smart_path(config.loaded_path)}` overrides a " \
'generated `Exclude` in `.rubocop_todo.yml`. Either remove ' \
"`#{cop_name}: Exclude` or add `inherit_mode: merge: - Exclude`."
end
((cop_exclude || []) + offending_files).uniq
end
end
def merge_mode_for_exclude?(cfg)
Array(cfg.to_h.dig('inherit_mode', 'merge')).include?('Exclude')
end
def output_exclude_path(output_buffer, exclude_path, parent)
# exclude_path is either relative path, an absolute path, or a regexp.
file_path = Pathname.new(exclude_path)
relative = file_path.relative_path_from(parent)
output_buffer.puts " - '#{relative}'"
rescue ArgumentError
file = exclude_path
output_buffer.puts " - '#{file}'"
rescue TypeError
regexp = exclude_path
output_buffer.puts " - !ruby/regexp /#{regexp.source}/"
end
def safe_autocorrect?(config)
config.fetch('Safe', true) && config.fetch('SafeAutoCorrect', true)
end
def no_exclude_limit?
@options[:no_exclude_limit] == false
end
# Returns true if the given arr include the given elm or if any of the
# given arr is a regexp that matches the given elm.
def include_or_match?(arr, elm)
arr.include?(elm) || arr.any? { |x| x.is_a?(Regexp) && x.match?(elm) }
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/renamed_cop.rb | lib/rubocop/config_obsoletion/renamed_cop.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Encapsulation of a ConfigObsoletion rule for renaming
# a cop or moving it to a new department.
# @api private
class RenamedCop < CopRule
attr_reader :new_name, :metadata
def initialize(config, old_name, name_or_hash)
super(config, old_name)
if name_or_hash.is_a?(Hash)
@metadata = name_or_hash
@new_name = name_or_hash['new_name']
else
@metadata = {}
@new_name = name_or_hash
end
end
def rule_message
"The `#{old_name}` cop has been #{verb} to `#{new_name}`."
end
def warning?
severity == 'warning'
end
private
def moved?
old_badge = Cop::Badge.parse(old_name)
new_badge = Cop::Badge.parse(new_name)
old_badge.department != new_badge.department && old_badge.cop_name == new_badge.cop_name
end
def verb
moved? ? 'moved' : 'renamed'
end
def severity
metadata['severity']
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/parameter_rule.rb | lib/rubocop/config_obsoletion/parameter_rule.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Base class for ConfigObsoletion rules relating to parameters
# @api private
class ParameterRule < Rule
attr_reader :cop, :parameter, :metadata
def initialize(config, cop, parameter, metadata)
super(config)
@cop = cop
@parameter = parameter
@metadata = metadata
end
def parameter_rule?
true
end
def violated?
applies_to_current_ruby_version? && config[cop]&.key?(parameter)
end
def warning?
severity == 'warning'
end
private
def applies_to_current_ruby_version?
minimum_ruby_version = metadata['minimum_ruby_version']
return true unless minimum_ruby_version
config.target_ruby_version >= minimum_ruby_version
end
def alternative
metadata['alternative']
end
def alternatives
metadata['alternatives']
end
def reason
metadata['reason']
end
def severity
metadata['severity']
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/split_cop.rb | lib/rubocop/config_obsoletion/split_cop.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Encapsulation of a ConfigObsoletion rule for splitting a cop's
# functionality into multiple new cops.
# @api private
class SplitCop < CopRule
attr_reader :metadata
def initialize(config, old_name, metadata)
super(config, old_name)
@metadata = metadata
end
def rule_message
"The `#{old_name}` cop has been split into #{to_sentence(alternatives)}."
end
private
def alternatives
Array(metadata['alternatives']).map { |name| "`#{name}`" }
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/changed_enforced_styles.rb | lib/rubocop/config_obsoletion/changed_enforced_styles.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Encapsulation of a ConfigObsoletion rule for changing a parameter
# @api private
class ChangedEnforcedStyles < ParameterRule
BASE_MESSAGE = 'obsolete `%<parameter>s: %<value>s` (for `%<cop>s`) found in %<path>s'
def violated?
super && config[cop][parameter] == value
end
def message
base = format(BASE_MESSAGE,
parameter: parameter, value: value, cop: cop, path: smart_loaded_path)
if alternative
"#{base}\n`#{parameter}: #{value}` has been renamed to " \
"`#{parameter}: #{alternative.chomp}`."
else
"#{base}\n#{reason.chomp}"
end
end
private
def value
metadata['value']
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/changed_parameter.rb | lib/rubocop/config_obsoletion/changed_parameter.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Encapsulation of a ConfigObsoletion rule for changing a parameter
# @api private
class ChangedParameter < ParameterRule
BASE_MESSAGE = 'obsolete parameter `%<parameter>s` (for `%<cop>s`) found in %<path>s'
def message
base = format(BASE_MESSAGE, parameter: parameter, cop: cop, path: smart_loaded_path)
if alternative
"#{base}\n`#{parameter}` has been renamed to `#{alternative.chomp}`."
elsif alternatives
"#{base}\n`#{parameter}` has been renamed to #{to_sentence(alternatives.map do |item|
"`#{item}`"
end,
connector: 'and/or')}."
else
"#{base}\n#{reason.chomp}"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/rule.rb | lib/rubocop/config_obsoletion/rule.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Abstract base class for ConfigObsoletion rules
# @api private
class Rule
def initialize(config)
@config = config
end
# Does this rule relate to cops?
def cop_rule?
false
end
# Does this rule relate to parameters?
def parameter_rule?
false
end
def violated?
raise NotImplementedError
end
private
attr_reader :config
def to_sentence(collection, connector: 'and')
return collection.first if collection.size == 1
[collection[0..-2].join(', '), collection[-1]].join(" #{connector} ")
end
def smart_loaded_path
PathUtil.smart_path(config.loaded_path)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/extracted_cop.rb | lib/rubocop/config_obsoletion/extracted_cop.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Encapsulation of a ConfigObsoletion rule for splitting a cop's
# functionality into multiple new cops.
# @api private
class ExtractedCop < CopRule
attr_reader :gem, :department
def initialize(config, old_name, gem)
super(config, old_name)
@department, * = old_name.rpartition('/')
@gem = gem
end
def violated?
return false if plugin_loaded?
affected_cops.any?
end
def rule_message
msg = '%<name>s been extracted to the `%<gem>s` gem.'
format(msg,
name: affected_cops.size > 1 ? "`#{department}` cops have" : "`#{old_name}` has",
gem: gem)
end
private
def affected_cops
return old_name unless old_name.end_with?('*')
# Handle whole departments (expressed as `Department/*`)
config.keys.select do |key|
key == department || key.start_with?("#{department}/")
end
end
def plugin_loaded?
# Plugins loaded via `require` are included in `loaded_features`.
config.loaded_plugins.include?(gem) || config.loaded_features.include?(gem)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/cop_rule.rb | lib/rubocop/config_obsoletion/cop_rule.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Base class for ConfigObsoletion rules relating to cops
# @api private
class CopRule < Rule
attr_reader :old_name
def initialize(config, old_name)
super(config)
@old_name = old_name
end
def cop_rule?
true
end
def message
rule_message + "\n(obsolete configuration found in #{smart_loaded_path}, please update it)"
end
# Cop rules currently can only be failures, not warnings
def warning?
false
end
def violated?
config.key?(old_name) || config.key?(Cop::Badge.parse(old_name).cop_name)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/config_obsoletion/removed_cop.rb | lib/rubocop/config_obsoletion/removed_cop.rb | # frozen_string_literal: true
module RuboCop
class ConfigObsoletion
# Encapsulation of a ConfigObsoletion rule for removing
# a previously defined cop.
# @api private
class RemovedCop < CopRule
attr_reader :old_name, :metadata
BASE_MESSAGE = 'The `%<old_name>s` cop has been removed'
def initialize(config, old_name, metadata)
super(config, old_name)
@metadata = metadata.is_a?(Hash) ? metadata : {}
end
def rule_message
base = format(BASE_MESSAGE, old_name: old_name)
if reason
"#{base} since #{reason.chomp}."
elsif alternatives
"#{base}. Please use #{to_sentence(alternatives, connector: 'and/or')} instead."
else
"#{base}."
end
end
private
def reason
metadata['reason']
end
def alternatives
Array(metadata['alternatives']).map { |name| "`#{name}`" }
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/core_ext/string.rb | lib/rubocop/core_ext/string.rb | # frozen_string_literal: true
# Extensions to the core String class
class String
unless method_defined?(:blank?) && ' '.blank?
# Checks whether a string is blank. A string is considered blank if it
# is either empty or contains only whitespace characters.
#
# @return [Boolean] true is the string is blank, false otherwise
#
# @example
# ''.blank? #=> true
# ' '.blank? #=> true
# ' test'.blank? #=> false
def blank?
empty? || lstrip.empty?
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/ext/regexp_node.rb | lib/rubocop/ext/regexp_node.rb | # frozen_string_literal: true
module RuboCop
module Ext
# Extensions to AST::RegexpNode for our cached parsed regexp info
module RegexpNode
ANY = Object.new
def ANY.==(_)
true
end
private_constant :ANY
# @return [Regexp::Expression::Root, nil]
# Note: we extend Regexp nodes to provide `loc` and `expression`
# see `ext/regexp_parser`.
attr_reader :parsed_tree
def assign_properties(*)
super
str = with_interpolations_blanked
@parsed_tree = begin
Regexp::Parser.parse(str, options: options)
rescue StandardError
nil
end
origin = loc.begin.end
@parsed_tree&.each_expression(true) { |e| e.origin = origin }
end
def each_capture(named: ANY)
return enum_for(__method__, named: named) unless block_given?
parsed_tree&.traverse do |event, exp, _index|
yield(exp) if named_capturing?(exp, event, named)
end
self
end
private
def named_capturing?(exp, event, named)
event == :enter &&
named == exp.respond_to?(:name) &&
exp.respond_to?(:capturing?) &&
exp.capturing?
end
def with_interpolations_blanked
# Ignore the trailing regopt node
children[0...-1].map do |child|
source = child.source
# We don't want to consider the contents of interpolations as part of the pattern source,
# but need to preserve their width, to allow offsets to correctly line up with the
# original source: spaces have no effect, and preserve width.
if child.begin_type?
' ' * source.length
else
source
end
end.join
end
AST::RegexpNode.include self
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/ext/range.rb | lib/rubocop/ext/range.rb | # frozen_string_literal: true
module RuboCop
module Ext
# Extensions to Parser::Source::Range
module Range
# Adds `Range#single_line?` to parallel `Node#single_line?`
def single_line?
first_line == last_line
end
end
end
end
Parser::Source::Range.include RuboCop::Ext::Range
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/ext/regexp_parser.rb | lib/rubocop/ext/regexp_parser.rb | # frozen_string_literal: true
module RuboCop
module Ext
# Extensions for `regexp_parser` gem
module RegexpParser
# Source map for RegexpParser nodes
class Map < ::Parser::Source::Map
attr_reader :body, :quantifier, :begin, :end
def initialize(expression, body:, quantifier: nil, begin_l: nil, end_l: nil)
@begin = begin_l
@end = end_l
@body = body
@quantifier = quantifier
super(expression)
end
end
module Expression
# Add `expression` and `loc` to all `regexp_parser` nodes
module Base
attr_accessor :origin
# Shortcut to `loc.expression`
def expression
@expression ||= origin.adjust(begin_pos: ts, end_pos: ts + full_length)
end
# @returns a location map like `parser` does, with:
# - expression: complete expression
# - quantifier: for `+`, `{1,2}`, etc.
# - begin/end: for `[` and `]` (only CharacterSet for now)
#
# E.g.
# [a-z]{2,}
# ^^^^^^^^^ expression
# ^^^^ quantifier
# ^^^^^ body
# ^ begin
# ^ end
#
# Please open issue if you need other locations
def loc
@loc ||= Map.new(expression, **build_location)
end
private
def build_location
return { body: expression } unless (q = quantifier)
body = expression.adjust(end_pos: -q.text.length)
q.origin = origin
q_loc = q.expression
{ body: body, quantifier: q_loc }
end
end
# Provide `CharacterSet` with `begin` and `end` locations.
module CharacterSet
def build_location
h = super
body = h[:body]
h.merge!(
begin_l: body.with(end_pos: body.begin_pos + 1),
end_l: body.with(begin_pos: body.end_pos - 1)
)
end
end
end
::Regexp::Expression::Base.include Expression::Base
::Regexp::Expression::Quantifier.include Expression::Base
::Regexp::Expression::CharacterSet.include Expression::CharacterSet
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/ext/processed_source.rb | lib/rubocop/ext/processed_source.rb | # frozen_string_literal: true
module RuboCop
module Ext
# Extensions to AST::ProcessedSource for our cached comment_config
module ProcessedSource
attr_accessor :registry, :config
def comment_config
@comment_config ||= CommentConfig.new(self)
end
def disabled_line_ranges
comment_config.cop_disabled_line_ranges
end
end
end
end
RuboCop::ProcessedSource.include RuboCop::Ext::ProcessedSource
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/ext/comment.rb | lib/rubocop/ext/comment.rb | # frozen_string_literal: true
module RuboCop
module Ext
# Extensions to `Parser::Source::Comment`.
module Comment
def source
loc.expression.source
end
def source_range
loc.expression
end
end
end
end
Parser::Source::Comment.include RuboCop::Ext::Comment
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/severity.rb | lib/rubocop/cop/severity.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Severity class is simple value object about severity
class Severity
include Comparable
NAMES = %i[info refactor convention warning error fatal].freeze
# @api private
CODE_TABLE = { I: :info, R: :refactor, C: :convention,
W: :warning, E: :error, F: :fatal }.freeze
# @api public
#
# @!attribute [r] name
#
# @return [Symbol]
# severity.
# any of `:info`, `:refactor`, `:convention`, `:warning`, `:error` or `:fatal`.
attr_reader :name
def self.name_from_code(code)
name = code.to_sym
CODE_TABLE[name] || name
end
# @api private
def initialize(name_or_code)
name = Severity.name_from_code(name_or_code)
raise ArgumentError, "Unknown severity: #{name}" unless NAMES.include?(name)
@name = name.freeze
freeze
end
def to_s
@name.to_s
end
def code
@name.to_s[0].upcase
end
def level
NAMES.index(name) + 1
end
def ==(other)
@name == if other.is_a?(Symbol)
other
else
other.name
end
end
def hash
@name.hash
end
def <=>(other)
level <=> other.level
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/cop.rb | lib/rubocop/cop/cop.rb | # frozen_string_literal: true
require 'uri'
require_relative 'legacy/corrections_proxy'
module RuboCop
module Cop
# @deprecated Use Cop::Base instead
# Legacy scaffold for Cops.
# See https://docs.rubocop.org/rubocop/v1_upgrade_notes.html
class Cop < Base
attr_reader :offenses
exclude_from_registry
# @deprecated
Correction = Struct.new(:lambda, :node, :cop) do
def call(corrector)
lambda.call(corrector)
rescue StandardError => e
raise ErrorWithAnalyzedFileLocation.new(cause: e, node: node, cop: cop)
end
end
def self.inherited(_subclass)
super
warn Rainbow(<<~WARNING).yellow, uplevel: 1
Inheriting from `RuboCop::Cop::Cop` is deprecated. Use `RuboCop::Cop::Base` instead.
For more information, see https://docs.rubocop.org/rubocop/v1_upgrade_notes.html.
WARNING
end
def self.support_autocorrect?
method_defined?(:autocorrect)
end
def self.joining_forces
return unless method_defined?(:join_force?)
cop = new
Force.all.select { |force_class| cop.join_force?(force_class) }
end
### Deprecated registry access
# @deprecated Use Registry.global
def self.registry
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`Cop.registry` is deprecated. Use `Registry.global` instead.
WARNING
Registry.global
end
# @deprecated Use Registry.all
def self.all
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`Cop.all` is deprecated. Use `Registry.all` instead.
WARNING
Registry.all
end
# @deprecated Use Registry.qualified_cop_name
def self.qualified_cop_name(name, origin)
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`Cop.qualified_cop_name` is deprecated. Use `Registry.qualified_cop_name` instead.
WARNING
Registry.qualified_cop_name(name, origin)
end
def add_offense(node_or_range, location: :expression, message: nil, severity: nil, &block)
@v0_argument = node_or_range
range = find_location(node_or_range, location)
# Since this range may be generated from Ruby code embedded in some
# template file, we convert it to location info in the original file.
range = range_for_original(range)
if block.nil? && !self.class.support_autocorrect?
super(range, message: message, severity: severity)
else
super(range, message: message, severity: severity) do |corrector|
emulate_v0_callsequence(corrector, &block)
end
end
end
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
# @deprecated Use class method
def support_autocorrect?
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`support_autocorrect?` is deprecated. Use `cop.class.support_autocorrect?`.
WARNING
self.class.support_autocorrect?
end
# @deprecated
def corrections
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`Cop#corrections` is deprecated.
WARNING
return [] unless @last_corrector
Legacy::CorrectionsProxy.new(@last_corrector)
end
# Called before all on_... have been called
def on_new_investigation
investigate(processed_source) if respond_to?(:investigate)
super
end
# Called after all on_... have been called
def on_investigation_end
investigate_post_walk(processed_source) if respond_to?(:investigate_post_walk)
super
end
# Called before any investigation
# @api private
def begin_investigation(processed_source, offset: 0, original: processed_source)
super
@offenses = current_offenses
@last_corrector = @current_corrector
# We need to keep track of the original source and offset,
# because `processed_source` here may be an embedded code in it.
@current_offset = offset
@current_original = original
end
private
# Override Base
def callback_argument(_range)
@v0_argument
end
def apply_correction(corrector)
suppress_clobbering { super }
end
# Just for legacy
def emulate_v0_callsequence(corrector)
lambda = correction_lambda
yield corrector if block_given?
unless corrector.empty?
raise 'Your cop must inherit from Cop::Base and extend AutoCorrector'
end
return unless lambda
suppress_clobbering { lambda.call(corrector) }
end
def correction_lambda
return unless self.class.support_autocorrect?
dedupe_on_node(@v0_argument) { autocorrect(@v0_argument) }
end
def dedupe_on_node(node)
@corrected_nodes ||= {}.compare_by_identity
yield unless @corrected_nodes.key?(node)
ensure
@corrected_nodes[node] = true
end
def suppress_clobbering
yield
rescue ::Parser::ClobberingError
# ignore Clobbering errors
end
def range_for_original(range)
::Parser::Source::Range.new(
@current_original.buffer,
range.begin_pos + @current_offset,
range.end_pos + @current_offset
)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/corrector.rb | lib/rubocop/cop/corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class takes a source buffer and rewrite its source
# based on the different correction rules supplied.
#
# Important!
# The nodes modified by the corrections should be part of the
# AST of the source_buffer.
class Corrector < ::Parser::Source::TreeRewriter
NOOP_CONSUMER = ->(diagnostic) {} # noop
# Duck typing for get to a ::Parser::Source::Buffer
def self.source_buffer(source)
source = source.processed_source if source.respond_to?(:processed_source)
source = source.buffer if source.respond_to?(:buffer)
source = source.source_buffer if source.respond_to?(:source_buffer)
unless source.is_a? ::Parser::Source::Buffer
raise TypeError, 'Expected argument to lead to a Parser::Source::Buffer ' \
"but got #{source.inspect}"
end
source
end
# @param source [Parser::Source::Buffer, or anything
# leading to one via `(processed_source.)buffer`]
#
# corrector = Corrector.new(cop)
def initialize(source)
source = self.class.source_buffer(source)
super(
source,
different_replacements: :raise,
swallowed_insertions: :raise,
crossing_deletions: :accept
)
# Don't print warnings to stderr if corrections conflict with each other
diagnostics.consumer = NOOP_CONSUMER
end
alias rewrite process # Legacy
# Removes `size` characters prior to the source range.
#
# @param [Parser::Source::Range, RuboCop::AST::Node] range or node
# @param [Integer] size
def remove_preceding(node_or_range, size)
range = to_range(node_or_range)
to_remove = range.with(begin_pos: range.begin_pos - size, end_pos: range.begin_pos)
remove(to_remove)
end
# Removes `size` characters from the beginning of the given range.
# If `size` is greater than the size of `range`, the removed region can
# overrun the end of `range`.
#
# @param [Parser::Source::Range, RuboCop::AST::Node] range or node
# @param [Integer] size
def remove_leading(node_or_range, size)
range = to_range(node_or_range)
to_remove = range.with(end_pos: range.begin_pos + size)
remove(to_remove)
end
# Removes `size` characters from the end of the given range.
# If `size` is greater than the size of `range`, the removed region can
# overrun the beginning of `range`.
#
# @param [Parser::Source::Range, RuboCop::AST::Node] range or node
# @param [Integer] size
def remove_trailing(node_or_range, size)
range = to_range(node_or_range)
to_remove = range.with(begin_pos: range.end_pos - size)
remove(to_remove)
end
# Swaps sources at the given ranges.
#
# @param [Parser::Source::Range, RuboCop::AST::Node] node_or_range1
# @param [Parser::Source::Range, RuboCop::AST::Node] node_or_range2
def swap(node_or_range1, node_or_range2)
range1 = to_range(node_or_range1)
range2 = to_range(node_or_range2)
if range1.end_pos == range2.begin_pos
insert_before(range1, range2.source)
remove(range2)
elsif range2.end_pos == range1.begin_pos
insert_before(range2, range1.source)
remove(range1)
else
replace(range1, range2.source)
replace(range2, range1.source)
end
end
private
# :nodoc:
def to_range(node_or_range)
range = case node_or_range
when ::RuboCop::AST::Node, ::Parser::Source::Comment
node_or_range.source_range
when ::Parser::Source::Range
node_or_range
else
raise TypeError,
'Expected a Parser::Source::Range, Comment or ' \
"RuboCop::AST::Node, got #{node_or_range.class}"
end
validate_buffer(range.source_buffer)
range
end
def check_range_validity(node_or_range)
super(to_range(node_or_range))
end
def validate_buffer(buffer)
return if buffer == source_buffer
unless buffer.is_a?(::Parser::Source::Buffer)
# actually this should be enforced by parser gem
raise 'Corrector expected range source buffer to be a ' \
"Parser::Source::Buffer, but got #{buffer.class}"
end
raise "Correction target buffer #{buffer.object_id} " \
"name:#{buffer.name.inspect} " \
"is not current #{@source_buffer.object_id} " \
"name:#{@source_buffer.name.inspect} under investigation"
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/variable_force.rb | lib/rubocop/cop/variable_force.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This force provides a way to track local variables and scopes of Ruby.
# Cops interact with this force need to override some of the hook methods.
#
# def before_entering_scope(scope, variable_table)
# end
#
# def after_entering_scope(scope, variable_table)
# end
#
# def before_leaving_scope(scope, variable_table)
# end
#
# def after_leaving_scope(scope, variable_table)
# end
#
# def before_declaring_variable(variable, variable_table)
# end
#
# def after_declaring_variable(variable, variable_table)
# end
#
# @api private
class VariableForce < Force # rubocop:disable Metrics/ClassLength
VARIABLE_ASSIGNMENT_TYPE = :lvasgn
REGEXP_NAMED_CAPTURE_TYPE = :match_with_lvasgn
PATTERN_MATCH_VARIABLE_TYPE = :match_var
VARIABLE_ASSIGNMENT_TYPES = [
VARIABLE_ASSIGNMENT_TYPE, REGEXP_NAMED_CAPTURE_TYPE, PATTERN_MATCH_VARIABLE_TYPE
].freeze
ARGUMENT_DECLARATION_TYPES = [
:arg, :optarg, :restarg,
:kwarg, :kwoptarg, :kwrestarg,
:blockarg, # This doesn't mean block argument, it's block-pass (&block).
:shadowarg # This means block local variable (obj.each { |arg; this| }).
].freeze
LOGICAL_OPERATOR_ASSIGNMENT_TYPES = %i[or_asgn and_asgn].freeze
OPERATOR_ASSIGNMENT_TYPES = (LOGICAL_OPERATOR_ASSIGNMENT_TYPES + [:op_asgn]).freeze
MULTIPLE_ASSIGNMENT_TYPE = :masgn
REST_ASSIGNMENT_TYPE = :splat
VARIABLE_REFERENCE_TYPE = :lvar
POST_CONDITION_LOOP_TYPES = %i[while_post until_post].freeze
LOOP_TYPES = (POST_CONDITION_LOOP_TYPES + %i[while until for]).freeze
RESCUE_TYPE = :rescue
ZERO_ARITY_SUPER_TYPE = :zsuper
TWISTED_SCOPE_TYPES = %i[block numblock itblock class sclass defs module].freeze
SCOPE_TYPES = (TWISTED_SCOPE_TYPES + [:def]).freeze
SEND_TYPE = :send
VariableReference = Struct.new(:name) do
def assignment?
false
end
end
AssignmentReference = Struct.new(:node) do
def assignment?
true
end
end
BRANCH_NODES = %i[if case case_match rescue].freeze
def variable_table
@variable_table ||= VariableTable.new(self)
end
# Starting point.
def investigate(processed_source)
root_node = processed_source.ast
return unless root_node
variable_table.push_scope(root_node)
process_node(root_node)
variable_table.pop_scope
end
def process_node(node)
method_name = node_handler_method_name(node)
retval = send(method_name, node) if method_name
process_children(node) unless retval == :skip_children
end
private
# This is called for each scope recursively.
def inspect_variables_in_scope(scope_node)
variable_table.push_scope(scope_node)
process_children(scope_node)
variable_table.pop_scope
end
def process_children(origin_node)
origin_node.each_child_node do |child_node|
next if scanned_node?(child_node)
process_node(child_node)
end
end
def skip_children!
:skip_children
end
NODE_HANDLER_METHOD_NAMES = [
[VARIABLE_ASSIGNMENT_TYPE, :process_variable_assignment],
[REGEXP_NAMED_CAPTURE_TYPE, :process_regexp_named_captures],
[PATTERN_MATCH_VARIABLE_TYPE, :process_pattern_match_variable],
[MULTIPLE_ASSIGNMENT_TYPE, :process_variable_multiple_assignment],
[VARIABLE_REFERENCE_TYPE, :process_variable_referencing],
[RESCUE_TYPE, :process_rescue],
[ZERO_ARITY_SUPER_TYPE, :process_zero_arity_super],
[SEND_TYPE, :process_send],
*ARGUMENT_DECLARATION_TYPES.product([:process_variable_declaration]),
*OPERATOR_ASSIGNMENT_TYPES.product([:process_variable_operator_assignment]),
*LOOP_TYPES.product([:process_loop]),
*SCOPE_TYPES.product([:process_scope])
].to_h.freeze
private_constant :NODE_HANDLER_METHOD_NAMES
def node_handler_method_name(node)
NODE_HANDLER_METHOD_NAMES[node.type]
end
def process_variable_declaration(node)
variable_name = node.children.first
# restarg and kwrestarg would have no name:
#
# def initialize(*)
# end
return unless variable_name
variable_table.declare_variable(variable_name, node)
end
def process_variable_assignment(node)
name = node.children.first
variable_table.declare_variable(name, node) unless variable_table.variable_exist?(name)
# Need to scan rhs before assignment so that we can mark previous
# assignments as referenced if rhs has referencing to the variable
# itself like:
#
# foo = 1
# foo = foo + 1
process_children(node)
variable_table.assign_to_variable(name, node)
skip_children!
end
def process_regexp_named_captures(node)
regexp_node, rhs_node = *node
variable_names = regexp_captured_names(regexp_node)
variable_names.each do |name|
next if variable_table.variable_exist?(name)
variable_table.declare_variable(name, node)
end
process_node(rhs_node)
process_node(regexp_node)
variable_names.each { |name| variable_table.assign_to_variable(name, node) }
skip_children!
end
def process_pattern_match_variable(node)
name = node.children.first
variable_table.declare_variable(name, node) unless variable_table.variable_exist?(name)
skip_children!
end
def regexp_captured_names(node)
regexp = node.to_regexp
regexp.named_captures.keys
end
def process_variable_operator_assignment(node)
asgn_node = node.lhs
return unless asgn_node.lvasgn_type?
name = asgn_node.name
variable_table.declare_variable(name, asgn_node) unless variable_table.variable_exist?(name)
# The following statements:
#
# foo = 1
# foo += foo = 2
# # => 3
#
# are equivalent to:
#
# foo = 1
# foo = foo + (foo = 2)
# # => 3
#
# So, at operator assignment node, we need to reference the variable
# before processing rhs nodes.
variable_table.reference_variable(name, node)
process_node(node.rhs)
variable_table.assign_to_variable(name, asgn_node)
skip_children!
end
def process_variable_multiple_assignment(node)
lhs_node, rhs_node = *node
process_node(rhs_node)
process_node(lhs_node)
skip_children!
end
def process_variable_referencing(node)
name = node.children.first
variable_table.reference_variable(name, node)
end
def process_loop(node)
if node.post_condition_loop?
# See the comment at the end of file for this behavior.
condition_node, body_node = *node
process_node(body_node)
process_node(condition_node)
elsif node.for_type?
# In `for item in items` the rightmost expression is evaluated first.
process_node(node.collection)
process_node(node.variable)
process_node(node.body) if node.body
else
process_children(node)
end
mark_assignments_as_referenced_in_loop(node)
skip_children!
end
def process_rescue(node)
resbody_nodes = node.each_child_node(:resbody)
contain_retry = resbody_nodes.any? do |resbody_node|
resbody_node.each_descendant.any?(&:retry_type?)
end
# Treat begin..rescue..end with retry as a loop.
process_loop(node) if contain_retry
end
def process_zero_arity_super(node)
variable_table.accessible_variables.each do |variable|
next unless variable.method_argument?
variable.reference!(node)
end
end
def process_scope(node)
if TWISTED_SCOPE_TYPES.include?(node.type)
# See the comment at the end of file for this behavior.
twisted_nodes(node).each do |twisted_node|
process_node(twisted_node)
scanned_nodes << twisted_node
end
end
inspect_variables_in_scope(node)
skip_children!
end
def twisted_nodes(node)
twisted_nodes = [node.children[0]]
twisted_nodes << node.children[1] if node.class_type?
twisted_nodes.compact
end
def process_send(node)
_receiver, method_name, args = *node
return unless method_name == :binding
return if args && !args.children.empty?
variable_table.accessible_variables.each { |variable| variable.reference!(node) }
end
# Mark last assignments which are referenced in the same loop
# as referenced by ignoring AST order since they would be referenced
# in next iteration.
def mark_assignments_as_referenced_in_loop(node)
referenced_variable_names_in_loop, assignment_nodes_in_loop = find_variables_in_loop(node)
referenced_variable_names_in_loop.each do |name|
variable = variable_table.find_variable(name)
# Non related references which are caught in the above scan
# would be skipped here.
next unless variable
loop_assignments = variable.assignments.select do |assignment|
assignment_nodes_in_loop.include?(assignment.node)
end
next unless loop_assignments.any?
reference_assignments(loop_assignments, node)
end
end
def find_variables_in_loop(loop_node)
referenced_variable_names_in_loop = []
assignment_nodes_in_loop = []
each_descendant_reference(loop_node) do |reference|
if reference.assignment?
assignment_nodes_in_loop << reference.node
else
referenced_variable_names_in_loop << reference.name
end
end
[referenced_variable_names_in_loop, assignment_nodes_in_loop]
end
def each_descendant_reference(loop_node)
# #each_descendant does not consider scope,
# but we don't need to care about it here.
loop_node.each_descendant do |node|
reference = descendant_reference(node)
yield reference if reference
end
end
def descendant_reference(node)
case node.type
when :lvar
VariableReference.new(node.children.first)
when :lvasgn
AssignmentReference.new(node)
when *OPERATOR_ASSIGNMENT_TYPES
VariableReference.new(node.lhs.name) if node.lhs.lvasgn_type?
end
end
def reference_assignments(loop_assignments, loop_node)
# If inside a branching statement, mark all as referenced.
# Otherwise, mark only the last assignment as referenced.
# Note that `rescue` must be considered as branching because of
# the `retry` keyword.
loop_assignments.each do |assignment|
assignment.reference!(loop_node) if assignment.node.each_ancestor(*BRANCH_NODES).any?
end
loop_assignments.last&.reference!(loop_node)
end
def scanned_node?(node)
scanned_nodes.include?(node)
end
def scanned_nodes
@scanned_nodes ||= Set.new.compare_by_identity
end
# Hooks invoked by VariableTable.
%i[
before_entering_scope
after_entering_scope
before_leaving_scope
after_leaving_scope
before_declaring_variable
after_declaring_variable
].each do |hook|
define_method(hook) do |arg|
# Invoke hook in cops.
run_hook(hook, arg, variable_table)
end
end
# Post condition loops
#
# Loop body nodes need to be scanned first.
#
# Ruby:
# begin
# foo = 1
# end while foo > 10
# puts foo
#
# AST:
# (begin
# (while-post
# (send
# (lvar :foo) :>
# (int 10))
# (kwbegin
# (lvasgn :foo
# (int 1))))
# (send nil :puts
# (lvar :foo)))
# Twisted scope types
#
# The variable foo belongs to the top level scope,
# but in AST, it's under the block node.
#
# Ruby:
# some_method(foo = 1) do
# end
# puts foo
#
# AST:
# (begin
# (block
# (send nil :some_method
# (lvasgn :foo
# (int 1)))
# (args) nil)
# (send nil :puts
# (lvar :foo)))
#
# So the method argument nodes need to be processed
# in current scope.
#
# Same thing.
#
# Ruby:
# instance = Object.new
# class << instance
# foo = 1
# end
#
# AST:
# (begin
# (lvasgn :instance
# (send
# (const nil :Object) :new))
# (sclass
# (lvar :instance)
# (begin
# (lvasgn :foo
# (int 1))
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/force.rb | lib/rubocop/cop/force.rb | # frozen_string_literal: true
module RuboCop
module Cop
# A scaffold for concrete forces.
class Force
# @api private
class HookError < StandardError
attr_reader :joining_cop
def initialize(joining_cop)
super
@joining_cop = joining_cop
end
end
attr_reader :cops
def self.all
@all ||= []
end
def self.inherited(subclass)
super
all << subclass
end
def self.force_name
name.split('::').last
end
def initialize(cops)
@cops = cops
end
def name
self.class.force_name
end
def run_hook(method_name, *args)
cops.each do |cop|
next unless cop.respond_to?(method_name)
cop.public_send(method_name, *args)
rescue StandardError
raise HookError, cop
end
end
def investigate(_processed_source)
# Do custom processing and invoke #run_hook at arbitrary timing.
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/autocorrect_logic.rb | lib/rubocop/cop/autocorrect_logic.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This module encapsulates the logic for autocorrect behavior for a cop.
module AutocorrectLogic
def autocorrect?
autocorrect_requested? && correctable? && autocorrect_enabled?
end
def autocorrect_with_disable_uncorrectable?
autocorrect_requested? && disable_uncorrectable? && autocorrect_enabled?
end
def autocorrect_requested?
@options.fetch(:autocorrect, false)
end
def correctable?
self.class.support_autocorrect? || disable_uncorrectable?
end
def disable_uncorrectable?
@options[:disable_uncorrectable] == true
end
def safe_autocorrect?
cop_config.fetch('Safe', true) && cop_config.fetch('SafeAutoCorrect', true)
end
def autocorrect_enabled?
# allow turning off autocorrect on a cop by cop basis
return true unless cop_config
# `false` is the same as `disabled` for backward compatibility.
return false if ['disabled', false].include?(cop_config['AutoCorrect'])
# When LSP is enabled or the `--editor-mode` option is on, it is considered as editing
# source code, and autocorrection with `AutoCorrect: contextual` will not be performed.
return false if contextual_autocorrect? && LSP.enabled?
# :safe_autocorrect is a derived option based on several command-line
# arguments - see RuboCop::Options#add_autocorrection_options
return safe_autocorrect? if @options.fetch(:safe_autocorrect, false)
true
end
private
def disable_offense(offense_range)
unbreakable_range = multiline_ranges(offense_range)&.find do |range|
eol_comment_would_be_inside_literal?(offense_range, range)
end
if unbreakable_range
disable_offense_before_and_after(range_by_lines(unbreakable_range))
else
disable_offense_with_eol_or_surround_comment(offense_range)
end
end
def multiline_ranges(offense_range)
return if offense_range.empty?
processed_source.ast.each_node.filter_map do |node|
if surrounding_heredoc?(node)
heredoc_range(node)
elsif string_continuation?(node)
range_by_lines(node.source_range)
elsif surrounding_percent_array?(node) || multiline_string?(node)
node.source_range
end
end
end
def disable_offense_with_eol_or_surround_comment(range)
if line_with_eol_comment_too_long?(range)
disable_offense_before_and_after(range_by_lines(range))
else
disable_offense_at_end_of_line(range_of_first_line(range))
end
end
def eol_comment_would_be_inside_literal?(offense_range, literal_range)
return true if line_with_eol_comment_too_long?(offense_range)
offense_line = offense_range.line
offense_line >= literal_range.first_line && offense_line < literal_range.last_line
end
def line_with_eol_comment_too_long?(range)
return false unless max_line_length
(range.source_line + eol_comment).length > max_line_length
end
def surrounding_heredoc?(node)
node.any_str_type? && node.heredoc?
end
def heredoc_range(node)
node.source_range.join(node.loc.heredoc_end)
end
def surrounding_percent_array?(node)
node.array_type? && node.percent_literal?
end
def string_continuation?(node)
node.any_str_type? && node.source.match?(/\\\s*$/)
end
def multiline_string?(node)
node.dstr_type? && node.multiline?
end
def range_of_first_line(range)
begin_of_first_line = range.begin_pos - range.column
end_of_first_line = begin_of_first_line + range.source_line.length
Parser::Source::Range.new(range.source_buffer, begin_of_first_line, end_of_first_line)
end
# Expand the given range to include all of any lines it covers. Does not
# include newline at end of the last line.
def range_by_lines(range)
begin_of_first_line = range.begin_pos - range.column
last_line = range.source_buffer.source_line(range.last_line)
last_line_offset = last_line.length - range.last_column
end_of_last_line = range.end_pos + last_line_offset
Parser::Source::Range.new(range.source_buffer, begin_of_first_line, end_of_last_line)
end
def max_line_length
return unless config.cop_enabled?('Layout/LineLength')
config.for_cop('Layout/LineLength')['Max'] || 120
end
def disable_offense_at_end_of_line(range)
Corrector.new(range).insert_after(range, eol_comment)
end
def eol_comment
" # rubocop:todo #{cop_name}"
end
def disable_offense_before_and_after(range_by_lines)
range_with_newline = range_by_lines.resize(range_by_lines.size + 1)
leading_whitespace = range_by_lines.source_line[/^\s*/]
Corrector.new(range_by_lines).wrap(
range_with_newline,
"#{leading_whitespace}# rubocop:todo #{cop_name}\n",
"#{leading_whitespace}# rubocop:enable #{cop_name}\n"
)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/offense.rb | lib/rubocop/cop/offense.rb | # frozen_string_literal: true
module RuboCop
module Cop
# An offense represents a style violation detected by RuboCop.
class Offense
include Comparable
# @api private
COMPARISON_ATTRIBUTES = %i[line column cop_name message severity].freeze
# @api public
#
# @!attribute [r] severity
#
# @return [RuboCop::Cop::Severity]
attr_reader :severity
# @api public
#
# @!attribute [r] location
#
# @return [Parser::Source::Range]
# the location where the violation is detected.
#
# @see https://www.rubydoc.info/gems/parser/Parser/Source/Range
# Parser::Source::Range
attr_reader :location
# @api public
#
# @!attribute [r] message
#
# @return [String]
# human-readable message
#
# @example
# 'Line is too long. [90/80]'
attr_reader :message
# @api public
#
# @!attribute [r] cop_name
#
# @return [String]
# the cop name as a String for which this offense is for.
#
# @example
# 'Layout/LineLength'
attr_reader :cop_name
# @api private
attr_reader :status
# @api public
#
# @!attribute [r] corrector
#
# @return [Corrector | nil]
# the autocorrection for this offense, or `nil` when not available
attr_reader :corrector
PseudoSourceRange = Struct.new(:line, :column, :source_line, :begin_pos,
:end_pos) do
alias_method :first_line, :line
alias_method :last_line, :line
alias_method :last_column, :column
def column_range
column...last_column
end
def size
end_pos - begin_pos
end
alias_method :length, :size
end
private_constant :PseudoSourceRange
NO_LOCATION = PseudoSourceRange.new(1, 0, '', 0, 0).freeze
# @api private
def initialize(severity, location, message, cop_name, # rubocop:disable Metrics/ParameterLists
status = :uncorrected, corrector = nil)
@severity = RuboCop::Cop::Severity.new(severity)
@location = location
@message = message.freeze
@cop_name = cop_name.freeze
@status = status
@corrector = corrector
freeze
end
# @api public
#
# @!attribute [r] correctable?
#
# @return [Boolean]
# whether this offense can be automatically corrected via autocorrect.
# This includes todo comments, for example when requested with `--disable-uncorrectable`.
def correctable?
@status != :unsupported
end
# @api public
#
# @!attribute [r] corrected?
#
# @return [Boolean]
# whether this offense is automatically corrected via
# autocorrect or a todo.
def corrected?
@status == :corrected || @status == :corrected_with_todo
end
# @api public
#
# @!attribute [r] corrected_with_todo?
#
# @return [Boolean]
# whether this offense is automatically disabled via a todo.
def corrected_with_todo?
@status == :corrected_with_todo
end
# @api public
#
# @!attribute [r] disabled?
#
# @return [Boolean]
# whether this offense was locally disabled with a
# disable or todo where it occurred.
def disabled?
@status == :disabled || @status == :todo
end
# @api public
#
# @return [Parser::Source::Range]
# the range of the code that is highlighted
def highlighted_area
Parser::Source::Range.new(source_line, column, column + column_length)
end
# @api private
# This is just for debugging purpose.
def to_s
format('%<severity>s:%3<line>d:%3<column>d: %<message>s',
severity: severity.code, line: line,
column: real_column, message: message)
end
# @api private
def line
location.line
end
# @api private
def column
location.column
end
# @api private
def source_line
location.source_line
end
# @api private
def column_length
if first_line == last_line
column_range.count
else
source_line.length - column
end
end
# @api private
def first_line
location.first_line
end
# @api private
def last_line
location.last_line
end
# @api private
def last_column
location.last_column
end
# @api private
def column_range
location.column_range
end
# @api private
#
# Internally we use column number that start at 0, but when
# outputting column numbers, we want them to start at 1. One
# reason is that editors, such as Emacs, expect this.
def real_column
column + 1
end
# @api public
#
# @return [Boolean]
# returns `true` if two offenses contain same attributes
def ==(other)
COMPARISON_ATTRIBUTES.all? do |attribute|
public_send(attribute) == other.public_send(attribute)
end
end
alias eql? ==
def hash
COMPARISON_ATTRIBUTES.map { |attribute| public_send(attribute) }.hash
end
# @api public
#
# Returns `-1`, `0`, or `+1`
# if this offense is less than, equal to, or greater than `other`.
#
# @return [Integer]
# comparison result
def <=>(other)
COMPARISON_ATTRIBUTES.each do |attribute|
result = public_send(attribute) <=> other.public_send(attribute)
return result unless result.zero?
end
0
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/message_annotator.rb | lib/rubocop/cop/message_annotator.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Message Annotator class annotates a basic offense message
# based on params passed into initializer.
#
# @see #initialize
#
# @example
# RuboCop::Cop::MessageAnnotator.new(
# config, cop_name, cop_config, @options
# ).annotate('message')
# #=> 'Cop/CopName: message (http://example.org/styleguide)'
class MessageAnnotator
attr_reader :options, :config, :cop_name, :cop_config
@style_guide_urls = {}
class << self
attr_reader :style_guide_urls
end
# @param config [RuboCop::Config] Check configs for all cops
# @note Message Annotator specifically checks the
# following config options for_all_cops
# :StyleGuideBaseURL [String] URL for styleguide
# :DisplayStyleGuide [Boolean] Include styleguide and reference URLs
# :ExtraDetails [Boolean] Include cop details
# :DisplayCopNames [Boolean] Include cop name
#
# @param [String] cop_name for specific cop name
# @param [Hash] cop_config configs for specific cop, from config#for_cop
# @option cop_config [String] :StyleGuide Extension of base styleguide URL
# @option cop_config [String] :References Full reference URLs
# @option cop_config [String] :Details
#
# @param [Hash, nil] options optional
# @option options [Boolean] :display_style_guide
# Include style guide and reference URLs
# @option options [Boolean] :extra_details
# Include cop specific details
# @option options [Boolean] :debug
# Include debug output
# @option options [Boolean] :display_cop_names
# Include cop name
def initialize(config, cop_name, cop_config, options)
@config = config
@cop_name = cop_name
@cop_config = cop_config || {}
@options = options
end
# Returns the annotated message,
# based on params passed into initializer
#
# @return [String] annotated message
def annotate(message)
message = "#{cop_name}: #{message}" if display_cop_names?
message += " #{details}" if extra_details? && details
if display_style_guide?
links = urls.join(', ')
message = "#{message} (#{links})"
end
message
end
def urls
[style_guide_url, *reference_urls].compact
end
private
def style_guide_url
url = cop_config['StyleGuide']
return nil if url.nil? || url.empty?
self.class.style_guide_urls[url] ||= begin
base_url = style_guide_base_url
if base_url.nil? || base_url.empty?
url
else
URI.join(base_url, url).to_s
end
end
end
# Returns the base style guide URL from AllCops or the specific department
#
# @return [String] style guide URL
def style_guide_base_url
department_name = cop_name.split('/')[0..-2].join('/')
config.for_department(department_name)['StyleGuideBaseURL'] ||
config.for_all_cops['StyleGuideBaseURL']
end
def display_style_guide?
(options[:display_style_guide] || config.for_all_cops['DisplayStyleGuide']) && !urls.empty?
end
def reference_urls
urls = cop_config
.values_at('References', 'Reference') # Support legacy Reference key
.flat_map { |url| Array(url) }
.reject(&:empty?)
urls unless urls.empty?
end
def extra_details?
options[:extra_details] || config.for_all_cops['ExtraDetails']
end
def debug?
options[:debug]
end
def display_cop_names?
return true if debug?
return false if options[:display_cop_names] == false
return true if options[:display_cop_names]
return false if options[:format] == 'json'
config.for_all_cops['DisplayCopNames']
end
def details
details = cop_config && cop_config['Details']
details.nil? || details.empty? ? nil : details
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/ignored_node.rb | lib/rubocop/cop/ignored_node.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Handles adding and checking ignored nodes.
module IgnoredNode
def ignore_node(node)
ignored_nodes << node
end
def part_of_ignored_node?(node)
ignored_nodes.map(&:loc).any? do |ignored_loc|
next false if ignored_loc.expression.begin_pos > node.source_range.begin_pos
ignored_end_pos = if ignored_loc.respond_to?(:heredoc_body)
ignored_loc.heredoc_end.end_pos
else
ignored_loc.expression.end_pos
end
ignored_end_pos >= node.source_range.end_pos
end
end
def ignored_node?(node)
# Same object found in array?
ignored_nodes.any? { |n| n.equal?(node) }
end
private
def ignored_nodes
@ignored_nodes ||= []
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/documentation.rb | lib/rubocop/cop/documentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Helpers for builtin documentation
module Documentation
module_function
# @api private
def department_to_basename(department)
"cops_#{department.to_s.downcase.tr('/', '_')}"
end
# @api private
def url_for(cop_class, config = nil)
base = department_to_basename(cop_class.department)
fragment = cop_class.cop_name.downcase.gsub(/[^a-z]/, '')
base_url = base_url_for(cop_class, config)
extension = extension_for(cop_class, config)
"#{base_url}/#{base}#{extension}##{fragment}" if base_url
end
# @api private
def base_url_for(cop_class, config)
if config
department_name = cop_class.department.to_s
url = config.for_department(department_name)['DocumentationBaseURL']
return url if url
end
default_base_url if builtin?(cop_class)
end
# @api private
def extension_for(cop_class, config)
if config
department_name = cop_class.department
extension = config.for_department(department_name)['DocumentationExtension']
return extension if extension
end
default_extension
end
# @api private
def default_base_url
'https://docs.rubocop.org/rubocop'
end
# @api private
def default_extension
'.html'
end
# @api private
def builtin?(cop_class)
# any custom method will do
return false unless (m = cop_class.instance_methods(false).first)
path, _line = cop_class.instance_method(m).source_location
path.start_with?(__dir__)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/registry.rb | lib/rubocop/cop/registry.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Error raised when an unqualified cop name is used that could
# refer to two or more cops under different departments
class AmbiguousCopName < RuboCop::Error
MSG = 'Ambiguous cop name `%<name>s` used in %<origin>s needs ' \
'department qualifier. Did you mean %<options>s?'
def initialize(name, origin, badges)
super(
format(MSG, name: name, origin: origin, options: badges.to_a.join(' or '))
)
end
end
# Registry that tracks all cops by their badge and department.
class Registry
include Enumerable
def self.all
global.without_department(:Test).cops
end
def self.qualified_cop_name(name, origin, warn: true)
global.qualified_cop_name(name, origin, warn: warn)
end
# Changes momentarily the global registry
# Intended for testing purposes
def self.with_temporary_global(temp_global = global.dup)
previous = @global
@global = temp_global
yield
ensure
@global = previous
end
def self.reset!
@global = new
end
def self.qualified_cop?(name)
badge = Badge.parse(name)
global.qualify_badge(badge).first == badge
end
attr_reader :options
def initialize(cops = [], options = {})
@registry = {}
@departments = {}
@cops_by_cop_name = Hash.new { |hash, key| hash[key] = [] }
@enrollment_queue = cops
@options = options
@enabled_cache = {}.compare_by_identity
@disabled_cache = {}.compare_by_identity
end
def enlist(cop)
@enrollment_queue << cop
end
def dismiss(cop)
raise "Cop #{cop} could not be dismissed" unless @enrollment_queue.delete(cop)
end
# @return [Array<Symbol>] list of departments for current cops.
def departments
clear_enrollment_queue
@departments.keys
end
# @return [Registry] Cops for that specific department.
def with_department(department)
clear_enrollment_queue
with(@departments.fetch(department, []))
end
# @return [Registry] Cops not for a specific department.
def without_department(department)
clear_enrollment_queue
without_department = @departments.dup
without_department.delete(department)
with(without_department.values.flatten)
end
# @return [Boolean] Checks if given name is department
def department?(name)
departments.include?(name.to_sym)
end
def contains_cop_matching?(names)
cops.any? { |cop| cop.match?(names) }
end
# Convert a user provided cop name into a properly namespaced name
#
# @example gives back a correctly qualified cop name
#
# registry = RuboCop::Cop::Registry
# registry.qualified_cop_name('Layout/EndOfLine', '') # => 'Layout/EndOfLine'
#
# @example fixes incorrect namespaces
#
# registry = RuboCop::Cop::Registry
# registry.qualified_cop_name('Lint/EndOfLine', '') # => 'Layout/EndOfLine'
#
# @example namespaces bare cop identifiers
#
# registry = RuboCop::Cop::Registry
# registry.qualified_cop_name('EndOfLine', '') # => 'Layout/EndOfLine'
#
# @example passes back unrecognized cop names
#
# registry = RuboCop::Cop::Registry
# registry.qualified_cop_name('NotACop', '') # => 'NotACop'
#
# @param name [String] Cop name extracted from config
# @param path [String, nil] Path of file that `name` was extracted from
# @param warn [Boolean] Print a warning if no department given for `name`
#
# @raise [AmbiguousCopName]
# if a bare identifier with two possible namespaces is provided
#
# @note Emits a warning if the provided name has an incorrect namespace
#
# @return [String] Qualified cop name
def qualified_cop_name(name, path, warn: true)
badge = Badge.parse(name)
print_warning(name, path) if warn && department_missing?(badge, name)
return name if registered?(badge)
potential_badges = qualify_badge(badge)
case potential_badges.size
when 0 then name # No namespace found. Deal with it later in caller.
when 1 then resolve_badge(badge, potential_badges.first, path, warn: warn)
else raise AmbiguousCopName.new(badge, path, potential_badges)
end
end
def department_missing?(badge, name)
!badge.qualified? && unqualified_cop_names.include?(name)
end
def print_warning(name, path)
message = "#{path}: Warning: no department given for #{name}."
if path.end_with?('.rb')
message += ' Run `rubocop -a --only Migration/DepartmentName` to fix.'
end
warn message
end
def unqualified_cop_names
clear_enrollment_queue
@unqualified_cop_names ||=
Set.new(@cops_by_cop_name.keys.map { |qn| File.basename(qn) }) <<
'RedundantCopDisableDirective'
end
def qualify_badge(badge)
clear_enrollment_queue
@departments
.map { |department, _| badge.with_department(department) }
.select { |potential_badge| registered?(potential_badge) }
end
# @return [Hash{String => Array<Class>}]
def to_h
clear_enrollment_queue
@cops_by_cop_name
end
def cops
clear_enrollment_queue
@registry.values
end
def length
clear_enrollment_queue
@registry.size
end
def enabled(config)
@enabled_cache[config] ||= select { |cop| enabled?(cop, config) }
end
def disabled(config)
@disabled_cache[config] ||= reject { |cop| enabled?(cop, config) }
end
def enabled?(cop, config)
return true if options[:only]&.include?(cop.cop_name)
# We need to use `cop_name` in this case, because `for_cop` uses caching
# which expects cop names or cop classes as keys.
cfg = config.for_cop(cop.cop_name)
cop_enabled = cfg.fetch('Enabled') == true || enabled_pending_cop?(cfg, config)
if options.fetch(:safe, false)
cop_enabled && cfg.fetch('Safe', true)
else
cop_enabled
end
end
def enabled_pending_cop?(cop_cfg, config)
return false if @options[:disable_pending_cops]
cop_cfg.fetch('Enabled') == 'pending' &&
(@options[:enable_pending_cops] || config.enabled_new_cops?)
end
def names
cops.map(&:cop_name)
end
def cops_for_department(department)
cops.select { |cop| cop.department == department.to_sym }
end
def names_for_department(department)
cops_for_department(department).map(&:cop_name)
end
def ==(other)
cops == other.cops
end
def sort!
clear_enrollment_queue
@registry = @registry.sort_by { |badge, _| badge.cop_name }.to_h
self
end
def select(&block)
cops.select(&block)
end
def each(&block)
cops.each(&block)
end
# @param [String] cop_name
# @return [Class, nil]
def find_by_cop_name(cop_name)
to_h[cop_name].first
end
# When a cop name is given returns a single-element array with the cop class.
# When a department name is given returns an array with all the cop classes
# for that department.
def find_cops_by_directive(directive)
cop = find_by_cop_name(directive)
cop ? [cop] : cops_for_department(directive)
end
def freeze
clear_enrollment_queue
unqualified_cop_names # build cache
super
end
@global = new
class << self
attr_reader :global
end
private
def initialize_copy(reg)
initialize(reg.cops, reg.options)
end
def clear_enrollment_queue
return if @enrollment_queue.empty?
@enrollment_queue.each do |cop|
@registry[cop.badge] = cop
@departments[cop.department] ||= []
@departments[cop.department] << cop
@cops_by_cop_name[cop.cop_name] << cop
end
@enrollment_queue = []
end
def with(cops)
self.class.new(cops)
end
def resolve_badge(given_badge, real_badge, source_path, warn: true)
unless given_badge.match?(real_badge)
path = PathUtil.smart_path(source_path)
if warn
warn("#{path}: #{given_badge} has the wrong namespace - " \
"replace it with #{given_badge.with_department(real_badge.department)}")
end
end
real_badge.to_s
end
def registered?(badge)
clear_enrollment_queue
@registry.key?(badge)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/exclude_limit.rb | lib/rubocop/cop/exclude_limit.rb | # frozen_string_literal: true
module RuboCop
# Allows specified configuration options to have an exclude limit
# ie. a maximum value tracked that it can be used by `--auto-gen-config`.
module ExcludeLimit
# Sets up a configuration option to have an exclude limit tracked.
# The parameter name given is transformed into a method name (eg. `Max`
# becomes `self.max=` and `MinDigits` becomes `self.min_digits=`).
def exclude_limit(parameter_name, method_name: transform(parameter_name))
define_method(:"#{method_name}=") do |value|
cfg = config_to_allow_offenses
cfg[:exclude_limit] ||= {}
current_max = cfg[:exclude_limit][parameter_name]
value = [current_max, value].max if current_max
cfg[:exclude_limit][parameter_name] = value
end
end
private
def transform(parameter_name)
parameter_name.gsub(/(?<!\A)(?=[A-Z])/, '_').downcase
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/badge.rb | lib/rubocop/cop/badge.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Identifier of all cops containing a department and cop name.
#
# All cops are identified by their badge. For example, the badge for
# `RuboCop::Cop::Layout::IndentationStyle` is `Layout/IndentationStyle`.
# Badges can be parsed as either `Department/CopName` or just `CopName` to
# allow for badge references in source files that omit the department for
# RuboCop to infer.
class Badge
attr_reader :department, :department_name, :cop_name
def self.for(class_name)
parts = class_name.split('::')
name_deep_enough = parts.length >= 4
new(name_deep_enough ? parts[2..] : parts.last(2))
end
@parse_cache = {}
def self.parse(identifier)
@parse_cache[identifier] ||= new(identifier.split('/').map! { |i| camel_case(i) })
end
def self.camel_case(name_part)
return 'RSpec' if name_part == 'rspec'
return name_part unless name_part.match?(/^[a-z]|_[a-z]/)
name_part.gsub(/^[a-z]|_[a-z]/) { |match| match[-1, 1].upcase }
end
def initialize(class_name_parts)
department_parts = class_name_parts[0...-1]
@department = (department_parts.join('/').to_sym unless department_parts.empty?)
@department_name = @department&.to_s
@cop_name = class_name_parts.last
end
def ==(other)
hash == other.hash
end
alias eql? ==
def hash
# Do hashing manually to reduce Array allocations.
department.hash ^ cop_name.hash # rubocop:disable Security/CompoundHash
end
def match?(other)
cop_name == other.cop_name && (!qualified? || department == other.department)
end
def to_s
@to_s ||= qualified? ? "#{department}/#{cop_name}" : cop_name
end
def qualified?
!department.nil?
end
def with_department(department)
self.class.new([department.to_s.split('/'), cop_name].flatten)
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/base.rb | lib/rubocop/cop/base.rb | # frozen_string_literal: true
module RuboCop
module Cop
# A scaffold for concrete cops.
#
# The Cop::Base class is meant to be extended.
#
# Cops track offenses and can autocorrect them on the fly.
#
# A commissioner object is responsible for traversing the AST and invoking
# the specific callbacks on each cop.
#
# First the callback `on_new_investigation` is called;
# if a cop needs to do its own processing of the AST or depends on
# something else.
#
# Then callbacks like `on_def`, `on_send` (see AST::Traversal) are called
# with their respective nodes.
#
# Finally the callback `on_investigation_end` is called.
#
# Within these callbacks, cops are meant to call `add_offense` or
# `add_global_offense`. Use the `processed_source` method to
# get the currently processed source being investigated.
#
# In case of invalid syntax / unparsable content,
# the callback `on_other_file` is called instead of all the other
# `on_...` callbacks.
#
# Private methods are not meant for custom cops consumption,
# nor are any instance variables.
#
class Base # rubocop:disable Metrics/ClassLength
extend RuboCop::AST::Sexp
extend NodePattern::Macros
extend ExcludeLimit
include RuboCop::AST::Sexp
include Util
include IgnoredNode
include AutocorrectLogic
attr_reader :config, :processed_source
# Reports of an investigation.
# Immutable
# Consider creation API private
InvestigationReport = Struct.new(:cop, :processed_source, :offenses, :corrector)
# List of methods names to restrict calls for `on_send` / `on_csend`
RESTRICT_ON_SEND = Set[].freeze # rubocop:disable InternalAffairs/UselessRestrictOnSend
# List of cops that should not try to autocorrect at the same
# time as this cop
#
# @return [Array<RuboCop::Cop::Base>]
#
# @api public
def self.autocorrect_incompatible_with
[]
end
# Returns a url to view this cops documentation online.
# Requires 'DocumentationBaseURL' to be set for your department.
# Will follow the convention of RuboCops own documentation structure,
# overwrite this method to accommodate your custom layout.
# @return [String, nil]
#
# @api public
def self.documentation_url(config = nil)
Documentation.url_for(self, config)
end
def self.inherited(subclass)
super
subclass.instance_variable_set(:@gem_requirements, gem_requirements.dup)
Registry.global.enlist(subclass)
end
# Call for abstract Cop classes
def self.exclude_from_registry
Registry.global.dismiss(self)
end
# Returns if class supports autocorrect.
# It is recommended to extend AutoCorrector instead of overriding
def self.support_autocorrect?
false
end
### Naming
def self.badge
@badge ||= Badge.for(name)
end
def self.cop_name
badge.to_s
end
def self.department
badge.department
end
def self.lint?
department == :Lint
end
# Returns true if the cop name or the cop namespace matches any of the
# given names.
def self.match?(given_names)
return false unless given_names
given_names.include?(cop_name) || given_names.include?(badge.department_name)
end
# Override and return the Force class(es) you need to join
def self.joining_forces; end
### Persistence
# Override if your cop should be called repeatedly for multiple investigations
# Between calls to `on_new_investigation` and `on_investigation_end`,
# the result of `processed_source` will remain constant.
# You should invalidate any caches that depend on the current `processed_source`
# in the `on_new_investigation` callback.
# If your cop does autocorrections, be aware that your instance may be called
# multiple times with the same `processed_source.path` but different content.
def self.support_multiple_source?
false
end
## Gem requirements
@gem_requirements = {}
class << self
attr_reader :gem_requirements
# Register a version requirement for the given gem name.
# This cop will be skipped unless the target satisfies *all* requirements.
# @param [String] gem_name
# @param [Array<String>] version_requirements The version requirements,
# using the same syntax as a Gemfile, e.g. ">= 1.2.3"
#
# If omitted, any version of the gem will be accepted.
#
# https://guides.rubygems.org/patterns/#declaring-dependencies
#
# @api public
def requires_gem(gem_name, *version_requirements)
@gem_requirements[gem_name] = Gem::Requirement.new(version_requirements)
end
end
def initialize(config = nil, options = nil)
@config = config || Config.new
@options = options || { debug: false }
reset_investigation
end
# Called before all on_... have been called
# When refining this method, always call `super`
def on_new_investigation
# Typically do nothing here
end
# Called after all on_... have been called
# When refining this method, always call `super`
def on_investigation_end
# Typically do nothing here
end
# Called instead of all on_... callbacks for unrecognized files / syntax errors
# When refining this method, always call `super`
def on_other_file
# Typically do nothing here
end
# Gets called if no message is specified when calling `add_offense` or
# `add_global_offense`
# Cops are discouraged to override this; instead pass your message directly
def message(_range = nil)
self.class::MSG
end
# Adds an offense that has no particular location.
# No correction can be applied to global offenses
def add_global_offense(message = nil, severity: nil)
severity = find_severity(nil, severity)
message = find_message(nil, message)
range = Offense::NO_LOCATION
status = enabled_line?(range.line) ? :unsupported : :disabled
current_offenses << Offense.new(severity, range, message, name, status)
end
# Adds an offense on the specified range (or node with an expression)
# Unless that offense is disabled for this range, a corrector will be yielded
# to provide the cop the opportunity to autocorrect the offense.
# If message is not specified, the method `message` will be called.
def add_offense(node_or_range, message: nil, severity: nil, &block)
range = range_from_node_or_range(node_or_range)
return unless current_offense_locations.add?(range)
range_to_pass = callback_argument(range)
severity = find_severity(range_to_pass, severity)
message = find_message(range_to_pass, message)
status, corrector = enabled_line?(range.line) ? correct(range, &block) : :disabled
# Since this range may be generated from Ruby code embedded in some
# template file, we convert it to location info in the original file.
range = range_for_original(range)
current_offenses << Offense.new(severity, range, message, name, status, corrector)
end
# This method should be overridden when a cop's behavior depends
# on state that lives outside of these locations:
#
# (1) the file under inspection
# (2) the cop's source code
# (3) the config (eg a .rubocop.yml file)
#
# For example, some cops may want to look at other parts of
# the codebase being inspected to find violations. A cop may
# use the presence or absence of file `foo.rb` to determine
# whether a certain violation exists in `bar.rb`.
#
# Overriding this method allows the cop to indicate to RuboCop's
# ResultCache system when those external dependencies change,
# ie when the ResultCache should be invalidated.
def external_dependency_checksum
nil
end
def cop_name
@cop_name ||= self.class.cop_name
end
alias name cop_name
### Configuration Helpers
def cop_config
# Use department configuration as basis, but let individual cop
# configuration override.
@cop_config ||= @config.for_badge(self.class.badge)
end
def config_to_allow_offenses
Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] ||= {}
end
def config_to_allow_offenses=(hash)
Formatter::DisabledConfigFormatter.config_to_allow_offenses[cop_name] = hash
end
def target_ruby_version
@config.target_ruby_version
end
# Returns a gems locked versions (i.e. from Gemfile.lock or gems.locked)
# @returns [Gem::Version | nil] The locked gem version, or nil if the gem is not present.
def target_gem_version(gem_name)
@config.gem_versions_in_target && @config.gem_versions_in_target[gem_name]
end
def parser_engine
@config.parser_engine
end
def target_rails_version
@config.target_rails_version
end
def active_support_extensions_enabled?
@config.active_support_extensions_enabled?
end
def string_literals_frozen_by_default?
@config.string_literals_frozen_by_default?
end
def relevant_file?(file)
return false unless target_satisfies_all_gem_version_requirements?
return true unless @config.clusivity_config_for_badge?(self.class.badge)
file == RuboCop::AST::ProcessedSource::STRING_SOURCE_NAME ||
(file_name_matches_any?(file, 'Include', true) &&
!file_name_matches_any?(file, 'Exclude', false))
end
def excluded_file?(file)
!relevant_file?(file)
end
# There should be very limited reasons for a Cop to do it's own parsing
def parse(source, path = nil)
ProcessedSource.new(source, target_ruby_version, path, parser_engine: parser_engine)
end
# @api private
# Called between investigations
def ready
return self if self.class.support_multiple_source?
self.class.new(@config, @options)
end
### Reserved for Cop::Cop
# @deprecated Make potential errors with previous API more obvious
def offenses
raise 'The offenses are not directly available; ' \
'they are returned as the result of the investigation'
end
### Reserved for Commissioner
# rubocop:disable Layout/ClassStructure
# @api private
def callbacks_needed
self.class.callbacks_needed
end
# @api private
def self.callbacks_needed
@callbacks_needed ||= public_instance_methods.select do |m|
# OPTIMIZE: Check method existence first to make fewer `start_with?` calls.
# At the time of writing this comment, this excludes 98 of ~104 methods.
# `start_with?` with two string arguments instead of a regex is faster
# in this specific case as well.
!Base.method_defined?(m) && # exclude standard "callbacks" like 'on_begin_investigation'
m.start_with?('on_', 'after_')
end
end
# rubocop:enable Layout/ClassStructure
# Called before any investigation
# @api private
def begin_investigation(processed_source, offset: 0, original: processed_source)
@current_offenses = nil
@current_offense_locations = nil
@currently_disabled_lines = nil
@processed_source = processed_source
@current_corrector = nil
# We need to keep track of the original source and offset,
# because `processed_source` here may be an embedded code in it.
@current_offset = offset
@current_original = original
end
# @api private
def always_autocorrect?
# `true` is the same as `'always'` for backward compatibility.
['always', true].include?(cop_config.fetch('AutoCorrect', 'always'))
end
# @api private
def contextual_autocorrect?
cop_config.fetch('AutoCorrect', 'always') == 'contextual'
end
def inspect # :nodoc:
"#<#{self.class.name}:#{object_id} @config=#{@config} @options=#{@options}>"
end
private
### Reserved for Cop::Cop
def callback_argument(range)
range
end
def apply_correction(corrector)
current_corrector&.merge!(corrector) if corrector
end
### Reserved for Commissioner:
def current_offense_locations
@current_offense_locations ||= Set.new
end
def currently_disabled_lines
@currently_disabled_lines ||= Set.new
end
def current_corrector
@current_corrector ||= Corrector.new(@processed_source) if @processed_source.valid_syntax?
end
def current_offenses
@current_offenses ||= []
end
private_class_method def self.restrict_on_send
@restrict_on_send ||= self::RESTRICT_ON_SEND.to_a.freeze
end
EMPTY_OFFENSES = [].freeze
private_constant :EMPTY_OFFENSES
# Called to complete an investigation
def complete_investigation
InvestigationReport.new(
self, processed_source, @current_offenses || EMPTY_OFFENSES, @current_corrector
)
ensure
reset_investigation
end
### Actually private methods
def reset_investigation
@currently_disabled_lines = @current_offenses = @processed_source = @current_corrector = nil
end
# @return [Symbol, Corrector] offense status
def correct(range)
if block_given?
corrector = Corrector.new(self)
yield corrector
if corrector.empty?
corrector = nil
elsif !self.class.support_autocorrect?
raise "The Cop #{name} must `extend AutoCorrector` to be able to autocorrect"
end
end
[use_corrector(range, corrector), corrector]
end
# @return [Symbol] offense status
def use_corrector(range, corrector)
if autocorrect?
attempt_correction(range, corrector)
elsif corrector && (always_autocorrect? || (contextual_autocorrect? && !LSP.enabled?))
:uncorrected
else
:unsupported
end
end
# @return [Symbol] offense status
def attempt_correction(range, corrector)
if corrector
status = :corrected
elsif disable_uncorrectable?
corrector = disable_uncorrectable(range)
status = :corrected_with_todo
else
return :unsupported
end
apply_correction(corrector)
status
end
def disable_uncorrectable(range)
line = range.line
return unless currently_disabled_lines.add?(line)
disable_offense(range)
end
def range_from_node_or_range(node_or_range)
if node_or_range.respond_to?(:loc)
node_or_range.source_range
elsif node_or_range.is_a?(::Parser::Source::Range)
node_or_range
else
extra = ' (call `add_global_offense`)' if node_or_range.nil?
raise "Expected a Source::Range, got #{node_or_range.inspect}#{extra}"
end
end
def find_message(range, message)
annotate(message || message(range))
end
def annotate(message)
RuboCop::Cop::MessageAnnotator.new(
config, cop_name, cop_config, @options
).annotate(message)
end
def file_name_matches_any?(file, parameter, default_result)
patterns = cop_config[parameter]
return default_result unless patterns
patterns = FilePatterns.from(patterns)
patterns.match?(config.path_relative_to_config(file)) || patterns.match?(file)
end
def enabled_line?(line_number)
return true if @options[:ignore_disable_comments] || !@processed_source
@processed_source.comment_config.cop_enabled_at_line?(self, line_number)
end
def find_severity(_range, severity)
custom_severity || severity || default_severity
end
def default_severity
self.class.lint? ? :warning : :convention
end
def custom_severity
severity = cop_config['Severity']
return unless severity
if Severity::NAMES.include?(severity.to_sym)
severity.to_sym
else
message = "Warning: Invalid severity '#{severity}'. " \
"Valid severities are #{Severity::NAMES.join(', ')}."
warn(Rainbow(message).red)
end
end
def range_for_original(range)
::Parser::Source::Range.new(
@current_original.buffer,
range.begin_pos + @current_offset,
range.end_pos + @current_offset
)
end
def target_satisfies_all_gem_version_requirements?
self.class.gem_requirements.all? do |gem_name, version_req|
all_gem_versions_in_target = @config.gem_versions_in_target
next false unless all_gem_versions_in_target
gem_version_in_target = all_gem_versions_in_target[gem_name]
next false unless gem_version_in_target
version_req.satisfied_by?(gem_version_in_target)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs.rb | lib/rubocop/cop/internal_affairs.rb | # frozen_string_literal: true
require_relative 'internal_affairs/cop_description'
require_relative 'internal_affairs/cop_enabled'
require_relative 'internal_affairs/create_empty_file'
require_relative 'internal_affairs/empty_line_between_expect_offense_and_correction'
require_relative 'internal_affairs/example_description'
require_relative 'internal_affairs/example_heredoc_delimiter'
require_relative 'internal_affairs/inherit_deprecated_cop_class'
require_relative 'internal_affairs/lambda_or_proc'
require_relative 'internal_affairs/location_exists'
require_relative 'internal_affairs/location_expression'
require_relative 'internal_affairs/location_line_equality_comparison'
require_relative 'internal_affairs/method_name_end_with'
require_relative 'internal_affairs/method_name_equal'
require_relative 'internal_affairs/node_destructuring'
require_relative 'internal_affairs/node_first_or_last_argument'
require_relative 'internal_affairs/node_matcher_directive'
require_relative 'internal_affairs/node_pattern_groups'
require_relative 'internal_affairs/node_type_group'
require_relative 'internal_affairs/node_type_multiple_predicates'
require_relative 'internal_affairs/node_type_predicate'
require_relative 'internal_affairs/numblock_handler'
require_relative 'internal_affairs/offense_location_keyword'
require_relative 'internal_affairs/on_send_without_on_csend'
require_relative 'internal_affairs/operator_keyword'
require_relative 'internal_affairs/processed_source_buffer_name'
require_relative 'internal_affairs/redundant_context_config_parameter'
require_relative 'internal_affairs/redundant_described_class_as_subject'
require_relative 'internal_affairs/redundant_expect_offense_arguments'
require_relative 'internal_affairs/redundant_let_rubocop_config_new'
require_relative 'internal_affairs/redundant_location_argument'
require_relative 'internal_affairs/redundant_message_argument'
require_relative 'internal_affairs/redundant_method_dispatch_node'
require_relative 'internal_affairs/redundant_source_range'
require_relative 'internal_affairs/single_line_comparison'
require_relative 'internal_affairs/style_detected_api_use'
require_relative 'internal_affairs/undefined_config'
require_relative 'internal_affairs/useless_message_assertion'
require_relative 'internal_affairs/useless_restrict_on_send'
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/generator.rb | lib/rubocop/cop/generator.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Source and spec generator for new cops
#
# This generator will take a cop name and generate a source file
# and spec file when given a valid qualified cop name.
# @api private
class Generator
SOURCE_TEMPLATE = <<~RUBY
# frozen_string_literal: true
module RuboCop
module Cop
module %<department>s
# TODO: Write cop description and example of bad / good code. For every
# `SupportedStyle` and unique configuration, there needs to be examples.
# Examples must have valid Ruby syntax. Do not use upticks.
#
# @safety
# Delete this section if the cop is not unsafe (`Safe: false` or
# `SafeAutoCorrect: false`), or use it to explain how the cop is
# unsafe.
#
# @example EnforcedStyle: bar (default)
# # Description of the `bar` style.
#
# # bad
# bad_bar_method
#
# # bad
# bad_bar_method(args)
#
# # good
# good_bar_method
#
# # good
# good_bar_method(args)
#
# @example EnforcedStyle: foo
# # Description of the `foo` style.
#
# # bad
# bad_foo_method
#
# # bad
# bad_foo_method(args)
#
# # good
# good_foo_method
#
# # good
# good_foo_method(args)
#
class %<cop_name>s < Base
# TODO: Implement the cop in here.
#
# In many cases, you can use a node matcher for matching node pattern.
# See https://github.com/rubocop/rubocop-ast/blob/master/lib/rubocop/ast/node_pattern.rb
#
# For example
MSG = 'Use `#good_method` instead of `#bad_method`.'
# TODO: Don't call `on_send` unless the method name is in this list
# If you don't need `on_send` in the cop you created, remove it.
RESTRICT_ON_SEND = %%i[bad_method].freeze
# @!method bad_method?(node)
def_node_matcher :bad_method?, <<~PATTERN
(send nil? :bad_method ...)
PATTERN
# Called on every `send` node (method call) while walking the AST.
# TODO: remove this method if inspecting `send` nodes is unneeded for your cop.
# By default, this is aliased to `on_csend` as well to handle method calls
# with safe navigation, remove the alias if this is unnecessary.
# If kept, ensure your tests cover safe navigation as well!
def on_send(node)
return unless bad_method?(node)
add_offense(node)
end
alias on_csend on_send
end
end
end
end
RUBY
SPEC_TEMPLATE = <<~SPEC
# frozen_string_literal: true
RSpec.describe RuboCop::Cop::%<department>s::%<cop_name>s, :config do
let(:config) { RuboCop::Config.new }
# TODO: Write test code
#
# For example
it 'registers an offense when using `#bad_method`' do
expect_offense(<<~RUBY)
bad_method
^^^^^^^^^^ Use `#good_method` instead of `#bad_method`.
RUBY
end
it 'does not register an offense when using `#good_method`' do
expect_no_offenses(<<~RUBY)
good_method
RUBY
end
end
SPEC
CONFIGURATION_ADDED_MESSAGE =
'[modify] A configuration for the cop is added into ' \
'%<configuration_file_path>s.'
def initialize(name, output: $stdout)
@badge = Badge.parse(name)
@output = output
return if badge.qualified?
raise ArgumentError, 'Specify a cop name with Department/Name style'
end
def write_source
write_unless_file_exists(source_path, generated_source)
end
def write_spec
write_unless_file_exists(spec_path, generated_spec)
end
def inject_require(root_file_path: 'lib/rubocop.rb')
RequireFileInjector.new(source_path: source_path, root_file_path: root_file_path).inject
end
def inject_config(config_file_path: 'config/default.yml',
version_added: '<<next>>')
injector =
ConfigurationInjector.new(configuration_file_path: config_file_path,
badge: badge,
version_added: version_added)
injector.inject do # rubocop:disable Lint/UnexpectedBlockArity
output.puts(format(CONFIGURATION_ADDED_MESSAGE,
configuration_file_path: config_file_path))
end
end
def todo
<<~TODO
Do 4 steps:
1. Modify the description of #{badge} in config/default.yml
2. Implement your new cop in the generated file!
3. Commit your new cop with a message such as
e.g. "Add new `#{badge}` cop"
4. Run `bundle exec rake changelog:new` to generate a changelog entry
for your new cop.
TODO
end
private
attr_reader :badge, :output
def write_unless_file_exists(path, contents)
if File.exist?(path)
warn "rake new_cop: #{path} already exists!"
exit!
end
dir = File.dirname(path)
FileUtils.mkdir_p(dir)
File.write(path, contents)
output.puts "[create] #{path}"
end
def generated_source
generate(SOURCE_TEMPLATE)
end
def generated_spec
generate(SPEC_TEMPLATE)
end
def generate(template)
format(template, department: badge.department.to_s.gsub('/', '::'),
cop_name: badge.cop_name)
end
def spec_path
File.join(
'spec',
'rubocop',
'cop',
snake_case(badge.department.to_s),
"#{snake_case(badge.cop_name.to_s)}_spec.rb"
)
end
def source_path
File.join(
'lib',
'rubocop',
'cop',
snake_case(badge.department.to_s),
"#{snake_case(badge.cop_name.to_s)}.rb"
)
end
def snake_case(camel_case_string)
camel_case_string
.gsub('RSpec', 'Rspec')
.gsub(%r{([^A-Z/])([A-Z]+)}, '\1_\2')
.gsub(%r{([A-Z])([A-Z][^A-Z\d/]+)}, '\1_\2')
.downcase
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/commissioner.rb | lib/rubocop/cop/commissioner.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Commissioner class is responsible for processing the AST and delegating
# work to the specified cops.
class Commissioner
include RuboCop::AST::Traversal
RESTRICTED_CALLBACKS = %i[on_send on_csend after_send after_csend].freeze
private_constant :RESTRICTED_CALLBACKS
# How a Commissioner returns the results of the investigation
# as a list of Cop::InvestigationReport and any errors caught
# during the investigation.
# Immutable
# Consider creation API private
InvestigationReport = Struct.new(:processed_source, :cop_reports, :errors) do
def cops
@cops ||= cop_reports.map(&:cop)
end
def offenses_per_cop
@offenses_per_cop ||= cop_reports.map(&:offenses)
end
def correctors
@correctors ||= cop_reports.map(&:corrector)
end
def offenses
@offenses ||= offenses_per_cop.flatten(1)
end
def merge(investigation)
InvestigationReport.new(processed_source,
cop_reports + investigation.cop_reports,
errors + investigation.errors)
end
end
attr_reader :errors
def initialize(cops, forces = [], options = {})
@cops = cops
@forces = forces
@options = options
initialize_callbacks
reset
end
# Create methods like :on_send, :on_super, etc. They will be called
# during AST traversal and try to call corresponding methods on cops.
# A call to `super` is used
# to continue iterating over the children of a node.
# However, if we know that a certain node type (like `int`) never has
# child nodes, there is no reason to pay the cost of calling `super`.
Parser::Meta::NODE_TYPES.each do |node_type|
method_name = :"on_#{node_type}"
next unless method_defined?(method_name)
# Hacky: Comment-out code as needed
r = '#' unless RESTRICTED_CALLBACKS.include?(method_name) # has Restricted?
c = '#' if NO_CHILD_NODES.include?(node_type) # has Children?
class_eval(<<~RUBY, __FILE__, __LINE__ + 1)
def on_#{node_type}(node) # def on_send(node)
trigger_responding_cops(:on_#{node_type}, node) # trigger_responding_cops(:on_send, node)
#{r} trigger_restricted_cops(:on_#{node_type}, node) # trigger_restricted_cops(:on_send, node)
#{c} super(node) # super(node)
#{c} trigger_responding_cops(:after_#{node_type}, node) # trigger_responding_cops(:after_send, node)
#{c}#{r} trigger_restricted_cops(:after_#{node_type}, node) # trigger_restricted_cops(:after_send, node)
end # end
RUBY
end
# @return [InvestigationReport]
def investigate(processed_source, offset: 0, original: processed_source)
reset
begin_investigation(processed_source, offset: offset, original: original)
if processed_source.valid_syntax?
invoke(:on_new_investigation, @cops)
invoke_with_argument(:investigate, @forces, processed_source)
walk(processed_source.ast) unless @cops.empty?
invoke(:on_investigation_end, @cops)
else
invoke(:on_other_file, @cops)
end
reports = @cops.map { |cop| cop.send(:complete_investigation) }
InvestigationReport.new(processed_source, reports, @errors)
end
private
def begin_investigation(processed_source, offset:, original:)
@cops.each do |cop|
cop.begin_investigation(processed_source, offset: offset, original: original)
end
end
def trigger_responding_cops(callback, node)
@callbacks[callback]&.each do |cop|
with_cop_error_handling(cop, node) do
cop.public_send(callback, node)
end
end
end
def reset
@errors = []
end
def initialize_callbacks
@callbacks = build_callbacks(@cops)
@restricted_map = restrict_callbacks(@callbacks)
end
def build_callbacks(cops)
callbacks = {}
cops.each do |cop|
cop.callbacks_needed.each do |callback|
(callbacks[callback] ||= []) << cop
end
end
callbacks
end
def restrict_callbacks(callbacks)
restricted = {}
RESTRICTED_CALLBACKS.each do |callback|
restricted[callback] = restricted_map(callbacks[callback])
end
restricted
end
def trigger_restricted_cops(event, node)
name = node.method_name
@restricted_map[event][name]&.each do |cop|
with_cop_error_handling(cop, node) do
cop.public_send(event, node)
end
end
end
# NOTE: mutates `callbacks` in place
def restricted_map(callbacks)
map = {}
callbacks&.select! do |cop|
restrictions = cop.class.send :restrict_on_send
restrictions.each { |name| (map[name] ||= []) << cop }
restrictions.empty?
end
map
end
def invoke(callback, cops)
cops.each { |cop| with_cop_error_handling(cop) { cop.send(callback) } }
end
def invoke_with_argument(callback, cops, arg)
cops.each { |cop| with_cop_error_handling(cop) { cop.send(callback, arg) } }
end
# Allow blind rescues here, since we're absorbing and packaging or
# re-raising exceptions that can be raised from within the individual
# cops' `#investigate` methods.
def with_cop_error_handling(cop, node = nil)
yield
rescue StandardError => e
raise e if @options[:raise_error] # For internal testing
err = ErrorWithAnalyzedFileLocation.new(cause: e, node: node, cop: cop)
raise err if @options[:raise_cop_error] # From user-input option
@errors << err
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/team.rb | lib/rubocop/cop/team.rb | # frozen_string_literal: true
module RuboCop
module Cop
# A group of cops, ready to be called on duty to inspect files.
# Team is responsible for selecting only relevant cops to be sent on duty,
# as well as insuring that the needed forces are sent along with them.
#
# For performance reasons, Team will first dispatch cops & forces in two groups,
# first the ones needed for autocorrection (if any), then the rest
# (unless autocorrections happened).
# rubocop:disable Metrics/ClassLength
class Team
# @return [Team]
def self.new(cop_or_classes, config, options = {})
# Support v0 api:
if cop_or_classes.first.is_a?(Class)
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`Team.new` with cop classes is deprecated. Use `Team.mobilize` instead.
WARNING
return mobilize(cop_or_classes, config, options)
end
super
end
# @return [Team] with cops assembled from the given `cop_classes`
def self.mobilize(cop_classes, config, options = {})
cops = mobilize_cops(cop_classes, config, options)
new(cops, config, options)
end
# @return [Array<Cop::Base>]
def self.mobilize_cops(cop_classes, config, options = {})
cop_classes = Registry.new(cop_classes.to_a, options) unless cop_classes.is_a?(Registry)
cop_classes.map do |cop_class|
cop_class.new(config, options)
end
end
# @return [Array<Force>] needed for the given cops
def self.forces_for(cops)
needed = Hash.new { |h, k| h[k] = [] }
cops.each do |cop|
forces = cop.class.joining_forces
if forces.is_a?(Array)
forces.each { |force| needed[force] << cop }
elsif forces
needed[forces] << cop
end
end
needed.map { |force_class, joining_cops| force_class.new(joining_cops) }
end
attr_reader :errors, :warnings, :updated_source_file, :cops
alias updated_source_file? updated_source_file
def initialize(cops, config = nil, options = {})
@cops = cops
@config = config
@options = options
reset
@ready = true
@registry = Registry.new(cops, options.dup)
validate_config
end
def autocorrect?
@options[:autocorrect]
end
def debug?
@options[:debug]
end
# @deprecated. Use investigate
# @return Array<offenses>
def inspect_file(processed_source)
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`inspect_file` is deprecated. Use `investigate` instead.
WARNING
investigate(processed_source).offenses
end
# @return [Commissioner::InvestigationReport]
def investigate(processed_source, offset: 0, original: processed_source)
be_ready
# The autocorrection process may have to be repeated multiple times
# until there are no corrections left to perform
# To speed things up, run autocorrecting cops by themselves, and only
# run the other cops when no corrections are left
on_duty = roundup_relevant_cops(processed_source)
autocorrect_cops, other_cops = on_duty.partition(&:autocorrect?)
report = investigate_partial(autocorrect_cops, processed_source,
offset: offset, original: original)
unless autocorrect(processed_source, report, offset: offset, original: original)
# If we corrected some errors, another round of inspection will be
# done, and any other offenses will be caught then, so only need
# to check other_cops if no correction was done
report = report.merge(investigate_partial(other_cops, processed_source,
offset: offset, original: original))
end
process_errors(processed_source.path, report.errors)
report
ensure
@ready = false
end
# @deprecated
def forces
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`forces` is deprecated.
WARNING
@forces ||= self.class.forces_for(cops)
end
def external_dependency_checksum
# The external dependency checksums are cached per RuboCop team so that
# the checksums don't need to be recomputed for each file.
@external_dependency_checksum ||= begin
keys = cops.filter_map(&:external_dependency_checksum)
Digest::SHA1.hexdigest(keys.join)
end
end
private
def autocorrect(processed_source, report, original:, offset:)
@updated_source_file = false
return unless autocorrect?
return if report.processed_source.parser_error
new_source = autocorrect_report(report, original: original, offset: offset)
return unless new_source
if @options[:stdin]
# holds source read in from stdin, when --stdin option is used
@options[:stdin] = new_source
else
filename = processed_source.file_path
File.write(filename, new_source)
end
@updated_source_file = true
end
def be_ready
return if @ready
reset
@cops.map!(&:ready)
@ready = true
end
def reset
@errors = []
@warnings = []
end
# @return [Commissioner::InvestigationReport]
def investigate_partial(cops, processed_source, offset:, original:)
commissioner = Commissioner.new(cops, self.class.forces_for(cops), @options)
commissioner.investigate(processed_source, offset: offset, original: original)
end
# @return [Array<cop>]
def roundup_relevant_cops(processed_source)
cops.select do |cop|
next true if processed_source.comment_config.cop_opted_in?(cop)
next false if cop.excluded_file?(processed_source.file_path)
next false unless @registry.enabled?(cop, @config)
support_target_ruby_version?(cop) && support_target_rails_version?(cop)
end
end
def support_target_ruby_version?(cop)
return true unless cop.class.respond_to?(:support_target_ruby_version?)
cop.class.support_target_ruby_version?(cop.target_ruby_version)
end
def support_target_rails_version?(cop)
# In this case, the rails version was already checked by `#excluded_file?`
return true if defined?(RuboCop::Rails::TargetRailsVersion::USES_REQUIRES_GEM_API)
return true unless cop.class.respond_to?(:support_target_rails_version?)
cop.class.support_target_rails_version?(cop.target_rails_version)
end
def autocorrect_report(report, offset:, original:)
corrector = collate_corrections(report, offset: offset, original: original)
corrector.rewrite unless corrector.empty?
end
def collate_corrections(report, offset:, original:)
corrector = Corrector.new(original)
each_corrector(report) do |to_merge|
suppress_clobbering do
if offset.positive?
corrector.import!(to_merge, offset: offset)
else
corrector.merge!(to_merge)
end
end
end
corrector
end
def each_corrector(report)
skips = Set.new
report.cop_reports.each do |cop_report|
cop = cop_report.cop
corrector = cop_report.corrector
next if corrector.nil? || corrector.empty?
next if skips.include?(cop.class)
yield corrector
skips.merge(cop.class.autocorrect_incompatible_with)
end
end
def suppress_clobbering
yield
rescue ::Parser::ClobberingError
# ignore Clobbering errors
end
def validate_config
cops.each do |cop|
cop.validate_config if cop.respond_to?(:validate_config)
end
end
def process_errors(file, errors)
errors.each do |error|
line = ":#{error.line}" if error.line
column = ":#{error.column}" if error.column
location = "#{file}#{line}#{column}"
cause = error.cause
if cause.is_a?(Warning)
handle_warning(cause, location)
elsif cause.is_a?(Force::HookError)
handle_error(cause.cause, location, cause.joining_cop)
else
handle_error(cause, location, error.cop)
end
end
end
def handle_warning(error, location)
message = Rainbow("#{error.message} (from file: #{location})").yellow
@warnings << message
warn message
puts error.backtrace if debug?
end
def handle_error(error, location, cop)
message = Rainbow("An error occurred while #{cop.name} cop was inspecting #{location}.").red
@errors << message
warn message
if debug?
puts error.full_message
else
warn 'To see the complete backtrace run rubocop -d.'
end
end
end
# rubocop:enable Metrics/ClassLength
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/util.rb | lib/rubocop/cop/util.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This module contains a collection of useful utility methods.
# rubocop:disable Metrics/ModuleLength
module Util
include PathUtil
# Match literal regex characters, not including anchors, character
# classes, alternatives, groups, repetitions, references, etc
LITERAL_REGEX = %r{[\w\s\-,"'!#%&<>=;:`~/]|\\[^AbBdDgGhHkpPRwWXsSzZ0-9]}.freeze
module_function
# This is a bad API
def comment_line?(line_source)
/^\s*#/.match?(line_source)
end
# @deprecated Use `ProcessedSource#line_with_comment?`, `contains_comment?` or similar
def comment_lines?(node)
warn Rainbow(<<~WARNING).yellow, uplevel: 1
`comment_lines?` is deprecated. Use `ProcessedSource#line_with_comment?`, `contains_comment?` or similar instead.
WARNING
processed_source[line_range(node)].any? { |line| comment_line?(line) }
end
def line_range(node)
node.first_line..node.last_line
end
def parentheses?(node)
node.loc_is?(:end, ')')
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def add_parentheses(node, corrector)
if node.args_type?
arguments_range = node.source_range
args_with_space = range_with_surrounding_space(arguments_range, side: :left)
leading_space = range_between(args_with_space.begin_pos, arguments_range.begin_pos)
corrector.replace(leading_space, '(')
corrector.insert_after(arguments_range, ')')
elsif !node.respond_to?(:arguments)
corrector.wrap(node, '(', ')')
elsif node.arguments.empty?
corrector.insert_after(node, '()')
else
args_begin = args_begin(node)
corrector.remove(args_begin)
corrector.insert_before(args_begin, '(')
corrector.insert_after(args_end(node), ')')
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
def any_descendant?(node, *types)
if block_given?
node.each_descendant(*types) do |descendant|
return true if yield(descendant)
end
else
# Use a block version to avoid allocating enumerators.
node.each_descendant do # rubocop:disable Lint/UnreachableLoop
return true
end
end
false
end
def args_begin(node)
loc = node.loc
selector = if node.type?(:super, :yield)
loc.keyword
elsif node.any_def_type?
loc.name
else
loc.selector
end
selector.end.resize(1)
end
def args_end(node)
node.source_range.end
end
def on_node(syms, sexp, excludes = [], &block)
return to_enum(:on_node, syms, sexp, excludes) unless block
yield sexp if include_or_equal?(syms, sexp.type)
return if include_or_equal?(excludes, sexp.type)
sexp.each_child_node { |elem| on_node(syms, elem, excludes, &block) }
end
# Arbitrarily chosen value, should be enough to cover
# the most nested source code in real world projects.
MAX_LINE_BEGINS_REGEX_INDEX = 50
LINE_BEGINS_REGEX_CACHE = Hash.new do |hash, index|
hash[index] = /^\s{#{index}}\S/ if index <= MAX_LINE_BEGINS_REGEX_INDEX
end
private_constant :MAX_LINE_BEGINS_REGEX_INDEX, :LINE_BEGINS_REGEX_CACHE
def begins_its_line?(range)
if (regex = LINE_BEGINS_REGEX_CACHE[range.column])
range.source_line.match?(regex)
else
range.source_line.index(/\S/) == range.column
end
end
# Returns, for example, a bare `if` node if the given node is an `if`
# with calls chained to the end of it.
def first_part_of_call_chain(node)
while node
if node.call_type?
node = node.receiver
elsif node.any_block_type?
node = node.send_node
else
break
end
end
node
end
# If converting a string to Ruby string literal source code, must
# double quotes be used?
def double_quotes_required?(string)
# Double quotes are required for strings which either:
# - Contain single quotes
# - Contain non-printable characters, which must use an escape
# Regex matches IF there is a ' or there is a \\ in the string that is
# not preceded/followed by another \\ (e.g. "\\x34") but not "\\\\".
/'|(?<! \\) \\{2}* \\ (?![\\"])/x.match?(string)
end
def needs_escaping?(string)
double_quotes_required?(escape_string(string))
end
def escape_string(string)
string.inspect[1..-2].tap { |s| s.gsub!('\\"', '"') }
end
def to_string_literal(string)
if needs_escaping?(string) && compatible_external_encoding_for?(string)
string.inspect
else
# In a single-quoted strings, double quotes don't need to be escaped
"'#{string.gsub('\\') { '\\\\' }.gsub('\"', '"')}'"
end
end
def trim_string_interpolation_escape_character(str)
str.gsub(/\\\#\{(.*?)\}/) { "\#{#{Regexp.last_match(1)}}" }
end
def interpret_string_escapes(string)
StringInterpreter.interpret(string)
end
def line(node_or_range)
if node_or_range.respond_to?(:line)
node_or_range.line
elsif node_or_range.respond_to?(:loc)
node_or_range.loc.line
end
end
def same_line?(node1, node2)
line1 = line(node1)
line2 = line(node2)
return false unless line1 && line2
line1 == line2
end
def indent(node, offset: 0)
' ' * (node.loc.column + offset)
end
@to_supported_styles_cache = {}
def to_supported_styles(enforced_style)
@to_supported_styles_cache[enforced_style] ||=
enforced_style.sub(/^Enforced/, 'Supported').sub('Style', 'Styles')
end
def parse_regexp(text)
Regexp::Parser.parse(text)
rescue Regexp::Parser::Error
# Upon encountering an invalid regular expression,
# we aim to proceed and identify any remaining potential offenses.
nil
end
private
def compatible_external_encoding_for?(src)
src.dup.force_encoding(Encoding.default_external).valid_encoding?
end
def include_or_equal?(source, target)
source == target || (source.is_a?(Array) && source.include?(target))
end
end
# rubocop:enable Metrics/ModuleLength
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/useless_assignment.rb | lib/rubocop/cop/lint/useless_assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Lint
# Checks for every useless assignment to local variable in every
# scope.
# The basic idea for this cop was from the warning of `ruby -cw`:
#
# [source,console]
# ----
# assigned but unused variable - foo
# ----
#
# Currently this cop has advanced logic that detects unreferenced
# reassignments and properly handles varied cases such as branch, loop,
# rescue, ensure, etc.
#
# This cop's autocorrection avoids cases like `a ||= 1` because removing assignment from
# operator assignment can cause `NameError` if this assignment has been used to declare
# a local variable. For example, replacing `a ||= 1` with `a || 1` may cause
# "undefined local variable or method `a' for main:Object (NameError)".
#
# NOTE: Given the assignment `foo = 1, bar = 2`, removing unused variables
# can lead to a syntax error, so this case is not autocorrected.
#
# @example
#
# # bad
# def some_method
# some_var = 1
# do_something
# end
#
# # good
# def some_method
# some_var = 1
# do_something(some_var)
# end
class UselessAssignment < Base
extend AutoCorrector
include RangeHelp
MSG = 'Useless assignment to variable - `%<variable>s`.'
def self.joining_forces
VariableForce
end
def after_leaving_scope(scope, _variable_table)
scope.variables.each_value { |variable| check_for_unused_assignments(variable) }
end
def check_for_unused_assignments(variable)
return if variable.should_be_unused?
variable.assignments.reverse_each do |assignment|
check_for_unused_assignment(variable, assignment)
end
end
def check_for_unused_assignment(variable, assignment)
assignment_node = assignment.node
return if ignored_assignment?(variable, assignment_node, assignment)
message = message_for_useless_assignment(assignment)
range = offense_range(assignment)
add_offense(range, message: message) do |corrector|
# In cases like `x = 1, y = 2`, where removing a variable would cause a syntax error,
# and where changing `x ||= 1` to `x = 1` would cause `NameError`,
# the autocorrect will be skipped, even if the variable is unused.
next if sequential_assignment?(assignment_node) ||
assignment_node.parent&.or_asgn_type?
autocorrect(corrector, assignment)
end
ignore_node(assignment_node) if chained_assignment?(assignment_node)
end
def ignored_assignment?(variable, assignment_node, assignment)
assignment.used? || part_of_ignored_node?(assignment_node) ||
variable_in_loop_condition?(assignment_node, variable)
end
def message_for_useless_assignment(assignment)
variable = assignment.variable
format(MSG, variable: variable.name) + message_specification(assignment, variable).to_s
end
def offense_range(assignment)
if assignment.regexp_named_capture?
assignment.node.children.first.source_range
else
assignment.node.loc.name
end
end
def sequential_assignment?(node)
if node.lvasgn_type? && node.expression&.array_type? &&
node.each_descendant.any?(&:assignment?)
return true
end
return false unless node.parent
sequential_assignment?(node.parent)
end
def chained_assignment?(node)
return true if node.lvasgn_type? && node.expression&.send_type?
node.respond_to?(:expression) && node.expression&.lvasgn_type?
end
def message_specification(assignment, variable)
if assignment.multiple_assignment?
multiple_assignment_message(variable.name)
elsif assignment.operator_assignment?
operator_assignment_message(variable.scope, assignment)
else
similar_name_message(variable)
end
end
def multiple_assignment_message(variable_name)
" Use `_` or `_#{variable_name}` as a variable name to indicate " \
"that it won't be used."
end
def operator_assignment_message(scope, assignment)
return_value_node = return_value_node_of_scope(scope)
return unless assignment.meta_assignment_node.equal?(return_value_node)
" Use `#{assignment.operator.delete_suffix('=')}` instead of `#{assignment.operator}`."
end
def similar_name_message(variable)
variable_like_names = collect_variable_like_names(variable.scope)
similar_name = NameSimilarity.find_similar_name(variable.name, variable_like_names)
" Did you mean `#{similar_name}`?" if similar_name
end
# TODO: More precise handling (rescue, ensure, nested begin, etc.)
def return_value_node_of_scope(scope)
body_node = scope.body_node
if body_node.begin_type?
body_node.children.last
else
body_node
end
end
def collect_variable_like_names(scope)
names = scope.each_node.with_object(Set.new) do |node, set|
set << node.method_name if variable_like_method_invocation?(node)
end
variable_names = scope.variables.each_value.map(&:name)
names.merge(variable_names)
end
def variable_like_method_invocation?(node)
return false unless node.send_type?
node.receiver.nil? && !node.arguments?
end
# rubocop:disable Metrics/AbcSize
def autocorrect(corrector, assignment)
if assignment.exception_assignment?
remove_exception_assignment_part(corrector, assignment.node)
elsif assignment.multiple_assignment? || assignment.rest_assignment? ||
assignment.for_assignment?
rename_variable_with_underscore(corrector, assignment.node)
elsif assignment.operator_assignment?
remove_trailing_character_from_operator(corrector, assignment.node)
elsif assignment.regexp_named_capture?
replace_named_capture_group_with_non_capturing_group(corrector, assignment.node,
assignment.variable.name)
else
remove_local_variable_assignment_part(corrector, assignment.node)
end
end
# rubocop:enable Metrics/AbcSize
def remove_exception_assignment_part(corrector, node)
corrector.remove(
range_between(
(node.parent.children.first&.source_range || node.parent.location.keyword).end_pos,
node.source_range.end_pos
)
)
end
def rename_variable_with_underscore(corrector, node)
corrector.replace(node, '_')
end
def remove_trailing_character_from_operator(corrector, node)
corrector.remove(node.parent.location.operator.end.adjust(begin_pos: -1))
end
def replace_named_capture_group_with_non_capturing_group(corrector, node, variable_name)
corrector.replace(
node.children.first,
node.children.first.source.sub(/\(\?<#{variable_name}>/, '(?:')
)
end
def remove_local_variable_assignment_part(corrector, node)
corrector.replace(node, node.expression.source)
end
def variable_in_loop_condition?(assignment_node, variable)
return false if assignment_node.each_ancestor(:any_def).any?
loop_node = assignment_node.each_ancestor.find do |ancestor|
ancestor.type?(*VariableForce::LOOP_TYPES)
end
return false unless loop_node.respond_to?(:condition)
condition_node = loop_node.condition
variable_name = variable.name
return true if condition_node.lvar_type? && condition_node.children.first == variable_name
condition_node.each_descendant(:lvar) do |lvar_node|
return true if lvar_node.children.first == variable_name
end
false
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.