Module: Solargraph::Diagnostics::RubocopHelpers

Included in:
Rubocop, LanguageServer::Message::TextDocument::Formatting
Defined in:
lib/solargraph/diagnostics/rubocop_helpers.rb

Overview

Utility methods for the RuboCop diagnostics reporter.

Class Method Summary collapse

Class Method Details

.find_rubocop_file(filename) ⇒ String?

Find a RuboCop configuration file in a file’s directory tree.

Parameters:

  • filename (String)

Returns:

  • (String, nil)


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/solargraph/diagnostics/rubocop_helpers.rb', line 30

def find_rubocop_file filename
  return nil unless File.exist?(filename)
  filename = File.realpath(filename)
  dir = File.dirname(filename)
  until File.dirname(dir) == dir
    here = File.join(dir, '.rubocop.yml')
    return here if File.exist?(here)
    dir = File.dirname(dir)
  end
  nil
end

.fix_drive_letter(path) ⇒ String

RuboCop internally uses capitalized drive letters for Windows paths, so we need to convert the paths provided to the command.

Parameters:

  • path (String)

Returns:

  • (String)


47
48
49
50
# File 'lib/solargraph/diagnostics/rubocop_helpers.rb', line 47

def fix_drive_letter path
  return path unless path.match(/^[a-z]:/)
  path[0].upcase + path[1..-1]
end

.generate_options(filename, code) ⇒ Array(Array<String>, Array<String>)

Generate command-line options for the specified filename and code.

Parameters:

  • filename (String)
  • code (String)

Returns:

  • (Array(Array<String>, Array<String>))


15
16
17
18
19
20
21
22
23
24
# File 'lib/solargraph/diagnostics/rubocop_helpers.rb', line 15

def generate_options filename, code
  args = ['-f', 'j']
  rubocop_file = find_rubocop_file(filename)
  args.push('-c', fix_drive_letter(rubocop_file)) unless rubocop_file.nil?
  args.push filename
  base_options = RuboCop::Options.new
  options, paths = base_options.parse(args)
  options[:stdin] = code
  [options, paths]
end

.redirect_stdoutString

TODO:

This is a smelly way to redirect output, but the RuboCop specs do the same thing.

Returns:

  • (String)


55
56
57
58
59
60
61
# File 'lib/solargraph/diagnostics/rubocop_helpers.rb', line 55

def redirect_stdout
  redir = StringIO.new
  $stdout = redir
  yield if block_given?
  $stdout = STDOUT
  redir.string
end