Module: Homebrew::Style Private

Defined in:
style.rb

Overview

This module is part of a private API. This module may only be used in the Homebrew/brew repository. Third parties should avoid using this module if possible, as it may be removed or changed without warning.

Helper module for running RuboCop.

Defined Under Namespace

Classes: LineLocation, Offense, Offenses

Constant Summary collapse

RUBOCOP =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

(HOMEBREW_LIBRARY_PATH/"utils/rubocop.rb").freeze

Class Method Summary collapse

Class Method Details

.check_style_and_print(files, **options) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Checks style for a list of files, printing simple RuboCop output. Returns true if violations were found, false otherwise.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'style.rb', line 15

def check_style_and_print(files, **options)
  success = check_style_impl(files, :print, **options)

  if ENV["GITHUB_ACTIONS"] && !success
    check_style_json(files, **options).each do |path, offenses|
      offenses.each do |o|
        line = o.location.line
        column = o.location.line

        annotation = GitHub::Actions::Annotation.new(:error, o.message, file: path, line: line, column: column)
        puts annotation if annotation.relevant?
      end
    end
  end

  success
end

.check_style_impl(files, output_type, fix: false, except_cops: nil, only_cops: nil, display_cop_names: false, reset_cache: false, debug: false, verbose: false) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Raises:

  • (ArgumentError)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'style.rb', line 39

def check_style_impl(files, output_type,
                     fix: false,
                     except_cops: nil, only_cops: nil,
                     display_cop_names: false,
                     reset_cache: false,
                     debug: false, verbose: false)
  raise ArgumentError, "Invalid output type: #{output_type.inspect}" unless [:print, :json].include?(output_type)

  shell_files, ruby_files =
    Array(files).map(&method(:Pathname))
                .partition { |f| f.realpath == HOMEBREW_BREW_FILE.realpath || f.extname == ".sh" }

  rubocop_result = if shell_files.any? && ruby_files.none?
    output_type == :json ? [] : true
  else
    run_rubocop(ruby_files, output_type,
                fix: fix,
                except_cops: except_cops, only_cops: only_cops,
                display_cop_names: display_cop_names,
                reset_cache: reset_cache,
                debug: debug, verbose: verbose)
  end

  shellcheck_result = if ruby_files.any? && shell_files.none?
    output_type == :json ? [] : true
  else
    run_shellcheck(shell_files, output_type)
  end

  if output_type == :json
    Offenses.new(rubocop_result + shellcheck_result)
  else
    rubocop_result && shellcheck_result
  end
end

.check_style_json(files, **options) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Checks style for a list of files, returning results as an Offenses object parsed from its JSON output.



35
36
37
# File 'style.rb', line 35

def check_style_json(files, **options)
  check_style_impl(files, :json, **options)
end

.json_result!(result) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



234
235
236
237
238
239
240
241
# File 'style.rb', line 234

def json_result!(result)
  # An exit status of 1 just means violations were found; other numbers mean
  # execution errors.
  # JSON needs to be at least 2 characters.
  result.assert_success! if !(0..1).cover?(result.status.exitstatus) || result.stdout.length < 2

  JSON.parse(result.stdout)
end

.run_rubocop(files, output_type, fix: false, except_cops: nil, only_cops: nil, display_cop_names: false, reset_cache: false, debug: false, verbose: false) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'style.rb', line 77

def run_rubocop(files, output_type,
                fix: false, except_cops: nil, only_cops: nil, display_cop_names: false, reset_cache: false,
                debug: false, verbose: false)
  Homebrew.install_bundler_gems!

  require "warnings"

  Warnings.ignore :parser_syntax do
    require "rubocop"
  end

  require "rubocops/all"

  args = %w[
    --force-exclusion
  ]
  args << if fix
    "-A"
  else
    "--parallel"
  end

  args += ["--extra-details"] if verbose
  args += ["--display-cop-names"] if display_cop_names || verbose

  if except_cops
    except_cops.map! { |cop| RuboCop::Cop::Cop.registry.qualified_cop_name(cop.to_s, "") }
    cops_to_exclude = except_cops.select do |cop|
      RuboCop::Cop::Cop.registry.names.include?(cop) ||
        RuboCop::Cop::Cop.registry.departments.include?(cop.to_sym)
    end

    args << "--except" << cops_to_exclude.join(",") unless cops_to_exclude.empty?
  elsif only_cops
    only_cops.map! { |cop| RuboCop::Cop::Cop.registry.qualified_cop_name(cop.to_s, "") }
    cops_to_include = only_cops.select do |cop|
      RuboCop::Cop::Cop.registry.names.include?(cop) ||
        RuboCop::Cop::Cop.registry.departments.include?(cop.to_sym)
    end

    odie "RuboCops #{only_cops.join(",")} were not found" if cops_to_include.empty?

    args << "--only" << cops_to_include.join(",")
  end

  has_non_formula = files.any? do |file|
    File.expand_path(file).start_with? HOMEBREW_LIBRARY_PATH
  end

  if files.any? && !has_non_formula
    config = if files.first && File.exist?("#{files.first}/spec")
      HOMEBREW_LIBRARY/".rubocop_rspec.yml"
    else
      HOMEBREW_LIBRARY/".rubocop.yml"
    end
    args << "--config" << config
  end

  if files.blank?
    args << HOMEBREW_LIBRARY_PATH
  else
    args += files
  end

  cache_env = { "XDG_CACHE_HOME" => "#{HOMEBREW_CACHE}/style" }

  FileUtils.rm_rf cache_env["XDG_CACHE_HOME"] if reset_cache

  case output_type
  when :print
    args << "--debug" if debug

    # Don't show the default formatter's progress dots
    # on CI or if only checking a single file.
    args << "--format" << "clang" if ENV["CI"] || files.count { |f| !f.directory? } == 1

    args << "--color" if Tty.color?

    system cache_env, RUBY_PATH, RUBOCOP, *args
    $CHILD_STATUS.success?
  when :json
    result = system_command RUBY_PATH,
                            args: [RUBOCOP, "--format", "json", *args],
                            env:  cache_env
    json = json_result!(result)
    json["files"]
  end
end

.run_shellcheck(files, output_type) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'style.rb', line 166

def run_shellcheck(files, output_type)
  shellcheck   = Formula["shellcheck"].opt_bin/"shellcheck" if Formula["shellcheck"].any_version_installed?
  shellcheck ||= which("shellcheck")
  shellcheck ||= which("shellcheck", ENV["HOMEBREW_PATH"])
  shellcheck ||= begin
    ohai "Installing `shellcheck` for shell style checks..."
    safe_system HOMEBREW_BREW_FILE, "install", "shellcheck"
    Formula["shellcheck"].opt_bin/"shellcheck"
  end

  if files.empty?
    files = [
      HOMEBREW_BREW_FILE,
      HOMEBREW_REPOSITORY/"completions/bash/brew",
      *HOMEBREW_LIBRARY.glob("Homebrew/*.sh"),
      *HOMEBREW_LIBRARY.glob("Homebrew/shims/**/*").map(&:realpath).uniq
                       .reject { |path| path.directory? || path.basename.to_s == "cc" },
      *HOMEBREW_LIBRARY.glob("Homebrew/{dev-,}cmd/*.sh"),
      *HOMEBREW_LIBRARY.glob("Homebrew/{cask/,}utils/*.sh"),
    ]
  end

  args = ["--shell=bash", "--enable=all", "--external-sources", "--source-path=#{HOMEBREW_LIBRARY}", "--", *files]

  case output_type
  when :print
    system shellcheck, "--format=tty", *args
    $CHILD_STATUS.success?
  when :json
    result = system_command shellcheck, args: ["--format=json", *args]
    json = json_result!(result)

    # Convert to same format as RuboCop offenses.
    severity_hash = { "style" => "refactor", "info" => "convention" }
    json.group_by { |v| v["file"] }
        .map do |k, v|
      {
        "path"     => k,
        "offenses" => v.map do |o|
          o.delete("file")

          o["cop_name"] = "SC#{o.delete("code")}"

          level = o.delete("level")
          o["severity"] = severity_hash.fetch(level, level)

          line = o.delete("line")
          column = o.delete("column")

          o["corrected"] = false
          o["correctable"] = o.delete("fix").present?

          o["location"] = {
            "start_line"   => line,
            "start_column" => column,
            "last_line"    => o.delete("endLine"),
            "last_column"  => o.delete("endColumn"),
            "line"         => line,
            "column"       => column,
          }

          o
        end,
      }
    end
  end
end