Module: RuboCop::ProjectIndexLoader

Defined in:
lib/rubocop/project_index_loader.rb

Overview

Defensive loader for the optional ‘rubydex` gem.

When ‘AllCops/UseProjectIndex` is enabled in the user’s configuration, RuboCop builds a project-wide index using ‘Rubydex::Graph` and exposes it to cops that opt in. The gem is intentionally not a runtime dependency; if it is not installed, or if the running Ruby is older than what `rubydex` supports, RuboCop falls back to its standard file-local behavior.

Constant Summary collapse

MINIMUM_RUBY_VERSION =
'3.2'

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns whether the ‘rubydex` gem can be loaded. The result is memoized for the lifetime of the process.

Returns:

  • (Boolean)


18
19
20
21
22
# File 'lib/rubocop/project_index_loader.rb', line 18

def available?
  return @available if defined?(@available)

  @available = supported_ruby? && try_require
end

.build_index(paths) ⇒ Object

Builds and resolves a ‘Rubydex::Graph` for the given file paths. Returns the resolved graph, or `nil` if the build fails. This is the only place in RuboCop that depends on the concrete `Rubydex::Graph` API, so callers (e.g. `Runner`) do not need to know which Rubydex classes or methods are involved.



57
58
59
60
61
62
63
64
# File 'lib/rubocop/project_index_loader.rb', line 57

def build_index(paths)
  graph = Rubydex::Graph.new
  graph.index_all(paths.map(&:to_s))
  graph.resolve
  graph
rescue StandardError => e
  warn Rainbow("rubydex index build failed: #{e.message}. Continuing without it.").yellow
end

.supported_ruby?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/rubocop/project_index_loader.rb', line 24

def supported_ruby?
  RUBY_VERSION >= MINIMUM_RUBY_VERSION
end

.try_requireObject



46
47
48
49
50
51
# File 'lib/rubocop/project_index_loader.rb', line 46

def try_require
  require 'rubydex'
  true
rescue LoadError
  false
end

.warn_unavailableObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rubocop/project_index_loader.rb', line 28

def warn_unavailable
  return if @warned

  @warned = true

  if supported_ruby?
    warn Rainbow(<<~MSG).yellow
      `AllCops/UseProjectIndex` is enabled but the `rubydex` gem is not installed.
      Analyses that use the project index will be skipped. Add `gem 'rubydex'` to your Gemfile.
    MSG
  else
    warn Rainbow(<<~MSG).yellow
      `AllCops/UseProjectIndex` is enabled but `rubydex` requires Ruby #{MINIMUM_RUBY_VERSION} or later (current: #{RUBY_VERSION}).
      Analyses that use the project index will be skipped.
    MSG
  end
end