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 |
|---|---|---|---|---|---|---|---|---|
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/language/perl/shebang_spec.rb | Library/Homebrew/test/language/perl/shebang_spec.rb | # frozen_string_literal: true
require "language/perl"
require "utils/shebang"
RSpec.describe Language::Perl::Shebang do
let(:file) { Tempfile.new("perl-shebang") }
let(:broken_file) { Tempfile.new("perl-shebang") }
let(:f) do
f = {}
f[:perl] = formula "perl" do
url "https://brew.sh/perl-1.0.tgz"
end
f[:depends_on] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
depends_on "perl"
end
f[:uses_from_macos] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
uses_from_macos "perl"
end
f[:no_deps] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
end
f
end
before do
file.write <<~EOS
#!/usr/bin/env perl
a
b
c
EOS
file.flush
broken_file.write <<~EOS
#!perl
a
b
c
EOS
broken_file.flush
end
after { [file, broken_file].each(&:unlink) }
describe "#detected_perl_shebang" do
it "can be used to replace Perl shebangs when depends_on \"perl\" is used" do
allow(Formulary).to receive(:factory).with(f[:perl].name).and_return(f[:perl])
Utils::Shebang.rewrite_shebang described_class.detected_perl_shebang(f[:depends_on]), file.path
expect(File.read(file)).to eq <<~EOS
#!#{HOMEBREW_PREFIX}/opt/perl/bin/perl
a
b
c
EOS
end
it "can be used to replace Perl shebangs when uses_from_macos \"perl\" is used" do
allow(Formulary).to receive(:factory).with(f[:perl].name).and_return(f[:perl])
Utils::Shebang.rewrite_shebang described_class.detected_perl_shebang(f[:uses_from_macos]), file.path
expected_shebang = if OS.mac?
"/usr/bin/perl#{MacOS.preferred_perl_version}"
else
HOMEBREW_PREFIX/"opt/perl/bin/perl"
end
expect(File.read(file)).to eq <<~EOS
#!#{expected_shebang}
a
b
c
EOS
end
it "can fix broken shebang like `#!perl`" do
allow(Formulary).to receive(:factory).with(f[:perl].name).and_return(f[:perl])
Utils::Shebang.rewrite_shebang described_class.detected_perl_shebang(f[:uses_from_macos]), broken_file.path
expected_shebang = if OS.mac?
"/usr/bin/perl#{MacOS.preferred_perl_version}"
else
HOMEBREW_PREFIX/"opt/perl/bin/perl"
end
expect(File.read(broken_file)).to eq <<~EOS
#!#{expected_shebang}
a
b
c
EOS
end
it "errors if formula doesn't depend on perl" do
expect { Utils::Shebang.rewrite_shebang described_class.detected_perl_shebang(f[:no_deps]), file.path }
.to raise_error(ShebangDetectionError, "Cannot detect Perl shebang: formula does not depend on Perl.")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/language/node/shebang_spec.rb | Library/Homebrew/test/language/node/shebang_spec.rb | # frozen_string_literal: true
require "language/node"
require "utils/shebang"
RSpec.describe Language::Node::Shebang do
let(:file) { Tempfile.new("node-shebang") }
let(:broken_file) { Tempfile.new("node-shebang") }
let(:f) do
f = {}
f[:node18] = formula "node@18" do
url "https://brew.sh/node-18.0.0.tgz"
end
f[:versioned_node_dep] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
depends_on "node@18"
end
f[:no_deps] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
end
f[:multiple_deps] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
depends_on "node"
depends_on "node@18"
end
f
end
before do
file.write <<~EOS
#!/usr/bin/env node
a
b
c
EOS
file.flush
broken_file.write <<~EOS
#!node
a
b
c
EOS
broken_file.flush
end
after { [file, broken_file].each(&:unlink) }
describe "#detected_node_shebang" do
it "can be used to replace Node shebangs" do
allow(Formulary).to receive(:factory).with(f[:node18].name).and_return(f[:node18])
Utils::Shebang.rewrite_shebang described_class.detected_node_shebang(f[:versioned_node_dep]), file.path
expect(File.read(file)).to eq <<~EOS
#!#{HOMEBREW_PREFIX/"opt/node@18/bin/node"}
a
b
c
EOS
end
it "can fix broken shebang like `#!node`" do
allow(Formulary).to receive(:factory).with(f[:node18].name).and_return(f[:node18])
Utils::Shebang.rewrite_shebang described_class.detected_node_shebang(f[:versioned_node_dep]), broken_file.path
expect(File.read(broken_file)).to eq <<~EOS
#!#{HOMEBREW_PREFIX/"opt/node@18/bin/node"}
a
b
c
EOS
end
it "errors if formula doesn't depend on node" do
expect { Utils::Shebang.rewrite_shebang described_class.detected_node_shebang(f[:no_deps]), file.path }
.to raise_error(ShebangDetectionError, "Cannot detect Node shebang: formula does not depend on Node.")
end
it "errors if formula depends on more than one node" do
expect { Utils::Shebang.rewrite_shebang described_class.detected_node_shebang(f[:multiple_deps]), file.path }
.to raise_error(ShebangDetectionError, "Cannot detect Node shebang: formula has multiple Node dependencies.")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/language/php/shebang_spec.rb | Library/Homebrew/test/language/php/shebang_spec.rb | # frozen_string_literal: true
require "language/php"
require "utils/shebang"
RSpec.describe Language::PHP::Shebang do
let(:file) { Tempfile.new("php-shebang") }
let(:broken_file) { Tempfile.new("php-shebang") }
let(:f) do
f = {}
f[:php81] = formula "php@8.1" do
url "https://brew.sh/node-18.0.0.tgz"
end
f[:versioned_php_dep] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
depends_on "php@8.1"
end
f[:no_deps] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
end
f[:multiple_deps] = formula "foo" do
url "https://brew.sh/foo-1.0.tgz"
depends_on "php"
depends_on "php@8.1"
end
f
end
before do
file.write <<~EOS
#!/usr/bin/env php
a
b
c
EOS
file.flush
broken_file.write <<~EOS
#!php
a
b
c
EOS
broken_file.flush
end
after { [file, broken_file].each(&:unlink) }
describe "#detected_php_shebang" do
it "can be used to replace PHP shebangs" do
allow(Formulary).to receive(:factory).with(f[:php81].name).and_return(f[:php81])
Utils::Shebang.rewrite_shebang described_class.detected_php_shebang(f[:versioned_php_dep]), file.path
expect(File.read(file)).to eq <<~EOS
#!#{HOMEBREW_PREFIX/"opt/php@8.1/bin/php"}
a
b
c
EOS
end
it "can fix broken shebang like `#!php`" do
allow(Formulary).to receive(:factory).with(f[:php81].name).and_return(f[:php81])
Utils::Shebang.rewrite_shebang described_class.detected_php_shebang(f[:versioned_php_dep]), broken_file.path
expect(File.read(broken_file)).to eq <<~EOS
#!#{HOMEBREW_PREFIX/"opt/php@8.1/bin/php"}
a
b
c
EOS
end
it "errors if formula doesn't depend on PHP" do
expect { Utils::Shebang.rewrite_shebang described_class.detected_php_shebang(f[:no_deps]), file.path }
.to raise_error(ShebangDetectionError, "Cannot detect PHP shebang: formula does not depend on PHP.")
end
it "errors if formula depends on more than one php" do
expect { Utils::Shebang.rewrite_shebang described_class.detected_php_shebang(f[:multiple_deps]), file.path }
.to raise_error(ShebangDetectionError, "Cannot detect PHP shebang: formula has multiple PHP dependencies.")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/rubocop.rb | Library/Homebrew/utils/rubocop.rb | #!/usr/bin/env ruby
# typed: strict
# frozen_string_literal: true
require_relative "../standalone"
require_relative "../warnings"
Warnings.ignore :parser_syntax do
require "rubocop"
end
# TODO: Remove this workaround once TestProf fixes their RuboCop plugin.
require_relative "test_prof_rubocop_stub"
exit RuboCop::CLI.new.run
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/gems.rb | Library/Homebrew/utils/gems.rb | # typed: true # rubocop:disable Sorbet/StrictSigil
# frozen_string_literal: true
# Never `require` anything in this file (except English). It needs to be able to
# work as the first item in `brew.rb` so we can load gems with Bundler when
# needed before anything else is loaded (e.g. `json`).
Homebrew::FastBootRequire.from_rubylibdir("English")
module Homebrew
# Bump this whenever a committed vendored gem is later added to or exclusion removed from gitignore.
# This will trigger it to reinstall properly if `brew install-bundler-gems` needs it.
VENDOR_VERSION = 7
private_constant :VENDOR_VERSION
RUBY_BUNDLE_VENDOR_DIRECTORY = (HOMEBREW_LIBRARY_PATH/"vendor/bundle/ruby").freeze
private_constant :RUBY_BUNDLE_VENDOR_DIRECTORY
# This is tracked across Ruby versions.
GEM_GROUPS_FILE = (RUBY_BUNDLE_VENDOR_DIRECTORY/".homebrew_gem_groups").freeze
private_constant :GEM_GROUPS_FILE
# This is tracked per Ruby version.
VENDOR_VERSION_FILE = (
RUBY_BUNDLE_VENDOR_DIRECTORY/"#{RbConfig::CONFIG["ruby_version"]}/.homebrew_vendor_version"
).freeze
private_constant :VENDOR_VERSION_FILE
def self.gemfile
File.join(ENV.fetch("HOMEBREW_LIBRARY"), "Homebrew", "Gemfile")
end
private_class_method :gemfile
def self.bundler_definition
@bundler_definition ||= Bundler::Definition.build(Bundler.default_gemfile, Bundler.default_lockfile, false)
end
private_class_method :bundler_definition
def self.valid_gem_groups
require "bundler"
Bundler.with_unbundled_env do
ENV["BUNDLE_GEMFILE"] = gemfile
groups = bundler_definition.groups
groups.delete(:default)
groups.map(&:to_s)
end
end
def self.ruby_bindir
"#{RbConfig::CONFIG["prefix"]}/bin"
end
def self.ohai_if_defined(message)
if defined?(ohai)
ohai message
else
$stderr.puts "==> #{message}"
end
end
def self.opoo_if_defined(message)
if defined?(opoo)
opoo message
else
$stderr.puts "Warning: #{message}"
end
end
def self.odie_if_defined(message)
if defined?(odie)
odie message
else
$stderr.puts "Error: #{message}"
exit 1
end
end
def self.setup_gem_environment!(setup_path: true)
require "rubygems"
raise "RubyGems too old!" if Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.2.0")
ENV["BUNDLER_NO_OLD_RUBYGEMS_WARNING"] = "1"
# Match where our bundler gems are.
gem_home = "#{RUBY_BUNDLE_VENDOR_DIRECTORY}/#{RbConfig::CONFIG["ruby_version"]}"
homebrew_cache = ENV.fetch("HOMEBREW_CACHE", nil)
gem_cache = "#{homebrew_cache}/gem-spec-cache" if homebrew_cache
Gem.paths = {
"GEM_HOME" => gem_home,
"GEM_PATH" => gem_home,
"GEM_SPEC_CACHE" => gem_cache,
}.compact
# Set TMPDIR so Xcode's `make` doesn't fall back to `/var/tmp/`,
# which may be not user-writable.
ENV["TMPDIR"] = ENV.fetch("HOMEBREW_TEMP", nil)
return unless setup_path
# Add necessary Ruby and Gem binary directories to `PATH`.
paths = ENV.fetch("PATH").split(":")
paths.unshift(ruby_bindir) unless paths.include?(ruby_bindir)
paths.unshift(Gem.bindir) unless paths.include?(Gem.bindir)
ENV["PATH"] = paths.compact.join(":")
# Set envs so the above binaries can be invoked.
# We don't do this unless requested as some formulae may invoke system Ruby instead of ours.
ENV["GEM_HOME"] = gem_home
ENV["GEM_PATH"] = gem_home
ENV["GEM_SPEC_CACHE"] = gem_cache if gem_cache
end
def self.install_gem!(name, version: nil, setup_gem_environment: true)
setup_gem_environment! if setup_gem_environment
specs = Gem::Specification.find_all_by_name(name, version)
if specs.empty?
ohai_if_defined "Installing '#{name}' gem"
# `document: []` is equivalent to --no-document
# `build_args: []` stops ARGV being used as a default
# `env_shebang: true` makes shebangs generic to allow switching between system and Portable Ruby
specs = Gem.install name, version, document: [], build_args: [], env_shebang: true
end
specs += specs.flat_map(&:runtime_dependencies)
.flat_map(&:to_specs)
# Add the specs to the $LOAD_PATH.
specs.each do |spec|
spec.require_paths.each do |path|
full_path = File.join(spec.full_gem_path, path)
$LOAD_PATH.unshift full_path unless $LOAD_PATH.include?(full_path)
end
end
rescue Gem::UnsatisfiableDependencyError
odie_if_defined "failed to install the '#{name}' gem."
end
def self.install_gem_setup_path!(name, version: nil, executable: name, setup_gem_environment: true)
install_gem!(name, version:, setup_gem_environment:)
return if find_in_path(executable)
odie_if_defined <<~EOS
the '#{name}' gem is installed but couldn't find '#{executable}' in the PATH:
#{ENV.fetch("PATH")}
EOS
end
def self.find_in_path(executable)
ENV.fetch("PATH").split(":").find do |path|
File.executable?(File.join(path, executable))
end
end
private_class_method :find_in_path
def self.user_gem_groups
@user_gem_groups ||= if GEM_GROUPS_FILE.exist?
GEM_GROUPS_FILE.readlines(chomp: true)
else
[]
end
end
private_class_method :user_gem_groups
def self.write_user_gem_groups(groups)
return if @user_gem_groups == groups && GEM_GROUPS_FILE.exist?
# Write the file atomically, in case we're working parallel
require "tempfile"
tmpfile = Tempfile.new([GEM_GROUPS_FILE.basename.to_s, "~"], GEM_GROUPS_FILE.dirname)
path = tmpfile.path
return if path.nil?
require "fileutils"
begin
FileUtils.chmod("+r", path)
tmpfile.write(groups.join("\n"))
tmpfile.close
File.rename(path, GEM_GROUPS_FILE)
ensure
tmpfile.unlink
end
@user_gem_groups = groups
end
private_class_method :write_user_gem_groups
def self.forget_user_gem_groups!
GEM_GROUPS_FILE.truncate(0) if GEM_GROUPS_FILE.exist?
@user_gem_groups = []
end
def self.user_vendor_version
@user_vendor_version ||= if VENDOR_VERSION_FILE.exist?
VENDOR_VERSION_FILE.read.to_i
else
0
end
end
private_class_method :user_vendor_version
def self.install_bundler_gems!(only_warn_on_failure: false, setup_path: true, groups: [])
old_path = ENV.fetch("PATH", nil)
old_gem_path = ENV.fetch("GEM_PATH", nil)
old_gem_home = ENV.fetch("GEM_HOME", nil)
old_gem_spec_cache = ENV.fetch("GEM_SPEC_CACHE", nil)
old_bundle_gemfile = ENV.fetch("BUNDLE_GEMFILE", nil)
old_bundle_with = ENV.fetch("BUNDLE_WITH", nil)
old_bundle_frozen = ENV.fetch("BUNDLE_FROZEN", nil)
invalid_groups = groups - valid_gem_groups
raise ArgumentError, "Invalid gem groups: #{invalid_groups.join(", ")}" unless invalid_groups.empty?
setup_gem_environment!
# Tests should not modify the state of the repository.
return if ENV["HOMEBREW_TESTS"]
# Combine the passed groups with the ones stored in settings.
groups |= (user_gem_groups & valid_gem_groups)
groups.sort!
if (homebrew_bundle_user_cache = ENV.fetch("HOMEBREW_BUNDLE_USER_CACHE", nil))
ENV["BUNDLE_USER_CACHE"] = homebrew_bundle_user_cache
end
ENV["BUNDLE_GEMFILE"] = gemfile
ENV["BUNDLE_WITH"] = groups.join(" ")
ENV["BUNDLE_FROZEN"] = "true"
if @bundle_installed_groups != groups
bundle = File.join(find_in_path("bundle"), "bundle")
bundle_check_output = `#{bundle} check 2>&1`
bundle_check_failed = !$CHILD_STATUS.success?
# for some reason sometimes the exit code lies so check the output too.
bundle_install_required = bundle_check_failed || bundle_check_output.include?("Install missing gems")
if user_vendor_version != VENDOR_VERSION
# Check if the install is intact. This is useful if any gems are added to gitignore.
# We intentionally map over everything and then call `any?` so that we remove the spec of each bad gem.
specs = bundler_definition.resolve.materialize(bundler_definition.locked_dependencies)
vendor_reinstall_required = specs.map do |spec|
spec_file = "#{Gem.dir}/specifications/#{spec.full_name}.gemspec"
next false unless File.exist?(spec_file)
cache_file = "#{Gem.dir}/cache/#{spec.full_name}.gem"
if File.exist?(cache_file)
require "rubygems/package"
package = Gem::Package.new(cache_file)
package_install_intact = begin
contents = package.contents
# If the gem has contents, ensure we have every file installed it contains.
contents&.all? do |gem_file|
File.exist?("#{Gem.dir}/gems/#{spec.full_name}/#{gem_file}")
end
rescue Gem::Package::Error, Gem::Security::Exception
# Malformed, assume broken
File.unlink(cache_file)
false
end
next false if package_install_intact
end
# Mark gem for reinstallation
File.unlink(spec_file)
true
end.any?
VENDOR_VERSION_FILE.dirname.mkpath
VENDOR_VERSION_FILE.write(VENDOR_VERSION.to_s)
bundle_install_required ||= vendor_reinstall_required
end
bundle_installed = if bundle_install_required
Process.wait(fork do
# Native build scripts fail if EUID != UID
Process::UID.change_privilege(Process.euid) if Process.euid != Process.uid
exec bundle, "install", out: :err
end)
if $CHILD_STATUS.success?
Homebrew::Bootsnap.reset! if defined?(Homebrew::Bootsnap) # Gem install can run before Bootsnap loads
true
else
message = <<~EOS
failed to run `#{bundle} install`!
EOS
if only_warn_on_failure
opoo_if_defined message
else
odie_if_defined message
end
false
end
elsif system bundle, "clean", out: :err # even if we have nothing to install, we may have removed gems
true
else
message = <<~EOS
failed to run `#{bundle} clean`!
EOS
if only_warn_on_failure
opoo_if_defined message
else
odie_if_defined message
end
false
end
if bundle_installed
write_user_gem_groups(groups)
@bundle_installed_groups = groups
end
end
setup_gem_environment!
ensure
unless setup_path
# Reset the paths. We need to have at least temporarily changed them while invoking `bundle`.
ENV["PATH"] = old_path
ENV["GEM_PATH"] = old_gem_path
ENV["GEM_HOME"] = old_gem_home
ENV["GEM_SPEC_CACHE"] = old_gem_spec_cache
ENV["BUNDLE_GEMFILE"] = old_bundle_gemfile
ENV["BUNDLE_WITH"] = old_bundle_with
ENV["BUNDLE_FROZEN"] = old_bundle_frozen
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/path.rb | Library/Homebrew/utils/path.rb | # typed: strict
# frozen_string_literal: true
module Utils
module Path
sig { params(parent: T.any(Pathname, String), child: T.any(Pathname, String)).returns(T::Boolean) }
def self.child_of?(parent, child)
parent_pathname = Pathname(parent).expand_path
child_pathname = Pathname(child).expand_path
child_pathname.ascend { |p| return true if p == parent_pathname }
false
end
sig { params(path: Pathname, package_type: Symbol).returns(T::Boolean) }
def self.loadable_package_path?(path, package_type)
return true unless Homebrew::EnvConfig.forbid_packages_from_paths?
path_realpath = path.realpath.to_s
path_string = path.to_s
allowed_paths = ["#{HOMEBREW_LIBRARY}/Taps/"]
allowed_paths << if package_type == :formula
"#{HOMEBREW_CELLAR}/"
else
"#{Cask::Caskroom.path}/"
end
return true if !path_realpath.end_with?(".rb") && !path_string.end_with?(".rb")
return true if allowed_paths.any? { |path| path_realpath.start_with?(path) }
return true if allowed_paths.any? { |path| path_string.start_with?(path) }
# Looks like a local path, Ruby file and not a tap.
if path_string.include?("./") || path_string.end_with?(".rb") || path_string.count("/") != 2
package_type_plural = Utils.pluralize(package_type.to_s, 2)
path_realpath_if_different = " (#{path_realpath})" if path_realpath != path_string
create_flag = " --cask" if package_type == :cask
raise <<~WARNING
Homebrew requires #{package_type_plural} to be in a tap, rejecting:
#{path_string}#{path_realpath_if_different}
To create a tap, run e.g.
brew tap-new <user|org>/<repository>
To create a #{package_type} in a tap run e.g.
brew create#{create_flag} <url> --tap=<user|org>/<repository>
WARNING
else
# Looks like a tap, let's quietly reject but not error.
path_string.count("/") != 2
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/curl.rb | Library/Homebrew/utils/curl.rb | # typed: strict
# frozen_string_literal: true
require "open3"
require "utils/timer"
require "system_command"
module Utils
# Helper function for interacting with `curl`.
module Curl
include SystemCommand::Mixin
extend SystemCommand::Mixin
extend T::Helpers
requires_ancestor { Kernel }
# Error returned when the server sent data curl could not parse.
CURL_WEIRD_SERVER_REPLY_EXIT_CODE = 8
# Error returned when `--fail` is used and the HTTP server returns an error
# code that is >= 400.
CURL_HTTP_RETURNED_ERROR_EXIT_CODE = 22
# Error returned when curl gets an error from the lowest networking layers
# that the receiving of data failed.
CURL_RECV_ERROR_EXIT_CODE = 56
# This regex is used to extract the part of an ETag within quotation marks,
# ignoring any leading weak validator indicator (`W/`). This simplifies
# ETag comparison in `#curl_check_http_content`.
ETAG_VALUE_REGEX = %r{^(?:[wW]/)?"((?:[^"]|\\")*)"}
# HTTP responses and body content are typically separated by a double
# `CRLF` (whereas HTTP header lines are separated by a single `CRLF`).
# In rare cases, this can also be a double newline (`\n\n`).
HTTP_RESPONSE_BODY_SEPARATOR = "\r\n\r\n"
# This regex is used to isolate the parts of an HTTP status line, namely
# the status code and any following descriptive text (e.g. `Not Found`).
HTTP_STATUS_LINE_REGEX = %r{^HTTP/.* (?<code>\d+)(?: (?<text>[^\r\n]+))?}
private_constant :CURL_WEIRD_SERVER_REPLY_EXIT_CODE,
:CURL_HTTP_RETURNED_ERROR_EXIT_CODE,
:CURL_RECV_ERROR_EXIT_CODE,
:ETAG_VALUE_REGEX, :HTTP_RESPONSE_BODY_SEPARATOR,
:HTTP_STATUS_LINE_REGEX
module_function
sig { params(use_homebrew_curl: T::Boolean).returns(T.any(Pathname, String)) }
def curl_executable(use_homebrew_curl: false)
return HOMEBREW_BREWED_CURL_PATH if use_homebrew_curl
@curl_executable ||= T.let(HOMEBREW_SHIMS_PATH/"shared/curl", T.nilable(T.any(Pathname, String)))
end
sig { returns(String) }
def curl_path
@curl_path ||= T.let(
Utils.popen_read(curl_executable, "--homebrew=print-path").chomp.presence,
T.nilable(String),
)
end
sig { void }
def clear_path_cache
@curl_path = nil
end
sig {
params(
extra_args: String,
connect_timeout: T.nilable(T.any(Integer, Float)),
max_time: T.nilable(T.any(Integer, Float)),
retries: T.nilable(Integer),
retry_max_time: T.nilable(T.any(Integer, Float)),
show_output: T.nilable(T::Boolean),
show_error: T.nilable(T::Boolean),
cookies: T.nilable(T::Hash[String, String]),
header: T.nilable(T.any(String, T::Array[String])),
referer: T.nilable(String),
user_agent: T.nilable(T.any(String, Symbol)),
).returns(T::Array[String])
}
def curl_args(
*extra_args,
connect_timeout: nil,
max_time: nil,
retries: Homebrew::EnvConfig.curl_retries.to_i,
retry_max_time: nil,
show_output: false,
show_error: true,
cookies: nil,
header: nil,
referer: nil,
user_agent: nil
)
args = []
# do not load .curlrc unless requested (must be the first argument)
curlrc = Homebrew::EnvConfig.curlrc
if curlrc&.start_with?("/")
# If the file exists, we still want to disable loading the default curlrc.
args << "--disable" << "--config" << curlrc
elsif curlrc
# This matches legacy behavior: `HOMEBREW_CURLRC` was a bool,
# omitting `--disable` when present.
else
args << "--disable"
end
args << "--cookie" << if cookies
cookies.map { |k, v| "#{k}=#{v}" }.join(";")
else
# Echo any cookies received on a redirect
File::NULL
end
args << "--globoff"
args << "--show-error" if show_error
if user_agent != :curl
args << "--user-agent" << case user_agent
when :browser, :fake
HOMEBREW_USER_AGENT_FAKE_SAFARI
when :default, nil
HOMEBREW_USER_AGENT_CURL
when String
user_agent
else
raise TypeError, ":user_agent must be :browser/:fake, :default, :curl, or a String"
end
end
args << "--header" << "Accept-Language: en"
case header
when String
args << "--header" << header
when Array
header.each { |h| args << "--header" << h.strip }
end
if show_output != true
args << "--fail"
args << "--progress-bar" unless Context.current.verbose?
args << "--verbose" if Homebrew::EnvConfig.curl_verbose?
args << "--silent" if !$stdout.tty? || Context.current.quiet?
end
args << "--connect-timeout" << connect_timeout.round(3) if connect_timeout.present?
args << "--max-time" << max_time.round(3) if max_time.present?
# A non-positive integer (e.g. 0) or `nil` will omit this argument
args << "--retry" << retries if retries&.positive?
args << "--retry-max-time" << retry_max_time.round if retry_max_time.present?
args << "--referer" << referer if referer.present?
(args + extra_args).map(&:to_s)
end
sig {
params(
args: String,
secrets: T.any(String, T::Array[String]),
print_stdout: T.any(T::Boolean, Symbol),
print_stderr: T.any(T::Boolean, Symbol),
debug: T.nilable(T::Boolean),
verbose: T.nilable(T::Boolean),
env: T::Hash[String, String],
timeout: T.nilable(T.any(Integer, Float)),
use_homebrew_curl: T::Boolean,
options: T.untyped,
).returns(SystemCommand::Result)
}
def curl_with_workarounds(
*args,
secrets: [], print_stdout: false, print_stderr: false, debug: nil,
verbose: nil, env: {}, timeout: nil, use_homebrew_curl: false, **options
)
end_time = Time.now + timeout if timeout
command_options = {
secrets:,
print_stdout:,
print_stderr:,
debug:,
verbose:,
}.compact
result = system_command curl_executable(use_homebrew_curl:),
args: curl_args(*args, **options),
env:,
timeout: Utils::Timer.remaining(end_time),
**command_options
return result if result.success? || args.include?("--http1.1")
raise Timeout::Error, result.stderr.lines.fetch(-1).chomp if timeout && result.status.exitstatus == 28
# Error in the HTTP2 framing layer
if result.exit_status == 16
return curl_with_workarounds(
*args, "--http1.1",
timeout: Utils::Timer.remaining(end_time), **command_options, **options
)
end
# This is a workaround for https://github.com/curl/curl/issues/1618.
if result.exit_status == 56 # Unexpected EOF
out = curl_output("-V").stdout
# If `curl` doesn't support HTTP2, the exception is unrelated to this bug.
return result unless out.include?("HTTP2")
# The bug is fixed in `curl` >= 7.60.0.
curl_version = out[/curl (\d+(\.\d+)+)/, 1]
return result if Gem::Version.new(curl_version) >= Gem::Version.new("7.60.0")
return curl_with_workarounds(*args, "--http1.1", **command_options, **options)
end
result
end
sig {
overridable.params(
args: String,
print_stdout: T.any(T::Boolean, Symbol),
options: T.untyped,
).returns(SystemCommand::Result)
}
def curl(*args, print_stdout: true, **options)
result = curl_with_workarounds(*args, print_stdout:, **options)
result.assert_success!
result
end
sig {
params(
args: String,
to: T.any(Pathname, String),
try_partial: T::Boolean,
options: T.untyped,
).returns(T.nilable(SystemCommand::Result))
}
def curl_download(*args, to:, try_partial: false, **options)
destination = Pathname(to)
destination.dirname.mkpath
args = ["--location", *args]
if try_partial && destination.exist?
headers = begin
parsed_output = curl_headers(*args, **options, wanted_headers: ["accept-ranges"])
parsed_output.fetch(:responses).last&.fetch(:headers) || {}
rescue ErrorDuringExecution
# Ignore errors here and let actual download fail instead.
{}
end
# Any value for `Accept-Ranges` other than `none` indicates that the server
# supports partial requests. Its absence indicates no support.
supports_partial = headers.fetch("accept-ranges", "none") != "none"
content_length = headers["content-length"]&.to_i
if supports_partial
# We've already downloaded all bytes.
return if destination.size == content_length
args = ["--continue-at", "-", *args]
end
end
args = ["--remote-time", "--output", destination.to_s, *args]
curl(*args, **options)
end
sig { overridable.params(args: String, options: T.untyped).returns(SystemCommand::Result) }
def curl_output(*args, **options)
curl_with_workarounds(*args, print_stderr: false, show_output: true, **options)
end
sig {
params(
args: String,
wanted_headers: T::Array[String],
options: T.untyped,
).returns(T::Hash[Symbol, T.untyped])
}
def curl_headers(*args, wanted_headers: [], **options)
base_args = ["--fail", "--location", "--silent"]
get_retry_args = []
if (is_post_request = args.include?("POST"))
base_args << "--dump-header" << "-"
else
base_args << "--head"
get_retry_args << "--request" << "GET"
end
# This is a workaround for https://github.com/Homebrew/brew/issues/18213
get_retry_args << "--http1.1" if curl_version >= Version.new("8.7") && curl_version < Version.new("8.10")
[[], get_retry_args].each do |request_args|
result = curl_output(*base_args, *request_args, *args, **options)
# We still receive usable headers with certain non-successful exit
# statuses, so we special case them below.
if result.success? || [
CURL_WEIRD_SERVER_REPLY_EXIT_CODE,
CURL_HTTP_RETURNED_ERROR_EXIT_CODE,
CURL_RECV_ERROR_EXIT_CODE,
].include?(result.exit_status)
parsed_output = parse_curl_output(result.stdout)
return parsed_output if is_post_request
if request_args.empty?
# If we didn't get any wanted header yet, retry using `GET`.
next if wanted_headers.any? &&
parsed_output.fetch(:responses).none? { |r| r.fetch(:headers).keys.intersect?(wanted_headers) }
# Some CDNs respond with 400 codes for `HEAD` but resolve with `GET`.
next if (400..499).cover?(parsed_output.fetch(:responses).last&.fetch(:status_code).to_i)
end
return parsed_output if result.success? ||
result.exit_status == CURL_WEIRD_SERVER_REPLY_EXIT_CODE
end
result.assert_success!
end
{}
end
# Check if a URL is protected by CloudFlare (e.g. badlion.net and jaxx.io).
# @param response [Hash] A response hash from `#parse_curl_response`.
# @return [true, false] Whether a response contains headers indicating that
# the URL is protected by Cloudflare.
sig { params(response: T::Hash[Symbol, T.untyped]).returns(T::Boolean) }
def url_protected_by_cloudflare?(response)
return false if response[:headers].blank?
return false unless [403, 503].include?(response[:status_code].to_i)
[*response[:headers]["server"]].any? { |server| server.match?(/^cloudflare/i) }
end
# Check if a URL is protected by Incapsula (e.g. corsair.com).
# @param response [Hash] A response hash from `#parse_curl_response`.
# @return [true, false] Whether a response contains headers indicating that
# the URL is protected by Incapsula.
sig { params(response: T::Hash[Symbol, T.untyped]).returns(T::Boolean) }
def url_protected_by_incapsula?(response)
return false if response[:headers].blank?
return false if response[:status_code].to_i != 403
set_cookie_header = Array(response[:headers]["set-cookie"])
set_cookie_header.compact.any? { |cookie| cookie.match?(/^(visid_incap|incap_ses)_/i) }
end
sig {
params(
url: String,
url_type: String,
specs: T::Hash[Symbol, String],
user_agents: T::Array[T.any(String, Symbol)],
referer: T.nilable(String),
check_content: T::Boolean,
strict: T::Boolean,
use_homebrew_curl: T::Boolean,
).returns(T.nilable(String))
}
def curl_check_http_content(url, url_type, specs: {}, user_agents: [:default], referer: nil,
check_content: false, strict: false, use_homebrew_curl: false)
return unless url.start_with? "http"
secure_url = url.sub(/\Ahttp:/, "https:")
secure_details = T.let(nil, T.nilable(T::Hash[Symbol, T.untyped]))
hash_needed = T.let(false, T::Boolean)
if url != secure_url
user_agents.each do |user_agent|
secure_details = begin
curl_http_content_headers_and_checksum(
secure_url,
specs:,
hash_needed: true,
use_homebrew_curl:,
user_agent:,
referer:,
)
rescue Timeout::Error
next
end
next unless http_status_ok?(secure_details[:status_code])
hash_needed = true
user_agents = [user_agent]
break
end
end
details = T.let({}, T::Hash[Symbol, T.untyped])
attempts = 0
user_agents.each do |user_agent|
loop do
details = curl_http_content_headers_and_checksum(
url,
specs:,
hash_needed:,
use_homebrew_curl:,
user_agent:,
referer:,
)
# Retry on network issues
break if details[:exit_status] != 52 && details[:exit_status] != 56
attempts += 1
break if attempts >= Homebrew::EnvConfig.curl_retries.to_i
end
break if http_status_ok?(details[:status_code])
end
return "The #{url_type} #{url} is not reachable" unless details[:status_code]
unless http_status_ok?(details[:status_code])
return if details[:responses].any? do |response|
url_protected_by_cloudflare?(response) || url_protected_by_incapsula?(response)
end
# https://github.com/Homebrew/brew/issues/13789
# If the `:homepage` of a formula is private, it will fail an `audit`
# since there's no way to specify a `strategy` with `using:` and
# GitHub does not authorize access to the web UI using token
#
# Strategy:
# If the `:homepage` 404s, it's a GitHub link and we have a token then
# check the API (which does use tokens) for the repository
repo_details = url.match(%r{https?://github\.com/(?<user>[^/]+)/(?<repo>[^/]+)/?.*})
check_github_api = url_type == SharedAudits::URL_TYPE_HOMEPAGE &&
details[:status_code] == "404" &&
repo_details &&
Homebrew::EnvConfig.github_api_token.present?
unless check_github_api
return "The #{url_type} #{url} is not reachable (HTTP status code #{details[:status_code]})"
end
if SharedAudits.github_repo_data(T.must(repo_details[:user]), T.must(repo_details[:repo])).nil?
"Unable to find homepage"
end
end
if url.start_with?("https://") && Homebrew::EnvConfig.no_insecure_redirect? &&
details[:final_url].present? && !details[:final_url].start_with?("https://")
return "The #{url_type} #{url} redirects back to HTTP"
end
return unless secure_details
return if !http_status_ok?(details[:status_code]) || !http_status_ok?(secure_details[:status_code])
etag_match = details[:etag] &&
details[:etag] == secure_details[:etag]
content_length_match =
details[:content_length] &&
details[:content_length] == secure_details[:content_length]
file_match = details[:file_hash] == secure_details[:file_hash]
http_with_https_available =
url.start_with?("http://") &&
secure_details[:final_url].present? && secure_details[:final_url].start_with?("https://")
if (etag_match || content_length_match || file_match) && http_with_https_available
return "The #{url_type} #{url} should use HTTPS rather than HTTP"
end
return unless check_content
no_protocol_file_contents = %r{https?:\\?/\\?/}
http_content = details[:file]&.scrub&.gsub(no_protocol_file_contents, "/")
https_content = secure_details[:file]&.scrub&.gsub(no_protocol_file_contents, "/")
# Check for the same content after removing all protocols
if http_content && https_content && (http_content == https_content) && http_with_https_available
return "The #{url_type} #{url} should use HTTPS rather than HTTP"
end
return unless strict
# Same size, different content after normalization
# (typical causes: Generated ID, Timestamp, Unix time)
if http_content.length == https_content.length
return "The #{url_type} #{url} may be able to use HTTPS rather than HTTP. Please verify it in a browser."
end
lenratio = (https_content.length * 100 / http_content.length).to_i
return unless (90..110).cover?(lenratio)
"The #{url_type} #{url} may be able to use HTTPS rather than HTTP. Please verify it in a browser."
end
sig {
params(
url: String,
specs: T::Hash[Symbol, String],
hash_needed: T::Boolean,
use_homebrew_curl: T::Boolean,
user_agent: T.any(String, Symbol),
referer: T.nilable(String),
).returns(T::Hash[Symbol, T.untyped])
}
def curl_http_content_headers_and_checksum(
url, specs: {}, hash_needed: false,
use_homebrew_curl: false, user_agent: :default, referer: nil
)
file = Tempfile.new.tap(&:close)
# Convert specs to options. This is mostly key-value options,
# unless the value is a boolean in which case treat as as flag.
specs = specs.flat_map do |option, argument|
next [] if argument == false # No flag.
args = ["--#{option.to_s.tr("_", "-")}"]
args << argument if argument != true # It's a flag.
args
end
max_time = hash_needed ? 600 : 25
output, _, status = curl_output(
*specs, "--dump-header", "-", "--output", file.path, "--location", url,
use_homebrew_curl:,
connect_timeout: 15,
max_time:,
retry_max_time: max_time,
user_agent:,
referer:
)
parsed_output = parse_curl_output(output)
responses = parsed_output[:responses]
final_url = curl_response_last_location(responses)
headers = if responses.last.present?
status_code = responses.last[:status_code]
responses.last[:headers]
else
{}
end
etag = headers["etag"][ETAG_VALUE_REGEX, 1] if headers["etag"].present?
content_length = headers["content-length"]
if status.success?
open_args = {}
content_type = headers["content-type"]
# Use the last `Content-Type` header if there is more than one instance
# in the response
content_type = content_type.last if content_type.is_a?(Array)
# Try to get encoding from Content-Type header
# TODO: add guessing encoding by <meta http-equiv="Content-Type" ...> tag
if content_type &&
(match = content_type.match(/;\s*charset\s*=\s*([^\s]+)/)) &&
(charset = match[1])
begin
open_args[:encoding] = Encoding.find(charset)
rescue ArgumentError
# Unknown charset in Content-Type header
end
end
file_contents = File.read(T.must(file.path), **open_args)
file_hash = Digest::SHA256.hexdigest(file_contents) if hash_needed
end
{
url:,
final_url:,
exit_status: status.exitstatus,
status_code:,
headers:,
etag:,
content_length:,
file: file_contents,
file_hash:,
responses:,
}
ensure
T.must(file).unlink
end
sig { returns(Version) }
def curl_version
@curl_version ||= T.let({}, T.nilable(T::Hash[String, Version]))
@curl_version[curl_path] ||= Version.new(T.must(curl_output("-V").stdout[/curl (\d+(\.\d+)+)/, 1]))
end
sig { returns(T::Boolean) }
def curl_supports_fail_with_body?
@curl_supports_fail_with_body ||= T.let(Hash.new do |h, key|
h[key] = curl_version >= Version.new("7.76.0")
end, T.nilable(T::Hash[T.any(Pathname, String), T::Boolean]))
@curl_supports_fail_with_body[curl_path]
end
sig { returns(T::Boolean) }
def curl_supports_tls13?
@curl_supports_tls13 ||= T.let(Hash.new do |h, key|
h[key] = quiet_system(curl_executable, "--tlsv1.3", "--head", "https://brew.sh/")
end, T.nilable(T::Hash[T.any(Pathname, String), T::Boolean]))
@curl_supports_tls13[curl_path]
end
sig { params(status: T.nilable(String)).returns(T::Boolean) }
def http_status_ok?(status)
return false if status.nil?
(100..299).cover?(status.to_i)
end
# Separates the output text from `curl` into an array of HTTP responses and
# the final response body (i.e. content). Response hashes contain the
# `:status_code`, `:status_text` and `:headers`.
# @param output [String] The output text from `curl` containing HTTP
# responses, body content, or both.
# @param max_iterations [Integer] The maximum number of iterations for the
# `while` loop that parses HTTP response text. This should correspond to
# the maximum number of requests in the output. If `curl`'s `--max-redirs`
# option is used, `max_iterations` should be `max-redirs + 1`, to
# account for any final response after the redirections.
# @return [Hash] A hash containing an array of response hashes and the body
# content, if found.
sig { params(output: String, max_iterations: Integer).returns(T::Hash[Symbol, T.untyped]) }
def parse_curl_output(output, max_iterations: 25)
responses = []
iterations = 0
output = output.lstrip
while output.match?(%r{\AHTTP/[\d.]+ \d+}) && output.include?(HTTP_RESPONSE_BODY_SEPARATOR)
iterations += 1
raise "Too many redirects (max = #{max_iterations})" if iterations > max_iterations
response_text, _, output = output.partition(HTTP_RESPONSE_BODY_SEPARATOR)
output = output.lstrip
next if response_text.blank?
response_text.chomp!
response = parse_curl_response(response_text)
responses << response if response.present?
end
{ responses:, body: output }
end
# Returns the URL from the last location header found in cURL responses,
# if any.
# @param responses [Array<Hash>] An array of hashes containing response
# status information and headers from `#parse_curl_response`.
# @param absolutize [true, false] Whether to make the location URL absolute.
# @param base_url [String, nil] The URL to use as a base for making the
# `location` URL absolute.
# @return [String, nil] The URL from the last-occurring `location` header
# in the responses or `nil` (if no `location` headers found).
sig {
params(
responses: T::Array[T::Hash[Symbol, T.untyped]],
absolutize: T::Boolean,
base_url: T.nilable(String),
).returns(T.nilable(String))
}
def curl_response_last_location(responses, absolutize: false, base_url: nil)
responses.reverse_each do |response|
next if response[:headers].blank?
location = response[:headers]["location"]
next if location.blank?
absolute_url = URI.join(base_url, location).to_s if absolutize && base_url.present?
return absolute_url || location
end
nil
end
# Returns the final URL by following location headers in cURL responses.
# @param responses [Array<Hash>] An array of hashes containing response
# status information and headers from `#parse_curl_response`.
# @param base_url [String] The URL to use as a base.
# @return [String] The final absolute URL after redirections.
sig {
params(
responses: T::Array[T::Hash[Symbol, T.untyped]],
base_url: String,
).returns(String)
}
def curl_response_follow_redirections(responses, base_url)
responses.each do |response|
next if response[:headers].blank?
location = response[:headers]["location"]
next if location.blank?
base_url = URI.join(base_url, location).to_s
end
base_url
end
private
# Parses HTTP response text from `curl` output into a hash containing the
# information from the status line (status code and, optionally,
# descriptive text) and headers.
# @param response_text [String] The text of a `curl` response, consisting
# of a status line followed by header lines.
# @return [Hash] A hash containing the response status information and
# headers (as a hash with header names as keys).
sig { params(response_text: String).returns(T::Hash[Symbol, T.untyped]) }
def parse_curl_response(response_text)
response = {}
return response unless (match = response_text.match(HTTP_STATUS_LINE_REGEX))
# Parse the status line and remove it
response[:status_code] = match["code"]
response[:status_text] = match["text"] if match["text"].present?
response_text = response_text.sub(%r{^HTTP/.* (\d+).*$\s*}, "")
# Create a hash from the header lines
response[:headers] = {}
response_text.split("\r\n").each do |line|
header_name, header_value = line.split(/:\s*/, 2)
next if header_name.blank? || header_value.nil?
header_name = header_name.strip.downcase
header_value.strip!
case response[:headers][header_name]
when String
response[:headers][header_name] = [response[:headers][header_name], header_value]
when Array
response[:headers][header_name].push(header_value)
else
response[:headers][header_name] = header_value
end
response[:headers][header_name]
end
response
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/bottles.rb | Library/Homebrew/utils/bottles.rb | # typed: strict
# frozen_string_literal: true
require "tab"
module Utils
# Helper functions for bottles.
#
# @api internal
module Bottles
class << self
# Gets the tag for the running OS.
#
# @api internal
sig { params(tag: T.nilable(T.any(Symbol, Tag))).returns(Tag) }
def tag(tag = nil)
case tag
when Symbol
Tag.from_symbol(tag)
when Tag
tag
else
@tag ||= T.let(Tag.new(
system: HOMEBREW_SYSTEM.downcase.to_sym,
arch: HOMEBREW_PROCESSOR.downcase.to_sym,
), T.nilable(Tag))
end
end
sig { params(formula: Formula).returns(T::Boolean) }
def built_as?(formula)
return false unless formula.latest_version_installed?
tab = Keg.new(formula.latest_installed_prefix).tab
tab.built_as_bottle
end
sig { params(formula: Formula, file: Pathname).returns(T::Boolean) }
def file_outdated?(formula, file)
file = file.resolved_path
filename = file.basename.to_s
bottle = formula.bottle
return false unless bottle
_, bottle_tag, bottle_rebuild = extname_tag_rebuild(filename)
return false if bottle_tag.blank?
bottle_tag != bottle.tag.to_s || bottle_rebuild.to_i != bottle.rebuild
end
sig { params(filename: String).returns(T::Array[String]) }
def extname_tag_rebuild(filename)
HOMEBREW_BOTTLES_EXTNAME_REGEX.match(filename).to_a
end
sig { params(bottle_file: Pathname).returns(T.nilable(String)) }
def receipt_path(bottle_file)
bottle_file_list(bottle_file).find do |line|
%r{.+/.+/INSTALL_RECEIPT.json}.match?(line)
end
end
sig { params(bottle_file: Pathname, file_path: String).returns(String) }
def file_from_bottle(bottle_file, file_path)
Utils.popen_read("tar", "--extract", "--to-stdout", "--file", bottle_file, file_path)
end
sig { params(bottle_file: Pathname).returns([String, String]) }
def resolve_formula_names(bottle_file)
name = bottle_file_list(bottle_file).first.to_s.split("/").fetch(0)
full_name = if (receipt_file_path = receipt_path(bottle_file))
receipt_file = file_from_bottle(bottle_file, receipt_file_path)
tap = Tab.from_file_content(receipt_file, "#{bottle_file}/#{receipt_file_path}").tap
"#{tap}/#{name}" if tap.present? && !tap.core_tap?
else
bottle_json_path = Pathname(bottle_file.sub(/\.(\d+\.)?tar\.gz$/, ".json"))
if bottle_json_path.exist? &&
(bottle_json_path_contents = bottle_json_path.read.presence) &&
(bottle_json = JSON.parse(bottle_json_path_contents).presence) &&
bottle_json.is_a?(Hash)
bottle_json.keys.first.presence
end
end
full_name ||= name
[name, full_name]
end
sig { params(bottle_file: Pathname).returns(PkgVersion) }
def resolve_version(bottle_file)
version = bottle_file_list(bottle_file).first.to_s.split("/").fetch(1)
PkgVersion.parse(version)
end
sig { params(bottle_file: Pathname, name: String).returns(String) }
def formula_contents(bottle_file, name: resolve_formula_names(bottle_file)[0])
bottle_version = resolve_version bottle_file
formula_path = "#{name}/#{bottle_version}/.brew/#{name}.rb"
contents = file_from_bottle(bottle_file, formula_path)
raise BottleFormulaUnavailableError.new(bottle_file, formula_path) unless $CHILD_STATUS.success?
contents
end
sig {
params(root_url: String, name: String, checksum: T.any(Checksum, String),
filename: T.nilable(Bottle::Filename)).returns(T.any([String, T.nilable(String)], String))
}
def path_resolved_basename(root_url, name, checksum, filename)
if root_url.match?(GitHubPackages::URL_REGEX)
image_name = GitHubPackages.image_formula_name(name)
["#{image_name}/blobs/sha256:#{checksum}", filename&.github_packages]
else
filename&.url_encode
end
end
sig { params(formula: Formula).returns(Tab) }
def load_tab(formula)
keg = Keg.new(formula.prefix)
tabfile = keg/AbstractTab::FILENAME
bottle_json_path = formula.local_bottle_path&.sub(/\.(\d+\.)?tar\.gz$/, ".json")
if (tab_attributes = formula.bottle_tab_attributes.presence)
tab = Tab.from_file_content(tab_attributes.to_json, tabfile)
return tab if tab.built_on["os"] == HOMEBREW_SYSTEM
elsif !tabfile.exist? && bottle_json_path&.exist?
_, tag, = Utils::Bottles.extname_tag_rebuild(formula.local_bottle_path.to_s)
bottle_hash = JSON.parse(File.read(bottle_json_path))
tab_json = bottle_hash[formula.full_name]["bottle"]["tags"][tag]["tab"].to_json
return Tab.from_file_content(tab_json, tabfile)
else
tab = keg.tab
end
tab.runtime_dependencies = begin
f_runtime_deps = formula.runtime_dependencies(read_from_tab: false)
Tab.runtime_deps_hash(formula, f_runtime_deps)
end
tab
end
private
sig { params(bottle_file: Pathname).returns(T::Array[String]) }
def bottle_file_list(bottle_file)
@bottle_file_list ||= T.let({}, T.nilable(T::Hash[Pathname, T::Array[String]]))
@bottle_file_list[bottle_file] ||= Utils.popen_read("tar", "--list", "--file", bottle_file)
.lines
.map(&:chomp)
end
end
# Denotes the arch and OS of a bottle.
class Tag
sig { returns(Symbol) }
attr_reader :system, :arch
sig { params(value: Symbol).returns(T.attached_class) }
def self.from_symbol(value)
return new(system: :all, arch: :all) if value == :all
@all_archs_regex ||= T.let(begin
all_archs = Hardware::CPU::ALL_ARCHS.map(&:to_s)
/
^((?<arch>#{Regexp.union(all_archs)})_)?
(?<system>[\w.]+)$
/x
end, T.nilable(Regexp))
match = @all_archs_regex.match(value.to_s)
raise ArgumentError, "Invalid bottle tag symbol" unless match
system = T.must(match[:system]).to_sym
arch = match[:arch]&.to_sym || :x86_64
new(system:, arch:)
end
sig { params(system: Symbol, arch: Symbol).void }
def initialize(system:, arch:)
@system = system
@arch = arch
end
sig { override.params(other: BasicObject).returns(T::Boolean) }
def ==(other)
case other
when Symbol
to_sym == other
when self.class
system == other.system && standardized_arch == other.standardized_arch
else false
end
end
sig { override.params(other: BasicObject).returns(T::Boolean) }
def eql?(other)
case other
when self.class
self == other
else false
end
end
sig { override.returns(Integer) }
def hash
[system, standardized_arch].hash
end
sig { returns(Symbol) }
def standardized_arch
return :x86_64 if [:x86_64, :intel].include? arch
return :arm64 if [:arm64, :arm, :aarch64].include? arch
arch
end
sig { returns(Symbol) }
def to_sym
arch_to_symbol(standardized_arch)
end
sig { override.returns(String) }
def to_s
to_sym.to_s
end
sig { returns(Symbol) }
def to_unstandardized_sym
# Never allow these generic names
return to_sym if [:intel, :arm].include? arch
# Backwards compatibility with older bottle names
arch_to_symbol(arch)
end
sig { returns(MacOSVersion) }
def to_macos_version
@to_macos_version ||= T.let(MacOSVersion.from_symbol(system), T.nilable(MacOSVersion))
end
sig { returns(T::Boolean) }
def linux?
system == :linux
end
sig { returns(T::Boolean) }
def macos?
MacOSVersion::SYMBOLS.key?(system)
end
sig { returns(T::Boolean) }
def valid_combination?
return true unless [:arm64, :arm, :aarch64].include? arch
return true unless macos?
# Big Sur is the first version of macOS that runs on ARM
to_macos_version >= :big_sur
end
sig { returns(String) }
def default_prefix
if linux?
HOMEBREW_LINUX_DEFAULT_PREFIX
elsif standardized_arch == :arm64
HOMEBREW_MACOS_ARM_DEFAULT_PREFIX
else
HOMEBREW_DEFAULT_PREFIX
end
end
sig { returns(String) }
def default_cellar
if linux?
Homebrew::DEFAULT_LINUX_CELLAR
elsif standardized_arch == :arm64
Homebrew::DEFAULT_MACOS_ARM_CELLAR
else
Homebrew::DEFAULT_MACOS_CELLAR
end
end
private
sig { params(arch: Symbol).returns(Symbol) }
def arch_to_symbol(arch)
if system == :all && arch == :all
:all
elsif macos? && standardized_arch == :x86_64
system
else
:"#{arch}_#{system}"
end
end
end
# The specification for a specific tag
class TagSpecification
sig { returns(Utils::Bottles::Tag) }
attr_reader :tag
sig { returns(Checksum) }
attr_reader :checksum
sig { returns(T.any(Symbol, String)) }
attr_reader :cellar
sig { params(tag: Utils::Bottles::Tag, checksum: Checksum, cellar: T.any(Symbol, String)).void }
def initialize(tag:, checksum:, cellar:)
@tag = tag
@checksum = checksum
@cellar = cellar
end
sig { override.params(other: BasicObject).returns(T::Boolean) }
def ==(other)
case other
when self.class
tag == other.tag && checksum == other.checksum && cellar == other.cellar
else false
end
end
alias eql? ==
end
# Collector for bottle specifications.
class Collector
sig { void }
def initialize
@tag_specs = T.let({}, T::Hash[Utils::Bottles::Tag, Utils::Bottles::TagSpecification])
end
sig { returns(T::Array[Utils::Bottles::Tag]) }
def tags
@tag_specs.keys
end
sig { override.params(other: BasicObject).returns(T::Boolean) }
def ==(other)
case other
when self.class
@tag_specs == other.tag_specs
else false
end
end
alias eql? ==
sig { params(tag: Utils::Bottles::Tag, checksum: Checksum, cellar: T.any(Symbol, String)).void }
def add(tag, checksum:, cellar:)
spec = Utils::Bottles::TagSpecification.new(tag:, checksum:, cellar:)
@tag_specs[tag] = spec
end
sig { params(tag: Utils::Bottles::Tag, no_older_versions: T::Boolean).returns(T::Boolean) }
def tag?(tag, no_older_versions: false)
tag = find_matching_tag(tag, no_older_versions:)
tag.present?
end
sig { params(block: T.proc.params(tag: Utils::Bottles::Tag).void).void }
def each_tag(&block)
@tag_specs.each_key(&block)
end
sig {
params(tag: Utils::Bottles::Tag, no_older_versions: T::Boolean)
.returns(T.nilable(Utils::Bottles::TagSpecification))
}
def specification_for(tag, no_older_versions: false)
tag = find_matching_tag(tag, no_older_versions:)
@tag_specs[tag] if tag
end
protected
sig { returns(T::Hash[Utils::Bottles::Tag, Utils::Bottles::TagSpecification]) }
attr_reader :tag_specs
private
sig { params(tag: Utils::Bottles::Tag, no_older_versions: T::Boolean).returns(T.nilable(Utils::Bottles::Tag)) }
def find_matching_tag(tag, no_older_versions: false)
if @tag_specs.key?(tag)
tag
else
all = Tag.from_symbol(:all)
all if @tag_specs.key?(all)
end
end
end
end
end
require "extend/os/bottles"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/attestation.rb | Library/Homebrew/utils/attestation.rb | # typed: strict
# frozen_string_literal: true
require "attestation"
require "bottle"
require "utils/output"
module Utils
module Attestation
extend Utils::Output::Mixin
sig { params(bottle: Bottle, quiet: T::Boolean).void }
def self.check_attestation(bottle, quiet: false)
ohai "Verifying attestation for #{bottle.name}" unless quiet
begin
Homebrew::Attestation.check_core_attestation bottle
rescue Homebrew::Attestation::GhIncompatible
# A small but significant number of users have developer mode enabled
# but *also* haven't upgraded in a long time, meaning that their `gh`
# version is too old to perform attestations.
raise CannotInstallFormulaError, <<~EOS
The bottle for #{bottle.name} could not be verified.
This typically indicates an outdated or incompatible `gh` CLI.
Please confirm that you're running the latest version of `gh`
by performing an upgrade before retrying:
brew update
brew upgrade gh
EOS
rescue Homebrew::Attestation::GhAuthInvalid
# Only raise an error if we explicitly opted-in to verification.
raise CannotInstallFormulaError, <<~EOS if Homebrew::EnvConfig.verify_attestations?
The bottle for #{bottle.name} could not be verified.
This typically indicates an invalid GitHub API token.
If you have `$HOMEBREW_GITHUB_API_TOKEN` set, check it is correct
or unset it and instead run:
gh auth login
EOS
# If we didn't explicitly opt-in, then quietly opt-out in the case of invalid credentials.
# Based on user reports, a significant number of users are running with stale tokens.
ENV["HOMEBREW_NO_VERIFY_ATTESTATIONS"] = "1"
rescue Homebrew::Attestation::GhAuthNeeded
raise CannotInstallFormulaError, <<~EOS
The bottle for #{bottle.name} could not be verified.
This typically indicates a missing GitHub API token, which you
can resolve either by setting `$HOMEBREW_GITHUB_API_TOKEN` or
by running:
gh auth login
EOS
rescue Homebrew::Attestation::MissingAttestationError, Homebrew::Attestation::InvalidAttestationError => e
raise CannotInstallFormulaError, <<~EOS
The bottle for #{bottle.name} has an invalid build provenance attestation.
This may indicate that the bottle was not produced by the expected
tap, or was maliciously inserted into the expected tap's bottle
storage.
Additional context:
#{e}
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/tar.rb | Library/Homebrew/utils/tar.rb | # typed: strict
# frozen_string_literal: true
require "system_command"
require "utils/output"
module Utils
# Helper functions for interacting with tar files.
module Tar
class << self
include SystemCommand::Mixin
include Utils::Output::Mixin
TAR_FILE_EXTENSIONS = %w[.tar .tb2 .tbz .tbz2 .tgz .tlz .txz .tZ].freeze
sig { returns(T::Boolean) }
def available?
executable.present?
end
sig { returns(T.nilable(Pathname)) }
def executable
return @executable if defined?(@executable)
gnu_tar_gtar_path = HOMEBREW_PREFIX/"opt/gnu-tar/bin/gtar"
gnu_tar_gtar = gnu_tar_gtar_path if gnu_tar_gtar_path.executable?
@executable = T.let(which("gtar") || gnu_tar_gtar || which("tar"), T.nilable(Pathname))
end
sig { params(path: T.any(Pathname, String)).void }
def validate_file(path)
return unless available?
path = Pathname.new(path)
return unless TAR_FILE_EXTENSIONS.include? path.extname
stdout, _, status = system_command(T.must(executable), args: ["--list", "--file", path],
print_stderr: false).to_a
odie "#{path} is not a valid tar file!" if !status.success? || stdout.blank?
end
sig { void }
def clear_executable_cache
remove_instance_variable(:@executable) if defined?(@executable)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/shebang.rb | Library/Homebrew/utils/shebang.rb | # typed: strict
# frozen_string_literal: true
module Utils
# Helper functions for manipulating shebang lines.
module Shebang
extend T::Helpers
requires_ancestor { Kernel }
module_function
# Specification on how to rewrite a given shebang.
class RewriteInfo
sig { returns(Regexp) }
attr_reader :regex
sig { returns(Integer) }
attr_reader :max_length
sig { returns(T.any(String, Pathname)) }
attr_reader :replacement
sig { params(regex: Regexp, max_length: Integer, replacement: T.any(String, Pathname)).void }
def initialize(regex, max_length, replacement)
@regex = regex
@max_length = max_length
@replacement = replacement
end
end
# Rewrite shebang for the given `paths` using the given `rewrite_info`.
#
# ### Example
#
# ```ruby
# rewrite_shebang detected_python_shebang, bin/"script.py"
# ```
#
# @api public
sig { params(rewrite_info: RewriteInfo, paths: T.any(String, Pathname)).void }
def rewrite_shebang(rewrite_info, *paths)
paths.each do |f|
f = Pathname(f)
next unless f.file?
next unless rewrite_info.regex.match?(f.read(rewrite_info.max_length))
Utils::Inreplace.inreplace f.to_s, rewrite_info.regex, "#!#{rewrite_info.replacement}"
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/socket.rb | Library/Homebrew/utils/socket.rb | # typed: strict
# frozen_string_literal: true
require "socket"
module Utils
# Wrapper around UNIXSocket to allow > 104 characters on macOS.
module UNIXSocketExt
extend T::Generic
sig {
type_parameters(:U).params(
path: String,
_block: T.proc.params(arg0: UNIXSocket).returns(T.type_parameter(:U)),
).returns(T.type_parameter(:U))
}
def self.open(path, &_block)
socket = Socket.new(:UNIX, :STREAM)
socket.connect(sockaddr_un(path))
unix_socket = UNIXSocket.for_fd(socket.fileno)
socket.autoclose = false # Transfer autoclose responsibility to UNIXSocket
yield unix_socket
end
sig { params(path: String).returns(String) }
def self.sockaddr_un(path)
Socket.sockaddr_un(path)
end
end
# Wrapper around UNIXServer to allow > 104 characters on macOS.
class UNIXServerExt < Socket
extend T::Generic
Elem = type_member(:out) { { fixed: String } }
sig { returns(String) }
attr_reader :path
sig { params(path: String).void }
def initialize(path)
super(:UNIX, :STREAM)
bind(UNIXSocketExt.sockaddr_un(path))
listen(Socket::SOMAXCONN)
@path = path
end
sig { returns(UNIXSocket) }
def accept_nonblock
socket, = super
socket.autoclose = false # Transfer autoclose responsibility to UNIXSocket
UNIXSocket.for_fd(socket.fileno)
end
end
end
require "extend/os/utils/socket"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/tty.rb | Library/Homebrew/utils/tty.rb | # typed: strict
# frozen_string_literal: true
# Various helper functions for interacting with TTYs.
module Tty
@stream = T.let($stdout, T.nilable(T.any(IO, StringIO)))
COLOR_CODES = T.let(
{
red: 31,
green: 32,
yellow: 33,
blue: 34,
magenta: 35,
cyan: 36,
default: 39,
}.freeze,
T::Hash[Symbol, Integer],
)
STYLE_CODES = T.let(
{
reset: 0,
bold: 1,
italic: 3,
underline: 4,
strikethrough: 9,
no_underline: 24,
}.freeze,
T::Hash[Symbol, Integer],
)
SPECIAL_CODES = T.let(
{
up: "1A",
down: "1B",
right: "1C",
left: "1D",
erase_line: "K",
erase_char: "P",
}.freeze,
T::Hash[Symbol, String],
)
CODES = T.let(COLOR_CODES.merge(STYLE_CODES).freeze, T::Hash[Symbol, Integer])
class << self
sig { params(stream: T.any(IO, StringIO), _block: T.proc.params(arg0: T.any(IO, StringIO)).void).void }
def with(stream, &_block)
previous_stream = @stream
@stream = T.let(stream, T.nilable(T.any(IO, StringIO)))
yield stream
ensure
@stream = T.let(previous_stream, T.nilable(T.any(IO, StringIO)))
end
sig { params(string: String).returns(String) }
def strip_ansi(string)
string.gsub(/\033\[\d+(;\d+)*m/, "")
end
sig { params(line_count: Integer).returns(String) }
def move_cursor_up(line_count)
"\033[#{line_count}A"
end
sig { params(line_count: Integer).returns(String) }
def move_cursor_up_beginning(line_count)
"\033[#{line_count}F"
end
sig { returns(String) }
def move_cursor_beginning
"\033[0G"
end
sig { params(line_count: Integer).returns(String) }
def move_cursor_down(line_count)
"\033[#{line_count}B"
end
sig { returns(String) }
def clear_to_end
"\033[K"
end
sig { returns(String) }
def hide_cursor
"\033[?25l"
end
sig { returns(String) }
def show_cursor
"\033[?25h"
end
sig { returns(T.nilable([Integer, Integer])) }
def size
return @size if defined?(@size)
height, width = `/bin/stty size 2>/dev/null`.presence&.split&.map(&:to_i)
return if height.nil? || width.nil?
@size = T.let([height, width], T.nilable([Integer, Integer]))
end
sig { returns(Integer) }
def height
@height ||= T.let(size&.first || `/usr/bin/tput lines 2>/dev/null`.presence&.to_i || 40, T.nilable(Integer))
end
sig { returns(Integer) }
def width
@width ||= T.let(size&.second || `/usr/bin/tput cols 2>/dev/null`.presence&.to_i || 80, T.nilable(Integer))
end
sig { params(string: String).returns(String) }
def truncate(string)
(w = width).zero? ? string.to_s : (string.to_s[0, w - 4] || "")
end
sig { returns(String) }
def current_escape_sequence
return "" if @escape_sequence.nil?
"\033[#{@escape_sequence.join(";")}m"
end
sig { void }
def reset_escape_sequence!
@escape_sequence = T.let(nil, T.nilable(T::Array[Integer]))
end
CODES.each do |name, code|
define_method(name) do
@escape_sequence ||= T.let([], T.nilable(T::Array[Integer]))
@escape_sequence << code
self
end
end
SPECIAL_CODES.each do |name, code|
define_method(name) do
@stream = T.let($stdout, T.nilable(T.any(IO, StringIO)))
if @stream&.tty?
"\033[#{code}"
else
""
end
end
end
sig { returns(String) }
def to_s
return "" unless color?
current_escape_sequence
ensure
reset_escape_sequence!
end
sig { returns(T::Boolean) }
def color?
require "env_config"
return false if Homebrew::EnvConfig.no_color?
return true if Homebrew::EnvConfig.color?
return false if @stream.blank?
@stream.tty?
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/output.rb | Library/Homebrew/utils/output.rb | # typed: strict
# frozen_string_literal: true
module Utils
module Output
module Mixin
extend T::Helpers
requires_ancestor { Kernel }
sig { params(title: String).returns(String) }
def ohai_title(title)
verbose = if respond_to?(:verbose?)
T.unsafe(self).verbose?
else
Context.current.verbose?
end
title = Tty.truncate(title.to_s) if $stdout.tty? && !verbose
Formatter.headline(title, color: :blue)
end
sig { params(title: T.any(String, Exception), sput: T.anything).void }
def ohai(title, *sput)
puts ohai_title(title.to_s)
puts sput
end
sig { params(title: T.any(String, Exception), sput: T.anything, always_display: T::Boolean).void }
def odebug(title, *sput, always_display: false)
debug = if respond_to?(:debug)
T.unsafe(self).debug?
else
Context.current.debug?
end
return if !debug && !always_display
$stderr.puts Formatter.headline(title.to_s, color: :magenta)
$stderr.puts sput unless sput.empty?
end
sig { params(title: String, truncate: T.any(Symbol, T::Boolean)).returns(String) }
def oh1_title(title, truncate: :auto)
verbose = if respond_to?(:verbose?)
T.unsafe(self).verbose?
else
Context.current.verbose?
end
title = Tty.truncate(title.to_s) if $stdout.tty? && !verbose && truncate == :auto
Formatter.headline(title, color: :green)
end
sig { params(title: String, truncate: T.any(Symbol, T::Boolean)).void }
def oh1(title, truncate: :auto)
puts oh1_title(title, truncate:)
end
# Print a warning message.
#
# @api public
sig { params(message: T.any(String, Exception)).void }
def opoo(message)
require "utils/github/actions"
return if GitHub::Actions.puts_annotation_if_env_set!(:warning, message.to_s)
require "utils/formatter"
Tty.with($stderr) do |stderr|
stderr.puts Formatter.warning(message, label: "Warning")
end
end
# Print a warning message only if not running in GitHub Actions.
#
# @api public
sig { params(message: T.any(String, Exception)).void }
def opoo_outside_github_actions(message)
require "utils/github/actions"
return if GitHub::Actions.env_set?
opoo(message)
end
# Print an error message.
#
# @api public
sig { params(message: T.any(String, Exception)).void }
def onoe(message)
require "utils/github/actions"
return if GitHub::Actions.puts_annotation_if_env_set!(:error, message.to_s)
require "utils/formatter"
Tty.with($stderr) do |stderr|
stderr.puts Formatter.error(message, label: "Error")
end
end
# Print an error message and fail at the end of the program.
#
# @api public
sig { params(error: T.any(String, Exception)).void }
def ofail(error)
onoe error
Homebrew.failed = true
end
# Print an error message and fail immediately.
#
# @api public
sig { params(error: T.any(String, Exception)).returns(T.noreturn) }
def odie(error)
onoe error
exit 1
end
# Output a deprecation warning/error message.
sig {
params(method: String, replacement: T.nilable(T.any(String, Symbol)), disable: T::Boolean,
disable_on: T.nilable(Time), disable_for_developers: T::Boolean, caller: T::Array[String]).void
}
def odeprecated(method, replacement = nil,
disable: false,
disable_on: nil,
disable_for_developers: true,
caller: send(:caller))
replacement_message = if replacement
"Use #{replacement} instead."
else
"There is no replacement."
end
unless disable_on.nil?
if disable_on > Time.now
will_be_disabled_message = " and will be disabled on #{disable_on.strftime("%Y-%m-%d")}"
else
disable = true
end
end
verb = if disable
"disabled"
else
"deprecated#{will_be_disabled_message}"
end
# Try to show the most relevant location in message, i.e. (if applicable):
# - Location in a formula.
# - Location of caller of deprecated method (if all else fails).
backtrace = caller
# Don't throw deprecations at all for cached, .brew or .metadata files.
return if backtrace.any? do |line|
next true if line.include?(HOMEBREW_CACHE.to_s)
next true if line.include?("/.brew/")
next true if line.include?("/.metadata/")
next false unless line.match?(HOMEBREW_TAP_PATH_REGEX)
path = Pathname(line.split(":", 2).first)
next false unless path.file?
next false unless path.readable?
formula_contents = path.read
formula_contents.include?(" deprecate! ") || formula_contents.include?(" disable! ")
end
tap_message = T.let(nil, T.nilable(String))
backtrace.each do |line|
next unless (match = line.match(HOMEBREW_TAP_PATH_REGEX))
require "tap"
tap = Tap.fetch(match[:user], match[:repository])
tap_message = "\nPlease report this issue to the #{tap.full_name} tap"
tap_message += " (not Homebrew/* repositories)" unless tap.official?
tap_message += ", or even better, submit a PR to fix it" if replacement
tap_message << ":\n #{line.sub(/^(.*:\d+):.*$/, '\1')}\n\n"
break
end
file, line, = backtrace.first.split(":")
line = line.to_i if line.present?
message = "Calling #{method} is #{verb}! #{replacement_message}"
message << tap_message if tap_message
message.freeze
disable = true if disable_for_developers && Homebrew::EnvConfig.developer?
if disable || Homebrew.raise_deprecation_exceptions?
require "utils/github/actions"
GitHub::Actions.puts_annotation_if_env_set!(:error, message, file:, line:)
exception = MethodDeprecatedError.new(message)
exception.set_backtrace(backtrace)
raise exception
elsif !Homebrew.auditing?
opoo message
end
end
sig {
params(method: String, replacement: T.nilable(T.any(String, Symbol)),
disable_on: T.nilable(Time), disable_for_developers: T::Boolean, caller: T::Array[String]).void
}
def odisabled(method, replacement = nil,
disable_on: nil,
disable_for_developers: true,
caller: send(:caller))
# This odeprecated should stick around indefinitely.
odeprecated(method, replacement, disable: true, disable_on:, disable_for_developers:, caller:)
end
sig { params(string: String).returns(String) }
def pretty_installed(string)
if !$stdout.tty?
string
elsif Homebrew::EnvConfig.no_emoji?
Formatter.success("#{Tty.bold}#{string} (installed)#{Tty.reset}")
else
"#{Tty.bold}#{string} #{Formatter.success("✔")}#{Tty.reset}"
end
end
sig { params(string: String).returns(String) }
def pretty_outdated(string)
if !$stdout.tty?
string
elsif Homebrew::EnvConfig.no_emoji?
Formatter.error("#{Tty.bold}#{string} (outdated)#{Tty.reset}")
else
"#{Tty.bold}#{string} #{Formatter.warning("⚠")}#{Tty.reset}"
end
end
sig { params(string: String).returns(String) }
def pretty_uninstalled(string)
if !$stdout.tty?
string
elsif Homebrew::EnvConfig.no_emoji?
Formatter.error("#{Tty.bold}#{string} (uninstalled)#{Tty.reset}")
else
"#{Tty.bold}#{string} #{Formatter.error("✘")}#{Tty.reset}"
end
end
sig { params(seconds: T.nilable(T.any(Integer, Float))).returns(String) }
def pretty_duration(seconds)
seconds = seconds.to_i
res = +""
if seconds > 59
minutes = seconds / 60
seconds %= 60
res = +Utils.pluralize("minute", minutes, include_count: true)
return res.freeze if seconds.zero?
res << " "
end
res << Utils.pluralize("second", seconds, include_count: true)
res.freeze
end
end
extend Mixin
$stdout.extend Mixin
$stderr.extend Mixin
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/autoremove.rb | Library/Homebrew/utils/autoremove.rb | # typed: strict
# frozen_string_literal: true
module Utils
# Helper function for finding autoremovable formulae.
#
# @private
module Autoremove
class << self
# An array of {Formula} without {Formula} or {Cask}
# dependents that weren't installed on request and without
# build dependencies for {Formula} installed from source.
# @private
sig { params(formulae: T::Array[Formula], casks: T::Array[Cask::Cask]).returns(T::Array[Formula]) }
def removable_formulae(formulae, casks)
unused_formulae = unused_formulae_with_no_formula_dependents(formulae)
unused_formulae - formulae_with_cask_dependents(casks)
end
private
# An array of all installed {Formula} with {Cask} dependents.
# @private
sig { params(casks: T::Array[Cask::Cask]).returns(T::Array[Formula]) }
def formulae_with_cask_dependents(casks)
casks.flat_map { |cask| cask.depends_on[:formula] }.compact.flat_map do |name|
f = begin
Formulary.resolve(name)
rescue FormulaUnavailableError
nil
end
next [] unless f
[f, *f.installed_runtime_formula_dependencies].compact
end
end
# An array of all installed bottled {Formula} without runtime {Formula}
# dependents for bottles and without build {Formula} dependents
# for those built from source.
# @private
sig { params(formulae: T::Array[Formula]).returns(T::Array[Formula]) }
def bottled_formulae_with_no_formula_dependents(formulae)
formulae_to_keep = T.let([], T::Array[Formula])
formulae.each do |formula|
formulae_to_keep += formula.installed_runtime_formula_dependencies
if (tab = formula.any_installed_keg&.tab)
# Ignore build dependencies when the formula is a bottle
next if tab.poured_from_bottle
# Keep the formula if it was built from source
formulae_to_keep << formula
end
formula.deps.select(&:build?).each do |dep|
formulae_to_keep << dep.to_formula
rescue FormulaUnavailableError
# do nothing
end
end
formulae - formulae_to_keep
end
# Recursive function that returns an array of {Formula} without
# {Formula} dependents that weren't installed on request.
# @private
sig { params(formulae: T::Array[Formula]).returns(T::Array[Formula]) }
def unused_formulae_with_no_formula_dependents(formulae)
unused_formulae = bottled_formulae_with_no_formula_dependents(formulae).select do |f|
tab = f.any_installed_keg&.tab
next unless tab
next unless tab.installed_on_request_present?
tab.installed_on_request == false
end
unless unused_formulae.empty?
unused_formulae += unused_formulae_with_no_formula_dependents(formulae - unused_formulae)
end
unused_formulae
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/github.rb | Library/Homebrew/utils/github.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "uri"
require "utils/github/actions"
require "utils/github/api"
require "utils/output"
require "system_command"
# A module that interfaces with GitHub, code like PAT scopes, credential handling and API errors.
#
# @api internal
module GitHub
extend SystemCommand::Mixin
extend Utils::Output::Mixin
MAX_PER_PAGE = T.let(100, Integer)
def self.issues(repo:, **filters)
uri = url_to("repos", repo, "issues")
uri.query = URI.encode_www_form(filters)
API.open_rest(uri)
end
def self.search_issues(query, **qualifiers)
json = search("issues", query, **qualifiers)
json.fetch("items", [])
end
sig { params(files: T::Hash[String, T.untyped], description: String, private: T::Boolean).returns(String) }
def self.create_gist(files, description, private:)
url = "#{API_URL}/gists"
data = { "public" => !private, "files" => files, "description" => description }
API.open_rest(url, data:, scopes: CREATE_GIST_SCOPES)["html_url"]
end
def self.create_issue(repo, title, body)
url = "#{API_URL}/repos/#{repo}/issues"
data = { "title" => title, "body" => body }
API.open_rest(url, data:, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)["html_url"]
end
def self.repository(user, repo)
API.open_rest(url_to("repos", user, repo))
end
def self.issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap&.full_name, state: nil, type: nil)
return [] unless tap_remote_repo
search_issues(name, repo: tap_remote_repo, state:, type:, in: "title")
end
sig { returns(T::Hash[String, T.untyped]) }
def self.user
@user ||= API.open_rest("#{API_URL}/user")
end
sig { params(repo: String, user: String).returns(T::Hash[String, T.untyped]) }
def self.permission(repo, user)
API.open_rest("#{API_URL}/repos/#{repo}/collaborators/#{user}/permission")
end
sig { params(repo: String, user: T.nilable(String)).returns(T::Boolean) }
def self.write_access?(repo, user = nil)
user ||= self.user["login"]
["admin", "write"].include?(permission(repo, user)["permission"])
end
def self.print_pull_requests_matching(query, only = nil)
open_or_closed_prs = search_issues(query, is: only, type: "pr", user: "Homebrew")
open_prs, closed_prs = open_or_closed_prs.partition { |pr| pr["state"] == "open" }
.map { |prs| prs.map { |pr| "#{pr["title"]} (#{pr["html_url"]})" } }
if open_prs.present?
ohai "Open pull requests"
open_prs.each { |pr| puts pr }
end
if closed_prs.present?
puts if open_prs.present?
ohai "Closed pull requests"
closed_prs.take(20).each { |pr| puts pr }
puts "..." if closed_prs.count > 20
end
puts "No pull requests found for #{query.inspect}" if open_prs.blank? && closed_prs.blank?
end
sig { params(repo: String, org: T.nilable(String)).returns(T::Hash[String, T.untyped]) }
def self.create_fork(repo, org: nil)
url = "#{API_URL}/repos/#{repo}/forks"
data = {}
data[:organization] = org if org
scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
API.open_rest(url, data:, scopes:)
end
sig { params(repo: String, org: T.nilable(String)).returns(T::Boolean) }
def self.fork_exists?(repo, org: nil)
_, reponame = repo.split("/")
username = org || API.open_rest(url_to("user")) { |json| json["login"] }
json = API.open_rest(url_to("repos", username, reponame))
return false if json["message"] == "Not Found"
true
end
sig { params(repo: String, title: String, head: String, base: String, body: String).returns(T::Hash[String, T.untyped]) }
def self.create_pull_request(repo, title, head, base, body)
url = "#{API_URL}/repos/#{repo}/pulls"
data = { title:, head:, base:, body:, maintainer_can_modify: true }
scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
API.open_rest(url, data:, scopes:)
end
# We default to private if we aren't sure or if the GitHub API is disabled.
sig { params(full_name: String).returns(T::Boolean) }
def self.private_repo?(full_name)
uri = url_to "repos", full_name
API.open_rest(uri) { |json| json.fetch("private", true) }
end
def self.search_query_string(*main_params, **qualifiers)
params = main_params
from = qualifiers.fetch(:from, nil)
to = qualifiers.fetch(:to, nil)
params << if from && to
"created:#{from}..#{to}"
elsif from
"created:>=#{from}"
elsif to
"created:<=#{to}"
end
params += qualifiers.except(:args, :from, :to).flat_map do |key, value|
Array(value).map { |v| "#{key.to_s.tr("_", "-")}:#{v}" }
end
"q=#{URI.encode_www_form_component(params.compact.join(" "))}&per_page=#{MAX_PER_PAGE}"
end
def self.url_to(*subroutes)
URI.parse([API_URL, *subroutes].join("/"))
end
def self.search(entity, *queries, **qualifiers)
uri = url_to "search", entity
uri.query = search_query_string(*queries, **qualifiers)
API.open_rest(uri)
end
def self.repository_approved_reviews(user, repo, pull_request, commit: nil)
query = <<~EOS
{ repository(name: "#{repo}", owner: "#{user}") {
pullRequest(number: #{pull_request}) {
reviews(states: APPROVED, first: 100) {
nodes {
author {
... on User { email login name databaseId }
... on Organization { email login name databaseId }
}
authorAssociation
commit { oid }
}
}
}
}
}
EOS
result = API.open_graphql(query, scopes: ["user:email"])
reviews = result["repository"]["pullRequest"]["reviews"]["nodes"]
valid_associations = %w[MEMBER OWNER]
reviews.filter_map do |r|
next if commit.present? && commit != r["commit"]["oid"]
next unless valid_associations.include? r["authorAssociation"]
email = r["author"]["email"].presence ||
"#{r["author"]["databaseId"]}+#{r["author"]["login"]}@users.noreply.github.com"
name = r["author"]["name"].presence ||
r["author"]["login"]
{
"email" => email,
"name" => name,
"login" => r["author"]["login"],
}
end
end
def self.workflow_dispatch_event(user, repo, workflow, ref, **inputs)
url = "#{API_URL}/repos/#{user}/#{repo}/actions/workflows/#{workflow}/dispatches"
API.open_rest(url, data: { ref:, inputs: },
request_method: :POST,
scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end
sig { params(user: String, repo: String, tag: String).returns(T::Hash[String, T.untyped]) }
def self.get_release(user, repo, tag)
url = "#{API_URL}/repos/#{user}/#{repo}/releases/tags/#{tag}"
API.open_rest(url, request_method: :GET)
end
sig { params(user: String, repo: String).returns(T::Hash[String, T.untyped]) }
def self.get_latest_release(user, repo)
url = "#{API_URL}/repos/#{user}/#{repo}/releases/latest"
API.open_rest(url, request_method: :GET)
end
def self.generate_release_notes(user, repo, tag, previous_tag: nil)
url = "#{API_URL}/repos/#{user}/#{repo}/releases/generate-notes"
data = { tag_name: tag }
data[:previous_tag_name] = previous_tag if previous_tag.present?
API.open_rest(url, data:, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end
sig {
params(user: String, repo: String, tag: String, id: T.nilable(String), name: T.nilable(String),
body: T.nilable(String), draft: T::Boolean).returns(T::Hash[String, T.untyped])
}
def self.create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false)
url = "#{API_URL}/repos/#{user}/#{repo}/releases"
method = if id
url += "/#{id}"
:PATCH
else
:POST
end
data = {
tag_name: tag,
name: name || tag,
draft:,
}
data[:body] = body if body.present?
API.open_rest(url, data:, request_method: method, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end
def self.upload_release_asset(user, repo, id, local_file: nil, remote_file: nil)
url = "https://uploads.github.com/repos/#{user}/#{repo}/releases/#{id}/assets"
url += "?name=#{remote_file}" if remote_file
API.open_rest(url, data_binary_path: local_file, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
end
def self.get_workflow_run(user, repo, pull_request, workflow_id: "tests.yml", artifact_pattern: "bottles{,_*}")
scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
# GraphQL unfortunately has no way to get the workflow yml name, so we need an extra REST call.
workflow_api_url = "#{API_URL}/repos/#{user}/#{repo}/actions/workflows/#{workflow_id}"
workflow_payload = API.open_rest(workflow_api_url, scopes:)
workflow_id_num = workflow_payload["id"]
query = <<~EOS
query ($user: String!, $repo: String!, $pr: Int!) {
repository(owner: $user, name: $repo) {
pullRequest(number: $pr) {
commits(last: 1) {
nodes {
commit {
checkSuites(first: 100) {
nodes {
status,
workflowRun {
databaseId,
url,
workflow {
databaseId
}
}
}
}
}
}
}
}
}
}
EOS
variables = {
user:,
repo:,
pr: pull_request.to_i,
}
result = API.open_graphql(query, variables:, scopes:)
commit_node = result["repository"]["pullRequest"]["commits"]["nodes"].first
check_suite = if commit_node.present?
commit_node["commit"]["checkSuites"]["nodes"].select do |suite|
suite.dig("workflowRun", "workflow", "databaseId") == workflow_id_num
end
else
[]
end
[check_suite, user, repo, pull_request, workflow_id, scopes, artifact_pattern]
end
sig { params(workflow_array: T::Array[T.untyped]).returns(T::Array[T.untyped]) }
def self.get_artifact_urls(workflow_array)
check_suite, user, repo, pr, workflow_id, scopes, artifact_pattern = *workflow_array
if check_suite.empty?
raise API::Error, <<~EOS
No matching check suite found for these criteria!
Pull request: #{pr}
Workflow: #{workflow_id}
EOS
end
status = check_suite.last["status"].sub("_", " ").downcase
if status != "completed"
raise API::Error, <<~EOS
The newest workflow run for ##{pr} is still #{status}!
#{Formatter.url check_suite.last["workflowRun"]["url"]}
EOS
end
run_id = check_suite.last["workflowRun"]["databaseId"]
artifacts = []
per_page = 50
API.paginate_rest("#{API_URL}/repos/#{user}/#{repo}/actions/runs/#{run_id}/artifacts",
per_page:, scopes:) do |result|
result = result["artifacts"]
artifacts.concat(result)
break if result.length < per_page
end
matching_artifacts =
artifacts
.group_by { |art| art["name"] }
.select { |name| File.fnmatch?(artifact_pattern, name, File::FNM_EXTGLOB) }
.map { |_, arts| arts.last }
if matching_artifacts.empty?
raise API::Error, <<~EOS
No artifacts with the pattern `#{artifact_pattern}` were found!
#{Formatter.url check_suite.last["workflowRun"]["url"]}
EOS
end
matching_artifacts.map { |art| art["archive_download_url"] }
end
def self.public_member_usernames(org, per_page: MAX_PER_PAGE)
url = "#{API_URL}/orgs/#{org}/public_members"
members = []
API.paginate_rest(url, per_page:) do |result|
result = result.map { |member| member["login"] }
members.concat(result)
return members if result.length < per_page
end
end
sig { params(org: String, team: String).returns(T::Hash[String, T.untyped]) }
def self.members_by_team(org, team)
query = <<~EOS
{ organization(login: "#{org}") {
teams(first: 100) {
nodes {
... on Team { name }
}
}
team(slug: "#{team}") {
members(first: 100) {
nodes {
... on User { login name }
}
}
}
}
}
EOS
result = API.open_graphql(query, scopes: ["read:org", "user"])
if result["organization"]["teams"]["nodes"].blank?
raise API::Error,
"Your token needs the 'read:org' scope to access this API"
end
raise API::Error, "The team #{org}/#{team} does not exist" if result["organization"]["team"].blank?
result["organization"]["team"]["members"]["nodes"].to_h { |member| [member["login"], member["name"]] }
end
sig {
params(user: String)
.returns(
T::Array[{
closest_tier_monthly_amount: Integer,
login: String,
monthly_amount: Integer,
name: String,
}],
)
}
def self.sponsorships(user)
query = <<~EOS
query($user: String!, $after: String) { organization(login: $user) {
sponsorshipsAsMaintainer(first: 100, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
tier {
monthlyPriceInDollars
closestLesserValueTier {
monthlyPriceInDollars
}
}
sponsorEntity {
... on Organization { login name }
... on User { login name }
}
}
}
}
}
EOS
sponsorships = T.let([], T::Array[Hash])
errors = T.let([], T::Array[Hash])
API.paginate_graphql(query, variables: { user: }, scopes: ["user"], raise_errors: false) do |result|
# Some organisations do not permit themselves to be queried through the
# API like this and raise an error so handle these errors later.
# This has been reported to GitHub.
errors += result["errors"] if result["errors"].present?
current_sponsorships = result.dig("data", "organization", "sponsorshipsAsMaintainer")
# if `current_sponsorships` is blank, then there should be errors to report.
next { "hasNextPage" => false } if current_sponsorships.blank?
# The organisations mentioned above will show up as nil nodes.
if (nodes = current_sponsorships["nodes"].compact.presence)
sponsorships += nodes
end
current_sponsorships.fetch("pageInfo")
end
# Only raise errors if we didn't get any sponsorships.
raise API::Error, errors.map { |e| e["message"] }.join("\n") if sponsorships.blank? && errors.present?
sponsorships.map do |sponsorship|
sponsor = sponsorship["sponsorEntity"]
tier = sponsorship["tier"].presence || {}
monthly_amount = tier["monthlyPriceInDollars"].presence || 0
closest_tier = tier["closestLesserValueTier"].presence || {}
closest_tier_monthly_amount = closest_tier["monthlyPriceInDollars"].presence || 0
{
name: sponsor["name"].presence || sponsor["login"],
login: sponsor["login"],
monthly_amount:,
closest_tier_monthly_amount:,
}
end
end
sig { params(user: String, repo: String, ref: T.nilable(String)).returns(T.nilable(String)) }
def self.get_repo_license(user, repo, ref: nil)
url = "#{API_URL}/repos/#{user}/#{repo}/license"
url += "?ref=#{ref}" if ref.present?
response = API.open_rest(url)
return unless response.key?("license")
response["license"]["spdx_id"]
rescue API::HTTPNotFoundError
nil
rescue API::AuthenticationFailedError => e
raise unless e.message.match?(API::GITHUB_IP_ALLOWLIST_ERROR)
end
def self.pull_request_title_regex(name, version = nil)
return /(^|\s)#{Regexp.quote(name)}(:|,|\s|$)/i if version.blank?
/(^|\s)#{Regexp.quote(name)}(:|,|\s)(.*\s)?#{Regexp.quote(version)}(:|,|\s|$)/i
end
sig {
params(name: String, tap_remote_repo: String, state: T.nilable(String), version: T.nilable(String))
.returns(T::Array[T::Hash[String, T.untyped]])
}
def self.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil)
return [] if Homebrew::EnvConfig.no_github_api?
regex = pull_request_title_regex(name, version)
query = "is:pr #{name} #{version}".strip
# Unauthenticated users cannot use GraphQL so use search REST API instead.
# Limit for this is 30/minute so is usually OK unless you're spamming bump PRs (e.g. CI).
if API.credentials_type == :none
return issues_for_formula(query, tap_remote_repo:, state:).select do |pr|
pr["html_url"].include?("/pull/") && regex.match?(pr["title"])
end
elsif state == "open" && ENV["GITHUB_REPOSITORY_OWNER"] == "Homebrew"
# Try use PR API, which might be cheaper on rate limits in some cases.
# The rate limit of the search API under GraphQL is unclear as it
# costs the same as any other query according to /rate_limit.
# The PR API is also not very scalable so limit to Homebrew CI.
return fetch_open_pull_requests(name, tap_remote_repo, version:)
end
query += " repo:#{tap_remote_repo} in:title"
query += " state:#{state}" if state.present?
graphql_query = <<~EOS
query($query: String!, $after: String) {
search(query: $query, type: ISSUE, first: 100, after: $after) {
nodes {
... on PullRequest {
number
title
url
state
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
EOS
variables = { query: }
pull_requests = []
API.paginate_graphql(graphql_query, variables:) do |result|
data = result["search"]
pull_requests.concat(data["nodes"].select { |pr| regex.match?(pr["title"]) })
data["pageInfo"]
end
pull_requests.map! do |pr|
pr.merge({
"html_url" => pr.delete("url"),
"state" => pr.fetch("state").downcase,
})
end
rescue API::RateLimitExceededError => e
opoo e.message
pull_requests || []
end
sig { params(name: String, tap_remote_repo: String, version: T.nilable(String)).returns(T::Array[T::Hash[String, T.untyped]]) }
def self.fetch_open_pull_requests(name, tap_remote_repo, version: nil)
return [] if tap_remote_repo.blank?
# Bust the cache every three minutes.
cache_expiry = 3 * 60
cache_epoch = Time.now - (Time.now.to_i % cache_expiry)
cache_key = "#{tap_remote_repo}_#{cache_epoch.to_i}"
@open_pull_requests ||= {}
@open_pull_requests[cache_key] ||= begin
query = <<~EOS
query($owner: String!, $repo: String!, $states: [PullRequestState!], $after: String) {
repository(owner: $owner, name: $repo) {
pullRequests(states: $states, first: 100, after: $after) {
nodes {
number
title
url
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
EOS
owner, repo = tap_remote_repo.split("/")
variables = { owner:, repo:, states: ["OPEN"] }
pull_requests = []
API.paginate_graphql(query, variables:) do |result|
data = result.dig("repository", "pullRequests")
pull_requests.concat(data["nodes"])
data["pageInfo"]
end
pull_requests
end
regex = pull_request_title_regex(name, version)
@open_pull_requests[cache_key].select { |pr| regex.match?(pr["title"]) }
.map { |pr| pr.merge("html_url" => pr.delete("url")) }
rescue API::RateLimitExceededError => e
opoo e.message
pull_requests || []
end
# Check for duplicate pull requests that modify the same file.
#
# Exits the process on duplicates if `strict` or both `version` and
# `official_tap`, otherwise warns.
#
# @api internal
sig {
params(
name: String,
tap_remote_repo: String,
file: String,
quiet: T::Boolean,
state: T.nilable(String),
version: T.nilable(String),
official_tap: T::Boolean,
strict: T::Boolean,
).void
}
def self.check_for_duplicate_pull_requests(name, tap_remote_repo, file:, quiet: false, state: nil,
version: nil, official_tap: true, strict: false)
pull_requests = fetch_pull_requests(name, tap_remote_repo, state:, version:)
pull_requests.select! do |pr|
get_pull_request_changed_files(
tap_remote_repo, pr["number"]
).any? { |f| f["filename"] == file }
end
return if pull_requests.blank?
confidence = version ? "are" : "might be"
duplicates_message = <<~EOS
These #{state} pull requests #{confidence} duplicates:
#{pull_requests.map { |pr| "#{pr["title"]} #{pr["html_url"]}" }.join("\n")}
EOS
error_message = <<~EOS
Duplicate PRs must not be opened.
Manually open these PRs if you are sure that they are not duplicates (and tell us that in the PR).
EOS
if strict || (version && official_tap)
odie <<~EOS
#{duplicates_message.chomp}
#{error_message}
EOS
elsif !official_tap
opoo duplicates_message
elsif quiet
opoo error_message
else
opoo <<~EOS
#{duplicates_message.chomp}
#{error_message}
EOS
end
end
sig { params(tap_remote_repo: String, pull_request: T.any(String, Integer)).returns(T::Array[T.untyped]) }
def self.get_pull_request_changed_files(tap_remote_repo, pull_request)
files = []
API.paginate_rest(url_to("repos", tap_remote_repo, "pulls", pull_request, "files")) do |result|
files.concat(result)
end
files
end
sig { params(url: String).returns(String) }
def self.add_auth_token_to_url!(url)
if API.credentials_type == :env_token
url.sub!(%r{^https://github\.com/}, "https://x-access-token:#{API.credentials}@github.com/")
end
url
end
sig { params(tap_remote_repo: String, org: T.nilable(String)).returns(T::Array[String]) }
def self.forked_repo_info!(tap_remote_repo, org: nil)
response = create_fork(tap_remote_repo, org:)
# GitHub API responds immediately but fork takes a few seconds to be ready.
sleep 1 until fork_exists?(tap_remote_repo, org:)
remote_url = if system("git", "config", "--local", "--get-regexp", "remote..*.url", "git@github.com:.*")
response.fetch("ssh_url")
else
add_auth_token_to_url!(response.fetch("clone_url"))
end
username = response.fetch("owner").fetch("login")
[remote_url, username]
end
def self.create_bump_pr(info, args:)
# --write-only without --commit means don't take any git actions at all.
return if args.write_only? && !args.commit?
tap = info[:tap]
remote = info[:remote] || "origin"
remote_branch = info[:remote_branch] || tap.git_repository.origin_branch_name
branch = info[:branch_name]
previous_branch = info[:previous_branch] || "-"
tap_remote_repo = info[:tap_remote_repo] || tap.full_name
pr_message = info[:pr_message]
pr_title = info[:pr_title]
commits = info[:commits]
remote_url = Utils.popen_read("git", "remote", "get-url", "--push", "origin").chomp
username = tap.user
tap.path.cd do
if args.no_fork? || args.write_only?
remote_url = Utils.popen_read("git", "remote", "get-url", "--push", "origin").chomp
username = tap.user
add_auth_token_to_url!(remote_url)
else
begin
remote_url, username = forked_repo_info!(tap_remote_repo, org: args.fork_org)
rescue *API::ERRORS => e
commits.each do |commit|
commit[:sourcefile_path].atomic_write(commit[:old_contents])
end
odie "Unable to fork: #{e.message}!"
end
end
next if args.dry_run?
require "utils/popen"
git_dir = Utils.popen_read("git", "rev-parse", "--git-dir").chomp
shallow = !git_dir.empty? && File.exist?("#{git_dir}/shallow")
safe_system "git", "fetch", "--unshallow", "origin" if !args.commit? && shallow
safe_system "git", "checkout", "--no-track", "-b", branch, "#{remote}/#{remote_branch}" unless args.commit?
Utils::Git.set_name_email!
end
commits.each do |commit|
sourcefile_path = commit[:sourcefile_path]
commit_message = commit[:commit_message]
additional_files = commit[:additional_files] || []
sourcefile_path.parent.cd do
require "utils/popen"
git_dir = Utils.popen_read("git", "rev-parse", "--git-dir").chomp
shallow = !git_dir.empty? && File.exist?("#{git_dir}/shallow")
changed_files = [sourcefile_path]
changed_files += additional_files if additional_files.present?
if args.dry_run? || (args.write_only? && !args.commit?)
ohai "git checkout --no-track -b #{branch} #{remote}/#{remote_branch}"
ohai "git fetch --unshallow origin" if shallow
ohai "git add #{changed_files.join(" ")}"
ohai "git commit --no-edit --verbose --message='#{commit_message}' " \
"-- #{changed_files.join(" ")}"
ohai "git push --set-upstream #{remote_url} #{branch}:#{branch}"
ohai "git checkout --quiet #{previous_branch}"
ohai "create pull request with GitHub API (base branch: #{remote_branch})"
else
safe_system "git", "add", *changed_files
Utils::Git.set_name_email!
safe_system "git", "commit", "--no-edit", "--verbose",
"--message=#{commit_message}",
"--", *changed_files
end
end
end
return if args.commit? || args.dry_run?
tap.path.cd do
system_command!("git", args: ["push", "--set-upstream", remote_url, "#{branch}:#{branch}"],
print_stdout: true)
safe_system "git", "checkout", "--quiet", previous_branch
pr_message = <<~EOS
#{pr_message}
EOS
user_message = args.message
if user_message
pr_message = <<~EOS
#{user_message}
---
#{pr_message}
EOS
end
begin
url = create_pull_request(tap_remote_repo, pr_title,
"#{username}:#{branch}", remote_branch, pr_message)["html_url"]
if args.no_browse?
puts url
else
exec_browser url
end
rescue *API::ERRORS => e
commits.each do |commit|
commit[:sourcefile_path].atomic_write(commit[:old_contents])
end
odie "Unable to open pull request for #{tap_remote_repo}: #{e.message}!"
end
end
end
def self.pull_request_commits(user, repo, pull_request, per_page: MAX_PER_PAGE)
pr_data = API.open_rest(url_to("repos", user, repo, "pulls", pull_request))
commits_api = pr_data["commits_url"]
commit_count = pr_data["commits"]
commits = []
if commit_count > API_MAX_ITEMS
raise API::Error, "Getting #{commit_count} commits would exceed limit of #{API_MAX_ITEMS} API items!"
end
API.paginate_rest(commits_api, per_page:) do |result, page|
commits.concat(result.map { |c| c["sha"] })
return commits if commits.length == commit_count
if result.empty? || page * per_page >= commit_count
raise API::Error, "Expected #{commit_count} commits but actually got #{commits.length}!"
end
end
end
def self.pull_request_labels(user, repo, pull_request)
pr_data = API.open_rest(url_to("repos", user, repo, "pulls", pull_request))
pr_data["labels"].map { |label| label["name"] }
end
def self.last_commit(user, repo, ref, version, length: nil)
return if Homebrew::EnvConfig.no_github_api?
require "utils/curl"
result = Utils::Curl.curl_output(
"--silent", "--head", "--location",
"--header", "Accept: application/vnd.github.sha",
url_to("repos", user, repo, "commits", ref).to_s
)
return unless result.status.success?
commit = result.stdout[/^ETag: "(\h+)"/i, 1]
return if commit.blank?
if length
return if commit.length < length
commit = commit[0, length]
# We return nil if the following fails as we currently don't have a way to
# determine the reason for the failure. This means we can't distinguish a
# GitHub API rate limit from a non-unique short commit where the latter
# needs (n+1) or more characters to match `git rev-parse --short=n`.
return if multiple_short_commits_exist?(user, repo, commit)
end
version.update_commit(commit)
commit
end
def self.multiple_short_commits_exist?(user, repo, commit)
return false if Homebrew::EnvConfig.no_github_api?
require "utils/curl"
result = Utils::Curl.curl_output(
"--silent", "--head", "--location",
"--header", "Accept: application/vnd.github.sha",
"--output", File::NULL,
# This is a Curl format token, not a Ruby one.
# rubocop:disable Style/FormatStringToken
"--write-out", "%{http_code}",
# rubocop:enable Style/FormatStringToken
url_to("repos", user, repo, "commits", commit).to_s
)
return true unless result.status.success?
return true if (output = result.stdout).blank?
output != "200"
end
sig {
params(repository_name_with_owner: String, user: String, filter: String, from: T.nilable(String),
to: T.nilable(String), max: Integer, verbose: T::Boolean).returns(T::Array[String])
}
def self.repo_commits_for_user(repository_name_with_owner, user, filter, from, to, max, verbose)
return [] if Homebrew::EnvConfig.no_github_api?
params = ["#{filter}=#{user}"]
params << "since=#{DateTime.parse(from).iso8601}" if from.present?
params << "until=#{DateTime.parse(to).iso8601}" if to.present?
commits = []
API.paginate_rest("#{API_URL}/repos/#{repository_name_with_owner}/commits",
additional_query_params: params.join("&")) do |result|
commits.concat(result.map { |c| c["sha"] })
if commits.length >= max
if verbose
opoo "#{user} exceeded #{max} #{repository_name_with_owner} commits as #{filter}, stopped counting!"
end
break
end
end
commits
end
sig {
params(repository_name_with_owner: String, user: String, max: Integer, verbose: T::Boolean,
from: T.nilable(String), to: T.nilable(String)).returns(Integer)
}
def self.count_repository_commits(repository_name_with_owner, user, max:, verbose:, from: nil, to: nil)
odie "Cannot count commits as `$HOMEBREW_NO_GITHUB_API` is set!" if Homebrew::EnvConfig.no_github_api?
author_shas = repo_commits_for_user(repository_name_with_owner, user, "author", from, to, max, verbose)
committer_shas = repo_commits_for_user(repository_name_with_owner, user, "committer", from, to, max, verbose)
return 0 if author_shas.blank? && committer_shas.blank?
author_count = author_shas.count
# Only count commits where the author and committer are different.
committer_count = committer_shas.difference(author_shas).count
author_count + committer_count
end
MAXIMUM_OPEN_PRS = 15
sig { params(tap: T.nilable(Tap)).returns(T::Boolean) }
def self.too_many_open_prs?(tap)
# We don't enforce unofficial taps.
return false if tap.nil? || !tap.official?
# BrewTestBot can open as many PRs as it wants.
return false if ENV["HOMEBREW_TEST_BOT_AUTOBUMP"].present?
odie "Cannot count PRs as `$HOMEBREW_NO_GITHUB_API` is set!" if Homebrew::EnvConfig.no_github_api?
query = <<~EOS
query($after: String) {
viewer {
login
pullRequests(first: 100, states: OPEN, after: $after) {
totalCount
nodes {
baseRepository {
owner {
login
}
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
}
EOS
puts
homebrew_prs_count = 0
begin
API.paginate_graphql(query) do |result|
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/backtrace.rb | Library/Homebrew/utils/backtrace.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Utils
module Backtrace
extend Utils::Output::Mixin
@print_backtrace_message = T.let(false, T::Boolean)
# Cleans `sorbet-runtime` gem paths from the backtrace unless...
# 1. `verbose` is set
# 2. first backtrace line starts with `sorbet-runtime`
# - This implies that the error is related to Sorbet.
sig { params(error: Exception).returns(T.nilable(T::Array[String])) }
def self.clean(error)
backtrace = error.backtrace
return backtrace if Context.current.verbose?
return backtrace if backtrace.blank?
return backtrace if backtrace.fetch(0).start_with?(sorbet_runtime_path)
old_backtrace_length = backtrace.length
backtrace.reject { |line| line.start_with?(sorbet_runtime_path) }
.tap { |new_backtrace| print_backtrace_message if old_backtrace_length > new_backtrace.length }
end
sig { returns(String) }
def self.sorbet_runtime_path
@sorbet_runtime_path ||= T.let("#{Gem.paths.home}/gems/sorbet-runtime", T.nilable(String))
end
sig { void }
def self.print_backtrace_message
return if @print_backtrace_message
# This is just unactionable noise in GitHub Actions.
opoo_outside_github_actions "Removed Sorbet lines from backtrace!"
puts "Rerun with `--verbose` to see the original backtrace" unless Homebrew::EnvConfig.no_env_hints?
@print_backtrace_message = true
end
sig { params(error: Exception).returns(T.nilable(String)) }
def self.tap_error_url(error)
backtrace = error.backtrace
return if backtrace.blank?
backtrace.each do |line|
if (tap = line.match(%r{/Library/Taps/([^/]+/[^/]+)/}))
return "https://github.com/#{tap[1]}/issues/new"
end
end
nil
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/popen.rb | Library/Homebrew/utils/popen.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Utils
IO_DEFAULT_BUFFER_SIZE = 4096
private_constant :IO_DEFAULT_BUFFER_SIZE
def self.popen_read(*args, safe: false, **options, &block)
output = popen(args, "rb", options, &block)
return output if !safe || $CHILD_STATUS.success?
raise ErrorDuringExecution.new(args, status: $CHILD_STATUS, output: [[:stdout, output]])
end
def self.safe_popen_read(*args, **options, &block)
popen_read(*args, safe: true, **options, &block)
end
def self.popen_write(*args, safe: false, **options)
output = ""
popen(args, "w+b", options) do |pipe|
# Before we yield to the block, capture as much output as we can
loop do
output += pipe.read_nonblock(IO_DEFAULT_BUFFER_SIZE)
rescue IO::WaitReadable, EOFError
break
end
yield pipe
pipe.close_write
pipe.wait_readable
# Capture the rest of the output
output += pipe.read
output.freeze
end
return output if !safe || $CHILD_STATUS.success?
raise ErrorDuringExecution.new(args, status: $CHILD_STATUS, output: [[:stdout, output]])
end
def self.safe_popen_write(*args, **options, &block)
popen_write(*args, safe: true, **options, &block)
end
def self.popen(args, mode, options = {})
IO.popen("-", mode) do |pipe|
if pipe
return pipe.read unless block_given?
yield pipe
else
options[:err] ||= File::NULL unless ENV["HOMEBREW_STDERR"]
cmd = if args[0].is_a? Hash
args[1]
else
args[0]
end
begin
exec(*args, options)
rescue Errno::ENOENT
$stderr.puts "brew: command not found: #{cmd}" if options[:err] != :close
exit! 127
rescue SystemCallError
$stderr.puts "brew: exec failed: #{cmd}" if options[:err] != :close
exit! 1
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/string_inreplace_extension.rb | Library/Homebrew/utils/string_inreplace_extension.rb | # typed: strong
# frozen_string_literal: true
require "utils/output"
# Used by the {Utils::Inreplace.inreplace} function.
class StringInreplaceExtension
include Utils::Output::Mixin
sig { returns(T::Array[String]) }
attr_accessor :errors
sig { returns(String) }
attr_accessor :inreplace_string
sig { params(string: String).void }
def initialize(string)
@inreplace_string = string
@errors = T.let([], T::Array[String])
end
# Same as `String#sub!`, but warns if nothing was replaced.
#
# @api public
sig { params(before: T.any(Regexp, String), after: String, audit_result: T::Boolean).returns(T.nilable(String)) }
def sub!(before, after, audit_result: true)
result = inreplace_string.sub!(before, after)
errors << "expected replacement of #{before.inspect} with #{after.inspect}" if audit_result && result.nil?
result
end
# Same as `String#gsub!`, but warns if nothing was replaced.
#
# @api public
sig {
params(
before: T.any(Pathname, Regexp, String),
after: T.any(Pathname, String),
audit_result: T::Boolean,
).returns(T.nilable(String))
}
def gsub!(before, after, audit_result: true)
before = before.to_s if before.is_a?(Pathname)
result = inreplace_string.gsub!(before, after.to_s)
errors << "expected replacement of #{before.inspect} with #{after.inspect}" if audit_result && result.nil?
result
end
# Looks for Makefile style variable definitions and replaces the
# value with "new_value", or removes the definition entirely.
#
# @api public
sig { params(flag: String, new_value: T.any(String, Pathname)).void }
def change_make_var!(flag, new_value)
return if gsub!(/^#{Regexp.escape(flag)}[ \t]*[\\?+:!]?=[ \t]*((?:.*\\\n)*.*)$/,
"#{flag}=#{new_value}",
audit_result: false)
errors << "expected to change #{flag.inspect} to #{new_value.inspect}"
end
# Removes variable assignments completely.
#
# @api public
sig { params(flags: T.any(String, T::Array[String])).void }
def remove_make_var!(flags)
Array(flags).each do |flag|
# Also remove trailing \n, if present.
next if gsub!(/^#{Regexp.escape(flag)}[ \t]*[\\?+:!]?=(?:.*\\\n)*.*$\n?/,
"",
audit_result: false)
errors << "expected to remove #{flag.inspect}"
end
end
# Finds the specified variable.
#
# @api public
sig { params(flag: String).returns(String) }
def get_make_var(flag)
T.must(inreplace_string[/^#{Regexp.escape(flag)}[ \t]*[\\?+:!]?=[ \t]*((?:.*\\\n)*.*)$/, 1])
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/shared_audits.rb | Library/Homebrew/utils/shared_audits.rb | # typed: strict
# frozen_string_literal: true
require "utils/curl"
require "utils/github/api"
# Auditing functions for rules common to both casks and formulae.
module SharedAudits
URL_TYPE_HOMEPAGE = "homepage URL"
sig { params(product: String, cycle: String).returns(T.nilable(T::Hash[String, T.untyped])) }
def self.eol_data(product, cycle)
@eol_data ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
key = "#{product}/#{cycle}"
return @eol_data[key] if @eol_data.key?(key)
result = Utils::Curl.curl_output(
"--location",
"https://endoflife.date/api/v1/products/#{product}/releases/#{cycle}",
)
return unless result.status.success?
@eol_data[key] = begin
JSON.parse(result.stdout)
rescue JSON::ParserError
nil
end
end
sig { params(user: String, repo: String).returns(T.nilable(T::Hash[String, T.untyped])) }
def self.github_repo_data(user, repo)
@github_repo_data ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
@github_repo_data["#{user}/#{repo}"] ||= GitHub.repository(user, repo)
@github_repo_data["#{user}/#{repo}"]
rescue GitHub::API::HTTPNotFoundError
nil
rescue GitHub::API::AuthenticationFailedError => e
raise unless e.message.match?(GitHub::API::GITHUB_IP_ALLOWLIST_ERROR)
end
sig { params(user: String, repo: String, tag: String).returns(T.nilable(T::Hash[String, T.untyped])) }
private_class_method def self.github_release_data(user, repo, tag)
id = "#{user}/#{repo}/#{tag}"
url = "#{GitHub::API_URL}/repos/#{user}/#{repo}/releases/tags/#{tag}"
@github_release_data ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
@github_release_data[id] ||= GitHub::API.open_rest(url)
@github_release_data[id]
rescue GitHub::API::HTTPNotFoundError
nil
rescue GitHub::API::AuthenticationFailedError => e
raise unless e.message.match?(GitHub::API::GITHUB_IP_ALLOWLIST_ERROR)
end
sig {
params(
user: String, repo: String, tag: String, formula: T.nilable(Formula), cask: T.nilable(Cask::Cask),
).returns(
T.nilable(String),
)
}
def self.github_release(user, repo, tag, formula: nil, cask: nil)
release = github_release_data(user, repo, tag)
return unless release
exception, name, version = if formula
[formula.tap&.audit_exception(:github_prerelease_allowlist, formula.name), formula.name, formula.version]
elsif cask
[cask.tap&.audit_exception(:github_prerelease_allowlist, cask.token), cask.token, cask.version]
end
return "#{tag} is a GitHub pre-release." if release["prerelease"] && [version, "all", "any"].exclude?(exception)
if !release["prerelease"] && exception && [version, "any"].exclude?(exception)
return "#{tag} is not a GitHub pre-release but '#{name}' is in the GitHub prerelease allowlist."
end
"#{tag} is a GitHub draft." if release["draft"]
end
sig { params(user: String, repo: String).returns(T.nilable(T::Hash[String, T.untyped])) }
def self.gitlab_repo_data(user, repo)
@gitlab_repo_data ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
@gitlab_repo_data["#{user}/#{repo}"] ||= begin
result = Utils::Curl.curl_output("https://gitlab.com/api/v4/projects/#{user}%2F#{repo}")
json = JSON.parse(result.stdout) if result.status.success?
json = nil if json&.dig("message")&.include?("404 Project Not Found")
json
end
end
sig { params(user: String, repo: String).returns(T.nilable(T::Hash[String, T.untyped])) }
def self.forgejo_repo_data(user, repo)
@forgejo_repo_data ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
@forgejo_repo_data["#{user}/#{repo}"] ||= begin
result = Utils::Curl.curl_output("https://codeberg.org/api/v1/repos/#{user}/#{repo}")
JSON.parse(result.stdout) if result.status.success?
end
end
sig { params(user: String, repo: String, tag: String).returns(T.nilable(T::Hash[String, T.untyped])) }
private_class_method def self.gitlab_release_data(user, repo, tag)
id = "#{user}/#{repo}/#{tag}"
@gitlab_release_data ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
@gitlab_release_data[id] ||= begin
result = Utils::Curl.curl_output(
"https://gitlab.com/api/v4/projects/#{user}%2F#{repo}/releases/#{tag}", "--fail"
)
JSON.parse(result.stdout) if result.status.success?
end
end
sig {
params(
user: String, repo: String, tag: String, formula: T.nilable(Formula), cask: T.nilable(Cask::Cask),
).returns(
T.nilable(String),
)
}
def self.gitlab_release(user, repo, tag, formula: nil, cask: nil)
release = gitlab_release_data(user, repo, tag)
return unless release
return if DateTime.parse(release["released_at"]) <= DateTime.now
exception, version = if formula
[formula.tap&.audit_exception(:gitlab_prerelease_allowlist, formula.name), formula.version]
elsif cask
[cask.tap&.audit_exception(:gitlab_prerelease_allowlist, cask.token), cask.version]
end
return if [version, "all"].include?(exception)
"#{tag} is a GitLab pre-release."
end
sig { params(user: String, repo: String, tag: String).returns(T.nilable(T::Hash[String, T.untyped])) }
private_class_method def self.forgejo_release_data(user, repo, tag)
id = "#{user}/#{repo}/#{tag}"
@forgejo_release_data ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
@forgejo_release_data[id] ||= begin
result = Utils::Curl.curl_output(
"https://codeberg.org/api/v1/repos/#{user}/#{repo}/releases/tags/#{tag}", "--fail"
)
JSON.parse(result.stdout) if result.status.success?
end
end
sig {
params(
user: String, repo: String, tag: String, formula: T.nilable(Formula), cask: T.nilable(Cask::Cask),
).returns(
T.nilable(String),
)
}
def self.forgejo_release(user, repo, tag, formula: nil, cask: nil)
release = forgejo_release_data(user, repo, tag)
return unless release
return unless release["prerelease"]
exception, version = if formula
[formula.tap&.audit_exception(:forgejo_prerelease_allowlist, formula.name), formula.version]
elsif cask
[cask.tap&.audit_exception(:forgejo_prerelease_allowlist, cask.token), cask.version]
end
return if [version, "all"].include?(exception)
"#{tag} is a Forgejo pre-release."
end
sig { params(user: String, repo: String).returns(T.nilable(String)) }
def self.github(user, repo)
metadata = github_repo_data(user, repo)
return if metadata.nil?
return "GitHub fork (not canonical repository)" if metadata["fork"]
if (metadata["forks_count"] < 30) && (metadata["subscribers_count"] < 30) &&
(metadata["stargazers_count"] < 75)
return "GitHub repository not notable enough (<30 forks, <30 watchers and <75 stars)"
end
return if Date.parse(metadata["created_at"]) <= (Date.today - 30)
"GitHub repository too new (<30 days old)"
end
sig { params(user: String, repo: String).returns(T.nilable(String)) }
def self.gitlab(user, repo)
metadata = gitlab_repo_data(user, repo)
return if metadata.nil?
return "GitLab fork (not canonical repository)" if metadata["fork"]
if (metadata["forks_count"] < 30) && (metadata["star_count"] < 75)
return "GitLab repository not notable enough (<30 forks and <75 stars)"
end
return if Date.parse(metadata["created_at"]) <= (Date.today - 30)
"GitLab repository too new (<30 days old)"
end
sig { params(user: String, repo: String).returns(T.nilable(String)) }
def self.bitbucket(user, repo)
api_url = "https://api.bitbucket.org/2.0/repositories/#{user}/#{repo}"
result = Utils::Curl.curl_output("--request", "GET", api_url)
return unless result.status.success?
metadata = JSON.parse(result.stdout)
return if metadata.nil?
return "Uses deprecated Mercurial support in Bitbucket" if metadata["scm"] == "hg"
return "Bitbucket fork (not canonical repository)" unless metadata["parent"].nil?
return "Bitbucket repository too new (<30 days old)" if Date.parse(metadata["created_on"]) >= (Date.today - 30)
forks_result = Utils::Curl.curl_output("--request", "GET", "#{api_url}/forks")
return unless forks_result.status.success?
watcher_result = Utils::Curl.curl_output("--request", "GET", "#{api_url}/watchers")
return unless watcher_result.status.success?
forks_metadata = JSON.parse(forks_result.stdout)
return if forks_metadata.nil?
watcher_metadata = JSON.parse(watcher_result.stdout)
return if watcher_metadata.nil?
return if forks_metadata["size"] >= 30 || watcher_metadata["size"] >= 75
"Bitbucket repository not notable enough (<30 forks and <75 watchers)"
end
sig { params(user: String, repo: String).returns(T.nilable(String)) }
def self.forgejo(user, repo)
metadata = forgejo_repo_data(user, repo)
return if metadata.nil?
return "Forgejo fork (not canonical repository)" if metadata["fork"]
if (metadata["forks_count"] < 30) && (metadata["watchers_count"] < 30) &&
(metadata["stars_count"] < 75)
return "Forgejo repository not notable enough (<30 forks, <30 watchers and <75 stars)"
end
return if Date.parse(metadata["created_at"]) <= (Date.today - 30)
"Forgejo repository too new (<30 days old)"
end
sig { params(url: String).returns(T.nilable(String)) }
def self.github_tag_from_url(url)
tag = url[%r{^https://github\.com/[\w-]+/[\w.-]+/archive/refs/tags/(.+)\.(tar\.gz|zip)$}, 1]
tag || url[%r{^https://github\.com/[\w-]+/[\w.-]+/releases/download/([^/]+)/}, 1]
end
sig { params(url: String).returns(T.nilable(String)) }
def self.gitlab_tag_from_url(url)
url[%r{^https://gitlab\.com/(?:\w[\w.-]*/){2,}-/archive/([^/]+)/}, 1]
end
sig { params(url: String).returns(T.nilable(String)) }
def self.forgejo_tag_from_url(url)
url[%r{^https://codeberg\.org/[\w-]+/[\w.-]+/archive/(.+)\.(tar\.gz|zip)$}, 1]
end
sig { params(formula_or_cask: T.any(Formula, Cask::Cask)).returns(T.nilable(String)) }
def self.check_deprecate_disable_reason(formula_or_cask)
return if !formula_or_cask.deprecated? && !formula_or_cask.disabled?
reason = formula_or_cask.deprecated? ? formula_or_cask.deprecation_reason : formula_or_cask.disable_reason
return unless reason.is_a?(Symbol)
reasons = if formula_or_cask.is_a?(Formula)
DeprecateDisable::FORMULA_DEPRECATE_DISABLE_REASONS
else
DeprecateDisable::CASK_DEPRECATE_DISABLE_REASONS
end
"#{reason} is not a valid deprecate! or disable! reason" unless reasons.include?(reason)
end
sig { params(message: T.any(String, Symbol)).returns(T.nilable(String)) }
def self.no_autobump_new_package_message(message)
return if message.is_a?(String) || message != :requires_manual_review
"`:requires_manual_review` is a temporary reason intended for existing packages, use a different reason instead."
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/repology.rb | Library/Homebrew/utils/repology.rb | # typed: strict
# frozen_string_literal: true
require "utils/curl"
require "utils/output"
# Repology API client.
module Repology
extend Utils::Output::Mixin
HOMEBREW_CORE = "homebrew"
HOMEBREW_CASK = "homebrew_casks"
MAX_PAGINATION = 15
private_constant :MAX_PAGINATION
sig { params(last_package_in_response: T.nilable(String), repository: String).returns(T::Hash[String, T.untyped]) }
def self.query_api(last_package_in_response = "", repository:)
last_package_in_response += "/" if last_package_in_response.present?
url = "https://repology.org/api/v1/projects/#{last_package_in_response}?inrepo=#{repository}&outdated=1"
result = Utils::Curl.curl_output(
"--silent", url.to_s,
use_homebrew_curl: !Utils::Curl.curl_supports_tls13?
)
JSON.parse(result.stdout)
rescue
if Homebrew::EnvConfig.developer?
$stderr.puts result&.stderr
else
odebug result&.stderr.to_s
end
raise
end
sig { params(name: String, repository: String).returns(T.nilable(T::Hash[String, T.untyped])) }
def self.single_package_query(name, repository:)
url = "https://repology.org/api/v1/project/#{name}"
result = Utils::Curl.curl_output(
"--location", "--silent", url.to_s,
use_homebrew_curl: !Utils::Curl.curl_supports_tls13?
)
data = JSON.parse(result.stdout)
{ name => data }
rescue => e
require "utils/backtrace"
error_output = [result&.stderr, "#{e.class}: #{e}", Utils::Backtrace.clean(e)].compact
if Homebrew::EnvConfig.developer?
$stderr.puts(*error_output)
else
odebug(*error_output)
end
nil
end
sig {
params(
limit: T.nilable(Integer),
last_package: T.nilable(String),
repository: String,
).returns(T::Hash[String, T.untyped])
}
def self.parse_api_response(limit = nil, last_package = "", repository:)
package_term = case repository
when HOMEBREW_CORE
"formulae"
when HOMEBREW_CASK
"casks"
else
"packages"
end
ohai "Querying outdated #{package_term} from Repology"
page_no = 1
outdated_packages = {}
while page_no <= MAX_PAGINATION
odebug "Paginating Repology API page: #{page_no}"
response = query_api(last_package, repository:)
outdated_packages.merge!(response)
last_package = response.keys.max
page_no += 1
break if (limit && outdated_packages.size >= limit) || response.size <= 1
end
package_term = package_term.chop if outdated_packages.size == 1
puts "#{outdated_packages.size} outdated #{package_term} found"
puts
outdated_packages.sort.to_h
end
sig { params(repositories: T::Array[String]).returns(T.any(String, Version)) }
def self.latest_version(repositories)
# The status is "unique" when the package is present only in Homebrew, so
# Repology has no way of knowing if the package is up-to-date.
is_unique = repositories.find do |repo|
repo["status"] == "unique"
end.present?
return "present only in Homebrew" if is_unique
latest_version = repositories.find do |repo|
repo["status"] == "newest"
end
# Repology cannot identify "newest" versions for packages without a version
# scheme
return "no latest version" if latest_version.blank?
Version.new(T.must(latest_version["version"]))
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/uid.rb | Library/Homebrew/utils/uid.rb | # typed: strict
# frozen_string_literal: true
module Utils
module UID
sig { type_parameters(:U).params(_block: T.proc.returns(T.type_parameter(:U))).returns(T.type_parameter(:U)) }
def self.drop_euid(&_block)
return yield if Process.euid == Process.uid
original_euid = Process.euid
begin
Process::Sys.seteuid(Process.uid)
yield
ensure
Process::Sys.seteuid(original_euid)
end
end
sig { returns(T.nilable(String)) }
def self.uid_home
require "etc"
Etc.getpwuid(Process.uid)&.dir
rescue ArgumentError
# Cover for misconfigured NSS setups
nil
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/link.rb | Library/Homebrew/utils/link.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Utils
# Helper functions for creating symlinks.
module Link
extend Utils::Output::Mixin
sig { params(src_dir: Pathname, dst_dir: Pathname, command: String, link_dir: T::Boolean).void }
def self.link_src_dst_dirs(src_dir, dst_dir, command, link_dir: false)
return unless src_dir.exist?
conflicts = []
src_paths = link_dir ? [src_dir] : src_dir.find
src_paths.each do |src|
next if src.directory? && !link_dir
dst = dst_dir/src.relative_path_from(src_dir)
if dst.symlink?
next if src == dst.resolved_path
dst.unlink
end
if dst.exist?
conflicts << dst
next
end
dst_dir.parent.mkpath
dst.make_relative_symlink(src)
end
return if conflicts.empty?
onoe <<~EOS
Could not link:
#{conflicts.join("\n")}
Please delete these paths and run:
#{command}
EOS
end
private_class_method :link_src_dst_dirs
sig { params(src_dir: Pathname, dst_dir: Pathname, unlink_dir: T::Boolean).void }
def self.unlink_src_dst_dirs(src_dir, dst_dir, unlink_dir: false)
return unless src_dir.exist?
src_paths = unlink_dir ? [src_dir] : src_dir.find
src_paths.each do |src|
next if src.directory? && !unlink_dir
dst = dst_dir/src.relative_path_from(src_dir)
dst.delete if dst.symlink? && src == dst.resolved_path
dst.parent.rmdir_if_possible
end
end
private_class_method :unlink_src_dst_dirs
sig { params(path: Pathname, command: String).void }
def self.link_manpages(path, command)
link_src_dst_dirs(path/"manpages", HOMEBREW_PREFIX/"share/man/man1", command)
end
sig { params(path: Pathname).void }
def self.unlink_manpages(path)
unlink_src_dst_dirs(path/"manpages", HOMEBREW_PREFIX/"share/man/man1")
end
sig { params(path: Pathname, command: String).void }
def self.link_completions(path, command)
link_src_dst_dirs(path/"completions/bash", HOMEBREW_PREFIX/"etc/bash_completion.d", command)
link_src_dst_dirs(path/"completions/zsh", HOMEBREW_PREFIX/"share/zsh/site-functions", command)
link_src_dst_dirs(path/"completions/fish", HOMEBREW_PREFIX/"share/fish/vendor_completions.d", command)
end
sig { params(path: Pathname).void }
def self.unlink_completions(path)
unlink_src_dst_dirs(path/"completions/bash", HOMEBREW_PREFIX/"etc/bash_completion.d")
unlink_src_dst_dirs(path/"completions/zsh", HOMEBREW_PREFIX/"share/zsh/site-functions")
unlink_src_dst_dirs(path/"completions/fish", HOMEBREW_PREFIX/"share/fish/vendor_completions.d")
end
sig { params(path: Pathname, command: String).void }
def self.link_docs(path, command)
link_src_dst_dirs(path/"docs", HOMEBREW_PREFIX/"share/doc/homebrew", command, link_dir: true)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/pypi.rb | Library/Homebrew/utils/pypi.rb | # typed: strict
# frozen_string_literal: true
require "utils/inreplace"
require "utils/output"
require "utils/ast"
# Helper functions for updating PyPI resources.
module PyPI
extend Utils::Output::Mixin
PYTHONHOSTED_URL_PREFIX = "https://files.pythonhosted.org/packages/"
private_constant :PYTHONHOSTED_URL_PREFIX
# Represents a Python package.
# This package can be a PyPI package (either by name/version or PyPI distribution URL),
# or it can be a non-PyPI URL.
class Package
include Utils::Output::Mixin
sig { params(package_string: String, is_url: T::Boolean, python_name: String).void }
def initialize(package_string, is_url: false, python_name: "python")
@pypi_info = T.let(nil, T.nilable(T::Array[String]))
@package_string = package_string
@is_url = is_url
@is_pypi_url = T.let(package_string.start_with?(PYTHONHOSTED_URL_PREFIX), T::Boolean)
@python_name = python_name
end
sig { returns(T.nilable(String)) }
def name
basic_metadata if @name.blank?
@name
end
sig { returns(T.nilable(T::Array[String])) }
def extras
basic_metadata if @extras.blank?
@extras
end
sig { returns(T.nilable(String)) }
def version
basic_metadata if @version.blank?
@version
end
sig { params(new_version: String).void }
def version=(new_version)
raise ArgumentError, "can't update version for non-PyPI packages" unless valid_pypi_package?
@version = T.let(new_version, T.nilable(String))
end
sig { returns(T::Boolean) }
def valid_pypi_package?
@is_pypi_url || !@is_url
end
# Get name, URL, SHA-256 checksum and latest version for a given package.
# This only works for packages from PyPI or from a PyPI URL; packages
# derived from non-PyPI URLs will produce `nil` here.
sig {
params(new_version: T.nilable(T.any(String, Version)),
ignore_errors: T.nilable(T::Boolean)).returns(T.nilable(T::Array[String]))
}
def pypi_info(new_version: nil, ignore_errors: false)
return unless valid_pypi_package?
return @pypi_info if @pypi_info.present? && new_version.blank?
new_version ||= version
metadata_url = if new_version.present?
"https://pypi.org/pypi/#{name}/#{new_version}/json"
else
"https://pypi.org/pypi/#{name}/json"
end
result = Utils::Curl.curl_output(metadata_url, "--location", "--fail")
return unless result.status.success?
begin
json = JSON.parse(result.stdout)
rescue JSON::ParserError
return
end
dist = json["urls"].find do |url|
url["packagetype"] == "sdist"
end
# If there isn't an sdist, we use the first pure Python3 or universal wheel
if dist.nil?
dist = json["urls"].find do |url|
url["filename"].match?("[.-]py3[^-]*-none-any.whl$")
end
end
if dist.nil?
return ["", "", "", "", "no suitable source distribution on PyPI"] if ignore_errors
onoe "#{name} exists on PyPI but lacks a suitable source distribution"
return
end
@pypi_info = [
PyPI.normalize_python_package(json["info"]["name"]), dist["url"],
dist["digests"]["sha256"], json["info"]["version"]
]
end
sig { returns(String) }
def to_s
if valid_pypi_package?
out = T.must(name)
if (pypi_extras = extras.presence)
out += "[#{pypi_extras.join(",")}]"
end
out += "==#{version}" if version.present?
out
else
@package_string
end
end
sig { params(other: Package).returns(T::Boolean) }
def same_package?(other)
# These names are pre-normalized, so we can compare them directly.
name == other.name
end
# Compare only names so we can use .include? and .uniq on a Package array
sig { params(other: T.anything).returns(T::Boolean) }
def ==(other)
case other
when Package
same_package?(other)
else
false
end
end
alias eql? ==
sig { returns(Integer) }
def hash
name.hash
end
sig { params(other: Package).returns(T.nilable(Integer)) }
def <=>(other)
name <=> other.name
end
private
# Returns [name, [extras], version] for this package.
sig { returns(T.nilable(T.any(String, T::Array[String]))) }
def basic_metadata
if @is_pypi_url
match = File.basename(@package_string).match(/^(.+)-([a-z\d.]+?)(?:.tar.gz|.zip)$/)
raise ArgumentError, "Package should be a valid PyPI URL" if match.blank?
@name ||= T.let(PyPI.normalize_python_package(T.must(match[1])), T.nilable(String))
@extras ||= T.let([], T.nilable(T::Array[String]))
@version ||= T.let(match[2], T.nilable(String))
elsif @is_url
require "formula"
Formula[@python_name].ensure_installed!
# The URL might be a source distribution hosted somewhere;
# try and use `pip install -q --no-deps --dry-run --report ...` to get its
# name and version.
# Note that this is different from the (similar) `pip install --report` we
# do below, in that it uses `--no-deps` because we only care about resolving
# this specific URL's project metadata.
command =
[Formula[@python_name].opt_libexec/"bin/python", "-m", "pip", "install", "-q", "--no-deps",
"--dry-run", "--ignore-installed", "--report", "/dev/stdout", @package_string]
pip_output = Utils.popen_read({ "PIP_REQUIRE_VIRTUALENV" => "false" }, *command)
unless $CHILD_STATUS.success?
raise ArgumentError, <<~EOS
Unable to determine metadata for "#{@package_string}" because of a failure when running
`#{command.join(" ")}`.
EOS
end
metadata = JSON.parse(pip_output)["install"].first["metadata"]
@name ||= T.let(PyPI.normalize_python_package(metadata["name"]), T.nilable(String))
@extras ||= T.let([], T.nilable(T::Array[String]))
@version ||= T.let(metadata["version"], T.nilable(String))
else
if @package_string.include? "=="
name, version = @package_string.split("==")
else
name = @package_string
version = nil
end
if (match = T.must(name).match(/^(.*?)\[(.+)\]$/))
name = match[1]
extras = T.must(match[2]).split ","
else
extras = []
end
@name ||= T.let(PyPI.normalize_python_package(T.must(name)), T.nilable(String))
@extras ||= extras
@version ||= version
end
end
end
sig { params(url: String, version: T.any(String, Version)).returns(T.nilable(String)) }
def self.update_pypi_url(url, version)
package = Package.new url, is_url: true
return unless package.valid_pypi_package?
_, url = package.pypi_info(new_version: version)
url
rescue ArgumentError
nil
end
# Return true if resources were checked (even if no change).
sig {
params(
formula: Formula,
version: T.nilable(String),
package_name: T.nilable(String),
extra_packages: T.nilable(T::Array[String]),
exclude_packages: T.nilable(T::Array[String]),
dependencies: T.nilable(T::Array[String]),
install_dependencies: T.nilable(T::Boolean),
print_only: T.nilable(T::Boolean),
silent: T.nilable(T::Boolean),
verbose: T.nilable(T::Boolean),
ignore_errors: T.nilable(T::Boolean),
ignore_non_pypi_packages: T.nilable(T::Boolean),
).returns(T.nilable(T::Boolean))
}
def self.update_python_resources!(formula, version: nil, package_name: nil, extra_packages: nil,
exclude_packages: nil, dependencies: nil, install_dependencies: false,
print_only: false, silent: false, verbose: false,
ignore_errors: false, ignore_non_pypi_packages: false)
if [package_name, extra_packages, exclude_packages, dependencies].all?(&:blank?)
list_entry = formula.pypi_packages_info
package_name = list_entry.package_name
extra_packages = list_entry.extra_packages
exclude_packages = list_entry.exclude_packages
dependencies = list_entry.dependencies
end
missing_dependencies = Array(dependencies).reject do |dependency|
Formula[dependency].any_version_installed?
rescue FormulaUnavailableError
odie "Formula \"#{dependency}\" not found but it is a dependency to update \"#{formula.name}\" resources."
end
if missing_dependencies.present?
missing_msg = "formulae required to update \"#{formula.name}\" resources: #{missing_dependencies.join(", ")}"
odie "Missing #{missing_msg}" unless install_dependencies
ohai "Installing #{missing_msg}"
require "formula"
missing_dependencies.each { |dep| Formula[dep].ensure_installed! }
end
python_deps = formula.deps
.select { |d| d.name.match?(/^python(@.+)?$/) }
.map(&:to_formula)
.sort_by(&:version)
.reverse
python_name = if python_deps.empty?
"python"
else
(python_deps.find(&:any_version_installed?) || python_deps.first).name
end
main_package = if package_name.present?
package_string = package_name
package_string += "==#{formula.version}" if version.blank? && formula.version.present?
Package.new(package_string, python_name:)
elsif package_name == ""
nil
else
stable = T.must(formula.stable)
url = if stable.specs[:tag].present?
"git+#{stable.url}@#{stable.specs[:tag]}"
else
T.must(stable.url)
end
Package.new(url, is_url: true, python_name:)
end
if main_package.nil?
odie "The main package was skipped but no PyPI `extra_packages` were provided." if extra_packages.blank?
elsif version.present?
if main_package.valid_pypi_package?
main_package.version = version
else
return if ignore_non_pypi_packages
odie "The main package is not a PyPI package, meaning that version-only updates cannot be \
performed. Please update its URL manually."
end
end
extra_packages = (extra_packages || []).map { |p| Package.new p }
exclude_packages = (exclude_packages || []).map { |p| Package.new p }
exclude_packages += %w[argparse pip wsgiref].map { |p| Package.new p }
if (newest_python = python_deps.first) && newest_python.version < Version.new("3.12")
exclude_packages.append(Package.new("setuptools"))
end
# remove packages from the exclude list if we've explicitly requested them as an extra package
exclude_packages.delete_if { |package| extra_packages.include?(package) }
input_packages = Array(main_package)
extra_packages.each do |extra_package|
if !extra_package.valid_pypi_package? && !ignore_non_pypi_packages
odie "\"#{extra_package}\" is not available on PyPI."
end
input_packages.each do |existing_package|
if existing_package.same_package?(extra_package) && existing_package.version != extra_package.version
odie "Conflicting versions specified for the `#{extra_package.name}` package: " \
"#{existing_package.version}, #{extra_package.version}"
end
end
input_packages << extra_package unless input_packages.include? extra_package
end
formula.resources.each do |resource|
if !print_only && !resource.url.start_with?(PYTHONHOSTED_URL_PREFIX)
odie "\"#{formula.name}\" contains non-PyPI resources. Please update the resources manually."
end
end
existing_resources_by_name = formula.resources.to_h { |resource| [resource.name, resource] }
formula_contents = formula.path.read
existing_resource_blocks = resource_blocks_from_formula(formula_contents)
require "formula"
Formula[python_name].ensure_installed!
# Resolve the dependency tree of all input packages
show_info = !print_only && !silent
ohai "Retrieving PyPI dependencies for \"#{input_packages.join(" ")}\"..." if show_info
print_stderr = verbose && show_info
print_stderr ||= false
found_packages = pip_report(input_packages, python_name:, print_stderr:)
# Resolve the dependency tree of excluded packages to prune the above
exclude_packages.delete_if { |package| found_packages.exclude? package }
ohai "Retrieving PyPI dependencies for excluded \"#{exclude_packages.join(" ")}\"..." if show_info
exclude_packages = pip_report(exclude_packages, python_name:, print_stderr:)
# Keep extra_packages even if they are dependencies of exclude_packages
exclude_packages.delete_if { |package| extra_packages.include? package }
if (main_package_name = main_package&.name)
exclude_packages += [Package.new(main_package_name)]
end
new_resource_blocks = ""
package_errors = ""
found_packages.sort.each do |package|
if exclude_packages.include? package
ohai "Excluding \"#{package}\"" if show_info
exclude_packages.delete package
next
end
ohai "Getting PyPI info for \"#{package}\"" if show_info
name, url, checksum, _, package_error = package.pypi_info(ignore_errors: ignore_errors)
if package_error.blank?
# Fail if unable to find name, url or checksum for any resource
if name.blank?
if ignore_errors
package_error = "unknown failure"
else
odie "Unable to resolve some dependencies. Please update the resources for \"#{formula.name}\" manually."
end
elsif url.blank? || checksum.blank?
if ignore_errors
package_error = "unable to find URL and/or sha256"
else
odie <<~EOS
Unable to find the URL and/or sha256 for the "#{name}" resource.
Please update the resources for "#{formula.name}" manually.
EOS
end
end
end
if package_error.blank?
if (existing_resource = existing_resources_by_name[T.must(name)]) &&
existing_resource.url == url &&
existing_resource.checksum&.hexdigest == checksum &&
(existing_block = existing_resource_blocks[T.must(name)])
new_resource_blocks += <<-EOS
#{existing_block.dup}
EOS
next
end
# Append indented resource block
new_resource_blocks += <<-EOS
resource "#{name}" do
url "#{url}"
sha256 "#{checksum}"
end
EOS
else
# Leave a placeholder for formula author to investigate
package_errors += " # RESOURCE-ERROR: Unable to resolve \"#{package}\" (#{package_error})\n"
end
end
package_errors += "\n" if package_errors.present?
resource_section = "#{package_errors}#{new_resource_blocks}"
odie "Excluded superfluous packages: #{exclude_packages.join(", ")}" if exclude_packages.any?
if print_only
puts resource_section.chomp
return
end
# Check whether resources already exist (excluding virtualenv dependencies)
if formula.resources.all? { |resource| resource.name.start_with?("homebrew-") }
# Place resources above install method
inreplace_regex = / def install/
resource_section += " def install"
else
# Replace existing resource blocks with new resource blocks
inreplace_regex = /
\ \ (
(\#\ RESOURCE-ERROR:\ .*\s+)*
resource\ .*\ do\s+
url\ .*\s+
sha256\ .*\s+
((\#.*\s+)*
patch\ (.*\ )?do\s+
url\ .*\s+
sha256\ .*\s+
end\s+)*
end\s+)+
/x
resource_section += " "
end
ohai "Updating resource blocks" unless silent
Utils::Inreplace.inreplace formula.path do |s|
if s.inreplace_string.split(/^ test do\b/, 2).fetch(0).scan(inreplace_regex).length > 1
odie "Unable to update resource blocks for \"#{formula.name}\" automatically. Please update them manually."
end
s.sub! inreplace_regex, resource_section
end
if package_errors.present?
ofail "Unable to resolve some dependencies. Please check #{formula.path} for RESOURCE-ERROR comments."
end
true
end
sig { params(contents: String).returns(T::Hash[String, String]) }
def self.resource_blocks_from_formula(contents)
blocks = {}
_processed_source, root_node = Utils::AST.process_source(contents)
return blocks if root_node.nil?
root_node.each_node(:block) do |node|
next unless Utils::AST.call_node_match?(node, name: :resource, type: :block_call)
send_node = node.send_node
name_node = send_node.arguments.first
next if name_node.blank? || !name_node.str_type?
resource_name = name_node.str_content
blocks[resource_name] = node.location.expression.source
end
blocks
end
sig { params(name: String).returns(String) }
def self.normalize_python_package(name)
# This normalization is defined in the PyPA packaging specifications;
# https://packaging.python.org/en/latest/specifications/name-normalization/#name-normalization
name.gsub(/[-_.]+/, "-").downcase
end
sig {
params(
packages: T::Array[Package], python_name: String, print_stderr: T::Boolean,
).returns(T::Array[Package])
}
def self.pip_report(packages, python_name: "python", print_stderr: false)
return [] if packages.blank?
command = [
Formula[python_name].opt_libexec/"bin/python", "-m", "pip", "install", "-q", "--disable-pip-version-check",
"--dry-run", "--ignore-installed", "--report=/dev/stdout", *packages.map(&:to_s)
]
options = {}
options[:err] = :err if print_stderr
pip_output = Utils.popen_read({ "PIP_REQUIRE_VIRTUALENV" => "false" }, *command, **options)
unless $CHILD_STATUS.success?
odie <<~EOS
Unable to determine dependencies for "#{packages.join(" ")}" because of a failure when running
`#{command.join(" ")}`.
Please update the resources manually.
EOS
end
pip_report_to_packages(JSON.parse(pip_output)).uniq
end
sig { params(report: T::Hash[String, T.untyped]).returns(T::Array[Package]) }
def self.pip_report_to_packages(report)
return [] if report.blank?
report["install"].filter_map do |package|
name = normalize_python_package(package["metadata"]["name"])
version = package["metadata"]["version"]
Package.new "#{name}==#{version}"
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/git_repository.rb | Library/Homebrew/utils/git_repository.rb | # typed: strict
# frozen_string_literal: true
module Utils
# Gets the full commit hash of the HEAD commit.
sig {
params(
repo: T.any(String, Pathname),
length: T.nilable(Integer),
safe: T::Boolean,
).returns(T.nilable(String))
}
def self.git_head(repo = Pathname.pwd, length: nil, safe: true)
return git_short_head(repo, length:) if length
GitRepository.new(Pathname(repo)).head_ref(safe:)
end
# Gets a short commit hash of the HEAD commit.
sig {
params(
repo: T.any(String, Pathname),
length: T.nilable(Integer),
safe: T::Boolean,
).returns(T.nilable(String))
}
def self.git_short_head(repo = Pathname.pwd, length: nil, safe: true)
GitRepository.new(Pathname(repo)).short_head_ref(length:, safe:)
end
# Gets the name of the currently checked-out branch, or HEAD if the repository is in a detached HEAD state.
sig {
params(
repo: T.any(String, Pathname),
safe: T::Boolean,
).returns(T.nilable(String))
}
def self.git_branch(repo = Pathname.pwd, safe: true)
GitRepository.new(Pathname(repo)).branch_name(safe:)
end
# Gets the full commit message of the specified commit, or of the HEAD commit if unspecified.
sig {
params(
repo: T.any(String, Pathname),
commit: String,
safe: T::Boolean,
).returns(T.nilable(String))
}
def self.git_commit_message(repo = Pathname.pwd, commit: "HEAD", safe: true)
GitRepository.new(Pathname(repo)).commit_message(commit, safe:)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/test_prof_rubocop_stub.rb | Library/Homebrew/utils/test_prof_rubocop_stub.rb | # typed: strict
# frozen_string_literal: true
require_relative "../warnings"
# TestProf's RuboCop plugin has two issues that we need to work around:
#
# 1. It references RuboCop::TestProf::Plugin::VERSION, which does not exist.
# To solve this, we define the constant ourselves, which requires creating a dummy LintRoller::Plugin class.
# This should be fixed in the next version of TestProf.
# See: https://github.com/test-prof/test-prof/commit/a151a513373563ed8fa7f8e56193138d3ee9b5e3
#
# 2. It checks the RuboCop version using a method that is incompatible with our RuboCop setup.
# To bypass this check, we need to manually require the necessary files. More details below.
module LintRoller
# Dummy class to satisfy TestProf's reference to LintRoller::Plugin.
class Plugin; end # rubocop:disable Lint/EmptyClass
end
module RuboCop
module TestProf
class Plugin < LintRoller::Plugin
VERSION = "1.5.0"
end
end
end
# TestProf is not able to detect what version of RuboCop we're using, so we need to manually import its cops.
# For more details, see https://github.com/test-prof/test-prof/blob/v1.5.0/lib/test_prof/rubocop.rb
# TODO: This will change in the next version of TestProf.
# See: https://github.com/test-prof/test-prof/commit/a151a513373563ed8fa7f8e56193138d3ee9b5e3
Warnings.ignore(/TestProf cops require RuboCop >= 0.51.0 to run/) do
# All this file does is check the RuboCop version and require the files below.
# If we don't require this now while the warning is ignored, we'll see the warning again later
# when RuboCop requires the file.
require "test_prof/rubocop"
# This is copied from test-prof/rubocop.rb, and is necessary because that file returns early if the RuboCop version
# check isn't met.
require "test_prof/cops/plugin"
require "test_prof/cops/rspec/aggregate_examples"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/svn.rb | Library/Homebrew/utils/svn.rb | # typed: strict
# frozen_string_literal: true
require "system_command"
require "utils/output"
module Utils
# Helper functions for querying SVN information.
module Svn
class << self
include SystemCommand::Mixin
include Utils::Output::Mixin
sig { returns(T::Boolean) }
def available?
version.present?
end
sig { returns(T.nilable(String)) }
def version
return @version if defined?(@version)
stdout, _, status = system_command(HOMEBREW_SHIMS_PATH/"shared/svn", args: ["--version"],
print_stderr: false).to_a
@version = T.let(status.success? ? stdout.chomp[/svn, version (\d+(?:\.\d+)*)/, 1] : nil, T.nilable(String))
end
sig { params(url: String).returns(T::Boolean) }
def remote_exists?(url)
return true unless available?
args = ["ls", url, "--depth", "empty"]
_, stderr, status = system_command("svn", args:, print_stderr: false).to_a
return !!status.success? unless stderr.include?("certificate verification failed")
# OK to unconditionally trust here because we're just checking if a URL exists.
system_command("svn", args: args.concat(invalid_cert_flags), print_stderr: false).success?
end
sig { returns(T::Array[String]) }
def invalid_cert_flags
opoo "Ignoring Subversion certificate errors!"
args = ["--non-interactive", "--trust-server-cert"]
if Version.new(version || "-1") >= Version.new("1.9")
args << "--trust-server-cert-failures=expired,not-yet-valid"
end
args
end
sig { void }
def clear_version_cache
remove_instance_variable(:@version) if defined?(@version)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/gzip.rb | Library/Homebrew/utils/gzip.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Utils
# Helper functions for creating gzip files.
module Gzip
extend ::Utils::Output::Mixin
# Apple's gzip also uses zlib so use the same buffer size here.
# https://github.com/apple-oss-distributions/file_cmds/blob/file_cmds-400/gzip/gzip.c#L147
GZIP_BUFFER_SIZE = T.let(64 * 1024, Integer)
sig {
params(
path: T.any(String, Pathname),
mtime: T.any(Integer, Time),
orig_name: String,
output: T.any(String, Pathname),
).returns(Pathname)
}
def self.compress_with_options(path, mtime: ENV["SOURCE_DATE_EPOCH"].to_i, orig_name: File.basename(path),
output: "#{path}.gz")
# There are two problems if `mtime` is less than or equal to 0:
#
# 1. Ideally, we would just set mtime = 0 if SOURCE_DATE_EPOCH is absent, but Ruby's
# Zlib::GzipWriter does not properly handle the case of setting mtime = 0:
# https://bugs.ruby-lang.org/issues/16285
#
# This was fixed in https://github.com/ruby/zlib/pull/10. This workaround
# won't be needed once we are using zlib gem version 1.1.0 or newer.
#
# 2. If mtime is less than 0, gzip may fail to cast a negative number to an unsigned int
# https://github.com/Homebrew/homebrew-core/pull/246155#issuecomment-3345772366
if mtime.to_i <= 0
odebug "Setting `mtime = 1` to avoid zlib gem bug and unsigned integer cast when `mtime <= 0`."
mtime = 1
end
File.open(path, "rb") do |fp|
odebug "Creating gzip file at #{output}"
gz = Zlib::GzipWriter.open(output)
gz.mtime = mtime
gz.orig_name = orig_name
gz.write(fp.read(GZIP_BUFFER_SIZE)) until fp.eof?
ensure
# GzipWriter should be closed in case of error as well
gz.close
end
FileUtils.rm_f path
Pathname.new(output)
end
sig {
params(
paths: T.any(String, Pathname),
reproducible: T::Boolean,
mtime: T.any(Integer, Time),
).returns(T::Array[Pathname])
}
def self.compress(*paths, reproducible: true, mtime: ENV["SOURCE_DATE_EPOCH"].to_i)
if reproducible
paths.map do |path|
compress_with_options(path, mtime:)
end
else
paths.map do |path|
safe_system "gzip", path
Pathname.new("#{path}.gz")
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/spdx.rb | Library/Homebrew/utils/spdx.rb | # typed: strict
# frozen_string_literal: true
require "utils/curl"
require "utils/github"
# Helper module for updating SPDX license data.
module SPDX
module_function
DATA_PATH = T.let((HOMEBREW_DATA_PATH/"spdx").freeze, Pathname)
API_URL = "https://api.github.com/repos/spdx/license-list-data/releases/latest"
LICENSEREF_PREFIX = "LicenseRef-Homebrew-"
ALLOWED_LICENSE_SYMBOLS = [
:public_domain,
:cannot_represent,
].freeze
sig { returns(T::Hash[String, T.untyped]) }
def license_data
@license_data ||= T.let(JSON.parse((DATA_PATH/"spdx_licenses.json").read), T.nilable(T::Hash[String, T.untyped]))
end
sig { returns(T::Hash[String, T.untyped]) }
def exception_data
@exception_data ||= T.let(JSON.parse((DATA_PATH/"spdx_exceptions.json").read),
T.nilable(T::Hash[String, T.untyped]))
end
sig { returns(String) }
def latest_tag
@latest_tag ||= T.let(GitHub::API.open_rest(API_URL)["tag_name"], T.nilable(String))
end
sig { params(to: Pathname).void }
def download_latest_license_data!(to: DATA_PATH)
data_url = "https://raw.githubusercontent.com/spdx/license-list-data/refs/tags/#{latest_tag}/json/"
Utils::Curl.curl_download("#{data_url}licenses.json", to: to/"spdx_licenses.json")
Utils::Curl.curl_download("#{data_url}exceptions.json", to: to/"spdx_exceptions.json")
end
sig {
params(
license_expression: T.any(
String,
Symbol,
T::Hash[T.any(Symbol, String), T.untyped],
T::Array[String],
),
).returns(
[
T::Array[T.any(String, Symbol)], T::Array[String]
],
)
}
def parse_license_expression(license_expression)
licenses = T.let([], T::Array[T.any(String, Symbol)])
exceptions = T.let([], T::Array[String])
case license_expression
when String, Symbol
licenses.push license_expression
when Hash, Array
if license_expression.is_a? Hash
license_expression = license_expression.filter_map do |key, value|
if key.is_a? String
licenses.push key
exceptions.push value[:with]
next
end
value
end
end
license_expression.each do |license|
sub_license, sub_exception = parse_license_expression license
licenses += sub_license
exceptions += sub_exception
end
end
[licenses, exceptions]
end
sig { params(license: T.any(String, Symbol)).returns(T::Boolean) }
def valid_license?(license)
return ALLOWED_LICENSE_SYMBOLS.include? license if license.is_a? Symbol
license = license.delete_suffix "+"
license_data["licenses"].any? { |spdx_license| spdx_license["licenseId"].downcase == license.downcase }
end
sig { params(license: T.any(String, Symbol)).returns(T::Boolean) }
def deprecated_license?(license)
return false if ALLOWED_LICENSE_SYMBOLS.include? license
return false unless valid_license?(license)
license = license.to_s.delete_suffix "+"
license_data["licenses"].none? do |spdx_license|
spdx_license["licenseId"].downcase == license.downcase && !spdx_license["isDeprecatedLicenseId"]
end
end
sig { params(exception: String).returns(T::Boolean) }
def valid_license_exception?(exception)
exception_data["exceptions"].any? do |spdx_exception|
spdx_exception["licenseExceptionId"].downcase == exception.downcase && !spdx_exception["isDeprecatedLicenseId"]
end
end
sig {
params(
license_expression: T.any(String, Symbol, T::Hash[T.nilable(T.any(Symbol, String)), T.untyped]),
bracket: T::Boolean,
hash_type: T.nilable(T.any(String, Symbol)),
).returns(T.nilable(String))
}
def license_expression_to_string(license_expression, bracket: false, hash_type: nil)
case license_expression
when String
license_expression
when Symbol
LICENSEREF_PREFIX + license_expression.to_s.tr("_", "-")
when Hash
expressions = []
if license_expression.keys.length == 1
hash_type = license_expression.keys.first
if hash_type.is_a? String
expressions.push "#{hash_type} WITH #{license_expression[hash_type][:with]}"
else
expressions += license_expression[hash_type].map do |license|
license_expression_to_string license, bracket: true, hash_type:
end
end
else
bracket = false
license_expression.each do |expression|
expressions.push license_expression_to_string([expression].to_h, bracket: true)
end
end
operator = if hash_type == :any_of
" OR "
else
" AND "
end
if bracket
"(#{expressions.join operator})"
else
expressions.join operator
end
end
end
LicenseExpression = T.type_alias do
T.any(
String,
Symbol,
T::Hash[T.any(String, Symbol), T.anything],
)
end
sig { params(string: T.nilable(String)).returns(T.nilable(LicenseExpression)) }
def string_to_license_expression(string)
return if string.blank?
result = string
result_type = nil
and_parts = string.split(/ and (?![^(]*\))/i)
if and_parts.length > 1
result = and_parts
result_type = :all_of
else
or_parts = string.split(/ or (?![^(]*\))/i)
if or_parts.length > 1
result = or_parts
result_type = :any_of
end
end
if result_type
result.map! do |part|
part = part[1..-2] if part[0] == "(" && part[-1] == ")"
string_to_license_expression(part)
end
{ result_type => result }
else
with_parts = string.split(/ with /i, 2)
if with_parts.length > 1
{ with_parts.first => { with: with_parts.second } }
else
return result unless result.start_with?(LICENSEREF_PREFIX)
license_sym = result.delete_prefix(LICENSEREF_PREFIX).downcase.tr("-", "_").to_sym
ALLOWED_LICENSE_SYMBOLS.include?(license_sym) ? license_sym : result
end
end
end
sig {
params(
license: T.any(String, Symbol),
).returns(
T.any(
[T.any(String, Symbol)],
[String, T.nilable(String), T::Boolean],
),
)
}
def license_version_info(license)
return [license] if ALLOWED_LICENSE_SYMBOLS.include? license
match = license.match(/-(?<version>[0-9.]+)(?:-.*?)??(?<or_later>\+|-only|-or-later)?$/)
return [license] if match.blank?
license_name = license.to_s.split(match[0].to_s).first
or_later = match["or_later"].present? && %w[+ -or-later].include?(match["or_later"])
# [name, version, later versions allowed?]
# e.g. GPL-2.0-or-later --> ["GPL", "2.0", true]
[license_name, match["version"], or_later]
end
sig {
params(license_expression: T.any(String, Symbol, T::Hash[T.any(Symbol, String), T.untyped]),
forbidden_licenses: T::Hash[T.any(Symbol, String), T.untyped]).returns(T::Boolean)
}
def licenses_forbid_installation?(license_expression, forbidden_licenses)
case license_expression
when String, Symbol
forbidden_licenses_include? license_expression, forbidden_licenses
when Hash
key = license_expression.keys.first
return false if key.nil?
case key
when :any_of
license_expression[key].all? { |license| licenses_forbid_installation? license, forbidden_licenses }
when :all_of
license_expression[key].any? { |license| licenses_forbid_installation? license, forbidden_licenses }
else
forbidden_licenses_include? key, forbidden_licenses
end
end
end
sig {
params(
license: T.any(Symbol, String),
forbidden_licenses: T::Hash[T.any(Symbol, String), T.untyped],
).returns(T::Boolean)
}
def forbidden_licenses_include?(license, forbidden_licenses)
return true if forbidden_licenses.key? license
name, version, = license_version_info license
forbidden_licenses.each_value do |license_info|
forbidden_name, forbidden_version, forbidden_or_later = *license_info
next if forbidden_name != name
return true if forbidden_or_later && forbidden_version <= version
return true if forbidden_version == version
end
false
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/topological_hash.rb | Library/Homebrew/utils/topological_hash.rb | # typed: strict
# frozen_string_literal: true
require "tsort"
module Utils
# Topologically sortable hash map.
class TopologicalHash < Hash
extend T::Generic
include TSort
CaskOrFormula = T.type_alias { T.any(Cask::Cask, Formula) }
K = type_member { { fixed: CaskOrFormula } }
V = type_member { { fixed: T::Array[CaskOrFormula] } }
Elem = type_member(:out) { { fixed: [CaskOrFormula, T::Array[CaskOrFormula]] } }
sig {
params(
packages: T.any(CaskOrFormula, T::Array[CaskOrFormula]),
accumulator: TopologicalHash,
).returns(TopologicalHash)
}
def self.graph_package_dependencies(packages, accumulator = TopologicalHash.new)
packages = Array(packages)
packages.each do |cask_or_formula|
next if accumulator.key?(cask_or_formula)
case cask_or_formula
when Cask::Cask
formula_deps = cask_or_formula.depends_on
.formula
.map { |f| Formula[f] }
cask_deps = cask_or_formula.depends_on
.cask
.map { |c| Cask::CaskLoader.load(c, config: nil) }
when Formula
formula_deps = cask_or_formula.deps
.reject(&:build?)
.reject(&:test?)
.map(&:to_formula)
cask_deps = cask_or_formula.requirements
.filter_map(&:cask)
.map { |c| Cask::CaskLoader.load(c, config: nil) }
else
T.absurd(cask_or_formula)
end
accumulator[cask_or_formula] = formula_deps + cask_deps
graph_package_dependencies(formula_deps, accumulator)
graph_package_dependencies(cask_deps, accumulator)
end
accumulator
end
private
sig { params(block: T.proc.params(arg0: K).void).void }
def tsort_each_node(&block)
each_key(&block)
end
sig { params(node: K, block: T.proc.params(arg0: CaskOrFormula).void).returns(V) }
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/pid_path.rb | Library/Homebrew/utils/pid_path.rb | #!/usr/bin/env ruby
# typed: strict
# frozen_string_literal: true
pid = ARGV[0]&.to_i
raise "Missing `pid` argument!" unless pid
require "fiddle"
# Canonically, this is a part of libproc.dylib. libproc is however just a symlink to libSystem
# and some security tools seem to not support aliases from the dyld shared cache and incorrectly flag this.
libproc = Fiddle.dlopen("/usr/lib/libSystem.B.dylib")
libproc_proc_pidpath_function = Fiddle::Function.new(
libproc["proc_pidpath"],
[Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP, Fiddle::TYPE_UINT32_T],
Fiddle::TYPE_INT,
)
# We have to allocate a (char) buffer of exactly `PROC_PIDPATHINFO_MAXSIZE` to use `proc_pidpath`
# From `include/sys/proc_info.h`, PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN
# From `include/sys/param.h`, MAXPATHLEN = PATH_MAX
# From `include/sys/syslimits.h`, PATH_MAX = 1024
# https://github.com/apple-oss-distributions/xnu/blob/e3723e1f17661b24996789d8afc084c0c3303b26/libsyscall/wrappers/libproc/libproc.c#L268-L275
buffer_size = 4 * 1024 # PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN
buffer = "\0" * buffer_size
pointer_to_buffer = Fiddle::Pointer.to_ptr(buffer)
# `proc_pidpath` returns a positive value on success. See:
# https://stackoverflow.com/a/8149198
# https://github.com/chromium/chromium/blob/86df41504a235f9369f6f53887da12a718a19db4/base/process/process_handle_mac.cc#L37-L44
# https://github.com/apple-oss-distributions/xnu/blob/e3723e1f17661b24996789d8afc084c0c3303b26/libsyscall/wrappers/libproc/libproc.c#L263-L283
return_value = libproc_proc_pidpath_function.call(pid, pointer_to_buffer, buffer_size)
raise "Call to `proc_pidpath` failed! `proc_pidpath` returned #{return_value}." unless return_value.positive?
puts pointer_to_buffer.to_s.strip
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/shell.rb | Library/Homebrew/utils/shell.rb | # typed: strict
# frozen_string_literal: true
module Utils
module Shell
extend T::Helpers
requires_ancestor { Kernel }
module_function
# Take a path and heuristically convert it to a shell name,
# return `nil` if there's no match.
sig { params(path: String).returns(T.nilable(Symbol)) }
def from_path(path)
# we only care about the basename
shell_name = File.basename(path)
# handle possible version suffix like `zsh-5.2`
shell_name.sub!(/-.*\z/m, "")
shell_name.to_sym if %w[bash csh fish ksh mksh pwsh rc sh tcsh zsh].include?(shell_name)
end
sig { params(default: String).returns(String) }
def preferred_path(default: "")
ENV.fetch("SHELL", default)
end
sig { returns(T.nilable(Symbol)) }
def preferred
from_path(preferred_path)
end
sig { returns(T.nilable(Symbol)) }
def parent
from_path(`ps -p #{Process.ppid} -o ucomm=`.strip)
end
# Quote values. Quoting keys is overkill.
sig { params(key: String, value: String, shell: T.nilable(Symbol)).returns(T.nilable(String)) }
def export_value(key, value, shell = preferred)
case shell
when :bash, :ksh, :mksh, :sh, :zsh
"export #{key}=\"#{sh_quote(value)}\""
when :fish
# fish quoting is mostly Bourne compatible except that
# a single quote can be included in a single-quoted string via \'
# and a literal \ can be included via \\
"set -gx #{key} \"#{sh_quote(value)}\""
when :rc
"#{key}=(#{sh_quote(value)})"
when :csh, :tcsh
"setenv #{key} #{csh_quote(value)};"
end
end
# Return the shell profile file based on user's preferred shell.
sig { returns(String) }
def profile
case preferred
when :bash
bash_profile = "#{Dir.home}/.bash_profile"
return bash_profile if File.exist? bash_profile
when :pwsh
pwsh_profile = "#{Dir.home}/.config/powershell/Microsoft.PowerShell_profile.ps1"
return pwsh_profile if File.exist? pwsh_profile
when :rc
rc_profile = "#{Dir.home}/.rcrc"
return rc_profile if File.exist? rc_profile
when :zsh
return "#{ENV["HOMEBREW_ZDOTDIR"]}/.zshrc" if ENV["HOMEBREW_ZDOTDIR"].present?
end
shell = preferred
return "~/.profile" if shell.nil?
SHELL_PROFILE_MAP.fetch(shell, "~/.profile")
end
sig { params(variable: String, value: String).returns(T.nilable(String)) }
def set_variable_in_profile(variable, value)
case preferred
when :bash, :ksh, :sh, :zsh, nil
"echo 'export #{variable}=#{sh_quote(value)}' >> #{profile}"
when :pwsh
"$env:#{variable}='#{value}' >> #{profile}"
when :rc
"echo '#{variable}=(#{sh_quote(value)})' >> #{profile}"
when :csh, :tcsh
"echo 'setenv #{variable} #{csh_quote(value)}' >> #{profile}"
when :fish
"echo 'set -gx #{variable} #{sh_quote(value)}' >> #{profile}"
end
end
sig { params(path: String).returns(T.nilable(String)) }
def prepend_path_in_profile(path)
case preferred
when :bash, :ksh, :mksh, :sh, :zsh, nil
"echo 'export PATH=\"#{sh_quote(path)}:$PATH\"' >> #{profile}"
when :pwsh
"$env:PATH = '#{path}' + \":${env:PATH}\" >> #{profile}"
when :rc
"echo 'path=(#{sh_quote(path)} $path)' >> #{profile}"
when :csh, :tcsh
"echo 'setenv PATH #{csh_quote(path)}:$PATH' >> #{profile}"
when :fish
"fish_add_path #{sh_quote(path)}"
end
end
SHELL_PROFILE_MAP = T.let(
{
bash: "~/.profile",
csh: "~/.cshrc",
fish: "~/.config/fish/config.fish",
ksh: "~/.kshrc",
mksh: "~/.kshrc",
pwsh: "~/.config/powershell/Microsoft.PowerShell_profile.ps1",
rc: "~/.rcrc",
sh: "~/.profile",
tcsh: "~/.tcshrc",
zsh: "~/.zshrc",
}.freeze,
T::Hash[Symbol, String],
)
UNSAFE_SHELL_CHAR = %r{([^A-Za-z0-9_\-.,:/@~+\n])}
sig { params(str: String).returns(String) }
def csh_quote(str)
# Ruby's implementation of `shell_escape`.
str = str.to_s
return "''" if str.empty?
str = str.dup
# Anything that isn't a known safe character is padded.
str.gsub!(UNSAFE_SHELL_CHAR, "\\\\" + "\\1") # rubocop:disable Style/StringConcatenation
# Newlines have to be specially quoted in `csh`.
str.gsub!("\n", "'\\\n'")
str
end
sig { params(str: String).returns(String) }
def sh_quote(str)
# Ruby's implementation of `shell_escape`.
str = str.to_s
return "''" if str.empty?
str = str.dup
# Anything that isn't a known safe character is padded.
str.gsub!(UNSAFE_SHELL_CHAR, "\\\\" + "\\1") # rubocop:disable Style/StringConcatenation
str.gsub!("\n", "'\n'")
str
end
sig { params(type: String, preferred_path: String, notice: T.nilable(String), home: String).returns(String) }
def shell_with_prompt(type, preferred_path:, notice:, home: Dir.home)
preferred = from_path(preferred_path)
path = ENV.fetch("PATH")
subshell = case preferred
when :zsh
zdotdir = Pathname.new(HOMEBREW_TEMP/"brew-zsh-prompt-#{Process.euid}")
zdotdir.mkpath
FileUtils.chmod_R(0700, zdotdir)
FileUtils.cp(HOMEBREW_LIBRARY_PATH/"utils/zsh/brew-sh-prompt-zshrc.zsh", zdotdir/".zshrc")
%w[.zshenv .zcompdump .zsh_history .zsh_sessions].each do |file|
FileUtils.ln_sf("#{home}/#{file}", zdotdir/file)
end
<<~ZSH.strip
BREW_PROMPT_PATH="#{path}" BREW_PROMPT_TYPE="#{type}" ZDOTDIR="#{zdotdir}" #{preferred_path}
ZSH
when :bash
<<~BASH.strip
BREW_PROMPT_PATH="#{path}" BREW_PROMPT_TYPE="#{type}" #{preferred_path} --rcfile "#{HOMEBREW_LIBRARY_PATH}/utils/bash/brew-sh-prompt-bashrc.bash"
BASH
else
"PS1=\"\\[\\033[1;32m\\]#{type} \\[\\033[1;31m\\]\\w \\[\\033[1;34m\\]$\\[\\033[0m\\] \" #{preferred_path}"
end
puts notice if notice.present?
$stdout.flush
subshell
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/service.rb | Library/Homebrew/utils/service.rb | # typed: strict
# frozen_string_literal: true
module Utils
# Helpers for `brew services` related code.
module Service
# Check if a service is running for a specified formula.
sig { params(formula: Formula).returns(T::Boolean) }
def self.running?(formula)
if launchctl?
quiet_system(launchctl, "list", formula.plist_name)
elsif systemctl?
quiet_system(systemctl, "is-active", "--quiet", formula.service_name)
else
false
end
end
# Check if a service file is installed in the expected location.
sig { params(formula: Formula).returns(T::Boolean) }
def self.installed?(formula)
(launchctl? && formula.launchd_service_path.exist?) ||
(systemctl? && formula.systemd_service_path.exist?)
end
# Path to launchctl binary.
sig { returns(T.nilable(Pathname)) }
def self.launchctl
return @launchctl if defined? @launchctl
return if ENV["HOMEBREW_TEST_GENERIC_OS"]
@launchctl = T.let(which("launchctl"), T.nilable(Pathname))
end
# Path to systemctl binary.
sig { returns(T.nilable(Pathname)) }
def self.systemctl
return @systemctl if defined? @systemctl
return if ENV["HOMEBREW_TEST_GENERIC_OS"]
@systemctl = T.let(which("systemctl"), T.nilable(Pathname))
end
sig { returns(T::Boolean) }
def self.launchctl?
!launchctl.nil?
end
sig { returns(T::Boolean) }
def self.systemctl?
!systemctl.nil?
end
# Quote a string for use in systemd command lines, e.g., in `ExecStart`.
# https://www.freedesktop.org/software/systemd/man/latest/systemd.syntax.html#Quoting
sig { params(str: String).returns(String) }
def self.systemd_quote(str)
result = +"\""
# No need to escape single quotes and spaces, as we're always double
# quoting the entire string.
str.each_char do |char|
result << case char
when "\a" then "\\a"
when "\b" then "\\b"
when "\f" then "\\f"
when "\n" then "\\n"
when "\r" then "\\r"
when "\t" then "\\t"
when "\v" then "\\v"
when "\\" then "\\\\"
when "\"" then "\\\""
else char
end
end
result << "\""
result.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/cpan.rb | Library/Homebrew/utils/cpan.rb | # typed: strict
# frozen_string_literal: true
require "utils/inreplace"
require "utils/output"
# Helper functions for updating CPAN resources.
module CPAN
METACPAN_URL_PREFIX = "https://cpan.metacpan.org/authors/id/"
CPAN_ARCHIVE_REGEX = /^(.+)-([0-9.v]+)\.(?:tar\.gz|tgz)$/
private_constant :METACPAN_URL_PREFIX, :CPAN_ARCHIVE_REGEX
extend Utils::Output::Mixin
# Represents a Perl package from an existing resource.
class Package
sig { params(resource_name: String, resource_url: String).void }
def initialize(resource_name, resource_url)
@cpan_info = T.let(nil, T.nilable(T::Array[String]))
@resource_name = resource_name
@resource_url = resource_url
@is_cpan_url = T.let(resource_url.start_with?(METACPAN_URL_PREFIX), T::Boolean)
end
sig { returns(String) }
def name
@resource_name
end
sig { returns(T.nilable(String)) }
def current_version
extract_version_from_url if @current_version.blank?
@current_version
end
sig { returns(T::Boolean) }
def valid_cpan_package?
@is_cpan_url
end
# Get latest release information from MetaCPAN API.
sig { returns(T.nilable(T::Array[String])) }
def latest_cpan_info
return @cpan_info if @cpan_info.present?
return unless valid_cpan_package?
metadata_url = "https://fastapi.metacpan.org/v1/download_url/#{@resource_name}"
result = Utils::Curl.curl_output(metadata_url, "--location", "--fail")
return unless result.status.success?
begin
json = JSON.parse(result.stdout)
rescue JSON::ParserError
return
end
download_url = json["download_url"]
return unless download_url
checksum = json["checksum_sha256"]
return unless checksum
@cpan_info = [@resource_name, download_url, checksum, json["version"]]
end
sig { returns(String) }
def to_s
@resource_name
end
private
sig { returns(T.nilable(String)) }
def extract_version_from_url
return unless @is_cpan_url
match = File.basename(@resource_url).match(CPAN_ARCHIVE_REGEX)
return unless match
@current_version = T.let(match[2], T.nilable(String))
end
end
# Update CPAN resources in a formula.
sig {
params(
formula: Formula,
print_only: T.nilable(T::Boolean),
silent: T.nilable(T::Boolean),
verbose: T.nilable(T::Boolean),
ignore_errors: T.nilable(T::Boolean),
).returns(T.nilable(T::Boolean))
}
def self.update_perl_resources!(formula, print_only: false, silent: false, verbose: false, ignore_errors: false)
cpan_resources = formula.resources.select { |resource| resource.url.start_with?(METACPAN_URL_PREFIX) }
odie "\"#{formula.name}\" has no CPAN resources to update." if cpan_resources.empty?
show_info = !print_only && !silent
non_cpan_resources = formula.resources.reject { |resource| resource.url.start_with?(METACPAN_URL_PREFIX) }
ohai "Skipping #{non_cpan_resources.length} non-CPAN resources" if non_cpan_resources.any? && show_info
ohai "Found #{cpan_resources.length} CPAN resources to update" if show_info
new_resource_blocks = ""
package_errors = ""
updated_count = 0
cpan_resources.each do |resource|
package = Package.new(resource.name, resource.url)
unless package.valid_cpan_package?
if ignore_errors
package_errors += " # RESOURCE-ERROR: \"#{resource.name}\" is not a valid CPAN resource\n"
next
else
odie "\"#{resource.name}\" is not a valid CPAN resource"
end
end
ohai "Checking \"#{resource.name}\" for updates..." if show_info
info = package.latest_cpan_info
unless info
if ignore_errors
package_errors += " # RESOURCE-ERROR: Unable to resolve \"#{resource.name}\"\n"
next
else
odie "Unable to resolve \"#{resource.name}\""
end
end
name, url, checksum, new_version = info
current_version = package.current_version
if current_version && new_version && current_version != new_version
ohai "\"#{resource.name}\": #{current_version} -> #{new_version}" if show_info
updated_count += 1
elsif show_info
ohai "\"#{resource.name}\": already up to date (#{current_version})" if current_version
end
new_resource_blocks += <<-EOS
resource "#{name}" do
url "#{url}"
sha256 "#{checksum}"
end
EOS
end
package_errors += "\n" if package_errors.present?
resource_section = "#{package_errors}#{new_resource_blocks}"
if print_only
puts resource_section.chomp
return true
end
if formula.resources.all? { |resource| resource.name.start_with?("homebrew-") }
inreplace_regex = / def install/
resource_section += " def install"
else
inreplace_regex = /
\ \ (
(\#\ RESOURCE-ERROR:\ .*\s+)*
resource\ .*\ do\s+
url\ .*\s+
sha256\ .*\s+
((\#.*\s+)*
patch\ (.*\ )?do\s+
url\ .*\s+
sha256\ .*\s+
end\s+)*
end\s+)+
/x
resource_section += " "
end
ohai "Updating resource blocks" unless silent
Utils::Inreplace.inreplace formula.path do |s|
if s.inreplace_string.split(/^ test do\b/, 2).fetch(0).scan(inreplace_regex).length > 1
odie "Unable to update resource blocks for \"#{formula.name}\" automatically. Please update them manually."
end
s.sub! inreplace_regex, resource_section
end
if package_errors.present?
ofail "Unable to resolve some dependencies. Please check #{formula.path} for RESOURCE-ERROR comments."
elsif updated_count.positive?
ohai "Updated #{updated_count} CPAN resource#{"s" if updated_count != 1}" unless silent
end
true
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/formatter.rb | Library/Homebrew/utils/formatter.rb | # typed: strict
# frozen_string_literal: true
require "utils/tty"
# Helper module for formatting output.
#
# @api internal
module Formatter
COMMAND_DESC_WIDTH = 80
OPTION_DESC_WIDTH = 45
sig { params(string: String, color: T.nilable(Symbol)).returns(String) }
def self.arrow(string, color: nil)
prefix("==>", string, color)
end
# Format a string as headline.
#
# @api internal
sig { params(string: String, color: T.nilable(Symbol)).returns(String) }
def self.headline(string, color: nil)
arrow("#{Tty.bold}#{string}#{Tty.reset}", color:)
end
sig { params(string: Object).returns(String) }
def self.identifier(string)
"#{Tty.green}#{string}#{Tty.default}"
end
sig { params(string: String).returns(String) }
def self.bold(string)
"#{Tty.bold}#{string}#{Tty.reset}"
end
sig { params(string: String).returns(String) }
def self.option(string)
bold(string)
end
# Format a string as success, with an optional label.
#
# @api internal
sig { params(string: String, label: T.nilable(String)).returns(String) }
def self.success(string, label: nil)
label(label, string, :green)
end
# Format a string as warning, with an optional label.
#
# @api internal
sig { params(string: T.any(String, Exception), label: T.nilable(String)).returns(String) }
def self.warning(string, label: nil)
label(label, string, :yellow)
end
# Format a string as error, with an optional label.
#
# @api internal
sig { params(string: T.any(String, Exception), label: T.nilable(String)).returns(String) }
def self.error(string, label: nil)
label(label, string, :red)
end
# Truncate a string to a specific length.
#
# @api internal
sig { params(string: String, max: Integer, omission: String).returns(String) }
def self.truncate(string, max: 30, omission: "...")
return string if string.length <= max
length_with_room_for_omission = max - omission.length
truncated = string[0, length_with_room_for_omission]
"#{truncated}#{omission}"
end
# Wraps text to fit within a given number of columns using regular expressions that:
#
# 1. convert hard-wrapped paragraphs to a single line
# 2. add line break and indent to subcommand descriptions
# 3. find any option descriptions longer than a pre-set length and wrap between words
# with a hanging indent, without breaking any words that overflow
# 4. wrap any remaining description lines that need wrapping with the same indent
# 5. wrap all lines to the given width.
#
# Note that an option (e.g. `--foo`) may not be at the beginning of a line,
# so we always wrap one word before an option.
# @see https://github.com/Homebrew/brew/pull/12672
# @see https://macromates.com/blog/2006/wrapping-text-with-regular-expressions/
sig { params(string: String, width: Integer).returns(String) }
def self.format_help_text(string, width: 172)
desc = OPTION_DESC_WIDTH
indent = width - desc
string.gsub(/(?<=\S) *\n(?=\S)/, " ")
.gsub(/([`>)\]]:) /, "\\1\n ")
.gsub(/^( +-.+ +(?=\S.{#{desc}}))(.{1,#{desc}})( +|$)(?!-)\n?/, "\\1\\2\n#{" " * indent}")
.gsub(/^( {#{indent}}(?=\S.{#{desc}}))(.{1,#{desc}})( +|$)(?!-)\n?/, "\\1\\2\n#{" " * indent}")
.gsub(/(.{1,#{width}})( +|$)(?!-)\n?/, "\\1\n")
end
sig { params(string: T.nilable(T.any(String, URI::Generic))).returns(String) }
def self.url(string)
"#{Tty.underline}#{string}#{Tty.no_underline}"
end
sig { params(label: T.nilable(String), string: T.any(String, Exception), color: Symbol).returns(String) }
def self.label(label, string, color)
label = "#{label}:" unless label.nil?
prefix(label, string, color)
end
private_class_method :label
sig {
params(prefix: T.nilable(String), string: T.any(String, Exception), color: T.nilable(Symbol)).returns(String)
}
def self.prefix(prefix, string, color)
if prefix.nil? && color.nil?
string.to_s
elsif prefix.nil?
"#{Tty.send(T.must(color))}#{string}#{Tty.reset}"
elsif color.nil?
"#{prefix} #{string}"
else
"#{Tty.send(color)}#{prefix}#{Tty.reset} #{string}"
end
end
private_class_method :prefix
# Layout objects in columns that fit the current terminal width.
#
# @api internal
sig { params(objects: T::Array[String], gap_size: Integer).returns(String) }
def self.columns(objects, gap_size: 2)
objects = objects.flatten.map(&:to_s)
fallback = proc do
return objects.join("\n").concat("\n")
end
fallback.call if objects.empty?
fallback.call if respond_to?(:tty?) ? !T.unsafe(self).tty? : !$stdout.tty?
console_width = Tty.width
object_lengths = objects.map { |obj| Tty.strip_ansi(obj).length }
cols = (console_width + gap_size) / (T.must(object_lengths.max) + gap_size)
fallback.call if cols < 2
rows = (objects.count + cols - 1) / cols
cols = (objects.count + rows - 1) / rows # avoid empty trailing columns
col_width = ((console_width + gap_size) / cols) - gap_size
gap_string = "".rjust(gap_size)
output = +""
rows.times do |row_index|
item_indices_for_row = T.cast(row_index.step(objects.size - 1, rows).to_a, T::Array[Integer])
first_n = T.must(item_indices_for_row[0...-1]).map do |index|
objects.fetch(index) + "".rjust(col_width - object_lengths.fetch(index))
end
# don't add trailing whitespace to last column
last = objects.values_at(item_indices_for_row.fetch(-1))
output.concat((first_n + last)
.join(gap_string))
.concat("\n")
end
output.freeze
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/timer.rb | Library/Homebrew/utils/timer.rb | # typed: strong
# frozen_string_literal: true
module Utils
module Timer
sig { params(time: T.nilable(Time)).returns(T.nilable(T.any(Float, Integer))) }
def self.remaining(time)
return unless time
[0, time - Time.now].max
end
sig { params(time: T.nilable(Time)).returns(T.nilable(T.any(Float, Integer))) }
def self.remaining!(time)
r = remaining(time)
raise Timeout::Error if r && r <= 0
r
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/ruby_check_version_script.rb | Library/Homebrew/utils/ruby_check_version_script.rb | #!/usr/bin/env ruby
# typed: true
# frozen_string_literal: true
HOMEBREW_REQUIRED_RUBY_VERSION = ARGV.first.freeze
raise "No Ruby version passed!" if HOMEBREW_REQUIRED_RUBY_VERSION.to_s.empty?
require "rubygems"
ruby_version = Gem::Version.new(RUBY_VERSION)
homebrew_required_ruby_version = Gem::Version.new(HOMEBREW_REQUIRED_RUBY_VERSION)
ruby_version_major, ruby_version_minor, = ruby_version.canonical_segments
homebrew_required_ruby_version_major, homebrew_required_ruby_version_minor, =
homebrew_required_ruby_version.canonical_segments
if (!ENV.fetch("HOMEBREW_DEVELOPER", "").empty? || !ENV.fetch("HOMEBREW_TESTS", "").empty?) &&
!ENV.fetch("HOMEBREW_USE_RUBY_FROM_PATH", "").empty? &&
ruby_version >= homebrew_required_ruby_version
return
elsif ruby_version_major != homebrew_required_ruby_version_major ||
ruby_version_minor != homebrew_required_ruby_version_minor
abort
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/analytics.rb | Library/Homebrew/utils/analytics.rb | # typed: strict
# frozen_string_literal: true
require "context"
require "erb"
require "settings"
require "cachable"
require "utils/output"
module Utils
# Helper module for fetching and reporting analytics data.
module Analytics
INFLUX_BUCKET = "analytics"
INFLUX_TOKEN = "iVdsgJ_OjvTYGAA79gOfWlA_fX0QCuj4eYUNdb-qVUTrC3tp3JTWCADVNE9HxV0kp2ZjIK9tuthy_teX4szr9A=="
INFLUX_HOST = "https://eu-central-1-1.aws.cloud2.influxdata.com"
INFLUX_ORG = "d81a3e6d582d485f"
extend Utils::Output::Mixin
extend Cachable
class << self
include Context
sig {
params(measurement: Symbol,
tags: T::Hash[Symbol, T.any(T::Boolean, String)],
fields: T::Hash[Symbol, T.any(T::Boolean, String)]).void
}
def report_influx(measurement, tags, fields)
return if not_this_run? || disabled?
# Tags are always implicitly strings and must have low cardinality.
tags_string = tags.map { |k, v| "#{k}=#{v}" }
.join(",")
# Fields need explicitly wrapped with quotes and can have high cardinality.
fields_string = fields.compact
.map { |k, v| %Q(#{k}="#{v}") }
.join(",")
args = [
"--max-time", "3",
"--header", "Authorization: Token #{INFLUX_TOKEN}",
"--header", "Content-Type: text/plain; charset=utf-8",
"--header", "Accept: application/json",
"--data-binary", "#{measurement},#{tags_string} #{fields_string} #{Time.now.to_i}"
]
# Second precision is highest we can do and has the lowest performance cost.
url = "#{INFLUX_HOST}/api/v2/write?bucket=#{INFLUX_BUCKET}&precision=s"
deferred_curl(url, args)
end
sig { params(url: String, args: T::Array[String]).void }
def deferred_curl(url, args)
require "utils/curl"
curl = Utils::Curl.curl_executable
args = Utils::Curl.curl_args(*args, "--silent", "--output", File::NULL, show_error: false)
if ENV["HOMEBREW_ANALYTICS_DEBUG"]
puts "#{curl} #{args.join(" ")} \"#{url}\""
puts Utils.popen_read(curl, *args, url)
else
pid = spawn curl, *args, url
Process.detach(pid)
end
end
sig {
params(measurement: Symbol, package_name: String, tap_name: String,
on_request: T::Boolean, options: String).void
}
def report_package_event(measurement, package_name:, tap_name:, on_request: false, options: "")
return if not_this_run? || disabled?
# ensure options are removed (by `.compact` below) if empty
options = nil if options.blank?
# Tags must have low cardinality.
tags = default_package_tags.merge(on_request:)
# Fields can have high cardinality.
fields = default_package_fields.merge(package: package_name, tap_name:, options:)
.compact
report_influx(measurement, tags, fields)
end
sig { params(exception: BuildError).void }
def report_build_error(exception)
return if not_this_run? || disabled?
formula = exception.formula
return unless formula
tap = formula.tap
return unless tap
return unless tap.should_report_analytics?
options = exception.options.to_a.compact.map(&:to_s).sort.uniq.join(" ")
report_package_event(:build_error, package_name: formula.name, tap_name: tap.name, options:)
end
sig { params(command_instance: Homebrew::AbstractCommand).void }
def report_command_run(command_instance)
return if not_this_run? || disabled?
command = command_instance.class.command_name
options_array = command_instance.args.options_only.to_a.compact
# Strip out any flag values to reduce cardinality and preserve privacy.
options_array.map! { |option| option.sub(/=.*/m, "=") }
# Strip out --with-* and --without-* options
options_array.reject! { |option| option.match(/^--with(out)?-/) }
options = options_array.sort.uniq.join(" ")
# Tags must have low cardinality.
tags = {
command:,
ci: ENV["CI"].present?,
devcmdrun: Homebrew::EnvConfig.devcmdrun?,
developer: Homebrew::EnvConfig.developer?,
}
# Fields can have high cardinality.
fields = { options: }
report_influx(:command_run, tags, fields)
end
sig { params(step_command_short: String, passed: T::Boolean).void }
def report_test_bot_test(step_command_short, passed)
return if not_this_run? || disabled?
return if ENV["HOMEBREW_TEST_BOT_ANALYTICS"].blank?
# Tags must have low cardinality.
tags = {
passed:,
arch: HOMEBREW_PHYSICAL_PROCESSOR,
os: HOMEBREW_SYSTEM,
}
# Strip out any flag values to reduce cardinality and preserve privacy.
# Sort options to ensure consistent ordering and improve readability.
command_and_package, options =
step_command_short.split
.map { |arg| arg.sub(/=.*/, "=") }
.partition { |arg| !arg.start_with?("-") }
command = (command_and_package + options.sort).join(" ")
# Fields can have high cardinality.
fields = { command: }
report_influx(:test_bot_test, tags, fields)
end
sig { returns(T::Boolean) }
def influx_message_displayed?
config_true?(:influxanalyticsmessage)
end
sig { returns(T::Boolean) }
def messages_displayed?
return false unless config_true?(:analyticsmessage)
return false unless config_true?(:caskanalyticsmessage)
influx_message_displayed?
end
sig { returns(T::Boolean) }
def disabled?
return true if Homebrew::EnvConfig.no_analytics?
config_true?(:analyticsdisabled)
end
sig { returns(T::Boolean) }
def not_this_run?
ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"].present?
end
sig { returns(T::Boolean) }
def no_message_output?
# Used by Homebrew/install
ENV["HOMEBREW_NO_ANALYTICS_MESSAGE_OUTPUT"].present?
end
sig { void }
def messages_displayed!
Homebrew::Settings.write :analyticsmessage, true
Homebrew::Settings.write :caskanalyticsmessage, true
Homebrew::Settings.write :influxanalyticsmessage, true
end
sig { void }
def enable!
Homebrew::Settings.write :analyticsdisabled, false
delete_uuid!
messages_displayed!
end
sig { void }
def disable!
Homebrew::Settings.write :analyticsdisabled, true
delete_uuid!
end
sig { void }
def delete_uuid!
Homebrew::Settings.delete :analyticsuuid
end
sig { params(args: Homebrew::Cmd::Info::Args, filter: T.nilable(String)).void }
def output(args:, filter: nil)
require "api"
days = args.days || "30"
category = args.category || "install"
begin
json = Homebrew::API::Analytics.fetch category, days
rescue ArgumentError
# Ignore failed API requests
return
end
return if json.blank? || json["items"].blank?
os_version = category == "os-version"
cask_install = category == "cask-install"
results = {}
json["items"].each do |item|
key = if os_version
item["os_version"]
elsif cask_install
item["cask"]
else
item["formula"]
end
next if filter.present? && key != filter && !key.start_with?("#{filter} ")
results[key] = item["count"].tr(",", "").to_i
end
if filter.present? && results.blank?
onoe "No results matching `#{filter}` found!"
return
end
table_output(category, days, results, os_version:, cask_install:)
end
sig { params(json: T::Hash[String, T.untyped], args: Homebrew::Cmd::Info::Args).void }
def output_analytics(json, args:)
full_analytics = args.analytics? || verbose?
ohai "Analytics"
json["analytics"].each do |category, value|
category = category.tr("_", "-")
analytics = []
value.each do |days, results|
days = days.to_i
if full_analytics
next if args.days.present? && args.days&.to_i != days
next if args.category.present? && args.category != category
table_output(category, days.to_s, results)
else
total_count = results.values.inject("+")
analytics << "#{number_readable(total_count)} (#{days} days)"
end
end
puts "#{category}: #{analytics.join(", ")}" unless full_analytics
end
end
# This method is undocumented because it is not intended for general use.
# It relies on screen scraping some GitHub HTML that's not available as an API.
# This seems very likely to break in the future.
# That said, it's the only way to get the data we want right now.
sig { params(formula: Formula, args: Homebrew::Cmd::Info::Args).void }
def output_github_packages_downloads(formula, args:)
return unless args.github_packages_downloads?
return unless formula.core_formula?
require "utils/curl"
escaped_formula_name = GitHubPackages.image_formula_name(formula.name)
.gsub("/", "%2F")
formula_url_suffix = "container/core%2F#{escaped_formula_name}/"
formula_url = "https://github.com/Homebrew/homebrew-core/pkgs/#{formula_url_suffix}"
output = Utils::Curl.curl_output("--fail", formula_url)
return unless output.success?
formula_version_urls = output.stdout
.scan(%r{/orgs/Homebrew/packages/#{formula_url_suffix}\d+\?tag=[^"]+})
.map do |url|
T.cast(url, String).sub("/orgs/Homebrew/packages/", "/Homebrew/homebrew-core/pkgs/")
end
return if formula_version_urls.empty?
thirty_day_download_count = 0
formula_version_urls.each do |formula_version_url_suffix|
formula_version_url = "https://github.com#{formula_version_url_suffix}"
output = Utils::Curl.curl_output("--fail", formula_version_url)
next unless output.success?
last_thirty_days_match = output.stdout.match(
%r{<span class="[\s\-a-z]*">Last 30 days</span>\s*<span class="[\s\-a-z]*">([\d.M,]+)</span>}m,
)
next if last_thirty_days_match.blank?
last_thirty_days_downloads = last_thirty_days_match.captures.fetch(0).tr(",", "")
thirty_day_download_count += if (millions_match = last_thirty_days_downloads.match(/(\d+\.\d+)M/).presence)
(millions_match.captures.first.to_f * 1_000_000).to_i
else
last_thirty_days_downloads.to_i
end
end
ohai "GitHub Packages Downloads"
puts "#{number_readable(thirty_day_download_count)} (30 days)"
end
sig { params(formula: Formula, args: Homebrew::Cmd::Info::Args).void }
def formula_output(formula, args:)
return if Homebrew::EnvConfig.no_analytics? || Homebrew::EnvConfig.no_github_api?
require "api"
return unless Homebrew::API.formula_names.include? formula.name
json = Homebrew::API::Formula.formula_json formula.name
return if json.blank? || json["analytics"].blank?
output_analytics(json, args:)
output_github_packages_downloads(formula, args:)
rescue ArgumentError
# Ignore failed API requests
nil
end
sig { params(cask: Cask::Cask, args: Homebrew::Cmd::Info::Args).void }
def cask_output(cask, args:)
return if Homebrew::EnvConfig.no_analytics? || Homebrew::EnvConfig.no_github_api?
require "api"
return unless Homebrew::API.cask_tokens.include? cask.token
json = Homebrew::API::Cask.cask_json cask.token
return if json.blank? || json["analytics"].blank?
output_analytics(json, args:)
rescue ArgumentError
# Ignore failed API requests
nil
end
sig { returns(T::Hash[Symbol, T.any(T::Boolean, String)]) }
def default_package_tags
cache[:default_package_tags] ||= begin
# Only display default prefixes to reduce cardinality and improve privacy
prefix = Homebrew.default_prefix? ? HOMEBREW_PREFIX.to_s : "custom-prefix"
# Tags are always strings and must have low cardinality.
{
ci: ENV["CI"].present?,
prefix:,
default_prefix: Homebrew.default_prefix?,
developer: Homebrew::EnvConfig.developer?,
devcmdrun: Homebrew::EnvConfig.devcmdrun?,
arch: HOMEBREW_PHYSICAL_PROCESSOR,
os: HOMEBREW_SYSTEM,
}
end
end
# remove os_version starting with " or number
# remove macOS patch release
sig { returns(T::Hash[Symbol, String]) }
def default_package_fields
cache[:default_package_fields] ||= begin
version = if (match_data = HOMEBREW_VERSION.match(/^[\d.]+/))
suffix = "-dev" if HOMEBREW_VERSION.include?("-")
match_data[0] + suffix.to_s
else
">=4.1.22"
end
# Only include OS versions with an actual name.
os_name_and_version = if (os_version = OS_VERSION.presence) && os_version.downcase.match?(/^[a-z]/)
os_version
end
{
version:,
os_name_and_version:,
}
end
end
sig {
params(
category: String, days: String, results: T::Hash[String, Integer], os_version: T::Boolean,
cask_install: T::Boolean
).void
}
def table_output(category, days, results, os_version: false, cask_install: false)
oh1 "#{category} (#{days} days)"
total_count = results.values.inject("+")
formatted_total_count = format_count(total_count)
formatted_total_percent = format_percent(100)
index_header = "Index"
count_header = "Count"
percent_header = "Percent"
name_with_options_header = if os_version
"macOS Version"
elsif cask_install
"Token"
else
"Name (with options)"
end
total_index_footer = "Total"
max_index_width = results.length.to_s.length
index_width = [
index_header.length,
total_index_footer.length,
max_index_width,
].max
count_width = [
count_header.length,
formatted_total_count.length,
].max
percent_width = [
percent_header.length,
formatted_total_percent.length,
].max
name_with_options_width = Tty.width -
index_width -
count_width -
percent_width -
10 # spacing and lines
formatted_index_header =
format "%#{index_width}s", index_header
formatted_name_with_options_header =
format "%-#{name_with_options_width}s",
name_with_options_header[0..(name_with_options_width-1)]
formatted_count_header =
format "%#{count_width}s", count_header
formatted_percent_header =
format "%#{percent_width}s", percent_header
puts "#{formatted_index_header} | #{formatted_name_with_options_header} | " \
"#{formatted_count_header} | #{formatted_percent_header}"
columns_line = "#{"-"*index_width}:|-#{"-"*name_with_options_width}-|-" \
"#{"-"*count_width}:|-#{"-"*percent_width}:"
puts columns_line
index = 0
results.each do |name_with_options, count|
index += 1
formatted_index = format "%0#{max_index_width}d", index
formatted_index = format "%-#{index_width}s", formatted_index
formatted_name_with_options =
format "%-#{name_with_options_width}s",
name_with_options[0..(name_with_options_width-1)]
formatted_count = format "%#{count_width}s", format_count(count)
formatted_percent = if total_count.zero?
format "%#{percent_width}s", format_percent(0)
else
format "%#{percent_width}s",
format_percent((count.to_i * 100) / total_count.to_f)
end
puts "#{formatted_index} | #{formatted_name_with_options} | " \
"#{formatted_count} | #{formatted_percent}%"
next if index > 10
end
return if results.length <= 1
formatted_total_footer =
format "%-#{index_width}s", total_index_footer
formatted_blank_footer =
format "%-#{name_with_options_width}s", ""
formatted_total_count_footer =
format "%#{count_width}s", formatted_total_count
formatted_total_percent_footer =
format "%#{percent_width}s", formatted_total_percent
puts "#{formatted_total_footer} | #{formatted_blank_footer} | " \
"#{formatted_total_count_footer} | #{formatted_total_percent_footer}%"
end
sig { params(key: Symbol).returns(T::Boolean) }
def config_true?(key)
Homebrew::Settings.read(key) == "true"
end
sig { params(count: Integer).returns(String) }
def format_count(count)
count.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end
sig { params(percent: T.any(Integer, Float)).returns(String) }
def format_percent(percent)
format("%<percent>.2f", percent:)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/fork.rb | Library/Homebrew/utils/fork.rb | # typed: strict
# frozen_string_literal: true
require "fcntl"
require "utils/socket"
module Utils
sig { params(child_error: T::Hash[String, T.untyped]).returns(Exception) }
def self.rewrite_child_error(child_error)
inner_class = Object.const_get(child_error["json_class"])
error = if child_error["cmd"] && inner_class == ErrorDuringExecution
ErrorDuringExecution.new(child_error["cmd"],
status: child_error["status"],
output: child_error["output"])
elsif child_error["cmd"] && inner_class == BuildError
# We fill `BuildError#formula` and `BuildError#options` in later,
# when we rescue this in `FormulaInstaller#build`.
BuildError.new(nil, child_error["cmd"], child_error["args"], child_error["env"])
elsif inner_class == Interrupt
Interrupt.new
else
# Everything other error in the child just becomes a RuntimeError.
RuntimeError.new <<~EOS
An exception occurred within a child process:
#{inner_class}: #{child_error["m"]}
EOS
end
error.set_backtrace child_error["b"]
error
end
# When using this function, remember to call `exec` as soon as reasonably possible.
# This function does not protect against the pitfalls of what you can do pre-exec in a fork.
# See `man fork` for more information.
sig {
params(directory: T.nilable(String), yield_parent: T::Boolean,
_blk: T.proc.params(arg0: T.nilable(String)).void).void
}
def self.safe_fork(directory: nil, yield_parent: false, &_blk)
require "json/add/exception"
block = proc do |tmpdir|
UNIXServerExt.open("#{tmpdir}/socket") do |server|
read, write = IO.pipe
pid = fork do
# bootsnap doesn't like these forked processes
ENV["HOMEBREW_NO_BOOTSNAP"] = "1"
error_pipe = server.path
ENV["HOMEBREW_ERROR_PIPE"] = error_pipe
server.close
read.close
write.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
Process::UID.change_privilege(Process.euid) if Process.euid != Process.uid
yield(error_pipe)
# This could be any type of exception, so rescue them all.
rescue Exception => e # rubocop:disable Lint/RescueException
error_hash = JSON.parse e.to_json
# Special case: We need to recreate ErrorDuringExecutions
# for proper error messages and because other code expects
# to rescue them further down.
if e.is_a?(ErrorDuringExecution)
error_hash["cmd"] = e.cmd
error_hash["status"] = if e.status.is_a?(Process::Status)
{
exitstatus: e.status.exitstatus,
termsig: e.status.termsig,
}
else
e.status
end
error_hash["output"] = e.output
end
write.puts error_hash.to_json
write.close
exit!
else
exit!(true)
end
begin
yield(nil) if yield_parent
begin
socket = server.accept_nonblock
rescue Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
retry unless Process.waitpid(pid, Process::WNOHANG)
else
socket.send_io(write)
socket.close
end
write.close
data = read.read
read.close
Process.waitpid(pid) unless socket.nil?
rescue Interrupt
Process.waitpid(pid)
end
# 130 is the exit status for a process interrupted via Ctrl-C.
raise Interrupt if $CHILD_STATUS.exitstatus == 130
raise Interrupt if $CHILD_STATUS.termsig == Signal.list["INT"]
if data.present?
error_hash = JSON.parse(data.lines.fetch(0))
raise rewrite_child_error(error_hash)
end
raise ChildProcessError, $CHILD_STATUS unless $CHILD_STATUS.success?
end
end
if directory
block.call(directory)
else
Dir.mktmpdir("homebrew-fork", HOMEBREW_TEMP, &block)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/inreplace.rb | Library/Homebrew/utils/inreplace.rb | # typed: strict
# frozen_string_literal: true
require "utils/string_inreplace_extension"
module Utils
# Helper functions for replacing text in files in-place.
module Inreplace
# Error during text replacement.
class Error < RuntimeError
sig { params(errors: T::Hash[String, T::Array[String]]).void }
def initialize(errors)
formatted_errors = errors.reduce(+"inreplace failed\n") do |s, (path, errs)|
s << "#{path}:\n" << errs.map { |e| " #{e}\n" }.join
end
super formatted_errors.freeze
end
end
# Sometimes we have to change a bit before we install. Mostly we
# prefer a patch, but if you need the {Formula#prefix prefix} of
# this formula in the patch you have to resort to `inreplace`,
# because in the patch you don't have access to any variables
# defined by the formula, as only `HOMEBREW_PREFIX` is available
# in the {DATAPatch embedded patch}.
#
# ### Examples
#
# `inreplace` supports regular expressions:
#
# ```ruby
# inreplace "somefile.cfg", /look[for]what?/, "replace by #{bin}/tool"
# ```
#
# `inreplace` supports blocks:
#
# ```ruby
# inreplace "Makefile" do |s|
# s.gsub! "/usr/local", HOMEBREW_PREFIX.to_s
# end
# ```
#
# @see StringInreplaceExtension
# @api public
sig {
params(
paths: T.any(T::Enumerable[T.any(String, Pathname)], String, Pathname),
before: T.nilable(T.any(Pathname, Regexp, String)),
after: T.nilable(T.any(Pathname, String, Symbol)),
audit_result: T::Boolean,
global: T::Boolean,
block: T.nilable(T.proc.params(s: StringInreplaceExtension).void),
).void
}
def self.inreplace(paths, before = nil, after = nil, audit_result: true, global: true, &block)
paths = Array(paths)
after &&= after.to_s
before = before.to_s if before.is_a?(Pathname)
errors = {}
errors["`paths` (first) parameter"] = ["`paths` was empty"] if paths.all?(&:blank?)
paths.each do |path|
str = File.binread(path)
s = StringInreplaceExtension.new(str)
if before.nil? && after.nil?
raise ArgumentError, "Must supply a block or before/after params" unless block
yield s
elsif global
s.gsub!(T.must(before), T.must(after), audit_result:)
else
s.sub!(T.must(before), T.must(after), audit_result:)
end
errors[path] = s.errors unless s.errors.empty?
Pathname(path).atomic_write(s.inreplace_string)
end
raise Utils::Inreplace::Error, errors if errors.present?
end
sig {
params(
path: T.any(String, Pathname),
replacement_pairs: T::Array[[T.any(Regexp, Pathname, String), T.any(Pathname, String)]],
read_only_run: T::Boolean,
silent: T::Boolean,
).returns(String)
}
def self.inreplace_pairs(path, replacement_pairs, read_only_run: false, silent: false)
str = File.binread(path)
contents = StringInreplaceExtension.new(str)
replacement_pairs.each do |old, new|
if old.blank?
contents.errors << "No old value for new value #{new}! Did you pass the wrong arguments?"
next
end
contents.gsub!(old, new)
end
raise Utils::Inreplace::Error, path => contents.errors if contents.errors.present?
Pathname(path).atomic_write(contents.inreplace_string) unless read_only_run
contents.inreplace_string
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/git.rb | Library/Homebrew/utils/git.rb | # typed: strict
# frozen_string_literal: true
require "system_command"
module Utils
# Helper functions for querying Git information.
#
# @see GitRepository
module Git
extend SystemCommand::Mixin
sig { returns(T::Boolean) }
def self.available?
!version.null?
end
sig { returns(Version) }
def self.version
@version ||= T.let(begin
stdout, _, status = system_command(git, args: ["--version"], verbose: false, print_stderr: false).to_a
version_str = status.success? ? stdout.chomp[/git version (\d+(?:\.\d+)*)/, 1] : nil
version_str.nil? ? Version::NULL : Version.new(version_str)
end, T.nilable(Version))
end
sig { returns(T.nilable(String)) }
def self.path
return unless available?
return @path if defined?(@path)
@path = T.let(Utils.popen_read(git, "--homebrew=print-path").chomp.presence, T.nilable(String))
end
sig { returns(Pathname) }
def self.git
@git ||= T.let(HOMEBREW_SHIMS_PATH/"shared/git", T.nilable(Pathname))
end
sig { params(url: String).returns(T::Boolean) }
def self.remote_exists?(url)
return true unless available?
quiet_system "git", "ls-remote", url
end
sig { void }
def self.clear_available_cache
remove_instance_variable(:@version) if defined?(@version)
remove_instance_variable(:@path) if defined?(@path)
remove_instance_variable(:@git) if defined?(@git)
end
sig {
params(repo: T.any(Pathname, String), file: T.any(Pathname, String),
before_commit: T.nilable(String)).returns(String)
}
def self.last_revision_commit_of_file(repo, file, before_commit: nil)
args = if before_commit.nil?
["--skip=1"]
else
[before_commit.split("..").first]
end
Utils.popen_read(git, "-C", repo, "log", "--format=%h", "--abbrev=7", "--max-count=1", *args, "--", file).chomp
end
sig {
params(
repo: T.any(Pathname, String),
files: T::Array[T.any(Pathname, String)],
before_commit: T.nilable(String),
).returns([T.nilable(String), T::Array[String]])
}
def self.last_revision_commit_of_files(repo, files, before_commit: nil)
args = if before_commit.nil?
["--skip=1"]
else
[before_commit.split("..").first]
end
# git log output format:
# <commit_hash>
# <file_path1>
# <file_path2>
# ...
# return [<commit_hash>, [file_path1, file_path2, ...]]
rev, *paths = Utils.popen_read(
git, "-C", repo, "log",
"--pretty=format:%h", "--abbrev=7", "--max-count=1",
"--diff-filter=d", "--name-only", *args, "--", *files
).lines.map(&:chomp).reject(&:empty?)
[rev, paths]
end
sig {
params(repo: T.any(Pathname, String), file: T.any(Pathname, String), before_commit: T.nilable(String))
.returns(String)
}
def self.last_revision_of_file(repo, file, before_commit: nil)
relative_file = Pathname(file).relative_path_from(repo)
commit_hash = last_revision_commit_of_file(repo, relative_file, before_commit:)
file_at_commit(repo, file, commit_hash)
end
sig { params(repo: T.any(Pathname, String), file: T.any(Pathname, String), commit: String).returns(String) }
def self.file_at_commit(repo, file, commit)
relative_file = Pathname(file)
relative_file = relative_file.relative_path_from(repo) if relative_file.absolute?
Utils.popen_read(git, "-C", repo, "show", "#{commit}:#{relative_file}")
end
sig { void }
def self.ensure_installed!
return if available?
# we cannot install brewed git if homebrew/core is unavailable.
if CoreTap.instance.installed?
begin
# Otherwise `git` will be installed from source in tests that need it. This is slow
# and will also likely fail due to `OS::Linux` and `OS::Mac` being undefined.
raise "Refusing to install Git on a generic OS." if ENV["HOMEBREW_TEST_GENERIC_OS"]
require "formula"
Formula["git"].ensure_installed!
clear_available_cache
rescue
raise "Git is unavailable"
end
end
raise "Git is unavailable" unless available?
end
sig { params(author: T::Boolean, committer: T::Boolean).void }
def self.set_name_email!(author: true, committer: true)
if Homebrew::EnvConfig.git_name
ENV["GIT_AUTHOR_NAME"] = Homebrew::EnvConfig.git_name if author
ENV["GIT_COMMITTER_NAME"] = Homebrew::EnvConfig.git_name if committer
end
if Homebrew::EnvConfig.git_committer_name && committer
ENV["GIT_COMMITTER_NAME"] = Homebrew::EnvConfig.git_committer_name
end
if Homebrew::EnvConfig.git_email
ENV["GIT_AUTHOR_EMAIL"] = Homebrew::EnvConfig.git_email if author
ENV["GIT_COMMITTER_EMAIL"] = Homebrew::EnvConfig.git_email if committer
end
return unless committer
return unless Homebrew::EnvConfig.git_committer_email
ENV["GIT_COMMITTER_EMAIL"] = Homebrew::EnvConfig.git_committer_email
end
sig { void }
def self.setup_gpg!
gnupg_bin = HOMEBREW_PREFIX/"opt/gnupg/bin"
return unless gnupg_bin.directory?
ENV["PATH"] = PATH.new(ENV.fetch("PATH")).prepend(gnupg_bin).to_s
end
# Special case of `git cherry-pick` that permits non-verbose output and
# optional resolution on merge conflict.
sig { params(repo: T.any(Pathname, String), args: String, resolve: T::Boolean, verbose: T::Boolean).returns(String) }
def self.cherry_pick!(repo, *args, resolve: false, verbose: false)
cmd = [git.to_s, "-C", repo, "cherry-pick"] + args
output = Utils.popen_read(*cmd, err: :out)
if $CHILD_STATUS.success?
puts output if verbose
output
else
system git.to_s, "-C", repo.to_s, "cherry-pick", "--abort" unless resolve
raise ErrorDuringExecution.new(cmd, status: $CHILD_STATUS, output: [[:stdout, output]])
end
end
sig { returns(T::Boolean) }
def self.supports_partial_clone_sparse_checkout?
# There is some support for partial clones prior to 2.20, but we avoid using it
# due to performance issues
version >= Version.new("2.20.0")
end
sig {
params(repository_path: T.nilable(Pathname), person: String, from: T.nilable(String),
to: T.nilable(String)).returns(Integer)
}
def self.count_coauthors(repository_path, person, from:, to:)
return 0 if repository_path.blank?
cmd = [git.to_s, "-C", repository_path.to_s, "log", "--oneline"]
cmd << "--format='%(trailers:key=Co-authored-by:)''"
cmd << "--before=#{to}" if to
cmd << "--after=#{from}" if from
Utils.safe_popen_read(*cmd).lines.count { |l| l.include?(person) }
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/linkage.rb | Library/Homebrew/utils/linkage.rb | # typed: strict
# frozen_string_literal: true
module Utils
sig {
params(binary: T.any(String, Pathname), library: T.any(String, Pathname)).returns(T::Boolean)
}
def self.binary_linked_to_library?(binary, library)
library = library.to_s
library = File.realpath(library) if library.start_with?(HOMEBREW_PREFIX.to_s)
binary_path = BinaryPathname.wrap(binary)
binary_path.dynamically_linked_libraries.any? do |dll|
dll = File.realpath(dll) if dll.start_with?(HOMEBREW_PREFIX.to_s)
dll == library
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/ast.rb | Library/Homebrew/utils/ast.rb | # typed: strict
# frozen_string_literal: true
require "ast_constants"
require "rubocop-ast"
module Utils
# Helper functions for editing Ruby files.
module AST
Node = RuboCop::AST::Node
SendNode = RuboCop::AST::SendNode
BlockNode = RuboCop::AST::BlockNode
ProcessedSource = RuboCop::AST::ProcessedSource
TreeRewriter = Parser::Source::TreeRewriter
module_function
sig { params(body_node: Node).returns(T::Array[Node]) }
def body_children(body_node)
if body_node.blank?
[]
elsif body_node.begin_type?
body_node.children.compact
else
[body_node]
end
end
sig { params(name: Symbol, value: T.any(Numeric, String, Symbol), indent: T.nilable(Integer)).returns(String) }
def stanza_text(name, value, indent: nil)
text = if value.is_a?(String)
_, node = process_source(value)
value if (node.is_a?(SendNode) || node.is_a?(BlockNode)) && node.method_name == name
end
text ||= "#{name} #{value.inspect}"
text = text.gsub(/^(?!$)/, " " * indent) if indent && !text.match?(/\A\n* +/)
text
end
sig { params(source: String).returns([ProcessedSource, Node]) }
def process_source(source)
ruby_version = Version.new(HOMEBREW_REQUIRED_RUBY_VERSION).major_minor.to_f
processed_source = ProcessedSource.new(source, ruby_version)
root_node = processed_source.ast
[processed_source, root_node]
end
sig {
params(
component_name: Symbol,
component_type: Symbol,
target_name: Symbol,
target_type: T.nilable(Symbol),
).returns(T::Boolean)
}
def component_match?(component_name:, component_type:, target_name:, target_type: nil)
component_name == target_name && (target_type.nil? || component_type == target_type)
end
sig { params(node: Node, name: Symbol, type: T.nilable(Symbol)).returns(T::Boolean) }
def call_node_match?(node, name:, type: nil)
node_type = case node
when SendNode then :method_call
when BlockNode then :block_call
else return false
end
component_match?(component_name: node.method_name,
component_type: node_type,
target_name: name,
target_type: type)
end
# Helper class for editing formulae.
class FormulaAST
extend Forwardable
include AST
delegate process: :tree_rewriter
sig { params(formula_contents: String).void }
def initialize(formula_contents)
@formula_contents = formula_contents
processed_source, children = process_formula
@processed_source = T.let(processed_source, ProcessedSource)
@children = T.let(children, T::Array[Node])
@tree_rewriter = T.let(TreeRewriter.new(processed_source.buffer), TreeRewriter)
end
sig { returns(T.nilable(Node)) }
def bottle_block
stanza(:bottle, type: :block_call)
end
sig { params(name: Symbol, type: T.nilable(Symbol)).returns(T.nilable(Node)) }
def stanza(name, type: nil)
children.find { |child| call_node_match?(child, name:, type:) }
end
sig { params(bottle_output: String).void }
def replace_bottle_block(bottle_output)
replace_stanza(:bottle, bottle_output.chomp, type: :block_call)
end
sig { params(bottle_output: String).void }
def add_bottle_block(bottle_output)
add_stanza(:bottle, "\n#{bottle_output.chomp}", type: :block_call)
end
sig { params(name: Symbol, type: T.nilable(Symbol)).void }
def remove_stanza(name, type: nil)
stanza_node = stanza(name, type:)
raise "Could not find '#{name}' stanza!" if stanza_node.blank?
# stanza is probably followed by a newline character
# try to delete it if so
stanza_range = stanza_node.source_range
trailing_range = stanza_range.with(begin_pos: stanza_range.end_pos,
end_pos: stanza_range.end_pos + 1)
if trailing_range.source.chomp.empty?
stanza_range = stanza_range.adjust(end_pos: 1)
# stanza_node is probably indented
# since a trailing newline has been removed,
# try to delete leading whitespace on line
leading_range = stanza_range.with(begin_pos: stanza_range.begin_pos - stanza_range.column,
end_pos: stanza_range.begin_pos)
if leading_range.source.strip.empty?
stanza_range = stanza_range.adjust(begin_pos: -stanza_range.column)
# if the stanza was preceded by a blank line, it should be removed
# that is, if the two previous characters are newlines,
# then delete one of them
leading_range = stanza_range.with(begin_pos: stanza_range.begin_pos - 2,
end_pos: stanza_range.begin_pos)
stanza_range = stanza_range.adjust(begin_pos: -1) if leading_range.source.chomp.chomp.empty?
end
end
tree_rewriter.remove(stanza_range)
end
sig { params(name: Symbol, replacement: T.any(Numeric, String, Symbol), type: T.nilable(Symbol)).void }
def replace_stanza(name, replacement, type: nil)
stanza_node = stanza(name, type:)
raise "Could not find '#{name}' stanza!" if stanza_node.blank?
tree_rewriter.replace(stanza_node.source_range, stanza_text(name, replacement, indent: 2).lstrip)
end
sig { params(name: Symbol, value: T.any(Numeric, String, Symbol), type: T.nilable(Symbol)).void }
def add_stanza(name, value, type: nil)
preceding_component = if children.length > 1
children.reduce do |previous_child, current_child|
if formula_component_before_target?(current_child,
target_name: name,
target_type: type)
next current_child
else
break previous_child
end
end
else
children.first
end
preceding_component = preceding_component.last_argument if preceding_component.is_a?(SendNode)
preceding_expr = preceding_component.location.expression
processed_source.comments.each do |comment|
comment_expr = comment.location.expression
distance = comment_expr.first_line - preceding_expr.first_line
case distance
when 0
if comment_expr.last_line > preceding_expr.last_line ||
comment_expr.end_pos > preceding_expr.end_pos
preceding_expr = comment_expr
end
when 1
preceding_expr = comment_expr
end
end
tree_rewriter.insert_after(preceding_expr, "\n#{stanza_text(name, value, indent: 2)}")
end
private
sig { returns(String) }
attr_reader :formula_contents
sig { returns(ProcessedSource) }
attr_reader :processed_source
sig { returns(T::Array[Node]) }
attr_reader :children
sig { returns(TreeRewriter) }
attr_reader :tree_rewriter
sig { returns([ProcessedSource, T::Array[Node]]) }
def process_formula
processed_source, root_node = process_source(formula_contents)
class_node = root_node if root_node.class_type?
if root_node.begin_type?
nodes = root_node.children.select(&:class_type?)
class_node = if nodes.count > 1
nodes.find { |n| n.parent_class&.const_name == "Formula" }
else
nodes.first
end
end
raise "Could not find formula class!" if class_node.nil?
children = body_children(class_node.body)
raise "Formula class is empty!" if children.empty?
[processed_source, children]
end
sig { params(node: Node, target_name: Symbol, target_type: T.nilable(Symbol)).returns(T::Boolean) }
def formula_component_before_target?(node, target_name:, target_type: nil)
FORMULA_COMPONENT_PRECEDENCE_LIST.each do |components|
return false if components.any? do |component|
component_match?(component_name: component[:name],
component_type: component[:type],
target_name:,
target_type:)
end
return true if components.any? do |component|
call_node_match?(node, name: component[:name], type: component[:type])
end
end
false
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/user.rb | Library/Homebrew/utils/user.rb | # typed: strict
# frozen_string_literal: true
require "delegate"
require "etc"
require "system_command"
# A system user.
class User < SimpleDelegator
include SystemCommand::Mixin
# Return whether the user has an active GUI session.
sig { returns(T::Boolean) }
def gui?
out, _, status = system_command("who").to_a
return false unless status.success?
out.lines
.map(&:split)
.any? { |user, type,| to_s == user && type == "console" }
end
# Return the current user.
sig { returns(T.nilable(T.attached_class)) }
def self.current
return @current if defined?(@current)
pwuid = Etc.getpwuid(Process.euid)
return if pwuid.nil?
@current = T.let(new(pwuid.name), T.nilable(T.attached_class))
end
# This explicit delegator exists to make to_s visible to sorbet.
sig { returns(String) }
def to_s = __getobj__.to_s
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/ruby_sh/ruby_gem_version.rb | Library/Homebrew/utils/ruby_sh/ruby_gem_version.rb | # typed: strict
# frozen_string_literal: true
require "rbconfig"
puts RbConfig::CONFIG["ruby_version"]
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/github/actions.rb | Library/Homebrew/utils/github/actions.rb | # typed: strict
# frozen_string_literal: true
module GitHub
# Helper functions for interacting with GitHub Actions.
#
# @api internal
module Actions
sig { params(string: String).returns(String) }
def self.escape(string)
# See https://github.community/t/set-output-truncates-multiline-strings/16852/3.
string.gsub("%", "%25")
.gsub("\n", "%0A")
.gsub("\r", "%0D")
end
sig { params(name: String, value: String).returns(String) }
def self.format_multiline_string(name, value)
# Format multiline strings for environment files
# See https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings
require "securerandom"
delimiter = "ghadelimiter_#{SecureRandom.uuid}"
if name.include?(delimiter) || value.include?(delimiter)
raise "`name` and `value` must not contain the delimiter"
end
<<~EOS
#{name}<<#{delimiter}
#{value}
#{delimiter}
EOS
end
sig { returns(T::Boolean) }
def self.env_set?
ENV.fetch("GITHUB_ACTIONS", false).present?
end
sig {
params(
type: Symbol, message: String,
file: T.nilable(T.any(String, Pathname)),
line: T.nilable(Integer)
).returns(T::Boolean)
}
def self.puts_annotation_if_env_set!(type, message, file: nil, line: nil)
# Don't print annotations during tests, too messy to handle these.
return false if ENV.fetch("HOMEBREW_TESTS", false)
return false unless env_set?
std = (type == :notice) ? $stdout : $stderr
std.puts Annotation.new(type, message)
true
end
# Helper class for formatting annotations on GitHub Actions.
class Annotation
ANNOTATION_TYPES = [:notice, :warning, :error].freeze
sig { params(path: T.any(String, Pathname)).returns(T.nilable(Pathname)) }
def self.path_relative_to_workspace(path)
workspace = Pathname(ENV.fetch("GITHUB_WORKSPACE", Dir.pwd)).realpath
path = Pathname(path)
return path unless path.exist?
path.realpath.relative_path_from(workspace)
end
sig {
params(
type: Symbol,
message: String,
file: T.nilable(T.any(String, Pathname)),
title: T.nilable(String),
line: T.nilable(Integer),
end_line: T.nilable(Integer),
column: T.nilable(Integer),
end_column: T.nilable(Integer),
).void
}
def initialize(type, message, file: nil, title: nil, line: nil, end_line: nil, column: nil, end_column: nil)
raise ArgumentError, "Unsupported type: #{type.inspect}" if ANNOTATION_TYPES.exclude?(type)
raise ArgumentError, "`title` must not contain `::`" if title.present? && title.include?("::")
require "utils/tty"
@type = type
@message = T.let(Tty.strip_ansi(message), String)
@file = T.let(self.class.path_relative_to_workspace(file), T.nilable(Pathname)) if file.present?
@title = T.let(Tty.strip_ansi(title), String) if title
@line = T.let(Integer(line), Integer) if line
@end_line = T.let(Integer(end_line), Integer) if end_line
@column = T.let(Integer(column), Integer) if column
@end_column = T.let(Integer(end_column), Integer) if end_column
end
sig { returns(String) }
def to_s
metadata = @type.to_s.dup
if @file
metadata << " file=#{Actions.escape(@file.to_s)}"
if @line
metadata << ",line=#{@line}"
metadata << ",endLine=#{@end_line}" if @end_line
if @column
metadata << ",col=#{@column}"
metadata << ",endColumn=#{@end_column}" if @end_column
end
end
end
if @title
metadata << (@file ? "," : " ")
metadata << "title=#{Actions.escape(@title)}"
end
metadata << " " if metadata.end_with?(":")
"::#{metadata}::#{Actions.escape(@message)}"
end
# An annotation is only relevant if the corresponding `file` is relative to
# the `GITHUB_WORKSPACE` directory or if no `file` is specified.
sig { returns(T::Boolean) }
def relevant?
return true if @file.blank?
@file.descend.next.to_s != ".."
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/github/api.rb | Library/Homebrew/utils/github/api.rb | # typed: strict
# frozen_string_literal: true
require "system_command"
require "utils/output"
module GitHub
sig { params(scopes: T::Array[String]).returns(String) }
def self.pat_blurb(scopes = ALL_SCOPES)
require "utils/formatter"
require "utils/shell"
<<~EOS
Create a GitHub personal access token:
#{Formatter.url(
"https://github.com/settings/tokens/new?scopes=#{scopes.join(",")}&description=Homebrew",
)}
#{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")}
EOS
end
API_URL = T.let("https://api.github.com", String)
API_MAX_PAGES = T.let(50, Integer)
private_constant :API_MAX_PAGES
API_MAX_ITEMS = T.let(5000, Integer)
private_constant :API_MAX_ITEMS
PAGINATE_RETRY_COUNT = T.let(3, Integer)
private_constant :PAGINATE_RETRY_COUNT
CREATE_GIST_SCOPES = T.let(["gist"].freeze, T::Array[String])
CREATE_ISSUE_FORK_OR_PR_SCOPES = T.let(["repo"].freeze, T::Array[String])
CREATE_WORKFLOW_SCOPES = T.let(["workflow"].freeze, T::Array[String])
ALL_SCOPES = T.let((CREATE_GIST_SCOPES + CREATE_ISSUE_FORK_OR_PR_SCOPES + CREATE_WORKFLOW_SCOPES).freeze,
T::Array[String])
private_constant :ALL_SCOPES
GITHUB_PERSONAL_ACCESS_TOKEN_REGEX = T.let(/^(?:[a-f0-9]{40}|(?:gh[pousr]|github_pat)_\w{36,251})$/, Regexp)
private_constant :GITHUB_PERSONAL_ACCESS_TOKEN_REGEX
# Helper functions for accessing the GitHub API.
#
# @api internal
module API
extend SystemCommand::Mixin
extend Utils::Output::Mixin
# Generic API error.
class Error < RuntimeError
include Utils::Output::Mixin
sig { returns(T.nilable(String)) }
attr_reader :github_message
sig { params(message: T.nilable(String), github_message: String).void }
def initialize(message = nil, github_message = T.unsafe(nil))
@github_message = T.let(github_message, T.nilable(String))
super(message)
end
end
# Error when the requested URL is not found.
class HTTPNotFoundError < Error
sig { params(github_message: String).void }
def initialize(github_message)
super(nil, github_message)
end
end
# Error when the API rate limit is exceeded.
class RateLimitExceededError < Error
sig { params(github_message: String, reset: Integer, resource: String, limit: Integer).void }
def initialize(github_message, reset:, resource:, limit:)
@reset = reset
new_pat_message = ", or:\n#{GitHub.pat_blurb}" if API.credentials.blank?
message = <<~EOS
GitHub API Error: #{github_message}
Rate limit exceeded for #{resource} resource (#{limit} limit).
Try again in #{pretty_ratelimit_reset}#{new_pat_message}
EOS
super(message, github_message)
end
sig { returns(Integer) }
attr_reader :reset
sig { returns(String) }
def pretty_ratelimit_reset
pretty_duration(Time.at(@reset) - Time.now)
end
end
GITHUB_IP_ALLOWLIST_ERROR = T.let(
Regexp.new(
"Although you appear to have the correct authorization credentials, " \
"the `(.+)` organization has an IP allow list enabled, " \
"and your IP address is not permitted to access this resource",
).freeze,
Regexp,
)
NO_CREDENTIALS_MESSAGE = T.let <<~MESSAGE.freeze, String
No GitHub credentials found in macOS Keychain, GitHub CLI or the environment.
#{GitHub.pat_blurb}
MESSAGE
# Error when authentication fails.
class AuthenticationFailedError < Error
sig { params(credentials_type: Symbol, github_message: String).void }
def initialize(credentials_type, github_message)
message = "GitHub API Error: #{github_message}\n"
message << case credentials_type
when :github_cli_token
<<~EOS
Your GitHub CLI login session may be invalid.
Refresh it with:
gh auth login --hostname github.com
EOS
when :keychain_username_password
<<~EOS
The GitHub credentials in the macOS keychain may be invalid.
Clear them with:
printf "protocol=https\\nhost=github.com\\n" | git credential-osxkeychain erase
EOS
when :env_token
require "utils/formatter"
<<~EOS
`$HOMEBREW_GITHUB_API_TOKEN` may be invalid or expired; check:
#{Formatter.url("https://github.com/settings/tokens")}
EOS
when :none
NO_CREDENTIALS_MESSAGE
end
super message.freeze, github_message
end
end
# Error when the user has no GitHub API credentials set at all (macOS keychain, GitHub CLI or env var).
class MissingAuthenticationError < Error
sig { void }
def initialize
super NO_CREDENTIALS_MESSAGE
end
end
# Error when the API returns a validation error.
class ValidationFailedError < Error
sig { params(github_message: String, errors: T::Array[String]).void }
def initialize(github_message, errors)
github_message = "#{github_message}: #{errors}" unless errors.empty?
super(github_message, github_message)
end
end
ERRORS = T.let([
AuthenticationFailedError,
HTTPNotFoundError,
RateLimitExceededError,
Error,
JSON::ParserError,
].freeze, T::Array[T.any(T.class_of(Error), T.class_of(JSON::ParserError))])
# Gets the token from the GitHub CLI for github.com.
sig { returns(T.nilable(String)) }
def self.github_cli_token
require "utils/uid"
Utils::UID.drop_euid do
# Avoid `Formula["gh"].opt_bin` so this method works even with `HOMEBREW_DISABLE_LOAD_FORMULA`.
env = {
"PATH" => PATH.new(HOMEBREW_PREFIX/"opt/gh/bin", ENV.fetch("PATH")),
"HOME" => Utils::UID.uid_home,
}.compact
gh_out, _, result = system_command("gh",
args: ["auth", "token", "--hostname", "github.com"],
env:,
print_stderr: false).to_a
return unless result.success?
gh_out.chomp.presence
end
end
# Gets the password field from `git-credential-osxkeychain` for github.com,
# but only if that password looks like a GitHub Personal Access Token.
sig { returns(T.nilable(String)) }
def self.keychain_username_password
require "utils/uid"
Utils::UID.drop_euid do
git_credential_out, _, result = system_command("git",
args: ["credential-osxkeychain", "get"],
input: ["protocol=https\n", "host=github.com\n"],
env: { "HOME" => Utils::UID.uid_home }.compact,
print_stderr: false).to_a
return unless result.success?
git_credential_out.force_encoding("ASCII-8BIT")
github_username = git_credential_out[/^username=(.+)/, 1]
github_password = git_credential_out[/^password=(.+)/, 1]
return unless github_username
# Don't use passwords from the keychain unless they look like
# GitHub Personal Access Tokens:
# https://github.com/Homebrew/brew/issues/6862#issuecomment-572610344
return unless GITHUB_PERSONAL_ACCESS_TOKEN_REGEX.match?(github_password)
github_password.presence
end
end
sig { returns(T.nilable(String)) }
def self.credentials
@credentials ||= T.let(nil, T.nilable(String))
@credentials ||= Homebrew::EnvConfig.github_api_token.presence
@credentials ||= github_cli_token
@credentials ||= keychain_username_password
end
sig { returns(Symbol) }
def self.credentials_type
if Homebrew::EnvConfig.github_api_token.present?
:env_token
elsif github_cli_token.present?
:github_cli_token
elsif keychain_username_password.present?
:keychain_username_password
else
:none
end
end
CREDENTIAL_NAMES = T.let({
env_token: "HOMEBREW_GITHUB_API_TOKEN",
github_cli_token: "GitHub CLI login",
keychain_username_password: "macOS Keychain GitHub",
}.freeze, T::Hash[Symbol, String])
# Given an API response from GitHub, warn the user if their credentials
# have insufficient permissions.
sig { params(response_headers: T::Hash[String, String], needed_scopes: T::Array[String]).void }
def self.credentials_error_message(response_headers, needed_scopes)
return if response_headers.empty?
scopes = response_headers["x-accepted-oauth-scopes"].to_s.split(", ").presence
needed_scopes = Set.new(scopes || needed_scopes)
credentials_scopes = response_headers["x-oauth-scopes"]
return if needed_scopes.subset?(Set.new(credentials_scopes.to_s.split(", ")))
github_permission_link = GitHub.pat_blurb(needed_scopes.to_a)
needed_scopes = needed_scopes.to_a.join(", ").presence || "none"
credentials_scopes = "none" if credentials_scopes.blank?
what = CREDENTIAL_NAMES.fetch(credentials_type)
@credentials_error_message ||= T.let(begin
error_message = <<~EOS
Your #{what} credentials do not have sufficient scope!
Scopes required: #{needed_scopes}
Scopes present: #{credentials_scopes}
#{github_permission_link}
EOS
onoe error_message
error_message
end, T.nilable(String))
end
sig {
params(
url: T.any(String, URI::Generic),
data: T::Hash[Symbol, T.untyped],
data_binary_path: String,
request_method: Symbol,
scopes: T::Array[String],
parse_json: T::Boolean,
_block: T.nilable(
T.proc
.params(data: T::Hash[String, T.untyped])
.returns(T.untyped),
),
).returns(T.untyped)
}
def self.open_rest(url, data: T.unsafe(nil), data_binary_path: T.unsafe(nil), request_method: T.unsafe(nil),
scopes: [].freeze, parse_json: true, &_block)
# This is a no-op if the user is opting out of using the GitHub API.
return block_given? ? yield({}) : {} if Homebrew::EnvConfig.no_github_api?
# This is a Curl format token, not a Ruby one.
# rubocop:disable Style/FormatStringToken
args = ["--header", "Accept: application/vnd.github+json", "--write-out", "\n%{http_code}"]
# rubocop:enable Style/FormatStringToken
token = credentials
args += ["--header", "Authorization: token #{token}"] if credentials_type != :none
args += ["--header", "X-GitHub-Api-Version:2022-11-28"]
require "tempfile"
data_tmpfile = nil
if data
begin
data = JSON.pretty_generate data
data_tmpfile = Tempfile.new("github_api_post", HOMEBREW_TEMP)
rescue JSON::ParserError => e
raise Error, "Failed to parse JSON request:\n#{e.message}\n#{data}", e.backtrace
end
end
if data_binary_path.present?
args += ["--data-binary", "@#{data_binary_path}"]
args += ["--header", "Content-Type: application/gzip"]
end
headers_tmpfile = Tempfile.new("github_api_headers", HOMEBREW_TEMP)
begin
if data_tmpfile
data_tmpfile.write data
data_tmpfile.close
args += ["--data", "@#{data_tmpfile.path}"]
args += ["--request", request_method.to_s] if request_method
end
args += ["--dump-header", T.must(headers_tmpfile.path)]
require "utils/curl"
result = Utils::Curl.curl_output("--location", url.to_s, *args, secrets: [token])
output, _, http_code = result.stdout.rpartition("\n")
output, _, http_code = output.rpartition("\n") if http_code == "000"
headers = headers_tmpfile.read
ensure
if data_tmpfile
data_tmpfile.close
data_tmpfile.unlink
end
headers_tmpfile.close
headers_tmpfile.unlink
end
begin
if !http_code.start_with?("2") || !result.status.success?
raise_error(output, result.stderr, http_code, headers || "", scopes)
end
return if http_code == "204" # No Content
output = JSON.parse output if parse_json
if block_given?
yield output
else
output
end
rescue JSON::ParserError => e
raise Error, "Failed to parse JSON response\n#{e.message}", e.backtrace
end
end
sig {
params(
url: T.any(String, URI::Generic),
additional_query_params: String,
per_page: Integer,
scopes: T::Array[String],
_block: T.proc
.params(result: T.untyped, page: Integer)
.returns(T.untyped),
).void
}
def self.paginate_rest(url, additional_query_params: T.unsafe(nil), per_page: 100, scopes: [].freeze, &_block)
(1..API_MAX_PAGES).each do |page|
retry_count = 1
result = begin
API.open_rest("#{url}?per_page=#{per_page}&page=#{page}&#{additional_query_params}", scopes:)
rescue Error
if retry_count < PAGINATE_RETRY_COUNT
retry_count += 1
retry
end
raise
end
break if result.blank?
yield(result, page)
end
end
sig {
params(
query: String,
variables: T::Hash[Symbol, T.untyped],
scopes: T::Array[String],
raise_errors: T::Boolean,
).returns(T.untyped)
}
def self.open_graphql(query, variables: {}, scopes: [].freeze, raise_errors: true)
data = { query:, variables: }
result = open_rest("#{API_URL}/graphql", scopes:, data:, request_method: :POST)
if raise_errors
raise Error, result["errors"].map { |e| e["message"] }.join("\n") if result["errors"].present?
result["data"]
else
result
end
end
sig {
params(
query: String,
variables: T::Hash[Symbol, T.untyped],
scopes: T::Array[String],
raise_errors: T::Boolean,
_block: T.proc.params(data: T::Hash[String, T.untyped]).returns(T.untyped),
).void
}
def self.paginate_graphql(query, variables: {}, scopes: [].freeze, raise_errors: true, &_block)
result = API.open_graphql(query, variables:, scopes:, raise_errors:)
has_next_page = T.let(true, T::Boolean)
while has_next_page
page_info = yield result
has_next_page = page_info["hasNextPage"]
if has_next_page
variables[:after] = page_info["endCursor"]
result = API.open_graphql(query, variables:, scopes:, raise_errors:)
end
end
end
sig {
params(
output: String,
errors: String,
http_code: String,
headers: String,
scopes: T::Array[String],
).void
}
def self.raise_error(output, errors, http_code, headers, scopes)
json = begin
JSON.parse(output)
rescue
nil
end
message = json&.[]("message") || "curl failed! #{errors}"
meta = {}
headers.lines.each do |l|
key, _, value = l.delete(":").partition(" ")
key = key.downcase.strip
next if key.empty?
meta[key] = value.strip
end
credentials_error_message(meta, scopes)
case http_code
when "401"
raise AuthenticationFailedError.new(credentials_type, message)
when "403"
if meta.fetch("x-ratelimit-remaining", 1).to_i <= 0
reset = meta.fetch("x-ratelimit-reset").to_i
resource = meta.fetch("x-ratelimit-resource")
limit = meta.fetch("x-ratelimit-limit").to_i
raise RateLimitExceededError.new(message, reset:, resource:, limit:)
end
raise AuthenticationFailedError.new(credentials_type, message)
when "404"
raise MissingAuthenticationError if credentials_type == :none && scopes.present?
raise HTTPNotFoundError, message
when "422"
errors = json&.[]("errors") || []
raise ValidationFailedError.new(message, errors)
else
raise Error, message
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/github/artifacts.rb | Library/Homebrew/utils/github/artifacts.rb | # typed: strict
# frozen_string_literal: true
require "download_strategy"
require "utils/github"
module GitHub
# Download an artifact from GitHub Actions and unpack it into the current working directory.
#
# @param url [String] URL to download from
# @param artifact_id [String] a value that uniquely identifies the downloaded artifact
sig { params(url: String, artifact_id: String).void }
def self.download_artifact(url, artifact_id)
token = API.credentials
raise API::MissingAuthenticationError if token.blank?
# We use a download strategy here to leverage the Homebrew cache
# to avoid repeated downloads of (possibly large) bottles.
downloader = GitHubArtifactDownloadStrategy.new(url, artifact_id, token:)
downloader.fetch
downloader.stage
end
end
# Strategy for downloading an artifact from GitHub Actions.
class GitHubArtifactDownloadStrategy < AbstractFileDownloadStrategy
sig { params(url: String, artifact_id: String, token: String).void }
def initialize(url, artifact_id, token:)
super(url, "artifact", artifact_id)
@cache = T.let(HOMEBREW_CACHE/"gh-actions-artifact", Pathname)
@token = token
end
sig { override.params(timeout: T.nilable(T.any(Float, Integer))).void }
def fetch(timeout: nil)
ohai "Downloading #{url}"
if cached_location.exist?
puts "Already downloaded: #{cached_location}"
else
begin
Utils::Curl.curl("--location", "--create-dirs", "--output", temporary_path.to_s, url,
"--header", "Authorization: token #{@token}",
secrets: [@token],
timeout:)
rescue ErrorDuringExecution
raise CurlDownloadStrategyError, url
end
cached_location.dirname.mkpath
temporary_path.rename(cached_location.to_s)
end
symlink_location.dirname.mkpath
FileUtils.ln_s cached_location.relative_path_from(symlink_location.dirname), symlink_location, force: true
end
private
sig { returns(String) }
def resolved_basename
"artifact.zip"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/lock_sh/ruby_check_version.rb | Library/Homebrew/utils/lock_sh/ruby_check_version.rb | # typed: strict
# frozen_string_literal: true
ruby_version_to_check = ARGV.first
exit(ruby_version_to_check < RUBY_VERSION)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/utils/lock_sh/ruby_lock_file_descriptor.rb | Library/Homebrew/utils/lock_sh/ruby_lock_file_descriptor.rb | # typed: strict
# frozen_string_literal: true
file_descriptor = ARGV.first.to_i
file = File.new(file_descriptor)
file.flock(File::LOCK_EX | File::LOCK_NB) || exit(1)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/requirements/macos_requirement.rb | Library/Homebrew/requirements/macos_requirement.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "requirement"
# A requirement on macOS.
class MacOSRequirement < Requirement
fatal true
attr_reader :comparator, :version
# Keep these around as empty arrays so we can keep the deprecation/disabling code the same.
# Treat these like odeprecated/odisabled in terms of deprecation/disabling.
DISABLED_MACOS_VERSIONS = T.let([].freeze, T::Array[Symbol])
DEPRECATED_MACOS_VERSIONS = T.let([
:mojave,
:high_sierra,
:sierra,
:el_capitan,
].freeze, T::Array[Symbol])
def initialize(tags = [], comparator: ">=")
@version = begin
if comparator == "==" && tags.first.respond_to?(:map)
tags.first.map { |s| MacOSVersion.from_symbol(s) }
else
MacOSVersion.from_symbol(tags.first) unless tags.empty?
end
rescue MacOSVersion::Error => e
if DISABLED_MACOS_VERSIONS.include?(e.version)
# This odisabled should stick around indefinitely.
odisabled "`depends_on macos: :#{e.version}`"
elsif DEPRECATED_MACOS_VERSIONS.include?(e.version)
# This odeprecated should stick around indefinitely.
odeprecated "`depends_on macos: :#{e.version}`"
else
raise
end
# Array of versions: remove the bad ones and try again.
if tags.first.respond_to?(:reject)
tags = [tags.first.reject { |s| s == e.version }, tags[1..]]
retry
end
# Otherwise fallback to the oldest allowed if comparator is >=.
MacOSVersion.new(HOMEBREW_MACOS_OLDEST_ALLOWED) if comparator == ">="
end
@comparator = comparator
super(tags.drop(1))
end
def version_specified?
@version.present?
end
satisfy(build_env: false) do
T.bind(self, MacOSRequirement)
next Array(@version).any? { |v| OS::Mac.version.compare(@comparator, v) } if OS.mac? && version_specified?
next true if OS.mac?
next true if @version
false
end
def minimum_version
return MacOSVersion.new(HOMEBREW_MACOS_OLDEST_ALLOWED) if @comparator == "<=" || !version_specified?
return @version.min if @version.respond_to?(:to_ary)
@version
end
def maximum_version
return MacOSVersion.new(HOMEBREW_MACOS_NEWEST_UNSUPPORTED) if @comparator == ">=" || !version_specified?
return @version.max if @version.respond_to?(:to_ary)
@version
end
def allows?(other)
return true unless version_specified?
case @comparator
when ">=" then other >= @version
when "<=" then other <= @version
else
return @version.include?(other) if @version.respond_to?(:to_ary)
@version == other
end
end
def message(type: :formula)
return "macOS is required for this software." unless version_specified?
case @comparator
when ">="
"This software does not run on macOS versions older than #{@version.pretty_name}."
when "<="
case type
when :formula
<<~EOS
This formula either does not compile or function as expected on macOS
versions newer than #{@version.pretty_name} due to an upstream incompatibility.
EOS
when :cask
"This cask does not run on macOS versions newer than #{@version.pretty_name}."
end
else
if @version.respond_to?(:to_ary)
*versions, last = @version.map(&:pretty_name)
return "This software does not run on macOS versions other than #{versions.join(", ")} and #{last}."
end
"This software does not run on macOS versions other than #{@version.pretty_name}."
end
end
def ==(other)
super && comparator == other.comparator && version == other.version
end
alias eql? ==
def hash
[super, comparator, version].hash
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: version#{@comparator}#{@version.to_s.inspect} #{tags.inspect}>"
end
sig { returns(String) }
def display_s
if version_specified?
if @version.respond_to?(:to_ary)
"macOS #{@comparator} #{version.join(" / ")} (or Linux)"
else
"macOS #{@comparator} #{@version} (or Linux)"
end
else
"macOS"
end
end
def to_json(options)
comp = @comparator.to_s
return { comp => @version.map(&:to_s) }.to_json(options) if @version.is_a?(Array)
{ comp => [@version.to_s] }.to_json(options)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/requirements/xcode_requirement.rb | Library/Homebrew/requirements/xcode_requirement.rb | # typed: strict
# frozen_string_literal: true
require "requirement"
# A requirement on Xcode.
class XcodeRequirement < Requirement
fatal true
sig { returns(T.nilable(String)) }
attr_reader :version
satisfy(build_env: false) do
T.bind(self, XcodeRequirement)
xcode_installed_version!
end
sig { params(tags: T::Array[T.any(String, Symbol)]).void }
def initialize(tags = [])
version = tags.shift if tags.first.to_s.match?(/(\d\.)+\d/)
@version = T.let(version&.to_s, T.nilable(String))
super
end
sig { returns(T::Boolean) }
def xcode_installed_version!
return false unless MacOS::Xcode.installed?
return true unless @version
MacOS::Xcode.version >= @version
end
sig { returns(String) }
def message
version = " #{@version}" if @version
message = <<~EOS
A full installation of Xcode.app#{version} is required to compile
this software. Installing just the Command Line Tools is not sufficient.
EOS
if @version && Version.new(MacOS::Xcode.latest_version) < Version.new(@version)
message + <<~EOS
Xcode#{version} cannot be installed on macOS #{MacOS.version}.
You must upgrade your version of macOS.
EOS
else
message + <<~EOS
Xcode can be installed from the App Store.
EOS
end
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: version>=#{@version.inspect} #{tags.inspect}>"
end
sig { returns(String) }
def display_s
return "#{name.capitalize} (on macOS)" unless @version
"#{name.capitalize} >= #{@version} (on macOS)"
end
end
require "extend/os/requirements/xcode_requirement"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/requirements/codesign_requirement.rb | Library/Homebrew/requirements/codesign_requirement.rb | # typed: strict
# frozen_string_literal: true
# A requirement on a code-signing identity.
class CodesignRequirement < Requirement
fatal true
sig { returns(String) }
attr_reader :identity
sig { params(tags: T::Array[T.untyped]).void }
def initialize(tags)
options = tags.shift
raise ArgumentError, "CodesignRequirement requires an options Hash!" unless options.is_a?(Hash)
raise ArgumentError, "CodesignRequirement requires an identity key!" unless options.key?(:identity)
@identity = T.let(options.fetch(:identity), String)
@with = T.let(options.fetch(:with, "code signing"), String)
@url = T.let(options.fetch(:url, nil), T.nilable(String))
super
end
satisfy(build_env: false) do
T.bind(self, CodesignRequirement)
odeprecated "CodesignRequirement"
mktemp do
FileUtils.cp "/usr/bin/false", "codesign_check"
quiet_system "/usr/bin/codesign", "-f", "-s", identity,
"--dryrun", "codesign_check"
end
end
sig { returns(String) }
def message
message = "#{@identity} identity must be available to build with #{@with}"
message += ":\n#{@url}" if @url.present?
message
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/requirements/arch_requirement.rb | Library/Homebrew/requirements/arch_requirement.rb | # typed: strict
# frozen_string_literal: true
require "requirement"
# A requirement on a specific architecture.
class ArchRequirement < Requirement
fatal true
@arch = T.let(nil, T.nilable(Symbol))
sig { returns(T.nilable(Symbol)) }
attr_reader :arch
sig { params(tags: T::Array[Symbol]).void }
def initialize(tags)
@arch = T.let(tags.shift, T.nilable(Symbol))
super
end
satisfy(build_env: false) do
case @arch
when :x86_64 then Hardware::CPU.intel? && Hardware::CPU.is_64_bit?
when :arm64 then Hardware::CPU.arm64?
when :arm, :intel, :ppc then Hardware::CPU.type == @arch
end
end
sig { returns(String) }
def message
"The #{@arch} architecture is required for this software."
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: arch=#{@arch.to_s.inspect} #{tags.inspect}>"
end
sig { returns(String) }
def display_s
"#{@arch} architecture"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/requirements/linux_requirement.rb | Library/Homebrew/requirements/linux_requirement.rb | # typed: strict
# frozen_string_literal: true
# A requirement on Linux.
class LinuxRequirement < Requirement
fatal true
satisfy(build_env: false) { OS.linux? }
sig { returns(String) }
def message
"Linux is required for this software."
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/json_download.rb | Library/Homebrew/api/json_download.rb | # typed: strict
# frozen_string_literal: true
require "downloadable"
module Homebrew
module API
class JSONDownloadStrategy < AbstractDownloadStrategy
sig { params(url: String, name: String, version: T.nilable(T.any(String, Version)), meta: T.untyped).void }
def initialize(url, name, version, **meta)
super
@target = T.let(meta.fetch(:target), Pathname)
@stale_seconds = T.let(meta[:stale_seconds], T.nilable(Integer))
end
sig { override.params(timeout: T.nilable(T.any(Integer, Float))).returns(Pathname) }
def fetch(timeout: nil)
with_context quiet: quiet? do
Homebrew::API.fetch_json_api_file(url, target: cached_location, stale_seconds: meta[:stale_seconds])
end
cached_location
end
sig { override.returns(T.nilable(Integer)) }
def fetched_size
File.size?(cached_location)
end
sig { override.returns(Pathname) }
def cached_location
meta.fetch(:target)
end
end
class JSONDownload
include Downloadable
sig { params(url: String, target: Pathname, stale_seconds: T.nilable(Integer)).void }
def initialize(url, target:, stale_seconds:)
super()
@url = T.let(URL.new(url, using: API::JSONDownloadStrategy, target:, stale_seconds:), URL)
@target = target
@stale_seconds = stale_seconds
end
sig { override.returns(API::JSONDownloadStrategy) }
def downloader
T.cast(super, API::JSONDownloadStrategy)
end
sig { override.returns(String) }
def download_queue_type = "JSON API"
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/source_download.rb | Library/Homebrew/api/source_download.rb | # typed: strict
# frozen_string_literal: true
require "downloadable"
module Homebrew
module API
class SourceDownloadStrategy < CurlDownloadStrategy
sig { override.returns(Pathname) }
def symlink_location
cache/name
end
end
class SourceDownload
include Downloadable
sig {
params(
url: String,
checksum: T.nilable(Checksum),
mirrors: T::Array[String],
cache: T.nilable(Pathname),
).void
}
def initialize(url, checksum, mirrors: [], cache: nil)
super()
@url = T.let(URL.new(url, using: API::SourceDownloadStrategy), URL)
@checksum = checksum
@mirrors = mirrors
@cache = cache
end
sig { override.returns(API::SourceDownloadStrategy) }
def downloader
T.cast(super, API::SourceDownloadStrategy)
end
sig { override.returns(String) }
def download_queue_type = "API Source"
sig { override.returns(Pathname) }
def cache
@cache || super
end
sig { returns(Pathname) }
def symlink_location
downloader.symlink_location
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/formula_struct.rb | Library/Homebrew/api/formula_struct.rb | # typed: strict
# frozen_string_literal: true
require "service"
require "utils/spdx"
module Homebrew
module API
class FormulaStruct < T::Struct
PREDICATES = [
:bottle,
:deprecate,
:disable,
:head,
:keg_only,
:no_autobump_message,
:pour_bottle,
:service,
:service_run,
:service_name,
:stable,
].freeze
# `:codesign` and custom requirement classes are not supported.
API_SUPPORTED_REQUIREMENTS = [:arch, :linux, :macos, :maximum_macos, :xcode].freeze
private_constant :API_SUPPORTED_REQUIREMENTS
DependencyArgs = T.type_alias do
T.any(
# Formula name: "foo"
String,
# Formula name and dependency type: { "foo" => :build }
T::Hash[String, Symbol],
)
end
RequirementArgs = T.type_alias do
T.any(
# Requirement name: :macos
Symbol,
# Requirement name and other info: { macos: :build }
T::Hash[Symbol, T::Array[T.anything]],
)
end
UsesFromMacOSArgs = T.type_alias do
[
T.any(
# Formula name: "foo"
String,
# Formula name and dependency type: { "foo" => :build }
# Formula name, dependency type, and version bounds: { "foo" => :build, since: :catalina }
T::Hash[T.any(String, Symbol), T.any(Symbol, T::Array[Symbol])],
),
# If the first argument is only a name, this argument contains the version bounds: { since: :catalina }
T::Hash[Symbol, Symbol],
]
end
PREDICATES.each do |predicate_name|
present_method_name = :"#{predicate_name}_present"
predicate_method_name = :"#{predicate_name}?"
const present_method_name, T::Boolean, default: false
define_method(predicate_method_name) do
send(present_method_name)
end
end
# Changes to this struct must be mirrored in Homebrew::API::Formula.generate_formula_struct_hash
const :aliases, T::Array[String], default: []
const :bottle, T::Hash[String, T.anything], default: {}
const :bottle_checksums, T::Array[T::Hash[String, T.anything]], default: []
const :bottle_rebuild, Integer, default: 0
const :caveats, T.nilable(String)
const :conflicts, T::Array[[String, T::Hash[Symbol, String]]], default: []
const :deprecate_args, T::Hash[Symbol, T.nilable(T.any(String, Symbol))], default: {}
const :desc, String
const :disable_args, T::Hash[Symbol, T.nilable(T.any(String, Symbol))], default: {}
const :head_url_args, [String, T::Hash[Symbol, T.anything]]
const :homepage, String
const :keg_only_args, T::Array[T.any(String, Symbol)], default: []
const :license, SPDX::LicenseExpression
const :link_overwrite_paths, T::Array[String], default: []
const :no_autobump_args, T::Hash[Symbol, T.any(String, Symbol)], default: {}
const :oldnames, T::Array[String], default: []
const :post_install_defined, T::Boolean, default: true
const :pour_bottle_args, T::Hash[Symbol, Symbol], default: {}
const :revision, Integer, default: 0
const :ruby_source_checksum, String
const :ruby_source_path, String
const :service_args, T::Array[[Symbol, BasicObject]], default: []
const :service_name_args, T::Hash[Symbol, String], default: {}
const :service_run_args, T::Array[Homebrew::Service::RunParam], default: []
const :service_run_kwargs, T::Hash[Symbol, Homebrew::Service::RunParam], default: {}
const :stable_checksum, T.nilable(String)
const :stable_url_args, [String, T::Hash[Symbol, T.anything]]
const :stable_version, String
const :tap_git_head, String
const :version_scheme, Integer, default: 0
const :versioned_formulae, T::Array[String], default: []
sig { returns(T::Array[T.any(DependencyArgs, RequirementArgs)]) }
def head_dependencies
spec_dependencies(:head) + spec_requirements(:head)
end
sig { returns(T::Array[T.any(DependencyArgs, RequirementArgs)]) }
def stable_dependencies
spec_dependencies(:stable) + spec_requirements(:stable)
end
sig { returns(T::Array[UsesFromMacOSArgs]) }
def head_uses_from_macos
spec_uses_from_macos(:head)
end
sig { returns(T::Array[UsesFromMacOSArgs]) }
def stable_uses_from_macos
spec_uses_from_macos(:stable)
end
private
const :stable_dependency_hash, T::Hash[String, T::Array[String]], default: {}
const :head_dependency_hash, T::Hash[String, T::Array[String]], default: {}
const :requirements_array, T::Array[T::Hash[String, T.untyped]], default: []
sig { params(spec: Symbol).returns(T::Array[DependencyArgs]) }
def spec_dependencies(spec)
deps_hash = send("#{spec}_dependency_hash")
dependencies = deps_hash.fetch("dependencies", [])
dependencies + [:build, :test, :recommended, :optional].filter_map do |type|
deps_hash["#{type}_dependencies"]&.map do |dep|
{ dep => type }
end
end.flatten(1)
end
sig { params(spec: Symbol).returns(T::Array[UsesFromMacOSArgs]) }
def spec_uses_from_macos(spec)
deps_hash = send("#{spec}_dependency_hash")
zipped_array = deps_hash["uses_from_macos"]&.zip(deps_hash["uses_from_macos_bounds"])
return [] unless zipped_array
zipped_array.map do |entry, bounds|
bounds ||= {}
bounds = bounds.transform_keys(&:to_sym).transform_values(&:to_sym)
if entry.is_a?(Hash)
# The key is the dependency name, the value is the dep type. Only the type should be a symbol
entry = entry.deep_transform_values(&:to_sym)
# When passing both a dep type and bounds, uses_from_macos expects them both in the first argument
entry = entry.merge(bounds)
[entry, {}]
else
[entry, bounds]
end
end
end
sig { params(spec: Symbol).returns(T::Array[RequirementArgs]) }
def spec_requirements(spec)
requirements_array.filter_map do |req|
next unless req["specs"].include?(spec.to_s)
req_name = req["name"].to_sym
next if API_SUPPORTED_REQUIREMENTS.exclude?(req_name)
req_version = case req_name
when :arch
req["version"]&.to_sym
when :macos, :maximum_macos
MacOSVersion::SYMBOLS.key(req["version"])
else
req["version"]
end
req_tags = []
req_tags << req_version if req_version.present?
req_tags += req["contexts"]&.map do |tag|
case tag
when String
tag.to_sym
when Hash
tag.deep_transform_keys(&:to_sym)
else
tag
end
end
if req_tags.empty?
req_name
else
{ req_name => req_tags }
end
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/formula.rb | Library/Homebrew/api/formula.rb | # typed: strict
# frozen_string_literal: true
require "cachable"
require "api"
require "api/source_download"
require "download_queue"
require "autobump_constants"
module Homebrew
module API
# Helper functions for using the formula JSON API.
module Formula
extend Cachable
DEFAULT_API_FILENAME = "formula.jws.json"
private_class_method :cache
sig { params(name: String).returns(T::Hash[String, T.untyped]) }
def self.formula_json(name)
fetch_formula_json! name if !cache.key?("formula_json") || !cache.fetch("formula_json").key?(name)
cache.fetch("formula_json").fetch(name)
end
sig { params(name: String, download_queue: T.nilable(DownloadQueue)).void }
def self.fetch_formula_json!(name, download_queue: nil)
endpoint = "formula/#{name}.json"
json_formula, updated = Homebrew::API.fetch_json_api_file endpoint, download_queue: download_queue
return if download_queue
json_formula = JSON.parse((HOMEBREW_CACHE_API/endpoint).read) unless updated
cache["formula_json"] ||= {}
cache["formula_json"][name] = json_formula
end
sig { params(formula: ::Formula, download_queue: T.nilable(Homebrew::DownloadQueue)).returns(Homebrew::API::SourceDownload) }
def self.source_download(formula, download_queue: nil)
path = formula.ruby_source_path || "Formula/#{formula.name}.rb"
git_head = formula.tap_git_head || "HEAD"
tap = formula.tap&.full_name || "Homebrew/homebrew-core"
download = Homebrew::API::SourceDownload.new(
"https://raw.githubusercontent.com/#{tap}/#{git_head}/#{path}",
formula.ruby_source_checksum,
cache: HOMEBREW_CACHE_API_SOURCE/"#{tap}/#{git_head}/Formula",
)
if download_queue
download_queue.enqueue(download)
elsif !download.symlink_location.exist?
download.fetch
end
download
end
sig { params(formula: ::Formula).returns(::Formula) }
def self.source_download_formula(formula)
download = source_download(formula)
with_env(HOMEBREW_INTERNAL_ALLOW_PACKAGES_FROM_PATHS: "1") do
Formulary.factory(download.symlink_location,
formula.active_spec_sym,
alias_path: formula.alias_path,
flags: formula.class.build_flags)
end
end
sig { returns(Pathname) }
def self.cached_json_file_path
HOMEBREW_CACHE_API/DEFAULT_API_FILENAME
end
sig {
params(download_queue: T.nilable(Homebrew::DownloadQueue), stale_seconds: T.nilable(Integer))
.returns([T.any(T::Array[T.untyped], T::Hash[String, T.untyped]), T::Boolean])
}
def self.fetch_api!(download_queue: nil, stale_seconds: nil)
Homebrew::API.fetch_json_api_file DEFAULT_API_FILENAME, stale_seconds:, download_queue:
end
sig {
params(download_queue: T.nilable(Homebrew::DownloadQueue), stale_seconds: T.nilable(Integer))
.returns([T.any(T::Array[T.untyped], T::Hash[String, T.untyped]), T::Boolean])
}
def self.fetch_tap_migrations!(download_queue: nil, stale_seconds: nil)
Homebrew::API.fetch_json_api_file "formula_tap_migrations.jws.json", stale_seconds:, download_queue:
end
sig { returns(T::Boolean) }
def self.download_and_cache_data!
json_formulae, updated = fetch_api!
cache["aliases"] = {}
cache["renames"] = {}
cache["formulae"] = json_formulae.to_h do |json_formula|
json_formula["aliases"].each do |alias_name|
cache["aliases"][alias_name] = json_formula["name"]
end
(json_formula["oldnames"] || [json_formula["oldname"]].compact).each do |oldname|
cache["renames"][oldname] = json_formula["name"]
end
[json_formula["name"], json_formula.except("name")]
end
updated
end
private_class_method :download_and_cache_data!
sig { returns(T::Hash[String, T.untyped]) }
def self.all_formulae
unless cache.key?("formulae")
json_updated = download_and_cache_data!
write_names_and_aliases(regenerate: json_updated)
end
cache.fetch("formulae")
end
sig { returns(T::Hash[String, String]) }
def self.all_aliases
unless cache.key?("aliases")
json_updated = download_and_cache_data!
write_names_and_aliases(regenerate: json_updated)
end
cache.fetch("aliases")
end
sig { returns(T::Hash[String, String]) }
def self.all_renames
unless cache.key?("renames")
json_updated = download_and_cache_data!
write_names_and_aliases(regenerate: json_updated)
end
cache.fetch("renames")
end
sig { returns(T::Hash[String, T.untyped]) }
def self.tap_migrations
unless cache.key?("tap_migrations")
json_migrations, = fetch_tap_migrations!
cache["tap_migrations"] = json_migrations
end
cache.fetch("tap_migrations")
end
sig { params(regenerate: T::Boolean).void }
def self.write_names_and_aliases(regenerate: false)
download_and_cache_data! unless cache.key?("formulae")
Homebrew::API.write_names_file!(all_formulae.keys, "formula", regenerate:)
Homebrew::API.write_aliases_file!(all_aliases, "formula", regenerate:)
end
sig { params(hash: T::Hash[String, T.untyped]).returns(FormulaStruct) }
def self.generate_formula_struct_hash(hash)
hash = Homebrew::API.merge_variations(hash).dup
if (caveats = hash["caveats"])
hash["caveats"] = Formulary.replace_placeholders(caveats)
end
hash["bottle_checksums"] = begin
files = hash.dig("bottle", "stable", "files") || {}
files.map do |tag, bottle_spec|
{
cellar: Utils.convert_to_string_or_symbol(bottle_spec.fetch("cellar")),
tag.to_sym => bottle_spec.fetch("sha256"),
}
end
end
hash["bottle_rebuild"] = hash.dig("bottle", "stable", "rebuild")
conflicts_with = hash["conflicts_with"] || []
conflicts_with_reasons = hash["conflicts_with_reasons"] || []
hash["conflicts"] = conflicts_with.zip(conflicts_with_reasons).map do |name, reason|
if reason.present?
[name, { because: reason }]
else
[name, {}]
end
end
if (deprecate_args = hash["deprecate_args"])
deprecate_args = deprecate_args.dup.transform_keys(&:to_sym)
deprecate_args[:because] =
DeprecateDisable.to_reason_string_or_symbol(deprecate_args[:because], type: :formula)
hash["deprecate_args"] = deprecate_args
end
if (disable_args = hash["disable_args"])
disable_args = disable_args.dup.transform_keys(&:to_sym)
disable_args[:because] = DeprecateDisable.to_reason_string_or_symbol(disable_args[:because], type: :formula)
hash["disable_args"] = disable_args
end
hash["head_dependency_hash"] = hash["head_dependencies"]
hash["head_url_args"] = begin
url = hash.dig("urls", "head", "url")
specs = {
branch: hash.dig("urls", "head", "branch"),
using: hash.dig("urls", "head", "using")&.to_sym,
}.compact_blank
[url, specs]
end
if (keg_only_hash = hash["keg_only_reason"])
reason = Utils.convert_to_string_or_symbol(keg_only_hash.fetch("reason"))
explanation = keg_only_hash["explanation"]
hash["keg_only_args"] = [reason, explanation].compact
end
hash["license"] = SPDX.string_to_license_expression(hash["license"])
hash["link_overwrite_paths"] = hash["link_overwrite"]
if (reason = hash["no_autobump_message"])
reason = reason.to_sym if NO_AUTOBUMP_REASONS_LIST.key?(reason.to_sym)
hash["no_autobump_args"] = { because: reason }
end
if (condition = hash["pour_bottle_only_if"])
hash["pour_bottle_args"] = { only_if: condition.to_sym }
end
hash["requirements_array"] = hash["requirements"]
hash["ruby_source_checksum"] = hash.dig("ruby_source_checksum", "sha256")
if (service_hash = hash["service"])
service_hash = Homebrew::Service.from_hash(service_hash)
hash["service_run_args"], hash["service_run_kwargs"] = case (run = service_hash[:run])
when Hash
[[], run]
when Array, String
[[run], {}]
else
[[], {}]
end
hash["service_name_args"] = service_hash[:name]
hash["service_args"] = service_hash.filter_map do |key, arg|
[key.to_sym, arg] if key != :name && key != :run
end
end
hash["stable_checksum"] = hash.dig("urls", "stable", "checksum")
hash["stable_dependency_hash"] = {
"dependencies" => hash["dependencies"] || [],
"build_dependencies" => hash["build_dependencies"] || [],
"test_dependencies" => hash["test_dependencies"] || [],
"recommended_dependencies" => hash["recommended_dependencies"] || [],
"optional_dependencies" => hash["optional_dependencies"] || [],
"uses_from_macos" => hash["uses_from_macos"] || [],
"uses_from_macos_bounds" => hash["uses_from_macos_bounds"] || [],
}
hash["stable_url_args"] = begin
url = hash.dig("urls", "stable", "url")
specs = {
tag: hash.dig("urls", "stable", "tag"),
revision: hash.dig("urls", "stable", "revision"),
using: hash.dig("urls", "stable", "using")&.to_sym,
}.compact_blank
[url, specs]
end
hash["stable_version"] = hash.dig("versions", "stable")
# Should match FormulaStruct::PREDICATES
hash["bottle_present"] = hash["bottle"].present?
hash["deprecate_present"] = hash["deprecate_args"].present?
hash["disable_present"] = hash["disable_args"].present?
hash["head_present"] = hash.dig("urls", "head").present?
hash["keg_only_present"] = hash["keg_only_reason"].present?
hash["no_autobump_message_present"] = hash["no_autobump_message"].present?
hash["pour_bottle_present"] = hash["pour_bottle_only_if"].present?
hash["service_present"] = hash["service"].present?
hash["service_run_present"] = hash.dig("service", "run").present?
hash["service_name_present"] = hash.dig("service", "name").present?
hash["stable_present"] = hash.dig("urls", "stable").present?
FormulaStruct.from_hash(hash)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/cask.rb | Library/Homebrew/api/cask.rb | # typed: strict
# frozen_string_literal: true
require "cachable"
require "api"
require "api/source_download"
require "download_queue"
module Homebrew
module API
# Helper functions for using the cask JSON API.
module Cask
extend Cachable
DEFAULT_API_FILENAME = "cask.jws.json"
private_class_method :cache
sig { params(name: String).returns(T::Hash[String, T.untyped]) }
def self.cask_json(name)
fetch_cask_json! name if !cache.key?("cask_json") || !cache.fetch("cask_json").key?(name)
cache.fetch("cask_json").fetch(name)
end
sig { params(name: String, download_queue: T.nilable(DownloadQueue)).void }
def self.fetch_cask_json!(name, download_queue: nil)
endpoint = "cask/#{name}.json"
json_cask, updated = Homebrew::API.fetch_json_api_file endpoint, download_queue: download_queue
return if download_queue
json_cask = JSON.parse((HOMEBREW_CACHE_API/endpoint).read) unless updated
cache["cask_json"] ||= {}
cache["cask_json"][name] = json_cask
end
sig { params(cask: ::Cask::Cask, download_queue: T.nilable(Homebrew::DownloadQueue)).returns(Homebrew::API::SourceDownload) }
def self.source_download(cask, download_queue: nil)
path = cask.ruby_source_path.to_s
sha256 = cask.ruby_source_checksum[:sha256]
checksum = Checksum.new(sha256) if sha256
git_head = cask.tap_git_head || "HEAD"
tap = cask.tap&.full_name || "Homebrew/homebrew-cask"
download = Homebrew::API::SourceDownload.new(
"https://raw.githubusercontent.com/#{tap}/#{git_head}/#{path}",
checksum,
mirrors: [
"#{HOMEBREW_API_DEFAULT_DOMAIN}/cask-source/#{File.basename(path)}",
],
cache: HOMEBREW_CACHE_API_SOURCE/"#{tap}/#{git_head}/Cask",
)
if download_queue
download_queue.enqueue(download)
elsif !download.symlink_location.exist?
download.fetch
end
download
end
sig { params(cask: ::Cask::Cask).returns(::Cask::Cask) }
def self.source_download_cask(cask)
download = source_download(cask)
::Cask::CaskLoader::FromPathLoader.new(download.symlink_location)
.load(config: cask.config)
end
sig { returns(Pathname) }
def self.cached_json_file_path
HOMEBREW_CACHE_API/DEFAULT_API_FILENAME
end
sig {
params(download_queue: T.nilable(::Homebrew::DownloadQueue), stale_seconds: T.nilable(Integer))
.returns([T.any(T::Array[T.untyped], T::Hash[String, T.untyped]), T::Boolean])
}
def self.fetch_api!(download_queue: nil, stale_seconds: nil)
Homebrew::API.fetch_json_api_file DEFAULT_API_FILENAME, stale_seconds:, download_queue:
end
sig {
params(download_queue: T.nilable(::Homebrew::DownloadQueue), stale_seconds: T.nilable(Integer))
.returns([T.any(T::Array[T.untyped], T::Hash[String, T.untyped]), T::Boolean])
}
def self.fetch_tap_migrations!(download_queue: nil, stale_seconds: nil)
Homebrew::API.fetch_json_api_file "cask_tap_migrations.jws.json", stale_seconds:, download_queue:
end
sig { returns(T::Boolean) }
def self.download_and_cache_data!
json_casks, updated = fetch_api!
cache["renames"] = {}
cache["casks"] = json_casks.to_h do |json_cask|
token = json_cask["token"]
json_cask.fetch("old_tokens", []).each do |old_token|
cache["renames"][old_token] = token
end
[token, json_cask.except("token")]
end
updated
end
private_class_method :download_and_cache_data!
sig { returns(T::Hash[String, T::Hash[String, T.untyped]]) }
def self.all_casks
unless cache.key?("casks")
json_updated = download_and_cache_data!
write_names(regenerate: json_updated)
end
cache.fetch("casks")
end
sig { returns(T::Hash[String, String]) }
def self.all_renames
unless cache.key?("renames")
json_updated = download_and_cache_data!
write_names(regenerate: json_updated)
end
cache.fetch("renames")
end
sig { returns(T::Hash[String, T.untyped]) }
def self.tap_migrations
unless cache.key?("tap_migrations")
json_migrations, = fetch_tap_migrations!
cache["tap_migrations"] = json_migrations
end
cache.fetch("tap_migrations")
end
sig { params(regenerate: T::Boolean).void }
def self.write_names(regenerate: false)
download_and_cache_data! unless cache.key?("casks")
Homebrew::API.write_names_file!(all_casks.keys, "cask", regenerate:)
end
# NOTE: this will be used to load installed cask JSON files, so it must never fail with older JSON API versions)
sig { params(hash: T::Hash[String, T.untyped]).returns(CaskStruct) }
def self.generate_cask_struct_hash(hash)
hash = Homebrew::API.merge_variations(hash).dup.deep_symbolize_keys.transform_keys(&:to_s)
hash["conflicts_with_args"] = hash["conflicts_with"]
hash["container_args"] = hash["container"]&.to_h do |key, value|
next [key, value.to_sym] if key == :type
[key, value]
end
hash["depends_on_args"] = hash["depends_on"]&.to_h do |key, value|
# Arch dependencies are encoded like `{ type: :intel, bits: 64 }`
# but `depends_on arch:` only accepts `:intel` or `:arm64`
if key == :arch
next [:arch, :intel] if value.first[:type] == "intel"
next [:arch, :arm64]
end
next [key, value] if key != :macos
dep_type = value.keys.first
if dep_type == :==
version_symbols = value[dep_type].filter_map do |version|
MacOSVersion::SYMBOLS.key(version)
end
next [key, version_symbols.presence]
end
version_symbol = value[dep_type].first
version_symbol = MacOSVersion::SYMBOLS.key(version_symbol)
version_dep = "#{dep_type} :#{version_symbol}" if version_symbol
[key, version_dep]
end&.compact_blank
if (deprecate_args = hash["deprecate_args"])
deprecate_args = deprecate_args.dup
deprecate_args[:because] =
DeprecateDisable.to_reason_string_or_symbol(deprecate_args[:because], type: :cask)
hash["deprecate_args"] = deprecate_args
end
if (disable_args = hash["disable_args"])
disable_args = disable_args.dup
disable_args[:because] = DeprecateDisable.to_reason_string_or_symbol(disable_args[:because], type: :cask)
hash["disable_args"] = disable_args
end
hash["names"] = hash["name"]
hash["raw_artifacts"] = Array(hash["artifacts"]).map do |artifact|
key = artifact.keys.first
# Pass an empty block to artifacts like postflight that can't be loaded from the API,
# but need to be set to something.
next [key, [], {}, -> {}] if artifact[key].nil?
args = artifact[key]
kwargs = if args.last.is_a?(Hash)
args.pop
else
{}
end
[key, args, kwargs, nil]
end
hash["raw_caveats"] = hash["caveats"]
hash["renames"] = hash["rename"]&.map do |operation|
[operation[:from], operation[:to]]
end
hash["ruby_source_checksum"] = {
sha256: hash.dig("ruby_source_checksum", :sha256),
}
hash["sha256"] = :no_check if hash["sha256"] == "no_check"
hash["tap_string"] = hash["tap"]
hash["url_args"] = [hash["url"]]
hash["url_kwargs"] = hash["url_specs"]&.to_h do |key, value|
value = case key
when :user_agent
Utils.convert_to_string_or_symbol(value)
when :using
value.to_sym
else
value
end
[key, value]
end&.compact_blank
# Should match CaskStruct::PREDICATES
hash["auto_updates_present"] = hash["auto_updates"].present?
hash["caveats_present"] = hash["caveats"].present?
hash["conflicts_present"] = hash["conflicts_with"].present?
hash["container_present"] = hash["container"].present?
hash["depends_on_present"] = hash["depends_on_args"].present?
hash["deprecate_present"] = hash["deprecate_args"].present?
hash["desc_present"] = hash["desc"].present?
hash["disable_present"] = hash["disable_args"].present?
CaskStruct.from_hash(hash)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/internal.rb | Library/Homebrew/api/internal.rb | # typed: strict
# frozen_string_literal: true
require "cachable"
require "api"
require "api/source_download"
require "download_queue"
require "formula_stub"
module Homebrew
module API
# Helper functions for using the JSON internal API.
module Internal
extend Cachable
private_class_method :cache
sig { returns(String) }
def self.formula_endpoint
"internal/formula.#{SimulateSystem.current_tag}.jws.json"
end
sig { returns(String) }
def self.cask_endpoint
"internal/cask.#{SimulateSystem.current_tag}.jws.json"
end
sig { params(name: String).returns(Homebrew::FormulaStub) }
def self.formula_stub(name)
return cache["formula_stubs"][name] if cache.key?("formula_stubs") && cache["formula_stubs"].key?(name)
stub_array = formula_arrays[name]
raise "No formula stub found for #{name}" unless stub_array
aliases = formula_aliases.filter_map do |alias_name, original_name|
alias_name if original_name == name
end
oldnames = formula_renames.filter_map do |oldname, newname|
oldname if newname == name
end
stub = Homebrew::FormulaStub.new(
name: name,
pkg_version: PkgVersion.parse(stub_array[0]),
version_scheme: stub_array[1],
rebuild: stub_array[2],
sha256: stub_array[3],
aliases:,
oldnames:,
)
cache["formula_stubs"] ||= {}
cache["formula_stubs"][name] = stub
stub
end
sig { returns(Pathname) }
def self.cached_formula_json_file_path
HOMEBREW_CACHE_API/formula_endpoint
end
sig { returns(Pathname) }
def self.cached_cask_json_file_path
HOMEBREW_CACHE_API/cask_endpoint
end
sig {
params(download_queue: T.nilable(Homebrew::DownloadQueue), stale_seconds: T.nilable(Integer))
.returns([T::Hash[String, T.untyped], T::Boolean])
}
def self.fetch_formula_api!(download_queue: nil, stale_seconds: nil)
json_contents, updated = Homebrew::API.fetch_json_api_file(formula_endpoint, stale_seconds:, download_queue:)
[T.cast(json_contents, T::Hash[String, T.untyped]), updated]
end
sig {
params(download_queue: T.nilable(Homebrew::DownloadQueue), stale_seconds: T.nilable(Integer))
.returns([T::Hash[String, T.untyped], T::Boolean])
}
def self.fetch_cask_api!(download_queue: nil, stale_seconds: nil)
json_contents, updated = Homebrew::API.fetch_json_api_file(cask_endpoint, stale_seconds:, download_queue:)
[T.cast(json_contents, T::Hash[String, T.untyped]), updated]
end
sig { returns(T::Boolean) }
def self.download_and_cache_formula_data!
json_contents, updated = fetch_formula_api!
cache["formula_stubs"] = {}
cache["formula_aliases"] = json_contents["aliases"]
cache["formula_renames"] = json_contents["renames"]
cache["formula_tap_migrations"] = json_contents["tap_migrations"]
cache["formula_arrays"] = json_contents["formulae"]
updated
end
private_class_method :download_and_cache_formula_data!
sig { returns(T::Boolean) }
def self.download_and_cache_cask_data!
json_contents, updated = fetch_cask_api!
cache["cask_stubs"] = {}
cache["cask_renames"] = json_contents["renames"]
cache["cask_tap_migrations"] = json_contents["tap_migrations"]
cache["cask_hashes"] = json_contents["casks"]
updated
end
private_class_method :download_and_cache_cask_data!
sig { params(regenerate: T::Boolean).void }
def self.write_formula_names_and_aliases(regenerate: false)
download_and_cache_formula_data! unless cache.key?("formula_arrays")
Homebrew::API.write_names_file!(formula_arrays.keys, "formula", regenerate:)
Homebrew::API.write_aliases_file!(formula_aliases, "formula", regenerate:)
end
sig { params(regenerate: T::Boolean).void }
def self.write_cask_names(regenerate: false)
download_and_cache_cask_data! unless cache.key?("cask_hashes")
Homebrew::API.write_names_file!(cask_hashes.keys, "cask", regenerate:)
end
sig { returns(T::Hash[String, [String, Integer, Integer, T.nilable(String)]]) }
def self.formula_arrays
unless cache.key?("formula_arrays")
updated = download_and_cache_formula_data!
write_formula_names_and_aliases(regenerate: updated)
end
cache["formula_arrays"]
end
sig { returns(T::Hash[String, String]) }
def self.formula_aliases
unless cache.key?("formula_aliases")
updated = download_and_cache_formula_data!
write_formula_names_and_aliases(regenerate: updated)
end
cache["formula_aliases"]
end
sig { returns(T::Hash[String, String]) }
def self.formula_renames
unless cache.key?("formula_renames")
updated = download_and_cache_formula_data!
write_formula_names_and_aliases(regenerate: updated)
end
cache["formula_renames"]
end
sig { returns(T::Hash[String, String]) }
def self.formula_tap_migrations
unless cache.key?("formula_tap_migrations")
updated = download_and_cache_formula_data!
write_formula_names_and_aliases(regenerate: updated)
end
cache["formula_tap_migrations"]
end
sig { returns(T::Hash[String, T::Hash[String, T.untyped]]) }
def self.cask_hashes
unless cache.key?("cask_hashes")
updated = download_and_cache_cask_data!
write_cask_names(regenerate: updated)
end
cache["cask_hashes"]
end
sig { returns(T::Hash[String, String]) }
def self.cask_renames
unless cache.key?("cask_renames")
updated = download_and_cache_cask_data!
write_cask_names(regenerate: updated)
end
cache["cask_renames"]
end
sig { returns(T::Hash[String, String]) }
def self.cask_tap_migrations
unless cache.key?("cask_tap_migrations")
updated = download_and_cache_cask_data!
write_cask_names(regenerate: updated)
end
cache["cask_tap_migrations"]
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/analytics.rb | Library/Homebrew/api/analytics.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module API
# Helper functions for using the analytics JSON API.
module Analytics
class << self
sig { returns(String) }
def analytics_api_path
"analytics"
end
sig { params(category: String, days: T.any(Integer, String)).returns(T::Hash[String, T.untyped]) }
def fetch(category, days)
Homebrew::API.fetch "#{analytics_api_path}/#{category}/#{days}d.json"
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/api/cask_struct.rb | Library/Homebrew/api/cask_struct.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module API
class CaskStruct < T::Struct
PREDICATES = [
:auto_updates,
:caveats,
:conflicts,
:container,
:depends_on,
:deprecate,
:desc,
:disable,
].freeze
ArtifactArgs = T.type_alias do
[
Symbol,
T::Array[T.anything],
T::Hash[Symbol, T.anything],
T.nilable(T.proc.void),
]
end
PREDICATES.each do |predicate_name|
present_method_name = :"#{predicate_name}_present"
predicate_method_name = :"#{predicate_name}?"
const present_method_name, T::Boolean, default: false
define_method(predicate_method_name) do
send(present_method_name)
end
end
# Changes to this struct must be mirrored in Homebrew::API::Cask.generate_cask_struct_hash
const :auto_updates, T::Boolean, default: false
const :conflicts_with_args, T::Hash[Symbol, T::Array[String]], default: {}
const :container_args, T::Hash[Symbol, T.any(Symbol, T.anything)], default: {}
const :depends_on_args, T::Hash[Symbol, T::Array[T.any(String, Symbol)]], default: {}
const :deprecate_args, T::Hash[Symbol, T.nilable(T.any(String, Symbol))], default: {}
const :desc, T.nilable(String)
const :disable_args, T::Hash[Symbol, T.nilable(T.any(String, Symbol))], default: {}
const :homepage, String
const :languages, T::Array[String], default: []
const :names, T::Array[String], default: []
const :renames, T::Array[[String, String]], default: []
const :ruby_source_checksum, T::Hash[Symbol, String]
const :ruby_source_path, String
const :sha256, T.any(String, Symbol)
const :tap_git_head, String
const :tap_string, String
const :url_args, T::Array[String], default: []
const :url_kwargs, T::Hash[Symbol, T.anything], default: {}
const :version, T.any(String, Symbol)
sig { params(appdir: T.any(Pathname, String)).returns(T::Array[ArtifactArgs]) }
def artifacts(appdir:)
deep_remove_placeholders(raw_artifacts, appdir.to_s)
end
sig { params(appdir: T.any(Pathname, String)).returns(T.nilable(String)) }
def caveats(appdir:)
deep_remove_placeholders(raw_caveats, appdir.to_s)
end
private
const :raw_artifacts, T::Array[ArtifactArgs], default: []
const :raw_caveats, T.nilable(String)
sig {
type_parameters(:U)
.params(
value: T.type_parameter(:U),
appdir: String,
)
.returns(T.type_parameter(:U))
}
def deep_remove_placeholders(value, appdir)
value = case value
when Hash
value.transform_values do |v|
deep_remove_placeholders(v, appdir)
end
when Array
value.map do |v|
deep_remove_placeholders(v, appdir)
end
when String
value.gsub(HOMEBREW_HOME_PLACEHOLDER, Dir.home)
.gsub(HOMEBREW_PREFIX_PLACEHOLDER, HOMEBREW_PREFIX)
.gsub(HOMEBREW_CELLAR_PLACEHOLDER, HOMEBREW_CELLAR)
.gsub(HOMEBREW_CASK_APPDIR_PLACEHOLDER, appdir)
else
value
end
T.cast(value, T.type_parameter(:U))
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/go_checker.rb | Library/Homebrew/bundle/go_checker.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module Checker
class GoChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :go
PACKAGE_TYPE_NAME = "Go Package"
sig { params(package: String, no_upgrade: T::Boolean).returns(String) }
def failure_reason(package, no_upgrade:)
"#{PACKAGE_TYPE_NAME} #{package} needs to be installed."
end
sig { params(package: String, no_upgrade: T::Boolean).returns(T::Boolean) }
def installed_and_up_to_date?(package, no_upgrade: false)
require "bundle/go_installer"
Homebrew::Bundle::GoInstaller.package_installed?(package)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/vscode_extension_dumper.rb | Library/Homebrew/bundle/vscode_extension_dumper.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module VscodeExtensionDumper
sig { void }
def self.reset!
@extensions = nil
end
sig { returns(T::Array[String]) }
def self.extensions
@extensions ||= T.let(nil, T.nilable(T::Array[String]))
@extensions ||= if Bundle.vscode_installed?
Bundle.exchange_uid_if_needed! do
ENV["WSL_DISTRO_NAME"] = ENV.fetch("HOMEBREW_WSL_DISTRO_NAME", nil)
`"#{Bundle.which_vscode}" --list-extensions 2>/dev/null`
end.split("\n").map(&:downcase)
else
[]
end
end
sig { returns(String) }
def self.dump
extensions.map { |name| "vscode \"#{name}\"" }.join("\n")
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/mac_app_store_dumper.rb | Library/Homebrew/bundle/mac_app_store_dumper.rb | # typed: strict
# frozen_string_literal: true
require "json"
module Homebrew
module Bundle
module MacAppStoreDumper
sig { void }
def self.reset!
@apps = nil
end
sig { returns(T::Array[[String, String]]) }
def self.apps
@apps ||= T.let(nil, T.nilable(T::Array[[String, String]]))
@apps ||= if Bundle.mas_installed?
`mas list 2>/dev/null`.split("\n").map do |app|
app_details = app.match(/\A\s*(?<id>\d+)\s+(?<name>.*?)\s+\((?<version>[\d.]*)\)\Z/)
# Only add the application details should we have a valid match.
# Strip unprintable characters
if app_details
name = T.must(app_details[:name])
[T.must(app_details[:id]), name.gsub(/[[:cntrl:]]|\p{C}/, "")]
end
end
else
[]
end.compact
end
sig { returns(T::Array[Integer]) }
def self.app_ids
apps.map { |id, _| id.to_i }
end
sig { returns(String) }
def self.dump
apps.sort_by { |_, name| name.downcase }.map { |id, name| "mas \"#{name}\", id: #{id}" }.join("\n")
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/tap_checker.rb | Library/Homebrew/bundle/tap_checker.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module Checker
class TapChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :tap
PACKAGE_TYPE_NAME = "Tap"
sig {
params(entries: T::Array[Homebrew::Bundle::Dsl::Entry], exit_on_first_error: T::Boolean,
no_upgrade: T::Boolean, verbose: T::Boolean).returns(T::Array[String])
}
def find_actionable(entries, exit_on_first_error: false, no_upgrade: false, verbose: false)
requested_taps = format_checkable(entries)
return [] if requested_taps.empty?
require "bundle/tap_dumper"
current_taps = Homebrew::Bundle::TapDumper.tap_names
(requested_taps - current_taps).map { |entry| "Tap #{entry} needs to be tapped." }
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/vscode_extension_installer.rb | Library/Homebrew/bundle/vscode_extension_installer.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module VscodeExtensionInstaller
sig { void }
def self.reset!
@installed_extensions = nil
end
sig { params(name: String, no_upgrade: T::Boolean, verbose: T::Boolean).returns(T::Boolean) }
def self.preinstall!(name, no_upgrade: false, verbose: false)
if !Bundle.vscode_installed? && Bundle.cask_installed?
puts "Installing visual-studio-code. It is not currently installed." if verbose
Bundle.brew("install", "--cask", "visual-studio-code", verbose:)
end
if extension_installed?(name)
puts "Skipping install of #{name} VSCode extension. It is already installed." if verbose
return false
end
raise "Unable to install #{name} VSCode extension. VSCode is not installed." unless Bundle.vscode_installed?
true
end
sig {
params(
name: String,
preinstall: T::Boolean,
no_upgrade: T::Boolean,
verbose: T::Boolean,
force: T::Boolean,
).returns(T::Boolean)
}
def self.install!(name, preinstall: true, no_upgrade: false, verbose: false, force: false)
return true unless preinstall
return true if extension_installed?(name)
puts "Installing #{name} VSCode extension. It is not currently installed." if verbose
return false unless Bundle.exchange_uid_if_needed! do
Bundle.system(T.must(Bundle.which_vscode), "--install-extension", name, verbose:)
end
installed_extensions << name
true
end
sig { params(name: String).returns(T::Boolean) }
def self.extension_installed?(name)
installed_extensions.include? name.downcase
end
sig { returns(T::Array[String]) }
def self.installed_extensions
require "bundle/vscode_extension_dumper"
@installed_extensions ||= T.let(
Homebrew::Bundle::VscodeExtensionDumper.extensions,
T.nilable(T::Array[String]),
)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/flatpak_dumper.rb | Library/Homebrew/bundle/flatpak_dumper.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module FlatpakDumper
sig { void }
def self.reset!
@packages = nil
@packages_with_remotes = nil
@remote_urls = nil
end
sig { returns(T::Hash[String, String]) }
def self.remote_urls
@remote_urls ||= T.let(nil, T.nilable(T::Hash[String, String]))
@remote_urls ||= if Bundle.flatpak_installed?
flatpak = Bundle.which_flatpak
output = `#{flatpak} remote-list --system --columns=name,url 2>/dev/null`.chomp
urls = {}
output.split("\n").each do |line|
parts = line.strip.split("\t")
next if parts.size < 2
name = parts[0]
url = parts[1]
urls[name] = url if name && url
end
urls
else
{}
end
end
sig { returns(T::Array[T::Hash[Symbol, String]]) }
def self.packages_with_remotes
@packages_with_remotes ||= T.let(nil, T.nilable(T::Array[T::Hash[Symbol, String]]))
@packages_with_remotes ||= if Bundle.flatpak_installed?
flatpak = Bundle.which_flatpak
# List applications with their origin remote
# Using --app to filter applications only
# Using --columns=application,origin to get app IDs and their remotes
output = `#{flatpak} list --app --columns=application,origin 2>/dev/null`.chomp
urls = remote_urls # Get the URL mapping
packages_list = output.split("\n").filter_map do |line|
parts = line.strip.split("\t")
name = parts[0]
next if parts.empty? || name.nil? || name.empty?
remote_name = parts[1] || "flathub"
remote_url = urls[remote_name]
{ name:, remote: remote_name, remote_url: }
end
packages_list.sort_by { |pkg| pkg[:name] }
else
[]
end
end
sig { returns(T::Array[String]) }
def self.packages
@packages ||= T.let(nil, T.nilable(T::Array[String]))
@packages ||= packages_with_remotes.map { |pkg| T.must(pkg[:name]) }
end
sig { returns(String) }
def self.dump
# 3-tier remote handling for dump:
# - Tier 1: flathub → no remote needed
# - Tier 2: single-app remote (*-origin) → dump with URL only
# - Tier 3: named shared remote → dump with remote: and url:
packages_with_remotes.map do |pkg|
remote_name = pkg[:remote]
remote_url = pkg[:remote_url]
if remote_name == "flathub"
# Tier 1: Don't specify remote for flathub (default)
"flatpak \"#{pkg[:name]}\""
elsif remote_name&.end_with?("-origin")
# Tier 2: Single-app remote - dump with URL only
if remote_url.present?
"flatpak \"#{pkg[:name]}\", remote: \"#{remote_url}\""
else
# Fallback if URL not available (shouldn't happen for -origin remotes)
"flatpak \"#{pkg[:name]}\", remote: \"#{remote_name}\""
end
elsif remote_url.present?
# Tier 3: Named shared remote - dump with name and URL
"flatpak \"#{pkg[:name]}\", remote: \"#{remote_name}\", url: \"#{remote_url}\""
else
# Named remote without URL (user-defined or system remote)
"flatpak \"#{pkg[:name]}\", remote: \"#{remote_name}\""
end
end.join("\n")
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/skipper.rb | Library/Homebrew/bundle/skipper.rb | # typed: strict
# frozen_string_literal: true
require "hardware"
module Homebrew
module Bundle
module Skipper
class << self
sig { params(entry: Dsl::Entry, silent: T::Boolean).returns(T::Boolean) }
def skip?(entry, silent: false)
require "bundle/formula_dumper"
return true if @failed_taps&.any? do |tap|
prefix = "#{tap}/"
entry.name.start_with?(prefix) || entry.options[:full_name]&.start_with?(prefix)
end
entry_type_skips = Array(skipped_entries[entry.type])
return false if entry_type_skips.empty?
# Check the name or ID particularly for Mac App Store entries where they
# can have spaces in the names (and the `mas` output format changes on
# occasion).
entry_ids = [entry.name, entry.options[:id]&.to_s].compact
return false unless entry_type_skips.intersect?(entry_ids)
puts Formatter.warning "Skipping #{entry.name}" unless silent
true
end
sig { params(tap_name: String).void }
def tap_failed!(tap_name)
@failed_taps ||= T.let([], T.nilable(T::Array[String]))
@failed_taps << tap_name
end
private
sig { returns(T::Hash[Symbol, T.nilable(T::Array[String])]) }
def skipped_entries
return @skipped_entries if @skipped_entries
@skipped_entries ||= T.let({}, T.nilable(T::Hash[Symbol, T.nilable(T::Array[String])]))
[:brew, :cask, :mas, :tap, :flatpak].each do |type|
@skipped_entries[type] =
ENV["HOMEBREW_BUNDLE_#{type.to_s.upcase}_SKIP"]&.split
end
@skipped_entries
end
end
end
end
end
require "extend/os/bundle/skipper"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/brew_checker.rb | Library/Homebrew/bundle/brew_checker.rb | # typed: strict
# frozen_string_literal: true
require "bundle/formula_installer"
module Homebrew
module Bundle
module Checker
class BrewChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :brew
PACKAGE_TYPE_NAME = "Formula"
sig { params(formula: String, no_upgrade: T::Boolean).returns(T::Boolean) }
def installed_and_up_to_date?(formula, no_upgrade: false)
Homebrew::Bundle::FormulaInstaller.formula_installed_and_up_to_date?(formula, no_upgrade:)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/go_installer.rb | Library/Homebrew/bundle/go_installer.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module GoInstaller
sig { void }
def self.reset!
@installed_packages = nil
end
sig { params(name: String, verbose: T::Boolean, _options: T.anything).returns(T::Boolean) }
def self.preinstall!(name, verbose: false, **_options)
unless Bundle.go_installed?
puts "Installing go. It is not currently installed." if verbose
Bundle.brew("install", "--formula", "go", verbose:)
raise "Unable to install #{name} package. Go installation failed." unless Bundle.go_installed?
end
if package_installed?(name)
puts "Skipping install of #{name} Go package. It is already installed." if verbose
return false
end
true
end
sig {
params(
name: String,
preinstall: T::Boolean,
verbose: T::Boolean,
force: T::Boolean,
_options: T.anything,
).returns(T::Boolean)
}
def self.install!(name, preinstall: true, verbose: false, force: false, **_options)
return true unless preinstall
puts "Installing #{name} Go package. It is not currently installed." if verbose
go = Bundle.which_go
return false unless Bundle.system go.to_s, "install", "#{name}@latest", verbose: verbose
installed_packages << name
true
end
sig { params(package: String).returns(T::Boolean) }
def self.package_installed?(package)
installed_packages.include? package
end
sig { returns(T::Array[String]) }
def self.installed_packages
require "bundle/go_dumper"
@installed_packages ||= T.let(Homebrew::Bundle::GoDumper.packages, T.nilable(T::Array[String]))
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/brew_service_checker.rb | Library/Homebrew/bundle/brew_service_checker.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module Bundle
module Checker
class BrewServiceChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :brew
PACKAGE_TYPE_NAME = "Service"
PACKAGE_ACTION_PREDICATE = "needs to be started."
def failure_reason(name, no_upgrade:)
"#{PACKAGE_TYPE_NAME} #{name} needs to be started."
end
def installed_and_up_to_date?(formula, no_upgrade: false)
return true unless formula_needs_to_start?(entry_to_formula(formula))
return true if service_is_started?(formula.name)
old_name = lookup_old_name(formula.name)
return true if old_name && service_is_started?(old_name)
false
end
def entry_to_formula(entry)
require "bundle/formula_installer"
Homebrew::Bundle::FormulaInstaller.new(entry.name, entry.options)
end
def formula_needs_to_start?(formula)
formula.start_service? || formula.restart_service?
end
def service_is_started?(service_name)
require "bundle/brew_services"
Homebrew::Bundle::BrewServices.started?(service_name)
end
def lookup_old_name(service_name)
require "bundle/formula_dumper"
@old_names ||= Homebrew::Bundle::FormulaDumper.formula_oldnames
old_name = @old_names[service_name]
old_name ||= @old_names[service_name.split("/").last]
old_name
end
def format_checkable(entries)
checkable_entries(entries)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/flatpak_installer.rb | Library/Homebrew/bundle/flatpak_installer.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module FlatpakInstaller
sig { void }
def self.reset!
@installed_packages = nil
end
sig {
params(
name: String,
verbose: T::Boolean,
remote: String,
url: T.nilable(String),
_options: T.anything,
).returns(T::Boolean)
}
def self.preinstall!(name, verbose: false, remote: "flathub", url: nil, **_options)
return false unless Bundle.flatpak_installed?
# Check if package is installed at all (regardless of remote)
if package_installed?(name)
puts "Skipping install of #{name} Flatpak. It is already installed." if verbose
return false
end
true
end
sig {
params(
name: String,
preinstall: T::Boolean,
verbose: T::Boolean,
force: T::Boolean,
remote: String,
url: T.nilable(String),
_options: T.anything,
).returns(T::Boolean)
}
def self.install!(name, preinstall: true, verbose: false, force: false, remote: "flathub", url: nil, **_options)
return true unless Bundle.flatpak_installed?
return true unless preinstall
flatpak = Bundle.which_flatpak.to_s
# 3-tier remote handling:
# - Tier 1: no URL → use named remote (default: flathub)
# - Tier 2: URL only → single-app remote (<app-id>-origin)
# - Tier 3: URL + name → named shared remote
if url.present?
# Tier 3: Named remote with URL - create shared remote
puts "Installing #{name} Flatpak from #{remote} (#{url}). It is not currently installed." if verbose
ensure_named_remote_exists!(flatpak, remote, url, verbose:)
actual_remote = remote
elsif remote.start_with?("http://", "https://")
if remote.end_with?(".flatpakref")
# .flatpakref files - install directly (Flatpak handles single-app remote natively)
puts "Installing #{name} Flatpak from #{remote}. It is not currently installed." if verbose
return install_flatpakref!(flatpak, name, remote, verbose:)
else
# Tier 2: URL only - create single-app remote
actual_remote = generate_single_app_remote_name(name)
if verbose
puts "Installing #{name} Flatpak from #{actual_remote} (#{remote}). It is not currently installed."
end
ensure_single_app_remote_exists!(flatpak, actual_remote, remote, verbose:)
end
else
# Tier 1: Named remote (default: flathub)
puts "Installing #{name} Flatpak from #{remote}. It is not currently installed." if verbose
actual_remote = remote
end
# Install from the remote
return false unless Bundle.system flatpak, "install", "-y", "--system", actual_remote, name,
verbose: verbose
installed_packages << { name:, remote: actual_remote }
true
end
# Install from a .flatpakref file (Tier 2 variant - Flatpak handles single-app remote natively)
sig { params(flatpak: String, name: String, url: String, verbose: T::Boolean).returns(T::Boolean) }
def self.install_flatpakref!(flatpak, name, url, verbose:)
return false unless Bundle.system flatpak, "install", "-y", "--system", url,
verbose: verbose
# Get the actual remote name used by Flatpak
output = `#{flatpak} list --app --columns=application,origin 2>/dev/null`.chomp
installed = output.split("\n").find { |line| line.start_with?(name) }
actual_remote = installed ? installed.split("\t")[1] : "#{name}-origin"
installed_packages << { name:, remote: actual_remote }
true
end
# Generate a single-app remote name (Tier 2)
# Pattern: <app-id>-origin (matches Flatpak's native behavior for .flatpakref)
sig { params(app_id: String).returns(String) }
def self.generate_single_app_remote_name(app_id)
"#{app_id}-origin"
end
# Ensure a single-app remote exists (Tier 2)
# Safe to replace if URL differs since it's isolated per-app
sig { params(flatpak: String, remote_name: String, url: String, verbose: T::Boolean).void }
def self.ensure_single_app_remote_exists!(flatpak, remote_name, url, verbose:)
existing_url = get_remote_url(flatpak, remote_name)
if existing_url && existing_url != url
# Single-app remote with different URL - safe to replace
puts "Replacing single-app remote #{remote_name} (URL changed)" if verbose
Bundle.system flatpak, "remote-delete", "--system", "--force", remote_name, verbose: verbose
existing_url = nil
end
return if existing_url # Already exists with correct URL
puts "Adding single-app remote #{remote_name} from #{url}" if verbose
add_remote!(flatpak, remote_name, url, verbose:)
end
# Ensure a named shared remote exists (Tier 3)
# Warn but don't change if URL differs (user explicitly named it)
sig { params(flatpak: String, remote_name: String, url: String, verbose: T::Boolean).void }
def self.ensure_named_remote_exists!(flatpak, remote_name, url, verbose:)
existing_url = get_remote_url(flatpak, remote_name)
if existing_url && existing_url != url
# Named remote with different URL - warn but don't change (user explicitly named it)
puts "Warning: Remote '#{remote_name}' exists with different URL (#{existing_url}), using existing"
return
end
return if existing_url # Already exists with correct URL
puts "Adding named remote #{remote_name} from #{url}" if verbose
add_remote!(flatpak, remote_name, url, verbose:)
end
# Get URL for an existing remote, or nil if not found
sig { params(flatpak: String, remote_name: String).returns(T.nilable(String)) }
def self.get_remote_url(flatpak, remote_name)
output = `#{flatpak} remote-list --system --columns=name,url 2>/dev/null`.chomp
output.split("\n").each do |line|
parts = line.split("\t")
return parts[1] if parts[0] == remote_name
end
nil
end
# Add a remote with appropriate flags
sig { params(flatpak: String, remote_name: String, url: String, verbose: T::Boolean).returns(T::Boolean) }
def self.add_remote!(flatpak, remote_name, url, verbose:)
if url.end_with?(".flatpakrepo")
Bundle.system flatpak, "remote-add", "--if-not-exists", "--system",
remote_name, url, verbose: verbose
else
# For bare repository URLs, add with --no-gpg-verify for user repos
Bundle.system flatpak, "remote-add", "--if-not-exists", "--system",
"--no-gpg-verify", remote_name, url, verbose: verbose
end
end
sig { params(package: String, remote: T.nilable(String)).returns(T::Boolean) }
def self.package_installed?(package, remote: nil)
if remote
# Check if package is installed from the specified remote
installed_packages.any? { |pkg| pkg[:name] == package && pkg[:remote] == remote }
else
# Just check if package is installed from any remote
installed_packages.any? { |pkg| pkg[:name] == package }
end
end
sig { returns(T::Array[T::Hash[Symbol, String]]) }
def self.installed_packages
require "bundle/flatpak_dumper"
@installed_packages ||= T.let(
Homebrew::Bundle::FlatpakDumper.packages_with_remotes,
T.nilable(T::Array[T::Hash[Symbol, String]]),
)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/dsl.rb | Library/Homebrew/bundle/dsl.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module Bundle
class Dsl
class Entry
attr_reader :type, :name, :options
def initialize(type, name, options = {})
@type = type
@name = name
@options = options
end
def to_s
name
end
end
attr_reader :entries, :cask_arguments, :input
def initialize(path)
@path = path
@input = path.read
@entries = []
@cask_arguments = {}
begin
process
# Want to catch all exceptions for e.g. syntax errors.
rescue Exception => e # rubocop:disable Lint/RescueException
error_msg = "Invalid Brewfile: #{e.message}"
raise RuntimeError, error_msg, e.backtrace
end
end
def process
instance_eval(@input, @path.to_s)
end
def cask_args(args)
raise "cask_args(#{args.inspect}) should be a Hash object" unless args.is_a? Hash
@cask_arguments.merge!(args)
end
def brew(name, options = {})
raise "name(#{name.inspect}) should be a String object" unless name.is_a? String
raise "options(#{options.inspect}) should be a Hash object" unless options.is_a? Hash
name = Homebrew::Bundle::Dsl.sanitize_brew_name(name)
@entries << Entry.new(:brew, name, options)
end
def cask(name, options = {})
raise "name(#{name.inspect}) should be a String object" unless name.is_a? String
raise "options(#{options.inspect}) should be a Hash object" unless options.is_a? Hash
options[:full_name] = name
name = Homebrew::Bundle::Dsl.sanitize_cask_name(name)
options[:args] = @cask_arguments.merge options.fetch(:args, {})
@entries << Entry.new(:cask, name, options)
end
def mas(name, options = {})
id = options[:id]
raise "name(#{name.inspect}) should be a String object" unless name.is_a? String
raise "options[:id](#{id}) should be an Integer object" unless id.is_a? Integer
@entries << Entry.new(:mas, name, id:)
end
def vscode(name)
raise "name(#{name.inspect}) should be a String object" unless name.is_a? String
@entries << Entry.new(:vscode, name)
end
sig { params(name: String).void }
def go(name)
@entries << Entry.new(:go, name)
end
sig { params(name: String).void }
def cargo(name)
@entries << Entry.new(:cargo, name)
end
sig { params(name: String, options: T::Hash[Symbol, String]).void }
def flatpak(name, options = {})
# Validate: url: can only be used with a named remote (not a URL remote)
if options[:url] && options[:remote]&.start_with?("http://", "https://")
raise "url: parameter cannot be used when remote: is already a URL"
end
# Default remote to "flathub"
options[:remote] ||= "flathub"
@entries << Entry.new(:flatpak, name, options)
end
def tap(name, clone_target = nil, options = {})
raise "name(#{name.inspect}) should be a String object" unless name.is_a? String
if clone_target && !clone_target.is_a?(String)
raise "clone_target(#{clone_target.inspect}) should be nil or a String object"
end
options[:clone_target] = clone_target
name = Homebrew::Bundle::Dsl.sanitize_tap_name(name)
@entries << Entry.new(:tap, name, options)
end
HOMEBREW_TAP_ARGS_REGEX = %r{^([\w-]+)/(homebrew-)?([\w-]+)$}
HOMEBREW_CORE_FORMULA_REGEX = %r{^homebrew/homebrew/([\w+-.@]+)$}i
HOMEBREW_TAP_FORMULA_REGEX = %r{^([\w-]+)/([\w-]+)/([\w+-.@]+)$}
def self.sanitize_brew_name(name)
name = name.downcase
if name =~ HOMEBREW_CORE_FORMULA_REGEX
Regexp.last_match(1)
elsif name =~ HOMEBREW_TAP_FORMULA_REGEX
user = Regexp.last_match(1)
repo = T.must(Regexp.last_match(2))
name = Regexp.last_match(3)
"#{user}/#{repo.sub("homebrew-", "")}/#{name}"
else
name
end
end
def self.sanitize_tap_name(name)
name = name.downcase
if name =~ HOMEBREW_TAP_ARGS_REGEX
"#{Regexp.last_match(1)}/#{Regexp.last_match(3)}"
else
name
end
end
def self.sanitize_cask_name(name)
name = name.split("/").last if name.include?("/")
name.downcase
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/brewfile.rb | Library/Homebrew/bundle/brewfile.rb | # typed: strict
# frozen_string_literal: true
require "bundle/dsl"
module Homebrew
module Bundle
module Brewfile
sig {
params(
dash_writes_to_stdout: T::Boolean,
global: T::Boolean,
file: T.nilable(String),
).returns(Pathname)
}
def self.path(dash_writes_to_stdout: false, global: false, file: nil)
env_bundle_file_global = ENV.fetch("HOMEBREW_BUNDLE_FILE_GLOBAL", nil)
env_bundle_file = ENV.fetch("HOMEBREW_BUNDLE_FILE", nil)
user_config_home = ENV.fetch("HOMEBREW_USER_CONFIG_HOME", nil)
filename = if global
if env_bundle_file_global.present?
env_bundle_file_global
else
raise "'HOMEBREW_BUNDLE_FILE' cannot be specified with '--global'" if env_bundle_file.present?
home_brewfile = Bundle.exchange_uid_if_needed! do
"#{Dir.home}/.Brewfile"
end
user_config_home_brewfile = "#{user_config_home}/Brewfile"
if user_config_home.present? && Dir.exist?(user_config_home) &&
(File.exist?(user_config_home_brewfile) || !File.exist?(home_brewfile))
user_config_home_brewfile
else
home_brewfile
end
end
elsif file.present?
handle_file_value(file, dash_writes_to_stdout)
elsif env_bundle_file.present?
env_bundle_file
else
"Brewfile"
end
Pathname.new(filename).expand_path(Dir.pwd)
end
sig { params(global: T::Boolean, file: T.nilable(String)).returns(Dsl) }
def self.read(global: false, file: nil)
Homebrew::Bundle::Dsl.new(Brewfile.path(global:, file:))
rescue Errno::ENOENT
raise "No Brewfile found"
end
sig {
params(
filename: String,
dash_writes_to_stdout: T::Boolean,
).returns(String)
}
private_class_method def self.handle_file_value(filename, dash_writes_to_stdout)
if filename != "-"
filename
elsif dash_writes_to_stdout
"/dev/stdout"
else
"/dev/stdin"
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/cask_installer.rb | Library/Homebrew/bundle/cask_installer.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module Bundle
module CaskInstaller
extend ::Utils::Output::Mixin
def self.reset!
@installed_casks = nil
@outdated_casks = nil
end
private_class_method def self.upgrading?(no_upgrade, name, options)
return false if no_upgrade
return true if cask_upgradable?(name)
return false unless options[:greedy]
require "bundle/cask_dumper"
Homebrew::Bundle::CaskDumper.cask_is_outdated_using_greedy?(name)
end
def self.preinstall!(name, no_upgrade: false, verbose: false, **options)
if cask_installed?(name) && !upgrading?(no_upgrade, name, options)
puts "Skipping install of #{name} cask. It is already installed." if verbose
return false
end
true
end
def self.install!(name, preinstall: true, no_upgrade: false, verbose: false, force: false, **options)
return true unless preinstall
full_name = options.fetch(:full_name, name)
install_result = if cask_installed?(name) && upgrading?(no_upgrade, name, options)
status = "#{options[:greedy] ? "may not be" : "not"} up-to-date"
puts "Upgrading #{name} cask. It is installed but #{status}." if verbose
Bundle.brew("upgrade", "--cask", full_name, verbose:)
else
args = options.fetch(:args, []).filter_map do |k, v|
case v
when TrueClass
"--#{k}"
when FalseClass, NilClass
nil
else
"--#{k}=#{v}"
end
end
args << "--force" if force
args << "--adopt" unless args.include?("--force")
args.uniq!
with_args = " with #{args.join(" ")}" if args.present?
puts "Installing #{name} cask#{with_args}. It is not currently installed." if verbose
if Bundle.brew("install", "--cask", full_name, *args, verbose:)
installed_casks << name
true
else
false
end
end
result = install_result
if cask_installed?(name)
postinstall_result = postinstall_change_state!(name:, options:, verbose:)
result &&= postinstall_result
end
result
end
def self.installable_or_upgradable?(name, no_upgrade: false, **options)
!cask_installed?(name) || upgrading?(no_upgrade, name, options)
end
private_class_method def self.postinstall_change_state!(name:, options:, verbose:)
postinstall = options.fetch(:postinstall, nil)
return true if postinstall.blank?
puts "Running postinstall for #{@name}: #{postinstall}" if verbose
Kernel.system(postinstall)
end
def self.cask_installed_and_up_to_date?(cask, no_upgrade: false)
return false unless cask_installed?(cask)
return true if no_upgrade
!cask_upgradable?(cask)
end
def self.cask_in_array?(cask, array)
return true if array.include?(cask)
array.include?(cask.split("/").last)
end
def self.cask_installed?(cask)
return true if cask_in_array?(cask, installed_casks)
require "bundle/cask_dumper"
old_names = Homebrew::Bundle::CaskDumper.cask_oldnames
old_name = old_names[cask]
old_name ||= old_names[cask.split("/").last]
return false unless old_name
return false unless cask_in_array?(old_name, installed_casks)
opoo "#{cask} was renamed to #{old_name}"
true
end
def self.cask_upgradable?(cask)
cask_in_array?(cask, outdated_casks)
end
def self.installed_casks
require "bundle/cask_dumper"
@installed_casks ||= Homebrew::Bundle::CaskDumper.cask_names
end
def self.outdated_casks
require "bundle/cask_dumper"
@outdated_casks ||= Homebrew::Bundle::CaskDumper.outdated_cask_names
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/adder.rb | Library/Homebrew/bundle/adder.rb | # typed: strict
# frozen_string_literal: true
require "bundle/brewfile"
require "bundle/dumper"
module Homebrew
module Bundle
module Adder
module_function
sig { params(args: String, type: Symbol, global: T::Boolean, file: String).void }
def add(*args, type:, global:, file:)
brewfile_path = Brewfile.path(global:, file:)
brewfile_path.write("") unless brewfile_path.exist?
brewfile = Brewfile.read(global:, file:)
content = brewfile.input
# TODO: - support `:describe`
new_content = args.map do |arg|
case type
when :brew
Formulary.factory(arg)
when :cask
Cask::CaskLoader.load(arg)
end
"#{type} \"#{arg}\""
end
content << new_content.join("\n") << "\n"
path = Dumper.brewfile_path(global:, file:)
Dumper.write_file path, content
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/lister.rb | Library/Homebrew/bundle/lister.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module Lister
sig {
params(entries: T::Array[Homebrew::Bundle::Dsl::Entry], formulae: T::Boolean, casks: T::Boolean,
taps: T::Boolean, mas: T::Boolean, vscode: T::Boolean, go: T::Boolean, cargo: T::Boolean,
flatpak: T::Boolean).void
}
def self.list(entries, formulae:, casks:, taps:, mas:, vscode:, go:, cargo:, flatpak:)
entries.each do |entry|
puts entry.name if show?(entry.type, formulae:, casks:, taps:, mas:, vscode:, go:, cargo:, flatpak:)
end
end
sig {
params(type: Symbol, formulae: T::Boolean, casks: T::Boolean, taps: T::Boolean, mas: T::Boolean,
vscode: T::Boolean, go: T::Boolean, cargo: T::Boolean, flatpak: T::Boolean).returns(T::Boolean)
}
private_class_method def self.show?(type, formulae:, casks:, taps:, mas:, vscode:, go:, cargo:, flatpak:)
return true if formulae && type == :brew
return true if casks && type == :cask
return true if taps && type == :tap
return true if mas && type == :mas
return true if vscode && type == :vscode
return true if go && type == :go
return true if cargo && type == :cargo
return true if flatpak && type == :flatpak
false
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/mac_app_store_checker.rb | Library/Homebrew/bundle/mac_app_store_checker.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "bundle/mac_app_store_installer"
module Homebrew
module Bundle
module Checker
class MacAppStoreChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :mas
PACKAGE_TYPE_NAME = "App"
def installed_and_up_to_date?(id, no_upgrade: false)
Homebrew::Bundle::MacAppStoreInstaller.app_id_installed_and_up_to_date?(id, no_upgrade:)
end
def format_checkable(entries)
checkable_entries(entries).to_h { |e| [e.options[:id], e.name] }
end
def exit_early_check(app_ids_with_names, no_upgrade:)
work_to_be_done = app_ids_with_names.find do |id, _name|
!installed_and_up_to_date?(id, no_upgrade:)
end
Array(work_to_be_done)
end
def full_check(app_ids_with_names, no_upgrade:)
app_ids_with_names.reject { |id, _name| installed_and_up_to_date?(id, no_upgrade:) }
.map { |_id, name| failure_reason(name, no_upgrade:) }
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/installer.rb | Library/Homebrew/bundle/installer.rb | # typed: strict
# frozen_string_literal: true
require "bundle/dsl"
require "bundle/formula_installer"
require "bundle/cask_installer"
require "bundle/mac_app_store_installer"
require "bundle/vscode_extension_installer"
require "bundle/go_installer"
require "bundle/cargo_installer"
require "bundle/flatpak_installer"
require "bundle/tap_installer"
require "bundle/skipper"
module Homebrew
module Bundle
module Installer
sig {
params(
entries: T::Array[Dsl::Entry],
global: T::Boolean,
file: T.nilable(String),
no_lock: T::Boolean,
no_upgrade: T::Boolean,
verbose: T::Boolean,
force: T::Boolean,
quiet: T::Boolean,
).returns(T::Boolean)
}
def self.install!(entries, global: false, file: nil, no_lock: false, no_upgrade: false, verbose: false,
force: false, quiet: false)
success = 0
failure = 0
installable_entries = entries.filter_map do |entry|
next if Homebrew::Bundle::Skipper.skip? entry
name = entry.name
args = [name]
options = {}
verb = "Installing"
type = entry.type
cls = case type
when :brew
options = entry.options
verb = "Upgrading" if Homebrew::Bundle::FormulaInstaller.formula_upgradable?(name)
Homebrew::Bundle::FormulaInstaller
when :cask
options = entry.options
verb = "Upgrading" if Homebrew::Bundle::CaskInstaller.cask_upgradable?(name)
Homebrew::Bundle::CaskInstaller
when :mas
args << entry.options[:id]
Homebrew::Bundle::MacAppStoreInstaller
when :vscode
Homebrew::Bundle::VscodeExtensionInstaller
when :go
Homebrew::Bundle::GoInstaller
when :cargo
Homebrew::Bundle::CargoInstaller
when :flatpak
options = entry.options
Homebrew::Bundle::FlatpakInstaller
when :tap
verb = "Tapping"
options = entry.options
Homebrew::Bundle::TapInstaller
end
next if cls.nil?
{ name:, args:, options:, verb:, type:, cls: }
end
if (fetchable_names = fetchable_formulae_and_casks(installable_entries, no_upgrade:).presence)
fetchable_names_joined = fetchable_names.join(", ")
Formatter.success("Fetching #{fetchable_names_joined}") unless quiet
unless Bundle.brew("fetch", *fetchable_names, verbose:)
$stderr.puts Formatter.error "`brew bundle` failed! Failed to fetch #{fetchable_names_joined}"
return false
end
end
installable_entries.each do |entry|
name = entry.fetch(:name)
args = entry.fetch(:args)
options = entry.fetch(:options)
verb = entry.fetch(:verb)
cls = entry.fetch(:cls)
preinstall = if cls.preinstall!(*args, **options, no_upgrade:, verbose:)
puts Formatter.success("#{verb} #{name}")
true
else
puts "Using #{name}" unless quiet
false
end
if cls.install!(*args, **options,
preinstall:, no_upgrade:, verbose:, force:)
success += 1
else
$stderr.puts Formatter.error("#{verb} #{name} has failed!")
failure += 1
end
end
unless failure.zero?
require "utils"
dependency = Utils.pluralize("dependency", failure)
$stderr.puts Formatter.error "`brew bundle` failed! #{failure} Brewfile #{dependency} failed to install"
return false
end
unless quiet
require "utils"
dependency = Utils.pluralize("dependency", success)
puts Formatter.success "`brew bundle` complete! #{success} Brewfile #{dependency} now installed."
end
true
end
sig {
params(
entries: T::Array[{ name: String,
args: T::Array[T.anything],
options: T::Hash[Symbol, T.untyped],
verb: String,
type: Symbol,
cls: T::Module[T.anything] }],
no_upgrade: T::Boolean,
).returns(T::Array[String])
}
def self.fetchable_formulae_and_casks(entries, no_upgrade:)
entries.filter_map do |entry|
name = entry.fetch(:name)
options = entry.fetch(:options)
case entry.fetch(:type)
when :brew
next unless tap_installed?(name)
next if Homebrew::Bundle::FormulaInstaller.formula_installed_and_up_to_date?(name, no_upgrade:)
name
when :cask
full_name = options.fetch(:full_name, name)
next unless tap_installed?(full_name)
next unless Homebrew::Bundle::CaskInstaller.installable_or_upgradable?(name, no_upgrade:, **options)
full_name
end
end
end
sig { params(package_full_name: String).returns(T::Boolean) }
def self.tap_installed?(package_full_name)
user, repository, = package_full_name.split("/", 3)
return true if user.blank? || repository.blank?
Homebrew::Bundle::TapInstaller.installed_taps.include?("#{user}/#{repository}")
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/formula_dumper.rb | Library/Homebrew/bundle/formula_dumper.rb | # typed: true
# frozen_string_literal: true
require "json"
require "tsort"
require "utils/output"
module Homebrew
module Bundle
# TODO: refactor into multiple modules
module FormulaDumper
extend Utils::Output::Mixin
def self.reset!
require "bundle/brew_services"
Homebrew::Bundle::BrewServices.reset!
@formulae = nil
@formulae_by_full_name = nil
@formulae_by_name = nil
@formula_aliases = nil
@formula_oldnames = nil
end
def self.formulae
return @formulae if @formulae
formulae_by_full_name
@formulae
end
def self.formulae_by_full_name(name = nil)
return @formulae_by_full_name[name] if name.present? && @formulae_by_full_name&.key?(name)
require "formula"
require "formulary"
Formulary.enable_factory_cache!
@formulae_by_name ||= {}
@formulae_by_full_name ||= {}
if name.nil?
formulae = Formula.installed.map { add_formula(it) }
sort!(formulae)
return @formulae_by_full_name
end
formula = Formula[name]
add_formula(formula)
rescue FormulaUnavailableError => e
opoo "'#{name}' formula is unreadable: #{e}"
{}
end
def self.formulae_by_name(name)
formulae_by_full_name(name) || @formulae_by_name[name]
end
def self.dump(describe: false, no_restart: false)
require "bundle/brew_services"
requested_formula = formulae.select do |f|
f[:installed_on_request?] || !f[:installed_as_dependency?]
end
requested_formula.map do |f|
brewline = if describe && f[:desc].present?
f[:desc].split("\n").map { |s| "# #{s}\n" }.join
else
""
end
brewline += "brew \"#{f[:full_name]}\""
args = f[:args].map { |arg| "\"#{arg}\"" }.sort.join(", ")
brewline += ", args: [#{args}]" unless f[:args].empty?
brewline += ", restart_service: :changed" if !no_restart && BrewServices.started?(f[:full_name])
brewline += ", link: #{f[:link?]}" unless f[:link?].nil?
brewline
end.join("\n")
end
def self.formula_aliases
return @formula_aliases if @formula_aliases
@formula_aliases = {}
formulae.each do |f|
aliases = f[:aliases]
next if aliases.blank?
aliases.each do |a|
@formula_aliases[a] = f[:full_name]
if f[:full_name].include? "/" # tap formula
tap_name = f[:full_name].rpartition("/").first
@formula_aliases["#{tap_name}/#{a}"] = f[:full_name]
end
end
end
@formula_aliases
end
def self.formula_oldnames
return @formula_oldnames if @formula_oldnames
@formula_oldnames = {}
formulae.each do |f|
oldnames = f[:oldnames]
next if oldnames.blank?
oldnames.each do |oldname|
@formula_oldnames[oldname] = f[:full_name]
if f[:full_name].include? "/" # tap formula
tap_name = f[:full_name].rpartition("/").first
@formula_oldnames["#{tap_name}/#{oldname}"] = f[:full_name]
end
end
end
@formula_oldnames
end
private_class_method def self.add_formula(formula)
hash = formula_to_hash formula
@formulae_by_name[hash[:name]] = hash
@formulae_by_full_name[hash[:full_name]] = hash
hash
end
private_class_method def self.formula_to_hash(formula)
keg = if formula.linked?
link = true if formula.keg_only?
formula.linked_keg
else
link = false unless formula.keg_only?
formula.any_installed_prefix
end
if keg
require "tab"
tab = Tab.for_keg(keg)
args = tab.used_options.map(&:name)
version = begin
keg.realpath.basename
rescue
# silently handle broken symlinks
nil
end.to_s
args << "HEAD" if version.start_with?("HEAD")
installed_as_dependency = tab.installed_as_dependency
installed_on_request = tab.installed_on_request
runtime_dependencies = if (runtime_deps = tab.runtime_dependencies)
runtime_deps.filter_map { |d| d["full_name"] }
end
poured_from_bottle = tab.poured_from_bottle
end
runtime_dependencies ||= formula.runtime_dependencies.map(&:name)
bottled = if (stable = formula.stable) && stable.bottle_defined?
bottle_hash = formula.bottle_hash.deep_symbolize_keys
stable.bottled?
end
{
name: formula.name,
desc: formula.desc,
oldnames: formula.oldnames,
full_name: formula.full_name,
aliases: formula.aliases,
any_version_installed?: formula.any_version_installed?,
args: Array(args).uniq,
version:,
installed_as_dependency?: installed_as_dependency || false,
installed_on_request?: installed_on_request || false,
dependencies: runtime_dependencies,
build_dependencies: formula.deps.select(&:build?).map(&:name).uniq,
conflicts_with: formula.conflicts.map(&:name),
pinned?: formula.pinned? || false,
outdated?: formula.outdated? || false,
link?: link,
poured_from_bottle?: poured_from_bottle || false,
bottle: bottle_hash || false,
bottled: bottled || false,
official_tap: formula.tap&.official? || false,
}
end
class Topo < Hash
include TSort
def each_key(&block)
keys.each(&block)
end
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node.downcase).sort.each(&block)
end
end
private_class_method def self.sort!(formulae)
# Step 1: Sort by formula full name while putting tap formulae behind core formulae.
# So we can have a nicer output.
formulae = formulae.sort do |a, b|
if a[:full_name].exclude?("/") && b[:full_name].include?("/")
-1
elsif a[:full_name].include?("/") && b[:full_name].exclude?("/")
1
else
a[:full_name] <=> b[:full_name]
end
end
# Step 2: Sort by formula dependency topology.
topo = Topo.new
formulae.each do |f|
topo[f[:name]] = topo[f[:full_name]] = f[:dependencies].filter_map do |dep|
ff = formulae_by_name(dep)
next if ff.blank?
next unless ff[:any_version_installed?]
ff[:full_name]
end
end
@formulae = topo.tsort
.map { |name| @formulae_by_full_name[name] || @formulae_by_name[name] }
.uniq { |f| f[:full_name] }
rescue TSort::Cyclic => e
e.message =~ /\["([^"]*)".*"([^"]*)"\]/
cycle_first = Regexp.last_match(1)
cycle_last = Regexp.last_match(2)
odie e.message if !cycle_first || !cycle_last
odie <<~EOS
Formulae dependency graph sorting failed (likely due to a circular dependency):
#{cycle_first}: #{topo[cycle_first] if topo}
#{cycle_last}: #{topo[cycle_last] if topo}
Please run the following commands and try again:
brew update
brew uninstall --ignore-dependencies --force #{cycle_first} #{cycle_last}
brew install #{cycle_first} #{cycle_last}
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/tap_dumper.rb | Library/Homebrew/bundle/tap_dumper.rb | # typed: strict
# frozen_string_literal: true
require "json"
module Homebrew
module Bundle
module TapDumper
sig { void }
def self.reset!
@taps = nil
end
sig { returns(String) }
def self.dump
taps.map do |tap|
remote = if tap.custom_remote? && (tap_remote = tap.remote)
if (api_token = ENV.fetch("HOMEBREW_GITHUB_API_TOKEN", false).presence)
# Replace the API token in the remote URL with interpolation.
# Rubocop's warning here is wrong; we intentionally want to not
# evaluate this string until the Brewfile is evaluated.
# rubocop:disable Lint/InterpolationCheck
tap_remote = tap_remote.gsub api_token, '#{ENV.fetch("HOMEBREW_GITHUB_API_TOKEN")}'
# rubocop:enable Lint/InterpolationCheck
end
", \"#{tap_remote}\""
end
"tap \"#{tap.name}\"#{remote}"
end.sort.uniq.join("\n")
end
sig { returns(T::Array[String]) }
def self.tap_names
taps.map(&:name)
end
sig { returns(T::Array[Tap]) }
private_class_method def self.taps
@taps ||= T.let(nil, T.nilable(T::Array[Tap]))
@taps ||= begin
require "tap"
Tap.select(&:installed?).to_a
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/brew_services.rb | Library/Homebrew/bundle/brew_services.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "services/system"
module Homebrew
module Bundle
module BrewServices
def self.reset!
@started_services = nil
end
def self.stop(name, keep: false, verbose: false)
return true unless started?(name)
args = ["services", "stop", name]
args << "--keep" if keep
return unless Bundle.brew(*args, verbose:)
started_services.delete(name)
true
end
def self.start(name, file: nil, verbose: false)
args = ["services", "start", name]
args << "--file=#{file}" if file
return unless Bundle.brew(*args, verbose:)
started_services << name
true
end
def self.run(name, file: nil, verbose: false)
args = ["services", "run", name]
args << "--file=#{file}" if file
return unless Bundle.brew(*args, verbose:)
started_services << name
true
end
def self.restart(name, file: nil, verbose: false)
args = ["services", "restart", name]
args << "--file=#{file}" if file
return unless Bundle.brew(*args, verbose:)
started_services << name
true
end
def self.started?(name)
started_services.include? name
end
def self.started_services
@started_services ||= begin
states_to_skip = %w[stopped none]
Utils.safe_popen_read(HOMEBREW_BREW_FILE, "services", "list").lines.filter_map do |line|
name, state, _plist = line.split(/\s+/)
next if states_to_skip.include? state
name
end
end
end
def self.versioned_service_file(name)
env_version = Bundle.formula_versions_from_env(name)
return if env_version.nil?
formula = Formula[name]
prefix = formula.rack/env_version
return unless prefix.directory?
service_file = if Homebrew::Services::System.launchctl?
prefix/"#{formula.plist_name}.plist"
else
prefix/"#{formula.service_name}.service"
end
service_file if service_file.file?
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/cargo_dumper.rb | Library/Homebrew/bundle/cargo_dumper.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module CargoDumper
sig { void }
def self.reset!
@packages = nil
end
sig { returns(T::Array[String]) }
def self.packages
@packages ||= T.let(nil, T.nilable(T::Array[String]))
@packages ||= if Bundle.cargo_installed?
require "bundle/cargo_installer"
cargo = Bundle.which_cargo
parse_package_list(`#{cargo} install --list`)
else
[]
end
end
sig { returns(String) }
def self.dump
packages.map { |name| "cargo \"#{name}\"" }.join("\n")
end
sig { params(output: String).returns(T::Array[String]) }
private_class_method def self.parse_package_list(output)
output.lines.filter_map do |line|
next if line.match?(/^\s/)
match = line.match(/\A(?<name>[^\s:]+)\s+v[0-9A-Za-z.+-]+/)
match[:name] if match
end.uniq
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/flatpak_checker.rb | Library/Homebrew/bundle/flatpak_checker.rb | # typed: strict
# frozen_string_literal: true
require "bundle/checker"
module Homebrew
module Bundle
module Checker
class FlatpakChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :flatpak
PACKAGE_TYPE_NAME = "Flatpak"
sig {
params(entries: T::Array[Homebrew::Bundle::Dsl::Entry], exit_on_first_error: T::Boolean,
no_upgrade: T::Boolean, verbose: T::Boolean).returns(T::Array[String])
}
def find_actionable(entries, exit_on_first_error: false, no_upgrade: false, verbose: false)
super
end
# Override to return entry hashes with options instead of just names
sig { params(entries: T::Array[Bundle::Dsl::Entry]).returns(T::Array[T::Hash[Symbol, T.untyped]]) }
def format_checkable(entries)
checkable_entries(entries).map do |entry|
{ name: entry.name, options: entry.options || {} }
end
end
sig { params(package: T.any(String, T::Hash[Symbol, T.untyped]), no_upgrade: T::Boolean).returns(String) }
def failure_reason(package, no_upgrade:)
name = package.is_a?(Hash) ? package[:name] : package
"#{PACKAGE_TYPE_NAME} #{name} needs to be installed."
end
sig {
params(package: T.any(String, T::Hash[Symbol, T.untyped]), no_upgrade: T::Boolean).returns(T::Boolean)
}
def installed_and_up_to_date?(package, no_upgrade: false)
require "bundle/flatpak_installer"
if package.is_a?(Hash)
name = package[:name]
remote = package.dig(:options, :remote) || "flathub"
url = package.dig(:options, :url)
# 3-tier remote handling:
# - Tier 1: Named remote → check with that remote name
# - Tier 2: URL only → resolve to single-app remote name (<app-id>-origin)
# - Tier 3: URL + name → check with the named remote
actual_remote = if url.blank? && remote.start_with?("http://", "https://")
# Tier 2: URL only - resolve to single-app remote name
# (.flatpakref - check by name only since remote name varies)
return Homebrew::Bundle::FlatpakInstaller.package_installed?(name) if remote.end_with?(".flatpakref")
Homebrew::Bundle::FlatpakInstaller.generate_single_app_remote_name(name)
else
# Tier 1 (named remote) and Tier 3 (named remote with URL) both use the remote name
remote
end
Homebrew::Bundle::FlatpakInstaller.package_installed?(name, remote: actual_remote)
else
# If just a string, check without remote
Homebrew::Bundle::FlatpakInstaller.package_installed?(package)
end
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/tap_installer.rb | Library/Homebrew/bundle/tap_installer.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module TapInstaller
sig { params(name: String, verbose: T::Boolean, _options: T.anything).returns(T::Boolean) }
def self.preinstall!(name, verbose: false, **_options)
if installed_taps.include? name
puts "Skipping install of #{name} tap. It is already installed." if verbose
return false
end
true
end
sig {
params(
name: String,
preinstall: T::Boolean,
verbose: T::Boolean,
force: T::Boolean,
clone_target: T.nilable(String),
_options: T.anything,
).returns(T::Boolean)
}
def self.install!(name, preinstall: true, verbose: false, force: false, clone_target: nil, **_options)
return true unless preinstall
puts "Installing #{name} tap. It is not currently installed." if verbose
args = []
official_tap = name.downcase.start_with? "homebrew/"
args << "--force" if force || (official_tap && Homebrew::EnvConfig.developer?)
success = if clone_target
Bundle.brew("tap", name, clone_target, *args, verbose:)
else
Bundle.brew("tap", name, *args, verbose:)
end
unless success
require "bundle/skipper"
Homebrew::Bundle::Skipper.tap_failed!(name)
return false
end
installed_taps << name
true
end
sig { returns(T::Array[String]) }
def self.installed_taps
require "bundle/tap_dumper"
@installed_taps ||= T.let(Homebrew::Bundle::TapDumper.tap_names, T.nilable(T::Array[String]))
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/remover.rb | Library/Homebrew/bundle/remover.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Homebrew
module Bundle
module Remover
extend ::Utils::Output::Mixin
sig { params(args: String, type: Symbol, global: T::Boolean, file: T.nilable(String)).void }
def self.remove(*args, type:, global:, file:)
require "bundle/brewfile"
require "bundle/dumper"
brewfile = Brewfile.read(global:, file:)
content = brewfile.input
entry_type = type.to_s if type != :none
escaped_args = args.flat_map do |arg|
names = if type == :brew
possible_names(arg)
else
[arg]
end
names.uniq.map { |a| Regexp.escape(a) }
end
new_content = content.split("\n")
.grep_v(/#{entry_type}(\s+|\(\s*)"(#{escaped_args.join("|")})"/)
.join("\n") << "\n"
if content.chomp == new_content.chomp &&
type == :none &&
args.any? { |arg| possible_names(arg, raise_error: false).count > 1 }
opoo "No matching entries found in Brewfile. Try again with `--formula` to match formula " \
"aliases and old formula names."
return
end
path = Dumper.brewfile_path(global:, file:)
Dumper.write_file path, new_content
end
sig { params(formula_name: String, raise_error: T::Boolean).returns(T::Array[String]) }
def self.possible_names(formula_name, raise_error: true)
formula = Formulary.factory(formula_name)
[formula_name, formula.name, formula.full_name, *formula.aliases, *formula.oldnames].compact.uniq
rescue FormulaUnavailableError
raise if raise_error
[]
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/mac_app_store_installer.rb | Library/Homebrew/bundle/mac_app_store_installer.rb | # typed: strict
# frozen_string_literal: true
require "os"
module Homebrew
module Bundle
module MacAppStoreInstaller
sig { void }
def self.reset!
@installed_app_ids = nil
@outdated_app_ids = nil
end
sig { params(name: String, id: Integer, no_upgrade: T::Boolean, verbose: T::Boolean).returns(T::Boolean) }
def self.preinstall!(name, id, no_upgrade: false, verbose: false)
unless Bundle.mas_installed?
puts "Installing mas. It is not currently installed." if verbose
Bundle.brew("install", "mas", verbose:)
raise "Unable to install #{name} app. mas installation failed." unless Bundle.mas_installed?
end
if app_id_installed?(id) &&
(no_upgrade || !app_id_upgradable?(id))
puts "Skipping install of #{name} app. It is already installed." if verbose
return false
end
true
end
sig {
params(
name: String,
id: Integer,
preinstall: T::Boolean,
no_upgrade: T::Boolean,
verbose: T::Boolean,
force: T::Boolean,
).returns(T::Boolean)
}
def self.install!(name, id, preinstall: true, no_upgrade: false, verbose: false, force: false)
return true unless preinstall
if app_id_installed?(id)
puts "Upgrading #{name} app. It is installed but not up-to-date." if verbose
return false unless Bundle.system "mas", "upgrade", id.to_s, verbose: verbose
return true
end
puts "Installing #{name} app. It is not currently installed." if verbose
return false unless Bundle.system "mas", "install", id.to_s, verbose: verbose
installed_app_ids << id
true
end
sig { params(id: Integer, no_upgrade: T::Boolean).returns(T::Boolean) }
def self.app_id_installed_and_up_to_date?(id, no_upgrade: false)
return false unless app_id_installed?(id)
return true if no_upgrade
!app_id_upgradable?(id)
end
sig { params(id: Integer).returns(T::Boolean) }
def self.app_id_installed?(id)
installed_app_ids.include? id
end
sig { params(id: Integer).returns(T::Boolean) }
def self.app_id_upgradable?(id)
outdated_app_ids.include? id
end
sig { returns(T::Array[Integer]) }
def self.installed_app_ids
require "bundle/mac_app_store_dumper"
@installed_app_ids ||= T.let(Homebrew::Bundle::MacAppStoreDumper.app_ids, T.nilable(T::Array[Integer]))
end
sig { returns(T::Array[Integer]) }
def self.outdated_app_ids
@outdated_app_ids ||= T.let(
if Bundle.mas_installed?
`mas outdated 2>/dev/null`.split("\n").map do |app|
app.split(" ", 2).first.to_i
end
else
[]
end, T.nilable(T::Array[Integer])
)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/cask_dumper.rb | Library/Homebrew/bundle/cask_dumper.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module CaskDumper
sig { void }
def self.reset!
@casks = nil
@cask_names = nil
@cask_oldnames = nil
end
sig { returns(T::Array[String]) }
def self.cask_names
@cask_names ||= T.let(casks.map(&:to_s), T.nilable(T::Array[String]))
end
sig { returns(T::Array[String]) }
def self.outdated_cask_names
return [] unless Bundle.cask_installed?
casks.select { |c| c.outdated?(greedy: false) }
.map(&:to_s)
end
sig { params(cask_name: String).returns(T::Boolean) }
def self.cask_is_outdated_using_greedy?(cask_name)
return false unless Bundle.cask_installed?
cask = casks.find { |c| c.to_s == cask_name }
return false if cask.nil?
cask.outdated?(greedy: true)
end
sig { params(describe: T::Boolean).returns(String) }
def self.dump(describe: false)
casks.map do |cask|
description = "# #{cask.desc}\n" if describe && cask.desc.present?
config = ", args: { #{explicit_s(cask.config)} }" if cask.config.present? && cask.config.explicit.present?
"#{description}cask \"#{cask}\"#{config}"
end.join("\n")
end
sig { returns(T::Hash[String, String]) }
def self.cask_oldnames
@cask_oldnames ||= T.let(casks.each_with_object({}) do |c, hash|
oldnames = c.old_tokens
next if oldnames.blank?
oldnames.each do |oldname|
hash[oldname] = c.full_name
if c.full_name.include? "/" # tap cask
tap_name = c.full_name.rpartition("/").first
hash["#{tap_name}/#{oldname}"] = c.full_name
end
end
end, T.nilable(T::Hash[String, String]))
end
sig { params(cask_list: T::Array[String]).returns(T::Array[String]) }
def self.formula_dependencies(cask_list)
return [] unless Bundle.cask_installed?
return [] if cask_list.blank?
casks.flat_map do |cask|
next unless cask_list.include?(cask.to_s)
cask.depends_on[:formula]
end.compact
end
sig { returns(T::Array[Cask::Cask]) }
private_class_method def self.casks
return [] unless Bundle.cask_installed?
require "cask/caskroom"
@casks ||= T.let(Cask::Caskroom.casks, T.nilable(T::Array[Cask::Cask]))
end
sig { params(cask_config: Cask::Config).returns(String) }
private_class_method def self.explicit_s(cask_config)
cask_config.explicit.map do |key, value|
# inverse of #env - converts :languages config key back to --language flag
if key == :languages
key = "language"
value = Array(cask_config.explicit.fetch(:languages, [])).join(",")
end
"#{key}: \"#{value.to_s.sub(/^#{Dir.home}/, "~")}\""
end.join(", ")
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/cargo_checker.rb | Library/Homebrew/bundle/cargo_checker.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module Checker
class CargoChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :cargo
PACKAGE_TYPE_NAME = "Cargo Package"
sig { params(package: String, no_upgrade: T::Boolean).returns(String) }
def failure_reason(package, no_upgrade:)
"#{PACKAGE_TYPE_NAME} #{package} needs to be installed."
end
sig { params(package: String, no_upgrade: T::Boolean).returns(T::Boolean) }
def installed_and_up_to_date?(package, no_upgrade: false)
require "bundle/cargo_installer"
Homebrew::Bundle::CargoInstaller.package_installed?(package)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/vscode_extension_checker.rb | Library/Homebrew/bundle/vscode_extension_checker.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module Checker
class VscodeExtensionChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :vscode
PACKAGE_TYPE_NAME = "VSCode Extension"
sig { params(extension: String, no_upgrade: T::Boolean).returns(String) }
def failure_reason(extension, no_upgrade:)
"#{PACKAGE_TYPE_NAME} #{extension} needs to be installed."
end
sig { params(extension: String, no_upgrade: T::Boolean).returns(T::Boolean) }
def installed_and_up_to_date?(extension, no_upgrade: false)
require "bundle/vscode_extension_installer"
Homebrew::Bundle::VscodeExtensionInstaller.extension_installed?(extension)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/go_dumper.rb | Library/Homebrew/bundle/go_dumper.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module GoDumper
sig { void }
def self.reset!
@packages = nil
end
sig { returns(T::Array[String]) }
def self.packages
@packages ||= T.let(nil, T.nilable(T::Array[String]))
@packages ||= if Bundle.go_installed?
go = Bundle.which_go
ENV["GOBIN"] = ENV.fetch("HOMEBREW_GOBIN", nil)
ENV["GOPATH"] = ENV.fetch("HOMEBREW_GOPATH", nil)
gobin = `#{go} env GOBIN`.chomp
gopath = `#{go} env GOPATH`.chomp
bin_dir = gobin.empty? ? "#{gopath}/bin" : gobin
return [] unless File.directory?(bin_dir)
binaries = Dir.glob("#{bin_dir}/*").select do |f|
File.executable?(f) && !File.directory?(f) && !File.symlink?(f)
end
binaries.filter_map do |binary|
output = `#{go} version -m "#{binary}" 2>/dev/null`
next if output.empty?
# Parse the output to find the path line
# Format: "\tpath\tgithub.com/user/repo"
lines = output.split("\n")
path_line = lines.find { |line| line.strip.start_with?("path\t") }
next unless path_line
# Extract the package path (second field after splitting by tab)
# The line format is: "\tpath\tgithub.com/user/repo"
parts = path_line.split("\t")
path = parts[2]&.strip if parts.length >= 3
# `command-line-arguments` is a dummy package name for binaries built
# from a list of source files instead of a specific package name.
# https://github.com/golang/go/issues/36043
next if path == "command-line-arguments"
path
end.compact.uniq
else
[]
end
end
sig { returns(String) }
def self.dump
packages.map { |name| "go \"#{name}\"" }.join("\n")
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/cask_checker.rb | Library/Homebrew/bundle/cask_checker.rb | # typed: strict
# frozen_string_literal: true
require "bundle/cask_installer"
module Homebrew
module Bundle
module Checker
class CaskChecker < Homebrew::Bundle::Checker::Base
PACKAGE_TYPE = :cask
PACKAGE_TYPE_NAME = "Cask"
sig { params(cask: String, no_upgrade: T::Boolean).returns(T::Boolean) }
def installed_and_up_to_date?(cask, no_upgrade: false)
Homebrew::Bundle::CaskInstaller.cask_installed_and_up_to_date?(cask, no_upgrade:)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/checker.rb | Library/Homebrew/bundle/checker.rb | # typed: true
# frozen_string_literal: true
module Homebrew
module Bundle
module Checker
class Base
# Implement these in any subclass
# PACKAGE_TYPE = :pkg
# PACKAGE_TYPE_NAME = "Package"
def exit_early_check(packages, no_upgrade:)
work_to_be_done = packages.find do |pkg|
!installed_and_up_to_date?(pkg, no_upgrade:)
end
Array(work_to_be_done)
end
def failure_reason(name, no_upgrade:)
reason = if no_upgrade && Bundle.upgrade_formulae.exclude?(name)
"needs to be installed."
else
"needs to be installed or updated."
end
"#{self.class.const_get(:PACKAGE_TYPE_NAME)} #{name} #{reason}"
end
def full_check(packages, no_upgrade:)
packages.reject { |pkg| installed_and_up_to_date?(pkg, no_upgrade:) }
.map { |pkg| failure_reason(pkg, no_upgrade:) }
end
def checkable_entries(all_entries)
require "bundle/skipper"
all_entries.select { |e| e.type == self.class.const_get(:PACKAGE_TYPE) }
.reject(&Bundle::Skipper.method(:skip?))
end
def format_checkable(entries)
checkable_entries(entries).map(&:name)
end
def installed_and_up_to_date?(_pkg, no_upgrade: false)
raise NotImplementedError
end
def find_actionable(entries, exit_on_first_error: false, no_upgrade: false, verbose: false)
requested = format_checkable entries
if exit_on_first_error
exit_early_check(requested, no_upgrade:)
else
full_check(requested, no_upgrade:)
end
end
end
CheckResult = Struct.new :work_to_be_done, :errors
CHECKS = {
taps_to_tap: "Taps",
casks_to_install: "Casks",
extensions_to_install: "VSCode Extensions",
apps_to_install: "Apps",
formulae_to_install: "Formulae",
formulae_to_start: "Services",
go_packages_to_install: "Go Packages",
cargo_packages_to_install: "Cargo Packages",
flatpaks_to_install: "Flatpaks",
}.freeze
def self.check(global: false, file: nil, exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/brewfile"
@dsl ||= Brewfile.read(global:, file:)
check_method_names = CHECKS.keys
errors = []
enumerator = exit_on_first_error ? :find : :map
work_to_be_done = check_method_names.public_send(enumerator) do |check_method|
check_errors =
send(check_method, exit_on_first_error:, no_upgrade:, verbose:)
any_errors = check_errors.any?
errors.concat(check_errors) if any_errors
any_errors
end
work_to_be_done = Array(work_to_be_done).flatten.any?
CheckResult.new work_to_be_done, errors
end
def self.casks_to_install(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/cask_checker"
Homebrew::Bundle::Checker::CaskChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.formulae_to_install(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/brew_checker"
Homebrew::Bundle::Checker::BrewChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.taps_to_tap(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/tap_checker"
Homebrew::Bundle::Checker::TapChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.apps_to_install(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/mac_app_store_checker"
Homebrew::Bundle::Checker::MacAppStoreChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.extensions_to_install(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/vscode_extension_checker"
Homebrew::Bundle::Checker::VscodeExtensionChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.formulae_to_start(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/brew_service_checker"
Homebrew::Bundle::Checker::BrewServiceChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.go_packages_to_install(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/go_checker"
Homebrew::Bundle::Checker::GoChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.cargo_packages_to_install(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/cargo_checker"
Homebrew::Bundle::Checker::CargoChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.flatpaks_to_install(exit_on_first_error: false, no_upgrade: false, verbose: false)
require "bundle/flatpak_checker"
Homebrew::Bundle::Checker::FlatpakChecker.new.find_actionable(
@dsl.entries,
exit_on_first_error:, no_upgrade:, verbose:,
)
end
def self.reset!
require "bundle/cask_dumper"
require "bundle/formula_dumper"
require "bundle/mac_app_store_dumper"
require "bundle/tap_dumper"
require "bundle/brew_services"
@dsl = nil
Homebrew::Bundle::CaskDumper.reset!
Homebrew::Bundle::FormulaDumper.reset!
Homebrew::Bundle::MacAppStoreDumper.reset!
Homebrew::Bundle::TapDumper.reset!
Homebrew::Bundle::BrewServices.reset!
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/formula_installer.rb | Library/Homebrew/bundle/formula_installer.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module Bundle
class FormulaInstaller
def self.reset!
@installed_formulae = nil
@outdated_formulae = nil
@pinned_formulae = nil
end
def self.preinstall!(name, no_upgrade: false, verbose: false, **options)
new(name, options).preinstall!(no_upgrade:, verbose:)
end
def self.install!(name, preinstall: true, no_upgrade: false, verbose: false, force: false, **options)
new(name, options).install!(preinstall:, no_upgrade:, verbose:, force:)
end
def initialize(name, options = {})
@full_name = name
@name = name.split("/").last
@args = options.fetch(:args, []).map { |arg| "--#{arg}" }
@conflicts_with_arg = options.fetch(:conflicts_with, [])
@restart_service = options[:restart_service]
@start_service = options.fetch(:start_service, @restart_service)
@link = options.fetch(:link, nil)
@postinstall = options.fetch(:postinstall, nil)
@version_file = options.fetch(:version_file, nil)
@changed = nil
end
def preinstall!(no_upgrade: false, verbose: false)
if installed? && (self.class.no_upgrade_with_args?(no_upgrade, @name) || !upgradable?)
puts "Skipping install of #{@name} formula. It is already installed." if verbose
@changed = nil
return false
end
true
end
def install!(preinstall: true, no_upgrade: false, verbose: false, force: false)
install_result = if preinstall
install_change_state!(no_upgrade:, verbose:, force:)
else
true
end
result = install_result
if installed?
service_result = service_change_state!(verbose:)
result &&= service_result
link_result = link_change_state!(verbose:)
result &&= link_result
postinstall_result = postinstall_change_state!(verbose:)
result &&= postinstall_result
if result && @version_file.present?
# Use the version from the environment if it hasn't changed.
# Strip the revision number because it's not part of the non-Homebrew version.
version = if !changed? && (env_version = Bundle.formula_versions_from_env(@name))
PkgVersion.parse(env_version).version
else
Formula[@full_name].version
end.to_s
File.write(@version_file, "#{version}\n")
puts "Wrote #{@name} version #{version} to #{@version_file}" if verbose
end
end
result
end
def install_change_state!(no_upgrade:, verbose:, force:)
return false unless resolve_conflicts!(verbose:)
if installed?
upgrade_formula!(verbose:, force:)
else
install_formula!(verbose:, force:)
end
end
def start_service?
@start_service.present?
end
def start_service_needed?
require "bundle/brew_services"
start_service? && !BrewServices.started?(@full_name)
end
def restart_service?
@restart_service.present?
end
def restart_service_needed?
return false unless restart_service?
# Restart if `restart_service: :always`, or if the formula was installed or upgraded
@restart_service.to_s == "always" || changed?
end
def changed?
@changed.present?
end
def service_change_state!(verbose:)
require "bundle/brew_services"
file = Bundle::BrewServices.versioned_service_file(@name)
if restart_service_needed?
puts "Restarting #{@name} service." if verbose
BrewServices.restart(@full_name, file:, verbose:)
elsif start_service_needed?
puts "Starting #{@name} service." if verbose
BrewServices.start(@full_name, file:, verbose:)
else
true
end
end
def link_change_state!(verbose: false)
link_args = []
link_args << "--force" if unlinked_and_keg_only?
cmd = case @link
when :overwrite
link_args << "--overwrite"
"link" unless linked?
when true
"link" unless linked?
when false
"unlink" if linked?
when nil
if keg_only?
"unlink" if linked?
else
"link" unless linked?
end
end
if cmd.present?
verb = "#{cmd}ing".capitalize
with_args = " with #{link_args.join(" ")}" if link_args.present?
puts "#{verb} #{@name} formula#{with_args}." if verbose
return Bundle.brew(cmd, *link_args, @name, verbose:)
end
true
end
def postinstall_change_state!(verbose:)
return true if @postinstall.blank?
return true unless changed?
puts "Running postinstall for #{@name}: #{@postinstall}" if verbose
Kernel.system(@postinstall)
end
def self.formula_installed_and_up_to_date?(formula, no_upgrade: false)
return false unless formula_installed?(formula)
return true if no_upgrade_with_args?(no_upgrade, formula)
!formula_upgradable?(formula)
end
def self.no_upgrade_with_args?(no_upgrade, formula_name)
no_upgrade && Bundle.upgrade_formulae.exclude?(formula_name)
end
def self.formula_in_array?(formula, array)
return true if array.include?(formula)
return true if array.include?(formula.split("/").last)
require "bundle/formula_dumper"
old_names = Homebrew::Bundle::FormulaDumper.formula_oldnames
old_name = old_names[formula]
old_name ||= old_names[formula.split("/").last]
return true if old_name && array.include?(old_name)
resolved_full_name = Homebrew::Bundle::FormulaDumper.formula_aliases[formula]
return false unless resolved_full_name
return true if array.include?(resolved_full_name)
return true if array.include?(resolved_full_name.split("/").last)
false
end
def self.formula_installed?(formula)
formula_in_array?(formula, installed_formulae)
end
def self.formula_upgradable?(formula)
# Check local cache first and then authoritative Homebrew source.
formula_in_array?(formula, upgradable_formulae) && Formula[formula].outdated?
end
def self.installed_formulae
@installed_formulae ||= formulae.map { |f| f[:name] }
end
def self.upgradable_formulae
outdated_formulae - pinned_formulae
end
def self.outdated_formulae
@outdated_formulae ||= formulae.filter_map { |f| f[:name] if f[:outdated?] }
end
def self.pinned_formulae
@pinned_formulae ||= formulae.filter_map { |f| f[:name] if f[:pinned?] }
end
def self.formulae
require "bundle/formula_dumper"
Homebrew::Bundle::FormulaDumper.formulae
end
private
def installed?
FormulaInstaller.formula_installed?(@name)
end
def linked?
Formula[@full_name].linked?
end
def keg_only?
Formula[@full_name].keg_only?
end
def unlinked_and_keg_only?
!linked? && keg_only?
end
def upgradable?
FormulaInstaller.formula_upgradable?(@name)
end
def conflicts_with
@conflicts_with ||= begin
conflicts_with = Set.new
conflicts_with += @conflicts_with_arg
require "bundle/formula_dumper"
if (formula = Homebrew::Bundle::FormulaDumper.formulae_by_full_name(@full_name)) &&
(formula_conflicts_with = formula[:conflicts_with])
conflicts_with += formula_conflicts_with
end
conflicts_with.to_a
end
end
def resolve_conflicts!(verbose:)
conflicts_with.each do |conflict|
next unless FormulaInstaller.formula_installed?(conflict)
if verbose
puts <<~EOS
Unlinking #{conflict} formula.
It is currently installed and conflicts with #{@name}.
EOS
end
return false unless Bundle.brew("unlink", conflict, verbose:)
next unless restart_service?
require "bundle/brew_services"
puts "Stopping #{conflict} service (if it is running)." if verbose
BrewServices.stop(conflict, verbose:)
end
true
end
def install_formula!(verbose:, force:)
install_args = @args.dup
install_args << "--force" << "--overwrite" if force
install_args << "--skip-link" if @link == false
with_args = " with #{install_args.join(" ")}" if install_args.present?
puts "Installing #{@name} formula#{with_args}. It is not currently installed." if verbose
unless Bundle.brew("install", "--formula", @full_name, *install_args, verbose:)
@changed = nil
return false
end
FormulaInstaller.installed_formulae << @name
@changed = true
true
end
def upgrade_formula!(verbose:, force:)
upgrade_args = []
upgrade_args << "--force" if force
with_args = " with #{upgrade_args.join(" ")}" if upgrade_args.present?
puts "Upgrading #{@name} formula#{with_args}. It is installed but not up-to-date." if verbose
unless Bundle.brew("upgrade", "--formula", @name, *upgrade_args, verbose:)
@changed = nil
return false
end
@changed = true
true
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/dumper.rb | Library/Homebrew/bundle/dumper.rb | # typed: strict
# frozen_string_literal: true
require "fileutils"
require "pathname"
module Homebrew
module Bundle
module Dumper
sig { params(brewfile_path: Pathname, force: T::Boolean).returns(T::Boolean) }
private_class_method def self.can_write_to_brewfile?(brewfile_path, force: false)
raise "#{brewfile_path} already exists" if should_not_write_file?(brewfile_path, overwrite: force)
true
end
sig {
params(
describe: T::Boolean,
no_restart: T::Boolean,
formulae: T::Boolean,
taps: T::Boolean,
casks: T::Boolean,
mas: T::Boolean,
vscode: T::Boolean,
go: T::Boolean,
cargo: T::Boolean,
flatpak: T::Boolean,
).returns(String)
}
def self.build_brewfile(describe:, no_restart:, formulae:, taps:, casks:, mas:, vscode:, go:, cargo:, flatpak:)
require "bundle/tap_dumper"
require "bundle/formula_dumper"
require "bundle/cask_dumper"
require "bundle/mac_app_store_dumper"
require "bundle/vscode_extension_dumper"
require "bundle/go_dumper"
require "bundle/cargo_dumper"
require "bundle/flatpak_dumper"
content = []
content << TapDumper.dump if taps
content << FormulaDumper.dump(describe:, no_restart:) if formulae
content << CaskDumper.dump(describe:) if casks
content << MacAppStoreDumper.dump if mas
content << VscodeExtensionDumper.dump if vscode
content << GoDumper.dump if go
content << CargoDumper.dump if cargo
content << FlatpakDumper.dump if flatpak
"#{content.reject(&:empty?).join("\n")}\n"
end
sig {
params(
global: T::Boolean,
file: T.nilable(String),
describe: T::Boolean,
force: T::Boolean,
no_restart: T::Boolean,
formulae: T::Boolean,
taps: T::Boolean,
casks: T::Boolean,
mas: T::Boolean,
vscode: T::Boolean,
go: T::Boolean,
cargo: T::Boolean,
flatpak: T::Boolean,
).void
}
def self.dump_brewfile(global:, file:, describe:, force:, no_restart:, formulae:, taps:, casks:, mas:,
vscode:, go:, cargo:, flatpak:)
path = brewfile_path(global:, file:)
can_write_to_brewfile?(path, force:)
content = build_brewfile(
describe:, no_restart:, taps:, formulae:, casks:, mas:, vscode:, go:, cargo:, flatpak:,
)
write_file path, content
end
sig { params(global: T::Boolean, file: T.nilable(String)).returns(Pathname) }
def self.brewfile_path(global: false, file: nil)
require "bundle/brewfile"
Brewfile.path(dash_writes_to_stdout: true, global:, file:)
end
sig { params(file: Pathname, overwrite: T::Boolean).returns(T::Boolean) }
private_class_method def self.should_not_write_file?(file, overwrite: false)
file.exist? && !overwrite && file.to_s != "/dev/stdout"
end
sig { params(file: Pathname, content: String).void }
def self.write_file(file, content)
Bundle.exchange_uid_if_needed! do
file.open("w") { |io| io.write content }
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/cargo_installer.rb | Library/Homebrew/bundle/cargo_installer.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Bundle
module CargoInstaller
sig { void }
def self.reset!
@installed_packages = nil
end
sig { params(name: String, verbose: T::Boolean, _options: T.anything).returns(T::Boolean) }
def self.preinstall!(name, verbose: false, **_options)
unless Bundle.cargo_installed?
puts "Installing rust for cargo. It is not currently installed." if verbose
Bundle.brew("install", "--formula", "rust", verbose:)
Bundle.reset!
raise "Unable to install #{name} package. Rust installation failed." unless Bundle.cargo_installed?
end
if package_installed?(name)
puts "Skipping install of #{name} Cargo package. It is already installed." if verbose
return false
end
true
end
sig {
params(
name: String,
preinstall: T::Boolean,
verbose: T::Boolean,
force: T::Boolean,
_options: T.anything,
).returns(T::Boolean)
}
def self.install!(name, preinstall: true, verbose: false, force: false, **_options)
return true unless preinstall
puts "Installing #{name} Cargo package. It is not currently installed." if verbose
cargo = T.must(Bundle.which_cargo)
env = { "PATH" => "#{cargo.dirname}:#{ENV.fetch("PATH")}" }
success = with_env(env) do
Bundle.system cargo.to_s, "install", "--locked", name, verbose:
end
return false unless success
installed_packages << name
true
end
sig { params(package: String).returns(T::Boolean) }
def self.package_installed?(package)
installed_packages.include? package
end
sig { returns(T::Array[String]) }
def self.installed_packages
require "bundle/cargo_dumper"
@installed_packages ||= T.let(Homebrew::Bundle::CargoDumper.packages, T.nilable(T::Array[String]))
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/commands/add.rb | Library/Homebrew/bundle/commands/add.rb | # typed: strict
# frozen_string_literal: true
require "bundle/adder"
module Homebrew
module Bundle
module Commands
module Add
sig { params(args: String, type: Symbol, global: T::Boolean, file: T.nilable(String)).void }
def self.run(*args, type:, global:, file:)
Homebrew::Bundle::Adder.add(*args, type:, global:, file:)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/bundle/commands/dump.rb | Library/Homebrew/bundle/commands/dump.rb | # typed: strict
# frozen_string_literal: true
require "bundle/dumper"
module Homebrew
module Bundle
module Commands
module Dump
sig {
params(global: T::Boolean, file: T.nilable(String), describe: T::Boolean, force: T::Boolean,
no_restart: T::Boolean, taps: T::Boolean, formulae: T::Boolean, casks: T::Boolean,
mas: T::Boolean, vscode: T::Boolean, go: T::Boolean, cargo: T::Boolean,
flatpak: T::Boolean).void
}
def self.run(global:, file:, describe:, force:, no_restart:, taps:, formulae:, casks:, mas:,
vscode:, go:, cargo:, flatpak:)
Homebrew::Bundle::Dumper.dump_brewfile(
global:, file:, describe:, force:, no_restart:, taps:, formulae:, casks:, mas:, vscode:,
go:, cargo:, flatpak:
)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.