Class: Homebrew::DevCmd::Bottle Private

Inherits:
AbstractCommand show all
Includes:
FileUtils, OS::Linux::DevCmd::Bottle, OS::Mac::DevCmd::Bottle
Defined in:
dev-cmd/bottle.rb,
sorbet/rbi/dsl/homebrew/dev_cmd/bottle.rbi

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

Defined Under Namespace

Classes: Args, BottlingResult

Constant Summary collapse

BOTTLE_ERB =

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.

T.let(<<-EOS.freeze, String)
  bottle do
    <% if [HOMEBREW_BOTTLE_DEFAULT_DOMAIN.to_s,
     "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}/bottles"].exclude?(root_url) %>
    root_url "<%= root_url %>"<% if root_url_using.present? %>,
using: <%= root_url_using %>
    <% end %>
    <% end %>
    <% if rebuild.positive? %>
    rebuild <%= rebuild %>
    <% end %>
    <% sha256_lines.each do |line| %>
    <%= line %>
    <% end %>
  end
EOS
MAXIMUM_STRING_MATCHES =

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.

100
T.let([
  %r{#{Regexp.escape(HOMEBREW_LIBRARY)}/Homebrew/os/(?:mac|linux)/pkgconfig},
].freeze, T::Array[Regexp])

Instance Method Summary collapse

Methods inherited from AbstractCommand

command, command_name, dev_cmd?, #initialize, parser, ruby_cmd?

Methods included from Utils::Output::Mixin

#issue_reporting_message, #odebug, #odeprecated, #odie, #odisabled, #ofail, #oh1, #oh1_title, #ohai, #ohai_title, #onoe, #opoo, #opoo_once, #opoo_outside_github_actions, #opoo_without_github_actions_annotation, #pretty_cannot_install, #pretty_deprecated, #pretty_disabled, #pretty_duration, #pretty_incompatible, #pretty_install_status, #pretty_installed, #pretty_removed, #pretty_uninstalled, #pretty_unmarked, #pretty_upgradable, #pretty_warning

Constructor Details

This class inherits a constructor from Homebrew::AbstractCommand

Instance Method Details

#args ⇒ Homebrew::DevCmd::Bottle::Args

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.



10
# File 'sorbet/rbi/dsl/homebrew/dev_cmd/bottle.rbi', line 10

def args; end

#binary_relocation_diagnostic_string(match, relative_path, offset) ⇒ String

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.

strings - uses locale-dependent isprint(), so a match can contain invalid UTF-8. Scrub it instead of dropping it, or a build prefix could go undetected.

Parameters:

Returns:



245
246
247
248
249
250
251
# File 'dev-cmd/bottle.rb', line 245

def binary_relocation_diagnostic_string(match, relative_path, offset)
  utf8_match = match.dup.force_encoding(Encoding::UTF_8)
  return utf8_match if utf8_match.valid_encoding?

  opoo "Scrubbing string with invalid encoding in #{relative_path} at offset 0x#{offset}"
  utf8_match.scrub
end

#bottle_keg(formula, keg, tap, bottle_path, tar_path, padded:) ⇒ BottlingResult

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.

Parameters:

Returns:



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'dev-cmd/bottle.rb', line 257

def bottle_keg(formula, keg, tap, bottle_path, tar_path, padded:)
  prefix = HOMEBREW_PREFIX.to_s
  cellar = HOMEBREW_CELLAR.to_s
  formula_and_runtime_deps_names = [formula.name] + formula.runtime_dependencies.map(&:name)
  binary_relocation_files = T.let([], T::Array[Pathname])
  binary_relocation_diagnostics = T.let([], T::Array[T::Hash[String, T.any(String, Integer)]])
  tab = T.let(nil, T.nilable(Tab))
  relocatable = T.let(false, T::Boolean)
  skip_relocation = T.let(false, T::Boolean)

  keg.lock do
    original_tab = nil
    changed_files = T.let(nil, T.nilable(T::Array[Pathname]))
    linkage_files = T.let(nil, T.nilable(T::Array[Pathname]))

    begin
      keg.delete_pyc_files!
      keg.delete_node_gyp_debris!
      keg.strip_node_gyp_addons!
      keg.relativize_prefix_symlinks!

      unless args.skip_relocation?
        changed_files, linkage_files = keg.replace_locations_with_placeholders
      end

      [Formula, Keg, Tab, Dependency, Requirement].each(&:clear_cache)

      tab = keg.tab
      original_tab = tab.dup
      tab.built_prefix = prefix if tab.built_prefix
      tab.poured_from_bottle = false
      tab.time = nil
      tab.changed_files = changed_files&.dup
      tab.linkage_files = linkage_files&.sort

      ohai "Detecting if #{bottle_path.basename} is relocatable..." if keg.disk_usage > 1 * 1024 * 1024

      is_usr_local_prefix = prefix == "/usr/local"
      prefix_check = is_usr_local_prefix ? "#{prefix}/opt" : prefix

      # Ignore matches to source code, which is not required at run time.
      # These matches may be caused by debugging symbols.
      ignores = [%r{/include/|\.(?:c|cc|cpp|h|hpp)$}]

      # Add additional workarounds to ignore
      ignores += formula_ignores(formula)

      repository_reference = if HOMEBREW_PREFIX == HOMEBREW_REPOSITORY
        HOMEBREW_LIBRARY
      else
        HOMEBREW_REPOSITORY
      end.to_s
      if keg_contain?(repository_reference, keg, ignores + ALLOWABLE_HOMEBREW_REPOSITORY_LINKS)
        odie "Bottle contains non-relocatable reference to #{repository_reference}!"
      end

      relocatable = true
      if args.skip_relocation?
        skip_relocation = true
      else
        [prefix_check, cellar, HOMEBREW_LIBRARY.to_s].each do |path|
          relocatable = false if keg_contain?(
            path, keg, ignores, formula_and_runtime_deps_names,
            binary_relocation_files:, binary_relocation_diagnostics:
          )
        end
        if is_usr_local_prefix
          relocatable = false if keg_contain_absolute_symlink_starting_with?(prefix, keg)
          if tap.disabled_new_usr_local_relocation_formulae.exclude?(formula.name)
            keg.new_usr_local_replacement_pairs.each_value do |value|
              relocatable = false if keg_contain?(
                value.fetch(:old), keg, ignores,
                binary_relocation_files:, binary_relocation_diagnostics:
              )
            end
          else
            ["#{prefix}/etc", "#{prefix}/var", "#{prefix}/share/vim"].each do |path|
              relocatable = false if keg_contain?(
                path, keg, ignores,
                binary_relocation_files:, binary_relocation_diagnostics:
              )
            end
          end
        end
        skip_relocation = relocatable && !keg.require_relocation?
      end
      tab.padded_prefix = (true if padded && !relocatable)
      tab.binary_relocation_files = args.skip_relocation? ? nil : binary_relocation_files.sort

      if args.only_json_tab?
        tab.changed_files&.delete(Pathname.new(AbstractTab::FILENAME))
        tab.tabfile&.unlink
      else
        tab.write
      end

      SBOM.create(formula, tab).write(bottling: true)

      keg.consistent_reproducible_symlink_permissions!

      cd cellar do
        sudo_purge
        # Tar then gzip for reproducible bottles.
        # GNU tar fails to create a bottle if modification time is unsigned integer
        # (i.e. before 1970)
        time_at_epoch = Time.at(1)
        tab_source_modified_time = [time_at_epoch, tab.source_modified_time].max
        tar_mtime = tab_source_modified_time.strftime("%Y-%m-%d %H:%M:%S")
        tar, tar_args = setup_tar_and_args!(tar_mtime, default_tar: formula.name == "gnu-tar")
        SystemCommand.safe_system tar, "--create", "--numeric-owner",
                                  args: [*tar_args, "--file", tar_path,
                                         "#{formula.name}/#{formula.pkg_version}"]
        sudo_purge
        # Set filename as it affects the tarball checksum.
        relocatable_tar_path = "#{formula}-bottle.tar"
        mv tar_path, relocatable_tar_path
        # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2
        # or an uncompressed tarball (and more bandwidth friendly).
        Utils::Gzip.compress_with_options(relocatable_tar_path,
                                          mtime:     tab.source_modified_time,
                                          orig_name: relocatable_tar_path,
                                          output:    bottle_path)
        sudo_purge
      end

      puts if !relocatable && args.verbose?
    rescue Interrupt
      Utils::Interrupts.ignore { bottle_path.unlink if bottle_path.exist? }
      raise
    ensure
      Utils::Interrupts.ignore do
        original_tab&.write
        keg.replace_placeholders_with_locations(changed_files) if changed_files
      end
    end
  end

  BottlingResult.new(tab:, relocatable:, skip_relocation:, binary_relocation_diagnostics:)
end

#bottle_output(bottle, root_url_using) ⇒ String

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.

Parameters:

Returns:



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'dev-cmd/bottle.rb', line 145

def bottle_output(bottle, root_url_using)
  cellars = bottle.checksums.filter_map do |checksum|
    cellar = checksum["cellar"]
    next unless cellar_parameter_needed? cellar

    case cellar
    when String
      %Q("#{cellar}")
    when Symbol
      ":#{cellar}"
    end
  end
  tag_column = cellars.empty? ? 0 : "cellar: #{cellars.max_by(&:length)}, ".length

  tags = bottle.checksums.map { |checksum| checksum["tag"] }
  # Start where the tag ends, add the max length of the tag, add two for the `: `
  digest_column = tag_column + tags.max_by(&:length).length + 2

  sha256_lines = bottle.checksums.map do |checksum|
    generate_sha256_line(checksum["tag"], checksum["digest"], checksum["cellar"], tag_column, digest_column)
  end
  erb_binding = bottle.instance_eval { binding }
  erb_binding.local_variable_set(:sha256_lines, sha256_lines)
  erb_binding.local_variable_set(:root_url_using, root_url_using)
  erb = ERB.new BOTTLE_ERB
  erb.result(erb_binding).gsub(/^\s*$\n/, "")
end

#generate_sha256_line(tag, digest, cellar, tag_column, digest_column) ⇒ String

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.

Parameters:

Returns:



129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'dev-cmd/bottle.rb', line 129

def generate_sha256_line(tag, digest, cellar, tag_column, digest_column)
  line = "sha256 "
  tag_column += line.length
  digest_column += line.length
  if cellar.is_a?(Symbol)
    line += "cellar: :#{cellar},"
  elsif cellar_parameter_needed?(cellar)
    line += %Q(cellar: "#{cellar}",)
  end
  line += " " * (tag_column - line.length)
  line += "#{tag}:"
  line += " " * (digest_column - line.length)
  %Q(#{line}"#{digest}")
end

#merge_bottle_spec(old_keys, old_bottle_spec, new_bottle_hash) ⇒ Array<(Array<String>, Array<Hash{Symbol => String, Symbol}>)>

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.

Parameters:

Returns:



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
233
234
235
236
237
238
239
240
# File 'dev-cmd/bottle.rb', line 199

def merge_bottle_spec(old_keys, old_bottle_spec, new_bottle_hash)
  mismatches = []
  checksums = []

  new_values = {
    root_url: new_bottle_hash["root_url"],
    rebuild:  new_bottle_hash["rebuild"],
  }

  # A `manifest_sha256` is stale once the block changes, so it is dropped.
  skip_keys = [:sha256, :cellar, :manifest_sha256]
  old_keys.each do |key|
    next if skip_keys.include?(key)

    old_value = old_bottle_spec.public_send(key).to_s
    new_value = new_values[key].to_s

    next if old_value.present? && new_value == old_value

    mismatches << "#{key}: old: #{old_value.inspect}, new: #{new_value.inspect}"
  end

  return [mismatches, checksums] if old_keys.exclude? :sha256

  old_bottle_spec.collector.each_tag do |tag|
    old_tag_spec = old_bottle_spec.collector.specification_for(tag)
    odie "Specification for tag #{tag} is nil" if old_tag_spec.nil?

    old_hexdigest = old_tag_spec.checksum.hexdigest
    old_cellar = old_tag_spec.cellar
    new_value = new_bottle_hash.dig("tags", tag.to_s)
    if new_value.present? && new_value["sha256"] != old_hexdigest
      mismatches << "sha256 #{tag}: old: #{old_hexdigest.inspect}, new: #{new_value["sha256"].inspect}"
    elsif new_value.present? && new_value["cellar"] != old_cellar.to_s
      mismatches << "cellar #{tag}: old: #{old_cellar.to_s.inspect}, new: #{new_value["cellar"].inspect}"
    else
      checksums << { cellar: old_cellar, tag.to_sym => old_hexdigest }
    end
  end

  [mismatches, checksums]
end

#merge_json_files(json_files) ⇒ Hash{String => T.untyped}

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.

Parameters:

Returns:



181
182
183
184
185
186
187
188
189
190
191
192
# File 'dev-cmd/bottle.rb', line 181

def merge_json_files(json_files)
  json_files.reduce({}) do |hash, json_file|
    json_file.each_value do |json_hash|
      json_bottle = json_hash["bottle"]
      cellar = json_bottle.delete("cellar")
      json_bottle["tags"].each_value do |json_platform|
        json_platform["cellar"] ||= cellar
      end
    end
    hash.deep_merge(json_file)
  end
end

#parse_json_files(filenames) ⇒ Array<Hash{String => T.untyped}>

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.

Parameters:

Returns:



174
175
176
177
178
# File 'dev-cmd/bottle.rb', line 174

def parse_json_files(filenames)
  filenames.map do |filename|
    JSON.parse(File.read(filename))
  end
end

#run ⇒ void

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.

This method returns an undefined value.



110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'dev-cmd/bottle.rb', line 110

def run
  if args.merge?
    Utils::GemSetup.install_bundler_gems!(groups: ["ast"])
    return merge
  end

  Utils::GemSetup.install_bundler_gems!(groups: ["bottle"])

  gnu_tar_formula_ensure_installed_if_needed! if args.only_json_tab?

  args.named.to_resolved_formulae(uniq: false).each do |formula|
    bottle_formula formula
  end
end

#warn_missing_all_bottle(formula_name, tag_hashes) ⇒ void

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.

This method returns an undefined value.

Parameters:



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'dev-cmd/bottle.rb', line 406

def warn_missing_all_bottle(formula_name, tag_hashes)
  github_event_path = ENV.fetch("GITHUB_EVENT_PATH", nil)
  return if github_event_path.blank?

  github_event = JSON.parse(File.read(github_event_path))
  repository = github_event.dig("repository", "full_name")
  # `brew pr-pull` runs from `workflow_dispatch`, which passes the PR as an input.
  pull_request_number = github_event.dig("pull_request", "number") ||
                        github_event.dig("inputs", "pull_request")
  return if repository.blank? || pull_request_number.blank?

  GitHub.create_issue_comment(repository, pull_request_number, <<~MARKDOWN)
    Warning: #{formula_name} should have had an `:all` bottle but one could not be created.
    #{Utils::Bottles.missing_all_bottle_publish_note.capitalize}.

    ```json
    #{JSON.pretty_generate(tag_hashes)}
    ```
  MARKDOWN
rescue GitHub::API::Error, JSON::ParserError, Errno::ENOENT => e
  opoo "Failed to post missing `:all` bottle warning to pull request: #{e.message}"
end

#write_bottle_json(filename, contents) ⇒ void

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.

This method returns an undefined value.

Parameters:



398
399
400
401
402
403
# File 'dev-cmd/bottle.rb', line 398

def write_bottle_json(filename, contents)
  puts "Writing #{filename}" if args.verbose?
  json_path = Pathname(filename)
  json_path.unlink if json_path.exist?
  json_path.write(contents)
end