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/api.rb | Library/Homebrew/api.rb | # typed: strict
# frozen_string_literal: true
require "api/analytics"
require "api/cask"
require "api/formula"
require "api/internal"
require "api/formula_struct"
require "api/cask_struct"
require "base64"
require "utils/output"
module Homebrew
# Helper functions for using Homebrew's formulae.brew.sh API.
module API
extend Utils::Output::Mixin
extend Cachable
HOMEBREW_CACHE_API = T.let((HOMEBREW_CACHE/"api").freeze, Pathname)
HOMEBREW_CACHE_API_SOURCE = T.let((HOMEBREW_CACHE/"api-source").freeze, Pathname)
DEFAULT_API_STALE_SECONDS = T.let(7 * 24 * 60 * 60, Integer) # 7 days
sig { params(endpoint: String).returns(T::Hash[String, T.untyped]) }
def self.fetch(endpoint)
return cache[endpoint] if cache.present? && cache.key?(endpoint)
api_url = "#{Homebrew::EnvConfig.api_domain}/#{endpoint}"
output = Utils::Curl.curl_output("--fail", api_url)
if !output.success? && Homebrew::EnvConfig.api_domain != HOMEBREW_API_DEFAULT_DOMAIN
# Fall back to the default API domain and try again
api_url = "#{HOMEBREW_API_DEFAULT_DOMAIN}/#{endpoint}"
output = Utils::Curl.curl_output("--fail", api_url)
end
raise ArgumentError, "No file found at: #{Tty.underline}#{api_url}#{Tty.reset}" unless output.success?
cache[endpoint] = JSON.parse(output.stdout, freeze: true)
rescue JSON::ParserError
raise ArgumentError, "Invalid JSON file: #{Tty.underline}#{api_url}#{Tty.reset}"
end
sig { params(target: Pathname, stale_seconds: T.nilable(Integer)).returns(T::Boolean) }
def self.skip_download?(target:, stale_seconds:)
return true if Homebrew.running_as_root_but_not_owned_by_root?
return false if !target.exist? || target.empty?
return true unless stale_seconds
(Time.now - stale_seconds) < target.mtime
end
sig {
params(
endpoint: String,
target: Pathname,
stale_seconds: T.nilable(Integer),
download_queue: T.nilable(DownloadQueue),
).returns([T.any(T::Array[T.untyped], T::Hash[String, T.untyped]), T::Boolean])
}
def self.fetch_json_api_file(endpoint, target: HOMEBREW_CACHE_API/endpoint,
stale_seconds: nil, download_queue: nil)
# Lazy-load dependency.
require "development_tools"
retry_count = 0
url = "#{Homebrew::EnvConfig.api_domain}/#{endpoint}"
default_url = "#{HOMEBREW_API_DEFAULT_DOMAIN}/#{endpoint}"
if Homebrew.running_as_root_but_not_owned_by_root? &&
(!target.exist? || target.empty?)
odie "Need to download #{url} but cannot as root! Run `brew update` without `sudo` first then try again."
end
curl_args = Utils::Curl.curl_args(retries: 0) + %W[
--compressed
--speed-limit #{ENV.fetch("HOMEBREW_CURL_SPEED_LIMIT")}
--speed-time #{ENV.fetch("HOMEBREW_CURL_SPEED_TIME")}
]
insecure_download = DevelopmentTools.ca_file_substitution_required? ||
DevelopmentTools.curl_substitution_required?
skip_download = skip_download?(target:, stale_seconds:)
if download_queue
unless skip_download
require "api/json_download"
download = Homebrew::API::JSONDownload.new(endpoint, target:, stale_seconds:)
download_queue.enqueue(download)
end
return [{}, false]
end
json_data = begin
begin
args = curl_args.dup
args.prepend("--time-cond", target.to_s) if target.exist? && !target.empty?
if insecure_download
opoo DevelopmentTools.insecure_download_warning(endpoint)
args.append("--insecure")
end
unless skip_download
ohai "Downloading #{url}" if $stdout.tty? && !Context.current.quiet?
# Disable retries here, we handle them ourselves below.
Utils::Curl.curl_download(*args, url, to: target, retries: 0, show_error: false)
end
rescue ErrorDuringExecution
if url == default_url
raise unless target.exist?
raise if target.empty?
elsif retry_count.zero? || !target.exist? || target.empty?
# Fall back to the default API domain and try again
# This block will be executed only once, because we set `url` to `default_url`
url = default_url
target.unlink if target.exist? && target.empty?
skip_download = false
retry
end
opoo "#{target.basename}: update failed, falling back to cached version."
end
mtime = insecure_download ? Time.new(1970, 1, 1) : Time.now
FileUtils.touch(target, mtime:) unless skip_download
# Can use `target.read` again when/if https://github.com/sorbet/sorbet/pull/8999 is merged/released.
JSON.parse(File.read(target, encoding: Encoding::UTF_8), freeze: true)
rescue JSON::ParserError
target.unlink
retry_count += 1
skip_download = false
odie "Cannot download non-corrupt #{url}!" if retry_count > Homebrew::EnvConfig.curl_retries.to_i
retry
end
if endpoint.end_with?(".jws.json")
success, data = verify_and_parse_jws(json_data)
unless success
target.unlink
odie <<~EOS
Failed to verify integrity (#{data}) of:
#{url}
Potential MITM attempt detected. Please run `brew update` and try again.
EOS
end
[data, !skip_download]
else
[json_data, !skip_download]
end
end
sig {
params(json: T::Hash[String, T.untyped],
bottle_tag: ::Utils::Bottles::Tag).returns(T::Hash[String, T.untyped])
}
def self.merge_variations(json, bottle_tag: T.unsafe(nil))
return json unless json.key?("variations")
bottle_tag ||= Homebrew::SimulateSystem.current_tag
if (variation = json.dig("variations", bottle_tag.to_s).presence) ||
(variation = json.dig("variations", bottle_tag.to_sym).presence)
json = json.merge(variation)
end
json.except("variations")
end
sig { void }
def self.fetch_api_files!
download_queue = if Homebrew::EnvConfig.download_concurrency > 1
require "download_queue"
Homebrew::DownloadQueue.new
end
stale_seconds = if ENV["HOMEBREW_API_UPDATED"].present? ||
(Homebrew::EnvConfig.no_auto_update? && !Homebrew::EnvConfig.force_api_auto_update?)
nil
elsif Homebrew.auto_update_command?
Homebrew::EnvConfig.api_auto_update_secs.to_i
else
DEFAULT_API_STALE_SECONDS
end
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.fetch_formula_api!(download_queue:, stale_seconds:)
Homebrew::API::Internal.fetch_cask_api!(download_queue:, stale_seconds:)
else
Homebrew::API::Formula.fetch_api!(download_queue:, stale_seconds:)
Homebrew::API::Formula.fetch_tap_migrations!(download_queue:, stale_seconds: DEFAULT_API_STALE_SECONDS)
Homebrew::API::Cask.fetch_api!(download_queue:, stale_seconds:)
Homebrew::API::Cask.fetch_tap_migrations!(download_queue:, stale_seconds: DEFAULT_API_STALE_SECONDS)
end
ENV["HOMEBREW_API_UPDATED"] = "1"
return unless download_queue
begin
download_queue.fetch
ensure
download_queue.shutdown
end
end
sig { void }
def self.write_names_and_aliases
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.write_formula_names_and_aliases
Homebrew::API::Internal.write_cask_names
else
Homebrew::API::Formula.write_names_and_aliases
Homebrew::API::Cask.write_names
end
end
sig { params(names: T::Array[String], type: String, regenerate: T::Boolean).returns(T::Boolean) }
def self.write_names_file!(names, type, regenerate:)
names_path = HOMEBREW_CACHE_API/"#{type}_names.txt"
if !names_path.exist? || regenerate
names_path.unlink if names_path.exist?
names_path.write(names.sort.join("\n"))
return true
end
false
end
sig { params(aliases: T::Hash[String, String], type: String, regenerate: T::Boolean).returns(T::Boolean) }
def self.write_aliases_file!(aliases, type, regenerate:)
aliases_path = HOMEBREW_CACHE_API/"#{type}_aliases.txt"
if !aliases_path.exist? || regenerate
aliases_text = aliases.map do |alias_name, real_name|
"#{alias_name}|#{real_name}"
end
aliases_path.unlink if aliases_path.exist?
aliases_path.write(aliases_text.sort.join("\n"))
return true
end
false
end
sig {
params(json_data: T::Hash[String, T.untyped])
.returns([T::Boolean, T.any(String, T::Array[T.untyped], T::Hash[String, T.untyped])])
}
private_class_method def self.verify_and_parse_jws(json_data)
signatures = json_data["signatures"]
homebrew_signature = signatures&.find { |sig| sig.dig("header", "kid") == "homebrew-1" }
return false, "key not found" if homebrew_signature.nil?
header = JSON.parse(Base64.urlsafe_decode64(homebrew_signature["protected"]))
if header["alg"] != "PS512" || header["b64"] != false # NOTE: nil has a meaning of true
return false, "invalid algorithm"
end
require "openssl"
pubkey = OpenSSL::PKey::RSA.new((HOMEBREW_LIBRARY_PATH/"api/homebrew-1.pem").read)
signing_input = "#{homebrew_signature["protected"]}.#{json_data["payload"]}"
unless pubkey.verify_pss("SHA512",
Base64.urlsafe_decode64(homebrew_signature["signature"]),
signing_input,
salt_length: :digest,
mgf1_hash: "SHA512")
return false, "signature mismatch"
end
[true, JSON.parse(json_data["payload"], freeze: true)]
end
sig { params(path: Pathname).returns(T.nilable(Tap)) }
def self.tap_from_source_download(path)
path = path.expand_path
source_relative_path = path.relative_path_from(Homebrew::API::HOMEBREW_CACHE_API_SOURCE)
return if source_relative_path.to_s.start_with?("../")
org, repo = source_relative_path.each_filename.first(2)
return if org.blank? || repo.blank?
Tap.fetch(org, repo)
end
sig { returns(T::Array[String]) }
def self.formula_names
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.formula_arrays.keys
else
Homebrew::API::Formula.all_formulae.keys
end
end
sig { returns(T::Hash[String, String]) }
def self.formula_aliases
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.formula_aliases
else
Homebrew::API::Formula.all_aliases
end
end
sig { returns(T::Hash[String, String]) }
def self.formula_renames
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.formula_renames
else
Homebrew::API::Formula.all_renames
end
end
sig { returns(T::Hash[String, String]) }
def self.formula_tap_migrations
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.formula_tap_migrations
else
Homebrew::API::Formula.tap_migrations
end
end
sig { returns(Pathname) }
def self.cached_formula_json_file_path
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.cached_formula_json_file_path
else
Homebrew::API::Formula.cached_json_file_path
end
end
sig { returns(T::Array[String]) }
def self.cask_tokens
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.cask_hashes.keys
else
Homebrew::API::Cask.all_casks.keys
end
end
sig { returns(T::Hash[String, String]) }
def self.cask_renames
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.cask_renames
else
Homebrew::API::Cask.all_renames
end
end
sig { returns(T::Hash[String, String]) }
def self.cask_tap_migrations
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.cask_tap_migrations
else
Homebrew::API::Cask.tap_migrations
end
end
sig { returns(Pathname) }
def self.cached_cask_json_file_path
if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.cached_cask_json_file_path
else
Homebrew::API::Cask.cached_json_file_path
end
end
end
sig { type_parameters(:U).params(block: T.proc.returns(T.type_parameter(:U))).returns(T.type_parameter(:U)) }
def self.with_no_api_env(&block)
return yield if Homebrew::EnvConfig.no_install_from_api?
with_env(HOMEBREW_NO_INSTALL_FROM_API: "1", HOMEBREW_AUTOMATICALLY_SET_NO_INSTALL_FROM_API: "1", &block)
end
sig {
type_parameters(:U).params(
condition: T::Boolean,
block: T.proc.returns(T.type_parameter(:U)),
).returns(T.type_parameter(:U))
}
def self.with_no_api_env_if_needed(condition, &block)
return yield unless condition
with_no_api_env(&block)
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/help.rb | Library/Homebrew/help.rb | # typed: strict
# frozen_string_literal: true
require "cli/parser"
require "commands"
require "utils/output"
module Homebrew
# Helper module for printing help output.
module Help
extend Utils::Output::Mixin
sig {
params(
cmd: T.nilable(String),
empty_argv: T::Boolean,
usage_error: T.nilable(String),
remaining_args: T::Array[String],
).void
}
def self.help(cmd = nil, empty_argv: false, usage_error: nil, remaining_args: [])
if cmd.nil?
# Handle `brew` (no arguments).
if empty_argv
$stderr.puts HOMEBREW_HELP_MESSAGE
exit 1
end
# Handle `brew (-h|--help|--usage|-?|help)` (no other arguments).
puts HOMEBREW_HELP_MESSAGE
exit 0
end
# Resolve command aliases and find file containing the implementation.
path = Commands.path(cmd)
# Display command-specific (or generic) help in response to `UsageError`.
if usage_error
$stderr.puts path ? command_help(cmd, path, remaining_args:) : HOMEBREW_HELP_MESSAGE
$stderr.puts
onoe usage_error
exit 1
end
# Resume execution in `brew.rb` for unknown commands.
return if path.nil?
# Display help for internal command (or generic help if undocumented).
puts command_help(cmd, path, remaining_args:)
exit 0
end
sig {
params(
cmd: String,
path: Pathname,
remaining_args: T::Array[String],
).returns(String)
}
def self.command_help(cmd, path, remaining_args:)
# Only some types of commands can have a parser.
output = if Commands.valid_internal_cmd?(cmd) ||
Commands.valid_internal_dev_cmd?(cmd) ||
Commands.external_ruby_v2_cmd_path(cmd)
parser_help(path, remaining_args:)
end
output ||= comment_help(path)
output ||= if output.blank?
opoo "No help text in: #{path}" if Homebrew::EnvConfig.developer?
HOMEBREW_HELP_MESSAGE
end
output
end
private_class_method :command_help
sig {
params(
path: Pathname,
remaining_args: T::Array[String],
).returns(T.nilable(String))
}
def self.parser_help(path, remaining_args:)
# Let OptionParser generate help text for commands which have a parser.
cmd_parser = CLI::Parser.from_cmd_path(path)
return unless cmd_parser
# Try parsing arguments here in order to show formula options in help output.
cmd_parser.parse(remaining_args, ignore_invalid_options: true)
cmd_parser.generate_help_text
end
private_class_method :parser_help
sig { params(path: Pathname).returns(T::Array[String]) }
def self.command_help_lines(path)
path.read
.lines
.grep(/^#:/)
.filter_map { |line| line.slice(2..-1)&.delete_prefix(" ") }
end
private_class_method :command_help_lines
sig { params(path: Pathname).returns(T.nilable(String)) }
def self.comment_help(path)
# Otherwise read #: lines from the file.
help_lines = command_help_lines(path)
return if help_lines.blank?
Formatter.format_help_text(help_lines.join, width: Formatter::COMMAND_DESC_WIDTH)
.sub("@hide_from_man_page ", "")
.sub(/^\* /, "#{Tty.bold}Usage: brew#{Tty.reset} ")
.gsub(/`(.*?)`/m, "#{Tty.bold}\\1#{Tty.reset}")
.gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) }
.gsub(/<(.*?)>/m, "#{Tty.underline}\\1#{Tty.reset}")
.gsub(/\*(.*?)\*/m, "#{Tty.underline}\\1#{Tty.reset}")
end
private_class_method :comment_help
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/git_repository.rb | Library/Homebrew/git_repository.rb | # typed: strict
# frozen_string_literal: true
require "utils/git"
require "utils/popen"
# Given a {Pathname}, provides methods for querying Git repository information.
# @see Utils::Git
class GitRepository
sig { returns(Pathname) }
attr_reader :pathname
sig { params(pathname: Pathname).void }
def initialize(pathname)
@pathname = pathname
end
sig { returns(T::Boolean) }
def git_repository?
pathname.join(".git").exist?
end
# Gets the URL of the Git origin remote.
sig { returns(T.nilable(String)) }
def origin_url
popen_git("config", "--get", "remote.origin.url")
end
# Sets the URL of the Git origin remote.
sig { params(origin: String).void }
def origin_url=(origin)
return if !git_repository? || !Utils::Git.available?
safe_system Utils::Git.git, "remote", "set-url", "origin", origin, chdir: pathname
end
# Gets the full commit hash of the HEAD commit.
sig { params(safe: T::Boolean).returns(T.nilable(String)) }
def head_ref(safe: false)
popen_git("rev-parse", "--verify", "--quiet", "HEAD", safe:)
end
# Gets a short commit hash of the HEAD commit.
sig { params(length: T.nilable(Integer), safe: T::Boolean).returns(T.nilable(String)) }
def short_head_ref(length: nil, safe: false)
short_arg = length.present? ? "--short=#{length}" : "--short"
popen_git("rev-parse", short_arg, "--verify", "--quiet", "HEAD", safe:)
end
# Gets the relative date of the last commit, e.g. "1 hour ago"
sig { returns(T.nilable(String)) }
def last_committed
popen_git("show", "-s", "--format=%cr", "HEAD")
end
# Gets the name of the currently checked-out branch, or HEAD if the repository is in a detached HEAD state.
sig { params(safe: T::Boolean).returns(T.nilable(String)) }
def branch_name(safe: false)
popen_git("rev-parse", "--abbrev-ref", "HEAD", safe:)
end
# Change the name of a local branch
sig { params(old: String, new: String).void }
def rename_branch(old:, new:)
popen_git("branch", "-m", old, new)
end
# Set an upstream branch for a local branch to track
sig { params(local: String, origin: String).void }
def set_upstream_branch(local:, origin:)
popen_git("branch", "-u", "origin/#{origin}", local)
end
# Gets the name of the default origin HEAD branch.
sig { returns(T.nilable(String)) }
def origin_branch_name
popen_git("symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD")&.split("/")&.last
end
# Returns true if the repository's current branch matches the default origin branch.
sig { returns(T.nilable(T::Boolean)) }
def default_origin_branch?
origin_branch_name == branch_name
end
# Returns the date of the last commit, in YYYY-MM-DD format.
sig { returns(T.nilable(String)) }
def last_commit_date
popen_git("show", "-s", "--format=%cd", "--date=short", "HEAD")
end
# Returns true if the given branch exists on origin
sig { params(branch: String).returns(T::Boolean) }
def origin_has_branch?(branch)
popen_git("ls-remote", "--heads", "origin", branch).present?
end
sig { void }
def set_head_origin_auto
popen_git("remote", "set-head", "origin", "--auto")
end
# Gets the full commit message of the specified commit, or of the HEAD commit if unspecified.
sig { params(commit: String, safe: T::Boolean).returns(T.nilable(String)) }
def commit_message(commit = "HEAD", safe: false)
popen_git("log", "-1", "--pretty=%B", commit, "--", safe:, err: :out)&.strip
end
sig { returns(String) }
def to_s = pathname.to_s
private
sig { params(args: T.untyped, safe: T::Boolean, err: T.nilable(Symbol)).returns(T.nilable(String)) }
def popen_git(*args, safe: false, err: nil)
unless git_repository?
return unless safe
raise "Not a Git repository: #{pathname}"
end
unless Utils::Git.available?
return unless safe
raise "Git is unavailable"
end
Utils.popen_read(Utils::Git.git, *args, safe:, chdir: pathname, err:).chomp.presence
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/github_runner_matrix.rb | Library/Homebrew/github_runner_matrix.rb | # typed: strict
# frozen_string_literal: true
require "test_runner_formula"
require "github_runner"
class GitHubRunnerMatrix
# When bumping newest runner, run e.g. `git log -p --reverse -G "sha256 tahoe"`
# on homebrew/core and tag the first commit with a bottle e.g.
# `git tag 15-sequoia f42c4a659e4da887fc714f8f41cc26794a4bb320`
# to allow people to jump to specific commits based on their macOS version.
NEWEST_HOMEBREW_CORE_MACOS_RUNNER = :tahoe
OLDEST_HOMEBREW_CORE_MACOS_RUNNER = :sonoma
NEWEST_HOMEBREW_CORE_INTEL_MACOS_RUNNER = :sonoma
RunnerSpec = T.type_alias { T.any(LinuxRunnerSpec, MacOSRunnerSpec) }
private_constant :RunnerSpec
MacOSRunnerSpecHash = T.type_alias do
{
name: String,
runner: String,
timeout: Integer,
cleanup: T::Boolean,
testing_formulae: String,
}
end
private_constant :MacOSRunnerSpecHash
LinuxRunnerSpecHash = T.type_alias do
{
name: String,
runner: String,
container: T::Hash[Symbol, String],
workdir: String,
timeout: Integer,
cleanup: T::Boolean,
testing_formulae: String,
}
end
private_constant :LinuxRunnerSpecHash
RunnerSpecHash = T.type_alias { T.any(LinuxRunnerSpecHash, MacOSRunnerSpecHash) }
private_constant :RunnerSpecHash
sig { returns(T::Array[GitHubRunner]) }
attr_reader :runners
sig {
params(
testing_formulae: T::Array[TestRunnerFormula],
deleted_formulae: T::Array[String],
all_supported: T::Boolean,
dependent_matrix: T::Boolean,
).void
}
def initialize(testing_formulae, deleted_formulae, all_supported:, dependent_matrix:)
if all_supported && (testing_formulae.present? || deleted_formulae.present? || dependent_matrix)
raise ArgumentError, "all_supported is mutually exclusive to other arguments"
end
@testing_formulae = testing_formulae
@deleted_formulae = deleted_formulae
@all_supported = all_supported
@dependent_matrix = dependent_matrix
@compatible_testing_formulae = T.let({}, T::Hash[GitHubRunner, T::Array[TestRunnerFormula]])
@formulae_with_untested_dependents = T.let({}, T::Hash[GitHubRunner, T::Array[TestRunnerFormula]])
@runners = T.let([], T::Array[GitHubRunner])
generate_runners!
freeze
end
sig { returns(T::Array[RunnerSpecHash]) }
def active_runner_specs_hash
runners.select(&:active)
.map(&:spec)
.map(&:to_h)
end
private
SELF_HOSTED_LINUX_RUNNER = "linux-self-hosted-1"
# ARM macOS timeout, keep this under 1/2 of GitHub's job execution time limit for self-hosted runners.
# https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners#usage-limits
GITHUB_ACTIONS_LONG_TIMEOUT = 2160 # 36 hours
GITHUB_ACTIONS_SHORT_TIMEOUT = 60
private_constant :SELF_HOSTED_LINUX_RUNNER, :GITHUB_ACTIONS_LONG_TIMEOUT, :GITHUB_ACTIONS_SHORT_TIMEOUT
sig { params(arch: Symbol).returns(LinuxRunnerSpec) }
def linux_runner_spec(arch)
linux_runner = case arch
when :arm64 then "ubuntu-22.04-arm"
when :x86_64 then ENV.fetch("HOMEBREW_LINUX_RUNNER", "ubuntu-latest")
else raise "Unknown Linux architecture: #{arch}"
end
LinuxRunnerSpec.new(
name: "Linux #{arch}",
runner: linux_runner,
container: {
image: "ghcr.io/homebrew/ubuntu22.04:main",
options: "--user=linuxbrew -e GITHUB_ACTIONS_HOMEBREW_SELF_HOSTED",
},
workdir: "/github/home",
timeout: GITHUB_ACTIONS_LONG_TIMEOUT,
cleanup: linux_runner == SELF_HOSTED_LINUX_RUNNER,
)
end
VALID_PLATFORMS = T.let([:macos, :linux].freeze, T::Array[Symbol])
VALID_ARCHES = T.let([:arm64, :x86_64].freeze, T::Array[Symbol])
private_constant :VALID_PLATFORMS, :VALID_ARCHES
sig {
params(
platform: Symbol,
arch: Symbol,
spec: T.nilable(RunnerSpec),
macos_version: T.nilable(MacOSVersion),
).returns(GitHubRunner)
}
def create_runner(platform, arch, spec = nil, macos_version = nil)
raise "Unexpected platform: #{platform}" if VALID_PLATFORMS.exclude?(platform)
raise "Unexpected arch: #{arch}" if VALID_ARCHES.exclude?(arch)
raise "Missing `spec` argument" if spec.nil? && platform != :linux
spec ||= linux_runner_spec(arch)
runner = GitHubRunner.new(platform:, arch:, spec:, macos_version:)
runner.spec.testing_formulae += testable_formulae(runner)
runner.active = active_runner?(runner)
runner.freeze
end
sig { params(macos_version: MacOSVersion).returns(T::Boolean) }
def runner_enabled?(macos_version)
macos_version.between?(OLDEST_HOMEBREW_CORE_MACOS_RUNNER, NEWEST_HOMEBREW_CORE_MACOS_RUNNER)
end
NEWEST_GITHUB_ACTIONS_INTEL_MACOS_RUNNER = :ventura
OLDEST_GITHUB_ACTIONS_INTEL_MACOS_RUNNER = :ventura
NEWEST_GITHUB_ACTIONS_ARM_MACOS_RUNNER = :tahoe
OLDEST_GITHUB_ACTIONS_ARM_MACOS_RUNNER = :sonoma
GITHUB_ACTIONS_RUNNER_TIMEOUT = 360
private_constant :NEWEST_GITHUB_ACTIONS_INTEL_MACOS_RUNNER, :OLDEST_GITHUB_ACTIONS_INTEL_MACOS_RUNNER,
:NEWEST_GITHUB_ACTIONS_ARM_MACOS_RUNNER, :OLDEST_GITHUB_ACTIONS_ARM_MACOS_RUNNER,
:GITHUB_ACTIONS_RUNNER_TIMEOUT
sig { void }
def generate_runners!
return if @runners.present?
# gracefully handle non-GitHub Actions environments
github_run_id = if ENV.key?("GITHUB_ACTIONS")
ENV.fetch("GITHUB_RUN_ID")
else
ENV.fetch("GITHUB_RUN_ID", "")
end
# Portable Ruby logic
if @testing_formulae.any? { |tf| tf.name.start_with?("portable-") }
@runners << create_runner(:linux, :x86_64)
@runners << create_runner(:linux, :arm64)
x86_64_spec = MacOSRunnerSpec.new(
name: "macOS 10.15 x86_64",
runner: "10.15-#{github_run_id}",
timeout: GITHUB_ACTIONS_LONG_TIMEOUT,
cleanup: true,
)
x86_64_macos_version = MacOSVersion.new("10.15")
@runners << create_runner(:macos, :x86_64, x86_64_spec, x86_64_macos_version)
# odisabled: remove support for Big Sur September (or later) 2027
arm64_spec = MacOSRunnerSpec.new(
name: "macOS 11-arm64-cross",
runner: "11-arm64-cross-#{github_run_id}",
timeout: GITHUB_ACTIONS_LONG_TIMEOUT,
cleanup: true,
)
arm64_macos_version = MacOSVersion.new("11")
@runners << create_runner(:macos, :arm64, arm64_spec, arm64_macos_version)
return
end
if !@all_supported || ENV.key?("HOMEBREW_LINUX_RUNNER")
self_hosted_deps = @dependent_matrix && ENV["HOMEBREW_LINUX_RUNNER"] == SELF_HOSTED_LINUX_RUNNER
@runners << create_runner(:linux, :x86_64)
@runners << create_runner(:linux, :arm64) unless self_hosted_deps
end
long_timeout = ENV.fetch("HOMEBREW_MACOS_LONG_TIMEOUT", "false") == "true"
use_github_runner = ENV.fetch("HOMEBREW_MACOS_BUILD_ON_GITHUB_RUNNER", "false") == "true"
runner_timeout = long_timeout ? GITHUB_ACTIONS_LONG_TIMEOUT : GITHUB_ACTIONS_SHORT_TIMEOUT
# Use GitHub Actions macOS Runner for testing dependents if compatible with timeout.
use_github_runner ||= @dependent_matrix
use_github_runner &&= runner_timeout <= GITHUB_ACTIONS_RUNNER_TIMEOUT
ephemeral_suffix = "-#{github_run_id}"
ephemeral_suffix << "-deps" if @dependent_matrix
ephemeral_suffix << "-long" if runner_timeout == GITHUB_ACTIONS_LONG_TIMEOUT
ephemeral_suffix.freeze
MacOSVersion::SYMBOLS.each_value do |version|
macos_version = MacOSVersion.new(version)
next unless runner_enabled?(macos_version)
github_runner_available = macos_version.between?(OLDEST_GITHUB_ACTIONS_ARM_MACOS_RUNNER,
NEWEST_GITHUB_ACTIONS_ARM_MACOS_RUNNER)
runner, timeout = if use_github_runner && github_runner_available
["macos-#{version}", GITHUB_ACTIONS_RUNNER_TIMEOUT]
elsif macos_version >= :monterey
["#{version}-arm64#{ephemeral_suffix}", runner_timeout]
else
["#{version}-arm64", runner_timeout]
end
# We test recursive dependents on ARM macOS, so they can be slower than our Intel runners.
timeout *= 2 if @dependent_matrix && timeout < GITHUB_ACTIONS_RUNNER_TIMEOUT
spec = MacOSRunnerSpec.new(
name: "macOS #{version}-arm64",
runner:,
timeout:,
cleanup: !runner.end_with?(ephemeral_suffix),
)
@runners << create_runner(:macos, :arm64, spec, macos_version)
skip_intel_runner = !@all_supported && macos_version > NEWEST_HOMEBREW_CORE_INTEL_MACOS_RUNNER
skip_intel_runner &&= @dependent_matrix || @testing_formulae.none? do |testing_formula|
testing_formula.formula.bottle_specification.tag?(Utils::Bottles.tag(macos_version.to_sym))
end
next if skip_intel_runner
github_runner_available = macos_version.between?(OLDEST_GITHUB_ACTIONS_INTEL_MACOS_RUNNER,
NEWEST_GITHUB_ACTIONS_INTEL_MACOS_RUNNER)
runner, timeout = if use_github_runner && github_runner_available
["macos-#{version}", GITHUB_ACTIONS_RUNNER_TIMEOUT]
else
["#{version}-x86_64#{ephemeral_suffix}", runner_timeout]
end
# macOS 12-x86_64 is usually slower.
timeout += 30 if macos_version <= :monterey
# The ARM runners are typically over twice as fast as the Intel runners.
timeout *= 2 if !(use_github_runner && github_runner_available) && timeout < GITHUB_ACTIONS_LONG_TIMEOUT
spec = MacOSRunnerSpec.new(
name: "macOS #{version}-x86_64",
runner:,
timeout:,
cleanup: !runner.end_with?(ephemeral_suffix),
)
@runners << create_runner(:macos, :x86_64, spec, macos_version)
end
@runners.freeze
end
sig { params(runner: GitHubRunner).returns(T::Array[String]) }
def testable_formulae(runner)
formulae = if @dependent_matrix
formulae_with_untested_dependents(runner)
else
compatible_testing_formulae(runner)
end
formulae.map(&:name)
end
sig { params(runner: GitHubRunner).returns(T::Boolean) }
def active_runner?(runner)
return true if @all_supported
return true if @deleted_formulae.present? && !@dependent_matrix
runner.spec.testing_formulae.present?
end
sig { params(runner: GitHubRunner).returns(T::Array[TestRunnerFormula]) }
def compatible_testing_formulae(runner)
@compatible_testing_formulae[runner] ||= begin
platform = runner.platform
arch = runner.arch
macos_version = runner.macos_version
@testing_formulae.select do |formula|
Homebrew::SimulateSystem.with(os: platform, arch: Homebrew::SimulateSystem.arch_symbols.fetch(arch)) do
simulated_formula = TestRunnerFormula.new(Formulary.factory(formula.name))
next false if macos_version && !simulated_formula.compatible_with?(macos_version)
simulated_formula.public_send(:"#{platform}_compatible?") &&
simulated_formula.public_send(:"#{arch}_compatible?")
end
end
end
end
sig { params(runner: GitHubRunner).returns(T::Array[TestRunnerFormula]) }
def formulae_with_untested_dependents(runner)
@formulae_with_untested_dependents[runner] ||= begin
platform = runner.platform
arch = runner.arch
macos_version = runner.macos_version
compatible_testing_formulae(runner).select do |formula|
compatible_dependents = formula.dependents(platform:, arch:, macos_version: macos_version&.to_sym)
.select do |dependent_f|
Homebrew::SimulateSystem.with(os: platform, arch: Homebrew::SimulateSystem.arch_symbols.fetch(arch)) do
simulated_dependent_f = TestRunnerFormula.new(Formulary.factory(dependent_f.name))
next false if macos_version && !simulated_dependent_f.compatible_with?(macos_version)
simulated_dependent_f.public_send(:"#{platform}_compatible?") &&
simulated_dependent_f.public_send(:"#{arch}_compatible?")
end
end
# These arrays will generally have been generated by different Formulary caches,
# so we can only compare them by name and not directly.
(compatible_dependents.map(&:name) - @testing_formulae.map(&:name)).present?
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/settings.rb | Library/Homebrew/settings.rb | # typed: strict
# frozen_string_literal: true
require "utils/popen"
module Homebrew
# Helper functions for reading and writing settings.
module Settings
sig {
params(setting: T.any(String, Symbol), repo: Pathname)
.returns(T.nilable(String))
}
def self.read(setting, repo: HOMEBREW_REPOSITORY)
return unless (repo/".git/config").exist?
value = Utils.popen_read("git", "-C", repo.to_s, "config", "--get", "homebrew.#{setting}").chomp
return if value.strip.empty?
value
end
sig { params(setting: T.any(String, Symbol), value: T.any(String, T::Boolean), repo: Pathname).void }
def self.write(setting, value, repo: HOMEBREW_REPOSITORY)
return unless (repo/".git/config").exist?
value = value.to_s
return if read(setting, repo:) == value
Kernel.system("git", "-C", repo.to_s, "config", "--replace-all", "homebrew.#{setting}", value, exception: true)
end
sig { params(setting: T.any(String, Symbol), repo: Pathname).void }
def self.delete(setting, repo: HOMEBREW_REPOSITORY)
return unless (repo/".git/config").exist?
return if read(setting, repo:).nil?
Kernel.system("git", "-C", repo.to_s, "config", "--unset-all", "homebrew.#{setting}", exception: 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/compilers.rb | Library/Homebrew/compilers.rb | # typed: strict
# frozen_string_literal: true
module CompilerConstants
# GCC 7 - Ubuntu 18.04 (ESM ends 2028-04-01)
# GCC 8 - RHEL 8 (ELS ends 2032-05-31)
GNU_GCC_VERSIONS = %w[7 8 9 10 11 12 13 14 15].freeze
GNU_GCC_REGEXP = /^gcc-(#{GNU_GCC_VERSIONS.join("|")})$/
COMPILER_SYMBOL_MAP = T.let({
"gcc" => :gcc,
"clang" => :clang,
"llvm_clang" => :llvm_clang,
}.freeze, T::Hash[String, Symbol])
COMPILERS = T.let((COMPILER_SYMBOL_MAP.values +
GNU_GCC_VERSIONS.map { |n| "gcc-#{n}" }).freeze, T::Array[T.any(String, Symbol)])
end
# Class for checking compiler compatibility for a formula.
class CompilerFailure
sig { returns(Symbol) }
attr_reader :type
sig { params(val: T.any(Integer, String)).returns(Version) }
def version(val = T.unsafe(nil))
@version = Version.parse(val.to_s) if val
@version
end
# Allows Apple compiler `fails_with` statements to keep using `build`
# even though `build` and `version` are the same internally.
alias build version
# The cause is no longer used so we need not hold a reference to the string.
sig { params(_: String).void }
def cause(_); end
sig {
params(spec: T.any(Symbol, T::Hash[Symbol, String]), block: T.nilable(T.proc.void)).returns(T.attached_class)
}
def self.create(spec, &block)
# Non-Apple compilers are in the format fails_with compiler => version
if spec.is_a?(Hash)
compiler, major_version = spec.first
raise ArgumentError, "The `fails_with` hash syntax only supports GCC" if compiler != :gcc
type = compiler
# so `fails_with gcc: "7"` simply marks all 7 releases incompatible
version = "#{major_version}.999"
exact_major_match = true
else
type = spec
version = 9999
exact_major_match = false
end
new(type, version, exact_major_match:, &block)
end
sig { params(compiler: CompilerSelector::Compiler).returns(T::Boolean) }
def fails_with?(compiler)
version_matched = if type != :gcc
version >= compiler.version
elsif @exact_major_match
gcc_major(version) == gcc_major(compiler.version) && version >= compiler.version
else
gcc_major(version) >= gcc_major(compiler.version)
end
type == compiler.type && version_matched
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: #{type} #{version}>"
end
private
sig {
params(
type: Symbol,
version: T.any(Integer, String),
exact_major_match: T::Boolean,
block: T.nilable(T.proc.void),
).void
}
def initialize(type, version, exact_major_match:, &block)
@type = type
@version = T.let(Version.parse(version.to_s), Version)
@exact_major_match = exact_major_match
instance_eval(&block) if block
end
sig { params(version: Version).returns(Version) }
def gcc_major(version)
Version.new(version.major.to_s)
end
end
# Class for selecting a compiler for a formula.
class CompilerSelector
include CompilerConstants
class Compiler < T::Struct
const :type, Symbol
const :name, T.any(String, Symbol)
const :version, Version
end
COMPILER_PRIORITY = T.let({
clang: [:clang, :llvm_clang, :gnu],
gcc: [:gnu, :gcc, :llvm_clang, :clang],
}.freeze, T::Hash[Symbol, T::Array[Symbol]])
sig {
params(formula: T.any(Formula, SoftwareSpec), compilers: T.nilable(T::Array[Symbol]), testing_formula: T::Boolean)
.returns(T.any(String, Symbol))
}
def self.select_for(formula, compilers = nil, testing_formula: false)
if compilers.nil? && DevelopmentTools.default_compiler == :clang
deps = formula.deps.filter_map do |dep|
dep.name if dep.required? || (testing_formula && dep.test?) || (!testing_formula && dep.build?)
end
compilers = [:clang, :gnu, :llvm_clang] if deps.none?("llvm") && deps.any?(/^gcc(@\d+)?$/)
end
new(formula, DevelopmentTools, compilers || self.compilers).compiler
end
sig { returns(T::Array[Symbol]) }
def self.compilers
COMPILER_PRIORITY.fetch(DevelopmentTools.default_compiler)
end
sig { returns(T.any(Formula, SoftwareSpec)) }
attr_reader :formula
sig { returns(T::Array[CompilerFailure]) }
attr_reader :failures
sig { returns(T.class_of(DevelopmentTools)) }
attr_reader :versions
sig { returns(T::Array[Symbol]) }
attr_reader :compilers
sig {
params(
formula: T.any(Formula, SoftwareSpec),
versions: T.class_of(DevelopmentTools),
compilers: T::Array[Symbol],
).void
}
def initialize(formula, versions, compilers)
@formula = formula
@failures = T.let(formula.compiler_failures, T::Array[CompilerFailure])
@versions = versions
@compilers = compilers
end
sig { returns(T.any(String, Symbol)) }
def compiler
find_compiler { |c| return c.name unless fails_with?(c) }
raise CompilerSelectionError, formula
end
sig { returns(String) }
def self.preferred_gcc
"gcc"
end
private
sig { returns(T::Array[String]) }
def gnu_gcc_versions
# prioritize gcc version provided by gcc formula.
v = Formulary.factory(CompilerSelector.preferred_gcc).version.to_s.slice(/\d+/)
GNU_GCC_VERSIONS - [v] + [v] # move the version to the end of the list
rescue FormulaUnavailableError
GNU_GCC_VERSIONS
end
sig { params(_block: T.proc.params(arg0: Compiler).void).void }
def find_compiler(&_block)
compilers.each do |compiler|
case compiler
when :gnu
gnu_gcc_versions.reverse_each do |v|
executable = "gcc-#{v}"
version = compiler_version(executable)
yield Compiler.new(type: :gcc, name: executable, version:) unless version.null?
end
when :llvm
next # no-op. DSL supported, compiler is not.
else
version = compiler_version(compiler)
yield Compiler.new(type: compiler, name: compiler, version:) unless version.null?
end
end
end
sig { params(compiler: Compiler).returns(T::Boolean) }
def fails_with?(compiler)
failures.any? { |failure| failure.fails_with?(compiler) }
end
sig { params(name: T.any(String, Symbol)).returns(Version) }
def compiler_version(name)
case name.to_s
when "gcc", GNU_GCC_REGEXP
versions.gcc_version(name.to_s)
else
versions.send(:"#{name}_build_version")
end
end
end
require "extend/os/compilers"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dependencies_helpers.rb | Library/Homebrew/dependencies_helpers.rb | # typed: strict
# frozen_string_literal: true
require "cask_dependent"
# Helper functions for dependencies.
module DependenciesHelpers
def args_includes_ignores(args)
includes = [:required?, :recommended?] # included by default
includes << :implicit? if args.include_implicit?
includes << :build? if args.include_build?
includes << :test? if args.include_test?
includes << :optional? if args.include_optional?
ignores = []
ignores << :recommended? if args.skip_recommended?
ignores << :satisfied? if args.missing?
[includes, ignores]
end
sig {
params(root_dependent: T.any(Formula, CaskDependent), includes: T::Array[Symbol], ignores: T::Array[Symbol])
.returns(T::Array[Dependency])
}
def recursive_dep_includes(root_dependent, includes, ignores)
# The use of T.unsafe is recommended by the Sorbet docs:
# https://sorbet.org/docs/overloads#multiple-methods-but-sharing-a-common-implementation
T.unsafe(recursive_includes(Dependency, root_dependent, includes, ignores))
end
sig {
params(root_dependent: T.any(Formula, CaskDependent), includes: T::Array[Symbol], ignores: T::Array[Symbol])
.returns(Requirements)
}
def recursive_req_includes(root_dependent, includes, ignores)
# The use of T.unsafe is recommended by the Sorbet docs:
# https://sorbet.org/docs/overloads#multiple-methods-but-sharing-a-common-implementation
T.unsafe(recursive_includes(Requirement, root_dependent, includes, ignores))
end
sig {
params(
klass: T.any(T.class_of(Dependency), T.class_of(Requirement)),
root_dependent: T.any(Formula, CaskDependent),
includes: T::Array[Symbol],
ignores: T::Array[Symbol],
).returns(T.any(T::Array[Dependency], Requirements))
}
def recursive_includes(klass, root_dependent, includes, ignores)
cache_key = "recursive_includes_#{includes}_#{ignores}"
klass.expand(root_dependent, cache_key:) do |dependent, dep|
klass.prune if ignores.any? { |ignore| dep.public_send(ignore) }
klass.prune if includes.none? do |include|
# Ignore indirect test dependencies
next if include == :test? && dependent != root_dependent
dep.public_send(include)
end
# If a tap isn't installed, we can't find the dependencies of one of
# its formulae and an exception will be thrown if we try.
Dependency.keep_but_prune_recursive_deps if klass == Dependency && dep.tap && !dep.tap.installed?
end
end
sig {
params(
dependables: T.any(Dependencies, Requirements, T::Array[Dependency], T::Array[Requirement]),
ignores: T::Array[Symbol],
includes: T::Array[Symbol],
).returns(T::Array[T.any(Dependency, Requirement)])
}
def select_includes(dependables, ignores, includes)
dependables.select do |dep|
next false if ignores.any? { |ignore| dep.public_send(ignore) }
includes.any? { |include| dep.public_send(include) }
end
end
sig {
params(formulae_or_casks: T::Array[T.any(Formula, Keg, Cask::Cask)])
.returns(T::Array[T.any(Formula, CaskDependent)])
}
def dependents(formulae_or_casks)
formulae_or_casks.map do |formula_or_cask|
case formula_or_cask
when Formula then formula_or_cask
when Cask::Cask then CaskDependent.new(formula_or_cask)
else
raise TypeError, "Unsupported type: #{formula_or_cask.class}"
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/url.rb | Library/Homebrew/url.rb | # typed: strict
# frozen_string_literal: true
require "version"
class URL
sig { returns(T::Hash[Symbol, T.untyped]) }
attr_reader :specs
sig { returns(T.nilable(T.any(Symbol, T::Class[AbstractDownloadStrategy]))) }
attr_reader :using
sig { params(url: String, specs: T::Hash[Symbol, T.untyped]).void }
def initialize(url, specs = {})
@url = T.let(url.freeze, String)
@specs = T.let(specs.dup, T::Hash[Symbol, T.untyped])
@using = T.let(@specs.delete(:using), T.nilable(T.any(Symbol, T::Class[AbstractDownloadStrategy])))
@specs.freeze
end
sig { returns(String) }
def to_s
@url
end
sig { returns(T::Class[AbstractDownloadStrategy]) }
def download_strategy
@download_strategy ||=
T.let(DownloadStrategyDetector.detect(@url, @using), T.nilable(T::Class[AbstractDownloadStrategy]))
end
sig { returns(Version) }
def version
@version ||= T.let(Version.detect(@url, **@specs), T.nilable(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/global.rb | Library/Homebrew/global.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require_relative "startup"
HOMEBREW_HELP_MESSAGE = ENV.fetch("HOMEBREW_HELP_MESSAGE").freeze
HOMEBREW_API_DEFAULT_DOMAIN = ENV.fetch("HOMEBREW_API_DEFAULT_DOMAIN").freeze
HOMEBREW_BOTTLE_DEFAULT_DOMAIN = ENV.fetch("HOMEBREW_BOTTLE_DEFAULT_DOMAIN").freeze
HOMEBREW_BREW_DEFAULT_GIT_REMOTE = ENV.fetch("HOMEBREW_BREW_DEFAULT_GIT_REMOTE").freeze
HOMEBREW_CORE_DEFAULT_GIT_REMOTE = ENV.fetch("HOMEBREW_CORE_DEFAULT_GIT_REMOTE").freeze
HOMEBREW_DEFAULT_CACHE = ENV.fetch("HOMEBREW_DEFAULT_CACHE").freeze
HOMEBREW_DEFAULT_LOGS = ENV.fetch("HOMEBREW_DEFAULT_LOGS").freeze
HOMEBREW_DEFAULT_TEMP = ENV.fetch("HOMEBREW_DEFAULT_TEMP").freeze
HOMEBREW_REQUIRED_RUBY_VERSION = ENV.fetch("HOMEBREW_REQUIRED_RUBY_VERSION").freeze
HOMEBREW_PRODUCT = ENV.fetch("HOMEBREW_PRODUCT").freeze
HOMEBREW_VERSION = ENV.fetch("HOMEBREW_VERSION").freeze
HOMEBREW_WWW = "https://brew.sh"
HOMEBREW_API_WWW = "https://formulae.brew.sh"
HOMEBREW_DOCS_WWW = "https://docs.brew.sh"
HOMEBREW_SYSTEM = ENV.fetch("HOMEBREW_SYSTEM").freeze
HOMEBREW_PROCESSOR = ENV.fetch("HOMEBREW_PROCESSOR").freeze
HOMEBREW_PHYSICAL_PROCESSOR = ENV.fetch("HOMEBREW_PHYSICAL_PROCESSOR").freeze
HOMEBREW_BREWED_CURL_PATH = Pathname(ENV.fetch("HOMEBREW_BREWED_CURL_PATH")).freeze
HOMEBREW_USER_AGENT_CURL = ENV.fetch("HOMEBREW_USER_AGENT_CURL").freeze
HOMEBREW_USER_AGENT_RUBY =
"#{ENV.fetch("HOMEBREW_USER_AGENT")} ruby/#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}".freeze
HOMEBREW_USER_AGENT_FAKE_SAFARI =
# Don't update this beyond 10.15.7 until Safari actually updates their
# user agent to be beyond 10.15.7 (not the case as-of macOS 26)
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 " \
"(KHTML, like Gecko) Version/26.0 Safari/605.1.15"
HOMEBREW_GITHUB_PACKAGES_AUTH = ENV.fetch("HOMEBREW_GITHUB_PACKAGES_AUTH", "").freeze
HOMEBREW_DEFAULT_PREFIX = ENV.fetch("HOMEBREW_GENERIC_DEFAULT_PREFIX").freeze
HOMEBREW_DEFAULT_REPOSITORY = ENV.fetch("HOMEBREW_GENERIC_DEFAULT_REPOSITORY").freeze
HOMEBREW_MACOS_ARM_DEFAULT_PREFIX = ENV.delete("HOMEBREW_MACOS_ARM_DEFAULT_PREFIX").freeze
HOMEBREW_MACOS_ARM_DEFAULT_REPOSITORY = ENV.delete("HOMEBREW_MACOS_ARM_DEFAULT_REPOSITORY").freeze
HOMEBREW_LINUX_DEFAULT_PREFIX = ENV.delete("HOMEBREW_LINUX_DEFAULT_PREFIX").freeze
HOMEBREW_LINUX_DEFAULT_REPOSITORY = ENV.delete("HOMEBREW_LINUX_DEFAULT_REPOSITORY").freeze
HOMEBREW_PREFIX_PLACEHOLDER = "$HOMEBREW_PREFIX"
HOMEBREW_CELLAR_PLACEHOLDER = "$HOMEBREW_CELLAR"
# Needs a leading slash to avoid `File.expand.path` complaining about non-absolute home.
HOMEBREW_HOME_PLACEHOLDER = "/$HOME"
HOMEBREW_CASK_APPDIR_PLACEHOLDER = "$APPDIR"
HOMEBREW_MACOS_NEWEST_UNSUPPORTED = ENV.fetch("HOMEBREW_MACOS_NEWEST_UNSUPPORTED").freeze
HOMEBREW_MACOS_NEWEST_SUPPORTED = ENV.fetch("HOMEBREW_MACOS_NEWEST_SUPPORTED").freeze
HOMEBREW_MACOS_OLDEST_SUPPORTED = ENV.fetch("HOMEBREW_MACOS_OLDEST_SUPPORTED").freeze
HOMEBREW_MACOS_OLDEST_ALLOWED = ENV.fetch("HOMEBREW_MACOS_OLDEST_ALLOWED").freeze
HOMEBREW_PULL_API_REGEX =
%r{https://api\.github\.com/repos/([\w-]+)/([\w-]+)?/pulls/(\d+)}
HOMEBREW_PULL_OR_COMMIT_URL_REGEX =
%r[https://github\.com/([\w-]+)/([\w-]+)?/(?:pull/(\d+)|commit/[0-9a-fA-F]{4,40})]
HOMEBREW_BOTTLES_EXTNAME_REGEX = /\.([a-z0-9_]+)\.bottle\.(?:(\d+)\.)?tar\.gz$/
module Homebrew
DEFAULT_PREFIX = T.let(ENV.fetch("HOMEBREW_DEFAULT_PREFIX").freeze, String)
DEFAULT_REPOSITORY = T.let(ENV.fetch("HOMEBREW_DEFAULT_REPOSITORY").freeze, String)
DEFAULT_CELLAR = "#{DEFAULT_PREFIX}/Cellar".freeze
DEFAULT_MACOS_CELLAR = "#{HOMEBREW_DEFAULT_PREFIX}/Cellar".freeze
DEFAULT_MACOS_ARM_CELLAR = "#{HOMEBREW_MACOS_ARM_DEFAULT_PREFIX}/Cellar".freeze
DEFAULT_LINUX_CELLAR = "#{HOMEBREW_LINUX_DEFAULT_PREFIX}/Cellar".freeze
class << self
attr_writer :failed, :raise_deprecation_exceptions, :auditing
# Check whether Homebrew is using the default prefix.
#
# @api internal
sig { params(prefix: T.any(Pathname, String)).returns(T::Boolean) }
def default_prefix?(prefix = HOMEBREW_PREFIX)
prefix.to_s == DEFAULT_PREFIX
end
def failed?
@failed ||= false
@failed == true
end
def messages
@messages ||= Messages.new
end
def raise_deprecation_exceptions?
@raise_deprecation_exceptions == true
end
def auditing?
@auditing == true
end
def running_as_root?
@process_euid ||= Process.euid
@process_euid.zero?
end
def owner_uid
@owner_uid ||= HOMEBREW_ORIGINAL_BREW_FILE.stat.uid
end
def running_as_root_but_not_owned_by_root?
running_as_root? && !owner_uid.zero?
end
def auto_update_command?
ENV.fetch("HOMEBREW_AUTO_UPDATE_COMMAND", false).present?
end
sig { params(cmd: T.nilable(String)).void }
def running_command=(cmd)
@running_command_with_args = "#{cmd} #{ARGV.join(" ")}"
end
sig { returns String }
def running_command_with_args
"brew #{@running_command_with_args}".strip
end
end
end
require "PATH"
ENV["HOMEBREW_PATH"] ||= ENV.fetch("PATH")
ORIGINAL_PATHS = PATH.new(ENV.fetch("HOMEBREW_PATH")).filter_map do |p|
Pathname.new(p).expand_path
rescue
nil
end.freeze
require "extend/blank"
require "extend/kernel"
require "os"
require "extend/array"
require "cachable"
require "extend/enumerable"
require "extend/string"
require "extend/pathname"
require "exceptions"
require "tap_constants"
require "official_taps"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/formula_free_port.rb | Library/Homebrew/formula_free_port.rb | # typed: strict
# frozen_string_literal: true
require "socket"
module Homebrew
# Helper function for finding a free port.
module FreePort
# Returns a free port.
# @api public
sig { returns(Integer) }
def free_port
server = TCPServer.new 0
_, port, = server.addr
server.close
port
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/retryable_download.rb | Library/Homebrew/retryable_download.rb | # typed: strict
# frozen_string_literal: true
require "bottle"
require "api/json_download"
require "utils/output"
module Homebrew
class RetryableDownload
include Downloadable
include Utils::Output::Mixin
sig { override.returns(T.nilable(T.any(String, URL))) }
def url = downloadable.url
sig { override.returns(T.nilable(Checksum)) }
def checksum = downloadable.checksum
sig { override.returns(T::Array[String]) }
def mirrors = downloadable.mirrors
sig { params(downloadable: Downloadable, tries: Integer, pour: T::Boolean).void }
def initialize(downloadable, tries:, pour: false)
super()
@downloadable = downloadable
@try = T.let(0, Integer)
@tries = tries
@pour = pour
end
sig { override.returns(String) }
def download_queue_name = downloadable.download_queue_name
sig { override.returns(String) }
def download_queue_type = downloadable.download_queue_type
sig { override.returns(Pathname) }
def cached_download = downloadable.cached_download
sig { override.void }
def clear_cache = downloadable.clear_cache
sig { override.returns(T.nilable(Version)) }
def version = downloadable.version
sig { override.returns(T::Class[AbstractDownloadStrategy]) }
def download_strategy = downloadable.download_strategy
sig { override.returns(AbstractDownloadStrategy) }
def downloader = downloadable.downloader
sig {
override.params(
verify_download_integrity: T::Boolean,
timeout: T.nilable(T.any(Integer, Float)),
quiet: T::Boolean,
).returns(Pathname)
}
def fetch(verify_download_integrity: true, timeout: nil, quiet: false)
bottle_tmp_keg = nil
@try += 1
downloadable.downloading!
already_downloaded = downloadable.downloaded?
download = if downloadable.is_a?(Resource) && (resource = T.cast(downloadable, Resource))
resource.fetch(verify_download_integrity: false, timeout:, quiet:, skip_patches: true)
else
downloadable.fetch(verify_download_integrity: false, timeout:, quiet:)
end
downloadable.downloaded!
return download unless download.file?
unless quiet
puts "Downloaded to: #{download}" unless already_downloaded
puts "SHA-256: #{download.sha256}"
end
json_download = downloadable.is_a?(API::JSONDownload)
downloadable.verify_download_integrity(download) if verify_download_integrity && !json_download
if pour && downloadable.is_a?(Bottle)
downloadable.extracting!
HOMEBREW_TEMP_CELLAR.mkpath
bottle_filename = T.cast(downloadable, Bottle).filename
bottle_tmp_keg = HOMEBREW_TEMP_CELLAR/bottle_filename.name/bottle_filename.version.to_s
bottle_poured_file = Pathname("#{bottle_tmp_keg}.poured")
unless bottle_poured_file.exist?
FileUtils.rm(bottle_poured_file) if bottle_poured_file.symlink?
FileUtils.rm_r(bottle_tmp_keg) if bottle_tmp_keg.directory?
UnpackStrategy.detect(download, prioritize_extension: true)
.extract_nestedly(to: HOMEBREW_TEMP_CELLAR)
# Create a separate file to mark a completed extraction. This avoids
# a potential race condition if a user interrupts the install.
# We use a symlink to easily check that both this extra status file
# and the real extracted directory exist via `Pathname#exist?`.
FileUtils.ln_s(bottle_tmp_keg, bottle_poured_file)
end
downloadable.downloaded!
elsif json_download
FileUtils.touch(download, mtime: Time.now)
end
download
rescue DownloadError, ChecksumMismatchError, Resource::BottleManifest::Error
tries_remaining = @tries - @try
if tries_remaining.zero?
cleanup_partial_installation_on_error!(bottle_tmp_keg)
raise
end
wait = 2 ** @try
unless quiet
what = Utils.pluralize("try", tries_remaining)
ohai "Retrying download in #{wait}s... (#{tries_remaining} #{what} left)"
end
sleep wait
downloadable.clear_cache
retry
# Catch any other types of exceptions as they leave us with partial installations.
rescue Exception # rubocop:disable Lint/RescueException
cleanup_partial_installation_on_error!(bottle_tmp_keg)
raise
end
sig { override.params(filename: Pathname).void }
def verify_download_integrity(filename) = downloadable.verify_download_integrity(filename)
private
sig { returns(Downloadable) }
attr_reader :downloadable
sig { returns(T::Boolean) }
attr_reader :pour
sig { params(path: T.nilable(Pathname)).void }
def cleanup_partial_installation_on_error!(path)
return if path.nil?
return unless path.directory?
ignore_interrupts do
FileUtils.rm_r(path)
path.parent.rmdir_if_possible
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/bottle.rb | Library/Homebrew/bottle.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
class Bottle
include Downloadable
class Filename
attr_reader :name, :version, :tag, :rebuild
sig { params(formula: Formula, tag: Utils::Bottles::Tag, rebuild: Integer).returns(T.attached_class) }
def self.create(formula, tag, rebuild)
new(formula.name, formula.pkg_version, tag, rebuild)
end
sig { params(name: String, version: PkgVersion, tag: Utils::Bottles::Tag, rebuild: Integer).void }
def initialize(name, version, tag, rebuild)
@name = File.basename name
raise ArgumentError, "Invalid bottle name" unless Utils.safe_filename?(@name)
raise ArgumentError, "Invalid bottle version" unless Utils.safe_filename?(version.to_s)
@version = version
@tag = tag.to_unstandardized_sym.to_s
@rebuild = rebuild
end
sig { returns(String) }
def to_str
"#{name}--#{version}#{extname}"
end
sig { returns(String) }
def to_s = to_str
sig { returns(String) }
def json
"#{name}--#{version}.#{tag}.bottle.json"
end
def url_encode
ERB::Util.url_encode("#{name}-#{version}#{extname}")
end
def github_packages
"#{name}--#{version}#{extname}"
end
sig { returns(String) }
def extname
s = rebuild.positive? ? ".#{rebuild}" : ""
".#{tag}.bottle#{s}.tar.gz"
end
end
extend Forwardable
attr_reader :name, :resource, :tag, :cellar, :rebuild
def_delegators :resource, :url, :verify_download_integrity
def_delegators :resource, :cached_download, :downloader
def initialize(formula, spec, tag = nil)
super()
@name = formula.name
@resource = Resource.new
@resource.owner = formula
@spec = spec
tag_spec = spec.tag_specification_for(Utils::Bottles.tag(tag))
@tag = tag_spec.tag
@cellar = tag_spec.cellar
@rebuild = spec.rebuild
@resource.version(formula.pkg_version.to_s)
@resource.checksum = tag_spec.checksum
@fetch_tab_retried = false
root_url(spec.root_url, spec.root_url_specs)
end
sig {
override.params(
verify_download_integrity: T::Boolean,
timeout: T.nilable(T.any(Integer, Float)),
quiet: T.nilable(T::Boolean),
).returns(Pathname)
}
def fetch(verify_download_integrity: true, timeout: nil, quiet: false)
resource.fetch(verify_download_integrity:, timeout:, quiet:)
rescue DownloadError
raise unless fallback_on_error?
fetch_tab
retry
end
sig { override.returns(T.nilable(Integer)) }
def total_size
bottle_size || super
end
sig { override.void }
def clear_cache
@resource.clear_cache
github_packages_manifest_resource&.clear_cache
@fetch_tab_retried = false
end
def compatible_locations?
@spec.compatible_locations?(tag: @tag)
end
# Does the bottle need to be relocated?
def skip_relocation?
@spec.skip_relocation?(tag: @tag)
end
def stage = downloader.stage
def fetch_tab(timeout: nil, quiet: false)
return unless (resource = github_packages_manifest_resource)
begin
resource.fetch(timeout:, quiet:)
rescue DownloadError
raise unless fallback_on_error?
retry
rescue Resource::BottleManifest::Error
raise if @fetch_tab_retried
@fetch_tab_retried = true
resource.clear_cache
retry
end
end
def tab_attributes
if (resource = github_packages_manifest_resource) && resource.downloaded?
return resource.tab
end
{}
end
sig { returns(T.nilable(Integer)) }
def bottle_size
resource = github_packages_manifest_resource
return unless resource&.downloaded?
resource.bottle_size
end
sig { returns(T.nilable(Integer)) }
def installed_size
resource = github_packages_manifest_resource
return unless resource&.downloaded?
resource.installed_size
end
sig { returns(Filename) }
def filename
Filename.create(resource.owner, @tag, @spec.rebuild)
end
sig { returns(T.nilable(Resource::BottleManifest)) }
def github_packages_manifest_resource
return if @resource.download_strategy != CurlGitHubPackagesDownloadStrategy
@github_packages_manifest_resource ||= begin
resource = Resource::BottleManifest.new(self)
version_rebuild = GitHubPackages.version_rebuild(@resource.version, rebuild)
resource.version(version_rebuild)
image_name = GitHubPackages.image_formula_name(@name)
image_tag = GitHubPackages.image_version_rebuild(version_rebuild)
resource.url(
"#{root_url}/#{image_name}/manifests/#{image_tag}",
using: CurlGitHubPackagesDownloadStrategy,
headers: ["Accept: application/vnd.oci.image.index.v1+json"],
)
T.cast(resource.downloader, CurlGitHubPackagesDownloadStrategy).resolved_basename =
"#{name}-#{version_rebuild}.bottle_manifest.json"
resource
end
end
sig { override.returns(String) }
def download_queue_type = "Bottle"
sig { override.returns(String) }
def download_queue_name = "#{name} (#{resource.version})"
private
def select_download_strategy(specs)
specs[:using] ||= DownloadStrategyDetector.detect(@root_url)
specs[:bottle] = true
specs
end
def fallback_on_error?
# Use the default bottle domain as a fallback mirror
if @resource.url.start_with?(Homebrew::EnvConfig.bottle_domain) &&
Homebrew::EnvConfig.bottle_domain != HOMEBREW_BOTTLE_DEFAULT_DOMAIN
opoo "Bottle missing, falling back to the default domain..."
root_url(HOMEBREW_BOTTLE_DEFAULT_DOMAIN)
@github_packages_manifest_resource = nil
true
else
false
end
end
def root_url(val = nil, specs = {})
return @root_url if val.nil?
@root_url = val
filename = Filename.create(resource.owner, @tag, @spec.rebuild)
path, resolved_basename = Utils::Bottles.path_resolved_basename(val, name, resource.checksum, filename)
@resource.url("#{val}/#{path}", **select_download_strategy(specs))
@resource.downloader.resolved_basename = resolved_basename if resolved_basename.present?
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/locale.rb | Library/Homebrew/locale.rb | # typed: strict
# frozen_string_literal: true
# Representation of a system locale.
#
# Used to compare the system language and languages defined using the cask `language` stanza.
class Locale
# Error when a string cannot be parsed to a `Locale`.
class ParserError < StandardError
end
# ISO 639-1 or ISO 639-2
LANGUAGE_REGEX = /(?:[a-z]{2,3})/
private_constant :LANGUAGE_REGEX
# ISO 15924
SCRIPT_REGEX = /(?:[A-Z][a-z]{3})/
private_constant :SCRIPT_REGEX
# ISO 3166-1 or UN M.49
REGION_REGEX = /(?:[A-Z]{2}|\d{3})/
private_constant :REGION_REGEX
LOCALE_REGEX = /\A((?:#{LANGUAGE_REGEX}|#{REGION_REGEX}|#{SCRIPT_REGEX})(?:-|$)){1,3}\Z/
private_constant :LOCALE_REGEX
sig { params(string: String).returns(T.attached_class) }
def self.parse(string)
if (locale = try_parse(string))
return locale
end
raise ParserError, "'#{string}' cannot be parsed to a #{self}"
end
sig { params(string: String).returns(T.nilable(T.attached_class)) }
def self.try_parse(string)
return if string.blank?
scanner = StringScanner.new(string)
if (language = scanner.scan(LANGUAGE_REGEX))
sep = scanner.scan("-")
return if (sep && scanner.eos?) || (sep.nil? && !scanner.eos?)
end
if (script = scanner.scan(SCRIPT_REGEX))
sep = scanner.scan("-")
return if (sep && scanner.eos?) || (sep.nil? && !scanner.eos?)
end
region = scanner.scan(REGION_REGEX)
return unless scanner.eos?
new(language, script, region)
end
sig { returns(T.nilable(String)) }
attr_reader :language
sig { returns(T.nilable(String)) }
attr_reader :script
sig { returns(T.nilable(String)) }
attr_reader :region
sig { params(language: T.nilable(String), script: T.nilable(String), region: T.nilable(String)).void }
def initialize(language, script, region)
raise ArgumentError, "#{self.class} cannot be empty" if language.nil? && region.nil? && script.nil?
unless language.nil?
regex = LANGUAGE_REGEX
raise ParserError, "'language' does not match #{regex}" unless language.match?(regex)
@language = T.let(language, T.nilable(String))
end
unless script.nil?
regex = SCRIPT_REGEX
raise ParserError, "'script' does not match #{regex}" unless script.match?(regex)
@script = T.let(script, T.nilable(String))
end
return if region.nil?
regex = REGION_REGEX
raise ParserError, "'region' does not match #{regex}" unless region.match?(regex)
@region = T.let(region, T.nilable(String))
end
sig { params(other: T.any(String, Locale)).returns(T::Boolean) }
def include?(other)
unless other.is_a?(self.class)
other = self.class.try_parse(other)
return false if other.nil?
end
[:language, :script, :region].all? do |var|
next true if other.public_send(var).nil?
public_send(var) == other.public_send(var)
end
end
sig { params(other: T.any(String, Locale)).returns(T::Boolean) }
def eql?(other)
unless other.is_a?(self.class)
other = self.class.try_parse(other)
return false if other.nil?
end
[:language, :script, :region].all? do |var|
public_send(var) == other.public_send(var)
end
end
alias == eql?
sig {
params(
locale_groups: T::Enumerable[T::Enumerable[T.any(String, Locale)]],
).returns(
T.nilable(T::Enumerable[T.any(String, Locale)]),
)
}
def detect(locale_groups)
locale_groups.find { |locales| locales.any? { |locale| eql?(locale) } } ||
locale_groups.find { |locales| locales.any? { |locale| include?(locale) } }
end
sig { returns(String) }
def to_s
[@language, @script, @region].compact.join("-")
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/rubocops.rb | Library/Homebrew/rubocops.rb | # typed: strict
# frozen_string_literal: true
require_relative "standalone"
require "rubocops/all"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/upgrade.rb | Library/Homebrew/upgrade.rb | # typed: strict
# frozen_string_literal: true
require "reinstall"
require "formula_installer"
require "development_tools"
require "messages"
require "cleanup"
require "utils/topological_hash"
require "utils/output"
module Homebrew
# Helper functions for upgrading formulae.
module Upgrade
extend Utils::Output::Mixin
class Dependents < T::Struct
const :upgradeable, T::Array[Formula]
const :pinned, T::Array[Formula]
const :skipped, T::Array[Formula]
end
class << self
sig {
params(
formulae_to_install: T::Array[Formula], flags: T::Array[String], dry_run: T::Boolean,
force_bottle: T::Boolean, build_from_source_formulae: T::Array[String],
dependents: T::Boolean, interactive: T::Boolean, keep_tmp: T::Boolean,
debug_symbols: T::Boolean, force: T::Boolean, overwrite: T::Boolean,
debug: T::Boolean, quiet: T::Boolean, verbose: T::Boolean
).returns(T::Array[FormulaInstaller])
}
def formula_installers(
formulae_to_install,
flags:,
dry_run: false,
force_bottle: false,
build_from_source_formulae: [],
dependents: false,
interactive: false,
keep_tmp: false,
debug_symbols: false,
force: false,
overwrite: false,
debug: false,
quiet: false,
verbose: false
)
return [] if formulae_to_install.empty?
# Sort keg-only before non-keg-only formulae to avoid any needless conflicts
# with outdated, non-keg-only versions of formulae being upgraded.
formulae_to_install.sort! do |a, b|
if !a.keg_only? && b.keg_only?
1
elsif a.keg_only? && !b.keg_only?
-1
else
0
end
end
dependency_graph = Utils::TopologicalHash.graph_package_dependencies(formulae_to_install)
begin
formulae_to_install = dependency_graph.tsort & formulae_to_install
rescue TSort::Cyclic
if Homebrew::EnvConfig.developer?
raise CyclicDependencyError, dependency_graph.strongly_connected_components
end
end
formulae_to_install.filter_map do |formula|
Migrator.migrate_if_needed(formula, force:, dry_run:)
begin
fi = create_formula_installer(
formula,
flags:,
force_bottle:,
build_from_source_formulae:,
interactive:,
keep_tmp:,
debug_symbols:,
force:,
overwrite:,
debug:,
quiet:,
verbose:,
)
fi.fetch_bottle_tab(quiet: !debug)
all_runtime_deps_installed = fi.bottle_tab_runtime_dependencies.presence&.all? do |dependency, hash|
minimum_version = if (version = hash["version"])
Version.new(version)
end
Dependency.new(dependency).installed?(minimum_version:, minimum_revision: hash["revision"].to_i)
end
if !dry_run && dependents && all_runtime_deps_installed
# Don't need to install this bottle if all of the runtime
# dependencies have the same or newer version already installed.
next
end
fi
rescue CannotInstallFormulaError => e
ofail e
nil
rescue UnsatisfiedRequirements, DownloadError => e
ofail "#{formula}: #{e}"
nil
end
end
end
sig { params(formula_installers: T::Array[FormulaInstaller], dry_run: T::Boolean, verbose: T::Boolean).void }
def upgrade_formulae(formula_installers, dry_run: false, verbose: false)
valid_formula_installers = if dry_run
formula_installers
else
Install.fetch_formulae(formula_installers)
end
valid_formula_installers.each do |fi|
upgrade_formula(fi, dry_run:, verbose:)
Cleanup.install_formula_clean!(fi.formula, dry_run:)
end
end
sig { params(formula: Formula).returns(T::Array[Keg]) }
def outdated_kegs(formula)
[formula, *formula.old_installed_formulae].map(&:linked_keg)
.select(&:directory?)
.map { |k| Keg.new(k.resolved_path) }
end
sig { params(formula: Formula, fi_options: Options).void }
def print_upgrade_message(formula, fi_options)
version_upgrade = if formula.optlinked?
"#{Keg.new(formula.opt_prefix).version} -> #{formula.pkg_version}"
else
"-> #{formula.pkg_version}"
end
oh1 "Upgrading #{Formatter.identifier(formula.full_specified_name)}"
puts " #{version_upgrade} #{fi_options.to_a.join(" ")}"
end
sig {
params(
formulae: T::Array[Formula], flags: T::Array[String], dry_run: T::Boolean,
ask: T::Boolean, installed_on_request: T::Boolean, force_bottle: T::Boolean,
build_from_source_formulae: T::Array[String], interactive: T::Boolean,
keep_tmp: T::Boolean, debug_symbols: T::Boolean, force: T::Boolean,
debug: T::Boolean, quiet: T::Boolean, verbose: T::Boolean
).returns(Dependents)
}
def dependants(
formulae,
flags:,
dry_run: false,
ask: false,
installed_on_request: false,
force_bottle: false,
build_from_source_formulae: [],
interactive: false,
keep_tmp: false,
debug_symbols: false,
force: false,
debug: false,
quiet: false,
verbose: false
)
no_dependents = Dependents.new(upgradeable: [], pinned: [], skipped: [])
if Homebrew::EnvConfig.no_installed_dependents_check?
unless Homebrew::EnvConfig.no_env_hints?
opoo <<~EOS
`$HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK` is set: not checking for outdated
dependents or dependents with broken linkage!
EOS
end
return no_dependents
end
formulae_to_install = formulae.reject { |f| f.core_formula? && f.versioned_formula? }
return no_dependents if formulae_to_install.empty?
# TODO: this should be refactored to use FormulaInstaller new logic
outdated = formulae_to_install.flat_map(&:runtime_installed_formula_dependents)
.uniq
.select(&:outdated?)
# Ensure we never attempt a source build for outdated dependents of upgraded formulae.
outdated, skipped = outdated.partition do |dependent|
dependent.bottled? && dependent.deps.map(&:to_formula).all?(&:bottled?)
end
return no_dependents if outdated.blank?
outdated -= formulae_to_install if dry_run
upgradeable = outdated.reject(&:pinned?)
.sort { |a, b| depends_on(a, b) }
pinned = outdated.select(&:pinned?)
.sort { |a, b| depends_on(a, b) }
Dependents.new(upgradeable:, pinned:, skipped:)
end
sig {
params(deps: Dependents, formulae: T::Array[Formula], flags: T::Array[String],
dry_run: T::Boolean, installed_on_request: T::Boolean, force_bottle: T::Boolean,
build_from_source_formulae: T::Array[String], interactive: T::Boolean, keep_tmp: T::Boolean,
debug_symbols: T::Boolean, force: T::Boolean, debug: T::Boolean, quiet: T::Boolean,
verbose: T::Boolean).void
}
def upgrade_dependents(deps, formulae,
flags:,
dry_run: false,
installed_on_request: false,
force_bottle: false,
build_from_source_formulae: [],
interactive: false,
keep_tmp: false,
debug_symbols: false,
force: false,
debug: false,
quiet: false,
verbose: false)
return if deps.blank?
upgradeable = deps.upgradeable
pinned = deps.pinned
skipped = deps.skipped
if pinned.present?
plural = Utils.pluralize("dependent", pinned.count)
opoo "Not upgrading #{pinned.count} pinned #{plural}:"
puts(pinned.map do |f|
"#{f.full_specified_name} #{f.pkg_version}"
end.join(", "))
end
if skipped.present?
opoo <<~EOS
The following dependents of upgraded formulae are outdated but will not
be upgraded because they are not bottled:
#{skipped * "\n "}
EOS
end
upgradeable.reject! { |f| FormulaInstaller.installed.include?(f) }
# Print the upgradable dependents.
if upgradeable.present?
installed_formulae = (dry_run ? formulae : FormulaInstaller.installed.to_a).dup
formula_plural = Utils.pluralize("formula", installed_formulae.count)
upgrade_verb = dry_run ? "Would upgrade" : "Upgrading"
ohai "#{upgrade_verb} #{Utils.pluralize("dependent", upgradeable.count,
include_count: true)} of upgraded #{formula_plural}:"
puts_no_installed_dependents_check_disable_message_if_not_already!
formulae_upgrades = upgradeable.map do |f|
name = f.full_specified_name
if f.optlinked?
"#{name} #{Keg.new(f.opt_prefix).version} -> #{f.pkg_version}"
else
"#{name} #{f.pkg_version}"
end
end
puts formulae_upgrades.join(", ")
end
return if upgradeable.blank?
unless dry_run
dependent_installers = formula_installers(
upgradeable,
flags:,
force_bottle:,
build_from_source_formulae:,
dependents: true,
interactive:,
keep_tmp:,
debug_symbols:,
force:,
debug:,
quiet:,
verbose:,
)
upgrade_formulae(dependent_installers, dry_run:, verbose:)
end
# Update non-core installed formulae for linkage checks after upgrading
# Don't need to check core formulae because we do so at CI time.
installed_non_core_formulae = FormulaInstaller.installed.to_a.reject(&:core_formula?)
return if installed_non_core_formulae.blank?
# Assess the dependents tree again now we've upgraded.
unless dry_run
oh1 "Checking for dependents of upgraded formulae..."
puts_no_installed_dependents_check_disable_message_if_not_already!
end
broken_dependents = check_broken_dependents(installed_non_core_formulae)
if broken_dependents.blank?
if dry_run
ohai "No currently broken dependents found!"
opoo "If they are broken by the upgrade they will also be upgraded or reinstalled."
else
ohai "No broken dependents found!"
end
return
end
reinstallable_broken_dependents =
broken_dependents.reject(&:outdated?)
.reject(&:pinned?)
.sort { |a, b| depends_on(a, b) }
outdated_pinned_broken_dependents =
broken_dependents.select(&:outdated?)
.select(&:pinned?)
.sort { |a, b| depends_on(a, b) }
# Print the pinned dependents.
if outdated_pinned_broken_dependents.present?
count = outdated_pinned_broken_dependents.count
plural = Utils.pluralize("dependent", outdated_pinned_broken_dependents.count)
onoe "Not reinstalling #{count} broken and outdated, but pinned #{plural}:"
$stderr.puts(outdated_pinned_broken_dependents.map do |f|
"#{f.full_specified_name} #{f.pkg_version}"
end.join(", "))
end
# Print the broken dependents.
if reinstallable_broken_dependents.blank?
ohai "No broken dependents to reinstall!"
else
ohai "Reinstalling #{Utils.pluralize("dependent", reinstallable_broken_dependents.count,
include_count: true)} with broken linkage from source:"
puts_no_installed_dependents_check_disable_message_if_not_already!
puts reinstallable_broken_dependents.map(&:full_specified_name)
.join(", ")
end
return if dry_run
reinstall_contexts = reinstallable_broken_dependents.map do |formula|
Reinstall.build_install_context(
formula,
flags:,
force_bottle:,
build_from_source_formulae: build_from_source_formulae + [formula.full_name],
interactive:,
keep_tmp:,
debug_symbols:,
force:,
debug:,
quiet:,
verbose:,
)
end
valid_formula_installers = Install.fetch_formulae(reinstall_contexts.map(&:formula_installer))
reinstall_contexts.each do |reinstall_context|
next unless valid_formula_installers.include?(reinstall_context.formula_installer)
Reinstall.reinstall_formula(reinstall_context)
rescue FormulaInstallationAlreadyAttemptedError
# We already attempted to reinstall f as part of the dependency tree of
# another formula. In that case, don't generate an error, just move on.
nil
rescue CannotInstallFormulaError, DownloadError => e
ofail e
rescue BuildError => e
e.dump(verbose:)
puts
Homebrew.failed = true
end
end
private
sig { params(formula_installer: FormulaInstaller, dry_run: T::Boolean, verbose: T::Boolean).void }
def upgrade_formula(formula_installer, dry_run: false, verbose: false)
formula = formula_installer.formula
if dry_run
Install.print_dry_run_dependencies(formula, formula_installer.compute_dependencies) do |f|
name = f.full_specified_name
if f.optlinked?
"#{name} #{Keg.new(f.opt_prefix).version} -> #{f.pkg_version}"
else
"#{name} #{f.pkg_version}"
end
end
return
end
Install.install_formula(formula_installer, upgrade: true)
rescue BuildError => e
e.dump(verbose:)
puts
Homebrew.failed = true
end
sig { params(installed_formulae: T::Array[Formula]).returns(T::Array[Formula]) }
def check_broken_dependents(installed_formulae)
CacheStoreDatabase.use(:linkage) do |db|
installed_formulae.flat_map(&:runtime_installed_formula_dependents)
.uniq
.select do |f|
keg = f.any_installed_keg
next unless keg
next unless keg.directory?
LinkageChecker.new(keg, cache_db: db)
.broken_library_linkage?
end.compact
end
end
sig { void }
def puts_no_installed_dependents_check_disable_message_if_not_already!
return if Homebrew::EnvConfig.no_env_hints?
return if Homebrew::EnvConfig.no_installed_dependents_check?
return if @puts_no_installed_dependents_check_disable_message_if_not_already
puts "Disable this behaviour by setting `HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1`."
puts "Hide these hints with `HOMEBREW_NO_ENV_HINTS=1` (see `man brew`)."
@puts_no_installed_dependents_check_disable_message_if_not_already = T.let(true, T.nilable(T::Boolean))
end
sig {
params(formula: Formula, flags: T::Array[String], force_bottle: T::Boolean,
build_from_source_formulae: T::Array[String], interactive: T::Boolean,
keep_tmp: T::Boolean, debug_symbols: T::Boolean, force: T::Boolean,
overwrite: T::Boolean, debug: T::Boolean, quiet: T::Boolean, verbose: T::Boolean).returns(FormulaInstaller)
}
def create_formula_installer(
formula,
flags:,
force_bottle: false,
build_from_source_formulae: [],
interactive: false,
keep_tmp: false,
debug_symbols: false,
force: false,
overwrite: false,
debug: false,
quiet: false,
verbose: false
)
keg = if formula.optlinked?
Keg.new(formula.opt_prefix.resolved_path)
else
formula.installed_kegs.find(&:optlinked?)
end
if keg
tab = keg.tab
link_keg = keg.linked?
installed_as_dependency = tab.installed_as_dependency == true
installed_on_request = tab.installed_on_request == true
build_bottle = tab.built_bottle?
else
link_keg = nil
installed_as_dependency = false
installed_on_request = true
build_bottle = false
end
build_options = BuildOptions.new(Options.create(flags), formula.options)
options = build_options.used_options
options |= formula.build.used_options
options &= formula.options
FormulaInstaller.new(
formula,
**{
options:,
link_keg:,
installed_as_dependency:,
installed_on_request:,
build_bottle:,
force_bottle:,
build_from_source_formulae:,
interactive:,
keep_tmp:,
debug_symbols:,
force:,
overwrite:,
debug:,
quiet:,
verbose:,
}.compact,
)
end
sig { params(one: Formula, two: Formula).returns(Integer) }
def depends_on(one, two)
if one.any_installed_keg
&.runtime_dependencies
&.any? { |dependency| dependency["full_name"] == two.full_name }
1
else
T.must(one <=> two)
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/diagnostic.rb | Library/Homebrew/diagnostic.rb | # typed: strict
# frozen_string_literal: true
require "keg"
require "language/python"
require "formula"
require "formulary"
require "version"
require "development_tools"
require "utils/shell"
require "utils/output"
require "system_config"
require "cask/caskroom"
require "cask/quarantine"
require "system_command"
module Homebrew
# Module containing diagnostic checks.
module Diagnostic
extend Utils::Output::Mixin
sig {
params(formulae: T::Array[Formula], hide: T::Array[String], _block: T.nilable(
T.proc.params(formula_name: String, missing_dependencies: T::Array[Dependency]).void,
)).returns(T::Hash[String, T::Array[String]])
}
def self.missing_deps(formulae, hide = [], &_block)
missing = {}
formulae.each do |f|
missing_dependencies = f.missing_dependencies(hide: hide)
next if missing_dependencies.empty?
yield f.full_name, missing_dependencies if block_given?
missing[f.full_name] = missing_dependencies
end
missing
end
sig { params(type: Symbol, fatal: T::Boolean).void }
def self.checks(type, fatal: true)
@checks ||= T.let(Checks.new, T.nilable(Checks))
failed = T.let(false, T::Boolean)
@checks.public_send(type).each do |check|
out = @checks.public_send(check)
next if out.nil?
if fatal
failed ||= true
ofail out
else
opoo out
end
end
exit 1 if failed && fatal
end
# Diagnostic checks.
class Checks
include SystemCommand::Mixin
include Utils::Output::Mixin
sig { params(verbose: T::Boolean).void }
def initialize(verbose: true)
@verbose = verbose
@found = T.let([], T::Array[String])
@seen_prefix_bin = T.let(false, T::Boolean)
@seen_prefix_sbin = T.let(false, T::Boolean)
@user_path_1_done = T.let(false, T::Boolean)
@non_core_taps = T.let([], T.nilable(T::Array[Tap]))
end
############# @!group HELPERS
# Finds files in `HOMEBREW_PREFIX` *and* /usr/local.
# Specify paths relative to a prefix, e.g. "include/foo.h".
# Sets @found for your convenience.
sig { params(relative_paths: T.any(String, T::Array[String])).void }
def find_relative_paths(*relative_paths)
@found = [HOMEBREW_PREFIX, "/usr/local"].uniq.reduce([]) do |found, prefix|
found + relative_paths.map { |f| File.join(prefix, f) }.select { |f| File.exist? f }
end
end
sig { params(list: T::Array[T.any(Formula, Pathname, String)], string: String).returns(String) }
def inject_file_list(list, string)
list.reduce(string.dup) { |acc, elem| acc << " #{elem}\n" }
.freeze
end
sig { params(path: String).returns(String) }
def user_tilde(path)
home = Dir.home
if path == home
"~"
else
path.gsub(%r{^#{home}/}, "~/")
end
end
sig { returns(T.nilable(String)) }
def none_string
"<NONE>"
end
sig { params(args: T.anything).void }
def add_info(*args)
ohai(*args) if @verbose
end
############# @!endgroup END HELPERS
sig { returns(T::Array[String]) }
def fatal_preinstall_checks
%w[
check_access_directories
].freeze
end
sig { returns(T::Array[String]) }
def fatal_build_from_source_checks
%w[
check_for_installed_developer_tools
].freeze
end
sig { returns(T::Array[String]) }
def fatal_setup_build_environment_checks
[].freeze
end
sig { returns(T::Array[String]) }
def supported_configuration_checks
[].freeze
end
sig { returns(T::Array[String]) }
def build_from_source_checks
[].freeze
end
sig { returns(T::Array[String]) }
def build_error_checks
supported_configuration_checks + build_from_source_checks
end
sig { params(tier: T.any(Integer, String, Symbol)).returns(T.nilable(String)) }
def support_tier_message(tier:)
return if tier.to_s == "1"
tier_title, tier_slug, tier_issues = if tier.to_s == "unsupported"
["Unsupported", "unsupported", "Do not report any"]
else
["Tier #{tier}", "tier-#{tier.to_s.downcase}", "You can report Tier #{tier} unrelated"]
end
<<~EOS
This is a #{tier_title} configuration:
#{Formatter.url("https://docs.brew.sh/Support-Tiers##{tier_slug}")}
#{Formatter.bold("#{tier_issues} issues to Homebrew/* repositories!")}
Read the above document before opening any issues or PRs.
EOS
end
sig { params(repository_path: GitRepository, desired_origin: String).returns(T.nilable(String)) }
def examine_git_origin(repository_path, desired_origin)
return if !Utils::Git.available? || !repository_path.git_repository?
current_origin = repository_path.origin_url
if current_origin.nil?
<<~EOS
Missing #{desired_origin} git origin remote.
Without a correctly configured origin, Homebrew won't update
properly. You can solve this by adding the remote:
git -C "#{repository_path}" remote add origin #{Formatter.url(desired_origin)}
EOS
elsif !current_origin.match?(%r{#{desired_origin}(\.git|/)?$}i)
<<~EOS
Suspicious #{desired_origin} git origin remote found.
The current git origin is:
#{current_origin}
With a non-standard origin, Homebrew won't update properly.
You can solve this by setting the origin remote:
git -C "#{repository_path}" remote set-url origin #{Formatter.url(desired_origin)}
EOS
end
end
sig { params(tap: Tap).returns(T.nilable(String)) }
def broken_tap(tap)
return unless Utils::Git.available?
repo = GitRepository.new(HOMEBREW_REPOSITORY)
return unless repo.git_repository?
message = <<~EOS
#{tap.full_name} was not tapped properly! Run:
rm -rf "#{tap.path}"
brew tap #{tap.name}
EOS
return message if tap.remote.blank?
tap_head = tap.git_head
return message if tap_head.blank?
return if tap_head != repo.head_ref
message
end
sig { returns(T.nilable(String)) }
def check_for_installed_developer_tools
return if DevelopmentTools.installed?
<<~EOS
No developer tools installed.
#{DevelopmentTools.installation_instructions}
EOS
end
sig { params(dir: String, pattern: String, allow_list: T::Array[String], message: String).returns(T.nilable(String)) }
def __check_stray_files(dir, pattern, allow_list, message)
return unless File.directory?(dir)
files = Dir.chdir(dir) do
(Dir.glob(pattern) - Dir.glob(allow_list))
.select { |f| File.file?(f) && !File.symlink?(f) }
.map do |f|
f.sub!(%r{/.*}, "/*") unless @verbose
File.join(dir, f)
end
.sort.uniq
end
return if files.empty?
inject_file_list(files, message)
end
sig { returns(T.nilable(String)) }
def check_for_stray_dylibs
# Dylibs which are generally OK should be added to this list,
# with a short description of the software they come with.
allow_list = [
"libfuse.2.dylib", # MacFuse
"libfuse3.*.dylib", # MacFuse
"libfuse_ino64.2.dylib", # MacFuse
"libmacfuse_i32.2.dylib", # OSXFuse MacFuse compatibility layer
"libmacfuse_i64.2.dylib", # OSXFuse MacFuse compatibility layer
"libosxfuse_i32.2.dylib", # OSXFuse
"libosxfuse_i64.2.dylib", # OSXFuse
"libosxfuse.2.dylib", # OSXFuse
"libTrAPI.dylib", # TrAPI/Endpoint Security VPN
"libntfs-3g.*.dylib", # NTFS-3G
"libntfs.*.dylib", # NTFS-3G
"libublio.*.dylib", # NTFS-3G
"libUFSDNTFS.dylib", # Paragon NTFS
"libUFSDExtFS.dylib", # Paragon ExtFS
"libecomlodr.dylib", # Symantec Endpoint Protection
"libsymsea*.dylib", # Symantec Endpoint Protection
"sentinel.dylib", # SentinelOne
"sentinel-*.dylib", # SentinelOne
]
__check_stray_files "/usr/local/lib", "*.dylib", allow_list, <<~EOS
Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae and may need to be deleted.
Unexpected dylibs:
EOS
end
sig { returns(T.nilable(String)) }
def check_for_stray_static_libs
# Static libs which are generally OK should be added to this list,
# with a short description of the software they come with.
allow_list = [
"libntfs-3g.a", # NTFS-3G
"libntfs.a", # NTFS-3G
"libublio.a", # NTFS-3G
"libappfirewall.a", # Symantec Endpoint Protection
"libautoblock.a", # Symantec Endpoint Protection
"libautosetup.a", # Symantec Endpoint Protection
"libconnectionsclient.a", # Symantec Endpoint Protection
"liblocationawareness.a", # Symantec Endpoint Protection
"libpersonalfirewall.a", # Symantec Endpoint Protection
"libtrustedcomponents.a", # Symantec Endpoint Protection
]
__check_stray_files "/usr/local/lib", "*.a", allow_list, <<~EOS
Unbrewed static libraries were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae and may need to be deleted.
Unexpected static libraries:
EOS
end
sig { returns(T.nilable(String)) }
def check_for_stray_pcs
# Package-config files which are generally OK should be added to this list,
# with a short description of the software they come with.
allow_list = [
"fuse.pc", # OSXFuse/MacFuse
"fuse3.pc", # OSXFuse/MacFuse
"macfuse.pc", # OSXFuse MacFuse compatibility layer
"osxfuse.pc", # OSXFuse
"libntfs-3g.pc", # NTFS-3G
"libublio.pc", # NTFS-3G
]
__check_stray_files "/usr/local/lib/pkgconfig", "*.pc", allow_list, <<~EOS
Unbrewed '.pc' files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae and may need to be deleted.
Unexpected '.pc' files:
EOS
end
sig { returns(T.nilable(String)) }
def check_for_stray_las
allow_list = [
"libfuse.la", # MacFuse
"libfuse_ino64.la", # MacFuse
"libosxfuse_i32.la", # OSXFuse
"libosxfuse_i64.la", # OSXFuse
"libosxfuse.la", # OSXFuse
"libntfs-3g.la", # NTFS-3G
"libntfs.la", # NTFS-3G
"libublio.la", # NTFS-3G
]
__check_stray_files "/usr/local/lib", "*.la", allow_list, <<~EOS
Unbrewed '.la' files were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae and may need to be deleted.
Unexpected '.la' files:
EOS
end
sig { returns(T.nilable(String)) }
def check_for_stray_headers
allow_list = [
"fuse.h", # MacFuse
"fuse/**/*.h", # MacFuse
"fuse3/**/*.h", # MacFuse
"macfuse/**/*.h", # OSXFuse MacFuse compatibility layer
"osxfuse/**/*.h", # OSXFuse
"ntfs/**/*.h", # NTFS-3G
"ntfs-3g/**/*.h", # NTFS-3G
]
__check_stray_files "/usr/local/include", "**/*.h", allow_list, <<~EOS
Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae and may need to be deleted.
Unexpected header files:
EOS
end
sig { returns(T.nilable(String)) }
def check_for_broken_symlinks
broken_symlinks = []
Keg.must_exist_subdirectories.each do |d|
next unless d.directory?
d.find do |path|
broken_symlinks << path if path.symlink? && !path.resolved_path_exists?
end
end
return if broken_symlinks.empty?
inject_file_list broken_symlinks, <<~EOS
Broken symlinks were found. Remove them with `brew cleanup`:
EOS
end
sig { returns(T.nilable(String)) }
def check_tmpdir_sticky_bit
world_writable = HOMEBREW_TEMP.stat.mode & 0777 == 0777
return if !world_writable || HOMEBREW_TEMP.sticky?
<<~EOS
#{HOMEBREW_TEMP} is world-writable but does not have the sticky bit set.
To set it, run the following command:
sudo chmod +t #{HOMEBREW_TEMP}
EOS
end
sig { returns(T.nilable(String)) }
def check_exist_directories
return if HOMEBREW_PREFIX.writable?
not_exist_dirs = Keg.must_exist_directories.reject(&:exist?)
return if not_exist_dirs.empty?
<<~EOS
The following directories do not exist:
#{not_exist_dirs.join("\n")}
You should create these directories and change their ownership to your user.
sudo mkdir -p #{not_exist_dirs.join(" ")}
sudo chown -R #{current_user} #{not_exist_dirs.join(" ")}
EOS
end
sig { returns(T.nilable(String)) }
def check_access_directories
not_writable_dirs =
Keg.must_be_writable_directories.select(&:exist?)
.reject(&:writable?)
return if not_writable_dirs.empty?
<<~EOS
The following directories are not writable by your user:
#{not_writable_dirs.join("\n")}
You should change the ownership of these directories to your user.
sudo chown -R #{current_user} #{not_writable_dirs.join(" ")}
And make sure that your user has write permission.
chmod u+w #{not_writable_dirs.join(" ")}
EOS
end
sig { returns(T.nilable(String)) }
def check_multiple_cellars
return if HOMEBREW_PREFIX.to_s == HOMEBREW_REPOSITORY.to_s
return unless (HOMEBREW_REPOSITORY/"Cellar").exist?
return unless (HOMEBREW_PREFIX/"Cellar").exist?
<<~EOS
You have multiple Cellars.
You should delete #{HOMEBREW_REPOSITORY}/Cellar:
rm -rf #{HOMEBREW_REPOSITORY}/Cellar
EOS
end
sig { returns(T.nilable(String)) }
def check_user_path_1
@seen_prefix_bin = false
@seen_prefix_sbin = false
message = ""
paths.each do |p|
case p
when "/usr/bin"
unless @seen_prefix_bin
# only show the doctor message if there are any conflicts
# rationale: a default install should not trigger any brew doctor messages
conflicts = Dir["#{HOMEBREW_PREFIX}/bin/*"]
.map { |fn| File.basename fn }
.select { |bn| File.exist? "/usr/bin/#{bn}" }
unless conflicts.empty?
message = inject_file_list conflicts, <<~EOS
/usr/bin occurs before #{HOMEBREW_PREFIX}/bin in your PATH.
This means that system-provided programs will be used instead of those
provided by Homebrew. Consider setting your PATH so that
#{HOMEBREW_PREFIX}/bin occurs before /usr/bin. Here is a one-liner:
#{Utils::Shell.prepend_path_in_profile("#{HOMEBREW_PREFIX}/bin")}
The following tools exist at both paths:
EOS
end
end
when "#{HOMEBREW_PREFIX}/bin"
@seen_prefix_bin = true
when "#{HOMEBREW_PREFIX}/sbin"
@seen_prefix_sbin = true
end
end
@user_path_1_done = true
message unless message.empty?
end
sig { returns(T.nilable(String)) }
def check_user_path_2
check_user_path_1 unless @user_path_1_done
return if @seen_prefix_bin
<<~EOS
Homebrew's "bin" was not found in your PATH.
Consider setting your PATH for example like so:
#{Utils::Shell.prepend_path_in_profile("#{HOMEBREW_PREFIX}/bin")}
EOS
end
sig { returns(T.nilable(String)) }
def check_user_path_3
check_user_path_1 unless @user_path_1_done
return if @seen_prefix_sbin
# Don't complain about sbin not being in the path if it doesn't exist
sbin = HOMEBREW_PREFIX/"sbin"
return unless sbin.directory?
return if sbin.children.empty?
return if sbin.children.one? && sbin.children.first.basename.to_s == ".keepme"
<<~EOS
Homebrew's "sbin" was not found in your PATH but you have installed
formulae that put executables in #{HOMEBREW_PREFIX}/sbin.
Consider setting your PATH for example like so:
#{Utils::Shell.prepend_path_in_profile("#{HOMEBREW_PREFIX}/sbin")}
EOS
end
sig { returns(T.nilable(String)) }
def check_for_symlinked_cellar
return unless HOMEBREW_CELLAR.exist?
return unless HOMEBREW_CELLAR.symlink?
<<~EOS
Symlinked Cellars can cause problems.
Your Homebrew Cellar is a symlink: #{HOMEBREW_CELLAR}
which resolves to: #{HOMEBREW_CELLAR.realpath}
The recommended Homebrew installations are either:
(A) Have Cellar be a real directory inside of your `$HOMEBREW_PREFIX`
(B) Symlink "bin/brew" into your prefix, but don't symlink "Cellar".
Older installations of Homebrew may have created a symlinked Cellar, but this can
cause problems when two formulae install to locations that are mapped on top of each
other during the linking step.
EOS
end
sig { returns(T.nilable(String)) }
def check_git_version
minimum_version = ENV.fetch("HOMEBREW_MINIMUM_GIT_VERSION")
return unless Utils::Git.available?
return if Utils::Git.version >= Version.new(minimum_version)
git = Formula["git"]
git_upgrade_cmd = git.any_version_installed? ? "upgrade" : "install"
<<~EOS
An outdated version (#{Utils::Git.version}) of Git was detected in your PATH.
Git #{minimum_version} or newer is required for Homebrew.
Please upgrade:
brew #{git_upgrade_cmd} git
EOS
end
sig { returns(T.nilable(String)) }
def check_for_git
return if Utils::Git.available?
<<~EOS
Git could not be found in your PATH.
Homebrew uses Git for several internal functions and some formulae use Git
checkouts instead of stable tarballs. You may want to install Git:
brew install git
EOS
end
sig { returns(T.nilable(String)) }
def check_git_newline_settings
return unless Utils::Git.available?
autocrlf = HOMEBREW_REPOSITORY.cd { `git config --get core.autocrlf`.chomp }
return if autocrlf != "true"
<<~EOS
Suspicious Git newline settings found.
The detected Git newline settings will cause checkout problems:
core.autocrlf = #{autocrlf}
If you are not routinely dealing with Windows-based projects,
consider removing these by running:
git config --global core.autocrlf input
EOS
end
sig { returns(T.nilable(String)) }
def check_brew_git_origin
repo = GitRepository.new(HOMEBREW_REPOSITORY)
examine_git_origin(repo, Homebrew::EnvConfig.brew_git_remote)
end
sig { returns(T.nilable(String)) }
def check_coretap_integrity
core_tap = CoreTap.instance
unless core_tap.installed?
return unless EnvConfig.no_install_from_api?
core_tap.ensure_installed!
end
broken_tap(core_tap) || examine_git_origin(core_tap.git_repository, Homebrew::EnvConfig.core_git_remote)
end
sig { returns(T.nilable(String)) }
def check_casktap_integrity
core_cask_tap = CoreCaskTap.instance
return unless core_cask_tap.installed?
broken_tap(core_cask_tap) || examine_git_origin(core_cask_tap.git_repository, T.must(core_cask_tap.remote))
end
sig { returns(T.nilable(String)) }
def check_tap_git_branch
return if ENV["CI"]
return unless Utils::Git.available?
commands = Tap.installed.filter_map do |tap|
next if tap.git_repository.default_origin_branch?
"git -C $(brew --repo #{tap.name}) checkout #{tap.git_repository.origin_branch_name}"
end
return if commands.blank?
<<~EOS
Some taps are not on the default git origin branch and may not receive
updates. If this is a surprise to you, check out the default branch with:
#{commands.join("\n ")}
EOS
end
sig { returns(T.nilable(String)) }
def check_deprecated_official_taps
tapped_deprecated_taps =
Tap.select(&:official?).map(&:repository) & DEPRECATED_OFFICIAL_TAPS
# TODO: remove this once it's no longer in the default GitHub Actions image
tapped_deprecated_taps -= ["bundle"] if GitHub::Actions.env_set?
return if tapped_deprecated_taps.empty?
<<~EOS
You have the following deprecated, official taps tapped:
Homebrew/homebrew-#{tapped_deprecated_taps.join("\n Homebrew/homebrew-")}
Untap them with `brew untap`.
EOS
end
sig { params(formula: Formula).returns(T::Boolean) }
def __check_linked_brew!(formula)
formula.installed_prefixes.each do |prefix|
prefix.find do |src|
next if src == prefix
dst = HOMEBREW_PREFIX + src.relative_path_from(prefix)
return true if dst.symlink? && src == dst.resolved_path
end
end
false
end
sig { returns(T.nilable(String)) }
def check_for_other_frameworks
# Other frameworks that are known to cause problems when present
frameworks_to_check = %w[
expat.framework
libexpat.framework
libcurl.framework
]
frameworks_found = frameworks_to_check
.map { |framework| "/Library/Frameworks/#{framework}" }
.select { |framework| File.exist? framework }
return if frameworks_found.empty?
inject_file_list frameworks_found, <<~EOS
Some frameworks can be picked up by CMake's build system and will likely
cause the build to fail. To compile CMake, you may wish to move these
out of the way:
EOS
end
sig { returns(T.nilable(String)) }
def check_tmpdir
tmpdir = ENV.fetch("TMPDIR", nil)
return if tmpdir.nil? || File.directory?(tmpdir)
<<~EOS
TMPDIR #{tmpdir.inspect} doesn't exist.
EOS
end
sig { returns(T.nilable(String)) }
def check_missing_deps
return unless HOMEBREW_CELLAR.exist?
missing = Set.new
Homebrew::Diagnostic.missing_deps(Formula.installed).each_value do |deps|
missing.merge(deps)
end
return if missing.empty?
<<~EOS
Some installed formulae are missing dependencies.
You should `brew install` the missing dependencies:
brew install #{missing.map(&:to_installed_formula).sort_by(&:full_name) * " "}
Run `brew missing` for more details.
EOS
end
sig { returns(T.nilable(String)) }
def check_deprecated_disabled
return unless HOMEBREW_CELLAR.exist?
deprecated_or_disabled = Formula.installed.select(&:deprecated?)
deprecated_or_disabled += Formula.installed.select(&:disabled?)
return if deprecated_or_disabled.empty?
<<~EOS
Some installed formulae are deprecated or disabled.
You should find replacements for the following formulae:
#{deprecated_or_disabled.sort_by(&:full_name).uniq * "\n "}
EOS
end
sig { returns(T.nilable(String)) }
def check_cask_deprecated_disabled
deprecated_or_disabled = Cask::Caskroom.casks.select(&:deprecated?)
deprecated_or_disabled += Cask::Caskroom.casks.select(&:disabled?)
return if deprecated_or_disabled.empty?
<<~EOS
Some installed casks are deprecated or disabled.
You should find replacements for the following casks:
#{deprecated_or_disabled.sort_by(&:token).uniq * "\n "}
EOS
end
sig { returns(T.nilable(String)) }
def check_git_status
return unless Utils::Git.available?
message = T.let(nil, T.nilable(String))
repos = {
"Homebrew/brew" => HOMEBREW_REPOSITORY,
"Homebrew/homebrew-core" => CoreTap.instance.path,
"Homebrew/homebrew-cask" => CoreCaskTap.instance.path,
}
repos.each do |name, path|
next unless path.exist?
status = path.cd do
`git status --untracked-files=all --porcelain 2>/dev/null`
end
next if status.blank?
message ||= ""
message += "\n" unless message.empty?
message += <<~EOS
You have uncommitted modifications to #{name}.
If this is a surprise to you, then you should stash these modifications.
Stashing returns Homebrew to a pristine state but can be undone
should you later need to do so for some reason.
git -C "#{path}" stash -u && git -C "#{path}" clean -d -f
EOS
modified = status.split("\n")
message += inject_file_list modified, <<~EOS
Uncommitted files:
EOS
end
message
end
sig { returns(T.nilable(String)) }
def check_for_non_prefixed_coreutils
coreutils = Formula["coreutils"]
return unless coreutils.any_version_installed?
gnubin = %W[#{coreutils.opt_libexec}/gnubin #{coreutils.libexec}/gnubin]
return unless paths.intersect?(gnubin)
<<~EOS
Putting non-prefixed coreutils in your path can cause GMP builds to fail.
EOS
rescue FormulaUnavailableError
nil
end
sig { returns(T.nilable(String)) }
def check_for_pydistutils_cfg_in_home
return unless File.exist? "#{Dir.home}/.pydistutils.cfg"
<<~EOS
A '.pydistutils.cfg' file was found in $HOME, which may cause Python
builds to fail. See:
#{Formatter.url("https://bugs.python.org/issue6138")}
#{Formatter.url("https://bugs.python.org/issue4655")}
EOS
end
sig { returns(T.nilable(String)) }
def check_for_unreadable_installed_formula
formula_unavailable_exceptions = []
Formula.racks.each do |rack|
Formulary.from_rack(rack)
rescue FormulaUnreadableError, FormulaClassUnavailableError,
TapFormulaUnreadableError, TapFormulaClassUnavailableError => e
formula_unavailable_exceptions << e
rescue FormulaUnavailableError, TapFormulaAmbiguityError
nil
end
return if formula_unavailable_exceptions.empty?
<<~EOS
Some installed formulae are not readable:
#{formula_unavailable_exceptions.join("\n\n ")}
EOS
end
sig { returns(T.nilable(String)) }
def check_for_unlinked_but_not_keg_only
unlinked = Formula.racks.reject do |rack|
next true if (HOMEBREW_LINKED_KEGS/rack.basename).directory?
begin
Formulary.from_rack(rack).keg_only?
rescue FormulaUnavailableError, TapFormulaAmbiguityError
false
end
end.map(&:basename)
return if unlinked.empty?
inject_file_list unlinked, <<~EOS
You have unlinked kegs in your Cellar.
Leaving kegs unlinked can lead to build-trouble and cause formulae that depend on
those kegs to fail to run properly once built. Run `brew link` on these:
EOS
end
sig { returns(T.nilable(String)) }
def check_for_external_cmd_name_conflict
cmds = Commands.tap_cmd_directories.flat_map { |p| Dir["#{p}/brew-*"] }.uniq
cmds = cmds.select { |cmd| File.file?(cmd) && File.executable?(cmd) }
cmd_map = {}
cmds.each do |cmd|
cmd_name = File.basename(cmd, ".rb")
cmd_map[cmd_name] ||= []
cmd_map[cmd_name] << cmd
end
cmd_map.reject! { |_cmd_name, cmd_paths| cmd_paths.size == 1 }
return if cmd_map.empty?
if ENV["CI"].present? && cmd_map.keys.length == 1 &&
cmd_map.keys.first == "brew-test-bot"
return
end
message = "You have external commands with conflicting names.\n"
cmd_map.each do |cmd_name, cmd_paths|
message += inject_file_list cmd_paths, <<~EOS
Found command `#{cmd_name}` in the following places:
EOS
end
message
end
sig { returns(T.nilable(String)) }
def check_for_tap_ruby_files_locations
bad_tap_files = {}
Tap.installed.each do |tap|
unused_formula_dirs = tap.potential_formula_dirs - [tap.formula_dir]
unused_formula_dirs.each do |dir|
next unless dir.exist?
dir.children.each do |path|
next if path.extname != ".rb"
bad_tap_files[tap] ||= []
bad_tap_files[tap] << path
end
end
end
return if bad_tap_files.empty?
bad_tap_files.keys.map do |tap|
<<~EOS
Found Ruby file outside #{tap} tap formula directory.
(#{tap.formula_dir}):
#{bad_tap_files[tap].join("\n ")}
EOS
end.join("\n")
end
sig { returns(T.nilable(String)) }
def check_homebrew_prefix
return if Homebrew.default_prefix?
<<~EOS
Your Homebrew's prefix is not #{Homebrew::DEFAULT_PREFIX}.
Most of Homebrew's bottles (binary packages) can only be used with the default prefix.
Consider uninstalling Homebrew and reinstalling into the default prefix.
#{support_tier_message(tier: 3)}
EOS
end
sig { returns(T.nilable(String)) }
def check_deleted_formula
kegs = Keg.all
deleted_formulae = kegs.filter_map do |keg|
tap = keg.tab.tap
tap_keg_name = tap ? "#{tap}/#{keg.name}" : keg.name
loadable = [
Formulary::FromAPILoader,
Formulary::FromTapLoader,
Formulary::FromNameLoader,
].any? do |loader_class|
loader = begin
loader_class.try_new(tap_keg_name, warn: false)
rescue TapFormulaAmbiguityError => e
e.loaders.first
end
loader.instance_of?(Formulary::FromTapLoader) ? loader.path.exist? : loader.present?
end
keg.name unless loadable
end.uniq
return if deleted_formulae.blank?
<<~EOS
Some installed kegs have no formulae!
This means they were either deleted or installed manually.
You should find replacements for the following formulae:
#{deleted_formulae.join("\n ")}
EOS
end
sig { returns(T.nilable(String)) }
def check_for_unnecessary_core_tap
return if Homebrew::EnvConfig.developer?
return if Homebrew::EnvConfig.no_install_from_api?
return if Homebrew::EnvConfig.devcmdrun?
return unless CoreTap.instance.installed?
<<~EOS
You have an unnecessary local Core tap!
This can cause problems installing up-to-date formulae.
Please remove it by running:
brew untap #{CoreTap.instance.name}
EOS
end
sig { returns(T.nilable(String)) }
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/messages.rb | Library/Homebrew/messages.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
# A {Messages} object collects messages that may need to be displayed together
# at the end of a multi-step `brew` command run.
class Messages
include ::Utils::Output::Mixin
sig { returns(T::Array[{ package: String, caveats: T.any(String, Caveats) }]) }
attr_reader :caveats
sig { returns(Integer) }
attr_reader :package_count
sig { returns(T::Array[{ package: String, time: Float }]) }
attr_reader :install_times
sig { void }
def initialize
@caveats = T.let([], T::Array[{ package: String, caveats: T.any(String, Caveats) }])
@completions_and_elisp = T.let(Set.new, T::Set[String])
@package_count = T.let(0, Integer)
@install_times = T.let([], T::Array[{ package: String, time: Float }])
end
sig { params(package: String, caveats: T.any(String, Caveats)).void }
def record_caveats(package, caveats)
@caveats.push(package:, caveats:)
end
sig { params(completions_and_elisp: T::Array[String]).void }
def record_completions_and_elisp(completions_and_elisp)
@completions_and_elisp.merge(completions_and_elisp)
end
sig { params(package: String, elapsed_time: Float).void }
def package_installed(package, elapsed_time)
@package_count += 1
@install_times.push(package:, time: elapsed_time)
end
sig { params(force_caveats: T::Boolean, display_times: T::Boolean).void }
def display_messages(force_caveats: false, display_times: false)
display_caveats(force: force_caveats)
display_install_times if display_times
end
sig { params(force: T::Boolean).void }
def display_caveats(force: false)
return if @package_count.zero?
return if @caveats.empty? && @completions_and_elisp.empty?
oh1 "Caveats" unless @completions_and_elisp.empty?
@completions_and_elisp.each { |c| puts c }
return if @package_count == 1 && !force
oh1 "Caveats" if @completions_and_elisp.empty?
@caveats.each { |c| ohai c.fetch(:package), c.fetch(:caveats) }
end
sig { void }
def display_install_times
return if install_times.empty?
oh1 "Installation times"
install_times.each do |t|
puts format("%<package>-20s %<time>10.3f s", t)
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/official_taps.rb | Library/Homebrew/official_taps.rb | # typed: strict
# frozen_string_literal: true
DEPRECATED_OFFICIAL_TAPS = %w[
aliases
apache
binary
bundle
cask-drivers
cask-eid
cask-fonts
cask-versions
command-not-found
completions
devel-only
dupes
emacs
formula-analytics
fuse
games
gui
head-only
linux-fonts
livecheck
nginx
php
portable-ruby
python
science
services
test-bot
tex
versions
x11
].freeze
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/tap.rb | Library/Homebrew/tap.rb | # typed: strict
# frozen_string_literal: true
require "api"
require "commands"
require "settings"
require "utils/output"
# A {Tap} is used to encapsulate Homebrew formulae, casks and custom commands.
# Usually, it's synced with a remote Git repository. And it's likely
# a GitHub repository with the name of `user/homebrew-repository`. In such
# cases, `user/repository` will be used as the {#name} of this {Tap}, where
# {#user} represents the GitHub username and {#repository} represents the
# repository name without the leading `homebrew-`.
class Tap
extend Cachable
extend Utils::Output::Mixin
include Utils::Output::Mixin
HOMEBREW_TAP_CASK_RENAMES_FILE = "cask_renames.json"
private_constant :HOMEBREW_TAP_CASK_RENAMES_FILE
HOMEBREW_TAP_FORMULA_RENAMES_FILE = "formula_renames.json"
private_constant :HOMEBREW_TAP_FORMULA_RENAMES_FILE
HOMEBREW_TAP_MIGRATIONS_FILE = "tap_migrations.json"
private_constant :HOMEBREW_TAP_MIGRATIONS_FILE
HOMEBREW_TAP_AUTOBUMP_FILE = ".github/autobump.txt"
private_constant :HOMEBREW_TAP_AUTOBUMP_FILE
HOMEBREW_TAP_SYNCED_VERSIONS_FORMULAE_FILE = "synced_versions_formulae.json"
private_constant :HOMEBREW_TAP_SYNCED_VERSIONS_FORMULAE_FILE
HOMEBREW_TAP_DISABLED_NEW_USR_LOCAL_RELOCATION_FORMULAE_FILE = "disabled_new_usr_local_relocation_formulae.json"
private_constant :HOMEBREW_TAP_DISABLED_NEW_USR_LOCAL_RELOCATION_FORMULAE_FILE
HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR = "audit_exceptions"
private_constant :HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR
HOMEBREW_TAP_STYLE_EXCEPTIONS_DIR = "style_exceptions"
private_constant :HOMEBREW_TAP_STYLE_EXCEPTIONS_DIR
HOMEBREW_TAP_JSON_FILES = T.let(%W[
#{HOMEBREW_TAP_FORMULA_RENAMES_FILE}
#{HOMEBREW_TAP_CASK_RENAMES_FILE}
#{HOMEBREW_TAP_MIGRATIONS_FILE}
#{HOMEBREW_TAP_SYNCED_VERSIONS_FORMULAE_FILE}
#{HOMEBREW_TAP_DISABLED_NEW_USR_LOCAL_RELOCATION_FORMULAE_FILE}
#{HOMEBREW_TAP_AUDIT_EXCEPTIONS_DIR}/*.json
#{HOMEBREW_TAP_STYLE_EXCEPTIONS_DIR}/*.json
].freeze, T::Array[String])
class InvalidNameError < ArgumentError; end
# Fetch a {Tap} by name.
#
# @api public
sig { params(user: String, repository: String).returns(Tap) }
def self.fetch(user, repository = T.unsafe(nil))
user, repository = user.split("/", 2) if repository.nil?
if [user, repository].any? { |part| part.nil? || part.include?("/") }
raise InvalidNameError, "Invalid tap name: '#{[*user, *repository].join("/")}'"
end
user = T.must(user)
# We special case homebrew and linuxbrew so that users don't have to shift in a terminal.
user = user.capitalize if ["homebrew", "linuxbrew"].include?(user)
repository = repository.sub(HOMEBREW_OFFICIAL_REPO_PREFIXES_REGEX, "")
return CoreTap.instance if ["Homebrew", "Linuxbrew"].include?(user) && ["core", "homebrew"].include?(repository)
return CoreCaskTap.instance if user == "Homebrew" && repository == "cask"
cache_key = "#{user}/#{repository}".downcase
cache.fetch(cache_key) { |key| cache[key] = new(user, repository) }
end
# Get a {Tap} from its path or a path inside of it.
#
# @api public
sig { params(path: T.any(Pathname, String)).returns(T.nilable(Tap)) }
def self.from_path(path)
match = File.expand_path(path).match(HOMEBREW_TAP_PATH_REGEX)
return unless match
return unless (user = match[:user])
return unless (repository = match[:repository])
fetch(user, repository)
end
sig { params(name: String).returns(T.nilable([Tap, String])) }
def self.with_formula_name(name)
return unless (match = name.match(HOMEBREW_TAP_FORMULA_REGEX))
user = T.must(match[:user])
repository = T.must(match[:repository])
name = T.must(match[:name])
# Relative paths are not taps.
return if [user, repository].intersect?([".", ".."])
tap = fetch(user, repository)
[tap, name.downcase]
end
sig { params(token: String).returns(T.nilable([Tap, String])) }
def self.with_cask_token(token)
return unless (match = token.match(HOMEBREW_TAP_CASK_REGEX))
user = T.must(match[:user])
repository = T.must(match[:repository])
token = T.must(match[:token])
# Relative paths are not taps.
return if [user, repository].intersect?([".", ".."])
tap = fetch(user, repository)
[tap, token.downcase]
end
sig { returns(T::Set[Tap]) }
def self.allowed_taps
cache_key = :"allowed_taps_#{Homebrew::EnvConfig.allowed_taps.to_s.tr(" ", "_")}"
cache[cache_key] ||= begin
allowed_tap_list = Homebrew::EnvConfig.allowed_taps.to_s.split
Set.new(allowed_tap_list.filter_map do |tap|
Tap.fetch(tap)
rescue Tap::InvalidNameError
opoo "Invalid tap name in `$HOMEBREW_ALLOWED_TAPS`: #{tap}"
nil
end).freeze
end
end
sig { returns(T::Set[Tap]) }
def self.forbidden_taps
cache_key = :"forbidden_taps_#{Homebrew::EnvConfig.forbidden_taps.to_s.tr(" ", "_")}"
cache[cache_key] ||= begin
forbidden_tap_list = Homebrew::EnvConfig.forbidden_taps.to_s.split
Set.new(forbidden_tap_list.filter_map do |tap|
Tap.fetch(tap)
rescue Tap::InvalidNameError
opoo "Invalid tap name in `$HOMEBREW_FORBIDDEN_TAPS`: #{tap}"
nil
end).freeze
end
end
class << self
extend T::Generic
Elem = type_member(:out) { { fixed: Tap } }
# @api public
include Enumerable
end
# The user name of this {Tap}. Usually, it's the GitHub username of
# this {Tap}'s remote repository.
#
# @api public
sig { returns(String) }
attr_reader :user
# The repository name of this {Tap} without the leading `homebrew-`.
#
# @api public
sig { returns(String) }
attr_reader :repository
# The repository name of this {Tap} including the leading `homebrew-`.
#
# @api public
sig { returns(String) }
attr_reader :full_repository
# The name of this {Tap}. It combines {#user} and {#repository} with a slash.
# {#name} is always in lowercase.
# e.g. `user/repository`
#
# @api public
sig { returns(String) }
attr_reader :name
# @api public
sig { returns(String) }
def to_s = name
# The full name of this {Tap}, including the `homebrew-` prefix.
# It combines {#user} and 'homebrew-'-prefixed {#repository} with a slash.
# e.g. `user/homebrew-repository`
#
# @api public
sig { returns(String) }
attr_reader :full_name
# The local path to this {Tap}.
# e.g. `/usr/local/Library/Taps/user/homebrew-repository`
#
# @api public
sig { returns(Pathname) }
attr_reader :path
# The git repository of this {Tap}.
sig { returns(GitRepository) }
attr_reader :git_repository
# Always use `Tap.fetch` instead of `Tap.new`.
private_class_method :new
sig { params(user: String, repository: String).void }
def initialize(user, repository)
require "git_repository"
@user = user
@repository = repository
@name = T.let("#{@user}/#{@repository}".downcase, String)
@full_repository = T.let("homebrew-#{@repository}", String)
@full_name = T.let("#{@user}/#{@full_repository}", String)
@path = T.let(HOMEBREW_TAP_DIRECTORY/@full_name.downcase, Pathname)
@git_repository = T.let(GitRepository.new(@path), GitRepository)
end
# Clear internal cache.
sig { void }
def clear_cache
@remote = nil
@repository_var_suffix = nil
remove_instance_variable(:@private) if instance_variable_defined?(:@private)
@formula_dir = nil
@formula_files = nil
@formula_files_by_name = nil
@formula_names = nil
@prefix_to_versioned_formulae_names = nil
@formula_renames = nil
@formula_reverse_renames = nil
@cask_dir = nil
@cask_files = nil
@cask_files_by_name = nil
@cask_tokens = nil
@cask_renames = nil
@cask_reverse_renames = nil
@alias_dir = nil
@alias_files = nil
@aliases = nil
@alias_table = nil
@alias_reverse_table = nil
@command_dir = nil
@command_files = nil
@tap_migrations = nil
@reverse_tap_migrations_renames = nil
@audit_exceptions = nil
@style_exceptions = nil
@synced_versions_formulae = nil
@config = nil
end
sig { overridable.void }
def ensure_installed!
return if installed?
install
end
# The remote path to this {Tap}.
# e.g. `https://github.com/user/homebrew-repository`
#
# @api public
sig { overridable.returns(T.nilable(String)) }
def remote
return default_remote unless installed?
@remote ||= T.let(git_repository.origin_url, T.nilable(String))
end
# The remote repository name of this {Tap}.
# e.g. `user/homebrew-repository`
#
# @api public
sig { returns(T.nilable(String)) }
def remote_repository
return unless (remote = self.remote)
return unless (match = remote.match(HOMEBREW_TAP_REPOSITORY_REGEX))
@remote_repository ||= T.let(T.must(match[:remote_repository]), T.nilable(String))
end
# The default remote path to this {Tap}.
sig { returns(String) }
def default_remote
"https://github.com/#{full_name}"
end
sig { returns(String) }
def repository_var_suffix
@repository_var_suffix ||= T.let(path.to_s
.delete_prefix(HOMEBREW_TAP_DIRECTORY.to_s)
.tr("^A-Za-z0-9", "_")
.upcase, T.nilable(String))
end
# Check whether this {Tap} is a Git repository.
#
# @api public
sig { returns(T::Boolean) }
def git?
git_repository.git_repository?
end
# Git branch for this {Tap}.
#
# @api public
sig { returns(T.nilable(String)) }
def git_branch
raise TapUnavailableError, name unless installed?
git_repository.branch_name
end
# Git HEAD for this {Tap}.
#
# @api public
sig { returns(T.nilable(String)) }
def git_head
raise TapUnavailableError, name unless installed?
@git_head ||= T.let(git_repository.head_ref, T.nilable(String))
end
# Time since last git commit for this {Tap}.
#
# @api public
sig { returns(T.nilable(String)) }
def git_last_commit
raise TapUnavailableError, name unless installed?
git_repository.last_committed
end
# The issues URL of this {Tap}.
# e.g. `https://github.com/user/homebrew-repository/issues`
#
# @api public
sig { returns(T.nilable(String)) }
def issues_url
return if !official? && custom_remote?
"#{default_remote}/issues"
end
# Check whether this {Tap} is an official Homebrew tap.
#
# @api public
sig { returns(T::Boolean) }
def official?
user == "Homebrew"
end
# Check whether the remote of this {Tap} is a private repository.
#
# @api public
sig { returns(T::Boolean) }
def private?
return @private unless @private.nil?
@private = T.let(
begin
if core_tap? || core_cask_tap?
false
elsif custom_remote? || (value = GitHub.private_repo?(full_name)).nil?
true
else
value
end
rescue GitHub::API::Error
true
end,
T.nilable(T::Boolean),
)
T.must(@private)
end
# {TapConfig} of this {Tap}.
sig { returns(TapConfig) }
def config
@config ||= T.let(begin
raise TapUnavailableError, name unless installed?
TapConfig.new(self)
end, T.nilable(TapConfig))
end
# Check whether this {Tap} is installed.
#
# @api public
sig { returns(T::Boolean) }
def installed?
path.directory?
end
# Check whether this {Tap} is a shallow clone.
sig { returns(T::Boolean) }
def shallow?
(path/".git/shallow").exist?
end
sig { overridable.returns(T::Boolean) }
def core_tap?
false
end
sig { returns(T::Boolean) }
def core_cask_tap?
false
end
# Install this {Tap}.
#
# @param clone_target If passed, it will be used as the clone remote.
# @param quiet If set, suppress all output.
# @param custom_remote If set, change the tap's remote if already installed.
# @param verify If set, verify all the formula, casks and aliases in the tap are valid.
# @param force If set, force core and cask taps to install even under API mode.
#
# @api public
sig {
overridable.params(
quiet: T::Boolean,
clone_target: T.nilable(T.any(Pathname, String)),
custom_remote: T::Boolean,
verify: T::Boolean,
force: T::Boolean,
).void
}
def install(quiet: false, clone_target: nil,
custom_remote: false, verify: false, force: false)
require "descriptions"
require "readall"
if official? && DEPRECATED_OFFICIAL_TAPS.include?(repository)
odie "#{name} was deprecated. This tap is now empty and all its contents were either deleted or migrated."
elsif user == "caskroom" || name == "phinze/cask"
new_repository = (repository == "cask") ? "cask" : "cask-#{repository}"
odie "#{name} was moved. Tap homebrew/#{new_repository} instead."
end
raise TapNoCustomRemoteError, name if custom_remote && clone_target.nil?
requested_remote = clone_target || default_remote
if installed? && !custom_remote
raise TapRemoteMismatchError.new(name, @remote, requested_remote) if clone_target && requested_remote != remote
raise TapAlreadyTappedError, name unless shallow?
end
if !allowed_by_env? || forbidden_by_env?
owner = Homebrew::EnvConfig.forbidden_owner
owner_contact = if (contact = Homebrew::EnvConfig.forbidden_owner_contact.presence)
"\n#{contact}"
end
error_message = "The installation of the #{full_name} was requested but #{owner}\n"
error_message << "has not allowed this tap in `$HOMEBREW_ALLOWED_TAPS`" unless allowed_by_env?
error_message << " and\n" if !allowed_by_env? && forbidden_by_env?
error_message << "has forbidden this tap in `$HOMEBREW_FORBIDDEN_TAPS`" if forbidden_by_env?
error_message << ".#{owner_contact}"
odie error_message
end
# ensure git is installed
Utils::Git.ensure_installed!
if installed?
if requested_remote != remote # we are sure that clone_target is not nil and custom_remote is true here
fix_remote_configuration(requested_remote:, quiet:)
end
config.delete(:forceautoupdate)
$stderr.ohai "Unshallowing #{name}" if shallow? && !quiet
args = %w[fetch]
# Git throws an error when attempting to unshallow a full clone
args << "--unshallow" if shallow?
args << "-q" if quiet
path.cd { safe_system "git", *args }
return
elsif (core_tap? || core_cask_tap?) && !Homebrew::EnvConfig.no_install_from_api? && !force
odie "Tapping #{name} is no longer typically necessary.\n" \
"Add #{Formatter.option("--force")} if you are sure you need it for contributing to Homebrew."
end
clear_cache
Tap.clear_cache
$stderr.ohai "Tapping #{name}" unless quiet
args = %W[clone #{requested_remote} #{path}]
# Override possible user configs like:
# git config --global clone.defaultRemoteName notorigin
args << "--origin=origin"
args << "-q" if quiet
# Override user-set default template.
args << "--template="
# Prevent `fsmonitor` from watching this repository.
args << "--config" << "core.fsmonitor=false"
begin
safe_system "git", *args
if verify && !Homebrew::EnvConfig.developer? && !Readall.valid_tap?(self, aliases: true)
raise "Cannot tap #{name}: invalid syntax in tap!"
end
rescue Interrupt, RuntimeError
ignore_interrupts do
# wait for git to possibly cleanup the top directory when interrupt happens.
sleep 0.1
FileUtils.rm_rf path
path.parent.rmdir_if_possible
end
raise
end
Commands.rebuild_commands_completion_list
link_completions_and_manpages
formatted_contents = contents.presence&.to_sentence&.prepend(" ")
$stderr.puts "Tapped#{formatted_contents} (#{path.abv})." unless quiet
require "description_cache_store"
CacheStoreDatabase.use(:descriptions) do |db|
DescriptionCacheStore.new(db)
.update_from_formula_names!(formula_names)
end
CacheStoreDatabase.use(:cask_descriptions) do |db|
CaskDescriptionCacheStore.new(db)
.update_from_cask_tokens!(cask_tokens)
end
if official?
untapped = self.class.untapped_official_taps
untapped -= [name]
if untapped.empty?
Homebrew::Settings.delete :untapped
else
Homebrew::Settings.write :untapped, untapped.join(";")
end
end
return if clone_target
return unless private?
return if quiet
path.cd do
return if Utils.popen_read("git", "config", "--get", "credential.helper").present?
end
$stderr.puts <<~EOS
It looks like you tapped a private repository. To avoid entering your
credentials each time you update, you can use git HTTP credential
caching or issue the following command:
cd #{path}
git remote set-url origin git@github.com:#{full_name}.git
EOS
end
sig { void }
def link_completions_and_manpages
require "utils/link"
command = "brew tap --repair"
Utils::Link.link_manpages(path, command)
require "completions"
Homebrew::Completions.show_completions_message_if_needed
if official? || Homebrew::Completions.link_completions?
Utils::Link.link_completions(path, command)
else
Utils::Link.unlink_completions(path)
end
end
sig { params(requested_remote: T.nilable(T.any(Pathname, String)), quiet: T::Boolean).void }
def fix_remote_configuration(requested_remote: nil, quiet: false)
if requested_remote.present?
path.cd do
safe_system "git", "remote", "set-url", "origin", requested_remote
safe_system "git", "config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"
end
$stderr.ohai "#{name}: changed remote from #{remote} to #{requested_remote}" unless quiet
end
return unless remote
current_upstream_head = git_repository.origin_branch_name
return if current_upstream_head.present? && requested_remote.blank? &&
git_repository.origin_has_branch?(current_upstream_head)
args = %w[fetch]
args << "--quiet" if quiet
args << "origin"
args << "+refs/heads/*:refs/remotes/origin/*"
safe_system "git", "-C", path, *args
git_repository.set_head_origin_auto
current_upstream_head ||= T.must(git_repository.origin_branch_name)
new_upstream_head = T.must(git_repository.origin_branch_name)
return if new_upstream_head == current_upstream_head
safe_system "git", "-C", path, "config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"
git_repository.rename_branch old: current_upstream_head, new: new_upstream_head
git_repository.set_upstream_branch local: new_upstream_head, origin: new_upstream_head
return if quiet
$stderr.ohai "#{name}: changed default branch name from #{current_upstream_head} to #{new_upstream_head}!"
end
# Uninstall this {Tap}.
#
# @api public
sig { overridable.params(manual: T::Boolean).void }
def uninstall(manual: false)
require "descriptions"
raise TapUnavailableError, name unless installed?
$stderr.puts "Untapping #{name}..."
abv = path.abv
formatted_contents = contents.presence&.to_sentence&.prepend(" ")
require "description_cache_store"
CacheStoreDatabase.use(:descriptions) do |db|
DescriptionCacheStore.new(db)
.delete_from_formula_names!(formula_names)
end
CacheStoreDatabase.use(:cask_descriptions) do |db|
CaskDescriptionCacheStore.new(db)
.delete_from_cask_tokens!(cask_tokens)
end
require "utils/link"
Utils::Link.unlink_manpages(path)
Utils::Link.unlink_completions(path)
FileUtils.rm_r(path)
path.parent.rmdir_if_possible
$stderr.puts "Untapped#{formatted_contents} (#{abv})."
Commands.rebuild_commands_completion_list
clear_cache
Tap.clear_cache
return if !manual || !official?
untapped = self.class.untapped_official_taps
return if untapped.include? name
untapped << name
Homebrew::Settings.write :untapped, untapped.join(";")
end
# Check whether the {#remote} of {Tap} is customized.
#
# @api public
sig { returns(T::Boolean) }
def custom_remote?
return true unless (remote = self.remote)
!T.must(remote.casecmp(default_remote)).zero?
end
# Path to the directory of all {Formula} files for this {Tap}.
#
# @api public
sig { overridable.returns(Pathname) }
def formula_dir
# Official formulae taps always use this directory, saves time to hardcode.
@formula_dir ||= T.let(
if official?
path/"Formula"
else
potential_formula_dirs.find(&:directory?) || (path/"Formula")
end,
T.nilable(Pathname),
)
end
sig { returns(T::Array[Pathname]) }
def potential_formula_dirs
@potential_formula_dirs ||= T.let([path/"Formula", path/"HomebrewFormula", path].freeze, T.nilable(T::Array[Pathname]))
end
sig { overridable.params(name: String).returns(Pathname) }
def new_formula_path(name)
formula_dir/"#{name.downcase}.rb"
end
# Path to the directory of all {Cask} files for this {Tap}.
#
# @api public
sig { returns(Pathname) }
def cask_dir
@cask_dir ||= T.let(path/"Casks", T.nilable(Pathname))
end
sig { params(token: String).returns(Pathname) }
def new_cask_path(token)
cask_dir/"#{token.downcase}.rb"
end
sig { params(token: String).returns(String) }
def relative_cask_path(token)
new_cask_path(token).to_s
.delete_prefix("#{path}/")
end
sig { returns(T::Array[String]) }
def contents
contents = []
if (command_count = command_files.count).positive?
contents << Utils.pluralize("command", command_count, include_count: true)
end
if (cask_count = cask_files.count).positive?
contents << Utils.pluralize("cask", cask_count, include_count: true)
end
if (formula_count = formula_files.count).positive?
contents << Utils.pluralize("formula", formula_count, include_count: true)
end
contents
end
# An array of all {Formula} files of this {Tap}.
sig { overridable.returns(T::Array[Pathname]) }
def formula_files
@formula_files ||= T.let(
if formula_dir.directory?
if formula_dir == path
# We only want the top level here so we don't treat commands & casks as formulae.
# Sharding is only supported in Formula/ and HomebrewFormula/.
Pathname.glob(formula_dir/"*.rb")
else
Pathname.glob(formula_dir/"**/*.rb")
end
else
[]
end,
T.nilable(T::Array[Pathname]),
)
end
# A mapping of {Formula} names to {Formula} file paths.
sig { overridable.returns(T::Hash[String, Pathname]) }
def formula_files_by_name
@formula_files_by_name ||= T.let(formula_files.each_with_object({}) do |file, hash|
# If there's more than one file with the same basename: use the longer one to prioritise more specific results.
basename = file.basename(".rb").to_s
existing_file = hash[basename]
hash[basename] = file if existing_file.nil? || existing_file.to_s.length < file.to_s.length
end, T.nilable(T::Hash[String, Pathname]))
end
# An array of all {Cask} files of this {Tap}.
sig { returns(T::Array[Pathname]) }
def cask_files
@cask_files ||= T.let(
if cask_dir.directory?
Pathname.glob(cask_dir/"**/*.rb")
else
[]
end,
T.nilable(T::Array[Pathname]),
)
end
# A mapping of {Cask} tokens to {Cask} file paths.
sig { returns(T::Hash[String, Pathname]) }
def cask_files_by_name
@cask_files_by_name ||= T.let(cask_files.each_with_object({}) do |file, hash|
# If there's more than one file with the same basename: use the longer one to prioritise more specific results.
basename = file.basename(".rb").to_s
existing_file = hash[basename]
hash[basename] = file if existing_file.nil? || existing_file.to_s.length < file.to_s.length
end, T.nilable(T::Hash[String, Pathname]))
end
RUBY_FILE_NAME_REGEX = %r{[^/]+\.rb}
private_constant :RUBY_FILE_NAME_REGEX
ZERO_OR_MORE_SUBDIRECTORIES_REGEX = %r{(?:[^/]+/)*}
private_constant :ZERO_OR_MORE_SUBDIRECTORIES_REGEX
sig { returns(Regexp) }
def formula_file_regex
@formula_file_regex ||= T.let(
case formula_dir
when path/"Formula"
%r{^Formula/#{ZERO_OR_MORE_SUBDIRECTORIES_REGEX.source}#{RUBY_FILE_NAME_REGEX.source}$}o
when path/"HomebrewFormula"
%r{^HomebrewFormula/#{ZERO_OR_MORE_SUBDIRECTORIES_REGEX.source}#{RUBY_FILE_NAME_REGEX.source}$}o
when path
/^#{RUBY_FILE_NAME_REGEX.source}$/o
else
raise ArgumentError, "Unexpected formula_dir: #{formula_dir}"
end,
T.nilable(Regexp),
)
end
private :formula_file_regex
# accepts the relative path of a file from {Tap}'s path
sig { params(file: String).returns(T::Boolean) }
def formula_file?(file)
file.match?(formula_file_regex)
end
CASK_FILE_REGEX = %r{^Casks/#{ZERO_OR_MORE_SUBDIRECTORIES_REGEX.source}#{RUBY_FILE_NAME_REGEX.source}$}
private_constant :CASK_FILE_REGEX
# accepts the relative path of a file from {Tap}'s path
sig { params(file: String).returns(T::Boolean) }
def cask_file?(file)
file.match?(CASK_FILE_REGEX)
end
# An array of all {Formula} names of this {Tap}.
sig { overridable.returns(T::Array[String]) }
def formula_names
@formula_names ||= T.let(formula_files.map { formula_file_to_name(it) }, T.nilable(T::Array[String]))
end
# A hash of all {Formula} name prefixes to versioned {Formula} in this {Tap}.
sig { returns(T::Hash[String, T::Array[String]]) }
def prefix_to_versioned_formulae_names
@prefix_to_versioned_formulae_names ||= T.let(formula_names
.select { |name| name.include?("@") }
.group_by { |name| name.gsub(/(@[\d.]+)?$/, "") }
.transform_values(&:sort)
.freeze, T.nilable(T::Hash[String, T::Array[String]]))
end
# An array of all {Cask} tokens of this {Tap}.
sig { returns(T::Array[String]) }
def cask_tokens
@cask_tokens ||= T.let(cask_files.map { formula_file_to_name(it) }, T.nilable(T::Array[String]))
end
# Path to the directory of all alias files for this {Tap}.
sig { overridable.returns(Pathname) }
def alias_dir
@alias_dir ||= T.let(path/"Aliases", T.nilable(Pathname))
end
# An array of all alias files of this {Tap}.
sig { returns(T::Array[Pathname]) }
def alias_files
@alias_files ||= T.let(Pathname.glob("#{alias_dir}/*").select(&:file?), T.nilable(T::Array[Pathname]))
end
# An array of all aliases of this {Tap}.
sig { returns(T::Array[String]) }
def aliases
@aliases ||= T.let(alias_table.keys, T.nilable(T::Array[String]))
end
# Mapping from aliases to formula names.
sig { overridable.returns(T::Hash[String, String]) }
def alias_table
@alias_table ||= T.let(alias_files.each_with_object({}) do |alias_file, alias_table|
alias_table[alias_file_to_name(alias_file)] = formula_file_to_name(alias_file.resolved_path)
end, T.nilable(T::Hash[String, String]))
end
# Mapping from formula names to aliases.
sig { returns(T::Hash[String, T::Array[String]]) }
def alias_reverse_table
@alias_reverse_table ||= T.let(
alias_table.each_with_object({}) do |(alias_name, formula_name), alias_reverse_table|
alias_reverse_table[formula_name] ||= []
alias_reverse_table[formula_name] << alias_name
end,
T.nilable(T::Hash[String, T::Array[String]]),
)
end
sig { returns(Pathname) }
def command_dir
@command_dir ||= T.let(path/"cmd", T.nilable(Pathname))
end
# An array of all commands files of this {Tap}.
sig { returns(T::Array[Pathname]) }
def command_files
@command_files ||= T.let(
if command_dir.directory?
Commands.find_commands(command_dir)
else
[]
end,
T.nilable(T::Array[Pathname]),
)
end
sig { returns(T::Hash[String, T.untyped]) }
def to_hash
hash = {
"name" => name,
"user" => user,
"repo" => repository,
"repository" => repository,
"path" => path.to_s,
"installed" => installed?,
"official" => official?,
"formula_names" => formula_names,
"cask_tokens" => cask_tokens,
}
if installed?
hash["formula_files"] = formula_files.map(&:to_s)
hash["cask_files"] = cask_files.map(&:to_s)
hash["command_files"] = command_files.map(&:to_s)
hash["remote"] = remote
hash["custom_remote"] = custom_remote?
hash["private"] = private?
hash["HEAD"] = git_head || "(none)"
hash["last_commit"] = git_last_commit || "never"
hash["branch"] = git_branch || "(none)"
end
hash
end
# Hash with tap cask renames.
sig { returns(T::Hash[String, String]) }
def cask_renames
@cask_renames ||= T.let(
if (rename_file = path/HOMEBREW_TAP_CASK_RENAMES_FILE).file?
JSON.parse(rename_file.read)
else
{}
end,
T.nilable(T::Hash[String, String]),
)
end
# Mapping from new to old cask tokens. Reverse of {#cask_renames}.
sig { returns(T::Hash[String, T::Array[String]]) }
def cask_reverse_renames
@cask_reverse_renames ||= T.let(cask_renames.each_with_object({}) do |(old_name, new_name), hash|
hash[new_name] ||= []
hash[new_name] << old_name
end, T.nilable(T::Hash[String, T::Array[String]]))
end
# Hash with tap formula renames.
sig { overridable.returns(T::Hash[String, String]) }
def formula_renames
@formula_renames ||= T.let(
if (rename_file = path/HOMEBREW_TAP_FORMULA_RENAMES_FILE).file?
JSON.parse(rename_file.read)
else
{}
end,
T.nilable(T::Hash[String, String]),
)
end
# Mapping from new to old formula names. Reverse of {#formula_renames}.
sig { returns(T::Hash[String, T::Array[String]]) }
def formula_reverse_renames
@formula_reverse_renames ||= T.let(formula_renames.each_with_object({}) do |(old_name, new_name), hash|
hash[new_name] ||= []
hash[new_name] << old_name
end, T.nilable(T::Hash[String, T::Array[String]]))
end
# Hash with tap migrations.
sig { overridable.returns(T::Hash[String, String]) }
def tap_migrations
@tap_migrations ||= T.let(
if (migration_file = path/HOMEBREW_TAP_MIGRATIONS_FILE).file?
JSON.parse(migration_file.read)
else
{}
end, T.nilable(T::Hash[String, String])
)
end
sig { returns(T::Hash[String, T::Array[String]]) }
def reverse_tap_migrations_renames
@reverse_tap_migrations_renames ||= T.let(
tap_migrations.each_with_object({}) do |(old_name, new_name), hash|
# Only include renames:
# + `homebrew/cask/water-buffalo`
# - `homebrew/cask`
next if new_name.count("/") != 2
hash[new_name] ||= []
hash[new_name] << old_name
end,
T.nilable(T::Hash[String, T::Array[String]]),
)
end
# The old names a formula or cask had before getting migrated to the current tap.
sig { params(current_tap: Tap, name_or_token: String).returns(T::Array[String]) }
def self.tap_migration_oldnames(current_tap, name_or_token)
key = "#{current_tap}/#{name_or_token}"
Tap.each_with_object([]) do |tap, array|
next unless (renames = tap.reverse_tap_migrations_renames[key])
array.concat(renames)
end
end
# Array with autobump names
sig { overridable.returns(T::Array[String]) }
def autobump
autobump_packages = if core_cask_tap?
Homebrew::API::Cask.all_casks
elsif core_tap?
Homebrew::API::Formula.all_formulae
else
{}
end
@autobump ||= T.let(autobump_packages.select do |_, p|
next if p["disabled"]
next if p["deprecated"] && p["deprecation_reason"] != "fails_gatekeeper_check"
next if p["skip_livecheck"]
p["autobump"] == true
end.keys, T.nilable(T::Array[String]))
if @autobump.blank?
@autobump = T.let(
if (autobump_file = path/HOMEBREW_TAP_AUTOBUMP_FILE).file?
autobump_file.readlines(chomp: true)
else
[]
end,
T.nilable(T::Array[String]),
)
end
T.must(@autobump)
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dependents_message.rb | Library/Homebrew/dependents_message.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
class DependentsMessage
include ::Utils::Output::Mixin
sig { returns(T::Array[T.any(String, Keg)]) }
attr_reader :reqs
sig { returns(T::Array[String]) }
attr_reader :deps, :named_args
sig { params(requireds: T::Array[T.any(String, Keg)], dependents: T::Array[String], named_args: T::Array[String]).void }
def initialize(requireds, dependents, named_args: [])
@reqs = requireds
@deps = dependents
@named_args = named_args
end
sig { void }
def output
ofail <<~EOS
Refusing to uninstall #{reqs.to_sentence}
because #{reqs.one? ? "it" : "they"} #{are_required_by_deps}.
You can override this and force removal with:
#{sample_command}
EOS
end
protected
sig { returns(String) }
def sample_command
"brew uninstall --ignore-dependencies #{named_args.join(" ")}"
end
sig { returns(String) }
def are_required_by_deps
"#{reqs.one? ? "is" : "are"} required by #{deps.to_sentence}, " \
"which #{deps.one? ? "is" : "are"} currently installed"
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/fetch.rb | Library/Homebrew/fetch.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Fetch
sig {
params(
formula: Formula,
force_bottle: T::Boolean,
bottle_tag: T.nilable(Symbol),
build_from_source_formulae: T::Array[String],
os: T.nilable(Symbol),
arch: T.nilable(Symbol),
).returns(T::Boolean)
}
def fetch_bottle?(formula, force_bottle:, bottle_tag:, build_from_source_formulae:, os:, arch:)
bottle = formula.bottle
return true if force_bottle && bottle.present?
if os.present?
return true
elsif ENV["HOMEBREW_TEST_GENERIC_OS"].present?
# `:generic` bottles don't exist and `--os` flag is not specified.
return false
end
return true if arch.present?
return true if bottle_tag.present? && formula.bottled?(bottle_tag)
bottle.present? &&
formula.pour_bottle? &&
build_from_source_formulae.exclude?(formula.full_name) &&
bottle.compatible_locations?
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/pkg_version.rb | Library/Homebrew/pkg_version.rb | # typed: strict
# frozen_string_literal: true
require "version"
# Combination of a version and a revision.
class PkgVersion
include Comparable
extend Forwardable
REGEX = /\A(.+?)(?:_(\d+))?\z/
private_constant :REGEX
sig { returns(Version) }
attr_reader :version
sig { returns(Integer) }
attr_reader :revision
delegate [:major, :minor, :patch, :major_minor, :major_minor_patch] => :version
sig { params(path: String).returns(PkgVersion) }
def self.parse(path)
_, version, revision = *path.match(REGEX)
version = Version.new(version.to_s)
new(version, revision.to_i)
end
sig { params(version: Version, revision: Integer).void }
def initialize(version, revision)
@version = version
@revision = revision
end
sig { returns(T::Boolean) }
def head?
version.head?
end
sig { returns(String) }
def to_str
if revision.positive?
"#{version}_#{revision}"
else
version.to_s
end
end
sig { returns(String) }
def to_s = to_str
sig { params(other: PkgVersion).returns(T.nilable(Integer)) }
def <=>(other)
version_comparison = (version <=> other.version)
return if version_comparison.nil?
version_comparison.nonzero? || revision <=> other.revision
end
alias eql? ==
sig { returns(Integer) }
def hash
[version, revision].hash
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_bot.rb | Library/Homebrew/test_bot.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "test_bot/step"
require "test_bot/test_runner"
require "date"
require "json"
require "development_tools"
require "formula"
require "formula_installer"
require "os"
require "tap"
require "utils"
require "utils/bottles"
module Homebrew
module TestBot
module_function
GIT = "/usr/bin/git"
HOMEBREW_TAP_REGEX = %r{^([\w-]+)/homebrew-([\w-]+)$}
def cleanup?(args)
args.cleanup? || GitHub::Actions.env_set?
end
def local?(args)
args.local? || GitHub::Actions.env_set?
end
def resolve_test_tap(tap = nil)
return Tap.fetch(tap) if tap
# Get tap from GitHub Actions GITHUB_REPOSITORY
git_url = ENV.fetch("GITHUB_REPOSITORY", nil)
return if git_url.blank?
url_path = git_url.sub(%r{^https?://github\.com/}, "")
.chomp("/")
.sub(/\.git$/, "")
return CoreTap.instance if url_path == CoreTap.instance.full_name
begin
Tap.fetch(url_path) if url_path.match?(HOMEBREW_TAP_REGEX)
rescue
# Don't care if tap fetch fails
nil
end
end
def run!(args)
$stdout.sync = true
$stderr.sync = true
if Pathname.pwd == HOMEBREW_PREFIX && cleanup?(args)
raise UsageError, "cannot use --cleanup from HOMEBREW_PREFIX as it will delete all output."
end
ENV["HOMEBREW_DEVELOPER"] = "1"
ENV["HOMEBREW_NO_AUTO_UPDATE"] = "1"
ENV["HOMEBREW_NO_EMOJI"] = "1"
ENV["HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK"] = "1"
ENV["HOMEBREW_FAIL_LOG_LINES"] = "150"
ENV["HOMEBREW_CURL"] = ENV["HOMEBREW_CURL_PATH"] = "/usr/bin/curl"
ENV["HOMEBREW_GIT"] = ENV["HOMEBREW_GIT_PATH"] = GIT
ENV["HOMEBREW_DISALLOW_LIBNSL1"] = "1"
ENV["HOMEBREW_NO_ENV_HINTS"] = "1"
ENV["HOMEBREW_PATH"] = ENV["PATH"] =
"#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin:#{ENV.fetch("PATH")}"
if local?(args)
home = "#{Dir.pwd}/home"
logs = "#{Dir.pwd}/logs"
gitconfig = "#{Dir.home}/.gitconfig"
ENV["HOMEBREW_HOME"] = ENV["HOME"] = home
ENV["HOMEBREW_LOGS"] = logs
FileUtils.mkdir_p home
FileUtils.mkdir_p logs
FileUtils.cp gitconfig, home if File.exist?(gitconfig)
end
tap = resolve_test_tap(args.tap)
if tap&.core_tap?
ENV["HOMEBREW_NO_INSTALL_FROM_API"] = "1"
ENV["HOMEBREW_VERIFY_ATTESTATIONS"] = "1" if args.only_formulae?
end
# Tap repository if required, this is done before everything else
# because Formula parsing and/or git commit hash lookup depends on it.
# At the same time, make sure Tap is not a shallow clone.
# bottle rebuild and bottle upload rely on full clone.
if tap
if !tap.path.exist?
safe_system "brew", "tap", tap.name
elsif (tap.path/".git/shallow").exist?
raise unless quiet_system GIT, "-C", tap.path, "fetch", "--unshallow"
end
end
brew_version = Utils.safe_popen_read(
GIT, "-C", HOMEBREW_REPOSITORY.to_s,
"describe", "--tags", "--abbrev", "--dirty"
).strip
brew_commit_subject = Utils.safe_popen_read(
GIT, "-C", HOMEBREW_REPOSITORY.to_s,
"log", "-1", "--format=%s"
).strip
puts Formatter.headline("Using Homebrew/brew #{brew_version} (#{brew_commit_subject})", color: :cyan)
if tap.to_s != CoreTap.instance.name && CoreTap.instance.installed?
core_revision = Utils.safe_popen_read(
GIT, "-C", CoreTap.instance.path.to_s,
"log", "-1", "--format=%h (%s)"
).strip
puts Formatter.headline("Using #{CoreTap.instance.full_name} #{core_revision}", color: :cyan)
end
if tap
tap_github = " (#{ENV["GITHUB_REPOSITORY"]})" if tap.full_name != ENV["GITHUB_REPOSITORY"]
tap_revision = Utils.safe_popen_read(
GIT, "-C", tap.path.to_s,
"log", "-1", "--format=%h (%s)"
).strip
puts Formatter.headline("Testing #{tap.full_name}#{tap_github} #{tap_revision}:", color: :cyan)
end
ENV["HOMEBREW_GIT_NAME"] = args.git_name || "BrewTestBot"
ENV["HOMEBREW_GIT_EMAIL"] = args.git_email ||
"1589480+BrewTestBot@users.noreply.github.com"
Homebrew.failed = !TestRunner.run!(tap, git: GIT, args:)
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/dependable.rb | Library/Homebrew/dependable.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "options"
# Shared functions for classes which can be depended upon.
module Dependable
extend T::Helpers
# `:run` and `:linked` are no longer used but keep them here to avoid their
# misuse in future.
RESERVED_TAGS = [:build, :optional, :recommended, :run, :test, :linked, :implicit, :no_linkage].freeze
attr_reader :tags
abstract!
sig { abstract.returns(T::Array[String]) }
def option_names; end
def build?
tags.include? :build
end
def optional?
tags.include? :optional
end
def recommended?
tags.include? :recommended
end
def test?
tags.include? :test
end
def implicit?
tags.include? :implicit
end
def no_linkage?
tags.include? :no_linkage
end
def required?
!build? && !test? && !optional? && !recommended?
end
sig { returns(T::Array[String]) }
def option_tags
tags.grep(String)
end
sig { returns(Options) }
def options
Options.create(option_tags)
end
def prune_from_option?(build)
return false if !optional? && !recommended?
build.without?(self)
end
def prune_if_build_and_not_dependent?(dependent, formula = nil)
return false unless build?
return dependent.installed? unless formula
dependent != formula
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/formula_auditor.rb | Library/Homebrew/formula_auditor.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "deprecate_disable"
require "formula_versions"
require "formula_name_cask_token_auditor"
require "resource_auditor"
require "utils/shared_audits"
require "utils/output"
require "utils/git"
module Homebrew
# Auditor for checking common violations in {Formula}e.
class FormulaAuditor
include FormulaCellarChecks
include Utils::Curl
include Utils::Output::Mixin
attr_reader :formula, :text, :problems, :new_formula_problems
def initialize(formula, options = {})
@formula = formula
@versioned_formula = formula.versioned_formula?
@new_formula_inclusive = options[:new_formula]
@new_formula = options[:new_formula] && !@versioned_formula
@strict = options[:strict]
@online = options[:online]
@git = options[:git]
@display_cop_names = options[:display_cop_names]
@only = options[:only]
@except = options[:except]
# Accept precomputed style offense results, for efficiency
@style_offenses = options[:style_offenses]
# Allow the formula tap to be set as homebrew/core, for testing purposes
@core_tap = formula.tap&.core_tap? || options[:core_tap]
@problems = []
@new_formula_problems = []
@text = formula.path.open("rb", &:read)
@specs = %w[stable head].filter_map { |s| formula.send(s) }
@spdx_license_data = options[:spdx_license_data]
@spdx_exception_data = options[:spdx_exception_data]
@tap_audit = options[:tap_audit]
@committed_version_info_cache = {}
end
def audit_style
return unless @style_offenses
@style_offenses.each do |offense|
cop_name = "#{offense.cop_name}: " if @display_cop_names
message = "#{cop_name}#{offense.message}"
problem message, location: offense.location, corrected: offense.corrected?
end
end
def audit_file
if formula.core_formula? && @versioned_formula
unversioned_name = formula.name.gsub(/@.*$/, "")
# ignore when an unversioned formula doesn't exist after an explicit rename
return if formula.tap.formula_renames.key?(unversioned_name)
# build this ourselves as we want e.g. homebrew/core to be present
full_name = "#{formula.tap}/#{unversioned_name}"
unversioned_formula = begin
Formulary.factory(full_name).path
rescue FormulaUnavailableError, TapFormulaAmbiguityError
Pathname.new formula.path.to_s.gsub(/@.*\.rb$/, ".rb")
end
unless unversioned_formula.exist?
unversioned_name = unversioned_formula.basename(".rb")
problem "#{formula} is versioned but no #{unversioned_name} formula exists"
end
elsif formula.stable? &&
!@versioned_formula &&
(versioned_formulae = formula.versioned_formulae - [formula]) &&
versioned_formulae.present?
versioned_aliases, unversioned_aliases = formula.aliases.partition { |a| /.@\d/.match?(a) }
_, last_alias_version = versioned_formulae.map(&:name).last.split("@")
alias_name_major = "#{formula.name}@#{formula.version.major}"
alias_name_major_minor = "#{formula.name}@#{formula.version.major_minor}"
alias_name = if last_alias_version.split(".").length == 1
alias_name_major
else
alias_name_major_minor
end
valid_main_alias_names = [alias_name_major, alias_name_major_minor].uniq
# Also accept versioned aliases with names of other aliases, but do not require them.
valid_other_alias_names = unversioned_aliases.flat_map do |name|
%W[
#{name}@#{formula.version.major}
#{name}@#{formula.version.major_minor}
].uniq
end
unless @core_tap
[versioned_aliases, valid_main_alias_names, valid_other_alias_names].each do |array|
array.map! { |a| "#{formula.tap}/#{a}" }
end
end
valid_versioned_aliases = versioned_aliases & valid_main_alias_names
invalid_versioned_aliases = versioned_aliases - valid_main_alias_names - valid_other_alias_names
latest_versioned_formula = versioned_formulae.map(&:name).first
if valid_versioned_aliases.empty? && alias_name != latest_versioned_formula
if formula.tap
problem <<~EOS
Formula has other versions so create a versioned alias:
cd #{formula.tap.alias_dir}
ln -s #{formula.path.to_s.gsub(formula.tap.path, "..")} #{alias_name}
EOS
else
problem "Formula has other versions so create an alias named '#{alias_name}'."
end
end
if invalid_versioned_aliases.present?
problem <<~EOS
Formula has invalid versioned aliases:
#{invalid_versioned_aliases.join("\n ")}
EOS
end
end
return if !formula.core_formula? || formula.path == formula.tap.new_formula_path(formula.name)
problem <<~EOS
Formula is in wrong path:
Expected: #{formula.tap.new_formula_path(formula.name)}
Actual: #{formula.path}
EOS
end
def self.aliases
# core aliases + tap alias names + tap alias full name
@aliases ||= Formula.aliases + Formula.tap_aliases
end
def audit_synced_versions_formulae
return unless formula.synced_with_other_formulae?
name = formula.name
version = formula.version
formula.tap.synced_versions_formulae.each do |synced_version_formulae|
next unless synced_version_formulae.include?(name)
synced_version_formulae.each do |synced_formula|
next if synced_formula == name
if (synced_version = Formulary.factory(synced_formula).version) != version
problem "Version of #{synced_formula} (#{synced_version}) should match version of #{name} (#{version})"
end
end
break
end
end
def audit_name
name = formula.name
name_auditor = Homebrew::FormulaNameCaskTokenAuditor.new(name)
if (errors = name_auditor.errors).any?
problem "Formula name '#{name}' must not contain #{errors.to_sentence(two_words_connector: " or ",
last_word_connector: " or ")}."
end
return unless @core_tap
return unless @strict
problem "'#{name}' is not allowed in homebrew/core." if MissingFormula.disallowed_reason(name)
if Formula.aliases.include? name
problem "Formula name conflicts with existing aliases in homebrew/core."
return
end
if (oldname = CoreTap.instance.formula_renames[name])
problem "'#{name}' is reserved as the old name of #{oldname} in homebrew/core."
return
end
cask_tokens = CoreCaskTap.instance.cask_tokens.presence
cask_tokens ||= Homebrew::API.cask_tokens
if cask_tokens.include?(name)
problem "Formula name conflicts with an existing Homebrew/cask cask's token."
return
end
return if formula.core_formula?
return unless Formula.core_names.include?(name)
problem "Formula name conflicts with an existing formula in homebrew/core."
end
PERMITTED_LICENSE_MISMATCHES = {
"AGPL-3.0" => ["AGPL-3.0-only", "AGPL-3.0-or-later"],
"GPL-2.0" => ["GPL-2.0-only", "GPL-2.0-or-later"],
"GPL-3.0" => ["GPL-3.0-only", "GPL-3.0-or-later"],
"LGPL-2.1" => ["LGPL-2.1-only", "LGPL-2.1-or-later"],
"LGPL-3.0" => ["LGPL-3.0-only", "LGPL-3.0-or-later"],
}.freeze
# The following licenses are non-free/open based on multiple sources (e.g. Debian, Fedora, FSF, OSI, ...)
INCOMPATIBLE_LICENSES = [
"Aladdin", # https://www.gnu.org/licenses/license-list.html#Aladdin
"CPOL-1.02", # https://www.gnu.org/licenses/license-list.html#cpol
"gSOAP-1.3b", # https://salsa.debian.org/ellert/gsoap/-/blob/HEAD/debian/copyright
"JSON", # https://wiki.debian.org/DFSGLicenses#JSON_evil_license
"MS-LPL", # https://github.com/spdx/license-list-XML/issues/1432#issuecomment-1077680709
"OPL-1.0", # https://wiki.debian.org/DFSGLicenses#Open_Publication_License_.28OPL.29_v1.0
].freeze
INCOMPATIBLE_LICENSE_PREFIXES = [
"BUSL", # https://spdx.org/licenses/BUSL-1.1.html#notes
"CC-BY-NC", # https://people.debian.org/~bap/dfsg-faq.html#no_commercial
"Elastic", # https://www.elastic.co/licensing/elastic-license#Limitations
"SSPL", # https://fedoraproject.org/wiki/Licensing/SSPL#License_Notes
].freeze
def audit_license
if formula.license.present?
licenses, exceptions = SPDX.parse_license_expression formula.license
incompatible_licenses = licenses.select do |license|
license.to_s.start_with?(*INCOMPATIBLE_LICENSE_PREFIXES) || INCOMPATIBLE_LICENSES.include?(license.to_s)
end
if incompatible_licenses.present? && @core_tap
problem <<~EOS
Formula #{formula.name} contains incompatible licenses: #{incompatible_licenses}.
Formulae in homebrew/core must either use a Debian Free Software Guidelines license
or be released into the public domain: #{Formatter.url("https://docs.brew.sh/License-Guidelines")}
EOS
end
non_standard_licenses = licenses.reject { |license| SPDX.valid_license? license }
if non_standard_licenses.present?
problem <<~EOS
Formula #{formula.name} contains non-standard SPDX licenses: #{non_standard_licenses}.
For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")}
EOS
end
if @strict || @core_tap
deprecated_licenses = licenses.select do |license|
SPDX.deprecated_license? license
end
if deprecated_licenses.present?
problem <<~EOS
Formula #{formula.name} contains deprecated SPDX licenses: #{deprecated_licenses}.
You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`).
For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")}
EOS
end
end
invalid_exceptions = exceptions.reject { |exception| SPDX.valid_license_exception? exception }
if invalid_exceptions.present?
problem <<~EOS
Formula #{formula.name} contains invalid or deprecated SPDX license exceptions: #{invalid_exceptions}.
For a list of valid license exceptions check:
#{Formatter.url("https://spdx.org/licenses/exceptions-index.html")}
EOS
end
return unless @online
user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*})
return if user.blank?
tag = SharedAudits.github_tag_from_url(formula.stable.url)
tag ||= formula.stable.specs[:tag]
github_license = GitHub.get_repo_license(user, repo, ref: tag)
return unless github_license
return if (licenses + ["NOASSERTION"]).include?(github_license)
return if PERMITTED_LICENSE_MISMATCHES[github_license]&.any? { |license| licenses.include? license }
return if formula.tap&.audit_exception :permitted_formula_license_mismatches, formula.name
problem "Formula license #{licenses} does not match GitHub license #{Array(github_license)}."
elsif @core_tap && !formula.disabled?
problem "Formulae in homebrew/core must specify a license."
end
end
def audit_deps
@specs.each do |spec|
# Check for things we don't like to depend on.
# We allow non-Homebrew installs whenever possible.
spec.declared_deps.each do |dep|
begin
dep_f = dep.to_formula
rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap dependencies
next
rescue FormulaUnavailableError
problem "Can't find dependency '#{dep.name}'."
next
rescue TapFormulaAmbiguityError
problem "Ambiguous dependency '#{dep.name}'."
next
end
if dep_f.oldnames.include?(dep.name.split("/").last)
problem "Dependency '#{dep.name}' was renamed; use new name '#{dep_f.name}'."
end
if @core_tap &&
@new_formula &&
!dep.uses_from_macos? &&
dep_f.keg_only? &&
dep_f.keg_only_reason.provided_by_macos? &&
dep_f.keg_only_reason.applicable? &&
formula.requirements.none?(LinuxRequirement) &&
!formula.tap&.audit_exception(:provided_by_macos_depends_on_allowlist, dep.name)
new_formula_problem(
"Dependency '#{dep.name}' is provided by macOS; " \
"please replace 'depends_on' with 'uses_from_macos'.",
)
end
dep.options.each do |opt|
next if @core_tap
next if dep_f.option_defined?(opt)
next if dep_f.requirements.find do |r|
if r.recommended?
opt.name == "with-#{r.name}"
elsif r.optional?
opt.name == "without-#{r.name}"
end
end
problem "Dependency '#{dep}' does not define option: #{opt.name.inspect}"
end
problem "Don't use 'git' as a dependency (it's always available)" if @new_formula && dep.name == "git"
dep.tags.each do |tag|
if [:run, :linked].include?(tag)
problem "Dependency '#{dep.name}' is marked as :#{tag}. Remove :#{tag}; it is a no-op."
elsif tag.is_a?(Symbol) && Dependable::RESERVED_TAGS.exclude?(tag)
problem "Dependency '#{dep.name}' is marked as :#{tag} which is not a valid tag."
end
end
next unless @core_tap
if dep_f.tap.nil?
problem <<~EOS
Dependency '#{dep.name}' does not exist in any tap.
EOS
elsif !dep_f.tap.core_tap?
problem <<~EOS
Dependency '#{dep.name}' is not in homebrew/core. Formulae in homebrew/core
should not have dependencies in external taps.
EOS
end
if dep_f.deprecated? && !formula.deprecated? && !formula.disabled?
problem <<~EOS
Dependency '#{dep.name}' is deprecated but has un-deprecated dependents. Either
un-deprecate '#{dep.name}' or deprecate it and all of its dependents.
EOS
end
if dep_f.disabled? && !formula.disabled?
problem <<~EOS
Dependency '#{dep.name}' is disabled but has un-disabled dependents. Either
un-disable '#{dep.name}' or disable it and all of its dependents.
EOS
end
# we want to allow uses_from_macos for aliases but not bare dependencies.
# we also allow `pkg-config` for backwards compatibility in external taps.
if self.class.aliases.include?(dep.name) && !dep.uses_from_macos? && (dep.name != "pkg-config" || @core_tap)
problem "Dependency '#{dep.name}' is an alias; use the canonical name '#{dep.to_formula.full_name}'."
end
if dep.tags.include?(:recommended) || dep.tags.include?(:optional)
problem "Formulae in homebrew/core should not have optional or recommended dependencies"
end
end
next unless @core_tap
if spec.requirements.map(&:recommended?).any? || spec.requirements.map(&:optional?).any?
problem "Formulae in homebrew/core should not have optional or recommended requirements"
end
end
return unless @core_tap
return if formula.tap&.audit_exception :versioned_dependencies_conflicts_allowlist, formula.name
# The number of conflicts on Linux is absurd.
# TODO: remove this and check these there too.
return if Homebrew::SimulateSystem.simulating_or_running_on_linux?
# Skip the versioned dependencies conflict audit for *-staging branches.
# This will allow us to migrate dependents of formulae like Python or OpenSSL
# gradually over separate PRs which target a *-staging branch. See:
# https://github.com/Homebrew/homebrew-core/pull/134260
ignore_formula_conflict, staging_formula =
if @tap_audit && (github_event_path = ENV.fetch("GITHUB_EVENT_PATH", nil)).present?
event_payload = JSON.parse(File.read(github_event_path))
base_info = event_payload.dig("pull_request", "base").to_h # handle `nil`
# We need to read the head ref from `GITHUB_EVENT_PATH` because
# `git branch --show-current` returns the default branch on PR branches.
staging_branch = base_info["ref"]&.end_with?("-staging")
homebrew_owned_repo = base_info.dig("repo", "owner", "login") == "Homebrew"
homebrew_core_pr = base_info.dig("repo", "name") == "homebrew-core"
# Support staging branches named `formula-staging` or `formula@version-staging`.
base_formula = base_info["ref"]&.split(/-|@/, 2)&.first
[staging_branch && homebrew_owned_repo && homebrew_core_pr, base_formula]
end
recursive_runtime_formulae = formula.runtime_formula_dependencies(undeclared: false)
version_hash = {}
version_conflicts = Set.new
recursive_runtime_formulae.each do |f|
name = f.name
unversioned_name, = name.split("@")
next if ignore_formula_conflict && unversioned_name == staging_formula
# Allow use of the full versioned name (e.g. `python@3.99`) or an unversioned alias (`python`).
next if formula.tap&.audit_exception :versioned_formula_dependent_conflicts_allowlist, name
next if formula.tap&.audit_exception :versioned_formula_dependent_conflicts_allowlist, unversioned_name
version_hash[unversioned_name] ||= Set.new
version_hash[unversioned_name] << name
next if version_hash[unversioned_name].length < 2
version_conflicts += version_hash[unversioned_name]
end
return if version_conflicts.empty?
return if formula.disabled?
return if formula.deprecated? &&
formula.deprecation_reason != DeprecateDisable::FORMULA_DEPRECATE_DISABLE_REASONS[:versioned_formula]
problem <<~EOS
#{formula.full_name} contains conflicting version recursive dependencies:
#{version_conflicts.to_a.join ", "}
View these with `brew deps --tree #{formula.full_name}`.
EOS
end
def audit_conflicts
tap = formula.tap
formula.conflicts.each do |conflict|
conflicting_formula = Formulary.factory(conflict.name)
next if tap != conflicting_formula.tap
problem "Formula should not conflict with itself" if formula == conflicting_formula
if T.must(tap).formula_renames.key?(conflict.name) || T.must(tap).aliases.include?(conflict.name)
problem "Formula conflict should be declared using " \
"canonical name (#{conflicting_formula.name}) instead of '#{conflict.name}'"
end
reverse_conflict_found = T.let(false, T::Boolean)
conflicting_formula.conflicts.each do |reverse_conflict|
reverse_conflict_formula = Formulary.factory(reverse_conflict.name)
if T.must(tap).formula_renames.key?(reverse_conflict.name) ||
T.must(tap).aliases.include?(reverse_conflict.name)
problem "Formula #{conflicting_formula.name} conflict should be declared using " \
"canonical name (#{reverse_conflict_formula.name}) instead of '#{reverse_conflict.name}'"
end
reverse_conflict_found ||= reverse_conflict_formula == formula
end
unless reverse_conflict_found
problem "Formula #{conflicting_formula.name} should also have a conflict declared with #{formula.name}"
end
rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap conflicts.
next
rescue FormulaUnavailableError
problem "Can't find conflicting formula #{conflict.name.inspect}."
rescue TapFormulaAmbiguityError
problem "Ambiguous conflicting formula #{conflict.name.inspect}."
end
end
def audit_gcc_dependency
return unless @core_tap
return unless Homebrew::SimulateSystem.simulating_or_running_on_linux?
return unless linux_only_gcc_dep?(formula)
# https://github.com/Homebrew/homebrew-core/pull/171634
# https://github.com/nghttp2/nghttp2/issues/2194
return if formula.tap&.audit_exception(:linux_only_gcc_dependency_allowlist, formula.name)
problem "Formulae in homebrew/core should not have a Linux-only dependency on GCC."
end
def audit_glibc
return unless @core_tap
return if formula.name != "glibc"
# Also allow LINUX_GLIBC_NEXT_CI_VERSION for when we're upgrading.
return if [OS::LINUX_GLIBC_CI_VERSION, OS::LINUX_GLIBC_NEXT_CI_VERSION].include?(formula.version.to_s)
problem "The glibc version must be #{OS::LINUX_GLIBC_CI_VERSION}, as needed by our CI on Linux. " \
"The glibc formula is for users who have a system glibc with a lower version, " \
"which allows them to use our Linux bottles, which were compiled against system glibc on CI."
end
def audit_relicensed_formulae
return unless @core_tap
relicensed_version = formula.tap&.audit_exception :relicensed_formulae_versions, formula.name
return unless relicensed_version
return if formula.version < Version.new(relicensed_version)
problem "#{formula.name} was relicensed to a non-open-source license from version #{relicensed_version}. " \
"It must not be upgraded to version #{relicensed_version} or newer."
end
def audit_versioned_keg_only
return unless @versioned_formula
return unless @core_tap
if formula.keg_only?
return if formula.keg_only_reason.versioned_formula?
return if formula.name.start_with?("openssl", "libressl") && formula.keg_only_reason.by_macos?
end
return if formula.tap&.audit_exception :versioned_keg_only_allowlist, formula.name
problem "Versioned formulae in homebrew/core should use `keg_only :versioned_formula`"
end
def audit_homepage
homepage = formula.homepage
return if homepage.blank?
return unless @online
return if formula.tap&.audit_exception :cert_error_allowlist, formula.name, homepage
return unless DevelopmentTools.curl_handles_most_https_certificates?
# Skip gnu.org and nongnu.org audit on GitHub runners
# See issue: https://github.com/Homebrew/homebrew-core/issues/206757
github_runner = GitHub::Actions.env_set? && !ENV["GITHUB_ACTIONS_HOMEBREW_SELF_HOSTED"]
return if homepage.match?(%r{^https?://www\.(?:non)?gnu\.org/.+}) && github_runner
use_homebrew_curl = [:stable, :head].any? do |spec_name|
next false unless (spec = formula.send(spec_name))
spec.using == :homebrew_curl
end
if (http_content_problem = curl_check_http_content(
homepage,
SharedAudits::URL_TYPE_HOMEPAGE,
user_agents: [:browser, :default],
check_content: true,
strict: @strict,
use_homebrew_curl:,
))
problem http_content_problem
end
end
def audit_bottle_spec
# special case: new versioned formulae should be audited
return unless @new_formula_inclusive
return unless @core_tap
return unless formula.bottle_defined?
new_formula_problem "New formulae in homebrew/core should not have a `bottle do` block"
end
def audit_eol
return unless @online
return unless @core_tap
return if formula.deprecated? || formula.disabled?
name = if formula.versioned_formula?
formula.name.split("@").first
else
formula.name
end
return if formula.tap&.audit_exception :eol_date_blocklist, name
metadata = SharedAudits.eol_data(name, formula.version.major.to_s)
metadata ||= SharedAudits.eol_data(name, formula.version.major_minor.to_s)
return if metadata.blank? || (metadata.dig("result", "isEol") != true)
eol_from = metadata.dig("result", "eolFrom")
eol_date = Date.parse(eol_from) if eol_from.present?
message = "Product is EOL"
message += " since #{eol_date}" if eol_date.present?
message += ", see #{Formatter.url("https://endoflife.date/#{name}")}"
problem message
end
def audit_wayback_url
return unless @core_tap
return if formula.deprecated? || formula.disabled?
regex = %r{^https?://web\.archive\.org}
problem_prefix = "Formula with a Internet Archive Wayback Machine"
problem "#{problem_prefix} `url` should be deprecated with `:repo_removed`" if regex.match?(formula.stable.url)
if regex.match?(formula.homepage)
problem "#{problem_prefix} `homepage` should find an alternative `homepage` or be deprecated."
end
return unless formula.head
return unless regex.match?(formula.head.url)
problem "Remove Internet Archive Wayback Machine `head` URL"
end
def audit_github_repository_archived
return if formula.deprecated? || formula.disabled?
user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @online
return if user.blank?
metadata = SharedAudits.github_repo_data(user, repo)
return if metadata.nil?
problem "GitHub repository is archived" if metadata["archived"]
end
def audit_gitlab_repository_archived
return if formula.deprecated? || formula.disabled?
user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @online
return if user.blank?
metadata = SharedAudits.gitlab_repo_data(user, repo)
return if metadata.nil?
problem "GitLab repository is archived" if metadata["archived"]
end
sig { void }
def audit_forgejo_repository_archived
return if formula.deprecated? || formula.disabled?
user, repo = get_repo_data(%r{https?://codeberg\.org/([^/]+)/([^/]+)/?.*}) if @online
return if user.blank?
metadata = SharedAudits.forgejo_repo_data(user, repo)
return if metadata.nil?
problem "Forgejo repository is archived since #{metadata["archived_at"]}" if metadata["archived"]
end
def audit_github_repository
user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @new_formula
return if user.blank?
warning = SharedAudits.github(user, repo)
return if warning.nil?
new_formula_problem warning
end
def audit_gitlab_repository
user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @new_formula
return if user.blank?
warning = SharedAudits.gitlab(user, repo)
return if warning.nil?
new_formula_problem warning
end
def audit_bitbucket_repository
user, repo = get_repo_data(%r{https?://bitbucket\.org/([^/]+)/([^/]+)/?.*}) if @new_formula
return if user.blank?
warning = SharedAudits.bitbucket(user, repo)
return if warning.nil?
new_formula_problem warning
end
sig { void }
def audit_forgejo_repository
user, repo = get_repo_data(%r{https?://codeberg\.org/([^/]+)/([^/]+)/?.*}) if @new_formula
return if user.blank?
warning = SharedAudits.forgejo(user, repo)
return if warning.nil?
new_formula_problem warning
end
def get_repo_data(regex)
return unless @core_tap
return unless @online
_, user, repo = *regex.match(formula.stable.url) if formula.stable
_, user, repo = *regex.match(formula.homepage) unless user
_, user, repo = *regex.match(formula.head.url) if !user && formula.head
return if !user || !repo
repo.delete_suffix!(".git")
[user, repo]
end
def audit_specs
problem "HEAD-only (no stable download)" if head_only?(formula) && @core_tap
%w[Stable HEAD].each do |name|
spec_name = name.downcase.to_sym
next unless (spec = formula.send(spec_name))
except = @except.to_a
if spec_name == :head &&
formula.tap&.audit_exception(:head_non_default_branch_allowlist, formula.name, spec.specs[:branch])
except << "head_branch"
end
ra = ResourceAuditor.new(
spec, spec_name,
online: @online, strict: @strict, only: @only, core_tap: @core_tap, except:,
use_homebrew_curl: spec.using == :homebrew_curl
).audit
ra.problems.each do |message|
problem "#{name}: #{message}"
end
spec.resources.each_value do |resource|
problem "Resource name should be different from the formula name" if resource.name == formula.name
ra = ResourceAuditor.new(
resource, spec_name,
online: @online, strict: @strict, only: @only, except: @except,
use_homebrew_curl: resource.using == :homebrew_curl
).audit
ra.problems.each do |message|
problem "#{name} resource #{resource.name.inspect}: #{message}"
end
end
next if spec.patches.empty?
next if !@new_formula || !@core_tap
new_formula_problem(
"Formulae should not require patches to build. " \
"Patches should be submitted and accepted upstream first.",
)
end
return unless @core_tap
if formula.head && @versioned_formula &&
!formula.tap&.audit_exception(:versioned_head_spec_allowlist, formula.name)
problem "Versioned formulae should not have a `head` spec"
end
stable = formula.stable
return unless stable
return unless stable.url
version = stable.version
problem "Stable: version (#{version}) is set to a string without a digit" unless /\d/.match?(version.to_s)
stable_version_string = version.to_s
if stable_version_string.start_with?("HEAD")
problem "Stable: non-HEAD version (#{stable_version_string}) should not begin with `HEAD`"
end
stable_url_version = Version.parse(stable.url)
stable_url_minor_version = stable_url_version.minor.to_i
formula_suffix = stable.version.patch.to_i
throttled_rate = formula.livecheck.throttle
if throttled_rate && formula_suffix.modulo(throttled_rate).nonzero?
problem "Should only be updated every #{throttled_rate} releases on multiples of #{throttled_rate}"
end
case (url = stable.url)
when /[\d._-](alpha|beta|rc\d)/
matched = Regexp.last_match(1)
version_prefix = stable_version_string.sub(/\d+$/, "")
return if formula.tap&.audit_exception :unstable_allowlist, formula.name, version_prefix
return if formula.tap&.audit_exception :unstable_devel_allowlist, formula.name, version_prefix
problem "Stable: version URLs should not contain `#{matched}`"
when %r{download\.gnome\.org/sources}, %r{ftp\.gnome\.org/pub/GNOME/sources}i
version_prefix = stable.version.major_minor
return if formula.tap&.audit_exception :gnome_devel_allowlist, formula.name, version_prefix
return if formula.tap&.audit_exception :gnome_devel_allowlist, formula.name, "all"
return if stable_url_version < Version.new("1.0")
# All minor versions are stable in the new GNOME version scheme (which starts at version 40.0)
# https://discourse.gnome.org/t/new-gnome-versioning-scheme/4235
return if stable_url_version >= Version.new("40.0")
return if stable_url_minor_version.even?
problem "Stable: version (#{stable.version}) is a development release"
when %r{isc.org/isc/bind\d*/}i
return if stable_url_minor_version.even?
problem "Stable: version (#{stable.version}) is a development release"
when %r{https?://gitlab\.com/([\w-]+)/([\w-]+)}
owner = T.must(Regexp.last_match(1))
repo = T.must(Regexp.last_match(2))
tag = SharedAudits.gitlab_tag_from_url(url)
tag ||= stable.specs[:tag]
tag ||= stable.version.to_s
if @online
error = SharedAudits.gitlab_release(owner, repo, tag, formula:)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/PATH.rb | Library/Homebrew/PATH.rb | # typed: strict
# frozen_string_literal: true
require "forwardable"
# Representation of a `*PATH` environment variable.
class PATH
include Enumerable
extend Forwardable
extend T::Generic
delegate each: :@paths
Elem = type_member(:out) { { fixed: String } }
Element = T.type_alias { T.nilable(T.any(Pathname, String, PATH)) }
private_constant :Element
Elements = T.type_alias { T.any(Element, T::Array[Element]) }
sig { params(paths: Elements).void }
def initialize(*paths)
@paths = T.let(parse(paths), T::Array[String])
end
sig { params(paths: Elements).returns(T.self_type) }
def prepend(*paths)
@paths = parse(paths + @paths)
self
end
sig { params(paths: Elements).returns(T.self_type) }
def append(*paths)
@paths = parse(@paths + paths)
self
end
sig { params(index: Integer, paths: Elements).returns(T.self_type) }
def insert(index, *paths)
@paths = parse(@paths.insert(index, *paths))
self
end
sig { params(block: T.proc.params(arg0: String).returns(BasicObject)).returns(T.self_type) }
def select(&block)
self.class.new(@paths.select(&block))
end
sig { params(block: T.proc.params(arg0: String).returns(BasicObject)).returns(T.self_type) }
def reject(&block)
self.class.new(@paths.reject(&block))
end
sig { returns(T::Array[String]) }
def to_ary
@paths.dup.to_ary
end
alias to_a to_ary
sig { returns(String) }
def to_str
@paths.join(File::PATH_SEPARATOR)
end
sig { returns(String) }
def to_s = to_str
sig { params(other: T.untyped).returns(T::Boolean) }
def ==(other)
(other.respond_to?(:to_ary) && to_ary == other.to_ary) ||
(other.respond_to?(:to_str) && to_str == other.to_str) ||
false
end
sig { returns(T::Boolean) }
def empty?
@paths.empty?
end
sig { returns(T.nilable(T.self_type)) }
def existing
existing_path = select { File.directory?(it) }
# return nil instead of empty PATH, to unset environment variables
existing_path unless existing_path.empty?
end
private
sig { params(paths: T::Array[Elements]).returns(T::Array[String]) }
def parse(paths)
paths.flatten
.compact
.flat_map { |p| Pathname(p).to_path.split(File::PATH_SEPARATOR) }
.uniq
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/system_config.rb | Library/Homebrew/system_config.rb | # typed: strict
# frozen_string_literal: true
require "hardware"
require "software_spec"
require "development_tools"
require "extend/ENV"
require "system_command"
require "git_repository"
# Helper module for querying information about the system configuration.
module SystemConfig
class << self
include SystemCommand::Mixin
sig { void }
def initialize
@clang = T.let(nil, T.nilable(Version))
@clang_build = T.let(nil, T.nilable(Version))
end
sig { returns(Version) }
def clang
@clang ||= if DevelopmentTools.installed?
DevelopmentTools.clang_version
else
Version::NULL
end
end
sig { returns(Version) }
def clang_build
@clang_build ||= if DevelopmentTools.installed?
DevelopmentTools.clang_build_version
else
Version::NULL
end
end
sig { returns(GitRepository) }
def homebrew_repo
GitRepository.new(HOMEBREW_REPOSITORY)
end
sig { returns(String) }
def branch
homebrew_repo.branch_name || "(none)"
end
sig { returns(String) }
def head
homebrew_repo.head_ref || "(none)"
end
sig { returns(String) }
def last_commit
homebrew_repo.last_committed || "never"
end
sig { returns(String) }
def origin
homebrew_repo.origin_url || "(none)"
end
sig { returns(String) }
def describe_clang
return "N/A" if clang.null?
if clang_build.null?
clang.to_s
else
"#{clang} build #{clang_build}"
end
end
sig { params(path: T.nilable(Pathname)).returns(String) }
def describe_path(path)
return "N/A" if path.nil?
realpath = path.realpath
if realpath == path
path.to_s
else
"#{path} => #{realpath}"
end
end
sig { returns(String) }
def describe_homebrew_ruby
"#{RUBY_VERSION} => #{RUBY_PATH}"
end
sig { returns(T.nilable(String)) }
def hardware
return if Hardware::CPU.type == :dunno
"CPU: #{Hardware.cores_as_words}-core #{Hardware::CPU.bits}-bit #{Hardware::CPU.family}"
end
sig { returns(String) }
def kernel
`uname -m`.chomp
end
sig { returns(String) }
def describe_git
return "N/A" unless Utils::Git.available?
"#{Utils::Git.version} => #{Utils::Git.path}"
end
sig { returns(String) }
def describe_curl
out = system_command(Utils::Curl.curl_executable, args: ["--version"], verbose: false).stdout
match_data = /^curl (?<curl_version>[\d.]+)/.match(out)
if match_data
"#{match_data[:curl_version]} => #{Utils::Curl.curl_path}"
else
"N/A"
end
end
sig { params(tap: Tap, out: T.any(File, StringIO, IO)).void }
def dump_tap_config(tap, out = $stdout)
case tap
when CoreTap
tap_name = "Core tap"
json_file_name = "formula.jws.json"
when CoreCaskTap
tap_name = "Core cask tap"
json_file_name = "cask.jws.json"
else
raise ArgumentError, "Unknown tap: #{tap}"
end
if tap.installed?
out.puts "#{tap_name} origin: #{tap.remote}" if tap.remote != tap.default_remote
out.puts "#{tap_name} HEAD: #{tap.git_head || "(none)"}"
out.puts "#{tap_name} last commit: #{tap.git_last_commit || "never"}"
default_branches = %w[main master].freeze
out.puts "#{tap_name} branch: #{tap.git_branch || "(none)"}" if default_branches.exclude?(tap.git_branch)
end
json_file = Homebrew::API::HOMEBREW_CACHE_API/json_file_name
if json_file.exist?
out.puts "#{tap_name} JSON: #{json_file.mtime.utc.strftime("%d %b %H:%M UTC")}"
elsif !tap.installed?
out.puts "#{tap_name}: N/A"
end
end
sig { params(out: T.any(File, StringIO, IO)).void }
def core_tap_config(out = $stdout)
dump_tap_config(CoreTap.instance, out)
end
sig { params(out: T.any(File, StringIO, IO)).void }
def homebrew_config(out = $stdout)
out.puts "HOMEBREW_VERSION: #{HOMEBREW_VERSION}"
out.puts "ORIGIN: #{origin}"
out.puts "HEAD: #{head}"
out.puts "Last commit: #{last_commit}"
out.puts "Branch: #{branch}"
end
sig { params(out: T.any(File, StringIO, IO)).void }
def homebrew_env_config(out = $stdout)
out.puts "HOMEBREW_PREFIX: #{HOMEBREW_PREFIX}"
{
HOMEBREW_REPOSITORY: Homebrew::DEFAULT_REPOSITORY,
HOMEBREW_CELLAR: Homebrew::DEFAULT_CELLAR,
}.freeze.each do |key, default|
value = Object.const_get(key)
out.puts "#{key}: #{value}" if value.to_s != default.to_s
end
Homebrew::EnvConfig::ENVS.each do |env, hash|
method_name = Homebrew::EnvConfig.env_method_name(env, hash)
if hash[:boolean]
out.puts "#{env}: set" if Homebrew::EnvConfig.send(method_name)
next
end
value = Homebrew::EnvConfig.send(method_name)
next unless value
next if (default = hash[:default].presence) && value.to_s == default.to_s
if ENV.sensitive?(env)
out.puts "#{env}: set"
else
out.puts "#{env}: #{value}"
end
end
out.puts "Homebrew Ruby: #{describe_homebrew_ruby}"
end
sig { params(out: T.any(File, StringIO, IO)).void }
def host_software_config(out = $stdout)
out.puts "Clang: #{describe_clang}"
out.puts "Git: #{describe_git}"
out.puts "Curl: #{describe_curl}"
end
sig { params(out: T.any(File, StringIO, IO)).void }
def dump_verbose_config(out = $stdout)
homebrew_config(out)
core_tap_config(out)
homebrew_env_config(out)
out.puts hardware if hardware
host_software_config(out)
end
end
end
require "extend/os/system_config"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/downloadable.rb | Library/Homebrew/downloadable.rb | # typed: strict
# frozen_string_literal: true
require "url"
require "checksum"
require "download_strategy"
require "utils/output"
module Downloadable
include Context
include Utils::Output::Mixin
extend T::Helpers
abstract!
requires_ancestor { Kernel }
sig { overridable.returns(T.nilable(T.any(String, URL))) }
attr_reader :url
sig { overridable.returns(T.nilable(Checksum)) }
attr_reader :checksum
sig { overridable.returns(T::Array[String]) }
attr_reader :mirrors
sig { overridable.returns(Symbol) }
attr_accessor :phase
sig { void }
def downloading! = (@phase = :downloading)
sig { void }
def downloaded! = (@phase = :downloaded)
sig { void }
def verifying! = (@phase = :verifying)
sig { void }
def verified! = (@phase = :verified)
sig { void }
def extracting! = (@phase = :extracting)
sig { void }
def initialize
@url = T.let(nil, T.nilable(URL))
@checksum = T.let(nil, T.nilable(Checksum))
@mirrors = T.let([], T::Array[String])
@version = T.let(nil, T.nilable(Version))
@download_strategy = T.let(nil, T.nilable(T::Class[AbstractDownloadStrategy]))
@downloader = T.let(nil, T.nilable(AbstractDownloadStrategy))
@download_name = T.let(nil, T.nilable(String))
@phase = T.let(:preparing, Symbol)
end
sig { overridable.params(other: Downloadable).void }
def initialize_dup(other)
super
@checksum = @checksum.dup
@mirrors = @mirrors.dup
@version = @version.dup
end
sig { overridable.returns(T.self_type) }
def freeze
@checksum.freeze
@mirrors.freeze
@version.freeze
super
end
sig { returns(String) }
def download_queue_name = download_name
sig { abstract.returns(String) }
def download_queue_type; end
sig(:final) { returns(String) }
def download_queue_message
"#{download_queue_type} #{download_queue_name}"
end
sig(:final) { returns(T::Boolean) }
def downloaded?
cached_download.exist?
end
sig { overridable.returns(Pathname) }
def cached_download
downloader.cached_location
end
sig { overridable.void }
def clear_cache
downloader.clear_cache
end
# Total bytes downloaded if available.
sig { overridable.returns(T.nilable(Integer)) }
def fetched_size
downloader.fetched_size
end
# Total download size if available.
sig { overridable.returns(T.nilable(Integer)) }
def total_size
@total_size ||= T.let(downloader.total_size, T.nilable(Integer))
end
sig { overridable.returns(T.nilable(Version)) }
def version
return @version if @version && !@version.null?
version = determine_url&.version
version unless version&.null?
end
sig { overridable.returns(T::Class[AbstractDownloadStrategy]) }
def download_strategy
@download_strategy ||= T.must(determine_url).download_strategy
end
sig { overridable.returns(AbstractDownloadStrategy) }
def downloader
@downloader ||= begin
primary_url, *mirrors = determine_url_mirrors
raise ArgumentError, "attempted to use a `Downloadable` without a URL!" if primary_url.blank?
download_strategy.new(primary_url, download_name, version,
mirrors:, cache:, **T.must(@url).specs)
end
end
sig {
overridable.params(
verify_download_integrity: T::Boolean,
timeout: T.nilable(T.any(Integer, Float)),
quiet: T::Boolean,
).returns(Pathname)
}
def fetch(verify_download_integrity: true, timeout: nil, quiet: false)
downloading!
cache.mkpath
begin
downloader.quiet! if quiet
downloader.fetch(timeout:)
rescue ErrorDuringExecution, CurlDownloadStrategyError => e
raise DownloadError.new(self, e)
end
downloaded!
download = cached_download
verify_download_integrity(download) if verify_download_integrity
download
end
sig { overridable.params(filename: Pathname).void }
def verify_download_integrity(filename)
verifying!
if filename.file?
ohai "Verifying checksum for '#{filename.basename}'" if verbose?
filename.verify_checksum(checksum)
verified!
end
rescue ChecksumMissingError
return if silence_checksum_missing_error?
opoo <<~EOS
Cannot verify integrity of '#{filename.basename}'.
No checksum was provided.
For your reference, the checksum is:
sha256 "#{filename.sha256}"
EOS
end
sig { returns(Integer) }
def hash
[self.class, cached_download].hash
end
sig { params(other: Object).returns(T::Boolean) }
def eql?(other)
return false if self.class != other.class
other = T.cast(other, Downloadable)
cached_download == other.cached_download
end
sig { returns(String) }
def to_s
short_cached_download = cached_download.to_s
.delete_prefix("#{HOMEBREW_CACHE}/downloads/")
"#<#{self.class}: #{short_cached_download}>"
end
private
sig { overridable.returns(String) }
def download_name
@download_name ||= File.basename(determine_url.to_s).freeze
end
sig { overridable.returns(T::Boolean) }
def silence_checksum_missing_error?
false
end
sig { overridable.returns(T.nilable(URL)) }
def determine_url
@url
end
sig { overridable.returns(T::Array[String]) }
def determine_url_mirrors
[determine_url.to_s, *mirrors].uniq
end
sig { overridable.returns(Pathname) }
def cache
HOMEBREW_CACHE
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/unlink.rb | Library/Homebrew/unlink.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
# Provides helper methods for unlinking formulae and kegs with consistent output.
module Unlink
sig { params(formula: Formula, verbose: T::Boolean).void }
def self.unlink_versioned_formulae(formula, verbose: false)
formula.versioned_formulae
.select(&:keg_only?)
.select(&:linked?)
.filter_map(&:any_installed_keg)
.select(&:directory?)
.each do |keg|
unlink(keg, verbose:)
end
end
sig { params(keg: Keg, dry_run: T::Boolean, verbose: T::Boolean).void }
def self.unlink(keg, dry_run: false, verbose: false)
options = { dry_run:, verbose: }
keg.lock do
print "Unlinking #{keg}... "
puts if verbose
puts "#{keg.unlink(**options)} symlinks removed."
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/formulary.rb | Library/Homebrew/formulary.rb | # typed: strict
# frozen_string_literal: true
require "digest/sha2"
require "cachable"
require "tab"
require "utils"
require "utils/bottles"
require "utils/output"
require "utils/path"
require "service"
require "utils/curl"
require "deprecate_disable"
require "extend/hash/deep_transform_values"
require "extend/hash/keys"
require "tap"
# The {Formulary} is responsible for creating instances of {Formula}.
# It is not meant to be used directly from formulae.
module Formulary
extend Context
extend Cachable
extend Utils::Output::Mixin
include Utils::Output::Mixin
ALLOWED_URL_SCHEMES = %w[file].freeze
private_constant :ALLOWED_URL_SCHEMES
# Enable the factory cache.
#
# @api internal
sig { void }
def self.enable_factory_cache!
@factory_cache_enabled = T.let(true, T.nilable(TrueClass))
cache[platform_cache_tag] ||= {}
cache[platform_cache_tag][:formulary_factory] ||= {}
end
sig { returns(T::Boolean) }
def self.factory_cached?
!!@factory_cache_enabled
end
sig { returns(String) }
def self.platform_cache_tag
"#{Homebrew::SimulateSystem.current_os}_#{Homebrew::SimulateSystem.current_arch}"
end
private_class_method :platform_cache_tag
sig {
returns({
api: T.nilable(T::Hash[String, T.class_of(Formula)]),
# TODO: the hash values should be Formula instances, but the linux tests were failing
formulary_factory: T.nilable(T::Hash[String, T.untyped]),
path: T.nilable(T::Hash[String, T.class_of(Formula)]),
stub: T.nilable(T::Hash[String, T.class_of(Formula)]),
})
}
def self.platform_cache
cache[platform_cache_tag] ||= {}
end
sig { returns(T::Hash[String, Formula]) }
def self.factory_cache
cache[platform_cache_tag] ||= {}
cache[platform_cache_tag][:formulary_factory] ||= {}
end
sig { params(path: T.any(String, Pathname)).returns(T::Boolean) }
def self.formula_class_defined_from_path?(path)
platform_cache.key?(:path) && platform_cache.fetch(:path).key?(path.to_s)
end
sig { params(name: String).returns(T::Boolean) }
def self.formula_class_defined_from_api?(name)
platform_cache.key?(:api) && platform_cache.fetch(:api).key?(name)
end
sig { params(name: String).returns(T::Boolean) }
def self.formula_class_defined_from_stub?(name)
platform_cache.key?(:stub) && platform_cache.fetch(:stub).key?(name)
end
sig { params(path: T.any(String, Pathname)).returns(T.class_of(Formula)) }
def self.formula_class_get_from_path(path)
platform_cache.fetch(:path).fetch(path.to_s)
end
sig { params(name: String).returns(T.class_of(Formula)) }
def self.formula_class_get_from_api(name)
platform_cache.fetch(:api).fetch(name)
end
sig { params(name: String).returns(T.class_of(Formula)) }
def self.formula_class_get_from_stub(name)
platform_cache.fetch(:stub).fetch(name)
end
sig { void }
def self.clear_cache
platform_cache.each do |type, cached_objects|
next if type == :formulary_factory
cached_objects.each_value do |klass|
class_name = klass.name
# Already removed from namespace.
next if class_name.nil?
namespace = Utils.deconstantize(class_name)
next if Utils.deconstantize(namespace) != name
remove_const(Utils.demodulize(namespace).to_sym)
end
end
super
end
sig {
params(
name: String,
path: Pathname,
contents: String,
namespace: String,
flags: T::Array[String],
ignore_errors: T::Boolean,
).returns(T.class_of(Formula))
}
def self.load_formula(name, path, contents, namespace, flags:, ignore_errors:)
raise "Formula loading disabled by `$HOMEBREW_DISABLE_LOAD_FORMULA`!" if Homebrew::EnvConfig.disable_load_formula?
require "formula"
require "ignorable"
require "stringio"
# Capture stdout to prevent formulae from printing to stdout unexpectedly.
old_stdout = $stdout
$stdout = StringIO.new
mod = Module.new
namespace = namespace.to_sym
remove_const(namespace) if const_defined?(namespace)
const_set(namespace, mod)
eval_formula = lambda do
# Set `BUILD_FLAGS` in the formula's namespace so we can
# access them from within the formula's class scope.
mod.const_set(:BUILD_FLAGS, flags)
mod.module_eval(contents, path.to_s)
rescue NameError, ArgumentError, ScriptError, MethodDeprecatedError, MacOSVersion::Error => e
if e.is_a?(Ignorable::ExceptionMixin)
e.ignore
else
remove_const(namespace)
raise FormulaUnreadableError.new(name, e)
end
end
if ignore_errors
Ignorable.hook_raise(&eval_formula)
else
eval_formula.call
end
class_name = class_s(name)
begin
mod.const_get(class_name)
rescue NameError => e
class_list = mod.constants
.map { |const_name| mod.const_get(const_name) }
.grep(Class)
new_exception = FormulaClassUnavailableError.new(name, path, class_name, class_list)
remove_const(namespace)
raise new_exception, "", e.backtrace
end
ensure
# TODO: Make printing to stdout an error so that we can print a tap name.
# See discussion at https://github.com/Homebrew/brew/pull/20226#discussion_r2195886888
if (printed_to_stdout = $stdout.string.strip.presence)
opoo <<~WARNING
Formula #{name} attempted to print the following while being loaded:
#{printed_to_stdout}
WARNING
end
$stdout = old_stdout
end
sig { params(identifier: String).returns(String) }
def self.namespace_key(identifier)
Digest::SHA2.hexdigest(
"#{Homebrew::SimulateSystem.current_os}_#{Homebrew::SimulateSystem.current_arch}:#{identifier}",
)
end
sig { params(string: String).returns(String) }
def self.replace_placeholders(string)
string.gsub(HOMEBREW_PREFIX_PLACEHOLDER, HOMEBREW_PREFIX)
.gsub(HOMEBREW_CELLAR_PLACEHOLDER, HOMEBREW_CELLAR)
.gsub(HOMEBREW_HOME_PLACEHOLDER, Dir.home)
end
sig {
params(name: String, path: Pathname, flags: T::Array[String], ignore_errors: T::Boolean)
.returns(T.class_of(Formula))
}
def self.load_formula_from_path(name, path, flags:, ignore_errors:)
contents = path.open("r") { |f| ensure_utf8_encoding(f).read }
namespace = "FormulaNamespace#{namespace_key(path.to_s)}"
klass = load_formula(name, path, contents, namespace, flags:, ignore_errors:)
platform_cache[:path] ||= {}
platform_cache.fetch(:path)[path.to_s] = klass
end
sig { params(name: String, json_formula_with_variations: T::Hash[String, T.untyped], flags: T::Array[String]).returns(T.class_of(Formula)) }
def self.load_formula_from_json!(name, json_formula_with_variations, flags:)
namespace = :"FormulaNamespaceAPI#{namespace_key(json_formula_with_variations.to_json)}"
mod = Module.new
remove_const(namespace) if const_defined?(namespace)
const_set(namespace, mod)
mod.const_set(:BUILD_FLAGS, flags)
class_name = class_s(name)
formula_struct = Homebrew::API::Formula.generate_formula_struct_hash(json_formula_with_variations)
klass = Class.new(::Formula) do
@loaded_from_api = T.let(true, T.nilable(T::Boolean))
@api_source = T.let(json_formula_with_variations, T.nilable(T::Hash[String, T.untyped]))
desc formula_struct.desc
homepage formula_struct.homepage
license formula_struct.license
revision formula_struct.revision
version_scheme formula_struct.version_scheme
if formula_struct.stable?
stable do
url(*formula_struct.stable_url_args)
version formula_struct.stable_version
if (checksum = formula_struct.stable_checksum)
sha256 checksum
end
formula_struct.stable_dependencies.each do |dep|
depends_on dep
end
formula_struct.stable_uses_from_macos.each do |args|
uses_from_macos(*args)
end
end
end
if formula_struct.head?
head do
url(*formula_struct.head_url_args)
formula_struct.head_dependencies.each do |dep|
depends_on dep
end
formula_struct.head_uses_from_macos.each do |args|
uses_from_macos(*args)
end
end
end
no_autobump!(**formula_struct.no_autobump_args) if formula_struct.no_autobump_message?
if formula_struct.bottle?
bottle do
if Homebrew::EnvConfig.bottle_domain == HOMEBREW_BOTTLE_DEFAULT_DOMAIN
root_url HOMEBREW_BOTTLE_DEFAULT_DOMAIN
else
root_url Homebrew::EnvConfig.bottle_domain
end
rebuild formula_struct.bottle_rebuild
formula_struct.bottle_checksums.each do |args|
sha256(**args)
end
end
end
pour_bottle?(**formula_struct.pour_bottle_args) if formula_struct.pour_bottle?
keg_only(*formula_struct.keg_only_args) if formula_struct.keg_only?
deprecate!(**formula_struct.deprecate_args) if formula_struct.deprecate?
disable!(**formula_struct.disable_args) if formula_struct.disable?
formula_struct.conflicts.each do |name, args|
conflicts_with(name, **args)
end
formula_struct.link_overwrite_paths.each do |path|
link_overwrite path
end
define_method(:install) do
raise NotImplementedError, "Cannot build from source from abstract formula."
end
@post_install_defined_boolean = T.let(formula_struct.post_install_defined, T.nilable(T::Boolean))
define_method(:post_install_defined?) do
self.class.instance_variable_get(:@post_install_defined_boolean)
end
if formula_struct.service?
service do
run(*formula_struct.service_run_args, **formula_struct.service_run_kwargs) if formula_struct.service_run?
name(**formula_struct.service_name_args) if formula_struct.service_name?
formula_struct.service_args.each do |key, arg|
public_send(key, arg)
end
end
end
@caveats_string = T.let(formula_struct.caveats, T.nilable(String))
define_method(:caveats) do
self.class.instance_variable_get(:@caveats_string)
end
@tap_git_head_string = T.let(formula_struct.tap_git_head, T.nilable(String))
define_method(:tap_git_head) do
self.class.instance_variable_get(:@tap_git_head_string)
end
@oldnames_array = T.let(formula_struct.oldnames, T.nilable(T::Array[String]))
define_method(:oldnames) do
self.class.instance_variable_get(:@oldnames_array)
end
@aliases_array = T.let(formula_struct.aliases, T.nilable(T::Array[String]))
define_method(:aliases) do
self.class.instance_variable_get(:@aliases_array)
end
@versioned_formulae_array = T.let(formula_struct.versioned_formulae, T.nilable(T::Array[String]))
define_method(:versioned_formulae_names) do
self.class.instance_variable_get(:@versioned_formulae_array)
end
@ruby_source_path_string = T.let(formula_struct.ruby_source_path, T.nilable(String))
define_method(:ruby_source_path) do
self.class.instance_variable_get(:@ruby_source_path_string)
end
@ruby_source_checksum_string = T.let(formula_struct.ruby_source_checksum, T.nilable(String))
define_method(:ruby_source_checksum) do
checksum = self.class.instance_variable_get(:@ruby_source_checksum_string)
Checksum.new(checksum) if checksum
end
end
mod.const_set(class_name, klass)
platform_cache[:api] ||= {}
platform_cache.fetch(:api)[name] = klass
end
sig { params(name: String, formula_stub: Homebrew::FormulaStub, flags: T::Array[String]).returns(T.class_of(Formula)) }
def self.load_formula_from_stub!(name, formula_stub, flags:)
namespace = :"FormulaNamespaceStub#{namespace_key(formula_stub.to_json)}"
mod = Module.new
remove_const(namespace) if const_defined?(namespace)
const_set(namespace, mod)
mod.const_set(:BUILD_FLAGS, flags)
class_name = class_s(name)
klass = Class.new(::Formula) do
@loaded_from_api = T.let(true, T.nilable(T::Boolean))
@loaded_from_stub = T.let(true, T.nilable(T::Boolean))
url "formula-stub://#{name}/#{formula_stub.pkg_version}"
version formula_stub.version.to_s
revision formula_stub.revision
bottle do
if Homebrew::EnvConfig.bottle_domain == HOMEBREW_BOTTLE_DEFAULT_DOMAIN
root_url HOMEBREW_BOTTLE_DEFAULT_DOMAIN
else
root_url Homebrew::EnvConfig.bottle_domain
end
rebuild formula_stub.rebuild
sha256 Utils::Bottles.tag.to_sym => formula_stub.sha256
end
define_method :install do
raise NotImplementedError, "Cannot build from source from abstract stubbed formula."
end
@aliases_array = formula_stub.aliases
define_method(:aliases) do
self.class.instance_variable_get(:@aliases_array)
end
@oldnames_array = formula_stub.oldnames
define_method(:oldnames) do
self.class.instance_variable_get(:@oldnames_array)
end
end
mod.const_set(class_name, klass)
platform_cache[:stub] ||= {}
platform_cache.fetch(:stub)[name] = klass
end
sig {
params(name: String, spec: T.nilable(Symbol), force_bottle: T::Boolean, flags: T::Array[String], prefer_stub: T::Boolean).returns(Formula)
}
def self.resolve(
name,
spec: nil,
force_bottle: false,
flags: [],
prefer_stub: false
)
if name.include?("/") || File.exist?(name)
f = factory(name, *spec, force_bottle:, flags:, prefer_stub:)
if f.any_version_installed?
tab = Tab.for_formula(f)
resolved_spec = spec || tab.spec
f.active_spec = resolved_spec if f.send(resolved_spec)
f.build = tab
if f.head? && tab.tabfile
k = Keg.new(tab.tabfile.parent)
f.version.update_commit(k.version.version.commit) if k.version.head?
end
end
else
rack = to_rack(name)
alias_path = factory_stub(name, force_bottle:, flags:).alias_path
f = from_rack(rack, *spec, alias_path:, force_bottle:, flags:)
end
# If this formula was installed with an alias that has since changed,
# then it was specified explicitly in ARGV. (Using the alias would
# instead have found the new formula.)
#
# Because of this, the user is referring to this specific formula,
# not any formula targeted by the same alias, so in this context
# the formula shouldn't be considered outdated if the alias used to
# install it has changed.
f.follow_installed_alias = false
f
end
sig { params(io: IO).returns(IO) }
def self.ensure_utf8_encoding(io)
io.set_encoding(Encoding::UTF_8)
end
sig { params(name: String).returns(String) }
def self.class_s(name)
class_name = name.capitalize
class_name.gsub!(/[-_.\s]([a-zA-Z0-9])/) { T.must(Regexp.last_match(1)).upcase }
class_name.tr!("+", "x")
class_name.sub!(/(.)@(\d)/, "\\1AT\\2")
class_name
end
# A {FormulaLoader} returns instances of formulae.
# Subclasses implement loaders for particular sources of formulae.
class FormulaLoader
include Context
include Utils::Output::Mixin
# The formula's name.
sig { returns(String) }
attr_reader :name
# The formula file's path.
sig { returns(Pathname) }
attr_reader :path
# The name used to install the formula.
sig { returns(T.nilable(T.any(Pathname, String))) }
attr_reader :alias_path
# The formula's tap (`nil` if it should be implicitly determined).
sig { returns(T.nilable(Tap)) }
attr_reader :tap
sig {
params(name: String, path: Pathname, alias_path: T.nilable(T.any(Pathname, String)), tap: T.nilable(Tap)).void
}
def initialize(name, path, alias_path: nil, tap: nil)
@name = name
@path = path
@alias_path = alias_path
@tap = tap
end
# Gets the formula instance.
# `alias_path` can be overridden here in case an alias was used to refer to
# a formula that was loaded in another way.
sig {
overridable.params(
spec: Symbol,
alias_path: T.nilable(T.any(Pathname, String)),
force_bottle: T::Boolean,
flags: T::Array[String],
ignore_errors: T::Boolean,
).returns(Formula)
}
def get_formula(spec, alias_path: nil, force_bottle: false, flags: [], ignore_errors: false)
alias_path ||= self.alias_path
alias_path = Pathname(alias_path) if alias_path.is_a?(String)
klass(flags:, ignore_errors:)
.new(name, path, spec, alias_path:, tap:, force_bottle:)
end
sig { overridable.params(flags: T::Array[String], ignore_errors: T::Boolean).returns(T.class_of(Formula)) }
def klass(flags:, ignore_errors:)
load_file(flags:, ignore_errors:) unless Formulary.formula_class_defined_from_path?(path)
Formulary.formula_class_get_from_path(path)
end
private
sig { overridable.params(flags: T::Array[String], ignore_errors: T::Boolean).void }
def load_file(flags:, ignore_errors:)
raise FormulaUnavailableError, name unless path.file?
Formulary.load_formula_from_path(name, path, flags:, ignore_errors:)
end
end
# Loads a formula from a bottle.
class FromBottleLoader < FormulaLoader
include Utils::Output::Mixin
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
return if Homebrew::EnvConfig.forbid_packages_from_paths?
ref = ref.to_s
new(ref) if HOMEBREW_BOTTLES_EXTNAME_REGEX.match?(ref) && File.exist?(ref)
end
sig { params(bottle_name: String, warn: T::Boolean).void }
def initialize(bottle_name, warn: false)
@bottle_path = T.let(Pathname(bottle_name).realpath, Pathname)
name, full_name = Utils::Bottles.resolve_formula_names(@bottle_path)
super name, Formulary.path(full_name)
end
sig {
override.params(
spec: Symbol,
alias_path: T.nilable(T.any(Pathname, String)),
force_bottle: T::Boolean,
flags: T::Array[String],
ignore_errors: T::Boolean,
).returns(Formula)
}
def get_formula(spec, alias_path: nil, force_bottle: false, flags: [], ignore_errors: false)
formula = begin
contents = Utils::Bottles.formula_contents(@bottle_path, name:)
Formulary.from_contents(name, path, contents, spec, force_bottle:,
flags:, ignore_errors:)
rescue FormulaUnreadableError => e
opoo <<~EOS
Unreadable formula in #{@bottle_path}:
#{e}
EOS
super
rescue BottleFormulaUnavailableError => e
opoo <<~EOS
#{e}
Falling back to non-bottle formula.
EOS
super
end
formula.local_bottle_path = @bottle_path
formula
end
end
# Loads formulae from disk using a path.
class FromPathLoader < FormulaLoader
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
path = case ref
when String
Pathname(ref)
when Pathname
ref
else
return
end
return unless path.expand_path.exist?
return unless ::Utils::Path.loadable_package_path?(path, :formula)
if Homebrew::EnvConfig.use_internal_api?
# If the path is for an installed keg, use FromKegLoader instead
begin
keg = Keg.for(path)
loader = FromKegLoader.try_new(keg.name, from:, warn:)
return T.cast(loader, T.attached_class)
rescue NotAKegError
# Not a keg path, continue
end
end
if (tap = Tap.from_path(path))
# Only treat symlinks in taps as aliases.
if path.symlink?
alias_path = path
path = alias_path.resolved_path
end
else
# Don't treat cache symlinks as aliases.
tap = Homebrew::API.tap_from_source_download(path)
end
return if path.extname != ".rb"
new(path, alias_path:, tap:)
end
sig { params(path: T.any(Pathname, String), alias_path: T.nilable(Pathname), tap: T.nilable(Tap)).void }
def initialize(path, alias_path: nil, tap: nil)
path = Pathname(path).expand_path
name = path.basename(".rb").to_s
alias_path = alias_path&.expand_path
alias_dir = alias_path&.dirname
alias_path = nil if alias_dir != tap&.alias_dir
super(name, path, alias_path:, tap:)
end
end
# Loads formula from a URI.
class FromURILoader < FormulaLoader
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
return if Homebrew::EnvConfig.forbid_packages_from_paths?
# Cache compiled regex
@uri_regex ||= T.let(begin
uri_regex = ::URI::RFC2396_PARSER.make_regexp
Regexp.new("\\A#{uri_regex.source}\\Z", uri_regex.options)
end, T.nilable(Regexp))
uri = ref.to_s
return unless uri.match?(@uri_regex)
uri = URI(uri)
return unless uri.path
return unless uri.scheme.present?
new(uri, from:)
end
sig { returns(T.any(URI::Generic, String)) }
attr_reader :url
sig { params(url: T.any(URI::Generic, String), from: T.nilable(Symbol)).void }
def initialize(url, from: nil)
@url = url
@from = from
uri_path = URI(url).path
raise ArgumentError, "URL has no path component" unless uri_path
formula = File.basename(uri_path, ".rb")
super formula, HOMEBREW_CACHE_FORMULA/File.basename(uri_path)
end
sig { override.params(flags: T::Array[String], ignore_errors: T::Boolean).void }
def load_file(flags:, ignore_errors:)
url_scheme = URI(url).scheme
if ALLOWED_URL_SCHEMES.exclude?(url_scheme)
raise UnsupportedInstallationMethod,
"Non-checksummed download of #{name} formula file from an arbitrary URL is unsupported! " \
"Use `brew extract` or `brew create` and `brew tap-new` to create a formula file in a tap " \
"on GitHub instead."
end
HOMEBREW_CACHE_FORMULA.mkpath
FileUtils.rm_f(path)
Utils::Curl.curl_download url.to_s, to: path
super
rescue MethodDeprecatedError => e
if (match_data = url.to_s.match(%r{github.com/(?<user>[\w-]+)/(?<repo>[\w-]+)/}).presence)
e.issues_url = "https://github.com/#{match_data[:user]}/#{match_data[:repo]}/issues/new"
end
raise
end
end
# Loads tapped formulae.
class FromTapLoader < FormulaLoader
sig { returns(Tap) }
attr_reader :tap
sig { returns(Pathname) }
attr_reader :path
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
ref = ref.to_s
return unless (name_tap_type = Formulary.tap_formula_name_type(ref, warn:))
name, tap, type = name_tap_type
path = Formulary.find_formula_in_tap(name, tap)
if type == :alias
# TODO: Simplify this by making `tap_formula_name_type` return the alias name.
alias_name = T.must(ref[HOMEBREW_TAP_FORMULA_REGEX, :name]).downcase
end
if type == :migration && tap.core_tap? && (loader = FromAPILoader.try_new(name))
T.cast(loader, T.attached_class)
else
new(name, path, tap:, alias_name:)
end
end
sig { params(name: String, path: Pathname, tap: Tap, alias_name: T.nilable(String)).void }
def initialize(name, path, tap:, alias_name: nil)
alias_path = tap.alias_dir/alias_name if alias_name
super(name, path, alias_path:, tap:)
@tap = tap
end
sig {
override.params(
spec: Symbol,
alias_path: T.nilable(T.any(Pathname, String)),
force_bottle: T::Boolean,
flags: T::Array[String],
ignore_errors: T::Boolean,
).returns(Formula)
}
def get_formula(spec, alias_path: nil, force_bottle: false, flags: [], ignore_errors: false)
super
rescue FormulaUnreadableError => e
raise TapFormulaUnreadableError.new(tap, name, e.formula_error), "", e.backtrace
rescue FormulaClassUnavailableError => e
raise TapFormulaClassUnavailableError.new(tap, name, e.path, e.class_name, e.class_list), "", e.backtrace
rescue FormulaUnavailableError => e
raise TapFormulaUnavailableError.new(tap, name), "", e.backtrace
end
sig { override.params(flags: T::Array[String], ignore_errors: T::Boolean).void }
def load_file(flags:, ignore_errors:)
super
rescue MethodDeprecatedError => e
e.issues_url = tap.issues_url || tap.to_s
raise
end
end
# Loads a formula from a name, as long as it exists only in a single tap.
class FromNameLoader < FromTapLoader
sig {
override.params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
return unless ref.is_a?(String)
return unless ref.match?(/\A#{HOMEBREW_TAP_FORMULA_NAME_REGEX}\Z/o)
name = ref
# If it exists in the default tap, never treat it as ambiguous with another tap.
if (core_tap = CoreTap.instance).installed? &&
(core_loader = super("#{core_tap}/#{name}", warn:))&.path&.exist?
return core_loader
end
loaders = Tap.select { |tap| tap.installed? && !tap.core_tap? }
.filter_map { |tap| super("#{tap}/#{name}", warn:) }
.uniq(&:path)
.select { |loader| loader.is_a?(FromAPILoader) || loader.path.exist? }
case loaders.count
when 1
loaders.first
when 2..Float::INFINITY
raise TapFormulaAmbiguityError.new(name, loaders)
end
end
end
# Loads a formula from a formula file in a keg.
class FromKegLoader < FormulaLoader
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
ref = ref.to_s
keg_directory = HOMEBREW_PREFIX/"opt/#{ref}"
return unless keg_directory.directory?
# The formula file in `.brew` will use the canonical name, whereas `ref` can be an alias.
# Use `Keg#name` to get the canonical name.
keg = Keg.new(keg_directory)
return unless (keg_formula = keg_directory/".brew/#{keg.name}.rb").file?
new(keg.name, keg_formula, tap: keg.tab.tap)
end
end
# Loads a formula from a cached formula file.
class FromCacheLoader < FormulaLoader
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
ref = ref.to_s
return unless (cached_formula = HOMEBREW_CACHE_FORMULA/"#{ref}.rb").file?
new(ref, cached_formula)
end
end
# Pseudo-loader which will raise a {FormulaUnavailableError} when trying to load the corresponding formula.
class NullLoader < FormulaLoader
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
return if ref.is_a?(URI::Generic)
new(ref)
end
sig { params(ref: T.any(String, Pathname)).void }
def initialize(ref)
name = File.basename(ref, ".rb")
super name, Formulary.core_path(name)
end
sig {
override.params(
_spec: Symbol,
alias_path: T.nilable(T.any(Pathname, String)),
force_bottle: T::Boolean,
flags: T::Array[String],
ignore_errors: T::Boolean,
).returns(Formula)
}
def get_formula(_spec, alias_path: nil, force_bottle: false, flags: [], ignore_errors: false)
raise FormulaUnavailableError, name
end
end
# Load formulae directly from their contents.
class FormulaContentsLoader < FormulaLoader
# The formula's contents.
sig { returns(String) }
attr_reader :contents
sig { params(name: String, path: Pathname, contents: String).void }
def initialize(name, path, contents)
@contents = contents
super name, path
end
sig { override.params(flags: T::Array[String], ignore_errors: T::Boolean).returns(T.class_of(Formula)) }
def klass(flags:, ignore_errors:)
namespace = "FormulaNamespace#{Digest::MD5.hexdigest(contents.to_s)}"
Formulary.load_formula(name, path, contents, namespace, flags:, ignore_errors:)
end
end
# Load a formula from the API.
class FromAPILoader < FormulaLoader
sig {
params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
return if Homebrew::EnvConfig.no_install_from_api?
return unless ref.is_a?(String)
return unless (name = ref[HOMEBREW_DEFAULT_TAP_FORMULA_REGEX, :name])
if Homebrew::API.formula_names.exclude?(name) &&
!Homebrew::API.formula_aliases.key?(name) &&
!Homebrew::API.formula_renames.key?(name)
return
end
alias_name = name
ref = "#{CoreTap.instance}/#{name}"
return unless (name_tap_type = Formulary.tap_formula_name_type(ref, warn:))
name, tap, type = name_tap_type
alias_name = (type == :alias) ? alias_name.downcase : nil
new(name, tap:, alias_name:)
end
sig { params(name: String, tap: T.nilable(Tap), alias_name: T.nilable(String)).void }
def initialize(name, tap: nil, alias_name: nil)
alias_path = CoreTap.instance.alias_dir/alias_name if alias_name
super(name, Formulary.core_path(name), alias_path:, tap:)
end
sig { override.params(flags: T::Array[String], ignore_errors: T::Boolean).returns(T.class_of(Formula)) }
def klass(flags:, ignore_errors:)
load_from_api(flags:) unless Formulary.formula_class_defined_from_api?(name)
Formulary.formula_class_get_from_api(name)
end
private
sig { overridable.params(flags: T::Array[String]).void }
def load_from_api(flags:)
json_formula = if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Formula.formula_json(name)
else
Homebrew::API::Formula.all_formulae[name]
end
raise FormulaUnavailableError, name if json_formula.nil?
Formulary.load_formula_from_json!(name, json_formula, flags:)
end
end
# Load formulae directly from their JSON contents.
class FormulaJSONContentsLoader < FromAPILoader
sig { params(name: String, contents: T::Hash[String, T.untyped], tap: T.nilable(Tap), alias_name: T.nilable(String)).void }
def initialize(name, contents, tap: nil, alias_name: nil)
@contents = contents
super(name, tap: tap, alias_name: alias_name)
end
private
sig { override.params(flags: T::Array[String]).void }
def load_from_api(flags:)
Formulary.load_formula_from_json!(name, @contents, flags:)
end
end
# Load a formula stub from the internal API.
class FormulaStubLoader < FromAPILoader
sig {
override.params(ref: T.any(String, Pathname, URI::Generic), from: T.nilable(Symbol), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, from: nil, warn: false)
return unless Homebrew::EnvConfig.use_internal_api?
super
end
sig { override.params(flags: T::Array[String], ignore_errors: T::Boolean).returns(T.class_of(Formula)) }
def klass(flags:, ignore_errors:)
load_from_api(flags:) unless Formulary.formula_class_defined_from_stub?(name)
Formulary.formula_class_get_from_stub(name)
end
private
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/commands.rb | Library/Homebrew/commands.rb | # typed: strict
# frozen_string_literal: true
require "utils"
# Helper functions for commands.
module Commands
HOMEBREW_CMD_PATH = T.let((HOMEBREW_LIBRARY_PATH/"cmd").freeze, Pathname)
HOMEBREW_DEV_CMD_PATH = T.let((HOMEBREW_LIBRARY_PATH/"dev-cmd").freeze, Pathname)
# If you are going to change anything in below hash,
# be sure to also update appropriate case statement in brew.sh
HOMEBREW_INTERNAL_COMMAND_ALIASES = T.let({
"ls" => "list",
"homepage" => "home",
"-S" => "search",
"up" => "update",
"ln" => "link",
"instal" => "install", # gem does the same
"uninstal" => "uninstall",
"post_install" => "postinstall",
"rm" => "uninstall",
"remove" => "uninstall",
"abv" => "info",
"dr" => "doctor",
"--repo" => "--repository",
"environment" => "--env",
"--config" => "config",
"-v" => "--version",
"lc" => "livecheck",
"tc" => "typecheck",
}.freeze, T::Hash[String, String])
# This pattern is used to split descriptions at full stops. We only consider a
# dot as a full stop if it is either followed by a whitespace or at the end of
# the description. In this way we can prevent cutting off a sentence in the
# middle due to dots in URLs or paths.
DESCRIPTION_SPLITTING_PATTERN = /\.(?>\s|$)/
sig { params(cmd: String).returns(T::Boolean) }
def self.valid_internal_cmd?(cmd)
Homebrew.require?(HOMEBREW_CMD_PATH/cmd)
end
sig { params(cmd: String).returns(T::Boolean) }
def self.valid_internal_dev_cmd?(cmd)
Homebrew.require?(HOMEBREW_DEV_CMD_PATH/cmd)
end
sig { params(cmd: String).returns(T::Boolean) }
def self.valid_ruby_cmd?(cmd)
(valid_internal_cmd?(cmd) || valid_internal_dev_cmd?(cmd) || external_ruby_v2_cmd_path(cmd).present?) &&
(Homebrew::AbstractCommand.command(cmd)&.ruby_cmd? == true)
end
sig { params(cmd: String).returns(Symbol) }
def self.method_name(cmd)
cmd.to_s
.tr("-", "_")
.downcase
.to_sym
end
sig { params(cmd_path: Pathname).returns(Symbol) }
def self.args_method_name(cmd_path)
cmd_path_basename = basename_without_extension(cmd_path)
cmd_method_prefix = method_name(cmd_path_basename)
:"#{cmd_method_prefix}_args"
end
sig { params(cmd: String).returns(T.nilable(Pathname)) }
def self.internal_cmd_path(cmd)
[
HOMEBREW_CMD_PATH/"#{cmd}.rb",
HOMEBREW_CMD_PATH/"#{cmd}.sh",
].find(&:exist?)
end
sig { params(cmd: String).returns(T.nilable(Pathname)) }
def self.internal_dev_cmd_path(cmd)
[
HOMEBREW_DEV_CMD_PATH/"#{cmd}.rb",
HOMEBREW_DEV_CMD_PATH/"#{cmd}.sh",
].find(&:exist?)
end
# Ruby commands which can be `require`d without being run.
sig { params(cmd: String).returns(T.nilable(Pathname)) }
def self.external_ruby_v2_cmd_path(cmd)
path = which("#{cmd}.rb", tap_cmd_directories)
path if Homebrew.require?(path)
end
# Ruby commands which are run by being `require`d.
sig { params(cmd: String).returns(T.nilable(Pathname)) }
def self.external_ruby_cmd_path(cmd)
which("brew-#{cmd}.rb", PATH.new(ENV.fetch("PATH")).append(tap_cmd_directories))
end
sig { params(cmd: String).returns(T.nilable(Pathname)) }
def self.external_cmd_path(cmd)
which("brew-#{cmd}", PATH.new(ENV.fetch("PATH")).append(tap_cmd_directories))
end
sig { params(cmd: String).returns(T.nilable(Pathname)) }
def self.path(cmd)
internal_cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(cmd, cmd)
path ||= internal_cmd_path(internal_cmd)
path ||= internal_dev_cmd_path(internal_cmd)
path ||= external_ruby_v2_cmd_path(cmd)
path ||= external_ruby_cmd_path(cmd)
path ||= external_cmd_path(cmd)
path
end
sig { params(external: T::Boolean, aliases: T::Boolean).returns(T::Array[String]) }
def self.commands(external: true, aliases: false)
cmds = internal_commands
cmds += internal_developer_commands
cmds += external_commands if external
cmds += internal_commands_aliases if aliases
cmds.sort
end
# An array of all tap cmd directory {Pathname}s.
sig { returns(T::Array[Pathname]) }
def self.tap_cmd_directories
Pathname.glob HOMEBREW_TAP_DIRECTORY/"*/*/cmd"
end
sig { returns(T::Array[Pathname]) }
def self.internal_commands_paths
find_commands HOMEBREW_CMD_PATH
end
sig { returns(T::Array[Pathname]) }
def self.internal_developer_commands_paths
find_commands HOMEBREW_DEV_CMD_PATH
end
sig { returns(T::Array[String]) }
def self.internal_commands
find_internal_commands(HOMEBREW_CMD_PATH).map(&:to_s)
end
sig { returns(T::Array[String]) }
def self.internal_developer_commands
find_internal_commands(HOMEBREW_DEV_CMD_PATH).map(&:to_s)
end
sig { returns(T::Array[String]) }
def self.internal_commands_aliases
HOMEBREW_INTERNAL_COMMAND_ALIASES.keys
end
sig { params(path: Pathname).returns(T::Array[String]) }
def self.find_internal_commands(path)
find_commands(path).map(&:basename)
.map { |basename| basename_without_extension(basename) }
.uniq
end
sig { returns(T::Array[String]) }
def self.external_commands
tap_cmd_directories.flat_map do |path|
find_commands(path).select(&:executable?)
.map { |basename| basename_without_extension(basename) }
.map { |p| p.to_s.delete_prefix("brew-").strip }
end.map(&:to_s)
.sort
end
sig { params(path: Pathname).returns(String) }
def self.basename_without_extension(path)
path.basename(path.extname).to_s
end
sig { params(path: Pathname).returns(T::Array[Pathname]) }
def self.find_commands(path)
Pathname.glob("#{path}/*")
.select(&:file?)
.sort
end
sig { void }
def self.rebuild_internal_commands_completion_list
require "completions"
cmds = internal_commands + internal_developer_commands + internal_commands_aliases
cmds.reject! { |cmd| Homebrew::Completions::COMPLETIONS_EXCLUSION_LIST.include? cmd }
file = HOMEBREW_REPOSITORY/"completions/internal_commands_list.txt"
file.atomic_write("#{cmds.sort.join("\n")}\n")
end
sig { void }
def self.rebuild_commands_completion_list
require "completions"
# Ensure that the cache exists so we can build the commands list
HOMEBREW_CACHE.mkpath
cmds = commands(aliases: true) - Homebrew::Completions::COMPLETIONS_EXCLUSION_LIST
all_commands_file = HOMEBREW_CACHE/"all_commands_list.txt"
external_commands_file = HOMEBREW_CACHE/"external_commands_list.txt"
all_commands_file.atomic_write("#{cmds.sort.join("\n")}\n")
external_commands_file.atomic_write("#{external_commands.sort.join("\n")}\n")
end
sig { params(command: String).returns(T.nilable(T::Array[[String, String]])) }
def self.command_options(command)
return if command == "help"
path = self.path(command)
return if path.blank?
if (cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path))
cmd_parser.processed_options.filter_map do |short, long, desc, hidden|
next if hidden
[T.must(long || short), desc]
end
else
options = []
comment_lines = path.read.lines.grep(/^#:/)
return options if comment_lines.empty?
# skip the comment's initial usage summary lines
comment_lines.slice(2..-1)&.each do |line|
match_data = / (?<option>-[-\w]+) +(?<desc>.*)$/.match(line)
options << [match_data[:option], match_data[:desc]] if match_data
end
options
end
end
sig { params(command: String, short: T::Boolean).returns(T.nilable(String)) }
def self.command_description(command, short: false)
path = self.path(command)
return if path.blank?
if (cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path))
if short
cmd_parser.description&.split(DESCRIPTION_SPLITTING_PATTERN)&.first
else
cmd_parser.description
end
else
comment_lines = path.read.lines.grep(/^#:/)
# skip the comment's initial usage summary lines
comment_lines.slice(2..-1)&.each do |line|
match_data = /^#: (?<desc>\w.*+)$/.match(line)
next unless match_data
desc = T.must(match_data[:desc])
return desc.split(DESCRIPTION_SPLITTING_PATTERN).first if short
return desc
end
nil
end
end
sig { params(command: String).returns(T.nilable(T.any(T::Array[Symbol], T::Array[String]))) }
def self.named_args_type(command)
path = self.path(command)
return if path.blank?
cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path)
return if cmd_parser.blank?
Array(cmd_parser.named_args_type)
end
# Returns the conflicts of a given `option` for `command`.
sig { params(command: String, option: String).returns(T.nilable(T::Array[String])) }
def self.option_conflicts(command, option)
path = self.path(command)
return if path.blank?
cmd_parser = Homebrew::CLI::Parser.from_cmd_path(path)
return if cmd_parser.blank?
cmd_parser.conflicts.map do |set|
set.map! { |s| s.tr "_", "-" }
set - [option] if set.include? option
end.flatten.compact
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/lock_file.rb | Library/Homebrew/lock_file.rb | # typed: strict
# frozen_string_literal: true
require "fcntl"
require "utils/output"
# A lock file to prevent multiple Homebrew processes from modifying the same path.
class LockFile
include Utils::Output::Mixin
class OpenFileChangedOnDisk < RuntimeError; end
private_constant :OpenFileChangedOnDisk
sig { returns(Pathname) }
attr_reader :path
sig { params(type: Symbol, locked_path: Pathname).void }
def initialize(type, locked_path)
@locked_path = locked_path
lock_name = locked_path.basename.to_s
@path = T.let(HOMEBREW_LOCKS/"#{lock_name}.#{type}.lock", Pathname)
@lockfile = T.let(nil, T.nilable(File))
end
sig { void }
def lock
ignore_interrupts do
next if @lockfile.present?
path.dirname.mkpath
begin
lockfile = begin
File.open(path, File::RDWR | File::CREAT)
rescue Errno::EMFILE
odie "The maximum number of open files on this system has been reached. " \
"Use `ulimit -n` to increase this limit."
end
lockfile.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
if lockfile.flock(File::LOCK_EX | File::LOCK_NB)
# This prevents a race condition in case the file we locked doesn't exist on disk anymore, e.g.:
#
# 1. Process A creates and opens the file.
# 2. Process A locks the file.
# 3. Process B opens the file.
# 4. Process A unlinks the file.
# 5. Process A unlocks the file.
# 6. Process B locks the file.
# 7. Process C creates and opens the file.
# 8. Process C locks the file.
# 9. Process B and C hold locks to files with different inode numbers. 💥
if !path.exist? || lockfile.stat.ino != path.stat.ino
lockfile.close
raise OpenFileChangedOnDisk
end
@lockfile = lockfile
next
end
rescue OpenFileChangedOnDisk
retry
end
lockfile.close
raise OperationInProgressError, @locked_path
end
end
sig { params(unlink: T::Boolean).void }
def unlock(unlink: false)
ignore_interrupts do
next if @lockfile.nil?
@path.unlink if unlink
@lockfile.flock(File::LOCK_UN)
@lockfile.close
@lockfile = nil
end
end
sig { params(_block: T.proc.void).void }
def with_lock(&_block)
lock
yield
ensure
unlock
end
end
# A lock file for a formula.
class FormulaLock < LockFile
sig { params(rack_name: String).void }
def initialize(rack_name)
super(:formula, HOMEBREW_CELLAR/rack_name)
end
end
# A lock file for a cask.
class CaskLock < LockFile
sig { params(cask_token: String).void }
def initialize(cask_token)
super(:cask, HOMEBREW_PREFIX/"Caskroom/#{cask_token}")
end
end
# A lock file for a download.
class DownloadLock < LockFile
sig { params(download_path: Pathname).void }
def initialize(download_path)
super(:download, download_path)
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/formula_cellar_checks.rb | Library/Homebrew/formula_cellar_checks.rb | # typed: strict
# frozen_string_literal: true
require "utils/shell"
# Checks to perform on a formula's keg (versioned Cellar path).
module FormulaCellarChecks
extend T::Helpers
abstract!
requires_ancestor { Kernel }
sig { abstract.returns(Formula) }
def formula; end
sig { abstract.params(output: T.nilable(String)).void }
def problem_if_output(output); end
sig { params(bin: Pathname).returns(T.nilable(String)) }
def check_env_path(bin)
return if Homebrew::EnvConfig.no_env_hints?
# warn the user if stuff was installed outside of their PATH
return unless bin.directory?
return if bin.children.empty?
prefix_bin = (HOMEBREW_PREFIX/bin.basename)
return unless prefix_bin.directory?
prefix_bin = prefix_bin.realpath
return if ORIGINAL_PATHS.include? prefix_bin
<<~EOS
"#{prefix_bin}" is not in your PATH.
You can amend this by altering your #{Utils::Shell.profile} file.
EOS
end
sig { returns(T.nilable(String)) }
def check_manpages
# Check for man pages that aren't in share/man
return unless (formula.prefix/"man").directory?
<<~EOS
A top-level "man" directory was found.
Homebrew requires that man pages live under "share".
This can often be fixed by passing `--mandir=\#{man}` to `configure`.
EOS
end
sig { returns(T.nilable(String)) }
def check_infopages
# Check for info pages that aren't in share/info
return unless (formula.prefix/"info").directory?
<<~EOS
A top-level "info" directory was found.
Homebrew suggests that info pages live under "share".
This can often be fixed by passing `--infodir=\#{info}` to `configure`.
EOS
end
sig { returns(T.nilable(String)) }
def check_jars
return unless formula.lib.directory?
jars = formula.lib.children.select { |g| g.extname == ".jar" }
return if jars.empty?
<<~EOS
JARs were installed to "#{formula.lib}".
Installing JARs to "lib" can cause conflicts between packages.
For Java software, it is typically better for the formula to
install to "libexec" and then symlink or wrap binaries into "bin".
See formulae 'activemq', 'jruby', etc. for examples.
The offending files are:
#{jars * "\n "}
EOS
end
VALID_LIBRARY_EXTENSIONS = %w[.a .jnilib .la .o .so .jar .prl .pm .sh].freeze
sig { params(filename: Pathname).returns(T::Boolean) }
def valid_library_extension?(filename)
VALID_LIBRARY_EXTENSIONS.include? filename.extname
end
sig { returns(T.nilable(String)) }
def check_non_libraries
return unless formula.lib.directory?
non_libraries = formula.lib.children.reject do |g|
next true if g.directory?
valid_library_extension? g
end
return if non_libraries.empty?
<<~EOS
Non-libraries were installed to "#{formula.lib}".
Installing non-libraries to "lib" is discouraged.
The offending files are:
#{non_libraries * "\n "}
EOS
end
sig { params(bin: Pathname).returns(T.nilable(String)) }
def check_non_executables(bin)
return unless bin.directory?
non_exes = bin.children.select { |g| g.directory? || !g.executable? }
return if non_exes.empty?
<<~EOS
Non-executables were installed to "#{bin}".
The offending files are:
#{non_exes * "\n "}
EOS
end
sig { params(bin: Pathname).returns(T.nilable(String)) }
def check_generic_executables(bin)
return unless bin.directory?
generic_names = %w[service start stop]
generics = bin.children.select { |g| generic_names.include? g.basename.to_s }
return if generics.empty?
<<~EOS
Generic binaries were installed to "#{bin}".
Binaries with generic names are likely to conflict with other software.
Homebrew suggests that this software is installed to "libexec" and then
symlinked as needed.
The offending files are:
#{generics * "\n "}
EOS
end
sig { params(lib: Pathname).returns(T.nilable(String)) }
def check_easy_install_pth(lib)
pth_found = Dir["#{lib}/python3*/site-packages/easy-install.pth"].map { |f| File.dirname(f) }
return if pth_found.empty?
<<~EOS
'easy-install.pth' files were found.
These '.pth' files are likely to cause link conflicts.
Easy install is now deprecated, do not use it.
The offending files are:
#{pth_found * "\n "}
EOS
end
sig { params(share: Pathname, name: String).returns(T.nilable(String)) }
def check_elisp_dirname(share, name)
return unless (share/"emacs/site-lisp").directory?
# Emacs itself can do what it wants
return if name == "emacs"
bad_dir_name = (share/"emacs/site-lisp").children.any? do |child|
child.directory? && child.basename.to_s != name
end
return unless bad_dir_name
<<~EOS
Emacs Lisp files were installed into the wrong "site-lisp" subdirectory.
They should be installed into:
#{share}/emacs/site-lisp/#{name}
EOS
end
sig { params(share: Pathname, name: String).returns(T.nilable(String)) }
def check_elisp_root(share, name)
return unless (share/"emacs/site-lisp").directory?
# Emacs itself can do what it wants
return if name == "emacs"
elisps = (share/"emacs/site-lisp").children.select do |file|
Keg::ELISP_EXTENSIONS.include? file.extname
end
return if elisps.empty?
<<~EOS
Emacs Lisp files were linked directly to "#{HOMEBREW_PREFIX}/share/emacs/site-lisp".
This may cause conflicts with other packages.
They should instead be installed into:
#{share}/emacs/site-lisp/#{name}
The offending files are:
#{elisps * "\n "}
EOS
end
sig { params(lib: Pathname, deps: Dependencies).returns(T.nilable(String)) }
def check_python_packages(lib, deps)
return unless lib.directory?
lib_subdirs = lib.children
.select(&:directory?)
.map(&:basename)
pythons = lib_subdirs.filter_map do |p|
match = p.to_s.match(/^python(\d+\.\d+)$/)
next if match.blank?
next if match.captures.blank?
match.captures.first
end
return if pythons.blank?
python_deps = deps.to_a
.map(&:name)
.grep(/^python(@.*)?$/)
.filter_map { |d| Formula[d].version.to_s[/^\d+\.\d+/] }
return if python_deps.blank?
return if pythons.any? { |v| python_deps.include? v }
pythons = pythons.map { |v| "Python #{v}" }
python_deps = python_deps.map { |v| "Python #{v}" }
<<~EOS
Packages have been installed for:
#{pythons * "\n "}
but this formula depends on:
#{python_deps * "\n "}
EOS
end
sig { params(prefix: Pathname).returns(T.nilable(String)) }
def check_shim_references(prefix)
return unless prefix.directory?
keg = Keg.new(prefix)
matches = []
keg.each_unique_file_matching(HOMEBREW_SHIMS_PATH.to_s) do |f|
match = f.relative_path_from(keg.to_path)
next if match.to_s.match? %r{^share/doc/.+?/INFO_BIN$}
matches << match
end
return if matches.empty?
<<~EOS
Files were found with references to the Homebrew shims directory.
The offending files are:
#{matches * "\n "}
EOS
end
sig { params(prefix: Pathname, plist: Pathname).returns(T.nilable(String)) }
def check_plist(prefix, plist)
return unless prefix.directory?
plist = begin
Plist.parse_xml(plist, marshal: false)
rescue
nil
end
return if plist.blank?
program_location = plist["ProgramArguments"]&.first
key = "first ProgramArguments value"
if program_location.blank?
program_location = plist["Program"]
key = "Program"
end
return if program_location.blank?
Dir.chdir("/") do
unless File.exist?(program_location)
return <<~EOS
The plist "#{key}" does not exist:
#{program_location}
EOS
end
return if File.executable?(program_location)
end
<<~EOS
The plist "#{key}" is not executable:
#{program_location}
EOS
end
sig { params(name: String, keg_only: T::Boolean).returns(T.nilable(String)) }
def check_python_symlinks(name, keg_only)
return unless keg_only
return unless name.start_with? "python"
return if %w[pip3 wheel3].none? do |l|
link = HOMEBREW_PREFIX/"bin"/l
link.exist? && File.realpath(link).start_with?(HOMEBREW_CELLAR/name)
end
"Python formulae that are keg-only should not create `pip3` and `wheel3` symlinks."
end
sig { params(formula: Formula).returns(T.nilable(String)) }
def check_service_command(formula)
return unless formula.prefix.directory?
return unless formula.service?
return unless formula.service.command?
"Service command does not exist" unless File.exist?(formula.service.command.first)
end
sig { params(formula: Formula).returns(T.nilable(String)) }
def check_cpuid_instruction(formula)
# Checking for `cpuid` only makes sense on Intel:
# https://en.wikipedia.org/wiki/CPUID
return unless Hardware::CPU.intel?
dot_brew_formula = formula.prefix/".brew/#{formula.name}.rb"
return unless dot_brew_formula.exist?
return unless dot_brew_formula.read.include? "ENV.runtime_cpu_detection"
return if formula.tap&.audit_exception(:no_cpuid_allowlist, formula.name)
# macOS `objdump` is a bit slow, so we prioritise llvm's `llvm-objdump` (~5.7x faster)
# or binutils' `objdump` (~1.8x faster) if they are installed.
objdump = Formula["llvm"].opt_bin/"llvm-objdump" if Formula["llvm"].any_version_installed?
objdump ||= Formula["binutils"].opt_bin/"objdump" if Formula["binutils"].any_version_installed?
objdump ||= which("objdump")
objdump ||= which("objdump", ORIGINAL_PATHS)
unless objdump
return <<~EOS
No `objdump` found, so cannot check for a `cpuid` instruction. Install `objdump` with
brew install binutils
EOS
end
keg = Keg.new(formula.prefix)
return if keg.binary_executable_or_library_files.any? do |file|
cpuid_instruction?(file, objdump)
end
hardlinks = Set.new
return if formula.lib.directory? && formula.lib.find.any? do |pn|
next false if pn.symlink? || pn.directory? || pn.extname != ".a"
next false unless hardlinks.add? [pn.stat.dev, pn.stat.ino]
cpuid_instruction?(pn, objdump)
end
"No `cpuid` instruction detected. #{formula} should not use `ENV.runtime_cpu_detection`."
end
sig { params(formula: Formula).returns(T.nilable(String)) }
def check_binary_arches(formula)
return unless formula.prefix.directory?
keg = Keg.new(formula.prefix)
mismatches = {}
keg.binary_executable_or_library_files.each do |file|
# we know this has an `arch` method because it's a `MachOShim` or `ELFShim`
farch = T.unsafe(file).arch
mismatches[file] = farch if farch != Hardware::CPU.arch
end
return if mismatches.empty?
compatible_universal_binaries, mismatches = mismatches.partition do |file, arch|
arch == :universal && file.archs.include?(Hardware::CPU.arch)
end
# To prevent transformation into nested arrays
compatible_universal_binaries = compatible_universal_binaries.to_h
mismatches = mismatches.to_h
universal_binaries_expected = if (formula_tap = formula.tap).present? && formula_tap.core_tap?
formula_name = formula.name
# Apply audit exception to versioned formulae too from the unversioned name.
formula_name = formula_name.gsub(/@\d+(\.\d+)*$/, "") if formula.versioned_formula?
formula_tap.audit_exception(:universal_binary_allowlist, formula_name)
else
true
end
mismatches_expected = (formula_tap = formula.tap).blank? ||
formula_tap.audit_exception(:mismatched_binary_allowlist, formula.name)
mismatches_expected = [mismatches_expected] if mismatches_expected.is_a?(String)
if mismatches_expected.is_a?(Array)
glob_flags = File::FNM_DOTMATCH | File::FNM_EXTGLOB | File::FNM_PATHNAME
mismatches.delete_if do |file, _arch|
mismatches_expected.any? { |pattern| file.fnmatch?("#{formula.prefix.realpath}/#{pattern}", glob_flags) }
end
mismatches_expected = false
return if mismatches.empty? && compatible_universal_binaries.empty?
end
return if mismatches.empty? && universal_binaries_expected
return if compatible_universal_binaries.empty? && mismatches_expected
return if universal_binaries_expected && mismatches_expected
s = ""
if mismatches.present? && !mismatches_expected
s += <<~EOS
Binaries built for a non-native architecture were installed into #{formula}'s prefix.
The offending files are:
#{mismatches.map { |m| "#{m.first}\t(#{m.last})" } * "\n "}
EOS
end
if compatible_universal_binaries.present? && !universal_binaries_expected
s += <<~EOS
Unexpected universal binaries were found.
The offending files are:
#{compatible_universal_binaries.keys * "\n "}
EOS
end
s
end
sig { void }
def audit_installed
@new_formula ||= T.let(false, T.nilable(T::Boolean))
problem_if_output(check_manpages)
problem_if_output(check_infopages)
problem_if_output(check_jars)
problem_if_output(check_service_command(formula))
problem_if_output(check_non_libraries) if @new_formula
problem_if_output(check_non_executables(formula.bin))
problem_if_output(check_generic_executables(formula.bin))
problem_if_output(check_non_executables(formula.sbin))
problem_if_output(check_generic_executables(formula.sbin))
problem_if_output(check_easy_install_pth(formula.lib))
problem_if_output(check_elisp_dirname(formula.share, formula.name))
problem_if_output(check_elisp_root(formula.share, formula.name))
problem_if_output(check_python_packages(formula.lib, formula.deps))
problem_if_output(check_shim_references(formula.prefix))
problem_if_output(check_plist(formula.prefix, formula.launchd_service_path))
problem_if_output(check_python_symlinks(formula.name, formula.keg_only?))
problem_if_output(check_cpuid_instruction(formula))
problem_if_output(check_binary_arches(formula))
end
private
sig { params(dir: T.any(Pathname, String), pattern: String).returns(T::Array[String]) }
def relative_glob(dir, pattern)
File.directory?(dir) ? Dir.chdir(dir) { Dir[pattern] } : []
end
sig { params(file: T.any(Pathname, String), objdump: Pathname).returns(T::Boolean) }
def cpuid_instruction?(file, objdump)
@instruction_column_index ||= T.let({}, T.nilable(T::Hash[Pathname, Integer]))
instruction_column_index_objdump = @instruction_column_index[objdump] ||= begin
objdump_version = Utils.popen_read(objdump, "--version")
if objdump_version.include?("LLVM")
1 # `llvm-objdump` or macOS `objdump`
else
2 # GNU Binutils `objdump`
end
end
has_cpuid_instruction = T.let(false, T::Boolean)
Utils.popen_read(objdump, "--disassemble", file) do |io|
until io.eof?
instruction = io.readline.split("\t")[instruction_column_index_objdump]&.strip
has_cpuid_instruction = instruction == "cpuid" if instruction.present?
break if has_cpuid_instruction
end
end
has_cpuid_instruction
end
end
require "extend/os/formula_cellar_checks"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/shell_command.rb | Library/Homebrew/shell_command.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module ShellCommand
extend T::Helpers
requires_ancestor { AbstractCommand }
sig { void }
def run
T.bind(self, AbstractCommand)
sh_cmd_path = "#{self.class.dev_cmd? ? "dev-cmd" : "cmd"}/#{self.class.command_name}.sh"
raise StandardError,
"This command is just here for completions generation. " \
"It's actually defined in `#{sh_cmd_path}` instead."
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/dependency_collector.rb | Library/Homebrew/dependency_collector.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "dependency"
require "dependencies"
require "requirement"
require "requirements"
require "cachable"
# A dependency is a formula that another formula needs to install.
# A requirement is something other than a formula that another formula
# needs to be present. This includes external language modules,
# command-line tools in the path, or any arbitrary predicate.
#
# The `depends_on` method in the formula DSL is used to declare
# dependencies and requirements.
# This class is used by `depends_on` in the formula DSL to turn dependency
# specifications into the proper kinds of dependencies and requirements.
class DependencyCollector
extend Cachable
attr_reader :deps, :requirements
sig { void }
def initialize
# Ensure this is synced with `initialize_dup` and `freeze` (excluding simple objects like integers and booleans)
@deps = Dependencies.new
@requirements = Requirements.new
init_global_dep_tree_if_needed!
end
def initialize_dup(other)
super
@deps = @deps.dup
@requirements = @requirements.dup
end
def freeze
@deps.freeze
@requirements.freeze
super
end
def add(spec)
case dep = fetch(spec)
when Array
dep.compact.each { |dep| @deps << dep }
when Dependency
@deps << dep
when Requirement
@requirements << dep
when nil
# no-op when we have a nil value
nil
else
raise ArgumentError, "DependencyCollector#add passed something that isn't a Dependency or Requirement!"
end
dep
end
def fetch(spec)
self.class.cache.fetch(cache_key(spec)) { |key| self.class.cache[key] = build(spec) }
end
def cache_key(spec)
if spec.is_a?(Resource)
if spec.download_strategy <= CurlDownloadStrategy
return "#{spec.download_strategy}#{File.extname(T.must(spec.url)).split("?").first}"
end
return spec.download_strategy
end
spec
end
def build(spec)
spec, tags = spec.is_a?(Hash) ? spec.first : spec
parse_spec(spec, Array(tags))
end
sig { params(related_formula_names: T::Set[String]).returns(T.nilable(Dependency)) }
def gcc_dep_if_needed(related_formula_names); end
sig { params(related_formula_names: T::Set[String]).returns(T.nilable(Dependency)) }
def glibc_dep_if_needed(related_formula_names); end
def git_dep_if_needed(tags)
require "utils/git"
return if Utils::Git.available?
Dependency.new("git", [*tags, :implicit])
end
def curl_dep_if_needed(tags)
Dependency.new("curl", [*tags, :implicit])
end
def subversion_dep_if_needed(tags)
require "utils/svn"
return if Utils::Svn.available?
Dependency.new("subversion", [*tags, :implicit])
end
def cvs_dep_if_needed(tags)
Dependency.new("cvs", [*tags, :implicit]) unless which("cvs")
end
def xz_dep_if_needed(tags)
Dependency.new("xz", [*tags, :implicit]) unless which("xz")
end
def zstd_dep_if_needed(tags)
Dependency.new("zstd", [*tags, :implicit]) unless which("zstd")
end
def unzip_dep_if_needed(tags)
Dependency.new("unzip", [*tags, :implicit]) unless which("unzip")
end
def bzip2_dep_if_needed(tags)
Dependency.new("bzip2", [*tags, :implicit]) unless which("bzip2")
end
def self.tar_needs_xz_dependency?
!new.xz_dep_if_needed([]).nil?
end
private
sig { void }
def init_global_dep_tree_if_needed!; end
sig {
params(spec: T.any(String, Resource, Symbol, Requirement, Dependency, Class),
tags: T::Array[T.any(String, Symbol)]).returns(T.nilable(T.any(Dependency, Requirement, Array)))
}
def parse_spec(spec, tags)
raise ArgumentError, "Implicit dependencies cannot be manually specified" if tags.include?(:implicit)
case spec
when String
parse_string_spec(spec, tags)
when Resource
resource_dep(spec, tags)
when Symbol
parse_symbol_spec(spec, tags)
when Requirement, Dependency
spec
when Class
parse_class_spec(spec, tags)
end
end
def parse_string_spec(spec, tags)
Dependency.new(spec, tags)
end
def parse_symbol_spec(spec, tags)
# When modifying this list of supported requirements, consider
# whether `FormulaStruct::API_SUPPORTED_REQUIREMENTS` should also be changed.
case spec
when :arch then ArchRequirement.new(tags)
when :codesign then CodesignRequirement.new(tags)
when :linux then LinuxRequirement.new(tags)
when :macos then MacOSRequirement.new(tags)
when :maximum_macos then MacOSRequirement.new(tags, comparator: "<=")
when :xcode then XcodeRequirement.new(tags)
else
raise ArgumentError, "Unsupported special dependency: #{spec.inspect}"
end
end
def parse_class_spec(spec, tags)
raise TypeError, "#{spec.inspect} is not a Requirement subclass" unless spec < Requirement
spec.new(tags)
end
def resource_dep(spec, tags)
tags << :build << :test
strategy = spec.download_strategy
if strategy <= HomebrewCurlDownloadStrategy
[curl_dep_if_needed(tags), parse_url_spec(spec.url, tags)]
elsif strategy <= NoUnzipCurlDownloadStrategy
# ensure NoUnzip never adds any dependencies
elsif strategy <= CurlDownloadStrategy
parse_url_spec(spec.url, tags)
elsif strategy <= GitDownloadStrategy
git_dep_if_needed(tags)
elsif strategy <= SubversionDownloadStrategy
subversion_dep_if_needed(tags)
elsif strategy <= MercurialDownloadStrategy
Dependency.new("mercurial", [*tags, :implicit])
elsif strategy <= FossilDownloadStrategy
Dependency.new("fossil", [*tags, :implicit])
elsif strategy <= BazaarDownloadStrategy
Dependency.new("breezy", [*tags, :implicit])
elsif strategy <= CVSDownloadStrategy
cvs_dep_if_needed(tags)
elsif strategy < AbstractDownloadStrategy
# allow unknown strategies to pass through
else
raise TypeError, "#{strategy.inspect} is not an AbstractDownloadStrategy subclass"
end
end
def parse_url_spec(url, tags)
case File.extname(url)
when ".xz" then xz_dep_if_needed(tags)
when ".zst" then zstd_dep_if_needed(tags)
when ".zip" then unzip_dep_if_needed(tags)
when ".bz2" then bzip2_dep_if_needed(tags)
when ".lha", ".lzh" then Dependency.new("lha", [*tags, :implicit])
when ".lz" then Dependency.new("lzip", [*tags, :implicit])
when ".rar" then Dependency.new("libarchive", [*tags, :implicit])
when ".7z" then Dependency.new("p7zip", [*tags, :implicit])
end
end
end
require "extend/os/dependency_collector"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/software_spec.rb | Library/Homebrew/software_spec.rb | # typed: strict
# frozen_string_literal: true
require "resource"
require "download_strategy"
require "checksum"
require "version"
require "options"
require "build_options"
require "dependency_collector"
require "utils/bottles"
require "patch"
require "compilers"
require "macos_version"
require "on_system"
class SoftwareSpec
include Downloadable
extend Forwardable
include OnSystem::MacOSAndLinux
sig { returns(T.nilable(String)) }
attr_reader :name
sig { returns(T.nilable(String)) }
attr_reader :full_name
sig { returns(T.nilable(T.any(Formula, Cask::Cask))) }
attr_reader :owner
sig { returns(BuildOptions) }
attr_reader :build
sig { returns(T::Hash[String, Resource]) }
attr_reader :resources
sig { returns(T::Array[T.any(EmbeddedPatch, ExternalPatch)]) }
attr_reader :patches
sig { returns(Options) }
attr_reader :options
sig { returns(T::Array[DeprecatedOption]) }
attr_reader :deprecated_flags
sig { returns(T::Array[DeprecatedOption]) }
attr_reader :deprecated_options
sig { returns(DependencyCollector) }
attr_reader :dependency_collector
sig { returns(BottleSpecification) }
attr_reader :bottle_specification
sig { returns(T::Array[CompilerFailure]) }
attr_reader :compiler_failures
def_delegators :@resource, :stage, :fetch, :verify_download_integrity, :source_modified_time,
:cached_download, :clear_cache, :checksum, :mirrors, :specs, :using, :version, :mirror,
:downloader, :download_queue_name, :download_queue_type
def_delegators :@resource, :sha256
sig { params(flags: T::Array[String]).void }
def initialize(flags: [])
super()
@name = T.let(nil, T.nilable(String))
@full_name = T.let(nil, T.nilable(String))
@owner = T.let(nil, T.nilable(T.any(Formula, Cask::Cask)))
# Ensure this is synced with `initialize_dup` and `freeze` (excluding simple objects like integers and booleans)
@resource = T.let(Resource::Formula.new, Resource::Formula)
@resources = T.let({}, T::Hash[String, Resource])
@dependency_collector = T.let(DependencyCollector.new, DependencyCollector)
@bottle_specification = T.let(BottleSpecification.new, BottleSpecification)
@patches = T.let([], T::Array[T.any(EmbeddedPatch, ExternalPatch)])
@options = T.let(Options.new, Options)
@flags = flags
@deprecated_flags = T.let([], T::Array[DeprecatedOption])
@deprecated_options = T.let([], T::Array[DeprecatedOption])
@build = T.let(BuildOptions.new(Options.create(@flags), options), BuildOptions)
@compiler_failures = T.let([], T::Array[CompilerFailure])
end
sig { override.params(other: T.any(SoftwareSpec, Downloadable)).void }
def initialize_dup(other)
super
@resource = @resource.dup
@resources = @resources.dup
@dependency_collector = @dependency_collector.dup
@bottle_specification = @bottle_specification.dup
@patches = @patches.dup
@options = @options.dup
@flags = @flags.dup
@deprecated_flags = @deprecated_flags.dup
@deprecated_options = @deprecated_options.dup
@build = @build.dup
@compiler_failures = @compiler_failures.dup
end
sig { override.returns(T.self_type) }
def freeze
@resource.freeze
@resources.freeze
@dependency_collector.freeze
@bottle_specification.freeze
@patches.freeze
@options.freeze
@flags.freeze
@deprecated_flags.freeze
@deprecated_options.freeze
@build.freeze
@compiler_failures.freeze
super
end
sig { params(owner: T.any(Formula, Cask::Cask)).void }
def owner=(owner)
@name = owner.name
@full_name = owner.full_name
@bottle_specification.tap = owner.tap
@owner = owner
@resource.owner = self
resources.each_value do |r|
r.owner = self
next if r.version
next if version.nil?
r.version(version.head? ? Version.new("HEAD") : version.dup)
end
patches.each { |p| p.owner = self }
end
sig { override.params(val: T.nilable(String), specs: T::Hash[Symbol, T.anything]).returns(T.nilable(String)) }
def url(val = nil, specs = {})
if val
@resource.url(val, **specs)
dependency_collector.add(@resource)
end
@resource.url
end
sig { returns(T::Boolean) }
def bottle_defined?
!bottle_specification.collector.tags.empty?
end
sig { params(tag: T.nilable(T.any(Utils::Bottles::Tag, Symbol))).returns(T::Boolean) }
def bottle_tag?(tag = nil)
bottle_specification.tag?(Utils::Bottles.tag(tag))
end
sig { params(tag: T.nilable(T.any(Utils::Bottles::Tag, Symbol))).returns(T::Boolean) }
def bottled?(tag = nil)
return false unless bottle_tag?(tag)
return true if tag.present?
return true if bottle_specification.compatible_locations?
owner = self.owner
return false unless owner.is_a?(Formula)
owner.force_bottle
end
sig { params(block: T.proc.bind(BottleSpecification).void).void }
def bottle(&block)
bottle_specification.instance_eval(&block)
end
sig { params(name: String).returns(T::Boolean) }
def resource_defined?(name)
resources.key?(name)
end
sig {
params(name: String, klass: T.class_of(Resource), block: T.nilable(T.proc.bind(Resource).void))
.returns(T.nilable(Resource))
}
def resource(name = T.unsafe(nil), klass = Resource, &block)
if block
raise ArgumentError, "Resource must have a name." if name.nil?
raise DuplicateResourceError, name if resource_defined?(name)
res = klass.new(name, &block)
return unless res.url
resources[name] = res
dependency_collector.add(res)
res
else
return @resource if name.nil?
resources.fetch(name) { raise ResourceMissingError.new(owner, name) }
end
end
sig { params(name: T.any(Option, String)).returns(T::Boolean) }
def option_defined?(name)
options.include?(name)
end
sig { params(name: String, description: String).void }
def option(name, description = "")
raise ArgumentError, "option name is required" if name.empty?
raise ArgumentError, "option name must be longer than one character: #{name}" if name.length <= 1
raise ArgumentError, "option name must not start with dashes: #{name}" if name.start_with?("-")
options << Option.new(name, description)
end
sig { params(hash: T::Hash[T.any(String, T::Array[String]), T.any(String, T::Array[String])]).void }
def deprecated_option(hash)
raise ArgumentError, "deprecated_option hash must not be empty" if hash.empty?
hash.each do |old_options, new_options|
Array(old_options).each do |old_option|
Array(new_options).each do |new_option|
deprecated_option = DeprecatedOption.new(old_option, new_option)
deprecated_options << deprecated_option
old_flag = deprecated_option.old_flag
new_flag = deprecated_option.current_flag
next unless @flags.include? old_flag
@flags -= [old_flag]
@flags |= [new_flag]
@deprecated_flags << deprecated_option
end
end
end
@build = BuildOptions.new(Options.create(@flags), options)
end
sig { params(spec: T.any(String, Symbol, T::Hash[T.any(String, Symbol, T::Class[Requirement]), T.untyped], T::Class[Requirement], Dependable)).void }
def depends_on(spec)
dep = dependency_collector.add(spec)
add_dep_option(dep) if dep
end
sig {
params(
dep: T.any(String, T::Hash[T.any(String, Symbol), T.any(Symbol, T::Array[Symbol])]),
bounds: T::Hash[Symbol, Symbol],
).void
}
def uses_from_macos(dep, bounds = {})
if dep.is_a?(Hash)
bounds = dep.dup
dep, tags = bounds.shift
dep = T.cast(dep, String)
tags = [*tags]
bounds = T.cast(bounds, T::Hash[Symbol, Symbol])
else
tags = []
end
depends_on UsesFromMacOSDependency.new(dep, tags, bounds:)
end
sig { returns(Dependencies) }
def deps
dependency_collector.deps.dup_without_system_deps
end
sig { returns(Dependencies) }
def declared_deps
dependency_collector.deps
end
sig { returns(T::Array[Dependable]) }
def recursive_dependencies
deps_f = []
recursive_dependencies = deps.filter_map do |dep|
deps_f << dep.to_formula
dep
rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap dependencies
next
end.uniq
deps_f.compact.each do |f|
f.recursive_dependencies.each do |dep|
recursive_dependencies << dep unless recursive_dependencies.include?(dep)
end
end
recursive_dependencies
end
sig { returns(Requirements) }
def requirements
dependency_collector.requirements
end
sig { returns(Requirements) }
def recursive_requirements
Requirement.expand(self)
end
sig {
params(strip: T.any(Symbol, String), src: T.nilable(T.any(String, Symbol)),
block: T.nilable(T.proc.bind(Patch).void)).void
}
def patch(strip = :p1, src = T.unsafe(nil), &block)
p = Patch.create(strip, src, &block)
return if p.is_a?(ExternalPatch) && p.url.blank?
dependency_collector.add(p.resource) if p.is_a? ExternalPatch
patches << p
end
sig { params(compiler: T.any(T::Hash[Symbol, String], Symbol), block: T.nilable(T.proc.bind(CompilerFailure).void)).void }
def fails_with(compiler, &block)
compiler_failures << CompilerFailure.create(compiler, &block)
end
sig { params(dep: Dependable).void }
def add_dep_option(dep)
dep.option_names.each do |name|
if dep.optional? && !option_defined?("with-#{name}")
options << Option.new("with-#{name}", "Build with #{name} support")
elsif dep.recommended? && !option_defined?("without-#{name}")
options << Option.new("without-#{name}", "Build without #{name} support")
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/cxxstdlib.rb | Library/Homebrew/cxxstdlib.rb | # typed: strong
# frozen_string_literal: true
require "compilers"
# Combination of C++ standard library and compiler.
class CxxStdlib
sig { params(type: T.nilable(Symbol), compiler: T.any(Symbol, String)).returns(CxxStdlib) }
def self.create(type, compiler)
raise ArgumentError, "Invalid C++ stdlib type: #{type}" if type && [:libstdcxx, :libcxx].exclude?(type)
CxxStdlib.new(type, compiler)
end
sig { returns(T.nilable(Symbol)) }
attr_reader :type
sig { returns(Symbol) }
attr_reader :compiler
sig { params(type: T.nilable(Symbol), compiler: T.any(Symbol, String)).void }
def initialize(type, compiler)
@type = type
@compiler = T.let(compiler.to_sym, Symbol)
end
sig { returns(String) }
def type_string
type.to_s.gsub(/cxx$/, "c++")
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: #{compiler} #{type}>"
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/linkage_checker.rb | Library/Homebrew/linkage_checker.rb | # typed: strict
# frozen_string_literal: true
require "keg"
require "formula"
require "linkage_cache_store"
require "utils/output"
# Check for broken/missing linkage in a formula's keg.
class LinkageChecker
include Utils::Output::Mixin
sig { returns(Keg) }
attr_reader :keg
sig { returns(T.nilable(Formula)) }
attr_reader :formula
sig { returns(LinkageCacheStore) }
attr_reader :store
sig { returns(T::Array[String]) }
attr_reader :indirect_deps, :undeclared_deps, :unwanted_system_dylibs
sig { returns(T::Set[String]) }
attr_reader :system_dylibs
sig { params(keg: Keg, formula: T.nilable(Formula), cache_db: CacheStoreDatabase, rebuild_cache: T::Boolean).void }
def initialize(keg, formula = nil, cache_db:, rebuild_cache: false)
@keg = keg
@formula = T.let(formula || resolve_formula(keg), T.nilable(Formula))
@store = T.let(LinkageCacheStore.new(keg.to_s, cache_db), LinkageCacheStore)
@system_dylibs = T.let(Set.new, T::Set[String])
@broken_dylibs = T.let(Set.new, T::Set[String])
@variable_dylibs = T.let(Set.new, T::Set[String])
@brewed_dylibs = T.let({}, T::Hash[String, T::Set[String]])
@reverse_links = T.let({}, T::Hash[String, T::Set[String]])
@broken_deps = T.let({}, T::Hash[String, T::Array[String]])
@indirect_deps = T.let([], T::Array[String])
@undeclared_deps = T.let([], T::Array[String])
@unnecessary_deps = T.let([], T::Array[String])
@no_linkage_deps = T.let([], T::Array[String])
@unexpected_linkage_deps = T.let([], T::Array[String])
@unwanted_system_dylibs = T.let([], T::Array[String])
@version_conflict_deps = T.let([], T::Array[String])
@files_missing_rpaths = T.let([], T::Array[String])
@executable_path_dylibs = T.let([], T::Array[String])
check_dylibs(rebuild_cache:)
end
sig { void }
def display_normal_output
display_items "System libraries", @system_dylibs
display_items "Homebrew libraries", @brewed_dylibs
display_items "Indirect dependencies with linkage", @indirect_deps
display_items "@rpath-referenced libraries", @variable_dylibs
display_items "Missing libraries", @broken_dylibs
display_items "Broken dependencies", @broken_deps
display_items "Undeclared dependencies with linkage", @undeclared_deps
display_items "Dependencies with no linkage", @unnecessary_deps
display_items "Homebrew dependencies not requiring linkage", @no_linkage_deps
display_items "Unexpected linkage for no_linkage dependencies", @unexpected_linkage_deps
display_items "Unwanted system libraries", @unwanted_system_dylibs
display_items "Files with missing rpath", @files_missing_rpaths
display_items "@executable_path references in libraries", @executable_path_dylibs
end
sig { void }
def display_reverse_output
return if @reverse_links.empty?
sorted = @reverse_links.sort
sorted.each do |dylib, files|
puts dylib
files.each do |f|
unprefixed = f.to_s.delete_prefix "#{keg}/"
puts " #{unprefixed}"
end
puts if dylib != sorted.last&.first
end
end
sig { params(puts_output: T::Boolean, strict: T::Boolean).void }
def display_test_output(puts_output: true, strict: false)
display_items("Missing libraries", @broken_dylibs, puts_output:)
display_items("Broken dependencies", @broken_deps, puts_output:)
display_items("Unwanted system libraries", @unwanted_system_dylibs, puts_output:)
display_items("Conflicting libraries", @version_conflict_deps, puts_output:)
return unless strict
display_items("Indirect dependencies with linkage", @indirect_deps, puts_output:)
display_items("Undeclared dependencies with linkage", @undeclared_deps, puts_output:)
display_items("Unexpected linkage for no_linkage dependencies", @unexpected_linkage_deps, puts_output:)
display_items("Files with missing rpath", @files_missing_rpaths, puts_output:)
display_items "@executable_path references in libraries", @executable_path_dylibs, puts_output:
end
sig { params(test: T::Boolean, strict: T::Boolean).returns(T::Boolean) }
def broken_library_linkage?(test: false, strict: false)
raise ArgumentError, "Strict linkage checking requires test mode to be enabled." if strict && !test
issues = [@broken_deps, @broken_dylibs]
if test
issues += [@unwanted_system_dylibs, @version_conflict_deps]
if strict
issues += [@indirect_deps, @undeclared_deps, @unexpected_linkage_deps,
@files_missing_rpaths, @executable_path_dylibs]
end
end
issues.any?(&:present?)
end
private
sig { params(dylib: String).returns(T.nilable(String)) }
def dylib_to_dep(dylib)
dylib =~ %r{#{Regexp.escape(HOMEBREW_PREFIX)}/(opt|Cellar)/([\w+-.@]+)/}o
Regexp.last_match(2)
end
sig { params(file: String).returns(T::Boolean) }
def broken_dylibs_allowed?(file)
formula = self.formula
return false if formula.nil? || formula.name != "julia"
file.start_with?("#{formula.prefix.realpath}/share/julia/compiled/")
end
sig { params(rebuild_cache: T::Boolean).void }
def check_dylibs(rebuild_cache:)
keg_files_dylibs = nil
if rebuild_cache
store.delete!
else
keg_files_dylibs = store.fetch(:keg_files_dylibs)
end
keg_files_dylibs_was_empty = false
keg_files_dylibs ||= {}
if keg_files_dylibs.empty?
keg_files_dylibs_was_empty = true
@keg.find do |file|
next if file.symlink? || file.directory?
file = begin
BinaryPathname.wrap(file)
rescue NotImplementedError
next
end
next if !file.dylib? && !file.binary_executable? && !file.mach_o_bundle?
next unless file.arch_compatible?(Hardware::CPU.arch)
# weakly loaded dylibs may not actually exist on disk, so skip them
# when checking for broken linkage
keg_files_dylibs[file] =
file.dynamically_linked_libraries(except: :DYLIB_USE_WEAK_LINK)
end
end
checked_dylibs = Set.new
keg_files_dylibs.each do |file, dylibs|
file_has_any_rpath_dylibs = T.let(false, T::Boolean)
dylibs.each do |dylib|
(@reverse_links[dylib] ||= Set.new) << file
# Files that link @rpath-prefixed dylibs must include at
# least one rpath in order to resolve it.
if !file_has_any_rpath_dylibs && (dylib.start_with? "@rpath/")
file_has_any_rpath_dylibs = true
pathname = Pathname(file)
@files_missing_rpaths << file if pathname.rpaths.empty? && !broken_dylibs_allowed?(file.to_s)
end
next if checked_dylibs.include? dylib
checked_dylibs << dylib
if dylib.start_with? "@rpath"
@variable_dylibs << dylib
next
elsif dylib.start_with?("@executable_path") && !Pathname(file).binary_executable?
@executable_path_dylibs << dylib
next
end
begin
owner = Keg.for(Pathname(dylib))
rescue NotAKegError
@system_dylibs << dylib
rescue Errno::ENOENT
next if harmless_broken_link?(dylib)
if (dep = dylib_to_dep(dylib))
broken_dep = (@broken_deps[dep] ||= [])
broken_dep << dylib unless broken_dep.include?(dylib)
elsif system_libraries_exist_in_cache? && dylib_found_in_shared_cache?(dylib)
# If we cannot associate the dylib with a dependency, then it may be a system library.
# Check the dylib shared cache for the library to verify this.
@system_dylibs << dylib
elsif !system_framework?(dylib) && !broken_dylibs_allowed?(file.to_s)
@broken_dylibs << dylib
end
else
tap = owner.tab.tap
f = if tap.nil? || tap.core_tap?
owner.name
else
"#{tap}/#{owner.name}"
end
(@brewed_dylibs[f] ||= Set.new) << dylib
end
end
end
if (check_formula_deps = self.check_formula_deps)
@indirect_deps, @undeclared_deps, @unnecessary_deps,
@version_conflict_deps, @no_linkage_deps, @unexpected_linkage_deps = check_formula_deps
end
return unless keg_files_dylibs_was_empty
store.update!(keg_files_dylibs:)
end
sig { returns(T::Boolean) }
def system_libraries_exist_in_cache?
false
end
sig { params(dylib: String).returns(T::Boolean) }
def dylib_found_in_shared_cache?(dylib)
require "fiddle"
@dyld_shared_cache_contains_path ||= T.let(begin
libc = Fiddle.dlopen("/usr/lib/libSystem.B.dylib")
Fiddle::Function.new(
libc["_dyld_shared_cache_contains_path"],
[Fiddle::TYPE_CONST_STRING],
Fiddle::TYPE_BOOL,
)
end, T.nilable(Fiddle::Function))
@dyld_shared_cache_contains_path.call(dylib)
end
sig {
returns(T.nilable([T::Array[String], T::Array[String], T::Array[String],
T::Array[String], T::Array[String], T::Array[String]]))
}
def check_formula_deps
formula = self.formula
return if formula.nil?
filter_out = proc do |dep|
next true if dep.build? || dep.test?
(dep.optional? || dep.recommended?) && formula.build.without?(dep)
end
declared_deps_full_names = formula.deps
.reject { |dep| filter_out.call(dep) }
.map(&:name)
declared_deps_names = declared_deps_full_names.map do |dep|
dep.split("/").last
end
# Get dependencies marked with :no_linkage
no_linkage_deps_full_names = formula.deps
.reject { |dep| filter_out.call(dep) }
.select(&:no_linkage?)
.map(&:name)
no_linkage_deps_names = no_linkage_deps_full_names.map do |dep|
dep.split("/").last
end
recursive_deps = formula.runtime_formula_dependencies(undeclared: false)
.map(&:name)
indirect_deps = []
undeclared_deps = []
unexpected_linkage_deps = []
@brewed_dylibs.each_key do |full_name|
name = full_name.split("/").last
next if name == formula.name
# Check if this is a no_linkage dependency with unexpected linkage
if no_linkage_deps_names.include?(name)
unexpected_linkage_deps << full_name
next
end
if recursive_deps.include?(name)
indirect_deps << full_name unless declared_deps_names.include?(name)
else
undeclared_deps << full_name
end
end
sort_by_formula_full_name!(indirect_deps)
sort_by_formula_full_name!(undeclared_deps)
sort_by_formula_full_name!(unexpected_linkage_deps)
unnecessary_deps = declared_deps_full_names.reject do |full_name|
next true if Formula[full_name].bin.directory?
name = full_name.split("/").last
@brewed_dylibs.keys.map { |l| l.split("/").last }.include?(name)
end
# Remove no_linkage dependencies from unnecessary_deps since they're expected not to have linkage
unnecessary_deps -= no_linkage_deps_full_names
missing_deps = @broken_deps.values.flatten.map { |d| dylib_to_dep(d) }
unnecessary_deps -= missing_deps
version_hash = {}
version_conflict_deps = Set.new
@brewed_dylibs.each_key do |l|
name = l.split("/").fetch(-1)
unversioned_name, = name.split("@")
version_hash[unversioned_name] ||= Set.new
version_hash[unversioned_name] << name
next if version_hash[unversioned_name].length < 2
version_conflict_deps += version_hash[unversioned_name]
end
[indirect_deps, undeclared_deps,
unnecessary_deps, version_conflict_deps.to_a, no_linkage_deps_full_names, unexpected_linkage_deps]
end
sig { params(arr: T::Array[String]).void }
def sort_by_formula_full_name!(arr)
arr.sort! do |a, b|
if a.include?("/") && b.exclude?("/")
1
elsif a.exclude?("/") && b.include?("/")
-1
else
(a <=> b).to_i
end
end
end
# Whether or not dylib is a harmless broken link, meaning that it's
# okay to skip (and not report) as broken.
sig { params(dylib: String).returns(T::Boolean) }
def harmless_broken_link?(dylib)
# libgcc_s_* is referenced by programs that use the Java Service Wrapper,
# and is harmless on x86(_64) machines
# dyld will fall back to Apple libc++ if LLVM's is not available.
[
"/usr/lib/libgcc_s_ppc64.1.dylib",
"/opt/local/lib/libgcc/libgcc_s.1.dylib",
# TODO: Report linkage with `/usr/lib/libc++.1.dylib` when this link is broken.
"#{HOMEBREW_PREFIX}/opt/llvm/lib/libc++.1.dylib",
].include?(dylib)
end
sig { params(dylib: String).returns(T::Boolean) }
def system_framework?(dylib)
dylib.start_with?("/System/Library/Frameworks/")
end
# Display a list of things.
sig {
params(
label: String,
things: T.any(T::Array[String], T::Set[String], T::Hash[String, T::Enumerable[String]]),
puts_output: T::Boolean,
).returns(T.nilable(String))
}
def display_items(label, things, puts_output: true)
return if things.empty?
output = ["#{label}:"]
if things.is_a? Hash
things.sort.each do |list_label, items|
items.sort.each do |item|
output << "#{item} (#{list_label})"
end
end
else
output.concat(things.sort)
end
output = output.join("\n ")
puts output if puts_output
output
end
sig { params(keg: Keg).returns(T.nilable(Formula)) }
def resolve_formula(keg)
Formulary.from_keg(keg)
rescue FormulaUnavailableError
opoo "Formula unavailable: #{keg.name}"
nil
end
end
require "extend/os/linkage_checker"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask_dependent.rb | Library/Homebrew/cask_dependent.rb | # typed: strict
# frozen_string_literal: true
require "requirement"
# An adapter for casks to provide dependency information in a formula-like interface.
class CaskDependent
# Defines a dependency on another cask
class Requirement < ::Requirement
satisfy(build_env: false) do
Cask::CaskLoader.load(cask).installed?
end
end
sig { returns(Cask::Cask) }
attr_reader :cask
sig { params(cask: Cask::Cask).void }
def initialize(cask)
@cask = cask
end
sig { returns(String) }
def name
@cask.token
end
sig { returns(String) }
def full_name
@cask.full_name
end
sig { returns(T::Array[Dependency]) }
def runtime_dependencies
deps.flat_map { |dep| [dep, *dep.to_installed_formula.runtime_dependencies] }.uniq
end
sig { returns(T::Array[Dependency]) }
def deps
@deps ||= T.let(
@cask.depends_on.formula.map do |f|
Dependency.new f
end,
T.nilable(T::Array[Dependency]),
)
end
sig { returns(T::Array[::Requirement]) }
def requirements
@requirements ||= T.let(
begin
requirements = []
dsl_reqs = @cask.depends_on
dsl_reqs.arch&.each do |arch|
arch = if arch[:bits] == 64
if arch[:type] == :intel
:x86_64
else
:"#{arch[:type]}64"
end
elsif arch[:type] == :intel && arch[:bits] == 32
:i386
else
arch[:type]
end
requirements << ArchRequirement.new([arch])
end
dsl_reqs.cask.each do |cask_ref|
requirements << CaskDependent::Requirement.new([{ cask: cask_ref }])
end
requirements << dsl_reqs.macos if dsl_reqs.macos
requirements
end,
T.nilable(T::Array[::Requirement]),
)
end
sig { params(block: T.nilable(T.proc.returns(T::Array[Dependency]))).returns(T::Array[Dependency]) }
def recursive_dependencies(&block)
Dependency.expand(self, &block)
end
sig { params(block: T.nilable(T.proc.returns(CaskDependent::Requirement))).returns(Requirements) }
def recursive_requirements(&block)
Requirement.expand(self, &block)
end
sig { returns(T::Boolean) }
def any_version_installed?
@cask.installed?
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/dependencies.rb | Library/Homebrew/dependencies.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "delegate"
# A collection of dependencies.
class Dependencies < SimpleDelegator
def initialize(*args)
super(args)
end
alias eql? ==
def optional
__getobj__.select(&:optional?)
end
def recommended
__getobj__.select(&:recommended?)
end
def build
__getobj__.select(&:build?)
end
def required
__getobj__.select(&:required?)
end
def default
build + required + recommended
end
def dup_without_system_deps
self.class.new(*__getobj__.reject { |dep| dep.uses_from_macos? && dep.use_macos_install? })
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: #{__getobj__}>"
end
end
# A collection of requirements.
class Requirements < SimpleDelegator
def initialize(*args)
super(Set.new(args))
end
def <<(other)
if other.is_a?(Object) && other.is_a?(Comparable)
__getobj__.grep(other.class) do |req|
return self if req > other
__getobj__.delete(req)
end
end
# see https://sorbet.org/docs/faq#how-can-i-fix-type-errors-that-arise-from-super
T.bind(self, T.untyped)
super
self
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: {#{__getobj__.to_a.join(", ")}}>"
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/installed_dependents.rb | Library/Homebrew/installed_dependents.rb | # typed: strict
# frozen_string_literal: true
require "cask_dependent"
# Helper functions for installed dependents.
module InstalledDependents
module_function
# Given an array of kegs, this method will try to find some other kegs
# or casks that depend on them. If it does, it returns:
#
# - some kegs in the passed array that have installed dependents
# - some installed dependents of those kegs.
#
# If it doesn't, it returns nil.
#
# Note that nil will be returned if the only installed dependents of the
# passed kegs are other kegs in the array or casks present in the casks
# parameter.
#
# For efficiency, we don't bother trying to get complete data.
sig {
params(kegs: T::Array[Keg], casks: T::Array[Cask::Cask]).returns(T.nilable([T::Array[Keg], T::Array[String]]))
}
def find_some_installed_dependents(kegs, casks: [])
keg_names = kegs.select(&:optlinked?).map(&:name)
keg_formulae = []
kegs_by_source = kegs.group_by do |keg|
# First, attempt to resolve the keg to a formula
# to get up-to-date name and tap information.
f = keg.to_formula
keg_formulae << f
[f.name, f.tap]
rescue
# If the formula for the keg can't be found,
# fall back to the information in the tab.
[keg.name, keg.tab.tap]
end
all_required_kegs = Set.new
all_dependents = []
# Don't include dependencies of kegs that were in the given array.
dependents_to_check = (Formula.installed - keg_formulae) + (Cask::Caskroom.casks - casks)
dependents_to_check.each do |dependent|
required = case dependent
when Formula
dependent.missing_dependencies(hide: keg_names).map(&:to_installed_formula)
when Cask::Cask
# When checking for cask dependents, we don't care about missing or non-runtime dependencies
CaskDependent.new(dependent).runtime_dependencies.map(&:to_installed_formula)
end
required_kegs = required.filter_map do |f|
f_kegs = kegs_by_source[[f.name, f.tap]]
next unless f_kegs
f_kegs.max_by(&:scheme_and_version)
end
next if required_kegs.empty?
all_required_kegs += required_kegs
all_dependents << dependent.to_s
end
return if all_required_kegs.empty?
return if all_dependents.empty?
[all_required_kegs.to_a, all_dependents.sort]
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/pour_bottle_check.rb | Library/Homebrew/pour_bottle_check.rb | # typed: strict
# frozen_string_literal: true
class PourBottleCheck
include OnSystem::MacOSAndLinux
sig { params(formula: T.class_of(Formula)).void }
def initialize(formula)
@formula = formula
end
sig { params(reason: String).void }
def reason(reason)
@formula.pour_bottle_check_unsatisfied_reason = reason
end
sig { params(block: T.proc.void).void }
def satisfy(&block)
@formula.send(:define_method, :pour_bottle?, &block)
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/formula.rb | Library/Homebrew/formula.rb | # typed: strict
# frozen_string_literal: true
require "autobump_constants"
require "cache_store"
require "did_you_mean"
require "keg_only_reason"
require "lock_file"
require "formula_pin"
require "hardware"
require "utils"
require "utils/bottles"
require "utils/gzip"
require "utils/inreplace"
require "utils/shebang"
require "utils/shell"
require "utils/git_repository"
require "build_environment"
require "build_options"
require "formulary"
require "software_spec"
require "bottle"
require "pour_bottle_check"
require "head_software_spec"
require "bottle_specification"
require "livecheck"
require "service"
require "install_renamed"
require "pkg_version"
require "keg"
require "migrator"
require "linkage_checker"
require "extend/ENV"
require "language/java"
require "language/php"
require "language/python"
require "tab"
require "mktemp"
require "find"
require "utils/spdx"
require "on_system"
require "api"
require "api_hashable"
require "utils/output"
require "pypi_packages"
# A formula provides instructions and metadata for Homebrew to install a piece
# of software. Every Homebrew formula is a {Formula}.
# All subclasses of {Formula} (and all Ruby classes) have to be named
# `UpperCase` and `not-use-dashes`.
# A formula specified in `this-formula.rb` should have a class named
# `ThisFormula`. Homebrew does enforce that the name of the file and the class
# correspond.
# Make sure you check with `brew search` that the name is free!
# @abstract
# @see SharedEnvExtension
# @see Pathname
# @see https://www.rubydoc.info/stdlib/fileutils FileUtils
# @see https://docs.brew.sh/Formula-Cookbook Formula Cookbook
# @see https://rubystyle.guide Ruby Style Guide
#
# ### Example
#
# ```ruby
# class Wget < Formula
# homepage "https://www.gnu.org/software/wget/"
# url "https://ftp.gnu.org/gnu/wget/wget-1.15.tar.gz"
# sha256 "52126be8cf1bddd7536886e74c053ad7d0ed2aa89b4b630f76785bac21695fcd"
#
# def install
# system "./configure", "--prefix=#{prefix}"
# system "make", "install"
# end
# end
# ```
class Formula
include FileUtils
include Utils::Shebang
include Utils::Shell
include Utils::Output::Mixin
include Context
include OnSystem::MacOSAndLinux
include Homebrew::Livecheck::Constants
extend Forwardable
extend Cachable
extend APIHashable
extend T::Helpers
extend Utils::Output::Mixin
abstract!
# Used to track formulae that cannot be installed at the same time.
FormulaConflict = Struct.new(:name, :reason)
SUPPORTED_NETWORK_ACCESS_PHASES = [:build, :test, :postinstall].freeze
private_constant :SUPPORTED_NETWORK_ACCESS_PHASES
DEFAULT_NETWORK_ACCESS_ALLOWED = true
private_constant :DEFAULT_NETWORK_ACCESS_ALLOWED
# The name of this {Formula}.
# e.g. `this-formula`
#
# @api public
sig { returns(String) }
attr_reader :name
# The path to the alias that was used to identify this {Formula}.
# e.g. `/usr/local/Library/Taps/homebrew/homebrew-core/Aliases/another-name-for-this-formula`
sig { returns(T.nilable(Pathname)) }
attr_reader :alias_path
# The name of the alias that was used to identify this {Formula}.
# e.g. `another-name-for-this-formula`
sig { returns(T.nilable(String)) }
attr_reader :alias_name
# The fully-qualified name of this {Formula}.
# For core formulae it's the same as {#name}.
# e.g. `homebrew/tap-name/this-formula`
#
# @api public
sig { returns(String) }
attr_reader :full_name
# The fully-qualified alias referring to this {Formula}.
# For core formulae it's the same as {#alias_name}.
# e.g. `homebrew/tap-name/another-name-for-this-formula`
sig { returns(T.nilable(String)) }
attr_reader :full_alias_name
# The full path to this {Formula}.
# e.g. `/usr/local/Library/Taps/homebrew/homebrew-core/Formula/t/this-formula.rb`
#
# @api public
sig { returns(Pathname) }
attr_reader :path
# The {Tap} instance associated with this {Formula}.
# If it's `nil`, then this formula is loaded from a path or URL.
#
# @api internal
sig { returns(T.nilable(Tap)) }
attr_reader :tap
# The stable (and default) {SoftwareSpec} for this {Formula}.
# This contains all the attributes (e.g. URL, checksum) that apply to the
# stable version of this formula.
#
# @api internal
sig { returns(T.nilable(SoftwareSpec)) }
attr_reader :stable
# The HEAD {SoftwareSpec} for this {Formula}.
# Installed when using `brew install --HEAD`.
# This is always installed with the version `HEAD` and taken from the latest
# commit in the version control system.
# `nil` if there is no HEAD version.
#
# @see #stable
sig { returns(T.nilable(SoftwareSpec)) }
attr_reader :head
# The currently active {SoftwareSpec}.
# @see #determine_active_spec
sig { returns(SoftwareSpec) }
attr_reader :active_spec
protected :active_spec
# A symbol to indicate currently active {SoftwareSpec}.
# It's either `:stable` or `:head`.
# @see #active_spec
sig { returns(Symbol) }
attr_reader :active_spec_sym
# The most recent modified time for source files.
sig { returns(T.nilable(Time)) }
attr_reader :source_modified_time
# Used for creating new Homebrew versions of software without new upstream
# versions.
# @see .revision=
sig { returns(Integer) }
attr_reader :revision
# Used to change version schemes for packages.
# @see .version_scheme=
sig { returns(Integer) }
attr_reader :version_scheme
# Used to indicate API/ABI compatibility for dependencies.
# @see .compatibility_version=
sig { returns(T.nilable(Integer)) }
attr_reader :compatibility_version
# The current working directory during builds.
# Will only be non-`nil` inside {#install}.
sig { returns(T.nilable(Pathname)) }
attr_reader :buildpath
# The current working directory during tests.
# Will only be non-`nil` inside {.test}.
sig { returns(T.nilable(Pathname)) }
attr_reader :testpath
# When installing a bottle (binary package) from a local path this will be
# set to the full path to the bottle tarball. If not, it will be `nil`.
sig { returns(T.nilable(Pathname)) }
attr_accessor :local_bottle_path
# When performing a build, test, or other loggable action, indicates which
# log file location to use.
sig { returns(T.nilable(String)) }
attr_reader :active_log_type
# The {BuildOptions} or {Tab} for this {Formula}. Lists the arguments passed
# and any {.option}s in the {Formula}. Note that these may differ at
# different times during the installation of a {Formula}. This is annoying
# but is the result of state that we're trying to eliminate.
sig { returns(T.any(BuildOptions, Tab)) }
attr_reader :build
# Information about PyPI mappings for this {Formula} is stored
# as {PypiPackages} object.
sig { returns(PypiPackages) }
attr_reader :pypi_packages_info
# Whether this formula should be considered outdated
# if the target of the alias it was installed with has since changed.
# Defaults to true.
sig { returns(T::Boolean) }
attr_accessor :follow_installed_alias
alias follow_installed_alias? follow_installed_alias
# Whether or not to force the use of a bottle.
sig { returns(T::Boolean) }
attr_accessor :force_bottle
sig {
params(name: String, path: Pathname, spec: Symbol, alias_path: T.nilable(Pathname),
tap: T.nilable(Tap), force_bottle: T::Boolean).void
}
def initialize(name, path, spec, alias_path: nil, tap: nil, force_bottle: false)
# Only allow instances of subclasses. The base class does not hold any spec information (URLs etc).
raise "Do not call `Formula.new' directly without a subclass." unless self.class < Formula
# Stop any subsequent modification of a formula's definition.
# Changes do not propagate to existing instances of formulae.
# Now that we have an instance, it's too late to make any changes to the class-level definition.
self.class.freeze
@name = name
@unresolved_path = path
@path = T.let(path.resolved_path, Pathname)
@alias_path = alias_path
@alias_name = T.let((File.basename(alias_path) if alias_path), T.nilable(String))
@revision = T.let(self.class.revision || 0, Integer)
@version_scheme = T.let(self.class.version_scheme || 0, Integer)
@compatibility_version = T.let(self.class.compatibility_version, T.nilable(Integer))
@head = T.let(nil, T.nilable(SoftwareSpec))
@stable = T.let(nil, T.nilable(SoftwareSpec))
@autobump = T.let(true, T::Boolean)
@no_autobump_message = T.let(nil, T.nilable(T.any(String, Symbol)))
@force_bottle = force_bottle
@tap = T.let(tap, T.nilable(Tap))
@tap ||= if path == Formulary.core_path(name)
CoreTap.instance
else
Tap.from_path(path)
end
@pypi_packages_info = T.let(self.class.pypi_packages_info || PypiPackages.new, PypiPackages)
@full_name = T.let(T.must(full_name_with_optional_tap(name)), String)
@full_alias_name = T.let(full_name_with_optional_tap(@alias_name), T.nilable(String))
self.class.spec_syms.each do |sym|
spec_eval sym
end
@active_spec = T.let(determine_active_spec(spec), SoftwareSpec)
@active_spec_sym = T.let(head? ? :head : :stable, Symbol)
validate_attributes!
@build = T.let(active_spec.build, T.any(BuildOptions, Tab))
@pin = T.let(FormulaPin.new(self), FormulaPin)
@follow_installed_alias = T.let(true, T::Boolean)
@prefix_returns_versioned_prefix = T.let(false, T.nilable(T::Boolean))
@oldname_locks = T.let([], T::Array[FormulaLock])
@on_system_blocks_exist = T.let(false, T::Boolean)
@fully_loaded_formula = T.let(nil, T.nilable(Formula))
end
sig { params(spec_sym: Symbol).void }
def active_spec=(spec_sym)
spec = send(spec_sym)
raise FormulaSpecificationError, "#{spec_sym} spec is not available for #{full_name}" unless spec
old_spec_sym = @active_spec_sym
@active_spec = spec
@active_spec_sym = spec_sym
validate_attributes!
@build = active_spec.build
return if spec_sym == old_spec_sym
Dependency.clear_cache
Requirement.clear_cache
end
sig { params(build_options: T.any(BuildOptions, Tab)).void }
def build=(build_options)
old_options = @build
@build = build_options
return if old_options.used_options == build_options.used_options &&
old_options.unused_options == build_options.unused_options
Dependency.clear_cache
Requirement.clear_cache
end
# Ensure the given formula is installed.
# This is useful for installing a utility formula (e.g. `shellcheck` for `brew style`).
sig {
params(
reason: String,
latest: T::Boolean,
output_to_stderr: T::Boolean,
quiet: T::Boolean,
).returns(T.self_type)
}
def ensure_installed!(reason: "", latest: false, output_to_stderr: true, quiet: false)
if output_to_stderr || quiet
file = if quiet
File::NULL
else
$stderr
end
# Call this method itself with redirected stdout
redirect_stdout(file) do
return ensure_installed!(latest:, reason:, output_to_stderr: false)
end
end
reason = " for #{reason}" if reason.present?
unless any_version_installed?
ohai "Installing `#{name}`#{reason}..."
safe_system HOMEBREW_BREW_FILE, "install", "--formula", full_name
end
if latest && !latest_version_installed?
ohai "Upgrading `#{name}`#{reason}..."
safe_system HOMEBREW_BREW_FILE, "upgrade", "--formula", full_name
end
self
end
sig { returns(T::Boolean) }
def preserve_rpath? = self.class.preserve_rpath?
private
# Allow full name logic to be re-used between names, aliases and installed aliases.
sig { params(name: T.nilable(String)).returns(T.nilable(String)) }
def full_name_with_optional_tap(name)
if name.nil? || @tap.nil? || @tap.core_tap?
name
else
"#{@tap}/#{name}"
end
end
sig { params(name: T.any(String, Symbol)).void }
def spec_eval(name)
spec = self.class.send(name).dup
return unless spec.url
spec.owner = self
add_global_deps_to_spec(spec)
instance_variable_set(:"@#{name}", spec)
end
sig { params(spec: SoftwareSpec).void }
def add_global_deps_to_spec(spec); end
sig { params(requested: T.any(String, Symbol)).returns(SoftwareSpec) }
def determine_active_spec(requested)
spec = send(requested) || stable || head
spec || raise(FormulaSpecificationError, "#{full_name}: formula requires at least a URL")
end
sig { void }
def validate_attributes!
if name.blank? || name.match?(/\s/) || !Utils.safe_filename?(name)
raise FormulaValidationError.new(full_name, :name, name)
end
url = active_spec.url
raise FormulaValidationError.new(full_name, :url, url) if url.blank? || url.match?(/\s/)
val = version.respond_to?(:to_str) ? version.to_str : version
return if val.present? && !val.match?(/\s/) && Utils.safe_filename?(val)
raise FormulaValidationError.new(full_name, :version, val)
end
public
# The alias path that was used to install this formula, if it exists.
# Can differ from {#alias_path}, which is the alias used to find the formula,
# and is specified to this instance.
sig { returns(T.nilable(Pathname)) }
def installed_alias_path
build_tab = build
path = build_tab.source["path"] if build_tab.is_a?(Tab)
return unless path&.match?(%r{#{HOMEBREW_TAP_DIR_REGEX}/Aliases}o)
path = Pathname(path)
return unless path.symlink?
path
end
sig { returns(T.nilable(String)) }
def installed_alias_name = installed_alias_path&.basename&.to_s
sig { returns(T.nilable(String)) }
def full_installed_alias_name = full_name_with_optional_tap(installed_alias_name)
sig { returns(Pathname) }
def tap_path
return path unless (t = tap)
return Formulary.core_path(name) if t.core_tap?
return path unless t.installed?
t.formula_files_by_name[name] || path
end
# The path that was specified to find this formula.
sig { returns(T.nilable(Pathname)) }
def specified_path
return Homebrew::API::Formula.cached_json_file_path if loaded_from_api?
return alias_path if alias_path&.exist?
return @unresolved_path if @unresolved_path.exist?
return local_bottle_path if local_bottle_path.presence&.exist?
alias_path || @unresolved_path
end
# The name specified to find this formula.
sig { returns(String) }
def specified_name
alias_name || name
end
# The name (including tap) specified to find this formula.
sig { returns(String) }
def full_specified_name
full_alias_name || full_name
end
# The name specified to install this formula.
sig { returns(String) }
def installed_specified_name
installed_alias_name || name
end
# The name (including tap) specified to install this formula.
sig { returns(String) }
def full_installed_specified_name
full_installed_alias_name || full_name
end
# Is the currently active {SoftwareSpec} a {#stable} build?
sig { returns(T::Boolean) }
def stable?
active_spec == stable
end
# Is the currently active {SoftwareSpec} a {#head} build?
sig { returns(T::Boolean) }
def head?
active_spec == head
end
# Is this formula HEAD-only?
sig { returns(T::Boolean) }
def head_only?
!!head && !stable
end
# Stop RuboCop from erroneously indenting hash target
delegate [ # rubocop:disable Layout/HashAlignment
:bottle_defined?,
:bottle_tag?,
:bottled?,
:bottle_specification,
:downloader,
] => :active_spec
# The {Bottle} object for the currently active {SoftwareSpec}.
sig { returns(T.nilable(Bottle)) }
def bottle
@bottle ||= T.let(Bottle.new(self, bottle_specification), T.nilable(Bottle)) if bottled?
end
# The {Bottle} object for given tag.
sig { params(tag: T.nilable(Utils::Bottles::Tag)).returns(T.nilable(Bottle)) }
def bottle_for_tag(tag = nil)
Bottle.new(self, bottle_specification, tag) if bottled?(tag)
end
# The description of the software.
# @!method desc
# @see .desc
delegate desc: :"self.class"
# The SPDX ID of the software license.
# @!method license
# @see .license
delegate license: :"self.class"
# The homepage for the software.
# @!method homepage
# @see .homepage
delegate homepage: :"self.class"
# The `livecheck` specification for the software.
# @!method livecheck
# @see .livecheck
delegate livecheck: :"self.class"
# Is a `livecheck` specification defined for the software?
# @!method livecheck_defined?
# @see .livecheck_defined?
delegate livecheck_defined?: :"self.class"
# This is a legacy alias for `#livecheck_defined?`.
# @!method livecheckable?
# @see .livecheckable?
delegate livecheckable?: :"self.class"
# Exclude the formula from the autobump list.
# @!method no_autobump!
# @see .no_autobump!
delegate no_autobump!: :"self.class"
# Is the formula in the autobump list?
# @!method autobump?
# @see .autobump?
delegate autobump?: :"self.class"
# Is a `no_autobump!` method defined?
# @!method no_autobump_defined?
# @see .no_autobump_defined?
delegate no_autobump_defined?: :"self.class"
delegate no_autobump_message: :"self.class"
# Is a service specification defined for the software?
# @!method service?
# @see .service?
delegate service?: :"self.class"
# The version for the currently active {SoftwareSpec}.
# The version is autodetected from the URL and/or tag so only needs to be
# declared if it cannot be autodetected correctly.
# @!method version
# @see .version
delegate version: :active_spec
# Stop RuboCop from erroneously indenting hash target
delegate [ # rubocop:disable Layout/HashAlignment
:allow_network_access!,
:deny_network_access!,
:network_access_allowed?,
] => :"self.class"
# Whether this formula was loaded using the formulae.brew.sh API.
# @!method loaded_from_api?
# @see .loaded_from_api?
delegate loaded_from_api?: :"self.class"
# Whether this formula was loaded using the formulae.brew.sh API.
# @!method loaded_from_stub?
# @see .loaded_from_stub?
delegate loaded_from_stub?: :"self.class"
# The API source data used to load this formula.
# Returns `nil` if the formula was not loaded from the API.
# @!method api_source
# @see .api_source
delegate api_source: :"self.class"
sig { returns(Formula) }
def fully_loaded_formula
@fully_loaded_formula ||= if loaded_from_stub?
json_contents = Homebrew::API::Formula.formula_json(name)
Formulary.from_json_contents(name, json_contents)
else
self
end
end
sig { params(download_queue: T.nilable(Homebrew::DownloadQueue)).void }
def fetch_fully_loaded_formula!(download_queue: nil)
return unless loaded_from_stub?
Homebrew::API::Formula.fetch_formula_json!(name, download_queue:)
end
sig { void }
def update_head_version
return unless head?
head_spec = T.must(head)
return unless head_spec.downloader.is_a?(VCSDownloadStrategy)
return unless head_spec.downloader.cached_location.exist?
path = if ENV["HOMEBREW_ENV"]
ENV.fetch("PATH")
else
PATH.new(ORIGINAL_PATHS)
end
with_env(PATH: path) do
head_spec.version.update_commit(head_spec.downloader.last_commit)
end
end
# The {PkgVersion} for this formula with {version} and {#revision} information.
sig { returns(PkgVersion) }
def pkg_version = PkgVersion.new(version, revision)
# If this is a `@`-versioned formula.
sig { returns(T::Boolean) }
def versioned_formula? = name.include?("@")
# Returns any other `@`-versioned formulae names for any Formula (including versioned formulae).
sig { returns(T::Array[String]) }
def versioned_formulae_names
versioned_names = if tap
name_prefix = name.gsub(/(@[\d.]+)?$/, "")
T.must(tap).prefix_to_versioned_formulae_names.fetch(name_prefix, [])
elsif path.exist?
Pathname.glob(path.to_s.gsub(/(@[\d.]+)?\.rb$/, "@*.rb"))
.map { |path| path.basename(".rb").to_s }
.sort
else
raise "Either tap or path is required to list versioned formulae"
end
versioned_names.reject do |versioned_name|
versioned_name == name
end
end
# Returns any `@`-versioned Formula objects for any Formula (including versioned formulae).
sig { returns(T::Array[Formula]) }
def versioned_formulae
versioned_formulae_names.filter_map do |name|
Formula[name]
rescue FormulaUnavailableError
nil
end.sort_by(&:version).reverse
end
# Whether this {Formula} is version-synced with other formulae.
sig { returns(T::Boolean) }
def synced_with_other_formulae?
return false if @tap.nil?
@tap.synced_versions_formulae.any? { |synced_formulae| synced_formulae.include?(name) }
end
# A named {Resource} for the currently active {SoftwareSpec}.
# Additional downloads can be defined as {#resource}s.
# {Resource#stage} will create a temporary directory and yield to a block.
#
# ### Example
#
# ```ruby
# resource("additional_files").stage { bin.install "my/extra/tool" }
# ```
#
# FIXME: This should not actually take a block. All resources should be defined
# at the top-level using {Formula.resource} instead
# (see https://github.com/Homebrew/brew/issues/17203#issuecomment-2093654431).
#
# @api public
sig {
params(name: String, klass: T.class_of(Resource), block: T.nilable(T.proc.bind(Resource).void))
.returns(T.nilable(Resource))
}
def resource(name = T.unsafe(nil), klass = T.unsafe(nil), &block)
if klass.nil?
active_spec.resource(*name, &block)
else
active_spec.resource(name, klass, &block)
end
end
# Old names for the formula.
#
# @api internal
sig { returns(T::Array[String]) }
def oldnames
@oldnames ||= T.let(
if (tap = self.tap)
Tap.tap_migration_oldnames(tap, name) + tap.formula_reverse_renames.fetch(name, [])
else
[]
end, T.nilable(T::Array[String])
)
end
# All aliases for the formula.
#
# @api internal
sig { returns(T::Array[String]) }
def aliases
@aliases ||= T.let(
if (tap = self.tap)
tap.alias_reverse_table.fetch(full_name, []).map { it.split("/").fetch(-1) }
else
[]
end, T.nilable(T::Array[String])
)
end
# The {Resource}s for the currently active {SoftwareSpec}.
# @!method resources
def_delegator :"active_spec.resources", :values, :resources
# The {Dependency}s for the currently active {SoftwareSpec}.
#
# @api internal
delegate deps: :active_spec
# The declared {Dependency}s for the currently active {SoftwareSpec} (i.e. including those provided by macOS).
delegate declared_deps: :active_spec
# The {Requirement}s for the currently active {SoftwareSpec}.
delegate requirements: :active_spec
# The cached download for the currently active {SoftwareSpec}.
delegate cached_download: :active_spec
# Deletes the download for the currently active {SoftwareSpec}.
delegate clear_cache: :active_spec
# The list of patches for the currently active {SoftwareSpec}.
def_delegator :active_spec, :patches, :patchlist
# The options for the currently active {SoftwareSpec}.
delegate options: :active_spec
# The deprecated options for the currently active {SoftwareSpec}.
delegate deprecated_options: :active_spec
# The deprecated option flags for the currently active {SoftwareSpec}.
delegate deprecated_flags: :active_spec
# If a named option is defined for the currently active {SoftwareSpec}.
# @!method option_defined?
delegate option_defined?: :active_spec
# All the {.fails_with} for the currently active {SoftwareSpec}.
delegate compiler_failures: :active_spec
# If this {Formula} is installed.
# This is actually just a check for if the {#latest_installed_prefix} directory
# exists and is not empty.
sig { returns(T::Boolean) }
def latest_version_installed?
(dir = latest_installed_prefix).directory? && !dir.children.empty?
end
# If at least one version of {Formula} is installed.
#
# @api public
sig { returns(T::Boolean) }
def any_version_installed?
installed_prefixes.any? { |keg| (keg/AbstractTab::FILENAME).file? }
end
# The link status symlink directory for this {Formula}.
# You probably want {#opt_prefix} instead.
#
# @api internal
sig { returns(Pathname) }
def linked_keg
linked_keg = possible_names.map { |name| HOMEBREW_LINKED_KEGS/name }
.find(&:directory?)
return linked_keg if linked_keg.present?
HOMEBREW_LINKED_KEGS/name
end
sig { returns(T.nilable(PkgVersion)) }
def latest_head_version
head_versions = installed_prefixes.filter_map do |pn|
pn_pkgversion = PkgVersion.parse(pn.basename.to_s)
pn_pkgversion if pn_pkgversion.head?
end
head_versions.max_by do |pn_pkgversion|
[Keg.new(prefix(pn_pkgversion)).tab.source_modified_time, pn_pkgversion.revision]
end
end
sig { returns(T.nilable(Pathname)) }
def latest_head_prefix
head_version = latest_head_version
prefix(head_version) if head_version
end
sig { params(version: PkgVersion, fetch_head: T::Boolean).returns(T::Boolean) }
def head_version_outdated?(version, fetch_head: false)
tab = Tab.for_keg(prefix(version))
return true if tab.version_scheme < version_scheme
tab_stable_version = tab.stable_version
return true if stable && tab_stable_version && tab_stable_version < T.must(stable).version
return false unless fetch_head
return false unless head&.downloader.is_a?(VCSDownloadStrategy)
downloader = T.must(head).downloader
with_context quiet: true do
downloader.commit_outdated?(version.version.commit)
end
end
sig { params(fetch_head: T::Boolean).returns(PkgVersion) }
def latest_head_pkg_version(fetch_head: false)
return pkg_version unless (latest_version = latest_head_version)
return latest_version unless head_version_outdated?(latest_version, fetch_head:)
downloader = T.must(head).downloader
with_context quiet: true do
PkgVersion.new(Version.new("HEAD-#{downloader.last_commit}"), revision)
end
end
# The latest prefix for this formula. Checks for {#head} and then {#stable}'s {#prefix}.
sig { returns(Pathname) }
def latest_installed_prefix
if head && (head_version = latest_head_version) && !head_version_outdated?(head_version)
T.must(latest_head_prefix)
elsif stable && (stable_prefix = prefix(PkgVersion.new(T.must(stable).version, revision))).directory?
stable_prefix
else
prefix
end
end
# The directory in the Cellar that the formula is installed to.
# This directory points to {#opt_prefix} if it exists and if {#prefix} is not
# called from within the same formula's {#install} or {#post_install} methods.
# Otherwise, return the full path to the formula's keg (versioned Cellar path).
#
# @api public
sig { params(version: T.any(String, PkgVersion)).returns(Pathname) }
def prefix(version = pkg_version)
versioned_prefix = versioned_prefix(version)
version = PkgVersion.parse(version) if version.is_a?(String)
if !@prefix_returns_versioned_prefix && version == pkg_version &&
versioned_prefix.directory? && Keg.new(versioned_prefix).optlinked?
opt_prefix
else
versioned_prefix
end
end
# Is the formula linked?
#
# @api internal
sig { returns(T::Boolean) }
def linked? = linked_keg.exist?
# Is the formula linked to `opt`?
sig { returns(T::Boolean) }
def optlinked? = opt_prefix.symlink?
# If a formula's linked keg points to the prefix.
sig { params(version: T.any(String, PkgVersion)).returns(T::Boolean) }
def prefix_linked?(version = pkg_version)
return false unless linked?
linked_keg.resolved_path == versioned_prefix(version)
end
# {PkgVersion} of the linked keg for the formula.
sig { returns(T.nilable(PkgVersion)) }
def linked_version
return unless linked?
Keg.for(linked_keg).version
end
# The parent of the prefix; the named directory in the Cellar containing all
# installed versions of this software.
sig { returns(Pathname) }
def rack = HOMEBREW_CELLAR/name
# All currently installed prefix directories.
sig { returns(T::Array[Pathname]) }
def installed_prefixes
possible_names.map { |name| HOMEBREW_CELLAR/name }
.select(&:directory?)
.flat_map(&:subdirs)
.sort_by(&:basename)
end
# All currently installed kegs.
sig { returns(T::Array[Keg]) }
def installed_kegs
installed_prefixes.map { |dir| Keg.new(dir) }
end
# The directory where the formula's binaries should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# ### Examples
#
# Need to install into the {.bin} but the makefile doesn't `mkdir -p prefix/bin`?
#
# ```ruby
# bin.mkpath
# ```
#
# No `make install` available?
#
# ```ruby
# bin.install "binary1"
# ```
#
# @api public
sig { returns(Pathname) }
def bin = prefix/"bin"
# The directory where the formula's documentation should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# @api public
sig { returns(Pathname) }
def doc = share/"doc"/name
# The directory where the formula's headers should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# ### Example
#
# No `make install` available?
#
# ```ruby
# include.install "example.h"
# ```
#
# @api public
sig { returns(Pathname) }
def include = prefix/"include"
# The directory where the formula's info files should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# @api public
sig { returns(Pathname) }
def info = share/"info"
# The directory where the formula's libraries should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# ### Example
#
# No `make install` available?
#
# ```ruby
# lib.install "example.dylib"
# ```
#
# @api public
sig { returns(Pathname) }
def lib = prefix/"lib"
# The directory where the formula's binaries should be installed.
# This is not symlinked into `HOMEBREW_PREFIX`.
# It is commonly used to install files that we do not wish to be
# symlinked into `HOMEBREW_PREFIX` from one of the other directories and
# instead manually create symlinks or wrapper scripts into e.g. {#bin}.
#
# ### Example
#
# ```ruby
# libexec.install "foo.jar"
# bin.write_jar_script libexec/"foo.jar", "foo"
# ```
#
# @api public
sig { returns(Pathname) }
def libexec = prefix/"libexec"
# The root directory where the formula's manual pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
# Often one of the more specific `man` functions should be used instead,
# e.g. {#man1}.
#
# @api public
sig { returns(Pathname) }
def man = share/"man"
# The directory where the formula's man1 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# ### Example
#
# No `make install` available?
#
# ```ruby
# man1.install "example.1"
# ```
#
# @api public
sig { returns(Pathname) }
def man1 = man/"man1"
# The directory where the formula's man2 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# @api public
sig { returns(Pathname) }
def man2 = man/"man2"
# The directory where the formula's man3 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# ### Example
#
# No `make install` available?
#
# ```ruby
# man3.install "man.3"
# ```
#
# @api public
sig { returns(Pathname) }
def man3 = man/"man3"
# The directory where the formula's man4 pages should be installed.
# This is symlinked into `HOMEBREW_PREFIX` after installation or with
# `brew link` for formulae that are not keg-only.
#
# @api public
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/abstract_command.rb | Library/Homebrew/abstract_command.rb | # typed: strong
# frozen_string_literal: true
require "cli/parser"
require "shell_command"
require "utils/output"
module Homebrew
# Subclass this to implement a `brew` command. This is preferred to declaring a named function in the `Homebrew`
# module, because:
#
# - Each Command lives in an isolated namespace.
# - Each Command implements a defined interface.
# - `args` is available as an instance method and thus does not need to be passed as an argument to helper methods.
# - Subclasses no longer need to reference `CLI::Parser` or parse args explicitly.
#
# To subclass, implement a `run` method and provide a `cmd_args` block to document the command and its allowed args.
# To generate method signatures for command args, run `brew typecheck --update`.
#
# @api public
class AbstractCommand
extend T::Helpers
include Utils::Output::Mixin
abstract!
class << self
sig { returns(T.nilable(T.class_of(CLI::Args))) }
attr_reader :args_class
sig { returns(String) }
def command_name
require "utils"
Utils.underscore(T.must(name).split("::").fetch(-1))
.tr("_", "-")
.delete_suffix("-cmd")
end
# @return the AbstractCommand subclass associated with the brew CLI command name.
sig { params(name: String).returns(T.nilable(T.class_of(AbstractCommand))) }
def command(name) = subclasses.find { it.command_name == name }
sig { returns(T::Boolean) }
def dev_cmd? = T.must(name).start_with?("Homebrew::DevCmd")
sig { returns(T::Boolean) }
def ruby_cmd? = !include?(Homebrew::ShellCommand)
sig { returns(CLI::Parser) }
def parser = CLI::Parser.new(self, &@parser_block)
private
# The description and arguments of the command should be defined within this block.
#
# @api public
sig { params(block: T.proc.bind(CLI::Parser).void).void }
def cmd_args(&block)
@parser_block = T.let(block, T.nilable(T.proc.void))
@args_class = T.let(const_set(:Args, Class.new(CLI::Args)), T.nilable(T.class_of(CLI::Args)))
end
end
sig { returns(CLI::Args) }
attr_reader :args
sig { params(argv: T::Array[String]).void }
def initialize(argv = ARGV.freeze)
@args = T.let(self.class.parser.parse(argv), CLI::Args)
end
# This method will be invoked when the command is run.
#
# @api public
sig { abstract.void }
def run; end
end
module Cmd
# The command class for `brew` itself, allowing its args to be parsed.
class Brew < AbstractCommand
sig { override.void }
def run; 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/keg.rb | Library/Homebrew/keg.rb | # typed: strict
# frozen_string_literal: true
require "keg_relocate"
require "language/python"
require "lock_file"
require "cachable"
require "utils/output"
# Installation prefix of a formula.
class Keg
extend Cachable
include Utils::Output::Mixin
# Error for when a keg is already linked.
class AlreadyLinkedError < RuntimeError
sig { params(keg: Keg).void }
def initialize(keg)
super <<~EOS
Cannot link #{keg.name}
Another version is already linked: #{keg.linked_keg_record.resolved_path}
EOS
end
end
# Error for when a keg cannot be linked.
class LinkError < RuntimeError
sig { returns(Keg) }
attr_reader :keg
sig { returns(Pathname) }
attr_reader :src, :dst
sig { params(keg: Keg, src: Pathname, dst: Pathname, cause: Exception).void }
def initialize(keg, src, dst, cause)
@src = src
@dst = dst
@keg = keg
@cause = cause
super(cause.message)
set_backtrace(cause.backtrace)
end
end
# Error for when a file already exists or belongs to another keg.
class ConflictError < LinkError
sig { returns(String) }
def suggestion
conflict = Keg.for(dst)
rescue NotAKegError, Errno::ENOENT
"already exists. You may want to remove it:\n rm '#{dst}'\n"
else
<<~EOS
is a symlink belonging to #{conflict.name}. You can unlink it:
brew unlink #{conflict.name}
EOS
end
sig { returns(String) }
def to_s
s = []
s << "Could not symlink #{src}"
s << "Target #{dst}" << suggestion
s << <<~EOS
To force the link and overwrite all conflicting files:
brew link --overwrite #{keg.name}
To list all files that would be deleted:
brew link --overwrite #{keg.name} --dry-run
EOS
s.join("\n")
end
end
# Error for when a directory is not writable.
class DirectoryNotWritableError < LinkError
sig { returns(String) }
def to_s
<<~EOS
Could not symlink #{src}
#{dst.dirname} is not writable.
EOS
end
end
# Locale-specific directories have the form `language[_territory][.codeset][@modifier]`
LOCALEDIR_RX = %r{(locale|man)/([a-z]{2}|C|POSIX)(_[A-Z]{2})?(\.[a-zA-Z\-0-9]+(@.+)?)?}
INFOFILE_RX = %r{info/([^.].*?\.info(\.gz)?|dir)$}
# These paths relative to the keg's share directory should always be real
# directories in the prefix, never symlinks.
SHARE_PATHS = %w[
aclocal doc info java locale man
man/man1 man/man2 man/man3 man/man4
man/man5 man/man6 man/man7 man/man8
man/cat1 man/cat2 man/cat3 man/cat4
man/cat5 man/cat6 man/cat7 man/cat8
applications gnome gnome/help icons
mime-info pixmaps sounds postgresql
].freeze
ELISP_EXTENSIONS = %w[.el .elc].freeze
PYC_EXTENSIONS = %w[.pyc .pyo].freeze
LIBTOOL_EXTENSIONS = %w[.la .lai].freeze
KEEPME_FILE = ".keepme"
# @param path if this is a file in a keg, returns the containing {Keg} object.
sig { params(path: Pathname).returns(Keg) }
def self.for(path)
original_path = path
raise Errno::ENOENT, original_path.to_s unless original_path.exist?
if (path = original_path.realpath)
until path.root?
return Keg.new(path) if path.parent.parent == HOMEBREW_CELLAR.realpath
path = path.parent.realpath # realpath() prevents root? failing
end
end
raise NotAKegError, "#{original_path} is not inside a keg"
end
sig { params(rack: Pathname).returns(T.nilable(Keg)) }
def self.from_rack(rack)
return unless rack.directory?
kegs = rack.subdirs.map { |d| new(d) }
kegs.find(&:linked?) || kegs.find(&:optlinked?) || kegs.max_by(&:scheme_and_version)
end
sig { returns(T::Array[Keg]) }
def self.all
Formula.racks.flat_map(&:subdirs).map { |d| new(d) }
end
sig { returns(T::Array[String]) }
def self.keg_link_directories
@keg_link_directories ||= T.let(%w[
bin etc include lib sbin share var
].freeze, T.nilable(T::Array[String]))
end
sig { returns(T::Array[Pathname]) }
def self.must_exist_subdirectories
@must_exist_subdirectories ||= T.let((keg_link_directories - %w[var] + %w[
opt
var/homebrew/linked
]).map { |dir| HOMEBREW_PREFIX/dir }.sort.uniq.freeze, T.nilable(T::Array[Pathname]))
end
# Keep relatively in sync with
# {https://github.com/Homebrew/install/blob/HEAD/install.sh}
sig { returns(T::Array[Pathname]) }
def self.must_exist_directories
@must_exist_directories ||= T.let((must_exist_subdirectories + [
HOMEBREW_CELLAR,
].sort.uniq).freeze, T.nilable(T::Array[Pathname]))
end
# Keep relatively in sync with
# {https://github.com/Homebrew/install/blob/HEAD/install.sh}
sig { returns(T::Array[Pathname]) }
def self.must_be_writable_directories
@must_be_writable_directories ||= T.let((%w[
etc/bash_completion.d lib/pkgconfig
share/aclocal share/doc share/info share/locale share/man
share/man/man1 share/man/man2 share/man/man3 share/man/man4
share/man/man5 share/man/man6 share/man/man7 share/man/man8
share/zsh share/zsh/site-functions
share/pwsh share/pwsh/completions
var/log
].map { |dir| HOMEBREW_PREFIX/dir } + must_exist_subdirectories + [
HOMEBREW_CACHE,
HOMEBREW_CELLAR,
HOMEBREW_LOCKS,
HOMEBREW_LOGS,
HOMEBREW_REPOSITORY,
Language::Python.homebrew_site_packages,
]).sort.uniq.freeze, T.nilable(T::Array[Pathname]))
end
sig { returns(String) }
attr_reader :name
sig { returns(Pathname) }
attr_reader :path, :linked_keg_record, :opt_record
protected :path
extend Forwardable
def_delegators :path,
:to_path, :hash, :abv, :disk_usage, :file_count, :directory?, :exist?, :/,
:join, :rename, :find
sig { params(path: Pathname).void }
def initialize(path)
path = path.resolved_path if path.to_s.start_with?("#{HOMEBREW_PREFIX}/opt/")
raise "#{path} is not a valid keg" if path.parent.parent.realpath != HOMEBREW_CELLAR.realpath
raise "#{path} is not a directory" unless path.directory?
@path = path
@name = T.let(path.parent.basename.to_s, String)
@linked_keg_record = T.let(HOMEBREW_LINKED_KEGS/name, Pathname)
@opt_record = T.let(HOMEBREW_PREFIX/"opt/#{name}", Pathname)
@oldname_opt_records = T.let([], T::Array[Pathname])
@require_relocation = false
end
sig { returns(Pathname) }
def rack
path.parent
end
sig { returns(String) }
def to_s = path.to_s
sig { returns(String) }
def inspect
"#<#{self.class.name}:#{path}>"
end
sig { params(other: T.anything).returns(T::Boolean) }
def ==(other)
case other
when Keg
instance_of?(other.class) && path == other.path
else
false
end
end
alias eql? ==
sig { returns(T::Boolean) }
def empty_installation?
Pathname.glob("#{path}/*") do |file|
return false if file.directory? && !file.children.reject(&:ds_store?).empty?
basename = file.basename.to_s
require "metafiles"
next if Metafiles.copy?(basename)
next if %w[.DS_Store INSTALL_RECEIPT.json].include?(basename)
return false
end
true
end
sig { returns(T::Boolean) }
def require_relocation? = @require_relocation
sig { returns(T::Boolean) }
def linked?
linked_keg_record.symlink? &&
linked_keg_record.directory? &&
path == linked_keg_record.resolved_path
end
sig { void }
def remove_linked_keg_record
linked_keg_record.unlink
linked_keg_record.parent.rmdir_if_possible
end
sig { returns(T::Boolean) }
def optlinked?
opt_record.symlink? && path == opt_record.resolved_path
end
sig { void }
def remove_old_aliases
opt = opt_record.parent
linkedkegs = linked_keg_record.parent
tap = begin
to_formula.tap
rescue
# If the formula can't be found, just ignore aliases for now.
nil
end
if tap
bad_tap_opt = opt/tap.user
FileUtils.rm_rf bad_tap_opt if !bad_tap_opt.symlink? && bad_tap_opt.directory?
end
aliases.each do |a|
# versioned aliases are handled below
next if a.match?(/.+@./)
remove_alias_symlink(opt/a, opt_record)
remove_alias_symlink(linkedkegs/a, linked_keg_record)
end
Pathname.glob("#{opt_record}@*").each do |a|
a = a.basename.to_s
next if aliases.include?(a)
remove_alias_symlink(opt/a, rack)
remove_alias_symlink(linkedkegs/a, rack)
end
end
sig { void }
def remove_opt_record
opt_record.unlink
opt_record.parent.rmdir_if_possible
end
sig { params(raise_failures: T::Boolean).void }
def uninstall(raise_failures: false)
CacheStoreDatabase.use(:linkage) do |db|
break unless db.created?
LinkageCacheStore.new(path, db).delete!
end
FileUtils.rm_r(path)
path.parent.rmdir_if_possible
remove_opt_record if optlinked?
remove_linked_keg_record if linked?
remove_old_aliases
remove_oldname_opt_records
rescue Errno::EACCES, Errno::ENOTEMPTY
raise if raise_failures
odie <<~EOS
Could not remove #{name} keg! Do so manually:
sudo rm -rf #{path}
EOS
end
sig { void }
def ignore_interrupts_and_uninstall!
ignore_interrupts do
uninstall
end
end
sig { params(verbose: T::Boolean, dry_run: T::Boolean).returns(Integer) }
def unlink(verbose: false, dry_run: false)
ObserverPathnameExtension.reset_counts!
dirs = []
keg_directories = self.class.keg_link_directories.map { |d| path/d }
.select(&:exist?)
keg_directories.each do |dir|
dir.find do |src|
dst = HOMEBREW_PREFIX + src.relative_path_from(path)
dst.extend(ObserverPathnameExtension)
dirs << dst if dst.directory? && !dst.symlink?
# check whether the file to be unlinked is from the current keg first
next unless dst.symlink?
next if src != dst.resolved_path
if dry_run
puts dst
Find.prune if src.directory?
next
end
dst.uninstall_info if dst.to_s.match?(INFOFILE_RX)
dst.unlink
Find.prune if src.directory?
end
end
unless dry_run
remove_old_aliases
remove_linked_keg_record if linked?
(dirs - self.class.must_exist_subdirectories).reverse_each(&:rmdir_if_possible)
end
ObserverPathnameExtension.n
end
sig { params(_block: T.proc.void).void }
def lock(&_block)
FormulaLock.new(name).with_lock do
oldname_locks = oldname_opt_records.map do |record|
FormulaLock.new(record.basename.to_s)
end
oldname_locks.each(&:lock)
yield
ensure
oldname_locks&.each(&:unlock)
end
end
sig { params(shell: Symbol).returns(T::Boolean) }
def completion_installed?(shell)
dir = case shell
when :bash then path/"etc/bash_completion.d"
when :fish then path/"share/fish/vendor_completions.d"
when :zsh
dir = path/"share/zsh/site-functions"
dir if dir.directory? && dir.children.any? { |f| f.basename.to_s.start_with?("_") }
when :pwsh then path/"share/pwsh/completions"
end
!dir.nil? && dir.directory? && !dir.children.empty?
end
sig { params(shell: Symbol).returns(T::Boolean) }
def functions_installed?(shell)
case shell
when :fish
dir = path/"share/fish/vendor_functions.d"
dir.directory? && !dir.children.empty?
when :zsh
# Check for non completion functions (i.e. files not started with an underscore),
# since those can be checked separately
dir = path/"share/zsh/site-functions"
dir.directory? && dir.children.any? { |f| !f.basename.to_s.start_with?("_") }
else
false
end
end
sig { returns(T::Boolean) }
def plist_installed?
!Dir["#{path}/*.plist"].empty?
end
sig { returns(T::Array[Pathname]) }
def apps
app_prefix = optlinked? ? opt_record : path
Pathname.glob("#{app_prefix}/{,libexec/}*.app")
end
sig { returns(T::Boolean) }
def elisp_installed?
return false unless (path/"share/emacs/site-lisp"/name).exist?
(path/"share/emacs/site-lisp"/name).children.any? { |f| ELISP_EXTENSIONS.include? f.extname }
end
sig { returns(PkgVersion) }
def version
require "pkg_version"
PkgVersion.parse(path.basename.to_s)
end
sig { returns(Integer) }
def version_scheme
@version_scheme ||= T.let(tab.version_scheme, T.nilable(Integer))
end
# For ordering kegs by version with `.sort_by`, `.max_by`, etc.
# @see Formula.version_scheme
sig { returns([Integer, PkgVersion]) }
def scheme_and_version
[version_scheme, version]
end
sig { returns(Formula) }
def to_formula
Formulary.from_keg(self)
end
sig { returns(T::Array[Pathname]) }
def oldname_opt_records
return @oldname_opt_records unless @oldname_opt_records.empty?
@oldname_opt_records = if (opt_dir = HOMEBREW_PREFIX/"opt").directory?
opt_dir.subdirs.select do |dir|
dir.symlink? && dir != opt_record && path.parent == dir.resolved_path.parent
end
else
[]
end
end
sig { params(verbose: T::Boolean, dry_run: T::Boolean, overwrite: T::Boolean).returns(Integer) }
def link(verbose: false, dry_run: false, overwrite: false)
raise AlreadyLinkedError, self if linked_keg_record.directory?
ObserverPathnameExtension.reset_counts!
optlink(verbose:, dry_run:, overwrite:) unless dry_run
# yeah indeed, you have to force anything you need in the main tree into
# these dirs REMEMBER that *NOT* everything needs to be in the main tree
link_dir("etc", verbose:, dry_run:, overwrite:) { :mkpath }
link_dir("bin", verbose:, dry_run:, overwrite:) { :skip_dir }
link_dir("sbin", verbose:, dry_run:, overwrite:) { :skip_dir }
link_dir("include", verbose:, dry_run:, overwrite:) do |relative_path|
case relative_path.to_s
when /^postgresql@\d+/
:mkpath
else
:link
end
end
link_dir("share", verbose:, dry_run:, overwrite:) do |relative_path|
case relative_path.to_s
when INFOFILE_RX then :info
when "locale/locale.alias",
%r{^icons/.*/icon-theme\.cache$}
:skip_file
when LOCALEDIR_RX,
%r{^icons/}, # all icons subfolders should also mkpath
/^zsh/,
/^fish/,
%r{^lua/}, # Lua, Lua51, Lua53 all need the same handling.
%r{^guile/},
/^postgresql@\d+/,
/^pypy/,
*SHARE_PATHS
:mkpath
else
:link
end
end
link_dir("lib", verbose:, dry_run:, overwrite:) do |relative_path|
case relative_path.to_s
when "charset.alias"
:skip_file
when "pkgconfig", # pkg-config database gets explicitly created
"cmake", # cmake database gets explicitly created
"dtrace", # lib/language folders also get explicitly created
/^gdk-pixbuf/,
"ghc",
/^gio/,
/^lua/,
/^mecab/,
/^node/,
/^ocaml/,
/^perl5/,
"php",
/^postgresql@\d+/,
/^pypy/,
/^python[23]\.\d+/,
/^R/,
/^ruby/
:mkpath
else
# Everything else is symlinked to the Cellar
:link
end
end
link_dir("Frameworks", verbose:, dry_run:, overwrite:) do |relative_path|
# Frameworks contain symlinks pointing into a subdir, so we have to use
# the :link strategy. However, for Foo.framework and
# Foo.framework/Versions we have to use :mkpath so that multiple formulae
# can link their versions into it and `brew [un]link` works.
if relative_path.to_s.match?(%r{[^/]*\.framework(/Versions)?$})
:mkpath
else
:link
end
end
make_relative_symlink(linked_keg_record, path, verbose:, dry_run:, overwrite:) unless dry_run
rescue LinkError
unlink(verbose:)
raise
else
ObserverPathnameExtension.n
end
sig { void }
def prepare_debug_symbols; end
sig { void }
def consistent_reproducible_symlink_permissions!; end
sig { void }
def remove_oldname_opt_records
oldname_opt_records.reject! do |record|
return false if record.resolved_path != path
record.unlink
record.parent.rmdir_if_possible
true
end
end
sig { returns(Tab) }
def tab
Tab.for_keg(self)
end
sig { returns(T.nilable(T::Array[T.untyped])) }
def runtime_dependencies
Keg.cache[:runtime_dependencies] ||= {}
Keg.cache[:runtime_dependencies][path] ||= tab.runtime_dependencies
end
sig { returns(T::Array[String]) }
def aliases
tab.aliases || []
end
sig { params(verbose: T::Boolean, dry_run: T::Boolean, overwrite: T::Boolean).void }
def optlink(verbose: false, dry_run: false, overwrite: false)
opt_record.delete if opt_record.symlink? || opt_record.exist?
make_relative_symlink(opt_record, path, verbose:, dry_run:, overwrite:)
aliases.each do |a|
alias_opt_record = opt_record.parent/a
alias_opt_record.delete if alias_opt_record.symlink? || alias_opt_record.exist?
make_relative_symlink(alias_opt_record, path, verbose:, dry_run:, overwrite:)
end
oldname_opt_records.each do |record|
record.delete
make_relative_symlink(record, path, verbose:, dry_run:, overwrite:)
end
end
sig { void }
def delete_pyc_files!
path.find { |pn| pn.delete if PYC_EXTENSIONS.include?(pn.extname) }
path.find { |pn| FileUtils.rm_rf pn if pn.basename.to_s == "__pycache__" }
end
sig { void }
def normalize_pod2man_outputs!
# Only process uncompressed manpages, which end in a digit
manpages = Dir[path/"share/man/*/*.[1-9]{,p,pm}"]
generated_regex = /^\.\\"\s*Automatically generated by .*\n/
manpages.each do |f|
manpage = Pathname.new(f)
next unless manpage.file?
content = manpage.read
unless content.valid_encoding?
# Occasionally, a manpage might not be encoded as UTF-8. ISO-8859-1 is a
# common alternative that's worth trying in this case.
content = File.read(manpage, encoding: "ISO-8859-1")
# If the encoding is still invalid, we can't do anything about it.
next unless content.valid_encoding?
end
content = content.gsub(generated_regex, "")
content = content.lines.map do |line|
if line.start_with?(".TH")
# Split the line by spaces, but preserve quoted strings
parts = line.split(/\s(?=(?:[^"]|"[^"]*")*$)/)
next line if parts.length != 6
# pod2man embeds the perl version used into the 5th field of the footer
parts[4]&.gsub!(/^"perl v.*"$/, "\"\"")
# man extension remove in man files
parts[2]&.gsub!(/([1-9])(?:pm|p)?/, "\\1")
"#{parts.join(" ")}\n"
elsif line.start_with?(".IX")
# Split the line by spaces, but preserve quoted strings
parts = line.split(/\s(?=(?:[^"]|"[^"]*")*$)/)
next line if parts.length != 3
next line if parts[1] != "Title"
# man extension remove in man files
parts[2]&.gsub!(/([1-9])(?:pm|p)?/, "\\1")
"#{parts.join(" ")}\n"
else
line
end
end.join
manpage.atomic_write(content)
end
end
sig { returns(T::Array[String]) }
def keepme_refs
keepme = path/KEEPME_FILE
return [] if !keepme.exist? || !keepme.readable?
keepme.readlines.select { |ref| File.exist?(ref.strip) }
end
sig { returns(T::Array[Pathname]) }
def binary_executable_or_library_files
[]
end
sig { params(file: String).void }
def codesign_patched_binary(file); end
private
sig {
params(
dst: Pathname,
dry_run: T::Boolean,
verbose: T::Boolean,
overwrite: T::Boolean,
).returns(T.nilable(TrueClass))
}
def resolve_any_conflicts(dst, dry_run: false, verbose: false, overwrite: false)
return unless dst.symlink?
src = dst.resolved_path
# `src` itself may be a symlink, so check lstat to ensure we are dealing with
# a directory and not a symlink pointing to a directory (which needs to be
# treated as a file). In other words, we only want to resolve one symlink.
begin
stat = src.lstat
rescue Errno::ENOENT
# dst is a broken symlink, so remove it.
dst.unlink unless dry_run
return
end
return unless stat.directory?
begin
keg = Keg.for(src)
rescue NotAKegError
puts "Won't resolve conflicts for symlink #{dst} as it doesn't resolve into the Cellar." if verbose
return
end
dst.unlink unless dry_run
keg.link_dir(src, dry_run: false, verbose: false, overwrite: false) { :mkpath }
true
end
sig { params(dst: Pathname, src: Pathname, verbose: T::Boolean, dry_run: T::Boolean, overwrite: T::Boolean).void }
def make_relative_symlink(dst, src, verbose: false, dry_run: false, overwrite: false)
if dst.symlink? && src == dst.resolved_path
puts "Skipping; link already exists: #{dst}" if verbose
return
end
# cf. git-clean -n: list files to delete, don't really link or delete
if dry_run && overwrite
if dst.symlink?
puts "#{dst} -> #{dst.resolved_path}"
elsif dst.exist?
puts dst
end
return
end
# list all link targets
if dry_run
puts dst
return
end
dst.delete if overwrite && (dst.exist? || dst.symlink?)
dst.make_relative_symlink(src)
rescue Errno::EEXIST => e
raise ConflictError.new(self, src.relative_path_from(path), dst, e) if dst.exist?
if dst.symlink?
dst.unlink
retry
end
rescue Errno::EACCES => e
raise DirectoryNotWritableError.new(self, src.relative_path_from(path), dst, e)
rescue SystemCallError => e
raise LinkError.new(self, src.relative_path_from(path), dst, e)
end
sig { params(alias_symlink: Pathname, alias_match_path: Pathname).void }
def remove_alias_symlink(alias_symlink, alias_match_path)
if alias_symlink.symlink? && alias_symlink.exist?
alias_symlink.delete if alias_match_path.exist? && alias_symlink.realpath == alias_match_path.realpath
elsif alias_symlink.symlink? || alias_symlink.exist?
alias_symlink.delete
end
end
protected
# symlinks the contents of path+relative_dir recursively into #{HOMEBREW_PREFIX}/relative_dir
sig {
params(
relative_dir: T.any(String, Pathname),
verbose: T::Boolean,
dry_run: T::Boolean,
overwrite: T::Boolean,
_block: T.proc.params(relative_path: Pathname).returns(T.nilable(Symbol)),
).void
}
def link_dir(relative_dir, verbose: false, dry_run: false, overwrite: false, &_block)
root = path/relative_dir
return unless root.exist?
root.find do |src|
next if src == root
dst = HOMEBREW_PREFIX + src.relative_path_from(path)
dst.extend ObserverPathnameExtension
if src.symlink? || src.file?
Find.prune if File.basename(src) == ".DS_Store"
Find.prune if src.resolved_path == dst
# Don't link pyc or pyo files because Python overwrites these
# cached object files and next time brew wants to link, the
# file is in the way.
Find.prune if PYC_EXTENSIONS.include?(src.extname) && src.to_s.include?("/site-packages/")
case yield src.relative_path_from(root)
when :skip_file, nil
Find.prune
when :info
next if File.basename(src) == "dir" # skip historical local 'dir' files
make_relative_symlink(dst, src, verbose:, dry_run:, overwrite:)
dst.install_info
else
make_relative_symlink dst, src, verbose:, dry_run:, overwrite:
end
elsif src.directory?
# if the dst dir already exists, then great! walk the rest of the tree tho
next if dst.directory? && !dst.symlink?
# no need to put .app bundles in the path, the user can just use
# spotlight, or the open command and actual mac apps use an equivalent
Find.prune if src.extname == ".app"
case yield src.relative_path_from(root)
when :skip_dir
Find.prune
when :mkpath
dst.mkpath unless resolve_any_conflicts(dst, verbose:, dry_run:, overwrite:)
else
unless resolve_any_conflicts(dst, verbose:, dry_run:, overwrite:)
make_relative_symlink(dst, src, verbose:, dry_run:, overwrite:)
Find.prune
end
end
end
end
end
end
require "extend/os/keg"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/lazy_object.rb | Library/Homebrew/lazy_object.rb | # typed: strict
# frozen_string_literal: true
require "delegate"
# An object which lazily evaluates its inner block only once a method is called on it.
class LazyObject < Delegator
sig { params(callable: T.nilable(Proc)).void }
def initialize(&callable)
@__callable__ = T.let(nil, T.nilable(Proc))
@getobj_set = T.let(false, T::Boolean)
@__getobj__ = T.let(nil, T.untyped)
super(callable)
end
sig { params(_blk: T.untyped).returns(T.untyped) }
def __getobj__(&_blk)
return @__getobj__ if @getobj_set
@__getobj__ = T.must(@__callable__).call
@getobj_set = true
@__getobj__
end
sig { params(callable: T.nilable(Proc)).void }
def __setobj__(callable)
@__callable__ = callable
@getobj_set = false
@__getobj__ = nil
end
# Forward to the inner object to make lazy objects type-checkable.
#
# @!visibility private
sig { params(klass: T.any(T::Module[T.anything], T::Class[T.anything])).returns(T::Boolean) }
def is_a?(klass)
# see https://sorbet.org/docs/faq#how-can-i-fix-type-errors-that-arise-from-super
T.bind(self, T.untyped)
__getobj__.is_a?(klass) || super
end
sig { returns(T::Class[T.anything]) }
def class = __getobj__.class
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/cask.rb | Library/Homebrew/cask.rb | # typed: strict
# frozen_string_literal: true
require "cask/artifact"
require "cask/audit"
require "cask/auditor"
require "cask/cache"
require "cask/cask_loader"
require "cask/cask"
require "cask/caskroom"
require "cask/config"
require "cask/exceptions"
require "cask/denylist"
require "cask/download"
require "cask/dsl"
require "cask/installer"
require "cask/macos"
require "cask/metadata"
require "cask/migrator"
require "cask/pkg"
require "cask/quarantine"
require "cask/staged"
require "cask/tab"
require "cask/url"
require "cask/utils"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/service.rb | Library/Homebrew/service.rb | # typed: strict
# frozen_string_literal: true
require "ipaddr"
require "on_system"
require "utils/service"
module Homebrew
# The {Service} class implements the DSL methods used in a formula's
# `service` block and stores related instance variables. Most of these methods
# also return the related instance variable when no argument is provided.
class Service
extend Forwardable
include OnSystem::MacOSAndLinux
RUN_TYPE_IMMEDIATE = :immediate
RUN_TYPE_INTERVAL = :interval
RUN_TYPE_CRON = :cron
PROCESS_TYPE_BACKGROUND = :background
PROCESS_TYPE_STANDARD = :standard
PROCESS_TYPE_INTERACTIVE = :interactive
PROCESS_TYPE_ADAPTIVE = :adaptive
KEEP_ALIVE_KEYS = [:always, :successful_exit, :crashed, :path].freeze
NICE_RANGE = T.let(-20..19, T::Range[Integer])
SOCKET_STRING_REGEX = %r{^(?<type>[a-z]+)://(?<host>.+):(?<port>[0-9]+)$}i
RunParam = T.type_alias { T.nilable(T.any(T::Array[T.any(String, Pathname)], String, Pathname)) }
Sockets = T.type_alias { T::Hash[Symbol, { host: String, port: String, type: String }] }
sig { returns(String) }
attr_reader :plist_name, :service_name
sig { params(formula: Formula, block: T.nilable(T.proc.void)).void }
def initialize(formula, &block)
@cron = T.let({}, T::Hash[Symbol, T.any(Integer, String)])
@environment_variables = T.let({}, T::Hash[Symbol, String])
@error_log_path = T.let(nil, T.nilable(String))
@formula = formula
@input_path = T.let(nil, T.nilable(String))
@interval = T.let(nil, T.nilable(Integer))
@keep_alive = T.let({}, T::Hash[Symbol, T.untyped])
@launch_only_once = T.let(false, T::Boolean)
@log_path = T.let(nil, T.nilable(String))
@macos_legacy_timers = T.let(false, T::Boolean)
@nice = T.let(nil, T.nilable(Integer))
@plist_name = T.let(default_plist_name, String)
@process_type = T.let(nil, T.nilable(Symbol))
@require_root = T.let(false, T::Boolean)
@restart_delay = T.let(nil, T.nilable(Integer))
@throttle_interval = T.let(nil, T.nilable(Integer))
@root_dir = T.let(nil, T.nilable(String))
@run = T.let([], T::Array[String])
@run_at_load = T.let(true, T::Boolean)
@run_params = T.let(nil, T.any(RunParam, T::Hash[Symbol, RunParam]))
@run_type = T.let(RUN_TYPE_IMMEDIATE, Symbol)
@service_name = T.let(default_service_name, String)
@sockets = T.let({}, Sockets)
@working_dir = T.let(nil, T.nilable(String))
instance_eval(&block) if block
raise TypeError, "Service#nice: require_root true is required for negative nice values" if nice_requires_root?
end
sig { returns(T::Boolean) }
def nice_requires_root?
@nice&.negative? == true && !requires_root?
end
sig { returns(Formula) }
def f
@formula
end
sig { returns(String) }
def default_plist_name
"homebrew.mxcl.#{@formula.name}"
end
sig { returns(String) }
def default_service_name
"homebrew.#{@formula.name}"
end
sig { params(macos: T.nilable(String), linux: T.nilable(String)).void }
def name(macos: nil, linux: nil)
raise TypeError, "Service#name expects at least one String" if [macos, linux].none?(String)
@plist_name = macos if macos
@service_name = linux if linux
end
sig {
params(
command: T.nilable(RunParam),
macos: T.nilable(RunParam),
linux: T.nilable(RunParam),
).returns(T.nilable(T::Array[T.any(String, Pathname)]))
}
def run(command = nil, macos: nil, linux: nil)
# Save parameters for serialization
if command
@run_params = command
elsif macos || linux
@run_params = { macos:, linux: }.compact
end
command ||= on_system_conditional(macos:, linux:)
case command
when nil
@run
when String, Pathname
@run = [command.to_s]
when Array
@run = command.map(&:to_s)
end
end
sig { params(path: T.any(String, Pathname)).returns(T.nilable(String)) }
def working_dir(path = T.unsafe(nil))
if path
@working_dir = path.to_s
else
@working_dir
end
end
sig { params(path: T.any(String, Pathname)).returns(T.nilable(String)) }
def root_dir(path = T.unsafe(nil))
if path
@root_dir = path.to_s
else
@root_dir
end
end
sig { params(path: T.any(String, Pathname)).returns(T.nilable(String)) }
def input_path(path = T.unsafe(nil))
if path
@input_path = path.to_s
else
@input_path
end
end
sig { params(path: T.any(String, Pathname)).returns(T.nilable(String)) }
def log_path(path = T.unsafe(nil))
if path
@log_path = path.to_s
else
@log_path
end
end
sig { params(path: T.any(String, Pathname)).returns(T.nilable(String)) }
def error_log_path(path = T.unsafe(nil))
if path
@error_log_path = path.to_s
else
@error_log_path
end
end
sig {
params(value: T.any(T::Boolean, T::Hash[Symbol, T.untyped]))
.returns(T.nilable(T::Hash[Symbol, T.untyped]))
}
def keep_alive(value = T.unsafe(nil))
case value
when nil
@keep_alive
when true, false
@keep_alive = { always: value }
when Hash
unless (value.keys - KEEP_ALIVE_KEYS).empty?
raise TypeError, "Service#keep_alive only allows: #{KEEP_ALIVE_KEYS}"
end
@keep_alive = value
end
end
sig { params(value: T::Boolean).returns(T::Boolean) }
def require_root(value = T.unsafe(nil))
if value.nil?
@require_root
else
@require_root = value
end
end
# Returns a `Boolean` describing if a service requires root access.
sig { returns(T::Boolean) }
def requires_root?
@require_root.present? && @require_root == true
end
sig { params(value: T::Boolean).returns(T.nilable(T::Boolean)) }
def run_at_load(value = T.unsafe(nil))
if value.nil?
@run_at_load
else
@run_at_load = value
end
end
sig {
params(value: T.any(String, T::Hash[Symbol, String]))
.returns(T::Hash[Symbol, T::Hash[Symbol, String]])
}
def sockets(value = T.unsafe(nil))
return @sockets if value.nil?
value_hash = case value
when String
{ listeners: value }
when Hash
value
end
@sockets = T.must(value_hash).transform_values do |socket_string|
match = socket_string.match(SOCKET_STRING_REGEX)
raise TypeError, "Service#sockets a formatted socket definition as <type>://<host>:<port>" unless match
begin
IPAddr.new(match[:host])
rescue IPAddr::InvalidAddressError
raise TypeError, "Service#sockets expects a valid ipv4 or ipv6 host address"
end
{ host: match[:host], port: match[:port], type: match[:type] }
end
end
# Returns a `Boolean` describing if a service is set to be kept alive.
sig { returns(T::Boolean) }
def keep_alive?
!@keep_alive.empty? && @keep_alive[:always] != false
end
sig { params(value: T::Boolean).returns(T::Boolean) }
def launch_only_once(value = T.unsafe(nil))
if value.nil?
@launch_only_once
else
@launch_only_once = value
end
end
sig { params(value: Integer).returns(T.nilable(Integer)) }
def restart_delay(value = T.unsafe(nil))
if value
@restart_delay = value
else
@restart_delay
end
end
sig { params(value: Integer).returns(T.nilable(Integer)) }
def throttle_interval(value = T.unsafe(nil))
return @throttle_interval if value.nil?
@throttle_interval = value
end
sig { params(value: Symbol).returns(T.nilable(Symbol)) }
def process_type(value = T.unsafe(nil))
case value
when nil
@process_type
when :background, :standard, :interactive, :adaptive
@process_type = value
when Symbol
raise TypeError, "Service#process_type allows: " \
"'#{PROCESS_TYPE_BACKGROUND}'/'#{PROCESS_TYPE_STANDARD}'/" \
"'#{PROCESS_TYPE_INTERACTIVE}'/'#{PROCESS_TYPE_ADAPTIVE}'"
end
end
sig { params(value: Symbol).returns(T.nilable(Symbol)) }
def run_type(value = T.unsafe(nil))
case value
when nil
@run_type
when :immediate, :interval, :cron
@run_type = value
when Symbol
raise TypeError, "Service#run_type allows: '#{RUN_TYPE_IMMEDIATE}'/'#{RUN_TYPE_INTERVAL}'/'#{RUN_TYPE_CRON}'"
end
end
sig { params(value: Integer).returns(T.nilable(Integer)) }
def interval(value = T.unsafe(nil))
if value
@interval = value
else
@interval
end
end
sig { params(value: String).returns(T::Hash[Symbol, T.any(Integer, String)]) }
def cron(value = T.unsafe(nil))
if value
@cron = parse_cron(value)
else
@cron
end
end
sig { returns(T::Hash[Symbol, T.any(Integer, String)]) }
def default_cron_values
{
Month: "*",
Day: "*",
Weekday: "*",
Hour: "*",
Minute: "*",
}
end
sig { params(cron_statement: String).returns(T::Hash[Symbol, T.any(Integer, String)]) }
def parse_cron(cron_statement)
parsed = default_cron_values
case cron_statement
when "@hourly"
parsed[:Minute] = 0
when "@daily"
parsed[:Minute] = 0
parsed[:Hour] = 0
when "@weekly"
parsed[:Minute] = 0
parsed[:Hour] = 0
parsed[:Weekday] = 0
when "@monthly"
parsed[:Minute] = 0
parsed[:Hour] = 0
parsed[:Day] = 1
when "@yearly", "@annually"
parsed[:Minute] = 0
parsed[:Hour] = 0
parsed[:Day] = 1
parsed[:Month] = 1
else
cron_parts = cron_statement.split
raise TypeError, "Service#parse_cron expects a valid cron syntax" if cron_parts.length != 5
[:Minute, :Hour, :Day, :Month, :Weekday].each_with_index do |selector, index|
parsed[selector] = Integer(cron_parts.fetch(index)) if cron_parts.fetch(index) != "*"
end
end
parsed
end
sig { params(variables: T::Hash[Symbol, T.any(Pathname, String)]).returns(T.nilable(T::Hash[Symbol, String])) }
def environment_variables(variables = {})
@environment_variables = variables.transform_values(&:to_s)
end
sig { params(value: T::Boolean).returns(T::Boolean) }
def macos_legacy_timers(value = T.unsafe(nil))
if value.nil?
@macos_legacy_timers
else
@macos_legacy_timers = value
end
end
sig { params(value: Integer).returns(T.nilable(Integer)) }
def nice(value = T.unsafe(nil))
return @nice if value.nil?
raise TypeError, "Service#nice value should be in #{NICE_RANGE}" unless NICE_RANGE.cover?(value)
@nice = value
end
delegate [:bin, :etc, :libexec, :opt_bin, :opt_libexec, :opt_pkgshare, :opt_prefix, :opt_sbin, :var] => :@formula
sig { returns(String) }
def std_service_path_env
"#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin:/usr/bin:/bin:/usr/sbin:/sbin"
end
sig { returns(T::Array[String]) }
def command
@run.map(&:to_s).map { |arg| arg.start_with?("~") ? File.expand_path(arg) : arg }
end
sig { returns(T::Boolean) }
def command?
!@run.empty?
end
# Returns the `String` command to run manually instead of the service.
sig { returns(String) }
def manual_command
vars = @environment_variables.except(:PATH)
.map { |k, v| "#{k}=\"#{v}\"" }
vars.concat(command.map { |arg| Utils::Shell.sh_quote(arg) })
vars.join(" ")
end
# Returns a `Boolean` describing if a service is timed.
sig { returns(T::Boolean) }
def timed?
@run_type == RUN_TYPE_CRON || @run_type == RUN_TYPE_INTERVAL
end
# Returns a `String` plist.
sig { returns(String) }
def to_plist
# command needs to be first because it initializes all other values
base = {
Label: plist_name,
ProgramArguments: command,
RunAtLoad: @run_at_load == true,
}
base[:LaunchOnlyOnce] = @launch_only_once if @launch_only_once == true
base[:LegacyTimers] = @macos_legacy_timers if @macos_legacy_timers == true
base[:TimeOut] = @restart_delay if @restart_delay.present?
base[:ThrottleInterval] = @throttle_interval if @throttle_interval.present?
base[:ProcessType] = @process_type.to_s.capitalize if @process_type.present?
base[:Nice] = @nice if @nice.present?
base[:StartInterval] = @interval if @interval.present? && @run_type == RUN_TYPE_INTERVAL
base[:WorkingDirectory] = File.expand_path(@working_dir) if @working_dir.present?
base[:RootDirectory] = File.expand_path(@root_dir) if @root_dir.present?
base[:StandardInPath] = File.expand_path(@input_path) if @input_path.present?
base[:StandardOutPath] = File.expand_path(@log_path) if @log_path.present?
base[:StandardErrorPath] = File.expand_path(@error_log_path) if @error_log_path.present?
base[:EnvironmentVariables] = @environment_variables unless @environment_variables.empty?
if keep_alive?
if (always = @keep_alive[:always].presence)
base[:KeepAlive] = always
elsif @keep_alive.key?(:successful_exit)
base[:KeepAlive] = { SuccessfulExit: @keep_alive[:successful_exit] }
elsif @keep_alive.key?(:crashed)
base[:KeepAlive] = { Crashed: @keep_alive[:crashed] }
elsif @keep_alive.key?(:path) && @keep_alive[:path].present?
base[:KeepAlive] = { PathState: @keep_alive[:path].to_s }
end
end
unless @sockets.empty?
base[:Sockets] = {}
@sockets.each do |name, info|
base[:Sockets][name] = {
SockNodeName: info[:host],
SockServiceName: info[:port],
SockProtocol: info[:type].upcase,
}
end
end
if !@cron.empty? && @run_type == RUN_TYPE_CRON
base[:StartCalendarInterval] = @cron.reject { |_, value| value == "*" }
end
# Adding all session types has as the primary effect that if you initialise it through e.g. a Background session
# and you later "physically" sign in to the owning account (Aqua session), things shouldn't flip out.
# Also, we're not checking @process_type here because that is used to indicate process priority and not
# necessarily if it should run in a specific session type. Like database services could run with ProcessType
# Interactive so they have no resource limitations enforced upon them, but they aren't really interactive in the
# general sense.
base[:LimitLoadToSessionType] = %w[Aqua Background LoginWindow StandardIO System]
base.to_plist
end
# Returns a `String` systemd unit.
sig { returns(String) }
def to_systemd_unit
# command needs to be first because it initializes all other values
cmd = command.map { |arg| Utils::Service.systemd_quote(arg) }
.join(" ")
options = []
options << "Type=#{(@launch_only_once == true) ? "oneshot" : "simple"}"
options << "ExecStart=#{cmd}"
if @keep_alive.present?
if @keep_alive[:always].present? || @keep_alive[:crashed].present?
# Use on-failure instead of always to allow manual stops via systemctl
options << "Restart=on-failure"
elsif @keep_alive[:successful_exit].present?
options << "Restart=on-success"
end
end
options << "RestartSec=#{restart_delay}" if @restart_delay.present?
options << "Nice=#{@nice}" if @nice.present?
options << "WorkingDirectory=#{File.expand_path(@working_dir)}" if @working_dir.present?
options << "RootDirectory=#{File.expand_path(@root_dir)}" if @root_dir.present?
options << "StandardInput=file:#{File.expand_path(@input_path)}" if @input_path.present?
options << "StandardOutput=append:#{File.expand_path(@log_path)}" if @log_path.present?
options << "StandardError=append:#{File.expand_path(@error_log_path)}" if @error_log_path.present?
options += @environment_variables.map { |k, v| "Environment=\"#{k}=#{v}\"" } if @environment_variables.present?
<<~SYSTEMD
[Unit]
Description=Homebrew generated unit for #{@formula.name}
[Install]
WantedBy=default.target
[Service]
#{options.join("\n")}
SYSTEMD
end
# Returns a `String` systemd unit timer.
sig { returns(String) }
def to_systemd_timer
options = []
options << "Persistent=true" if @run_type == RUN_TYPE_CRON
options << "OnUnitActiveSec=#{@interval}" if @run_type == RUN_TYPE_INTERVAL
if @run_type == RUN_TYPE_CRON
minutes = (@cron[:Minute] == "*") ? "*" : format("%02d", @cron[:Minute])
hours = (@cron[:Hour] == "*") ? "*" : format("%02d", @cron[:Hour])
options << "OnCalendar=#{@cron[:Weekday]}-*-#{@cron[:Month]}-#{@cron[:Day]} #{hours}:#{minutes}:00"
end
<<~SYSTEMD
[Unit]
Description=Homebrew generated timer for #{@formula.name}
[Install]
WantedBy=timers.target
[Timer]
Unit=#{service_name}
#{options.join("\n")}
SYSTEMD
end
# Prepare the service hash for inclusion in the formula API JSON.
sig { returns(T::Hash[Symbol, T.untyped]) }
def to_hash
name_params = {
macos: (plist_name if plist_name != default_plist_name),
linux: (service_name if service_name != default_service_name),
}.compact
return { name: name_params }.compact_blank if @run_params.blank?
cron_string = if @cron.present?
[:Minute, :Hour, :Day, :Month, :Weekday]
.filter_map { |key| @cron[key].to_s.presence }
.join(" ")
end
sockets_var = unless @sockets.empty?
@sockets.transform_values { |info| "#{info[:type]}://#{info[:host]}:#{info[:port]}" }
.then do |sockets_hash|
# TODO: Remove this code when all users are running on versions of Homebrew
# that can process sockets hashes (this commit or later).
if sockets_hash.size == 1 && sockets_hash.key?(:listeners)
# When original #sockets argument was a string: `sockets "tcp://127.0.0.1:80"`
sockets_hash.fetch(:listeners)
else
# When original #sockets argument was a hash: `sockets http: "tcp://0.0.0.0:80"`
sockets_hash
end
end
end
{
name: name_params.presence,
run: @run_params,
run_type: @run_type,
interval: @interval,
cron: cron_string.presence,
keep_alive: @keep_alive,
launch_only_once: @launch_only_once,
require_root: @require_root,
environment_variables: @environment_variables.presence,
working_dir: @working_dir,
root_dir: @root_dir,
input_path: @input_path,
log_path: @log_path,
error_log_path: @error_log_path,
restart_delay: @restart_delay,
throttle_interval: @throttle_interval,
nice: @nice,
process_type: @process_type,
macos_legacy_timers: @macos_legacy_timers,
sockets: sockets_var,
}.compact_blank
end
# Turn the service API hash values back into what is expected by the formula DSL.
sig { params(api_hash: T::Hash[String, T.untyped]).returns(T::Hash[Symbol, T.untyped]) }
def self.from_hash(api_hash)
hash = {}
hash[:name] = api_hash["name"].transform_keys(&:to_sym) if api_hash.key?("name")
# The service hash might not have a "run" command if it only documents
# an existing service file with the "name" command.
return hash unless api_hash.key?("run")
hash[:run] =
case api_hash["run"]
when String
replace_placeholders(api_hash["run"])
when Array
api_hash["run"].map { replace_placeholders(it) }
when Hash
api_hash["run"].to_h do |key, elem|
run_cmd = if elem.is_a?(Array)
elem.map { replace_placeholders(it) }
else
replace_placeholders(elem)
end
[key.to_sym, run_cmd]
end
else
raise ArgumentError, "Unexpected run command: #{api_hash["run"]}"
end
if api_hash.key?("environment_variables")
hash[:environment_variables] = api_hash["environment_variables"].to_h do |key, value|
[key.to_sym, replace_placeholders(value)]
end
end
%w[run_type process_type].each do |key|
next unless (value = api_hash[key])
hash[key.to_sym] = value.to_sym
end
%w[working_dir root_dir input_path log_path error_log_path].each do |key|
next unless (value = api_hash[key])
hash[key.to_sym] = replace_placeholders(value)
end
%w[interval cron launch_only_once require_root restart_delay throttle_interval nice
macos_legacy_timers].each do |key|
next if (value = api_hash[key]).nil?
hash[key.to_sym] = value
end
%w[sockets keep_alive].each do |key|
next unless (value = api_hash[key])
hash[key.to_sym] = if value.is_a?(Hash)
value.transform_keys(&:to_sym)
else
value
end
end
hash
end
# Replace API path placeholders with local paths.
sig { params(string: String).returns(String) }
def self.replace_placeholders(string)
string.gsub(HOMEBREW_PREFIX_PLACEHOLDER, HOMEBREW_PREFIX)
.gsub(HOMEBREW_CELLAR_PLACEHOLDER, HOMEBREW_CELLAR)
.gsub(HOMEBREW_HOME_PLACEHOLDER, Dir.home)
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/build_options.rb | Library/Homebrew/build_options.rb | # typed: strict
# frozen_string_literal: true
# Options for a formula build.
class BuildOptions
sig { params(args: Options, options: Options).void }
def initialize(args, options)
@args = args
@options = options
end
# True if a {Formula} is being built with a specific option.
#
# ### Examples
#
# ```ruby
# args << "--i-want-spam" if build.with? "spam"
# ```
#
# ```ruby
# args << "--qt-gui" if build.with? "qt" # "--with-qt" ==> build.with? "qt"
# ```
#
# If a formula presents a user with a choice, but the choice must be fulfilled:
#
# ```ruby
# if build.with? "example2"
# args << "--with-example2"
# else
# args << "--with-example1"
# end
# ```
sig { params(val: T.any(String, Requirement, Dependency)).returns(T::Boolean) }
def with?(val)
option_names = if val.is_a?(String)
[val]
else
val.option_names
end
option_names.any? do |name|
if option_defined? "with-#{name}"
include? "with-#{name}"
elsif option_defined? "without-#{name}"
!include? "without-#{name}"
else
false
end
end
end
# True if a {Formula} is being built without a specific option.
#
# ### Example
#
# ```ruby
# args << "--no-spam-plz" if build.without? "spam"
# ```
sig { params(val: T.any(String, Requirement, Dependency)).returns(T::Boolean) }
def without?(val)
!with?(val)
end
# True if a {Formula} is being built as a bottle (i.e. binary package).
sig { returns(T::Boolean) }
def bottle?
include? "build-bottle"
end
# True if a {Formula} is being built with {Formula.head} instead of {Formula.stable}.
#
# ### Examples
#
# ```ruby
# args << "--some-new-stuff" if build.head?
# ```
#
# If there are multiple conditional arguments use a block instead of lines.
#
# ```ruby
# if build.head?
# args << "--i-want-pizza"
# args << "--and-a-cold-beer" if build.with? "cold-beer"
# end
# ```
sig { returns(T::Boolean) }
def head?
include? "HEAD"
end
# True if a {Formula} is being built with {Formula.stable} instead of {Formula.head}.
# This is the default.
#
# ### Example
#
# ```ruby
# args << "--some-feature" if build.stable?
# ```
sig { returns(T::Boolean) }
def stable?
!head?
end
# True if the build has any arguments or options specified.
sig { returns(T::Boolean) }
def any_args_or_options?
!@args.empty? || !@options.empty?
end
sig { returns(Options) }
def used_options
@options & @args
end
sig { returns(Options) }
def unused_options
@options - @args
end
private
sig { params(name: String).returns(T::Boolean) }
def include?(name)
@args.include?("--#{name}")
end
sig { params(name: String).returns(T::Boolean) }
def option_defined?(name)
@options.include? name
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/ignorable.rb | Library/Homebrew/ignorable.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "warnings"
Warnings.ignore(/warning: callcc is obsolete; use Fiber instead/) do
require "continuation"
end
# Provides the ability to optionally ignore errors raised and continue execution.
module Ignorable
# Marks exceptions which can be ignored and provides
# the ability to jump back to where it was raised.
module ExceptionMixin
attr_accessor :continuation
def ignore
continuation.call
end
end
def self.hook_raise
# TODO: migrate away from this inline class here, they don't play nicely with
# Sorbet, when we migrate to `typed: strict`
# rubocop:todo Sorbet/BlockMethodDefinition
Object.class_eval do
alias_method :original_raise, :raise
def raise(*)
callcc do |continuation|
super
# Handle all possible exceptions.
rescue Exception => e # rubocop:disable Lint/RescueException
unless e.is_a?(ScriptError)
e.extend(ExceptionMixin)
T.cast(e, ExceptionMixin).continuation = continuation
end
super(e)
end
end
alias_method :fail, :raise
end
# rubocop:enable Sorbet/BlockMethodDefinition
return unless block_given?
yield
unhook_raise
end
def self.unhook_raise
Object.class_eval do
alias_method :raise, :original_raise
alias_method :fail, :original_raise
undef :original_raise
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/context.rb | Library/Homebrew/context.rb | # typed: strict
# frozen_string_literal: true
require "monitor"
# Module for querying the current execution context.
module Context
extend MonitorMixin
# Struct describing the current execution context.
class ContextStruct
sig { params(debug: T.nilable(T::Boolean), quiet: T.nilable(T::Boolean), verbose: T.nilable(T::Boolean)).void }
def initialize(debug: nil, quiet: nil, verbose: nil)
@debug = T.let(debug, T.nilable(T::Boolean))
@quiet = T.let(quiet, T.nilable(T::Boolean))
@verbose = T.let(verbose, T.nilable(T::Boolean))
end
sig { returns(T::Boolean) }
def debug?
@debug == true
end
sig { returns(T::Boolean) }
def quiet?
@quiet == true
end
sig { returns(T::Boolean) }
def verbose?
@verbose == true
end
end
@current = T.let(nil, T.nilable(ContextStruct))
sig { params(context: ContextStruct).void }
def self.current=(context)
synchronize do
@current = context
end
end
sig { returns(ContextStruct) }
def self.current
current_context = T.cast(Thread.current[:context], T.nilable(ContextStruct))
return current_context if current_context
synchronize do
current = T.let(@current, T.nilable(ContextStruct))
current ||= ContextStruct.new
@current = current
current
end
end
sig { returns(T::Boolean) }
def debug?
Context.current.debug?
end
sig { returns(T::Boolean) }
def quiet?
Context.current.quiet?
end
sig { returns(T::Boolean) }
def verbose?
Context.current.verbose?
end
sig {
params(debug: T.nilable(T::Boolean), quiet: T.nilable(T::Boolean), verbose: T.nilable(T::Boolean),
_block: T.proc.void).returns(T.untyped)
}
def with_context(debug: debug?, quiet: quiet?, verbose: verbose?, &_block)
old_context = Context.current
Thread.current[:context] = ContextStruct.new(debug:, quiet:, verbose:)
begin
yield
ensure
Thread.current[:context] = old_context
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/debrew.rb | Library/Homebrew/debrew.rb | # typed: strict
# frozen_string_literal: true
require "ignorable"
# Helper module for debugging formulae.
module Debrew
# Module for allowing to debug formulae.
module Formula
sig { void }
def install
Debrew.debrew { super }
end
sig { void }
def patch
Debrew.debrew { super }
end
sig {
# TODO: replace `returns(BasicObject)` with `void` after dropping `return false` handling in test
returns(BasicObject)
}
def test
Debrew.debrew { super }
end
end
# Module for displaying a debugging menu.
class Menu
class Entry < T::Struct
const :name, String
const :action, T.proc.void
end
sig { returns(T.nilable(String)) }
attr_accessor :prompt
sig { returns(T::Array[Entry]) }
attr_accessor :entries
sig { void }
def initialize
@entries = T.let([], T::Array[Entry])
end
sig { params(name: Symbol, action: T.proc.void).void }
def choice(name, &action)
entries << Entry.new(name: name.to_s, action:)
end
sig { params(_block: T.proc.params(menu: Menu).void).void }
def self.choose(&_block)
menu = new
yield menu
choice = T.let(nil, T.nilable(Entry))
while choice.nil?
menu.entries.each_with_index { |e, i| puts "#{i + 1}. #{e.name}" }
print menu.prompt unless menu.prompt.nil?
input = $stdin.gets || exit
input.chomp!
i = input.to_i
if i.positive?
choice = menu.entries[i - 1]
else
possible = menu.entries.select { |e| e.name.start_with?(input) }
case possible.size
when 0 then puts "No such option"
when 1 then choice = possible.first
else puts "Multiple options match: #{possible.map(&:name).join(" ")}"
end
end
end
choice.action.call
end
end
@mutex = T.let(nil, T.nilable(Mutex))
@debugged_exceptions = T.let(Set.new, T::Set[Exception])
class << self
sig { returns(T::Set[Exception]) }
attr_reader :debugged_exceptions
sig { returns(T::Boolean) }
def active? = !@mutex.nil?
end
sig {
type_parameters(:U)
.params(_block: T.proc.returns(T.type_parameter(:U)))
.returns(T.type_parameter(:U))
}
def self.debrew(&_block)
@mutex = Mutex.new
Ignorable.hook_raise
begin
yield
rescue SystemExit
raise
rescue Ignorable::ExceptionMixin => e
e.ignore if debug(e) == :ignore # execution jumps back to where the exception was thrown
ensure
Ignorable.unhook_raise
@mutex = nil
end
end
sig { params(exception: Exception).returns(Symbol) }
def self.debug(exception)
raise(exception) if !active? || !debugged_exceptions.add?(exception) || !@mutex&.try_lock
begin
puts exception.backtrace&.first
puts Formatter.error(exception, label: exception.class.name)
loop do
Menu.choose do |menu|
menu.prompt = "Choose an action: "
menu.choice(:raise) { raise(exception) }
menu.choice(:ignore) { return :ignore } if exception.is_a?(Ignorable::ExceptionMixin)
menu.choice(:backtrace) { puts exception.backtrace }
if exception.is_a?(Ignorable::ExceptionMixin)
menu.choice(:irb) do
puts "When you exit this IRB session, execution will continue."
set_trace_func proc { |event, _, _, id, binding, klass|
if klass == Object && id == :raise && event == "return"
set_trace_func(nil)
@mutex.synchronize do
require "debrew/irb"
IRB.start_within(binding)
end
end
}
return :ignore
end
end
menu.choice(:shell) do
puts "When you exit this shell, you will return to the menu."
interactive_shell
end
end
end
ensure
@mutex.unlock
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_version.rb | Library/Homebrew/bundle_version.rb | # typed: strict
# frozen_string_literal: true
require "system_command"
module Homebrew
# Representation of a macOS bundle version, commonly found in `Info.plist` files.
class BundleVersion
include Comparable
extend SystemCommand::Mixin
sig { params(info_plist_path: Pathname).returns(T.nilable(T.attached_class)) }
def self.from_info_plist(info_plist_path)
plist = system_command!("plutil", args: ["-convert", "xml1", "-o", "-", info_plist_path]).plist
from_info_plist_content(plist)
end
sig { params(plist: T::Hash[String, T.untyped]).returns(T.nilable(T.attached_class)) }
def self.from_info_plist_content(plist)
short_version = plist["CFBundleShortVersionString"].presence
version = plist["CFBundleVersion"].presence
new(short_version, version) if short_version || version
end
sig { params(package_info_path: Pathname).returns(T.nilable(T.attached_class)) }
def self.from_package_info(package_info_path)
require "rexml/document"
xml = REXML::Document.new(package_info_path.read)
bundle_version_bundle = xml.get_elements("//pkg-info//bundle-version//bundle").first
bundle_id = bundle_version_bundle["id"] if bundle_version_bundle
return if bundle_id.blank?
bundle = xml.get_elements("//pkg-info//bundle").find { |b| b["id"] == bundle_id }
return unless bundle
short_version = bundle["CFBundleShortVersionString"]
version = bundle["CFBundleVersion"]
new(short_version, version) if short_version || version
end
sig { returns(T.nilable(String)) }
attr_reader :short_version, :version
sig { params(short_version: T.nilable(String), version: T.nilable(String)).void }
def initialize(short_version, version)
# Remove version from short version, if present.
short_version = short_version&.sub(/\s*\(#{Regexp.escape(version)}\)\Z/, "") if version
@short_version = T.let(short_version.presence, T.nilable(String))
@version = T.let(version.presence, T.nilable(String))
return if @short_version || @version
raise ArgumentError, "`short_version` and `version` cannot both be `nil` or empty"
end
sig { params(other: BundleVersion).returns(T.nilable(Integer)) }
def <=>(other)
return super unless instance_of?(other.class)
make_version = ->(v) { v ? Version.new(v) : Version::NULL }
version = self.version.then(&make_version)
other_version = other.version.then(&make_version)
difference = version <=> other_version
# If `version` is equal or cannot be compared, compare `short_version` instead.
if difference.nil? || difference.zero?
short_version = self.short_version.then(&make_version)
other_short_version = other.short_version.then(&make_version)
short_version_difference = short_version <=> other_short_version
return short_version_difference unless short_version_difference.nil?
end
difference
end
sig { params(other: BundleVersion).returns(T::Boolean) }
def ==(other)
instance_of?(other.class) && short_version == other.short_version && version == other.version
end
alias eql? ==
# Create a nicely formatted version (on a best effort basis).
sig { returns(String) }
def nice_version
nice_parts.join(",")
end
sig { returns(T::Array[String]) }
def nice_parts
short_version = self.short_version
version = self.version
return [T.must(short_version)] if short_version == version
if short_version && version
return [version] if version.match?(/\A\d+(\.\d+)+\Z/) && version.start_with?("#{short_version}.")
return [short_version] if short_version.match?(/\A\d+(\.\d+)+\Z/) && short_version.start_with?("#{version}.")
if short_version.match?(/\A\d+(\.\d+)*\Z/) && version.match?(/\A\d+\Z/)
return [short_version] if short_version.start_with?("#{version}.") || short_version.end_with?(".#{version}")
return [short_version, version]
end
end
[short_version, version].compact
end
private :nice_parts
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/install.rb | Library/Homebrew/install.rb | # typed: strict
# frozen_string_literal: true
require "diagnostic"
require "fileutils"
require "hardware"
require "development_tools"
require "upgrade"
require "download_queue"
require "utils/output"
module Homebrew
# Helper module for performing (pre-)install checks.
module Install
extend Utils::Output::Mixin
class << self
sig { params(all_fatal: T::Boolean).void }
def perform_preinstall_checks_once(all_fatal: false)
@perform_preinstall_checks_once ||= T.let({}, T.nilable(T::Hash[T::Boolean, TrueClass]))
@perform_preinstall_checks_once[all_fatal] ||= begin
perform_preinstall_checks(all_fatal:)
true
end
end
sig { params(cc: T.nilable(String)).void }
def check_cc_argv(cc)
return unless cc
@checks ||= T.let(Diagnostic::Checks.new, T.nilable(Homebrew::Diagnostic::Checks))
opoo <<~EOS
You passed `--cc=#{cc}`.
#{@checks.support_tier_message(tier: 3)}
EOS
end
sig { params(all_fatal: T::Boolean).void }
def perform_build_from_source_checks(all_fatal: false)
Diagnostic.checks(:fatal_build_from_source_checks)
Diagnostic.checks(:build_from_source_checks, fatal: all_fatal)
end
sig { void }
def global_post_install; end
sig { void }
def check_prefix
if (Hardware::CPU.intel? || Hardware::CPU.in_rosetta2?) &&
HOMEBREW_PREFIX.to_s == HOMEBREW_MACOS_ARM_DEFAULT_PREFIX
if Hardware::CPU.in_rosetta2?
odie <<~EOS
Cannot install under Rosetta 2 in ARM default prefix (#{HOMEBREW_PREFIX})!
To rerun under ARM use:
arch -arm64 brew install ...
To install under x86_64, install Homebrew into #{HOMEBREW_DEFAULT_PREFIX}.
EOS
else
odie "Cannot install on Intel processor in ARM default prefix (#{HOMEBREW_PREFIX})!"
end
elsif Hardware::CPU.arm? && HOMEBREW_PREFIX.to_s == HOMEBREW_DEFAULT_PREFIX
odie <<~EOS
Cannot install in Homebrew on ARM processor in Intel default prefix (#{HOMEBREW_PREFIX})!
Please create a new installation in #{HOMEBREW_MACOS_ARM_DEFAULT_PREFIX} using one of the
"Alternative Installs" from:
#{Formatter.url("https://docs.brew.sh/Installation")}
You can migrate your previously installed formula list with:
brew bundle dump
EOS
end
end
sig {
params(formula: Formula, head: T::Boolean, fetch_head: T::Boolean,
only_dependencies: T::Boolean, force: T::Boolean, quiet: T::Boolean,
skip_link: T::Boolean, overwrite: T::Boolean).returns(T::Boolean)
}
def install_formula?(
formula,
head: false,
fetch_head: false,
only_dependencies: false,
force: false,
quiet: false,
skip_link: false,
overwrite: false
)
# HEAD-only without --HEAD is an error
if !head && formula.stable.nil?
odie <<~EOS
#{formula.full_name} is a HEAD-only formula.
To install it, run:
brew install --HEAD #{formula.full_name}
EOS
end
# --HEAD, fail with no head defined
odie "No head is defined for #{formula.full_name}" if head && formula.head.nil?
installed_head_version = formula.latest_head_version
if installed_head_version &&
!formula.head_version_outdated?(installed_head_version, fetch_head:)
new_head_installed = true
end
prefix_installed = formula.prefix.exist? && !formula.prefix.children.empty?
# Check if the installed formula is from a different tap
if formula.any_version_installed? &&
(current_tap_name = formula.tap&.name.presence) &&
(installed_keg_tab = formula.any_installed_keg&.tab.presence) &&
(installed_tap_name = installed_keg_tab.tap&.name.presence) &&
installed_tap_name != current_tap_name
odie <<~EOS
#{formula.name} was installed from the #{Formatter.identifier(installed_tap_name)} tap
but you are trying to install it from the #{Formatter.identifier(current_tap_name)} tap.
Formulae with the same name from different taps cannot be installed at the same time.
To install this version, you must first uninstall the existing formula:
brew uninstall #{formula.name}
Then you can install the desired version:
brew install #{formula.full_name}
EOS
end
if formula.keg_only? && formula.any_version_installed? && formula.optlinked? && !force
# keg-only install is only possible when no other version is
# linked to opt, because installing without any warnings can break
# dependencies. Therefore before performing other checks we need to be
# sure the --force switch is passed.
if formula.outdated?
if !Homebrew::EnvConfig.no_install_upgrade? && !formula.pinned?
name = formula.name
version = formula.linked_version
puts "#{name} #{version} is already installed but outdated (so it will be upgraded)."
return true
end
unpin_cmd_if_needed = ("brew unpin #{formula.full_name} && " if formula.pinned?)
optlinked_version = Keg.for(formula.opt_prefix).version
onoe <<~EOS
#{formula.full_name} #{optlinked_version} is already installed.
To upgrade to #{formula.version}, run:
#{unpin_cmd_if_needed}brew upgrade #{formula.full_name}
EOS
elsif only_dependencies
return true
elsif !quiet
opoo <<~EOS
#{formula.full_name} #{formula.pkg_version} is already installed and up-to-date.
To reinstall #{formula.pkg_version}, run:
brew reinstall #{formula.name}
EOS
end
elsif (head && new_head_installed) || prefix_installed
# After we're sure the --force switch was passed for linking to opt
# keg-only we need to be sure that the version we're attempting to
# install is not already installed.
installed_version = if head
formula.latest_head_version
else
formula.pkg_version
end
msg = "#{formula.full_name} #{installed_version} is already installed"
linked_not_equals_installed = formula.linked_version != installed_version
if formula.linked? && linked_not_equals_installed
msg = if quiet
nil
else
<<~EOS
#{msg}.
The currently linked version is: #{formula.linked_version}
EOS
end
elsif only_dependencies || (!formula.linked? && overwrite)
msg = nil
return true
elsif !formula.linked? || formula.keg_only?
msg = <<~EOS
#{msg}, it's just not linked.
To link this version, run:
brew link #{formula}
EOS
else
msg = if quiet
nil
else
<<~EOS
#{msg} and up-to-date.
To reinstall #{formula.pkg_version}, run:
brew reinstall #{formula.name}
EOS
end
end
opoo msg if msg
elsif !formula.any_version_installed? && (old_formula = formula.old_installed_formulae.first)
msg = "#{old_formula.full_name} #{old_formula.any_installed_version} already installed"
msg = if !old_formula.linked? && !old_formula.keg_only?
<<~EOS
#{msg}, it's just not linked.
To link this version, run:
brew link #{old_formula.full_name}
EOS
elsif quiet
nil
else
"#{msg}."
end
opoo msg if msg
elsif formula.migration_needed? && !force
# Check if the formula we try to install is the same as installed
# but not migrated one. If --force is passed then install anyway.
opoo <<~EOS
#{formula.oldnames_to_migrate.first} is already installed, it's just not migrated.
To migrate this formula, run:
brew migrate #{formula}
Or to force-install it, run:
brew install #{formula} --force
EOS
elsif formula.linked?
message = "#{formula.name} #{formula.linked_version} is already installed"
if formula.outdated? && !head
if !Homebrew::EnvConfig.no_install_upgrade? && !formula.pinned?
puts "#{message} but outdated (so it will be upgraded)."
return true
end
unpin_cmd_if_needed = ("brew unpin #{formula.full_name} && " if formula.pinned?)
onoe <<~EOS
#{message}
To upgrade to #{formula.pkg_version}, run:
#{unpin_cmd_if_needed}brew upgrade #{formula.full_name}
EOS
elsif only_dependencies || skip_link
return true
else
onoe <<~EOS
#{message}
To install #{formula.pkg_version}, first run:
brew unlink #{formula.name}
EOS
end
else
# If none of the above is true and the formula is linked, then
# FormulaInstaller will handle this case.
return true
end
# Even if we don't install this formula mark it as no longer just
# installed as a dependency.
return false unless formula.opt_prefix.directory?
keg = Keg.new(formula.opt_prefix.resolved_path)
tab = keg.tab
unless tab.installed_on_request
tab.installed_on_request = true
tab.write
end
false
end
sig {
params(formulae_to_install: T::Array[Formula], installed_on_request: T::Boolean,
installed_as_dependency: T::Boolean, build_bottle: T::Boolean, force_bottle: T::Boolean,
bottle_arch: T.nilable(String), ignore_deps: T::Boolean, only_deps: T::Boolean,
include_test_formulae: T::Array[String], build_from_source_formulae: T::Array[String],
cc: T.nilable(String), git: T::Boolean, interactive: T::Boolean, keep_tmp: T::Boolean,
debug_symbols: T::Boolean, force: T::Boolean, overwrite: T::Boolean, debug: T::Boolean,
quiet: T::Boolean, verbose: T::Boolean, dry_run: T::Boolean, skip_post_install: T::Boolean,
skip_link: T::Boolean).returns(T::Array[FormulaInstaller])
}
def formula_installers(
formulae_to_install,
installed_on_request: true,
installed_as_dependency: false,
build_bottle: false,
force_bottle: false,
bottle_arch: nil,
ignore_deps: false,
only_deps: false,
include_test_formulae: [],
build_from_source_formulae: [],
cc: nil,
git: false,
interactive: false,
keep_tmp: false,
debug_symbols: false,
force: false,
overwrite: false,
debug: false,
quiet: false,
verbose: false,
dry_run: false,
skip_post_install: false,
skip_link: false
)
formulae_to_install.filter_map do |formula|
Migrator.migrate_if_needed(formula, force:, dry_run:)
build_options = formula.build
FormulaInstaller.new(
formula,
options: build_options.used_options,
installed_on_request:,
installed_as_dependency:,
build_bottle:,
force_bottle:,
bottle_arch:,
ignore_deps:,
only_deps:,
include_test_formulae:,
build_from_source_formulae:,
cc:,
git:,
interactive:,
keep_tmp:,
debug_symbols:,
force:,
overwrite:,
debug:,
quiet:,
verbose:,
skip_post_install:,
skip_link:,
)
end
end
sig { params(formula_installers: T::Array[FormulaInstaller]).returns(T::Array[FormulaInstaller]) }
def fetch_formulae(formula_installers)
formulae_names_to_install = formula_installers.map { |fi| fi.formula.name }
return formula_installers if formulae_names_to_install.empty?
formula_sentence = formulae_names_to_install.map { |name| Formatter.identifier(name) }.to_sentence
oh1 "Fetching downloads for: #{formula_sentence}", truncate: false
if EnvConfig.download_concurrency > 1
download_queue = Homebrew::DownloadQueue.new(pour: true)
formula_installers.each do |fi|
fi.download_queue = download_queue
end
end
valid_formula_installers = formula_installers.dup
begin
[:prelude_fetch, :prelude, :fetch].each do |step|
valid_formula_installers.select! do |fi|
fi.public_send(step)
true
rescue CannotInstallFormulaError => e
ofail e.message
false
rescue UnsatisfiedRequirements, DownloadError, ChecksumMismatchError => e
ofail "#{fi.formula}: #{e}"
false
end
download_queue&.fetch
end
ensure
download_queue&.shutdown
end
valid_formula_installers
end
sig {
params(formula_installers: T::Array[FormulaInstaller], installed_on_request: T::Boolean,
installed_as_dependency: T::Boolean, build_bottle: T::Boolean, force_bottle: T::Boolean,
bottle_arch: T.nilable(String), ignore_deps: T::Boolean, only_deps: T::Boolean,
include_test_formulae: T::Array[String], build_from_source_formulae: T::Array[String],
cc: T.nilable(String), git: T::Boolean, interactive: T::Boolean, keep_tmp: T::Boolean,
debug_symbols: T::Boolean, force: T::Boolean, overwrite: T::Boolean, debug: T::Boolean,
quiet: T::Boolean, verbose: T::Boolean, dry_run: T::Boolean,
skip_post_install: T::Boolean, skip_link: T::Boolean).void
}
def install_formulae(
formula_installers,
installed_on_request: true,
installed_as_dependency: false,
build_bottle: false,
force_bottle: false,
bottle_arch: nil,
ignore_deps: false,
only_deps: false,
include_test_formulae: [],
build_from_source_formulae: [],
cc: nil,
git: false,
interactive: false,
keep_tmp: false,
debug_symbols: false,
force: false,
overwrite: false,
debug: false,
quiet: false,
verbose: false,
dry_run: false,
skip_post_install: false,
skip_link: false
)
formulae_names_to_install = formula_installers.map { |fi| fi.formula.name }
return if formulae_names_to_install.empty?
if dry_run
ohai "Would install #{Utils.pluralize("formula", formulae_names_to_install.count, include_count: true)}:"
puts formulae_names_to_install.join(" ")
formula_installers.each do |fi|
print_dry_run_dependencies(fi.formula, fi.compute_dependencies, &:name)
end
return
end
formula_installers.each do |fi|
formula = fi.formula
upgrade = formula.linked? && formula.outdated? && !formula.head? && !Homebrew::EnvConfig.no_install_upgrade?
install_formula(fi, upgrade:)
Cleanup.install_formula_clean!(formula)
end
end
sig {
params(
formula: Formula,
dependencies: T::Array[Dependency],
_block: T.proc.params(arg0: Formula).returns(String),
).void
}
def print_dry_run_dependencies(formula, dependencies, &_block)
return if dependencies.empty?
ohai "Would install #{Utils.pluralize("dependency", dependencies.count, include_count: true)} " \
"for #{formula.name}:"
formula_names = dependencies.map { |dep| yield dep.to_formula }
puts formula_names.join(" ")
end
# If asking the user is enabled, show dependency and size information.
sig { params(formulae_installer: T::Array[FormulaInstaller], dependants: Homebrew::Upgrade::Dependents, args: Homebrew::CLI::Args).void }
def ask_formulae(formulae_installer, dependants, args:)
return if formulae_installer.empty?
formulae = collect_dependencies(formulae_installer, dependants)
ohai "Looking for bottles..."
sizes = compute_total_sizes(formulae, debug: args.debug?)
puts "#{::Utils.pluralize("Formula", formulae.count)} \
(#{formulae.count}): #{formulae.join(", ")}\n\n"
puts "Download Size: #{disk_usage_readable(sizes.fetch(:download))}"
puts "Install Size: #{disk_usage_readable(sizes.fetch(:installed))}"
if (net_install_size = sizes[:net]) && net_install_size != 0
puts "Net Install Size: #{disk_usage_readable(net_install_size)}"
end
ask_input
end
sig { params(casks: T::Array[Cask::Cask]).void }
def ask_casks(casks)
return if casks.empty?
puts "#{::Utils.pluralize("Cask", casks.count, plural: "s")} \
(#{casks.count}): #{casks.join(", ")}\n\n"
ask_input
end
sig { params(formula_installer: FormulaInstaller, upgrade: T::Boolean).void }
def install_formula(formula_installer, upgrade:)
formula = formula_installer.formula
formula_installer.check_installation_already_attempted
if upgrade
Upgrade.print_upgrade_message(formula, formula_installer.options)
kegs = Upgrade.outdated_kegs(formula)
linked_kegs = kegs.select(&:linked?)
else
formula.print_tap_action
end
# first we unlink the currently active keg for this formula otherwise it is
# possible for the existing build to interfere with the build we are about to
# do! Seriously, it happens!
kegs.each(&:unlink) if kegs.present?
formula_installer.install
formula_installer.finish
rescue FormulaInstallationAlreadyAttemptedError
# We already attempted to upgrade f as part of the dependency tree of
# another formula. In that case, don't generate an error, just move on.
nil
ensure
# restore previous installation state if build failed
begin
linked_kegs&.each(&:link) unless formula&.latest_version_installed?
rescue
nil
end
end
private
sig { params(formula: Formula).returns(T::Array[Keg]) }
def outdated_kegs(formula)
[formula, *formula.old_installed_formulae].map(&:linked_keg)
.select(&:directory?)
.map { |k| Keg.new(k.resolved_path) }
end
sig { params(all_fatal: T::Boolean).void }
def perform_preinstall_checks(all_fatal: false)
check_prefix
check_cpu
attempt_directory_creation
Diagnostic.checks(:supported_configuration_checks, fatal: all_fatal)
Diagnostic.checks(:fatal_preinstall_checks)
end
sig { void }
def attempt_directory_creation
Keg.must_exist_directories.each do |dir|
FileUtils.mkdir_p(dir) unless dir.exist?
rescue
nil
end
end
sig { void }
def check_cpu
return unless Hardware::CPU.ppc?
odie <<~EOS
Sorry, Homebrew does not support your computer's CPU architecture!
For PowerPC Mac (PPC32/PPC64BE) support, see:
#{Formatter.url("https://github.com/mistydemeo/tigerbrew")}
EOS
end
sig { void }
def ask_input
ohai "Do you want to proceed with the installation? [Y/y/yes/N/n/no]"
accepted_inputs = %w[y yes]
declined_inputs = %w[n no]
loop do
result = $stdin.gets
return unless result
result = result.chomp.strip.downcase
if accepted_inputs.include?(result)
break
elsif declined_inputs.include?(result)
exit 1
else
puts "Invalid input. Please enter 'Y', 'y', or 'yes' to proceed, or 'N' to abort."
end
end
end
# Compute the total sizes (download, installed, and net) for the given formulae.
sig { params(sized_formulae: T::Array[Formula], debug: T::Boolean).returns(T::Hash[Symbol, Integer]) }
def compute_total_sizes(sized_formulae, debug: false)
total_download_size = 0
total_installed_size = 0
total_net_size = 0
sized_formulae.each do |formula|
bottle = formula.bottle
next unless bottle
# Fetch additional bottle metadata (if necessary).
bottle.fetch_tab(quiet: !debug)
total_download_size += bottle.bottle_size.to_i if bottle.bottle_size
total_installed_size += bottle.installed_size.to_i if bottle.installed_size
# Sum disk usage for all installed kegs of the formula.
next if formula.installed_kegs.none?
kegs_dep_size = formula.installed_kegs.sum { |keg| keg.disk_usage.to_i }
total_net_size += bottle.installed_size.to_i - kegs_dep_size if bottle.installed_size
end
{ download: total_download_size,
installed: total_installed_size,
net: total_net_size }
end
sig {
params(formulae_installer: T::Array[FormulaInstaller],
dependants: Homebrew::Upgrade::Dependents).returns(T::Array[Formula])
}
def collect_dependencies(formulae_installer, dependants)
formulae_dependencies = formulae_installer.flat_map do |f|
[f.formula, f.compute_dependencies.flatten.grep(Dependency).flat_map(&:to_formula)]
end.flatten.uniq
formulae_dependencies.concat(dependants.upgradeable) if dependants.upgradeable
formulae_dependencies.uniq
end
end
end
end
require "extend/os/install"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/github_runner.rb | Library/Homebrew/github_runner.rb | # typed: strict
# frozen_string_literal: true
require "linux_runner_spec"
require "macos_runner_spec"
class GitHubRunner < T::Struct
const :platform, Symbol
const :arch, Symbol
const :spec, T.any(LinuxRunnerSpec, MacOSRunnerSpec)
const :macos_version, T.nilable(MacOSVersion)
prop :active, T::Boolean, default: false
sig { returns(T::Boolean) }
def macos?
platform == :macos
end
sig { returns(T::Boolean) }
def linux?
platform == :linux
end
sig { returns(T::Boolean) }
def x86_64?
arch == :x86_64
end
sig { returns(T::Boolean) }
def arm64?
arch == :arm64
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/dependency.rb | Library/Homebrew/dependency.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "dependable"
# A dependency on another Homebrew formula.
#
# @api internal
class Dependency
include Dependable
sig { returns(String) }
attr_reader :name
sig { returns(T.nilable(Tap)) }
attr_reader :tap
def initialize(name, tags = [])
raise ArgumentError, "Dependency must have a name!" unless name
@name = name
@tags = tags
return unless (tap_with_name = Tap.with_formula_name(name))
@tap, = tap_with_name
end
def ==(other)
instance_of?(other.class) && name == other.name && tags == other.tags
end
alias eql? ==
def hash
[name, tags].hash
end
def to_installed_formula
formula = Formulary.resolve(name)
formula.build = BuildOptions.new(options, formula.options)
formula
end
def to_formula
formula = Formulary.factory(name, warn: false)
formula.build = BuildOptions.new(options, formula.options)
formula
end
sig {
params(
minimum_version: T.nilable(Version),
minimum_revision: T.nilable(Integer),
minimum_compatibility_version: T.nilable(Integer),
bottle_os_version: T.nilable(String),
).returns(T::Boolean)
}
def installed?(minimum_version: nil, minimum_revision: nil, minimum_compatibility_version: nil,
bottle_os_version: nil)
formula = begin
to_installed_formula
rescue FormulaUnavailableError
nil
end
return false unless formula
# If the opt prefix doesn't exist: we likely have an incomplete installation.
return false unless formula.opt_prefix.exist?
return true if formula.latest_version_installed?
return false if minimum_version.blank?
installed_keg = formula.any_installed_keg
return false unless installed_keg
# If the keg name doesn't match, we may have moved from an alias to a full formula and need to upgrade.
return false unless formula.possible_names.include?(installed_keg.name)
installed_version = installed_keg.version
# If both the formula and minimum dependency have a compatibility_version set,
# and they match, the dependency is satisfied regardless of version/revision.
if minimum_compatibility_version.present? && formula.compatibility_version.present?
installed_tab = Tab.for_keg(installed_keg)
installed_compatibility_version = installed_tab.source&.dig("versions", "compatibility_version")
# If installed version has same compatibility_version as required, it's compatible
return true if installed_compatibility_version == minimum_compatibility_version &&
formula.compatibility_version == minimum_compatibility_version
end
# Tabs prior to 4.1.18 did not have revision or pkg_version fields.
# As a result, we have to be more conversative when we do not have
# a minimum revision from the tab and assume that if the formula has a
# the same version and a non-zero revision that it needs upgraded.
if minimum_revision.present?
minimum_pkg_version = PkgVersion.new(minimum_version, minimum_revision)
installed_version >= minimum_pkg_version
elsif installed_version.version == minimum_version
formula.revision.zero?
else
installed_version.version > minimum_version
end
end
def satisfied?(minimum_version: nil, minimum_revision: nil,
minimum_compatibility_version: nil, bottle_os_version: nil)
installed?(minimum_version:, minimum_revision:, minimum_compatibility_version:, bottle_os_version:) &&
missing_options.empty?
end
def missing_options
formula = to_installed_formula
required = options
required &= formula.options.to_a
required -= Tab.for_formula(formula).used_options
required
end
def option_names
[name.split("/").last].freeze
end
sig { overridable.returns(T::Boolean) }
def uses_from_macos?
false
end
sig { returns(String) }
def to_s = name
sig { returns(String) }
def inspect
"#<#{self.class.name}: #{name.inspect} #{tags.inspect}>"
end
sig { params(formula: Formula).returns(T.self_type) }
def dup_with_formula_name(formula)
self.class.new(formula.full_name.to_s, tags)
end
class << self
# Expand the dependencies of each dependent recursively, optionally yielding
# `[dependent, dep]` pairs to allow callers to apply arbitrary filters to
# the list.
# The default filter, which is applied when a block is not given, omits
# optionals and recommends based on what the dependent has asked for
#
# @api internal
def expand(dependent, deps = dependent.deps, cache_key: nil, cache_timestamp: nil, &block)
# Keep track dependencies to avoid infinite cyclic dependency recursion.
@expand_stack ||= []
@expand_stack.push dependent.name
if cache_key.present?
cache_key = "#{cache_key}-#{cache_timestamp}" if cache_timestamp
if (entry = cache(cache_key, cache_timestamp:)[cache_id dependent])
return entry.dup
end
end
expanded_deps = []
deps.each do |dep|
next if dependent.name == dep.name
case action(dependent, dep, &block)
when :prune
next
when :skip
next if @expand_stack.include? dep.name
expanded_deps.concat(expand(dep.to_formula, cache_key:, &block))
when :keep_but_prune_recursive_deps
expanded_deps << dep
else
next if @expand_stack.include? dep.name
dep_formula = dep.to_formula
expanded_deps.concat(expand(dep_formula, cache_key:, &block))
# Fixes names for renamed/aliased formulae.
dep = dep.dup_with_formula_name(dep_formula)
expanded_deps << dep
end
end
expanded_deps = merge_repeats(expanded_deps)
cache(cache_key, cache_timestamp:)[cache_id dependent] = expanded_deps.dup if cache_key.present?
expanded_deps
ensure
@expand_stack.pop
end
def action(dependent, dep, &block)
catch(:action) do
if block
yield dependent, dep
elsif dep.optional? || dep.recommended?
prune unless dependent.build.with?(dep)
end
end
end
# Prune a dependency and its dependencies recursively.
sig { void }
def prune
throw(:action, :prune)
end
# Prune a single dependency but do not prune its dependencies.
sig { void }
def skip
throw(:action, :skip)
end
# Keep a dependency, but prune its dependencies.
#
# @api internal
sig { void }
def keep_but_prune_recursive_deps
throw(:action, :keep_but_prune_recursive_deps)
end
def merge_repeats(all)
grouped = all.group_by(&:name)
all.map(&:name).uniq.map do |name|
deps = grouped.fetch(name)
dep = deps.first
tags = merge_tags(deps)
kwargs = {}
kwargs[:bounds] = dep.bounds if dep.uses_from_macos?
dep.class.new(name, tags, **kwargs)
end
end
def cache(key, cache_timestamp: nil)
@cache ||= { timestamped: {}, not_timestamped: {} }
if cache_timestamp
@cache[:timestamped][cache_timestamp] ||= {}
@cache[:timestamped][cache_timestamp][key] ||= {}
else
@cache[:not_timestamped][key] ||= {}
end
end
def clear_cache
return unless @cache
# No need to clear the timestamped cache as it's timestamped, and doing so causes problems in `expand`.
# See https://github.com/Homebrew/brew/pull/20896#issuecomment-3419257460
@cache[:not_timestamped].clear
end
def delete_timestamped_cache_entry(key, cache_timestamp)
return unless @cache
return unless (timestamp_entry = @cache[:timestamped][cache_timestamp])
timestamp_entry.delete(key)
@cache[:timestamped].delete(cache_timestamp) if timestamp_entry.empty?
end
private
def cache_id(dependent)
"#{dependent.full_name}_#{dependent.class}"
end
def merge_tags(deps)
other_tags = deps.flat_map(&:option_tags).uniq
other_tags << :test if deps.flat_map(&:tags).include?(:test)
merge_necessity(deps) + merge_temporality(deps) + other_tags
end
def merge_necessity(deps)
# Cannot use `deps.any?(&:required?)` here due to its definition.
if deps.any? { |dep| !dep.recommended? && !dep.optional? }
[] # Means required dependency.
elsif deps.any?(&:recommended?)
[:recommended]
else # deps.all?(&:optional?)
[:optional]
end
end
def merge_temporality(deps)
new_tags = []
new_tags << :build if deps.all?(&:build?)
new_tags << :implicit if deps.all?(&:implicit?)
new_tags
end
end
end
# A dependency that's marked as "installed" on macOS
class UsesFromMacOSDependency < Dependency
attr_reader :bounds
sig { params(name: String, tags: T::Array[Symbol], bounds: T::Hash[Symbol, Symbol]).void }
def initialize(name, tags = [], bounds:)
super(name, tags)
@bounds = bounds
end
def ==(other)
instance_of?(other.class) && name == other.name && tags == other.tags && bounds == other.bounds
end
def hash
[name, tags, bounds].hash
end
sig {
params(
minimum_version: T.nilable(Version),
minimum_revision: T.nilable(Integer),
minimum_compatibility_version: T.nilable(Integer),
bottle_os_version: T.nilable(String),
).returns(T::Boolean)
}
def installed?(minimum_version: nil, minimum_revision: nil, minimum_compatibility_version: nil,
bottle_os_version: nil)
use_macos_install?(bottle_os_version:) || super
end
sig { params(bottle_os_version: T.nilable(String)).returns(T::Boolean) }
def use_macos_install?(bottle_os_version: nil)
# Check whether macOS is new enough for dependency to not be required.
if Homebrew::SimulateSystem.simulating_or_running_on_macos?
# If there's no since bound, the dependency is always available from macOS
since_os_bounds = bounds[:since]
return true if since_os_bounds.blank?
# When installing a bottle built on an older macOS version, use that version
# to determine if the dependency should come from macOS or Homebrew
effective_os = if bottle_os_version.present? &&
bottle_os_version.start_with?("macOS ")
# bottle_os_version is a string like "14" for Sonoma, "15" for Sequoia
# Convert it to a MacOS version symbol for comparison
MacOSVersion.new(bottle_os_version.delete_prefix("macOS "))
elsif Homebrew::SimulateSystem.current_os == :macos
# Assume the oldest macOS version when simulating a generic macOS version
# Version::NULL is always treated as less than any other version.
Version::NULL
else
MacOSVersion.from_symbol(Homebrew::SimulateSystem.current_os)
end
since_os = begin
MacOSVersion.from_symbol(since_os_bounds)
rescue MacOSVersion::Error
# If we can't parse the bound, it means it's an unsupported macOS version
# so let's default to the oldest possible macOS version
Version::NULL
end
return true if effective_os >= since_os
end
false
end
sig { override.returns(T::Boolean) }
def uses_from_macos?
true
end
sig { override.params(formula: Formula).returns(T.self_type) }
def dup_with_formula_name(formula)
self.class.new(formula.full_name.to_s, tags, bounds:)
end
sig { returns(String) }
def inspect
"#<#{self.class.name}: #{name.inspect} #{tags.inspect} #{bounds.inspect}>"
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/macos_runner_spec.rb | Library/Homebrew/macos_runner_spec.rb | # typed: strict
# frozen_string_literal: true
class MacOSRunnerSpec < T::Struct
const :name, String
const :runner, String
const :timeout, Integer
const :cleanup, T::Boolean
prop :testing_formulae, T::Array[String], default: []
sig {
returns({
name: String,
runner: String,
timeout: Integer,
cleanup: T::Boolean,
testing_formulae: String,
})
}
def to_h
{
name:,
runner:,
timeout:,
cleanup:,
testing_formulae: testing_formulae.join(","),
}
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/github_releases.rb | Library/Homebrew/github_releases.rb | # typed: strict
# frozen_string_literal: true
require "utils/github"
require "utils/output"
require "json"
# GitHub Releases client.
class GitHubReleases
include Context
include Utils::Output::Mixin
URL_REGEX = %r{https://github\.com/([\w-]+)/([\w-]+)?/releases/download/(.+)}
sig { params(bottles_hash: T::Hash[String, T.untyped]).void }
def upload_bottles(bottles_hash)
bottles_hash.each_value do |bottle_hash|
root_url = bottle_hash["bottle"]["root_url"]
url_match = root_url.match URL_REGEX
_, user, repo, tag = *url_match
# Ensure a release is created.
release = begin
rel = GitHub.get_release user, repo, tag
odebug "Existing GitHub release \"#{tag}\" found"
rel
rescue GitHub::API::HTTPNotFoundError
odebug "Creating new GitHub release \"#{tag}\""
GitHub.create_or_update_release user, repo, tag
end
# Upload bottles as release assets.
bottle_hash["bottle"]["tags"].each_value do |tag_hash|
remote_file = tag_hash["filename"]
local_file = tag_hash["local_filename"]
odebug "Uploading #{remote_file}"
GitHub.upload_release_asset user, repo, release["id"], local_file:, remote_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/simulate_system.rb | Library/Homebrew/simulate_system.rb | # typed: strict
# frozen_string_literal: true
require "macos_version"
require "utils/bottles"
module Homebrew
# Helper module for simulating different system configurations.
class SimulateSystem
class << self
sig { returns(T.nilable(Symbol)) }
attr_reader :arch
sig { returns(T.nilable(Symbol)) }
attr_reader :os
sig { returns(T::Hash[Symbol, Symbol]) }
def arch_symbols
{ arm64: :arm, x86_64: :intel }.freeze
end
sig {
type_parameters(:U).params(
os: Symbol,
arch: Symbol,
_block: T.proc.returns(T.type_parameter(:U)),
).returns(T.type_parameter(:U))
}
def with(os: T.unsafe(nil), arch: T.unsafe(nil), &_block)
raise ArgumentError, "At least one of `os` or `arch` must be specified." if !os && !arch
old_os = self.os
old_arch = self.arch
begin
self.os = os if os && os != current_os
self.arch = arch if arch && arch != current_arch
yield
ensure
@os = old_os
@arch = old_arch
end
end
sig {
type_parameters(:U).params(
tag: Utils::Bottles::Tag,
block: T.proc.returns(T.type_parameter(:U)),
).returns(T.type_parameter(:U))
}
def with_tag(tag, &block)
raise ArgumentError, "Invalid tag: #{tag}" unless tag.valid_combination?
with(os: tag.system, arch: tag.arch, &block)
end
sig { params(new_os: Symbol).void }
def os=(new_os)
os_options = [:macos, :linux, *MacOSVersion::SYMBOLS.keys]
raise "Unknown OS: #{new_os}" unless os_options.include?(new_os)
@os = T.let(new_os, T.nilable(Symbol))
end
sig { params(new_arch: Symbol).void }
def arch=(new_arch)
raise "New arch must be :arm or :intel" unless OnSystem::ARCH_OPTIONS.include?(new_arch)
@arch = T.let(new_arch, T.nilable(Symbol))
end
sig { void }
def clear
@os = @arch = nil
end
sig { returns(T::Boolean) }
def simulating_or_running_on_macos?
[:macos, *MacOSVersion::SYMBOLS.keys].include?(os)
end
sig { returns(T::Boolean) }
def simulating_or_running_on_linux?
os == :linux
end
sig { returns(Symbol) }
def current_arch
@arch || Hardware::CPU.type
end
sig { returns(Symbol) }
def current_os
os || :generic
end
sig { returns(Utils::Bottles::Tag) }
def current_tag
Utils::Bottles::Tag.new(
system: current_os,
arch: current_arch,
)
end
end
end
end
require "extend/os/simulate_system"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/requirements.rb | Library/Homebrew/requirements.rb | # typed: strict
# frozen_string_literal: true
require "requirement"
require "requirements/arch_requirement"
require "requirements/codesign_requirement"
require "requirements/linux_requirement"
require "requirements/macos_requirement"
require "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/development_tools.rb | Library/Homebrew/development_tools.rb | # typed: strict
# frozen_string_literal: true
require "version"
# Helper class for gathering information about development tools.
#
# @api public
class DevelopmentTools
class << self
# Locate a development tool.
#
# @api public
sig { params(tool: T.any(String, Symbol)).returns(T.nilable(Pathname)) }
def locate(tool)
# Don't call tools (cc, make, strip, etc.) directly!
# Give the name of the binary you look for as a string to this method
# in order to get the full path back as a Pathname.
(@locate ||= T.let({}, T.nilable(T::Hash[T.any(String, Symbol), T.untyped]))).fetch(tool) do |key|
@locate[key] = if File.executable?(path = "/usr/bin/#{tool}")
Pathname.new path
# Homebrew GCCs most frequently; much faster to check this before xcrun
elsif (path = HOMEBREW_PREFIX/"bin/#{tool}").executable?
path
end
end
end
sig { returns(T::Boolean) }
def installed?
locate("clang").present? || locate("gcc").present?
end
sig { returns(String) }
def installation_instructions
"Install Clang or run `brew install gcc`."
end
sig { returns(String) }
def custom_installation_instructions
installation_instructions
end
sig { params(resource: String).returns(String) }
def insecure_download_warning(resource)
package = curl_handles_most_https_certificates? ? "ca-certificates" : "curl"
"Using `--insecure` with curl to download #{resource} because we need it to run " \
"`brew install #{package}` in order to download securely from now on. " \
"Checksums will still be verified."
end
# Get the default C compiler.
#
# @api public
sig { returns(Symbol) }
def default_compiler
:clang
end
sig { returns(Version) }
def ld64_version
Version::NULL
end
# Get the Clang version.
#
# @api public
sig { returns(Version) }
def clang_version
@clang_version ||= T.let(
if (path = locate("clang")) &&
(build_version = `#{path} --version`[/(?:clang|LLVM) version (\d+\.\d(?:\.\d)?)/, 1])
Version.new(build_version)
else
Version::NULL
end, T.nilable(Version)
)
end
# Get the Clang build version.
#
# @api public
sig { returns(Version) }
def clang_build_version
@clang_build_version ||= T.let(
if (path = locate("clang")) &&
(build_version = `#{path} --version`[%r{clang(-| version [^ ]+ \(tags/RELEASE_)(\d{2,})}, 2])
Version.new(build_version)
else
Version::NULL
end, T.nilable(Version)
)
end
# Get the LLVM Clang build version.
#
# @api public
sig { returns(Version) }
def llvm_clang_build_version
@llvm_clang_build_version ||= T.let(begin
path = Formulary.factory("llvm").opt_prefix/"bin/clang"
if path.executable? && (build_version = `#{path} --version`[/clang version (\d+\.\d\.\d)/, 1])
Version.new(build_version)
else
Version::NULL
end
rescue FormulaUnavailableError
Version::NULL
end, T.nilable(Version))
end
sig { returns(Pathname) }
def host_gcc_path
Pathname.new("/usr/bin/gcc")
end
# Get the GCC version.
#
# @api public
sig { params(cc: String).returns(Version) }
def gcc_version(cc = host_gcc_path.to_s)
(@gcc_version ||= T.let({}, T.nilable(T::Hash[String, Version]))).fetch(cc) do
path = HOMEBREW_PREFIX/"opt/#{CompilerSelector.preferred_gcc}/bin"/cc
path = locate(cc) unless path.exist?
version = if path &&
(build_version = `#{path} --version`[/gcc(?:(?:-\d+(?:\.\d)?)? \(.+\))? (\d+\.\d\.\d)/, 1])
Version.new(build_version)
else
Version::NULL
end
@gcc_version[cc] = version
end
end
sig { void }
def clear_version_cache
@clang_version = @clang_build_version = T.let(nil, T.nilable(Version))
@gcc_version = T.let({}, T.nilable(T::Hash[String, Version]))
end
sig { returns(T::Boolean) }
def needs_build_formulae?
needs_libc_formula? || needs_compiler_formula?
end
sig { returns(T::Boolean) }
def needs_libc_formula?
false
end
sig { returns(T::Boolean) }
def needs_compiler_formula?
false
end
sig { returns(T::Boolean) }
def ca_file_handles_most_https_certificates?
# The system CA file is too old for some modern HTTPS certificates on
# older OS versions.
ENV["HOMEBREW_SYSTEM_CA_CERTIFICATES_TOO_OLD"].nil?
end
sig { returns(T::Boolean) }
def curl_handles_most_https_certificates?
true
end
sig { returns(T::Boolean) }
def ca_file_substitution_required?
(!ca_file_handles_most_https_certificates? || ENV["HOMEBREW_FORCE_BREWED_CA_CERTIFICATES"].present?) &&
!(HOMEBREW_PREFIX/"etc/ca-certificates/cert.pem").exist?
end
sig { returns(T::Boolean) }
def curl_substitution_required?
!curl_handles_most_https_certificates? && !HOMEBREW_BREWED_CURL_PATH.exist?
end
sig { returns(T::Hash[String, T.nilable(String)]) }
def build_system_info
{
"os" => HOMEBREW_SYSTEM,
"os_version" => OS_VERSION,
"cpu_family" => Hardware::CPU.family.to_s,
}
end
end
end
require "extend/os/development_tools"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/formula_stub.rb | Library/Homebrew/formula_stub.rb | # typed: strict
# frozen_string_literal: true
require "pkg_version"
module Homebrew
# A stub for a formula, with only the information needed to fetch the bottle manifest.
class FormulaStub < T::Struct
const :name, String
const :pkg_version, PkgVersion
const :version_scheme, Integer, default: 0
const :rebuild, Integer, default: 0
const :sha256, T.nilable(String)
const :aliases, T::Array[String], default: []
const :oldnames, T::Array[String], default: []
sig { returns(Version) }
def version
pkg_version.version
end
sig { returns(Integer) }
def revision
pkg_version.revision
end
sig { params(other: T.anything).returns(T::Boolean) }
def ==(other)
case other
when FormulaStub
name == other.name &&
pkg_version == other.pkg_version &&
version_scheme == other.version_scheme &&
rebuild == other.rebuild &&
sha256 == other.sha256 &&
aliases == other.aliases &&
oldnames == other.oldnames
else
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/style.rb | Library/Homebrew/style.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "shellwords"
require "source_location"
require "system_command"
require "utils/output"
module Homebrew
# Helper module for running RuboCop.
module Style
extend Utils::Output::Mixin
extend SystemCommand::Mixin
# Checks style for a list of files, printing simple RuboCop output.
# Returns true if violations were found, false otherwise.
def self.check_style_and_print(files, **options)
success = check_style_impl(files, :print, **options)
if GitHub::Actions.env_set? && !success
check_style_json(files, **options).each do |path, offenses|
offenses.each do |o|
line = o.location.line
column = o.location.line
annotation = GitHub::Actions::Annotation.new(:error, o.message, file: path, line:, column:)
puts annotation if annotation.relevant?
end
end
end
success
end
# Checks style for a list of files, returning results as an {Offenses}
# object parsed from its JSON output.
def self.check_style_json(files, **options)
check_style_impl(files, :json, **options)
end
def self.check_style_impl(files, output_type,
fix: false,
except_cops: nil, only_cops: nil,
display_cop_names: false,
reset_cache: false,
debug: false, verbose: false)
raise ArgumentError, "Invalid output type: #{output_type.inspect}" if [:print, :json].exclude?(output_type)
ruby_files = T.let([], T::Array[Pathname])
shell_files = T.let([], T::Array[Pathname])
actionlint_files = T.let([], T::Array[Pathname])
Array(files).map { Pathname(it) }
.each do |path|
case path.extname
when ".rb"
ruby_files << path
when ".sh"
shell_files << path
when ".yml"
actionlint_files << path if path.realpath.to_s.include?("/.github/workflows/")
else
ruby_files << path
shell_files += if [HOMEBREW_PREFIX, HOMEBREW_REPOSITORY].include?(path)
shell_scripts
else
path.glob("**/*.sh")
.reject { |file_path| file_path.to_s.include?("/vendor/") || file_path.directory? }
end
actionlint_files += (path/".github/workflows").glob("*.y{,a}ml")
end
end
rubocop_result = if files.present? && ruby_files.empty?
(output_type == :json) ? [] : true
else
run_rubocop(ruby_files, output_type,
fix:,
except_cops:, only_cops:,
display_cop_names:,
reset_cache:,
debug:, verbose:)
end
shellcheck_result = if files.present? && shell_files.empty?
(output_type == :json) ? [] : true
else
run_shellcheck(shell_files, output_type, fix:)
end
shfmt_result = files.present? && shell_files.empty?
shfmt_result ||= run_shfmt!(shell_files, fix:)
actionlint_files = github_workflow_files if files.blank? && actionlint_files.blank?
has_actionlint_workflow = actionlint_files.any? do |path|
path.to_s.end_with?("/.github/workflows/actionlint.yml")
end
odebug "actionlint workflow detected. Skipping actionlint checks." if has_actionlint_workflow
actionlint_result = files.present? && (has_actionlint_workflow || actionlint_files.empty?)
actionlint_result ||= run_actionlint!(actionlint_files)
if output_type == :json
Offenses.new(rubocop_result + shellcheck_result)
else
rubocop_result && shellcheck_result && shfmt_result && actionlint_result
end
end
RUBOCOP = (HOMEBREW_LIBRARY_PATH/"utils/rubocop.rb").freeze
def self.run_rubocop(files, output_type,
fix: false, except_cops: nil, only_cops: nil, display_cop_names: false, reset_cache: false,
debug: false, verbose: false)
require "warnings"
Warnings.ignore :parser_syntax do
require "rubocop"
end
require "rubocops/all"
args = %w[
--force-exclusion
]
args << "--autocorrect-all" if fix
args += ["--extra-details"] if verbose
if except_cops
except_cops.map! { |cop| RuboCop::Cop::Registry.global.qualified_cop_name(cop.to_s, "") }
cops_to_exclude = except_cops.select do |cop|
RuboCop::Cop::Registry.global.names.include?(cop) ||
RuboCop::Cop::Registry.global.departments.include?(cop.to_sym)
end
args << "--except" << cops_to_exclude.join(",") unless cops_to_exclude.empty?
elsif only_cops
only_cops.map! { |cop| RuboCop::Cop::Registry.global.qualified_cop_name(cop.to_s, "") }
cops_to_include = only_cops.select do |cop|
RuboCop::Cop::Registry.global.names.include?(cop) ||
RuboCop::Cop::Registry.global.departments.include?(cop.to_sym)
end
odie "RuboCops #{only_cops.join(",")} were not found" if cops_to_include.empty?
args << "--only" << cops_to_include.join(",")
end
files&.map!(&:expand_path)
base_dir = Dir.pwd
if files.blank? || files == [HOMEBREW_REPOSITORY]
files = [HOMEBREW_LIBRARY_PATH]
base_dir = HOMEBREW_LIBRARY_PATH
elsif files.any? { |f| f.to_s.start_with?(HOMEBREW_REPOSITORY/"docs") || (f.basename.to_s == "docs") }
args << "--config" << (HOMEBREW_REPOSITORY/"docs/docs_rubocop_style.yml")
elsif files.any? { |f| f.to_s.start_with? HOMEBREW_LIBRARY_PATH }
base_dir = HOMEBREW_LIBRARY_PATH
else
args << "--config" << (HOMEBREW_LIBRARY/".rubocop.yml")
base_dir = HOMEBREW_LIBRARY if files.any? { |f| f.to_s.start_with? HOMEBREW_LIBRARY }
end
HOMEBREW_CACHE.mkpath
cache_env = if (cache_dir = HOMEBREW_CACHE.realpath/"style") && cache_dir.writable?
args << "--parallel" unless fix
FileUtils.rm_rf cache_dir if reset_cache
{ "XDG_CACHE_HOME" => cache_dir.to_s }
else
args << "--cache" << "false"
{}
end
args += files
ruby_args = HOMEBREW_RUBY_EXEC_ARGS.dup
case output_type
when :print
args << "--debug" if debug
# Don't show the default formatter's progress dots
# on CI or if only checking a single file.
args << "--format" << "clang" if ENV["CI"] || files.one? { |f| !f.directory? }
args << "--color" if Tty.color?
system cache_env, *ruby_args, "--", RUBOCOP, *args, chdir: base_dir
$CHILD_STATUS.success?
when :json
result = system_command ruby_args.shift,
args: [*ruby_args, "--", RUBOCOP, "--format", "json", *args],
env: cache_env,
chdir: base_dir
json = json_result!(result)
json["files"].each do |file|
file["path"] = File.absolute_path(file["path"], base_dir)
end
end
end
def self.run_shellcheck(files, output_type, fix: false)
files = shell_scripts if files.blank?
files = files.map(&:realpath) # use absolute file paths
args = [
"--shell=bash",
"--enable=all",
"--external-sources",
"--source-path=#{HOMEBREW_LIBRARY}",
"--",
*files,
]
if fix
# patch options:
# -g 0 (--get=0) : suppress environment variable `PATCH_GET`
# -f (--force) : we know what we are doing, force apply patches
# -d / (--directory=/) : change to root directory, since we use absolute file paths
# -p0 (--strip=0) : do not strip path prefixes, since we are at root directory
# NOTE: We use short flags for compatibility.
patch_command = %w[patch -g 0 -f -d / -p0]
patches = system_command(shellcheck, args: ["--format=diff", *args]).stdout
Utils.safe_popen_write(*patch_command) { |p| p.write(patches) } if patches.present?
end
case output_type
when :print
system shellcheck, "--format=tty", *args
$CHILD_STATUS.success?
when :json
result = system_command shellcheck, args: ["--format=json", *args]
json = json_result!(result)
# Convert to same format as RuboCop offenses.
severity_hash = { "style" => "refactor", "info" => "convention" }
json.group_by { |v| v["file"] }
.map do |k, v|
{
"path" => k,
"offenses" => v.map do |o|
o.delete("file")
o["cop_name"] = "SC#{o.delete("code")}"
level = o.delete("level")
o["severity"] = severity_hash.fetch(level, level)
line = o.delete("line")
column = o.delete("column")
o["corrected"] = false
o["correctable"] = o.delete("fix").present?
o["location"] = {
"start_line" => line,
"start_column" => column,
"last_line" => o.delete("endLine"),
"last_column" => o.delete("endColumn"),
"line" => line,
"column" => column,
}
o
end,
}
end
end
end
def self.run_shfmt!(files, fix: false)
files = shell_scripts if files.blank?
# Do not format completions and Dockerfile
files.delete(HOMEBREW_REPOSITORY/"completions/bash/brew")
files.delete(HOMEBREW_REPOSITORY/"Dockerfile")
args = ["--language-dialect", "bash", "--indent", "2", "--case-indent", "--", *files]
args.unshift("--write") if fix # need to add before "--"
system shfmt, *args
$CHILD_STATUS.success?
end
def self.run_actionlint!(files)
files = github_workflow_files if files.blank?
# the ignore is to avoid false positives in e.g. actions, homebrew-test-bot
system actionlint, "-shellcheck", shellcheck,
"-config-file", HOMEBREW_REPOSITORY/".github/actionlint.yaml",
"-ignore", "image: string; options: string",
"-ignore", "label .* is unknown",
*files
$CHILD_STATUS.success?
end
def self.json_result!(result)
# An exit status of 1 just means violations were found; other numbers mean
# execution errors.
# JSON needs to be at least 2 characters.
result.assert_success! if !(0..1).cover?(result.status.exitstatus) || result.stdout.length < 2
JSON.parse(result.stdout)
end
def self.shell_scripts
[
HOMEBREW_ORIGINAL_BREW_FILE.realpath,
HOMEBREW_REPOSITORY/"completions/bash/brew",
HOMEBREW_REPOSITORY/"Dockerfile",
*HOMEBREW_REPOSITORY.glob(".devcontainer/**/*.sh"),
*HOMEBREW_REPOSITORY.glob("package/scripts/*"),
*HOMEBREW_LIBRARY.glob("Homebrew/**/*.sh").reject { |path| path.to_s.include?("/vendor/") },
*HOMEBREW_LIBRARY.glob("Homebrew/shims/**/*").map(&:realpath).uniq
.reject(&:directory?)
.reject { |path| path.basename.to_s == "cc" }
.select do |path|
%r{^#! ?/bin/(?:ba)?sh( |$)}.match?(path.read(13))
end,
*HOMEBREW_LIBRARY.glob("Homebrew/{dev-,}cmd/*.sh"),
*HOMEBREW_LIBRARY.glob("Homebrew/{cask/,}utils/*.sh"),
]
end
def self.github_workflow_files
HOMEBREW_REPOSITORY.glob(".github/workflows/*.yml")
end
def self.shellcheck
require "formula"
shellcheck_stub = Formulary.factory_stub("shellcheck")
shellcheck_stub.ensure_installed!(latest: true, reason: "shell style checks").opt_bin/"shellcheck"
end
def self.shfmt
require "formula"
shfmt_stub = Formulary.factory_stub("shfmt")
shfmt_stub.ensure_installed!(latest: true, reason: "formatting shell scripts")
HOMEBREW_LIBRARY/"Homebrew/utils/shfmt.sh"
end
def self.actionlint
require "formula"
actionlint_stub = Formulary.factory_stub("actionlint")
actionlint_stub.ensure_installed!(latest: true, reason: "GitHub Actions checks").opt_bin/"actionlint"
end
# Collection of style offenses.
class Offenses
include Enumerable
def initialize(paths)
@offenses = {}
paths.each do |f|
next if f["offenses"].empty?
path = Pathname(f["path"]).realpath
@offenses[path] = f["offenses"].map { |x| Offense.new(x) }
end
end
def for_path(path)
@offenses.fetch(Pathname(path), [])
end
def each(*args, &block)
@offenses.each(*args, &block)
end
end
# A style offense.
class Offense
attr_reader :severity, :message, :corrected, :location, :cop_name
def initialize(json)
@severity = json["severity"]
@message = json["message"]
@cop_name = json["cop_name"]
@corrected = json["corrected"]
location = json["location"]
@location = SourceLocation.new(location.fetch("line"), location["column"])
end
def severity_code
@severity[0].upcase
end
def corrected?
@corrected
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/build_environment.rb | Library/Homebrew/build_environment.rb | # typed: strict
# frozen_string_literal: true
# Settings for the build environment.
class BuildEnvironment
sig { params(settings: Symbol).void }
def initialize(*settings)
@settings = T.let(Set.new(settings), T::Set[Symbol])
end
sig { params(args: T::Enumerable[Symbol]).returns(T.self_type) }
def merge(*args)
@settings.merge(*args)
self
end
sig { params(option: Symbol).returns(T.self_type) }
def <<(option)
@settings << option
self
end
sig { returns(T::Boolean) }
def std?
@settings.include? :std
end
# DSL for specifying build environment settings.
module DSL
# Initialise @env for each class which may use this DSL (e.g. each formula subclass).
# `env` may never be called and it needs to be initialised before the class is frozen.
sig { params(child: T.untyped).void }
def inherited(child)
super
child.instance_eval do
@env = T.let(BuildEnvironment.new, T.nilable(BuildEnvironment))
end
end
sig { params(settings: Symbol).returns(BuildEnvironment) }
def env(*settings)
T.must(@env).merge(settings)
end
end
KEYS = %w[
CC CXX LD OBJC OBJCXX
HOMEBREW_CC HOMEBREW_CXX
CFLAGS CXXFLAGS CPPFLAGS LDFLAGS SDKROOT MAKEFLAGS
CMAKE_PREFIX_PATH CMAKE_INCLUDE_PATH CMAKE_LIBRARY_PATH CMAKE_FRAMEWORK_PATH
MACOSX_DEPLOYMENT_TARGET PKG_CONFIG_PATH PKG_CONFIG_LIBDIR
HOMEBREW_DEBUG HOMEBREW_MAKE_JOBS HOMEBREW_VERBOSE
all_proxy ftp_proxy http_proxy https_proxy no_proxy
HOMEBREW_SVN HOMEBREW_GIT
HOMEBREW_SDKROOT
MAKE GIT CPP
ACLOCAL_PATH PATH CPATH
LD_LIBRARY_PATH LD_RUN_PATH LD_PRELOAD LIBRARY_PATH
].freeze
private_constant :KEYS
sig { params(env: T::Hash[String, T.nilable(T.any(String, Pathname))]).returns(T::Array[String]) }
def self.keys(env)
KEYS & env.keys
end
sig { params(env: T::Hash[String, T.nilable(T.any(String, Pathname))], out: IO).void }
def self.dump(env, out = $stdout)
keys = self.keys(env)
keys -= %w[CC CXX OBJC OBJCXX] if env["CC"] == env["HOMEBREW_CC"]
keys.each do |key|
value = env.fetch(key)
string = "#{key}: #{value}"
case key
when "CC", "CXX", "LD"
string << " => #{Pathname.new(value).realpath}" if value.present? && File.symlink?(value)
end
string.freeze
out.puts 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/readline_nonblock.rb | Library/Homebrew/readline_nonblock.rb | # typed: strict
# frozen_string_literal: true
class ReadlineNonblock
sig { params(io: IO).returns(String) }
def self.read(io)
line = +""
buffer = +""
begin
loop do
break if buffer == $INPUT_RECORD_SEPARATOR
io.read_nonblock(1, buffer)
line.concat(buffer)
end
line.freeze
rescue IO::WaitReadable, EOFError
raise if line.empty?
line.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/standalone.rb | Library/Homebrew/standalone.rb | # typed: strict
# frozen_string_literal: true
# This file should be the first `require` in all entrypoints outside the `brew` environment.
require_relative "standalone/init"
require_relative "standalone/sorbet"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/formula_installer.rb | Library/Homebrew/formula_installer.rb | # typed: strict
# frozen_string_literal: true
require "formula"
require "keg"
require "tab"
require "utils/bottles"
require "caveats"
require "cleaner"
require "formula_cellar_checks"
require "install_renamed"
require "sandbox"
require "development_tools"
require "cache_store"
require "linkage_checker"
require "messages"
require "cask/cask_loader"
require "cmd/install"
require "find"
require "utils/spdx"
require "deprecate_disable"
require "unlink"
require "service"
require "attestation"
require "sbom"
require "utils/fork"
require "utils/output"
require "utils/attestation"
# Installer for a formula.
class FormulaInstaller
include FormulaCellarChecks
include Utils::Output::Mixin
ETC_VAR_DIRS = T.let([HOMEBREW_PREFIX/"etc", HOMEBREW_PREFIX/"var"].freeze, T::Array[Pathname])
sig { override.returns(Formula) }
attr_reader :formula
sig { returns(T::Hash[String, T::Hash[String, String]]) }
attr_reader :bottle_tab_runtime_dependencies
sig { returns(Options) }
attr_accessor :options
sig { returns(T::Boolean) }
attr_accessor :link_keg
sig { returns(T.nilable(Homebrew::DownloadQueue)) }
attr_accessor :download_queue
sig {
params(
formula: Formula,
link_keg: T::Boolean,
installed_as_dependency: T::Boolean,
installed_on_request: T::Boolean,
show_header: T::Boolean,
build_bottle: T::Boolean,
skip_post_install: T::Boolean,
skip_link: T::Boolean,
force_bottle: T::Boolean,
bottle_arch: T.nilable(String),
ignore_deps: T::Boolean,
only_deps: T::Boolean,
include_test_formulae: T::Array[String],
build_from_source_formulae: T::Array[String],
env: T.nilable(String),
git: T::Boolean,
interactive: T::Boolean,
keep_tmp: T::Boolean,
debug_symbols: T::Boolean,
cc: T.nilable(String),
options: Options,
force: T::Boolean,
overwrite: T::Boolean,
debug: T::Boolean,
quiet: T::Boolean,
verbose: T::Boolean,
).void
}
def initialize(
formula,
link_keg: false,
installed_as_dependency: false,
installed_on_request: false,
show_header: false,
build_bottle: false,
skip_post_install: false,
skip_link: false,
force_bottle: false,
bottle_arch: nil,
ignore_deps: false,
only_deps: false,
include_test_formulae: [],
build_from_source_formulae: [],
env: nil,
git: false,
interactive: false,
keep_tmp: false,
debug_symbols: false,
cc: nil,
options: Options.new,
force: false,
overwrite: false,
debug: false,
quiet: false,
verbose: false
)
@formula = formula
@env = env
@force = force
@overwrite = overwrite
@keep_tmp = keep_tmp
@debug_symbols = debug_symbols
@link_keg = T.let(!formula.keg_only? || link_keg, T::Boolean)
@show_header = show_header
@ignore_deps = ignore_deps
@only_deps = only_deps
@build_from_source_formulae = build_from_source_formulae
@build_bottle = build_bottle
@skip_post_install = skip_post_install
@skip_link = skip_link
@bottle_arch = bottle_arch
@formula.force_bottle ||= force_bottle
@force_bottle = T.let(@formula.force_bottle, T::Boolean)
@include_test_formulae = include_test_formulae
@interactive = interactive
@git = git
@cc = cc
@verbose = verbose
@quiet = quiet
@debug = debug
@installed_as_dependency = installed_as_dependency
@installed_on_request = installed_on_request
@options = options
@requirement_messages = T.let([], T::Array[String])
@poured_bottle = T.let(false, T::Boolean)
@start_time = T.let(nil, T.nilable(Time))
@bottle_tab_runtime_dependencies = T.let({}.freeze, T::Hash[String, T::Hash[String, String]])
@bottle_built_os_version = T.let(nil, T.nilable(String))
@hold_locks = T.let(false, T::Boolean)
@show_summary_heading = T.let(false, T::Boolean)
@etc_var_preinstall = T.let([], T::Array[Pathname])
@download_queue = T.let(nil, T.nilable(Homebrew::DownloadQueue))
# Take the original formula instance, which might have been swapped from an API instance to a source instance
@formula = T.let(T.must(previously_fetched_formula), Formula) if previously_fetched_formula
@ran_prelude_fetch = T.let(false, T::Boolean)
end
sig { returns(T::Boolean) }
def debug? = @debug
sig { returns(T::Boolean) }
def debug_symbols? = @debug_symbols
sig { returns(T::Boolean) }
def force? = @force
sig { returns(T::Boolean) }
def force_bottle? = @force_bottle
sig { returns(T::Boolean) }
def git? = @git
sig { returns(T::Boolean) }
def ignore_deps? = @ignore_deps
sig { returns(T::Boolean) }
def installed_as_dependency? = @installed_as_dependency
sig { returns(T::Boolean) }
def installed_on_request? = @installed_on_request
sig { returns(T::Boolean) }
def interactive? = @interactive
sig { returns(T::Boolean) }
def keep_tmp? = @keep_tmp
sig { returns(T::Boolean) }
def only_deps? = @only_deps
sig { returns(T::Boolean) }
def overwrite? = @overwrite
sig { returns(T::Boolean) }
def quiet? = @quiet
sig { returns(T::Boolean) }
def show_header? = @show_header
sig { returns(T::Boolean) }
def show_summary_heading? = @show_summary_heading
sig { returns(T::Boolean) }
def verbose? = @verbose
sig { returns(T::Set[Formula]) }
def self.attempted
@attempted ||= T.let(Set.new, T.nilable(T::Set[Formula]))
end
sig { void }
def self.clear_attempted
@attempted = T.let(Set.new, T.nilable(T::Set[Formula]))
end
sig { returns(T::Set[Formula]) }
def self.installed
@installed ||= T.let(Set.new, T.nilable(T::Set[Formula]))
end
sig { void }
def self.clear_installed
@installed = T.let(Set.new, T.nilable(T::Set[Formula]))
end
sig { returns(T::Set[Formula]) }
def self.fetched
@fetched ||= T.let(Set.new, T.nilable(T::Set[Formula]))
end
sig { void }
def self.clear_fetched
@fetched = T.let(Set.new, T.nilable(T::Set[Formula]))
end
sig { returns(T::Boolean) }
def build_from_source?
@build_from_source_formulae.include?(formula.full_name)
end
sig { returns(T::Boolean) }
def include_test?
@include_test_formulae.include?(formula.full_name)
end
sig { returns(T::Boolean) }
def build_bottle?
@build_bottle.present?
end
sig { returns(T::Boolean) }
def skip_post_install?
@skip_post_install.present?
end
sig { returns(T::Boolean) }
def skip_link?
@skip_link.present?
end
sig { params(output_warning: T::Boolean).returns(T::Boolean) }
def pour_bottle?(output_warning: false)
return false if !formula.bottle_tag? && !formula.local_bottle_path
return true if force_bottle?
return false if build_from_source? || build_bottle? || interactive?
return false if @cc
return false unless options.empty?
unless formula.pour_bottle?
if output_warning && formula.pour_bottle_check_unsatisfied_reason
opoo <<~EOS
Building #{formula.full_name} from source:
#{formula.pour_bottle_check_unsatisfied_reason}
EOS
end
return false
end
return true if formula.local_bottle_path.present?
bottle = formula.bottle_for_tag(Utils::Bottles.tag)
return false if bottle.nil?
unless bottle.compatible_locations?
if output_warning
prefix = Pathname(bottle.cellar.to_s).parent
opoo <<~EOS
Building #{formula.full_name} from source as the bottle needs:
- `HOMEBREW_CELLAR=#{bottle.cellar}` (yours is #{HOMEBREW_CELLAR})
- `HOMEBREW_PREFIX=#{prefix}` (yours is #{HOMEBREW_PREFIX})
EOS
end
return false
end
true
end
sig { params(dep: Formula, build: BuildOptions).returns(T::Boolean) }
def install_bottle_for?(dep, build)
return pour_bottle? if dep == formula
@build_from_source_formulae.exclude?(dep.full_name) &&
dep.bottle.present? &&
dep.pour_bottle? &&
build.used_options.empty? &&
dep.bottle&.compatible_locations?
end
sig { void }
def prelude_fetch
deprecate_disable_type = DeprecateDisable.type(formula)
if deprecate_disable_type.present?
message = "#{formula.full_name} has been #{DeprecateDisable.message(formula)}"
case deprecate_disable_type
when :deprecated
opoo message
when :disabled
if force?
opoo message
else
GitHub::Actions.puts_annotation_if_env_set!(:error, message)
raise CannotInstallFormulaError, message
end
end
end
if pour_bottle?
# Needs to be done before expand_dependencies for compute_dependencies
fetch_bottle_tab
elsif formula.loaded_from_api?
Homebrew::API::Formula.source_download(formula, download_queue:)
end
fetch_fetch_deps unless ignore_deps?
@ran_prelude_fetch = true
end
sig { void }
def prelude
prelude_fetch unless @ran_prelude_fetch
Tab.clear_cache
# Setup bottle_tab_runtime_dependencies for compute_dependencies and
# bottle_built_os_version for dependency resolution.
begin
bottle_tab_attributes = formula.bottle_tab_attributes
@bottle_tab_runtime_dependencies = bottle_tab_attributes
.fetch("runtime_dependencies", []).then { |deps| deps || [] }
.each_with_object({}) { |dep, h| h[dep["full_name"]] = dep }
.freeze
if (bottle_tag = formula.bottle_for_tag(Utils::Bottles.tag)&.tag) &&
bottle_tag.system != :all
# Extract the OS version the bottle was built on.
# This ensures that when installing older bottles (e.g. Sonoma bottle on Sequoia),
# we resolve dependencies according to the bottle's built OS, not the current OS.
@bottle_built_os_version = bottle_tab_attributes.dig("built_on", "os_version")
end
rescue Resource::BottleManifest::Error
# If we can't get the bottle manifest, assume a full dependencies install.
end
verify_deps_exist unless ignore_deps?
forbidden_license_check
forbidden_tap_check
forbidden_formula_check
check_install_sanity
# with the download queue: these should have already been installed
install_fetch_deps if !ignore_deps? && download_queue.nil?
end
sig { void }
def verify_deps_exist
begin
compute_dependencies
rescue TapFormulaUnavailableError => e
raise if e.tap.installed?
e.tap.ensure_installed!
retry if e.tap.installed? # It may have not installed if it's a core tap.
end
rescue FormulaUnavailableError => e
e.dependent = formula.full_name
raise
end
sig { void }
def check_installation_already_attempted
raise FormulaInstallationAlreadyAttemptedError, formula if self.class.attempted.include?(formula)
end
sig { void }
def check_install_sanity
check_installation_already_attempted
if force_bottle? && !pour_bottle?
raise CannotInstallFormulaError, "`--force-bottle` passed but #{formula.full_name} has no bottle!"
end
if Homebrew.default_prefix? &&
!build_from_source? && !build_bottle? && !formula.head? && formula.tap&.core_tap? &&
# Integration tests override homebrew-core locations
ENV["HOMEBREW_INTEGRATION_TEST"].nil? &&
!pour_bottle?
message = if !formula.pour_bottle? && formula.pour_bottle_check_unsatisfied_reason
formula_message = formula.pour_bottle_check_unsatisfied_reason
formula_message[0] = formula_message[0].downcase
<<~EOS
#{formula}: #{formula_message}
EOS
# don't want to complain about no bottle available if doing an
# upgrade/reinstall/dependency install (but do in the case the bottle
# check fails)
elsif fresh_install?(formula)
<<~EOS
#{formula}: no bottle available!
EOS
end
if message
message += <<~EOS
If you're feeling brave, you can try to install from source with:
brew install --build-from-source #{formula}
This is a Tier 3 configuration:
#{Formatter.url("https://docs.brew.sh/Support-Tiers#tier-3")}
#{Formatter.bold("Do not report any issues to Homebrew/* repositories!")}
Read the above document instead before opening any issues or PRs.
EOS
raise CannotInstallFormulaError, message
end
end
return if ignore_deps?
if Homebrew::EnvConfig.developer?
# `recursive_dependencies` trims cyclic dependencies, so we do one level and take the recursive deps of that.
# Mapping direct dependencies to deeper dependencies in a hash is also useful for the cyclic output below.
recursive_dep_map = formula.deps.to_h { |dep| [dep, dep.to_formula.recursive_dependencies] }
cyclic_dependencies = []
recursive_dep_map.each do |dep, recursive_deps|
if [formula.name, formula.full_name].include?(dep.name)
cyclic_dependencies << "#{formula.full_name} depends on itself directly"
elsif recursive_deps.any? { |rdep| [formula.name, formula.full_name].include?(rdep.name) }
cyclic_dependencies << "#{formula.full_name} depends on itself via #{dep.name}"
end
end
if cyclic_dependencies.present?
raise CannotInstallFormulaError, <<~EOS
#{formula.full_name} contains a recursive dependency on itself:
#{cyclic_dependencies.join("\n ")}
EOS
end
end
recursive_deps = if pour_bottle?
formula.runtime_dependencies
else
formula.recursive_dependencies
end
invalid_arch_dependencies = []
pinned_unsatisfied_deps = []
recursive_deps.each do |dep|
tab = Tab.for_formula(dep.to_formula)
if tab.arch.present? && tab.arch.to_s != Hardware::CPU.arch.to_s
invalid_arch_dependencies << "#{dep} was built for #{tab.arch}"
end
next unless dep.to_formula.pinned?
next if dep.satisfied?
pinned_unsatisfied_deps << dep
end
if invalid_arch_dependencies.present?
raise CannotInstallFormulaError, <<~EOS
#{formula.full_name} dependencies not built for the #{Hardware::CPU.arch} CPU architecture:
#{invalid_arch_dependencies.join("\n ")}
EOS
end
return if pinned_unsatisfied_deps.empty?
raise CannotInstallFormulaError,
"You must `brew unpin #{pinned_unsatisfied_deps * " "}` as installing " \
"#{formula.full_name} requires the latest version of pinned dependencies."
end
sig { params(_formula: Formula).returns(T.nilable(T::Boolean)) }
def fresh_install?(_formula) = false
sig { void }
def fetch_fetch_deps
return if @compute_dependencies.blank?
compute_dependencies(use_cache: false) if @compute_dependencies.any? do |dep|
next false unless dep.implicit?
fetch_dependencies
true
end
end
sig { void }
def install_fetch_deps
return if @compute_dependencies.blank?
compute_dependencies(use_cache: false) if @compute_dependencies.any? do |dep|
next false unless dep.implicit?
fetch_dependencies
install_dependency(dep)
true
end
end
sig { void }
def build_bottle_preinstall
@etc_var_preinstall = Find.find(*ETC_VAR_DIRS.select(&:directory?)).to_a
end
sig { void }
def build_bottle_postinstall
etc_var_postinstall = Find.find(*ETC_VAR_DIRS.select(&:directory?)).to_a
(etc_var_postinstall - @etc_var_preinstall).each do |file|
Pathname.new(file).cp_path_sub(HOMEBREW_PREFIX, formula.bottle_prefix)
end
end
sig { void }
def install
lock
start_time = Time.now
if !pour_bottle? && DevelopmentTools.installed?
require "install"
Homebrew::Install.perform_build_from_source_checks
end
# Warn if a more recent version of this formula is available in the tap.
begin
if !quiet? &&
formula.pkg_version < (v = Formulary.factory(formula.full_name, force_bottle: force_bottle?).pkg_version)
opoo "#{formula.full_name} #{v} is available and more recent than version #{formula.pkg_version}."
end
rescue FormulaUnavailableError
nil
end
check_conflicts
raise UnbottledError, [formula] if !pour_bottle? && !DevelopmentTools.installed?
unless ignore_deps?
deps = compute_dependencies(use_cache: false)
if ((pour_bottle? && !DevelopmentTools.installed?) || build_bottle?) &&
(unbottled = unbottled_dependencies(deps)).presence
# Check that each dependency in deps has a bottle available, terminating
# abnormally with a UnbottledError if one or more don't.
raise UnbottledError, unbottled
end
install_dependencies(deps)
end
return if only_deps?
formula.deprecated_flags.each do |deprecated_option|
old_flag = deprecated_option.old_flag
new_flag = deprecated_option.current_flag
opoo "#{formula.full_name}: #{old_flag} was deprecated; using #{new_flag} instead!"
end
options = display_options(formula).join(" ")
oh1 "Installing #{Formatter.identifier(formula.full_name)} #{options}".strip if show_header?
if (tap = formula.tap) && tap.should_report_analytics?
require "utils/analytics"
Utils::Analytics.report_package_event(:formula_install, package_name: formula.name, tap_name: tap.name,
on_request: installed_on_request?, options:)
end
self.class.attempted << formula
if pour_bottle?
begin
pour
# Catch any other types of exceptions as they leave us with nothing installed.
rescue Exception # rubocop:disable Lint/RescueException
Keg.new(formula.prefix).ignore_interrupts_and_uninstall! if formula.prefix.exist?
raise
else
@poured_bottle = true
end
end
puts_requirement_messages
build_bottle_preinstall if build_bottle?
unless @poured_bottle
build
clean
# Store the formula used to build the keg in the keg.
formula_contents = if (local_bottle_path = formula.local_bottle_path)
Utils::Bottles.formula_contents local_bottle_path, name: formula.name
else
formula.path.read
end
s = formula_contents.gsub(/ bottle do.+?end\n\n?/m, "")
brew_prefix = formula.prefix/".brew"
brew_prefix.mkpath
Pathname(brew_prefix/"#{formula.name}.rb").atomic_write(s)
keg = Keg.new(formula.prefix)
tab = keg.tab
tab.installed_as_dependency = installed_as_dependency?
tab.installed_on_request = installed_on_request?
tab.write
end
build_bottle_postinstall if build_bottle?
opoo "Nothing was installed to #{formula.prefix}" unless formula.latest_version_installed?
end_time = Time.now
Homebrew.messages.package_installed(formula.name, end_time - start_time)
end
sig { void }
def check_conflicts
return if force?
conflicts = formula.conflicts.select do |c|
f = Formulary.factory(c.name)
rescue TapFormulaUnavailableError
# If the formula name is a fully-qualified name let's silently
# ignore it as we don't care about things used in taps that aren't
# currently tapped.
false
rescue FormulaUnavailableError => e
# If the formula name doesn't exist any more then complain but don't
# stop installation from continuing.
opoo <<~EOS
#{formula}: #{e.message}
'conflicts_with "#{c.name}"' should be removed from #{formula.path.basename}.
EOS
raise if Homebrew::EnvConfig.developer?
$stderr.puts "Please report this issue to the #{formula.tap&.full_name} tap".squeeze(" ")
$stderr.puts " (not Homebrew/* repositories)!" unless formula.core_formula?
false
else
f.linked_keg.exist? && f.opt_prefix.exist?
end
raise FormulaConflictError.new(formula, conflicts) unless conflicts.empty?
end
# Compute and collect the dependencies needed by the formula currently
# being installed.
sig { params(use_cache: T::Boolean).returns(T::Array[Dependency]) }
def compute_dependencies(use_cache: true)
@compute_dependencies = T.let(nil, T.nilable(T::Array[Dependency])) unless use_cache
@compute_dependencies ||= begin
# Needs to be done before expand_dependencies
fetch_bottle_tab if pour_bottle?
check_requirements(expand_requirements)
expand_dependencies
end
end
sig { params(deps: T::Array[Dependency]).returns(T::Array[Formula]) }
def unbottled_dependencies(deps)
deps.map(&:to_formula).reject do |dep_f|
next false unless dep_f.pour_bottle?
dep_f.bottled?
end
end
sig { void }
def compute_and_install_dependencies
deps = compute_dependencies
install_dependencies(deps)
end
sig { params(req_map: T::Hash[Formula, T::Array[Requirement]]).void }
def check_requirements(req_map)
@requirement_messages = []
fatals = []
req_map.each_pair do |dependent, reqs|
reqs.each do |req|
next if dependent.latest_version_installed? && req.is_a?(MacOSRequirement) && req.comparator == "<="
@requirement_messages << "#{dependent}: #{req.message}"
fatals << req if req.fatal?
end
end
return if fatals.empty?
puts_requirement_messages
raise UnsatisfiedRequirements, fatals
end
sig { params(formula: Formula).returns(T::Array[Requirement]) }
def runtime_requirements(formula)
runtime_deps = formula.runtime_formula_dependencies(undeclared: false)
recursive_requirements = formula.recursive_requirements do |dependent, _|
Requirement.prune unless runtime_deps.include?(dependent)
end
(recursive_requirements.to_a + formula.requirements.to_a).reject(&:build?).uniq
end
sig { returns(T::Hash[Formula, T::Array[Requirement]]) }
def expand_requirements
unsatisfied_reqs = Hash.new { |h, k| h[k] = [] }
formulae = [formula]
formula_deps_map = formula.recursive_dependencies
.each_with_object({}) { |dep, h| h[dep.name] = dep }
while (f = formulae.pop)
runtime_requirements = runtime_requirements(f)
f.recursive_requirements do |dependent, req|
build = effective_build_options_for(dependent)
install_bottle_for_dependent = install_bottle_for?(dependent, build)
keep_build_test = false
keep_build_test ||= runtime_requirements.include?(req)
keep_build_test ||= req.test? && include_test? && dependent == f
keep_build_test ||= req.build? && !install_bottle_for_dependent && !dependent.latest_version_installed?
if req.prune_from_option?(build) ||
req.satisfied?(env: @env, cc: @cc, build_bottle: @build_bottle, bottle_arch: @bottle_arch) ||
((req.build? || req.test?) && !keep_build_test) ||
formula_deps_map[dependent.name]&.build? ||
(only_deps? && f == dependent)
Requirement.prune
else
unsatisfied_reqs[dependent] << req
end
end
end
unsatisfied_reqs
end
sig { params(formula: Formula).returns(T::Array[Dependency]) }
def expand_dependencies_for_formula(formula)
# Cache for this expansion only. FormulaInstaller has a lot of inputs which can alter expansion.
cache_key = "FormulaInstaller-#{formula.full_name}-#{Time.now.to_f}"
Dependency.expand(formula, cache_key:) do |dependent, dep|
build = effective_build_options_for(dependent)
keep_build_test = false
keep_build_test ||= dep.test? && include_test? && @include_test_formulae.include?(dependent.full_name)
keep_build_test ||= dep.build? && !install_bottle_for?(dependent, build) &&
(formula.head? || !dependent.latest_version_installed?)
minimum_version = @bottle_tab_runtime_dependencies.dig(dep.name, "version").presence
minimum_version = Version.new(minimum_version) if minimum_version
minimum_revision = @bottle_tab_runtime_dependencies.dig(dep.name, "revision")
bottle_os_version = @bottle_built_os_version
if dep.prune_from_option?(build) || ((dep.build? || dep.test?) && !keep_build_test)
Dependency.prune
elsif dep.satisfied?(minimum_version:, minimum_revision:, bottle_os_version:)
Dependency.skip
end
end
end
sig { returns(T::Array[Dependency]) }
def expand_dependencies = expand_dependencies_for_formula(formula)
sig { params(dependent: Formula).returns(BuildOptions) }
def effective_build_options_for(dependent)
args = dependent.build.used_options
args |= options if dependent == formula
args |= Tab.for_formula(dependent).used_options
args &= dependent.options
BuildOptions.new(args, dependent.options)
end
sig { params(formula: Formula).returns(T::Array[String]) }
def display_options(formula)
options = if formula.head?
["--HEAD"]
else
[]
end
options += effective_build_options_for(formula).used_options.to_a.map(&:to_s)
options
end
sig { params(deps: T::Array[Dependency]).void }
def install_dependencies(deps)
if deps.empty? && only_deps?
puts "All dependencies for #{formula.full_name} are satisfied."
elsif !deps.empty?
if deps.length > 1
oh1 "Installing dependencies for #{formula.full_name}: " \
"#{deps.map { Formatter.identifier(it) }.to_sentence}",
truncate: false
end
deps.each { install_dependency(it) }
end
@show_header = true if deps.length > 1
end
sig { params(dep: Dependency).void }
def fetch_dependency(dep)
df = dep.to_formula
fi = FormulaInstaller.new(
df,
force_bottle: false,
# When fetching we don't need to recurse the dependency tree as it's already
# been done for us in `compute_dependencies` and there's no requirement to
# fetch in a particular order.
# Note, this tree can vary when pouring bottles so we need to check it then.
ignore_deps: !pour_bottle?,
installed_as_dependency: true,
include_test_formulae: @include_test_formulae,
build_from_source_formulae: @build_from_source_formulae,
keep_tmp: keep_tmp?,
debug_symbols: debug_symbols?,
force: force?,
debug: debug?,
quiet: quiet?,
verbose: verbose?,
)
fi.download_queue = download_queue
fi.prelude
fi.fetch
end
sig { params(dep: Dependency).void }
def install_dependency(dep)
df = dep.to_formula
if df.linked_keg.directory?
linked_keg = Keg.new(df.linked_keg.resolved_path)
tab = linked_keg.tab
keg_had_linked_keg = true
keg_was_linked = linked_keg.linked?
linked_keg.unlink
else
keg_had_linked_keg = false
end
if df.latest_version_installed?
installed_keg = Keg.new(df.prefix)
tab ||= installed_keg.tab
tmp_keg = Pathname.new("#{installed_keg}.tmp")
installed_keg.rename(tmp_keg) unless tmp_keg.directory?
end
if df.tap.present? && tab.present? && (tab_tap = tab.source["tap"].presence) &&
df.tap.to_s != tab_tap.to_s
odie <<~EOS
#{df} is already installed from #{tab_tap}!
Please `brew uninstall #{df}` first."
EOS
end
options = Options.new
options |= tab.used_options if tab.present?
options |= Tab.remap_deprecated_options(df.deprecated_options, dep.options)
options &= df.options
installed_on_request = df.any_version_installed? && tab.present? && tab.installed_on_request
installed_on_request ||= false
fi = FormulaInstaller.new(
df,
options:,
link_keg: keg_had_linked_keg && keg_was_linked,
installed_as_dependency: true,
installed_on_request:,
force_bottle: false,
include_test_formulae: @include_test_formulae,
build_from_source_formulae: @build_from_source_formulae,
keep_tmp: keep_tmp?,
debug_symbols: debug_symbols?,
force: force?,
debug: debug?,
quiet: quiet?,
verbose: verbose?,
)
oh1 "Installing #{formula.full_name} dependency: #{Formatter.identifier(dep.name)}"
# prelude only needed to populate bottle_tab_runtime_dependencies, fetching has already been done.
fi.prelude
fi.install
fi.finish
# Handle all possible exceptions installing deps.
rescue Exception => e # rubocop:disable Lint/RescueException
ignore_interrupts do
tmp_keg.rename(installed_keg.to_path) if tmp_keg && !installed_keg.directory?
linked_keg.link(verbose: verbose?) if keg_was_linked
end
raise unless e.is_a? FormulaInstallationAlreadyAttemptedError
# We already attempted to install f as part of another formula's
# dependency tree. In that case, don't generate an error, just move on.
nil
else
ignore_interrupts { FileUtils.rm_r(tmp_keg) if tmp_keg&.directory? }
end
sig { void }
def caveats
return if only_deps?
audit_installed if Homebrew::EnvConfig.developer?
return if !installed_on_request? || installed_as_dependency?
return if quiet?
caveats = Caveats.new(formula)
return if caveats.empty?
Homebrew.messages.record_completions_and_elisp(caveats.completions_and_elisp)
return if caveats.caveats.empty?
@show_summary_heading = true
ohai "Caveats", caveats.to_s
Homebrew.messages.record_caveats(formula.name, caveats)
end
sig { void }
def finish
return if only_deps?
ohai "Finishing up" if verbose?
keg = Keg.new(formula.prefix)
if skip_link?
unless quiet?
ohai "Skipping 'link' on request"
puts "You can run it manually using:"
puts " brew link #{formula.full_name}"
end
else
link(keg)
end
install_service
fix_dynamic_linkage(keg) if !@poured_bottle || !formula.bottle_specification.skip_relocation?
require "install"
Homebrew::Install.global_post_install
if build_bottle? || skip_post_install?
unless quiet?
if build_bottle?
ohai "Not running 'post_install' as we're building a bottle"
elsif skip_post_install?
ohai "Skipping 'post_install' on request"
end
puts "You can run it manually using:"
puts " brew postinstall #{formula.full_name}"
end
else
formula.install_etc_var
post_install if formula.post_install_defined?
end
keg.prepare_debug_symbols if debug_symbols?
# Updates the cache for a particular formula after doing an install
CacheStoreDatabase.use(:linkage) do |db|
break unless db.created?
LinkageChecker.new(keg, formula, cache_db: db, rebuild_cache: true)
end
# Update tab with actual runtime dependencies
tab = keg.tab
Tab.clear_cache
f_runtime_deps = formula.runtime_dependencies(read_from_tab: false)
tab.runtime_dependencies = Tab.runtime_deps_hash(formula, f_runtime_deps)
tab.write
# write/update a SBOM file (if we aren't bottling)
unless build_bottle?
sbom = SBOM.create(formula, tab)
sbom.write(validate: Homebrew::EnvConfig.developer?)
end
# let's reset Utils::Git.available? if we just installed git
Utils::Git.clear_available_cache if formula.name == "git"
# use installed ca-certificates when it's needed and available
if formula.name == "ca-certificates" &&
!DevelopmentTools.ca_file_handles_most_https_certificates?
ENV["SSL_CERT_FILE"] = ENV["GIT_SSL_CAINFO"] = (formula.pkgetc/"cert.pem").to_s
ENV["GIT_SSL_CAPATH"] = formula.pkgetc.to_s
end
# use installed curl when it's needed and available
if formula.name == "curl" &&
!DevelopmentTools.curl_handles_most_https_certificates?
ENV["HOMEBREW_CURL"] = (formula.opt_bin/"curl").to_s
Utils::Curl.clear_path_cache
end
caveats
ohai "Summary" if verbose? || show_summary_heading?
puts summary
self.class.installed << formula
ensure
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/formula_creator.rb | Library/Homebrew/formula_creator.rb | # typed: strict
# frozen_string_literal: true
require "digest"
require "erb"
require "utils/github"
require "utils/output"
module Homebrew
# Class for generating a formula from a template.
class FormulaCreator
include Utils::Output::Mixin
sig { returns(String) }
attr_accessor :name
sig { returns(Version) }
attr_reader :version
sig { returns(String) }
attr_reader :url
sig { returns(T::Boolean) }
attr_reader :head
sig {
params(url: String, name: T.nilable(String), version: T.nilable(String), tap: T.nilable(String),
mode: T.nilable(Symbol), license: T.nilable(String), fetch: T::Boolean, head: T::Boolean).void
}
def initialize(url:, name: nil, version: nil, tap: nil, mode: nil, license: nil, fetch: false, head: false)
@url = url
@mode = mode
@license = license
@fetch = fetch
tap = if tap.blank?
CoreTap.instance
else
Tap.fetch(tap)
end
@tap = T.let(tap, Tap)
if (match_github = url.match %r{github\.com/(?<user>[^/]+)/(?<repo>[^/]+).*})
user = T.must(match_github[:user])
repository = T.must(match_github[:repo])
if repository.end_with?(".git")
# e.g. https://github.com/Homebrew/brew.git
repository.delete_suffix!(".git")
head = true
end
odebug "github: #{user} #{repository} head:#{head}"
if name.blank?
name = repository
odebug "name from github: #{name}"
end
elsif name.blank?
stem = Pathname.new(url).stem
name = if stem.start_with?("index.cgi") && stem.include?("=")
# special cases first
# gitweb URLs e.g. http://www.codesrc.com/gitweb/index.cgi?p=libzipper.git;a=summary
stem.rpartition("=").last
else
# e.g. http://digit-labs.org/files/tools/synscan/releases/synscan-5.02.tar.gz
pathver = Version.parse(stem).to_s
stem.sub(/[-_.]?#{Regexp.escape(pathver)}$/, "")
end
odebug "name from url: #{name}"
end
@name = T.let(name, String)
@head = head
if version.present?
version = Version.new(version)
odebug "version from user: #{version}"
else
version = Version.detect(url)
odebug "version from url: #{version}"
end
if fetch && user && repository
github = GitHub.repository(user, repository)
if version.null? && !head
begin
latest_release = GitHub.get_latest_release(user, repository)
version = Version.new(latest_release.fetch("tag_name"))
odebug "github: version from latest_release: #{version}"
@url = "https://github.com/#{user}/#{repository}/archive/refs/tags/#{version}.tar.gz"
odebug "github: url changed to source archive #{@url}"
rescue GitHub::API::HTTPNotFoundError
odebug "github: latest_release lookup failed: #{url}"
end
end
end
@github = T.let(github, T.untyped)
@version = T.let(version, Version)
@sha256 = T.let(nil, T.nilable(String))
@desc = T.let(nil, T.nilable(String))
@homepage = T.let(nil, T.nilable(String))
@license = T.let(nil, T.nilable(String))
end
sig { void }
def verify_tap_available!
raise TapUnavailableError, @tap.name unless @tap.installed?
end
sig { returns(Pathname) }
def write_formula!
raise ArgumentError, "name is blank!" if @name.blank?
raise ArgumentError, "tap is blank!" if @tap.blank?
path = @tap.new_formula_path(@name)
raise "#{path} already exists" if path.exist?
if @version.nil? || @version.null?
odie "Version cannot be determined from URL. Explicitly set the version with `--set-version` instead."
end
if @fetch
unless @head
r = Resource.new
r.url(@url)
r.owner = self
filepath = r.fetch
html_doctype_prefix = "<!doctype html"
# Number of bytes to read from file start to ensure it is not HTML.
# HTML may start with arbitrary number of whitespace lines.
bytes_to_read = 100
if File.read(filepath, bytes_to_read).strip.downcase.start_with?(html_doctype_prefix)
raise "Downloaded URL is not archive"
end
@sha256 = T.let(filepath.sha256, T.nilable(String))
end
if @github
@desc = @github["description"]
@homepage = @github["homepage"].presence || "https://github.com/#{@github["full_name"]}"
@license = @github["license"]["spdx_id"] if @github["license"]
end
end
path.dirname.mkpath
path.write ERB.new(template, trim_mode: ">").result(binding)
path
end
private
sig { params(name: String).returns(String) }
def latest_versioned_formula(name)
name_prefix = "#{name}@"
CoreTap.instance.formula_names
.select { |f| f.start_with?(name_prefix) }
.max_by { |v| Gem::Version.new(v.sub(name_prefix, "")) } || "python"
end
sig { returns(String) }
def template
<<~ERB
# Documentation: https://docs.brew.sh/Formula-Cookbook
# https://docs.brew.sh/rubydoc/Formula
# PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
class #{Formulary.class_s(name)} < Formula
<% if @mode == :python %>
include Language::Python::Virtualenv
<% end %>
desc "#{@desc}"
homepage "#{@homepage}"
<% unless @head %>
url "#{@url}"
<% unless @version.detected_from_url? %>
version "#{@version.to_s.delete_prefix("v")}"
<% end %>
sha256 "#{@sha256}"
<% end %>
license "#{@license}"
<% if @head %>
head "#{@url}"
<% end %>
<% if @mode == :cabal %>
depends_on "cabal-install" => :build
depends_on "ghc" => :build
<% elsif @mode == :cmake %>
depends_on "cmake" => :build
<% elsif @mode == :crystal %>
depends_on "crystal" => :build
<% elsif @mode == :go %>
depends_on "go" => :build
<% elsif @mode == :meson %>
depends_on "meson" => :build
depends_on "ninja" => :build
<% elsif @mode == :node %>
depends_on "node"
<% elsif @mode == :perl %>
uses_from_macos "perl"
<% elsif @mode == :python %>
depends_on "#{latest_versioned_formula("python")}"
<% elsif @mode == :ruby %>
uses_from_macos "ruby"
<% elsif @mode == :rust %>
depends_on "rust" => :build
<% elsif @mode == :zig %>
depends_on "zig" => :build
<% elsif @mode.nil? %>
# depends_on "cmake" => :build
<% end %>
<% if @mode == :perl || :python || :ruby %>
# Additional dependency
# resource "" do
# url ""
# sha256 ""
# end
<% end %>
def install
<% if @mode == :cabal %>
system "cabal", "v2-update"
system "cabal", "v2-install", *std_cabal_v2_args
<% elsif @mode == :cmake %>
system "cmake", "-S", ".", "-B", "build", *std_cmake_args
system "cmake", "--build", "build"
system "cmake", "--install", "build"
<% elsif @mode == :autotools %>
# Remove unrecognized options if they cause configure to fail
# https://docs.brew.sh/rubydoc/Formula.html#std_configure_args-instance_method
system "./configure", "--disable-silent-rules", *std_configure_args
system "make", "install" # if this fails, try separate make/make install steps
<% elsif @mode == :crystal %>
system "shards", "build", "--release"
bin.install "bin/#{name}"
<% elsif @mode == :go %>
system "go", "build", *std_go_args(ldflags: "-s -w")
<% elsif @mode == :meson %>
system "meson", "setup", "build", *std_meson_args
system "meson", "compile", "-C", "build", "--verbose"
system "meson", "install", "-C", "build"
<% elsif @mode == :node %>
system "npm", "install", *std_npm_args
bin.install_symlink libexec.glob("bin/*")
<% elsif @mode == :perl %>
ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5"
ENV.prepend_path "PERL5LIB", libexec/"lib"
# Stage additional dependency (`Makefile.PL` style).
# resource("").stage do
# system "perl", "Makefile.PL", "INSTALL_BASE=\#{libexec}"
# system "make"
# system "make", "install"
# end
# Stage additional dependency (`Build.PL` style).
# resource("").stage do
# system "perl", "Build.PL", "--install_base", libexec
# system "./Build"
# system "./Build", "install"
# end
bin.install name
bin.env_script_all_files(libexec/"bin", PERL5LIB: ENV["PERL5LIB"])
<% elsif @mode == :python %>
virtualenv_install_with_resources
<% elsif @mode == :ruby %>
ENV["BUNDLE_FORCE_RUBY_PLATFORM"] = "1"
ENV["BUNDLE_WITHOUT"] = "development test"
ENV["BUNDLE_VERSION"] = "system" # Avoid installing Bundler into the keg
ENV["GEM_HOME"] = libexec
system "bundle", "install"
system "gem", "build", "\#{name}.gemspec"
system "gem", "install", "\#{name}-\#{version}.gem"
bin.install libexec/"bin/\#{name}"
bin.env_script_all_files(libexec/"bin", GEM_HOME: ENV["GEM_HOME"])
<% elsif @mode == :rust %>
system "cargo", "install", *std_cargo_args
<% elsif @mode == :zig %>
system "zig", "build", *std_zig_args
<% else %>
# Remove unrecognized options if they cause configure to fail
# https://docs.brew.sh/rubydoc/Formula.html#std_configure_args-instance_method
system "./configure", "--disable-silent-rules", *std_configure_args
# system "cmake", "-S", ".", "-B", "build", *std_cmake_args
<% end %>
end
test do
# `test do` will create, run in and delete a temporary directory.
#
# This test will fail and we won't accept that! For Homebrew/homebrew-core
# this will need to be a test that verifies the functionality of the
# software. Run the test with `brew test #{name}`. Options passed
# to `brew install` such as `--HEAD` also need to be provided to `brew test`.
#
# The installed folder is not in the path, so use the entire path to any
# executables being tested: `system bin/"program", "do", "something"`.
system "false"
end
end
ERB
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/migrator.rb | Library/Homebrew/migrator.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "lock_file"
require "keg"
require "tab"
require "utils/output"
# Helper class for migrating a formula from an old to a new name.
class Migrator
extend Utils::Output::Mixin
include Context
include Utils::Output::Mixin
# Error for when a migration is necessary.
class MigrationNeededError < RuntimeError
def initialize(oldname, newname)
super <<~EOS
#{oldname} was renamed to #{newname} and needs to be migrated by running:
brew migrate #{oldname}
EOS
end
end
# Error for when the old name's path does not exist.
class MigratorNoOldpathError < RuntimeError
def initialize(oldname)
super "#{HOMEBREW_CELLAR/oldname} doesn't exist."
end
end
# Error for when a formula is migrated to a different tap without explicitly using its fully-qualified name.
class MigratorDifferentTapsError < RuntimeError
def initialize(formula, oldname, tap)
msg = if tap.core_tap?
"Please try to use #{oldname} to refer to the formula.\n"
elsif tap
"Please try to use fully-qualified #{tap}/#{oldname} to refer to the formula.\n"
end
super <<~EOS
#{formula.name} from #{formula.tap} is given, but old name #{oldname} was installed from #{tap || "path or url"}.
#{msg}To force migration, run:
brew migrate --force #{oldname}
EOS
end
end
# Instance of renamed formula.
attr_reader :formula
# Old name of the formula.
attr_reader :oldname
# Path to oldname's Cellar.
attr_reader :old_cellar
# Path to oldname pin.
attr_reader :old_pin_record
# Path to oldname opt.
attr_reader :old_opt_records
# Oldname linked kegs.
attr_reader :old_linked_kegs
# Oldname linked kegs that were fully linked.
attr_reader :old_full_linked_kegs
# Tabs from oldname kegs.
attr_reader :old_tabs
# Tap of the old name.
attr_reader :old_tap
# Resolved path to oldname pin.
attr_reader :old_pin_link_record
# New name of the formula.
attr_reader :newname
# Path to newname Cellar according to new name.
attr_reader :new_cellar
# True if new Cellar existed at initialization time.
attr_reader :new_cellar_existed
# Path to newname pin.
attr_reader :new_pin_record
# Path to newname keg that will be linked if old_linked_keg isn't nil.
attr_reader :new_linked_keg_record
def self.oldnames_needing_migration(formula)
formula.oldnames.select do |oldname|
oldname_rack = HOMEBREW_CELLAR/oldname
next false if oldname_rack.symlink?
next false unless oldname_rack.directory?
true
end
end
def self.needs_migration?(formula)
!oldnames_needing_migration(formula).empty?
end
def self.migrate_if_needed(formula, force:, dry_run: false)
oldnames = Migrator.oldnames_needing_migration(formula)
begin
oldnames.each do |oldname|
if dry_run
oh1 "Would migrate formula #{Formatter.identifier(oldname)} to #{Formatter.identifier(formula.name)}"
next
end
migrator = Migrator.new(formula, oldname, force:)
migrator.migrate
end
rescue => e
onoe e
end
end
def initialize(formula, oldname, force: false)
@oldname = oldname
@newname = formula.name
@formula = formula
@old_cellar = HOMEBREW_CELLAR/oldname
raise MigratorNoOldpathError, oldname unless old_cellar.exist?
@old_tabs = old_cellar.subdirs.map { |d| Keg.new(d).tab }
@old_tap = old_tabs.first.tap
raise MigratorDifferentTapsError.new(formula, oldname, old_tap) if !force && !from_same_tap_user?
@new_cellar = HOMEBREW_CELLAR/formula.name
@new_cellar_existed = @new_cellar.exist?
@old_linked_kegs = linked_old_linked_kegs
@old_full_linked_kegs = []
@old_opt_records = []
old_linked_kegs.each do |old_linked_keg|
@old_full_linked_kegs << old_linked_keg if old_linked_keg.linked?
@old_opt_records << old_linked_keg.opt_record if old_linked_keg.optlinked?
end
unless old_linked_kegs.empty?
@new_linked_keg_record = HOMEBREW_CELLAR/"#{newname}/#{File.basename(old_linked_kegs.first)}"
end
@old_pin_record = HOMEBREW_PINNED_KEGS/oldname
@new_pin_record = HOMEBREW_PINNED_KEGS/newname
@pinned = old_pin_record.symlink?
@old_pin_link_record = old_pin_record.readlink if @pinned
end
# Fix `INSTALL_RECEIPT`s for tap-migrated formula.
def fix_tabs
old_tabs.each do |tab|
tab.tap = formula.tap
tab.write
end
end
sig { returns(T::Boolean) }
def from_same_tap_user?
formula_tap_user = formula.tap.user if formula.tap
old_tap_user = nil
new_tap = if old_tap
old_tap_user, = old_tap.user
if (migrate_tap = old_tap.tap_migrations[oldname])
new_tap_user, new_tap_repo = migrate_tap.split("/")
"#{new_tap_user}/#{new_tap_repo}"
end
end
if formula_tap_user == old_tap_user
true
# Homebrew didn't use to update tabs while performing tap-migrations,
# so there can be `INSTALL_RECEIPT`s containing wrong information about tap,
# so we check if there is an entry about oldname migrated to tap and if
# newname's tap is the same as tap to which oldname migrated, then we
# can perform migrations and the taps for oldname and newname are the same.
elsif formula.tap && old_tap && formula.tap == new_tap
fix_tabs
true
else
false
end
end
def linked_old_linked_kegs
keg_dirs = []
keg_dirs += new_cellar.subdirs if new_cellar.exist?
keg_dirs += old_cellar.subdirs
kegs = keg_dirs.map { |d| Keg.new(d) }
kegs.select { |keg| keg.linked? || keg.optlinked? }
end
def pinned?
@pinned
end
def migrate
oh1 "Migrating formula #{Formatter.identifier(oldname)} to #{Formatter.identifier(newname)}"
lock
unlink_oldname
unlink_newname if new_cellar.exist?
repin
move_to_new_directory
link_oldname_cellar
link_oldname_opt
link_newname unless old_linked_kegs.empty?
update_tabs
return unless formula.outdated?
opoo <<~EOS
#{Formatter.identifier(newname)} is outdated!
To avoid broken installations, as soon as possible please run:
brew upgrade
Or, if you're OK with a less reliable fix:
brew upgrade #{newname}
EOS
rescue Interrupt
ignore_interrupts { backup_oldname }
# Any exception means the migration did not complete.
rescue Exception => e # rubocop:disable Lint/RescueException
onoe "The migration did not complete successfully."
puts e
if debug?
require "utils/backtrace"
puts Utils::Backtrace.clean(e)
end
puts "Backing up..."
ignore_interrupts { backup_oldname }
ensure
unlock
end
def remove_conflicts(directory)
conflicted = T.let(false, T::Boolean)
directory.each_child do |c|
if c.directory? && !c.symlink?
conflicted ||= remove_conflicts(c)
else
next unless (new_cellar/c.relative_path_from(old_cellar)).exist?
begin
FileUtils.rm_rf c
rescue Errno::EACCES
conflicted = true
onoe "#{new_cellar/c.basename} already exists."
end
end
end
conflicted
end
def merge_directory(directory)
directory.each_child do |c|
new_path = new_cellar/c.relative_path_from(old_cellar)
if c.directory? && !c.symlink? && new_path.exist?
merge_directory(c)
c.unlink
else
FileUtils.mv(c, new_path)
end
end
end
# Move everything from `Cellar/oldname` to `Cellar/newname`.
def move_to_new_directory
return unless old_cellar.exist?
if new_cellar.exist?
conflicted = remove_conflicts(old_cellar)
odie "Remove #{new_cellar} and #{old_cellar} manually and run `brew reinstall #{newname}`." if conflicted
end
oh1 "Moving #{Formatter.identifier(oldname)} versions to #{new_cellar}"
if new_cellar.exist?
merge_directory(old_cellar)
else
FileUtils.mv(old_cellar, new_cellar)
end
end
def repin
return unless pinned?
# `old_pin_record` is a relative symlink and when we try to to read it
# from <dir> we actually try to find file
# <dir>/../<...>/../Cellar/name/version.
# To repin formula we need to update the link thus that it points to
# the right directory.
#
# NOTE: `old_pin_record.realpath.sub(oldname, newname)` is unacceptable
# here, because it resolves every symlink for `old_pin_record` and then
# substitutes oldname with newname. It breaks things like
# `Pathname#make_relative_symlink`, where `Pathname#relative_path_from`
# is used to find the relative path from source to destination parent
# and it assumes no symlinks.
src_oldname = (old_pin_record.dirname/old_pin_link_record).expand_path
new_pin_record.make_relative_symlink(src_oldname.sub(oldname, newname))
old_pin_record.delete
end
def unlink_oldname
oh1 "Unlinking #{Formatter.identifier(oldname)}"
old_cellar.subdirs.each do |d|
keg = Keg.new(d)
keg.unlink(verbose: verbose?)
end
end
def unlink_newname
oh1 "Temporarily unlinking #{Formatter.identifier(newname)}"
new_cellar.subdirs.each do |d|
keg = Keg.new(d)
keg.unlink(verbose: verbose?)
end
end
def link_newname
oh1 "Relinking #{Formatter.identifier(newname)}"
new_keg = Keg.new(new_linked_keg_record)
# If old_keg wasn't linked then we just optlink a keg.
# If old keg wasn't optlinked and linked, we don't call this method at all.
# If formula is keg-only we also optlink it.
if formula.keg_only? || old_full_linked_kegs.empty?
begin
new_keg.optlink(verbose: verbose?)
rescue Keg::LinkError => e
onoe "Failed to create #{formula.opt_prefix}"
raise
end
return
end
new_keg.remove_linked_keg_record if new_keg.linked?
begin
new_keg.link(overwrite: true, verbose: verbose?)
rescue Keg::ConflictError => e
onoe "The `brew link` step did not complete successfully."
puts e
puts
puts "Possible conflicting files are:"
new_keg.link(dry_run: true, overwrite: true, verbose: verbose?)
raise
rescue Keg::LinkError => e
onoe "The `brew link` step did not complete successfully."
puts e
puts
puts "You can try again using:"
puts " brew link #{formula.name}"
# Any exception means the `brew link` step did not complete.
rescue Exception => e # rubocop:disable Lint/RescueException
onoe "An unexpected error occurred during linking"
puts e
if debug?
require "utils/backtrace"
puts Utils::Backtrace.clean(e)
end
ignore_interrupts { new_keg.unlink(verbose: verbose?) }
raise
end
end
# Link keg to opt if it was linked before migrating.
def link_oldname_opt
old_opt_records.each do |old_opt_record|
old_opt_record.delete if old_opt_record.symlink?
old_opt_record.make_relative_symlink(new_linked_keg_record)
end
end
# After migration every `INSTALL_RECEIPT.json` has the wrong path to the formula
# so we must update `INSTALL_RECEIPT`s.
def update_tabs
new_tabs = new_cellar.subdirs.map { |d| Keg.new(d).tab }
new_tabs.each do |tab|
tab.source["path"] = formula.path.to_s if tab.source["path"]
tab.write
end
end
# Remove `opt/oldname` link if it belongs to newname.
def unlink_oldname_opt
return unless new_linked_keg_record.exist?
old_opt_records.each do |old_opt_record|
next unless old_opt_record.symlink?
next unless old_opt_record.exist?
next if new_linked_keg_record.realpath != old_opt_record.realpath
old_opt_record.unlink
old_opt_record.parent.rmdir_if_possible
end
end
# Remove `Cellar/oldname` if it exists.
def link_oldname_cellar
old_cellar.delete if old_cellar.symlink? || old_cellar.exist?
old_cellar.make_relative_symlink(formula.rack)
end
# Remove `Cellar/oldname` link if it belongs to newname.
def unlink_oldname_cellar
if (old_cellar.symlink? && !old_cellar.exist?) ||
(old_cellar.symlink? && formula.rack.exist? && formula.rack.realpath == old_cellar.realpath)
old_cellar.unlink
end
end
# Backup everything if errors occur while migrating.
def backup_oldname
unlink_oldname_opt
unlink_oldname_cellar
backup_oldname_cellar
backup_old_tabs
if pinned? && !old_pin_record.symlink?
src_oldname = (old_pin_record.dirname/old_pin_link_record).expand_path
old_pin_record.make_relative_symlink(src_oldname)
new_pin_record.delete
end
if new_cellar.exist?
new_cellar.subdirs.each do |d|
newname_keg = Keg.new(d)
newname_keg.unlink(verbose: verbose?)
newname_keg.uninstall unless new_cellar_existed
end
end
return if old_linked_kegs.empty?
# The keg used to be linked and when we backup everything we restore
# Cellar/oldname, the target also gets restored, so we are able to
# create a keg using its old path
old_full_linked_kegs.each do |old_linked_keg|
old_linked_keg.link(verbose: verbose?)
rescue Keg::LinkError
old_linked_keg.unlink(verbose: verbose?)
raise
rescue Keg::AlreadyLinkedError
old_linked_keg.unlink(verbose: verbose?)
retry
end
(old_linked_kegs - old_full_linked_kegs).each do |old_linked_keg|
old_linked_keg.optlink(verbose: verbose?)
end
end
def backup_oldname_cellar
FileUtils.mv(new_cellar, old_cellar) unless old_cellar.exist?
end
def backup_old_tabs
old_tabs.each(&:write)
end
def lock
@newname_lock = FormulaLock.new newname
@oldname_lock = FormulaLock.new oldname
@newname_lock.lock
@oldname_lock.lock
end
def unlock
@newname_lock.unlock
@oldname_lock.unlock
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/manpages.rb | Library/Homebrew/manpages.rb | # typed: strict
# frozen_string_literal: true
require "cli/parser"
require "erb"
module Homebrew
# Helper functions for generating homebrew manual.
module Manpages
Variables = Struct.new(
:alumni,
:commands,
:developer_commands,
:environment_variables,
:global_cask_options,
:global_options,
:project_leader,
:lead_maintainers,
:maintainers,
keyword_init: true,
)
SOURCE_PATH = T.let((HOMEBREW_LIBRARY_PATH/"manpages").freeze, Pathname)
TARGET_MAN_PATH = T.let((HOMEBREW_REPOSITORY/"manpages").freeze, Pathname)
TARGET_DOC_PATH = T.let((HOMEBREW_REPOSITORY/"docs").freeze, Pathname)
sig { params(quiet: T::Boolean).void }
def self.regenerate_man_pages(quiet:)
require "kramdown"
require "manpages/parser/ronn"
require "manpages/converter/kramdown"
require "manpages/converter/roff"
markup = build_man_page(quiet:)
root, warnings = Parser::Ronn.parse(markup)
$stderr.puts(warnings)
roff, warnings = Converter::Kramdown.convert(root)
$stderr.puts(warnings)
File.write(TARGET_DOC_PATH/"Manpage.md", roff)
roff, warnings = Converter::Roff.convert(root)
$stderr.puts(warnings)
File.write(TARGET_MAN_PATH/"brew.1", roff)
end
sig { params(quiet: T::Boolean).returns(String) }
def self.build_man_page(quiet:)
template = (SOURCE_PATH/"brew.1.md.erb").read
readme = HOMEBREW_REPOSITORY/"README.md"
variables = Variables.new(
commands: generate_cmd_manpages(Commands.internal_commands_paths),
developer_commands: generate_cmd_manpages(Commands.internal_developer_commands_paths),
global_cask_options: global_cask_options_manpage,
global_options: global_options_manpage,
environment_variables: env_vars_manpage,
project_leader: readme.read[/(Homebrew's \[Project Leader.*\.)/, 1]
.gsub(/\[([^\]]+)\]\([^)]+\)/, '\1'),
lead_maintainers: readme.read[/(Homebrew's \[Lead Maintainers.*\.)/, 1]
.gsub(/\[([^\]]+)\]\([^)]+\)/, '\1'),
maintainers: readme.read[/(Homebrew's other Maintainers .*\.)/, 1]
.gsub(/\[([^\]]+)\]\([^)]+\)/, '\1'),
alumni: readme.read[/(Former Maintainers .*\.)/, 1]
.gsub(/\[([^\]]+)\]\([^)]+\)/, '\1'),
)
ERB.new(template, trim_mode: ">").result(variables.instance_eval { binding })
end
sig { params(path: Pathname).returns(String) }
def self.sort_key_for_path(path)
# Options after regular commands (`~` comes after `z` in ASCII table).
path.basename.to_s.sub(/\.(rb|sh)$/, "").sub(/^--/, "~~")
end
sig { params(cmd_paths: T::Array[Pathname]).returns(String) }
def self.generate_cmd_manpages(cmd_paths)
man_page_lines = []
# preserve existing manpage order
cmd_paths.sort_by { sort_key_for_path(it) }
.each do |cmd_path|
cmd_man_page_lines = if (cmd_parser = Homebrew::CLI::Parser.from_cmd_path(cmd_path))
next if cmd_parser.hide_from_man_page
cmd_parser_manpage_lines(cmd_parser).join
else
cmd_comment_manpage_lines(cmd_path)&.join("\n")
end
# Convert subcommands to definition lists
cmd_man_page_lines&.gsub!(/(?<=\n\n)([\\?\[`].+):\n/, "\\1\n\n: ")
man_page_lines << cmd_man_page_lines
end
man_page_lines.compact.join("\n")
end
sig { params(cmd_parser: CLI::Parser).returns(T::Array[String]) }
def self.cmd_parser_manpage_lines(cmd_parser)
lines = []
usage_banner_text = cmd_parser.usage_banner_text
lines << format_usage_banner(usage_banner_text) if usage_banner_text
lines += cmd_parser.processed_options.filter_map do |short, long, desc, hidden|
next if hidden
if long.present?
next if Homebrew::CLI::Parser.global_options.include?([short, long, desc])
next if Homebrew::CLI::Parser.global_cask_options.any? do |_, option, kwargs|
[long, "#{long}="].include?(option) && kwargs.fetch(:description) == desc
end
end
generate_option_doc(short, long, desc)
end
lines
end
sig { params(cmd_path: Pathname).returns(T.nilable(T::Array[String])) }
def self.cmd_comment_manpage_lines(cmd_path)
comment_lines = cmd_path.read.lines.grep(/^#:/)
return if comment_lines.empty?
first_comment_line = comment_lines.first
return unless first_comment_line
return if first_comment_line.include?("@hide_from_man_page")
lines = [format_usage_banner(first_comment_line).chomp]
all_but_first_comment_lines = comment_lines.slice(1..-1)
return unless all_but_first_comment_lines
return if all_but_first_comment_lines.empty?
all_but_first_comment_lines.each do |line|
line = line.slice(4..-2)
unless line
lines.last << "\n"
next
end
# Omit the common global_options documented separately in the man page.
next if line.match?(/--(debug|help|quiet|verbose) /)
# Format one option or a comma-separated pair of short and long options.
line.gsub!(/^ +(-+[a-z-]+), (-+[a-z-]+) +(.*)$/, "`\\1`, `\\2`\n\n: \\3\n")
line.gsub!(/^ +(-+[a-z-]+) +(.*)$/, "`\\1`\n\n: \\2\n")
lines << line
end
lines.last << "\n"
lines
end
sig { returns(String) }
def self.global_cask_options_manpage
lines = ["These options are applicable to the `install`, `reinstall` and `upgrade` " \
"subcommands with the `--cask` switch.\n"]
lines += Homebrew::CLI::Parser.global_cask_options.map do |_, long, kwargs|
generate_option_doc(nil, long.chomp("="), kwargs.fetch(:description))
end
lines.join("\n")
end
sig { returns(String) }
def self.global_options_manpage
lines = ["These options are applicable across multiple subcommands.\n"]
lines += Homebrew::CLI::Parser.global_options.map do |short, long, desc|
generate_option_doc(short, long, desc)
end
lines.join("\n")
end
sig { returns(String) }
def self.env_vars_manpage
lines = Homebrew::EnvConfig::ENVS.flat_map do |env, hash|
entry = "`#{env}`\n\n: #{hash[:description]}\n"
default = hash[:default_text]
default ||= "`#{hash[:default]}`." if hash[:default]
entry += "\n\n *Default:* #{default}\n" if default
entry
end
lines.join("\n")
end
sig { params(opt: T.nilable(String)).returns(T.nilable(String)) }
def self.format_opt(opt)
"`#{opt}`" unless opt.nil?
end
sig {
params(
short: T.nilable(String),
long: T.nilable(String),
desc: String,
).returns(String)
}
def self.generate_option_doc(short, long, desc)
comma = (short && long) ? ", " : ""
<<~EOS
#{format_opt(short)}#{comma}#{format_opt(long)}
: #{desc}
EOS
end
sig { params(usage_banner: String).returns(String) }
def self.format_usage_banner(usage_banner)
usage_banner.sub(/^(#: *\* )?/, "### ")
.gsub(/(?<!`)\[([^\[\]]*)\](?!`)/, "\\[\\1\\]") # escape [] character (except those in code spans)
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/pypi_packages.rb | Library/Homebrew/pypi_packages.rb | # typed: strict
# frozen_string_literal: true
# Helper class for `pypi_packages` DSL.
# @api internal
class PypiPackages
sig { returns(T.nilable(String)) }
attr_reader :package_name
sig { returns(T::Array[String]) }
attr_reader :extra_packages
sig { returns(T::Array[String]) }
attr_reader :exclude_packages
sig { returns(T::Array[String]) }
attr_reader :dependencies
sig {
params(
package_name: T.nilable(String),
extra_packages: T::Array[String],
exclude_packages: T::Array[String],
dependencies: T::Array[String],
).void
}
def initialize(
package_name: nil,
extra_packages: [],
exclude_packages: [],
dependencies: []
)
@package_name = package_name
@extra_packages = extra_packages
@exclude_packages = exclude_packages
@dependencies = dependencies
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/env_config.rb | Library/Homebrew/env_config.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Homebrew
# Helper module for querying Homebrew-specific environment variables.
#
# @api internal
module EnvConfig
include Utils::Output::Mixin
extend Utils::Output::Mixin
module_function
ENVS = T.let({
HOMEBREW_ALLOWED_TAPS: {
description: "A space-separated list of taps. Homebrew will refuse to install a " \
"formula unless it and all of its dependencies are in an official tap " \
"or in a tap on this list.",
},
HOMEBREW_API_AUTO_UPDATE_SECS: {
description: "Check Homebrew's API for new formulae or cask data every " \
"`$HOMEBREW_API_AUTO_UPDATE_SECS` seconds. Alternatively, disable API auto-update " \
"checks entirely with `$HOMEBREW_NO_AUTO_UPDATE`.",
default: 450,
},
HOMEBREW_API_DOMAIN: {
description: "Use this URL as the download mirror for Homebrew JSON API. " \
"If metadata files at that URL are temporarily unavailable, " \
"the default API domain will be used as a fallback mirror.",
default_text: "`https://formulae.brew.sh/api`.",
default: HOMEBREW_API_DEFAULT_DOMAIN,
},
HOMEBREW_ARCH: {
description: "Linux only: Pass this value to a type name representing the compiler's `-march` option.",
default: "native",
},
HOMEBREW_ARTIFACT_DOMAIN: {
description: "Prefix all download URLs, including those for bottles, with this value. " \
"For example, `export HOMEBREW_ARTIFACT_DOMAIN=http://localhost:8080` will cause a " \
"formula with the URL `https://example.com/foo.tar.gz` to instead download from " \
"`http://localhost:8080/https://example.com/foo.tar.gz`. " \
"Bottle URLs however, have their domain replaced with this prefix. " \
"This results in e.g. " \
"`https://ghcr.io/v2/homebrew/core/gettext/manifests/0.21` " \
"to instead be downloaded from " \
"`http://localhost:8080/v2/homebrew/core/gettext/manifests/0.21`",
},
HOMEBREW_ARTIFACT_DOMAIN_NO_FALLBACK: {
description: "When `$HOMEBREW_ARTIFACT_DOMAIN` and `$HOMEBREW_ARTIFACT_DOMAIN_NO_FALLBACK` are both set, " \
"if the request to `$HOMEBREW_ARTIFACT_DOMAIN` fails then Homebrew will error rather than " \
"trying any other/default URLs.",
boolean: true,
},
HOMEBREW_ASK: {
description: "If set, pass `--ask` to all formulae `brew install`, `brew upgrade` and `brew reinstall` " \
"commands.",
boolean: true,
},
HOMEBREW_AUTO_UPDATE_SECS: {
description: "Run `brew update` once every `$HOMEBREW_AUTO_UPDATE_SECS` seconds before some commands, " \
"e.g. `brew install`, `brew upgrade` or `brew tap`. Alternatively, " \
"disable auto-update entirely with `$HOMEBREW_NO_AUTO_UPDATE`.",
default_text: "`86400` (24 hours), `3600` (1 hour) if a developer command has been run " \
"or `300` (5 minutes) if `$HOMEBREW_NO_INSTALL_FROM_API` is set.",
},
HOMEBREW_BAT: {
description: "If set, use `bat` for the `brew cat` command.",
boolean: true,
},
HOMEBREW_BAT_CONFIG_PATH: {
description: "Use this as the `bat` configuration file.",
default_text: "`$BAT_CONFIG_PATH`.",
},
HOMEBREW_BAT_THEME: {
description: "Use this as the `bat` theme for syntax highlighting.",
default_text: "`$BAT_THEME`.",
},
HOMEBREW_BOTTLE_DOMAIN: {
description: "Use this URL as the download mirror for bottles. " \
"If bottles at that URL are temporarily unavailable, " \
"the default bottle domain will be used as a fallback mirror. " \
"For example, `export HOMEBREW_BOTTLE_DOMAIN=http://localhost:8080` will cause all bottles " \
"to download from the prefix `http://localhost:8080/`. " \
"If bottles are not available at `$HOMEBREW_BOTTLE_DOMAIN` " \
"they will be downloaded from the default bottle domain.",
default_text: "`https://ghcr.io/v2/homebrew/core`.",
default: HOMEBREW_BOTTLE_DEFAULT_DOMAIN,
},
HOMEBREW_BREW_GIT_REMOTE: {
description: "Use this URL as the Homebrew/brew `git`(1) remote.",
default: HOMEBREW_BREW_DEFAULT_GIT_REMOTE,
},
HOMEBREW_BROWSER: {
description: "Use this as the browser when opening project homepages.",
default_text: "`$BROWSER` or the OS's default browser.",
},
HOMEBREW_BUNDLE_USER_CACHE: {
description: "If set, use this directory as the `bundle`(1) user cache.",
},
HOMEBREW_CACHE: {
description: "Use this directory as the download cache.",
default_text: "macOS: `~/Library/Caches/Homebrew`, " \
"Linux: `$XDG_CACHE_HOME/Homebrew` or `~/.cache/Homebrew`.",
default: HOMEBREW_DEFAULT_CACHE,
},
HOMEBREW_CASK_OPTS: {
description: "Append these options to all `cask` commands. All `--*dir` options, " \
"`--language`, `--require-sha` and `--no-binaries` are supported. " \
"For example, you might add something like the following to your " \
"`~/.profile`, `~/.bash_profile`, or `~/.zshenv`:" \
"\n\n `export HOMEBREW_CASK_OPTS=\"--appdir=${HOME}/Applications --fontdir=/Library/Fonts\"`",
},
HOMEBREW_CLEANUP_MAX_AGE_DAYS: {
description: "Cleanup all cached files older than this many days.",
default: 120,
},
HOMEBREW_CLEANUP_PERIODIC_FULL_DAYS: {
description: "If set, `brew install`, `brew upgrade` and `brew reinstall` will cleanup all formulae " \
"when this number of days has passed.",
default: 30,
},
HOMEBREW_COLOR: {
description: "If set, force colour output on non-TTY outputs.",
boolean: true,
},
HOMEBREW_CORE_GIT_REMOTE: {
description: "Use this URL as the Homebrew/homebrew-core `git`(1) remote.",
default_text: "`https://github.com/Homebrew/homebrew-core`.",
default: HOMEBREW_CORE_DEFAULT_GIT_REMOTE,
},
HOMEBREW_CURLRC: {
description: "If set to an absolute path (i.e. beginning with `/`), pass it with `--config` when invoking " \
"`curl`(1). " \
"If set but _not_ a valid path, do not pass `--disable`, which disables the " \
"use of `.curlrc`.",
},
HOMEBREW_CURL_PATH: {
description: "Linux only: Set this value to a new enough `curl` executable for Homebrew to use.",
default: "curl",
},
HOMEBREW_CURL_RETRIES: {
description: "Pass the given retry count to `--retry` when invoking `curl`(1).",
default: 3,
},
HOMEBREW_CURL_VERBOSE: {
description: "If set, pass `--verbose` when invoking `curl`(1).",
boolean: true,
},
HOMEBREW_DEBUG: {
description: "If set, always assume `--debug` when running commands.",
boolean: true,
},
HOMEBREW_DEVELOPER: {
description: "If set, tweak behaviour to be more relevant for Homebrew developers (active or " \
"budding) by e.g. turning warnings into errors.",
boolean: true,
},
HOMEBREW_DISABLE_DEBREW: {
description: "If set, the interactive formula debugger available via `--debug` will be disabled.",
boolean: true,
},
HOMEBREW_DISABLE_LOAD_FORMULA: {
description: "If set, refuse to load formulae. This is useful when formulae are not trusted (such " \
"as in pull requests).",
boolean: true,
},
HOMEBREW_DISPLAY: {
description: "Use this X11 display when opening a page in a browser, for example with " \
"`brew home`. Primarily useful on Linux.",
default_text: "`$DISPLAY`.",
},
HOMEBREW_DISPLAY_INSTALL_TIMES: {
description: "If set, print install times for each formula at the end of the run.",
boolean: true,
},
HOMEBREW_DOCKER_REGISTRY_BASIC_AUTH_TOKEN: {
description: "Use this base64 encoded username and password for authenticating with a Docker registry " \
"proxying GitHub Packages. If set to `none`, no authentication header will be sent. " \
"This can be used, if remote `$HOMEBREW_BOTTLE_DOMAIN` does not support any authentication. " \
"If `$HOMEBREW_DOCKER_REGISTRY_TOKEN` is set, it will be used instead.",
},
HOMEBREW_DOCKER_REGISTRY_TOKEN: {
description: "Use this bearer token for authenticating with a Docker registry proxying GitHub Packages. " \
"Preferred over `$HOMEBREW_DOCKER_REGISTRY_BASIC_AUTH_TOKEN`.",
},
HOMEBREW_DOWNLOAD_CONCURRENCY: {
description: "Homebrew will download in parallel using this many concurrent connections. " \
"The default, `auto`, will use twice the number of available CPU cores " \
"(what our benchmarks showed to produce the best performance). " \
"If set to `1`, Homebrew will download in serial.",
default: "auto",
},
HOMEBREW_EDITOR: {
description: "Use this editor when editing a single formula, or several formulae in the " \
"same directory." \
"\n\n *Note:* `brew edit` will open all of Homebrew as discontinuous files " \
"and directories. Visual Studio Code can handle this correctly in project mode, but many " \
"editors will do strange things in this case.",
default_text: "`$EDITOR` or `$VISUAL`.",
},
HOMEBREW_ENV_SYNC_STRICT: {
description: "If set, `brew *env-sync` will only sync the exact installed versions of formulae.",
boolean: true,
},
HOMEBREW_EVAL_ALL: {
description: "If set, `brew` commands evaluate all formulae and casks, executing their arbitrary code, by " \
"default without requiring `--eval-all`. Required to cache formula and cask descriptions.",
boolean: true,
},
HOMEBREW_FAIL_LOG_LINES: {
description: "Output this many lines of output on formula `system` failures.",
default: 15,
},
HOMEBREW_FORBIDDEN_CASKS: {
description: "A space-separated list of casks. Homebrew will refuse to install a " \
"cask if it or any of its dependencies is on this list.",
},
HOMEBREW_FORBIDDEN_CASK_ARTIFACTS: {
description: "A space-separated list of cask artifact types (e.g. `pkg installer`) that should be " \
"forbidden during cask installation. " \
"Valid values: `pkg`, `installer`, `binary`, `uninstall`, `zap`, `app`, `suite`, " \
"`artifact`, `prefpane`, `qlplugin`, `dictionary`, `font`, `service`, `colorpicker`, " \
"`inputmethod`, `internetplugin`, `audiounitplugin`, `vstplugin`, `vst3plugin`, " \
"`screensaver`, `keyboardlayout`, `mdimporter`, `preflight`, `postflight`, " \
"`manpage`, `bashcompletion`, `fishcompletion`, `zshcompletion`, `stageonly`.",
},
HOMEBREW_FORBIDDEN_FORMULAE: {
description: "A space-separated list of formulae. Homebrew will refuse to install a " \
"formula or cask if it or any of its dependencies is on this list.",
},
HOMEBREW_FORBIDDEN_LICENSES: {
description: "A space-separated list of SPDX license identifiers. Homebrew will refuse to install a " \
"formula if it or any of its dependencies has a license on this list.",
},
HOMEBREW_FORBIDDEN_OWNER: {
description: "The person who has set any `$HOMEBREW_FORBIDDEN_*` variables.",
default: "you",
},
HOMEBREW_FORBIDDEN_OWNER_CONTACT: {
description: "How to contact the `$HOMEBREW_FORBIDDEN_OWNER`, if set and necessary.",
},
HOMEBREW_FORBIDDEN_TAPS: {
description: "A space-separated list of taps. Homebrew will refuse to install a " \
"formula if it or any of its dependencies is in a tap on this list.",
},
HOMEBREW_FORBID_CASKS: {
description: "If set, Homebrew will refuse to install any casks.",
boolean: true,
},
HOMEBREW_FORBID_PACKAGES_FROM_PATHS: {
description: "If set, Homebrew will refuse to read formulae or casks provided from file paths, " \
"e.g. `brew install ./package.rb`.",
boolean: true,
default_text: "true unless `$HOMEBREW_DEVELOPER` is set.",
},
HOMEBREW_FORCE_API_AUTO_UPDATE: {
description: "If set, update the Homebrew API formula or cask data even if " \
"`$HOMEBREW_NO_AUTO_UPDATE` is set.",
boolean: true,
},
HOMEBREW_FORCE_BREWED_CA_CERTIFICATES: {
description: "If set, always use a Homebrew-installed `ca-certificates` rather than the system version. " \
"Automatically set if the system version is too old.",
boolean: true,
},
HOMEBREW_FORCE_BREWED_CURL: {
description: "If set, always use a Homebrew-installed `curl`(1) rather than the system version. " \
"Automatically set if the system version of `curl` is too old.",
boolean: true,
},
HOMEBREW_FORCE_BREWED_GIT: {
description: "If set, always use a Homebrew-installed `git`(1) rather than the system version. " \
"Automatically set if the system version of `git` is too old.",
boolean: true,
},
HOMEBREW_FORCE_BREW_WRAPPER: {
description: "If set, require `brew` to be invoked by the value of " \
"`$HOMEBREW_FORCE_BREW_WRAPPER` for non-trivial `brew` commands.",
},
HOMEBREW_FORCE_VENDOR_RUBY: {
description: "If set, always use Homebrew's vendored, relocatable Ruby version even if the system version " \
"of Ruby is new enough.",
boolean: true,
},
HOMEBREW_FORMULA_BUILD_NETWORK: {
description: "If set, controls network access to the sandbox for formulae builds. Overrides any " \
"controls set through DSL usage inside formulae. Must be `allow` or `deny`. If no value is " \
"set through this environment variable or DSL usage, the default behaviour is `allow`.",
},
HOMEBREW_FORMULA_POSTINSTALL_NETWORK: {
description: "If set, controls network access to the sandbox for formulae postinstall. Overrides any " \
"controls set through DSL usage inside formulae. Must be `allow` or `deny`. If no value is " \
"set through this environment variable or DSL usage, the default behaviour is `allow`.",
},
HOMEBREW_FORMULA_TEST_NETWORK: {
description: "If set, controls network access to the sandbox for formulae test. Overrides any " \
"controls set through DSL usage inside formulae. Must be `allow` or `deny`. If no value is " \
"set through this environment variable or DSL usage, the default behaviour is `allow`.",
},
HOMEBREW_GITHUB_API_TOKEN: {
description: "Use this personal access token for the GitHub API, for features such as " \
"`brew search`. You can create one at <https://github.com/settings/tokens>. If set, " \
"GitHub will allow you a greater number of API requests. For more information, see: " \
"<https://docs.github.com/en/rest/overview/rate-limits-for-the-rest-api>" \
"\n\n *Note:* Homebrew doesn't require permissions for any of the scopes, but some " \
"developer commands may require additional permissions.",
},
HOMEBREW_GITHUB_PACKAGES_TOKEN: {
description: "Use this GitHub personal access token when accessing the GitHub Packages Registry " \
"(where bottles may be stored).",
},
HOMEBREW_GITHUB_PACKAGES_USER: {
description: "Use this username when accessing the GitHub Packages Registry (where bottles may be stored).",
},
HOMEBREW_GIT_COMMITTER_EMAIL: {
description: "Set the Git committer email to this value.",
},
HOMEBREW_GIT_COMMITTER_NAME: {
description: "Set the Git committer name to this value.",
},
HOMEBREW_GIT_EMAIL: {
description: "Set the Git author name and, if `$HOMEBREW_GIT_COMMITTER_EMAIL` is unset, committer email to " \
"this value.",
},
HOMEBREW_GIT_NAME: {
description: "Set the Git author name and, if `$HOMEBREW_GIT_COMMITTER_NAME` is unset, committer name to " \
"this value.",
},
HOMEBREW_GIT_PATH: {
description: "Linux only: Set this value to a new enough `git` executable for Homebrew to use.",
default: "git",
},
HOMEBREW_INSTALL_BADGE: {
description: "Print this text before the installation summary of each successful build.",
default_text: 'The "Beer Mug" emoji.',
default: "🍺",
},
HOMEBREW_LIVECHECK_AUTOBUMP: {
description: "If set, `brew livecheck` will include data for packages that are autobumped by BrewTestBot.",
boolean: true,
},
HOMEBREW_LIVECHECK_WATCHLIST: {
description: "Consult this file for the list of formulae to check by default when no formula argument " \
"is passed to `brew livecheck`.",
default_text: "`${XDG_CONFIG_HOME}/homebrew/livecheck_watchlist.txt` if `$XDG_CONFIG_HOME` is set " \
"or `~/.homebrew/livecheck_watchlist.txt` otherwise.",
default: "#{ENV.fetch("HOMEBREW_USER_CONFIG_HOME")}/livecheck_watchlist.txt",
},
HOMEBREW_LOCK_CONTEXT: {
description: "If set, Homebrew will add this output as additional context for locking errors. " \
"This is useful when running `brew` in the background.",
},
HOMEBREW_LOGS: {
description: "Use this directory to store log files.",
default_text: "macOS: `~/Library/Logs/Homebrew`, " \
"Linux: `${XDG_CACHE_HOME}/Homebrew/Logs` or `~/.cache/Homebrew/Logs`.",
default: HOMEBREW_DEFAULT_LOGS,
},
HOMEBREW_MAKE_JOBS: {
description: "Use this value as the number of parallel jobs to run when building with `make`(1).",
default_text: "The number of available CPU cores.",
default: lambda {
require "os"
require "hardware"
Hardware::CPU.cores
},
},
HOMEBREW_NO_ANALYTICS: {
description: "If set, do not send analytics. Google Analytics were destroyed. " \
"For more information, see: <https://docs.brew.sh/Analytics>",
boolean: true,
},
HOMEBREW_NO_AUTOREMOVE: {
description: "If set, calls to `brew cleanup` and `brew uninstall` will not automatically " \
"remove unused formula dependents.",
boolean: true,
},
HOMEBREW_NO_AUTO_UPDATE: {
description: "If set, do not automatically update before running some commands, e.g. " \
"`brew install`, `brew upgrade` or `brew tap`. Preferably, " \
"run this less often by setting `$HOMEBREW_AUTO_UPDATE_SECS` to a value higher than the " \
"default. Note that setting this and e.g. tapping new taps may result in a broken " \
"configuration. Please ensure you always run `brew update` before reporting any issues.",
boolean: true,
},
HOMEBREW_NO_BOOTSNAP: {
description: "If set, do not use Bootsnap to speed up repeated `brew` calls.",
boolean: true,
},
HOMEBREW_NO_CLEANUP_FORMULAE: {
description: "A comma-separated list of formulae. Homebrew will refuse to clean up " \
"or autoremove a formula if it appears on this list.",
},
HOMEBREW_NO_COLOR: {
description: "If set, do not print text with colour added.",
default_text: "`$NO_COLOR`.",
boolean: true,
},
HOMEBREW_NO_EMOJI: {
description: "If set, do not print `$HOMEBREW_INSTALL_BADGE` on a successful build.",
boolean: true,
},
HOMEBREW_NO_ENV_HINTS: {
description: "If set, do not print any hints about changing Homebrew's behaviour with environment variables.",
boolean: true,
},
HOMEBREW_NO_FORCE_BREW_WRAPPER: {
description: "`Deprecated:` If set, disables `$HOMEBREW_FORCE_BREW_WRAPPER` behaviour, even if set.",
boolean: true,
},
HOMEBREW_NO_GITHUB_API: {
description: "If set, do not use the GitHub API, e.g. for searches or fetching relevant issues " \
"after a failed install.",
boolean: true,
},
HOMEBREW_NO_INSECURE_REDIRECT: {
description: "If set, forbid redirects from secure HTTPS to insecure HTTP." \
"\n\n *Note:* while ensuring your downloads are fully secure, this is likely to cause " \
"sources for certain formulae hosted by SourceForge, GNU or GNOME to fail to download.",
boolean: true,
},
HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK: {
description: "If set, do not check for broken linkage of dependents or outdated dependents after " \
"installing, upgrading or reinstalling formulae. This will result in fewer dependents " \
"(and their dependencies) being upgraded or reinstalled but may result in more breakage " \
"from running `brew install` <formula> or `brew upgrade` <formula>.",
boolean: true,
},
HOMEBREW_NO_INSTALL_CLEANUP: {
description: "If set, `brew install`, `brew upgrade` and `brew reinstall` will never automatically " \
"cleanup installed/upgraded/reinstalled formulae or all formulae every " \
"`$HOMEBREW_CLEANUP_PERIODIC_FULL_DAYS` days. Alternatively, `$HOMEBREW_NO_CLEANUP_FORMULAE` " \
"allows specifying specific formulae to not clean up.",
boolean: true,
},
HOMEBREW_NO_INSTALL_FROM_API: {
description: "If set, do not install formulae and casks in homebrew/core and homebrew/cask taps using " \
"Homebrew's API and instead use (large, slow) local checkouts of these repositories.",
boolean: true,
},
HOMEBREW_NO_INSTALL_UPGRADE: {
description: "If set, `brew install` <formula|cask> will not upgrade <formula|cask> if it is installed but " \
"outdated.",
boolean: true,
},
HOMEBREW_NO_UPDATE_REPORT_NEW: {
description: "If set, `brew update` will not show the list of newly added formulae/casks.",
boolean: true,
},
HOMEBREW_NO_VERIFY_ATTESTATIONS: {
description: "If set, Homebrew will not verify cryptographic attestations of build provenance for bottles " \
"from homebrew-core.",
boolean: true,
},
HOMEBREW_PIP_INDEX_URL: {
description: "If set, `brew install` <formula> will use this URL to download PyPI package resources.",
default_text: "`https://pypi.org/simple`.",
},
HOMEBREW_PRY: {
description: "If set, use Pry for the `brew irb` command.",
boolean: true,
},
HOMEBREW_SIMULATE_MACOS_ON_LINUX: {
description: "If set, running Homebrew on Linux will simulate certain macOS code paths. This is useful " \
"when auditing macOS formulae while on Linux.",
boolean: true,
},
HOMEBREW_SKIP_OR_LATER_BOTTLES: {
description: "If set along with `$HOMEBREW_DEVELOPER`, do not use bottles from older versions " \
"of macOS. This is useful in development on new macOS versions.",
boolean: true,
},
HOMEBREW_SORBET_RECURSIVE: {
description: "If set along with `$HOMEBREW_SORBET_RUNTIME`, enable recursive typechecking using Sorbet. " \
"Auomatically enabled when running tests.",
boolean: true,
},
HOMEBREW_SORBET_RUNTIME: {
description: "If set, enable runtime typechecking using Sorbet. " \
"Set by default for `$HOMEBREW_DEVELOPER` or when running some developer commands.",
boolean: true,
},
HOMEBREW_SSH_CONFIG_PATH: {
description: "If set, Homebrew will use the given config file instead of `~/.ssh/config` when " \
"fetching Git repositories over SSH.",
default_text: "`~/.ssh/config`",
},
HOMEBREW_SUDO_THROUGH_SUDO_USER: {
description: "If set, Homebrew will use the `$SUDO_USER` environment variable to define the user to " \
"`sudo`(8) through when running `sudo`(8).",
boolean: true,
},
HOMEBREW_SVN: {
description: "Use this as the `svn`(1) binary.",
default_text: "A Homebrew-built Subversion (if installed), or the system-provided binary.",
},
HOMEBREW_SYSTEM_ENV_TAKES_PRIORITY: {
description: "If set in Homebrew's system-wide environment file (`/etc/homebrew/brew.env`), " \
"the system-wide environment file will be loaded last to override any prefix or user settings.",
boolean: true,
},
HOMEBREW_TEMP: {
description: "Use this path as the temporary directory for building packages. Changing " \
"this may be needed if your system temporary directory and Homebrew prefix are on " \
"different volumes, as macOS has trouble moving symlinks across volumes when the target " \
"does not yet exist. This issue typically occurs when using FileVault or custom SSD " \
"configurations.",
default_text: "macOS: `/private/tmp`, Linux: `/var/tmp`.",
default: HOMEBREW_DEFAULT_TEMP,
},
HOMEBREW_UPDATE_TO_TAG: {
description: "If set, always use the latest stable tag (even if developer commands " \
"have been run).",
boolean: true,
},
HOMEBREW_UPGRADE_GREEDY: {
description: "If set, pass `--greedy` to all cask upgrade commands.",
boolean: true,
},
HOMEBREW_UPGRADE_GREEDY_CASKS: {
description: "A space-separated list of casks. Homebrew will act as " \
"if `--greedy` was passed when upgrading any cask on this list.",
},
HOMEBREW_USE_INTERNAL_API: {
description: "If set, test the new beta internal API for fetching formula and cask data.",
boolean: true,
},
HOMEBREW_VERBOSE: {
description: "If set, always assume `--verbose` when running commands.",
boolean: true,
},
HOMEBREW_VERBOSE_USING_DOTS: {
description: "If set, verbose output will print a `.` no more than once a minute. This can be " \
"useful to avoid long-running Homebrew commands being killed due to no output.",
boolean: true,
},
HOMEBREW_VERIFY_ATTESTATIONS: {
description: "If set, Homebrew will use the `gh` tool to verify cryptographic attestations " \
"of build provenance for bottles from homebrew-core.",
boolean: true,
},
SUDO_ASKPASS: {
description: "If set, pass the `-A` option when calling `sudo`(8).",
},
all_proxy: {
description: "Use this SOCKS5 proxy for `curl`(1), `git`(1) and `svn`(1) when downloading through Homebrew.",
},
ftp_proxy: {
description: "Use this FTP proxy for `curl`(1), `git`(1) and `svn`(1) when downloading through Homebrew.",
},
http_proxy: {
description: "Use this HTTP proxy for `curl`(1), `git`(1) and `svn`(1) when downloading through Homebrew.",
},
https_proxy: {
description: "Use this HTTPS proxy for `curl`(1), `git`(1) and `svn`(1) when downloading through Homebrew.",
},
no_proxy: {
description: "A comma-separated list of hostnames and domain names excluded " \
"from proxying by `curl`(1), `git`(1) and `svn`(1) when downloading through Homebrew.",
},
}.freeze, T::Hash[Symbol, T::Hash[Symbol, T.untyped]])
sig { params(env: Symbol, hash: T::Hash[Symbol, T.untyped]).returns(String) }
def env_method_name(env, hash)
method_name = env.to_s
.sub(/^HOMEBREW_/, "")
.downcase
method_name = "#{method_name}?" if hash[:boolean]
method_name
end
CUSTOM_IMPLEMENTATIONS = T.let(Set.new([
:HOMEBREW_MAKE_JOBS,
:HOMEBREW_CASK_OPTS,
:HOMEBREW_FORBID_PACKAGES_FROM_PATHS,
:HOMEBREW_DOWNLOAD_CONCURRENCY,
:HOMEBREW_USE_INTERNAL_API,
]).freeze, T::Set[Symbol])
FALSY_VALUES = T.let(%w[false no off nil 0].freeze, T::Array[String])
ENVS.each do |env, hash|
# Needs a custom implementation.
next if CUSTOM_IMPLEMENTATIONS.include?(env)
method_name = env_method_name(env, hash)
env = env.to_s
if hash[:boolean]
define_method(method_name) do
env_value = ENV.fetch(env, nil)
env_value.present? && FALSY_VALUES.exclude?(env_value.downcase)
end
elsif hash[:default].present?
define_method(method_name) do
ENV[env].presence || hash.fetch(:default).to_s
end
else
define_method(method_name) do
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/head_software_spec.rb | Library/Homebrew/head_software_spec.rb | # typed: strict
# frozen_string_literal: true
require "software_spec"
class HeadSoftwareSpec < SoftwareSpec
sig { params(flags: T::Array[String]).void }
def initialize(flags: [])
super
@resource.version(Version.new("HEAD"))
end
sig { params(_filename: Pathname).returns(NilClass) }
def verify_download_integrity(_filename)
# no-op
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/mktemp.rb | Library/Homebrew/mktemp.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
# Performs {Formula#mktemp}'s functionality and tracks the results.
# Each instance is only intended to be used once.
# Can also be used to create a temporary directory with the brew instance's group.
class Mktemp
include Utils::Output::Mixin
# Path to the tmpdir used in this run
sig { returns(T.nilable(Pathname)) }
attr_reader :tmpdir
sig { params(prefix: String, retain: T::Boolean, retain_in_cache: T::Boolean).void }
def initialize(prefix, retain: false, retain_in_cache: false)
@prefix = prefix
@retain_in_cache = retain_in_cache
@retain = T.let(retain || @retain_in_cache, T::Boolean)
@quiet = T.let(false, T::Boolean)
@tmpdir = T.let(nil, T.nilable(Pathname))
end
# Instructs this {Mktemp} to retain the staged files.
sig { void }
def retain!
@retain = true
end
# True if the staged temporary files should be retained.
sig { returns(T::Boolean) }
def retain?
@retain
end
# True if the source files should be retained.
sig { returns(T::Boolean) }
def retain_in_cache?
@retain_in_cache
end
# Instructs this Mktemp to not emit messages when retention is triggered.
sig { void }
def quiet!
@quiet = true
end
sig { returns(String) }
def to_s
"[Mktemp: #{tmpdir} retain=#{@retain} quiet=#{@quiet}]"
end
sig {
type_parameters(:U).params(
chdir: T::Boolean,
_block: T.proc.params(arg0: Mktemp).returns(T.type_parameter(:U)),
).returns(T.type_parameter(:U))
}
def run(chdir: true, &_block)
prefix_name = @prefix.tr "@", "AT"
@tmpdir = if retain_in_cache?
tmp_dir = HOMEBREW_CACHE/"Sources/#{prefix_name}"
chmod_rm_rf(tmp_dir) # clear out previous staging directory
tmp_dir.mkpath
tmp_dir
else
Pathname.new(Dir.mktmpdir("#{prefix_name}-", HOMEBREW_TEMP))
end
# Make sure files inside the temporary directory have the same group as the
# brew instance.
#
# Reference from `man 2 open`
# > When a new file is created, it is given the group of the directory which
# contains it.
group_id = if HOMEBREW_ORIGINAL_BREW_FILE.grpowned?
HOMEBREW_ORIGINAL_BREW_FILE.stat.gid
else
Process.gid
end
begin
@tmpdir.chown(nil, group_id)
rescue Errno::EPERM
require "etc"
group_name = begin
Etc.getgrgid(group_id)&.name
rescue ArgumentError
# Cover for misconfigured NSS setups
nil
end
opoo "Failed setting group \"#{group_name || group_id}\" on #{@tmpdir}"
end
begin
if chdir
Dir.chdir(@tmpdir) { yield self }
else
yield self
end
ensure
ignore_interrupts { chmod_rm_rf(@tmpdir) } unless retain?
end
ensure
if retain? && @tmpdir.present? && !@quiet
message = retain_in_cache? ? "Source files for debugging available at:" : "Temporary files retained at:"
ohai message, @tmpdir.to_s
end
end
private
sig { params(path: Pathname).void }
def chmod_rm_rf(path)
if path.directory? && !path.symlink?
FileUtils.chmod("u+rw", path) if path.owned? # Need permissions in order to see the contents
path.children.each { |child| chmod_rm_rf(child) }
FileUtils.rmdir(path)
else
FileUtils.rm_f(path)
end
rescue
nil # Just skip this directory.
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_bot/test.rb | Library/Homebrew/test_bot/test.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "utils/analytics"
require "utils/output"
module Homebrew
module TestBot
class Test
include Utils::Output::Mixin
def failed_steps
@steps.select(&:failed?)
end
def ignored_steps
@steps.select(&:ignored?)
end
attr_reader :steps
protected
def cleanup?(args)
Homebrew::TestBot.cleanup?(args)
end
def local?(args)
Homebrew::TestBot.local?(args)
end
private
attr_reader :tap, :git, :repository
def initialize(tap: nil, git: nil, dry_run: false, fail_fast: false, verbose: false)
@tap = tap
@git = git
@dry_run = dry_run
@fail_fast = fail_fast
@verbose = verbose
@steps = []
@repository = if @tap
@tap.path
else
CoreTap.instance.path
end
end
def test_header(klass, method: "run!")
puts
puts Formatter.headline("Running #{klass}##{method}", color: :magenta)
end
def info_header(text)
puts Formatter.headline(text, color: :cyan)
end
def test(*arguments, named_args: nil, env: {}, verbose: @verbose, ignore_failures: false,
report_analytics: false)
step = Step.new(
arguments,
named_args:,
env:,
verbose:,
ignore_failures:,
repository: @repository,
)
step.run(dry_run: @dry_run, fail_fast: @fail_fast)
@steps << step
if ENV["HOMEBREW_TEST_BOT_ANALYTICS"].present? && report_analytics
::Utils::Analytics.report_test_bot_test(step.command_short, step.passed?)
end
step
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/test_bot/cleanup_after.rb | Library/Homebrew/test_bot/cleanup_after.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class CleanupAfter < TestCleanup
def run!(args:)
if ENV["HOMEBREW_GITHUB_ACTIONS"].present? && ENV["GITHUB_ACTIONS_HOMEBREW_SELF_HOSTED"].blank? &&
# don't need to do post-build cleanup unless testing test-bot itself.
!args.test_default_formula?
return
end
test_header(:CleanupAfter)
pkill_if_needed
cleanup_shared
# Keep all "brew" invocations after cleanup_shared
# (which cleans up Homebrew/brew)
return unless local?(args)
FileUtils.rm_rf ENV.fetch("HOMEBREW_HOME")
FileUtils.rm_rf ENV.fetch("HOMEBREW_LOGS")
end
private
def pkill_if_needed
pgrep = ["pgrep", "-f", HOMEBREW_CELLAR.to_s]
return unless quiet_system(*pgrep)
test "pkill", "-f", HOMEBREW_CELLAR.to_s
return unless quiet_system(*pgrep)
sleep 1
test "pkill", "-9", "-f", HOMEBREW_CELLAR.to_s if system(*pgrep)
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/test_bot/setup.rb | Library/Homebrew/test_bot/setup.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class Setup < Test
def run!(args:)
test_header(:Setup)
test "brew", "install-bundler-gems", "--add-groups=ast,audit,bottle,formula_test,livecheck,style"
# Always output `brew config` output even when it doesn't fail.
test "brew", "config", verbose: true
if ENV["HOMEBREW_TEST_BOT_VERBOSE_DOCTOR"]
test "brew", "doctor", "--debug", verbose: true
else
test "brew", "doctor"
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/test_bot/tap_syntax.rb | Library/Homebrew/test_bot/tap_syntax.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class TapSyntax < Test
def run!(args:)
test_header(:TapSyntax)
return unless tap.installed?
unless args.stable?
# Run `brew typecheck` if this tap is typed.
# TODO: consider in future if we want to allow unsupported taps here.
if tap.official? && quiet_system(git, "-C", tap.path.to_s, "grep", "-qE",
"^# typed: (true|strict|strong)$")
test "brew", "typecheck", tap.name
end
test "brew", "style", tap.name
end
return if tap.formula_files.blank? && tap.cask_files.blank?
test "brew", "readall", "--aliases", "--os=all", "--arch=all", tap.name
return if args.stable?
test "brew", "audit", "--except=installed", "--tap=#{tap.name}"
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/test_bot/formulae_detect.rb | Library/Homebrew/test_bot/formulae_detect.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class FormulaeDetect < Test
attr_reader :testing_formulae, :added_formulae, :deleted_formulae
def initialize(argument, tap:, git:, dry_run:, fail_fast:, verbose:)
super(tap:, git:, dry_run:, fail_fast:, verbose:)
@argument = argument
@added_formulae = []
@deleted_formulae = []
@formulae_to_fetch = []
end
def run!(args:)
detect_formulae!(args:)
return unless GitHub::Actions.env_set?
File.open(ENV.fetch("GITHUB_OUTPUT"), "a") do |f|
f.puts "testing_formulae=#{@testing_formulae.join(",")}"
f.puts "added_formulae=#{@added_formulae.join(",")}"
f.puts "deleted_formulae=#{@deleted_formulae.join(",")}"
f.puts "formulae_to_fetch=#{@formulae_to_fetch.join(",")}"
end
end
private
def detect_formulae!(args:)
test_header(:FormulaeDetect, method: :detect_formulae!)
url = nil
origin_ref = "origin/main"
github_repository = ENV.fetch("GITHUB_REPOSITORY", nil)
github_ref = ENV.fetch("GITHUB_REF", nil)
if @argument == "HEAD"
@testing_formulae = []
# Use GitHub Actions variables for pull request jobs.
if github_ref.present? && github_repository.present? &&
%r{refs/pull/(\d+)/merge} =~ github_ref
url = "https://github.com/#{github_repository}/pull/#{Regexp.last_match(1)}/checks"
end
elsif (canonical_formula_name = safe_formula_canonical_name(@argument, args:))
unless canonical_formula_name.include?("/")
ENV["HOMEBREW_NO_INSTALL_FROM_API"] = "1"
CoreTap.instance.ensure_installed!
end
@testing_formulae = [canonical_formula_name]
else
raise UsageError,
"#{@argument} is not detected from GitHub Actions or a formula name!"
end
github_sha = ENV.fetch("GITHUB_SHA", nil)
if github_repository.blank? || github_sha.blank? || github_ref.blank?
if GitHub::Actions.env_set?
odie <<~EOS
We cannot find the needed GitHub Actions environment variables! Check you have e.g. exported them to a Docker container.
EOS
elsif ENV["CI"]
onoe <<~EOS
No known CI provider detected! If you are using GitHub Actions then we cannot find the expected environment variables! Check you have e.g. exported them to a Docker container.
EOS
end
elsif tap.present? && tap.full_name.casecmp(github_repository).zero?
# Use GitHub Actions variables for pull request jobs.
if (base_ref = ENV.fetch("GITHUB_BASE_REF", nil)).present?
unless tap.official?
test git, "-C", repository, "fetch",
"origin", "+refs/heads/#{base_ref}"
end
origin_ref = "origin/#{base_ref}"
diff_start_sha1 = rev_parse(origin_ref)
diff_end_sha1 = github_sha
# Use GitHub Actions variables for merge group jobs.
elsif ENV.fetch("GITHUB_EVENT_NAME", nil) == "merge_group"
diff_start_sha1 = rev_parse(origin_ref)
origin_ref = "origin/#{github_ref.gsub(%r{^refs/heads/}, "")}"
diff_end_sha1 = github_sha
# Use GitHub Actions variables for branch jobs.
else
test git, "-C", repository, "fetch", "origin", "+#{github_ref}" unless tap.official?
origin_ref = "origin/#{github_ref.gsub(%r{^refs/heads/}, "")}"
diff_end_sha1 = diff_start_sha1 = github_sha
end
end
if diff_start_sha1.present? && diff_end_sha1.present?
merge_base_sha1 =
Utils.safe_popen_read(git, "-C", repository, "merge-base",
diff_start_sha1, diff_end_sha1).strip
diff_start_sha1 = merge_base_sha1 if merge_base_sha1.present?
end
diff_start_sha1 = current_sha1 if diff_start_sha1.blank?
diff_end_sha1 = current_sha1 if diff_end_sha1.blank?
diff_start_sha1 = diff_end_sha1 if @testing_formulae.present?
if tap
tap_origin_ref_revision_args =
[git, "-C", tap.path.to_s, "log", "-1", "--format=%h (%s)", origin_ref]
tap_origin_ref_revision = if args.dry_run?
# May fail on dry run as we've not fetched.
Utils.popen_read(*tap_origin_ref_revision_args).strip
else
Utils.safe_popen_read(*tap_origin_ref_revision_args)
end.strip
tap_revision = Utils.safe_popen_read(
git, "-C", tap.path.to_s,
"log", "-1", "--format=%h (%s)"
).strip
end
puts <<-EOS
url #{url.presence || "(blank)"}
tap #{origin_ref} #{tap_origin_ref_revision.presence || "(blank)"}
HEAD #{tap_revision.presence || "(blank)"}
diff_start_sha1 #{diff_start_sha1.presence || "(blank)"}
diff_end_sha1 #{diff_end_sha1.presence || "(blank)"}
EOS
modified_formulae = []
if tap && diff_start_sha1 != diff_end_sha1
formula_path = tap.formula_dir.to_s
@added_formulae +=
diff_formulae(diff_start_sha1, diff_end_sha1, formula_path, "A")
modified_formulae +=
diff_formulae(diff_start_sha1, diff_end_sha1, formula_path, "M")
@deleted_formulae +=
diff_formulae(diff_start_sha1, diff_end_sha1, formula_path, "D")
end
# If a formula is both added and deleted: it's actually modified.
added_and_deleted_formulae = @added_formulae & @deleted_formulae
@added_formulae -= added_and_deleted_formulae
@deleted_formulae -= added_and_deleted_formulae
modified_formulae += added_and_deleted_formulae
if args.test_default_formula?
# Build the default test formulae.
modified_formulae << "libfaketime" << "xz"
elsif @added_formulae.present? &&
@added_formulae.all? { |formula| formula.start_with?("portable-") }
@added_formulae = ["portable-ruby"]
elsif modified_formulae.present? &&
modified_formulae.all? { |formula| formula.start_with?("portable-") }
modified_formulae = ["portable-ruby"]
elsif modified_formulae.any? { |formula| formula.start_with?("portable-") }
odie "Portable Ruby (and related formulae) cannot be tested in the same job as other formulae!"
end
@testing_formulae += @added_formulae + modified_formulae
# TODO: Remove `GITHUB_EVENT_NAME` check when formulae detection
# is fixed for branch jobs.
if @testing_formulae.blank? &&
@deleted_formulae.blank? &&
diff_start_sha1 == diff_end_sha1 &&
(ENV["GITHUB_EVENT_NAME"] != "push")
raise UsageError, "Did not find any formulae or commits to test!"
end
# Remove all duplicates.
@testing_formulae.uniq!
@added_formulae.uniq!
modified_formulae.uniq!
@deleted_formulae.uniq!
# We only need to do a fetch test on formulae that have had a change in the pkg version or bottle block.
# These fetch tests only happen in merge queues.
@formulae_to_fetch = if diff_start_sha1 == diff_end_sha1 || ENV["GITHUB_EVENT_NAME"] != "merge_group"
[]
else
require "formula_versions"
@testing_formulae.reject do |formula_name|
latest_formula = Formula[formula_name]
# nil = formula not found, false = bottles changed, true = bottles not changed
equal_bottles = FormulaVersions.new(latest_formula).formula_at_revision(diff_start_sha1) do |old_formula|
old_formula.pkg_version == latest_formula.pkg_version &&
old_formula.bottle_specification == latest_formula.bottle_specification
end
equal_bottles # only exclude the true case (bottles not changed)
end
end
puts <<-EOS
testing_formulae #{@testing_formulae.join(" ").presence || "(none)"}
added_formulae #{@added_formulae.join(" ").presence || "(none)"}
modified_formulae #{modified_formulae.join(" ").presence || "(none)"}
deleted_formulae #{@deleted_formulae.join(" ").presence || "(none)"}
formulae_to_fetch #{@formulae_to_fetch.join(" ").presence || "(none)"}
EOS
end
def safe_formula_canonical_name(formula_name, args:)
Homebrew.with_no_api_env do
Formulary.factory(formula_name).full_name
end
rescue TapFormulaUnavailableError => e
raise if e.tap.installed?
test "brew", "tap", e.tap.name
retry unless steps.last.failed?
onoe e
puts e.backtrace if args.debug?
rescue FormulaUnavailableError, TapFormulaAmbiguityError => e
onoe e
puts e.backtrace if args.debug?
end
def rev_parse(ref)
Utils.popen_read(git, "-C", repository, "rev-parse", "--verify", ref).strip
end
def current_sha1
rev_parse("HEAD")
end
def diff_formulae(start_revision, end_revision, path, filter)
return unless tap
Utils.safe_popen_read(
git, "-C", repository,
"diff-tree", "-r", "--name-only", "--diff-filter=#{filter}",
start_revision, end_revision, "--", path
).lines(chomp: true).filter_map do |file|
next unless tap.formula_file?(file)
file = Pathname.new(file)
tap.formula_file_to_name(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/test_bot/test_cleanup.rb | Library/Homebrew/test_bot/test_cleanup.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "os"
require "tap"
module Homebrew
module TestBot
class TestCleanup < Test
protected
ALLOWED_TAPS = [
CoreTap.instance.name,
CoreCaskTap.instance.name,
].freeze
def reset_if_needed(repository)
default_ref = default_origin_ref(repository)
return if system(git, "-C", repository, "diff", "--quiet", default_ref)
test git, "-C", repository, "reset", "--hard", default_ref
end
# Moving files is faster than removing them,
# so move them if the current runner is ephemeral.
def delete_or_move(paths, sudo: false)
return if paths.blank?
symlinks, paths = paths.partition(&:symlink?)
FileUtils.rm_f symlinks
return if ENV["HOMEBREW_GITHUB_ACTIONS"].blank?
paths.select!(&:exist?)
return if paths.blank?
if ENV["GITHUB_ACTIONS_HOMEBREW_SELF_HOSTED"].present?
if sudo
test "sudo", "rm", "-rf", *paths
else
FileUtils.rm_rf paths
end
else
paths.each do |path|
if sudo
test "sudo", "mv", path, Dir.mktmpdir
else
FileUtils.mv path, Dir.mktmpdir, force: true
end
end
end
end
def cleanup_shared
FileUtils.chmod_R("u+X", HOMEBREW_CELLAR, force: true)
if repository.exist?
cleanup_git_meta(repository)
clean_if_needed(repository)
prune_if_needed(repository)
end
if HOMEBREW_REPOSITORY != HOMEBREW_PREFIX
paths_to_delete = []
info_header "Determining #{HOMEBREW_PREFIX} files to purge..."
Keg.must_be_writable_directories.each(&:mkpath)
Pathname.glob("#{HOMEBREW_PREFIX}/**/*", File::FNM_DOTMATCH).each do |path|
next if Keg.must_be_writable_directories.include?(path)
next if path == HOMEBREW_PREFIX/"bin/brew"
next if path == HOMEBREW_PREFIX/"var"
next if path == HOMEBREW_PREFIX/"var/homebrew"
basename = path.basename.to_s
next if basename == "."
next if basename == ".keepme"
path_string = path.to_s
next if path_string.start_with?(HOMEBREW_REPOSITORY.to_s)
next if path_string.start_with?(Dir.pwd.to_s)
# allow deleting non-existent osxfuse symlinks.
if (!path.symlink? || path.resolved_path_exists?) &&
# don't try to delete other osxfuse files
path_string.match?("(include|lib)/(lib|osxfuse/|pkgconfig/)?(osx|mac)?fuse(.*.(dylib|h|la|pc))?$")
next
end
FileUtils.chmod("u+rw", path) if path.owned? && (!path.readable? || !path.writable?)
paths_to_delete << path
end
# Do this in a second pass so that all children have their permissions fixed before we delete the parent.
info_header "Purging..."
delete_or_move paths_to_delete
end
if tap
checkout_branch_if_needed(HOMEBREW_REPOSITORY)
reset_if_needed(HOMEBREW_REPOSITORY)
clean_if_needed(HOMEBREW_REPOSITORY)
end
# Keep all "brew" invocations after HOMEBREW_REPOSITORY operations
# (which cleans up Homebrew/brew)
taps_to_remove = Tap.map do |t|
next if t.name == tap&.name
next if ALLOWED_TAPS.include?(t.name)
t.path
end.uniq.compact
delete_or_move taps_to_remove
Pathname.glob("#{HOMEBREW_LIBRARY}/Taps/*/*").each do |git_repo|
cleanup_git_meta(git_repo)
next if repository == git_repo
checkout_branch_if_needed(git_repo)
reset_if_needed(git_repo)
clean_if_needed(git_repo)
prune_if_needed(git_repo)
end
# don't need to do `brew cleanup` unless we're self-hosted.
return if ENV["HOMEBREW_GITHUB_ACTIONS"] && !ENV["GITHUB_ACTIONS_HOMEBREW_SELF_HOSTED"]
test "brew", "cleanup", "--prune=3"
end
private
def default_origin_ref(repository)
default_branch = Utils.popen_read(
git, "-C", repository, "symbolic-ref", "refs/remotes/origin/HEAD", "--short"
).strip.presence
default_branch ||= "origin/main"
default_branch
end
def checkout_branch_if_needed(repository)
# We limit this to two parts, because branch names can have slashes in
default_branch = default_origin_ref(repository).split("/", 2).last
current_branch = Utils.safe_popen_read(
git, "-C", repository, "symbolic-ref", "HEAD", "--short"
).strip
return if default_branch == current_branch
test git, "-C", repository, "checkout", "-f", default_branch
end
def cleanup_git_meta(repository)
pr_locks = "#{repository}/.git/refs/remotes/*/pr/*/*.lock"
Dir.glob(pr_locks) { |lock| FileUtils.rm_f lock }
FileUtils.rm_f "#{repository}/.git/gc.log"
end
def clean_if_needed(repository)
return if repository == HOMEBREW_PREFIX && HOMEBREW_PREFIX != HOMEBREW_REPOSITORY
clean_args = [
"-dx",
"--exclude=/*.bottle*.*",
"--exclude=/Library/Taps",
"--exclude=/Library/Homebrew/vendor",
]
return if Utils.safe_popen_read(
git, "-C", repository, "clean", "--dry-run", *clean_args
).strip.empty?
test git, "-C", repository, "clean", "-ff", *clean_args
end
def prune_if_needed(repository)
return unless Utils.safe_popen_read(
"#{git} -C '#{repository}' -c gc.autoDetach=false gc --auto 2>&1",
).include?("git prune")
test git, "-C", repository, "prune"
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/test_bot/step.rb | Library/Homebrew/test_bot/step.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "system_command"
require "utils/github/actions"
module Homebrew
module TestBot
# Wraps command invocations. Instantiated by Test#test.
# Handles logging and pretty-printing.
class Step
include SystemCommand::Mixin
attr_reader :command, :name, :status, :output, :start_time, :end_time
# Instantiates a Step object.
# @param command [Array<String>] Command to execute and arguments.
# @param env [Hash] Environment variables to set when running command.
def initialize(command, env:, verbose:, named_args: nil, ignore_failures: false, repository: nil)
@named_args = [named_args].flatten.compact.map(&:to_s)
@command = command + @named_args
@env = env
@verbose = verbose
@ignore_failures = ignore_failures
@repository = repository
@name = command[1]&.delete("-")
@status = :running
@output = nil
end
def command_trimmed
command.reject { |arg| arg.to_s.start_with?("--exclude") }
.join(" ")
.delete_prefix("#{HOMEBREW_LIBRARY}/Taps/")
.delete_prefix("#{HOMEBREW_PREFIX}/")
.delete_prefix("/usr/bin/")
end
def command_short
(@command - %W[
brew
-C
#{HOMEBREW_PREFIX}
#{HOMEBREW_REPOSITORY}
#{@repository}
#{Dir.pwd}
--force
--retry
--verbose
--json
].freeze).join(" ")
.gsub(HOMEBREW_PREFIX.to_s, "")
.gsub(HOMEBREW_REPOSITORY.to_s, "")
.gsub(@repository.to_s, "")
.gsub(Dir.pwd, "")
end
def passed?
@status == :passed
end
def failed?
@status == :failed
end
def ignored?
@status == :ignored
end
def puts_command
puts Formatter.headline(command_trimmed, color: :blue)
end
def puts_result
puts Formatter.headline(Formatter.error("FAILED"), color: :red) unless passed?
end
def puts_github_actions_annotation(message, title, file, line)
return unless GitHub::Actions.env_set?
type = if passed?
:notice
elsif ignored?
:warning
else
:error
end
annotation = GitHub::Actions::Annotation.new(type, message, title:, file:, line:)
puts annotation
end
def puts_in_github_actions_group(title)
puts "::group::#{title}" if GitHub::Actions.env_set?
yield
puts "::endgroup::" if GitHub::Actions.env_set?
end
def output?
@output.present?
end
# The execution time of the task.
# Precondition: Step#run has been called.
# @return [Float] execution time in seconds
def time
end_time - start_time
end
def puts_full_output
return if @output.blank? || @verbose
puts_in_github_actions_group("Full #{command_short} output") do
puts @output
end
end
def annotation_location(name)
formula = Formulary.factory(name)
method_sym = command.second.to_sym
method_location = formula.method(method_sym).source_location if formula.respond_to?(method_sym)
if method_location.present? && (method_location.first == formula.path.to_s)
method_location
else
[formula.path, nil]
end
rescue FormulaUnavailableError
[@repository.glob("**/#{name}*").first, nil]
end
def truncate_output(output, max_kb:, context_lines:)
output_lines = output.lines
first_error_index = output_lines.find_index do |line|
!line.strip.match?(/^::error( .*)?::/) &&
(line.match?(/\berror:\s+/i) || line.match?(/\bcmake error\b/i))
end
if first_error_index.blank?
output = []
# Collect up to max_kb worth of the last lines of output.
output_lines.reverse_each do |line|
# Check output.present? so that we at least have _some_ output.
break if line.length + output.join.length > max_kb && output.present?
output.unshift line
end
output.join
else
start = [first_error_index - context_lines, 0].max
# Let GitHub Actions truncate us to 4KB if needed.
output_lines[start..].join
end
end
def run(dry_run: false, fail_fast: false)
@start_time = Time.now
puts_command
if dry_run
@status = :passed
puts_result
return
end
raise "git should always be called with -C!" if command[0] == "git" && %w[-C clone].exclude?(command[1])
executable, *args = command
result = system_command executable, args:,
print_stdout: @verbose,
print_stderr: @verbose,
env: @env
@end_time = Time.now
@status = if result.success?
:passed
elsif @ignore_failures
:ignored
else
:failed
end
puts_result
output = result.merged_output
# ActiveSupport can barf on some Unicode so don't use .present?
if output.empty?
puts if @verbose
exit 1 if fail_fast && failed?
return
end
output.force_encoding(Encoding::UTF_8)
@output = if output.valid_encoding?
output
else
output.encode!(Encoding::UTF_16, invalid: :replace)
output.encode!(Encoding::UTF_8)
end
return if passed?
puts_full_output
unless GitHub::Actions.env_set?
puts
exit 1 if fail_fast && failed?
return
end
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
os_string = if OS.mac?
str = "macOS #{MacOS.version.pretty_name} (#{MacOS.version})"
str << " on Apple Silicon" if Hardware::CPU.arm?
str
else
"#{OS.kernel_name} #{Hardware::CPU.arch}"
end
# rubocop:enable Homebrew/MoveToExtendOS
@named_args.each do |name|
next if name.blank?
path, line = annotation_location(name)
next if path.blank?
# GitHub Actions has a 4KB maximum for annotations.
annotation_output = truncate_output(@output, max_kb: 4, context_lines: 5)
annotation_title = "`#{command_trimmed}` failed on #{os_string}!"
file = path.to_s.delete_prefix("#{@repository}/")
puts_in_github_actions_group("Truncated #{command_short} output") do
puts_github_actions_annotation(annotation_output, annotation_title, file, line)
end
end
exit 1 if fail_fast && failed?
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/test_bot/test_runner.rb | Library/Homebrew/test_bot/test_runner.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "test_bot/junit"
require "test_bot/test"
require "test_bot/test_cleanup"
require "test_bot/test_formulae"
require "test_bot/cleanup_after"
require "test_bot/cleanup_before"
require "test_bot/formulae_detect"
require "test_bot/formulae_dependents"
require "test_bot/bottles_fetch"
require "test_bot/formulae"
require "test_bot/setup"
require "test_bot/tap_syntax"
module Homebrew
module TestBot
module TestRunner
module_function
def ensure_blank_file_exists!(file)
if file.exist?
file.truncate(0)
else
FileUtils.touch(file)
end
end
def run!(tap, git:, args:)
tests = T.let([], T::Array[Test])
skip_setup = args.skip_setup?
skip_cleanup_before = T.let(false, T::Boolean)
bottle_output_path = Pathname.new("bottle_output.txt")
linkage_output_path = Pathname.new("linkage_output.txt")
@skipped_or_failed_formulae_output_path = Pathname.new("skipped_or_failed_formulae-#{Utils::Bottles.tag}.txt")
if no_only_args?(args) || args.only_formulae?
ensure_blank_file_exists!(bottle_output_path)
ensure_blank_file_exists!(linkage_output_path)
ensure_blank_file_exists!(@skipped_or_failed_formulae_output_path)
end
output_paths = {
bottle: bottle_output_path,
linkage: linkage_output_path,
skipped_or_failed_formulae: @skipped_or_failed_formulae_output_path,
}
test_bot_args = args.named.dup
# With no arguments just build the most recent commit.
test_bot_args << "HEAD" if test_bot_args.empty?
test_bot_args.each do |argument|
skip_cleanup_after = argument != test_bot_args.last
current_tests = build_tests(argument, tap:,
git:,
output_paths:,
skip_setup:,
skip_cleanup_before:,
skip_cleanup_after:,
args:)
skip_setup = true
skip_cleanup_before = true
tests += current_tests.values
run_tests(current_tests, args:)
end
failed_steps = tests.map(&:failed_steps)
.flatten
.compact
ignored_steps = tests.map(&:ignored_steps)
.flatten
.compact
steps_output = if failed_steps.blank? && ignored_steps.blank?
"All steps passed!"
else
output_lines = []
if ignored_steps.present?
output_lines += ["Warning: #{ignored_steps.count} failed step#{"s" if ignored_steps.count > 1} ignored!"]
output_lines += ignored_steps.map(&:command_trimmed)
end
if failed_steps.present?
output_lines += ["Error: #{failed_steps.count} failed step#{"s" if failed_steps.count > 1}!"]
output_lines += failed_steps.map(&:command_trimmed)
end
output_lines.join("\n")
end
puts steps_output
steps_output_path = Pathname.new("steps_output.txt")
steps_output_path.unlink if steps_output_path.exist?
steps_output_path.write(steps_output)
if args.junit? && (no_only_args?(args) || args.only_formulae? || args.only_formulae_dependents?)
junit_filters = %w[audit test]
junit = Junit.new(tests)
junit.build(filters: junit_filters)
junit.write("brew-test-bot.xml")
end
failed_steps.empty?
end
def no_only_args?(args)
any_only = args.only_cleanup_before? ||
args.only_setup? ||
args.only_tap_syntax? ||
args.only_formulae? ||
args.only_formulae_detect? ||
args.only_formulae_dependents? ||
args.only_bottles_fetch? ||
args.only_cleanup_after?
!any_only
end
def build_tests(argument, tap:, git:, output_paths:, skip_setup:,
skip_cleanup_before:, skip_cleanup_after:, args:)
tests = {}
no_only_args = no_only_args?(args)
if !skip_setup && (no_only_args || args.only_setup?)
tests[:setup] = Setup.new(dry_run: args.dry_run?,
fail_fast: args.fail_fast?,
verbose: args.verbose?)
end
if no_only_args || args.only_tap_syntax?
tests[:tap_syntax] = TapSyntax.new(tap: tap || CoreTap.instance,
dry_run: args.dry_run?,
git:,
fail_fast: args.fail_fast?,
verbose: args.verbose?)
end
no_formulae_flags = args.testing_formulae.nil? &&
args.added_formulae.nil? &&
args.deleted_formulae.nil?
if no_formulae_flags && (no_only_args || args.only_formulae? || args.only_formulae_detect?)
tests[:formulae_detect] = FormulaeDetect.new(argument, tap:,
git:,
dry_run: args.dry_run?,
fail_fast: args.fail_fast?,
verbose: args.verbose?)
end
if no_only_args || args.only_formulae?
tests[:formulae] = Formulae.new(tap:,
git:,
dry_run: args.dry_run?,
fail_fast: args.fail_fast?,
verbose: args.verbose?,
output_paths:)
end
if !args.skip_dependents? && (no_only_args || args.only_formulae? || args.only_formulae_dependents?)
tests[:formulae_dependents] = FormulaeDependents.new(tap:,
git:,
dry_run: args.dry_run?,
fail_fast: args.fail_fast?,
verbose: args.verbose?)
end
if Homebrew::TestBot.cleanup?(args)
if !skip_cleanup_before && (no_only_args || args.only_cleanup_before?)
tests[:cleanup_before] = CleanupBefore.new(tap:,
git:,
dry_run: args.dry_run?,
fail_fast: args.fail_fast?,
verbose: args.verbose?)
end
if !skip_cleanup_after && (no_only_args || args.only_cleanup_after?)
tests[:cleanup_after] = CleanupAfter.new(tap:,
git:,
dry_run: args.dry_run?,
fail_fast: args.fail_fast?,
verbose: args.verbose?)
end
end
if args.only_bottles_fetch?
tests[:bottles_fetch] = BottlesFetch.new(tap:,
git:,
dry_run: args.dry_run?,
fail_fast: args.fail_fast?,
verbose: args.verbose?)
end
tests
end
def run_tests(tests, args:)
tests[:cleanup_before]&.run!(args:)
begin
tests[:setup]&.run!(args:)
tests[:tap_syntax]&.run!(args:)
testing_formulae, added_formulae, deleted_formulae = if (detect_test = tests[:formulae_detect])
detect_test.run!(args:)
[
detect_test.testing_formulae,
detect_test.added_formulae,
detect_test.deleted_formulae,
]
else
[
args.testing_formulae.to_a,
args.added_formulae.to_a,
args.deleted_formulae.to_a,
]
end
skipped_or_failed_formulae = if (formulae_test = tests[:formulae])
formulae_test.testing_formulae = testing_formulae
formulae_test.added_formulae = added_formulae
formulae_test.deleted_formulae = deleted_formulae
formulae_test.run!(args:)
formulae_test.skipped_or_failed_formulae
elsif args.skipped_or_failed_formulae.present?
Array.new(args.skipped_or_failed_formulae)
elsif @skipped_or_failed_formulae_output_path.exist?
@skipped_or_failed_formulae_output_path.read.chomp.split(",")
else
[]
end
if (dependents_test = tests[:formulae_dependents])
dependents_test.testing_formulae = testing_formulae
dependents_test.skipped_or_failed_formulae = skipped_or_failed_formulae
dependents_test.tested_formulae = args.tested_formulae.to_a.presence || testing_formulae
dependents_test.run!(args:)
end
if (fetch_test = tests[:bottles_fetch])
fetch_test.testing_formulae = testing_formulae
fetch_test.run!(args:)
end
ensure
tests[:cleanup_after]&.run!(args:)
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/test_bot/junit.rb | Library/Homebrew/test_bot/junit.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
# Creates Junit report with only required by BuildPulse attributes
# See https://github.com/Homebrew/homebrew-test-bot/pull/621#discussion_r658712640
class Junit
def initialize(tests)
@tests = tests
end
def build(filters: nil)
filters ||= []
require "rexml/document"
require "rexml/xmldecl"
require "rexml/cdata"
@xml_document = REXML::Document.new
@xml_document << REXML::XMLDecl.new
testsuites = @xml_document.add_element "testsuites"
@tests.each do |test|
next if test.steps.empty?
testsuite = testsuites.add_element "testsuite"
testsuite.add_attribute "name", "brew-test-bot.#{Utils::Bottles.tag}"
testsuite.add_attribute "timestamp", test.steps.first.start_time.iso8601
test.steps.each do |step|
next unless filters.any? { |filter| step.command_short.start_with? filter }
testcase = testsuite.add_element "testcase"
testcase.add_attribute "name", step.command_short
testcase.add_attribute "status", step.status
testcase.add_attribute "time", step.time
testcase.add_attribute "timestamp", step.start_time.iso8601
next if step.passed?
elem = testcase.add_element "failure"
elem.add_attribute "message", "#{step.status}: #{step.command.join(" ")}"
end
end
end
def write(filename)
output_path = Pathname(filename)
output_path.unlink if output_path.exist?
output_path.open("w") do |xml_file|
pretty_print_indent = 2
@xml_document.write(xml_file, pretty_print_indent)
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/test_bot/cleanup_before.rb | Library/Homebrew/test_bot/cleanup_before.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class CleanupBefore < TestCleanup
def run!(args:)
test_header(:CleanupBefore)
if tap.to_s != CoreTap.instance.name && CoreTap.instance.installed?
reset_if_needed(CoreTap.instance.path.to_s)
end
Pathname.glob("*.bottle*.*").each(&:unlink)
if ENV["HOMEBREW_GITHUB_ACTIONS"] && !ENV["GITHUB_ACTIONS_HOMEBREW_SELF_HOSTED"]
# minimally fix brew doctor failures (a full clean takes ~5m)
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
if OS.linux?
# brew doctor complains
bad_paths = %w[
/usr/local/include/node/
/opt/pipx_bin/ansible-config
].map { |path| Pathname.new(path) }
delete_or_move bad_paths, sudo: true
elsif OS.mac?
delete_or_move HOMEBREW_CELLAR.glob("*")
delete_or_move HOMEBREW_CASKROOM.glob("session-manager-plugin")
frameworks_dir = Pathname("/Library/Frameworks")
frameworks = %w[
Mono.framework
PluginManager.framework
Python.framework
R.framework
Xamarin.Android.framework
Xamarin.Mac.framework
Xamarin.iOS.framework
].map { |framework| frameworks_dir/framework }
delete_or_move frameworks, sudo: true
end
test "brew", "cleanup", "--prune-prefix"
end
# rubocop:enable Homebrew/MoveToExtendOS
# Keep all "brew" invocations after cleanup_shared
# (which cleans up Homebrew/brew)
cleanup_shared
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/test_bot/bottles_fetch.rb | Library/Homebrew/test_bot/bottles_fetch.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class BottlesFetch < TestFormulae
attr_accessor :testing_formulae
def run!(args:)
info_header "Testing formulae:"
puts testing_formulae
puts
testing_formulae.each do |formula_name|
fetch_bottles!(formula_name, args:)
puts
end
end
private
def fetch_bottles!(formula_name, args:)
test_header(:BottlesFetch, method: "fetch_bottles!(#{formula_name})")
formula = Formula[formula_name]
return if formula.disabled?
tags = formula.bottle_specification.collector.tags
odie "#{formula_name} is missing bottles! Did you mean to use `brew pr-publish`?" if tags.blank?
tags.each do |tag|
cleanup_during!(args:)
test "brew", "fetch", "--retry", "--formulae", "--bottle-tag=#{tag}", formula_name
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/test_bot/formulae_dependents.rb | Library/Homebrew/test_bot/formulae_dependents.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class FormulaeDependents < TestFormulae
attr_writer :testing_formulae, :tested_formulae
def run!(args:)
test "brew", "untap", "--force", "homebrew/cask" if !tap&.core_cask_tap? && CoreCaskTap.instance.installed?
installable_bottles = @tested_formulae - @skipped_or_failed_formulae
unneeded_formulae = @tested_formulae - @testing_formulae
@skipped_or_failed_formulae += unneeded_formulae
info_header "Skipped or failed formulae:"
puts skipped_or_failed_formulae
@testing_formulae_with_tested_dependents = []
@tested_dependents_list = Pathname("tested-dependents-#{Utils::Bottles.tag}.txt")
@dependent_testing_formulae = sorted_formulae - skipped_or_failed_formulae
install_formulae_if_needed_from_bottles!(installable_bottles, args:)
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
artifact_specifier = if OS.linux?
"{linux,ubuntu}"
else
"{macos-#{MacOS.version},#{MacOS.version}-#{Hardware::CPU.arch}}"
end
# rubocop:enable Homebrew/MoveToExtendOS
download_artifacts_from_previous_run!("dependents{,_#{artifact_specifier}*}", dry_run: args.dry_run?)
@skip_candidates = if (tested_dependents_cache = artifact_cache/@tested_dependents_list).exist?
tested_dependents_cache.read.split("\n")
else
[]
end
@dependent_testing_formulae.each do |formula_name|
dependent_formulae!(formula_name, args:)
puts
end
return unless GitHub::Actions.env_set?
# Remove `bash` after it is tested, since leaving a broken `bash`
# installation in the environment can cause issues with subsequent
# GitHub Actions steps.
return unless @dependent_testing_formulae.include?("bash")
test "brew", "uninstall", "--formula", "--force", "bash"
end
private
def install_formulae_if_needed_from_bottles!(installable_bottles, args:)
installable_bottles.each do |formula_name|
formula = Formulary.factory(formula_name)
next if formula.latest_version_installed?
install_formula_from_bottle!(formula_name, testing_formulae_dependents: true, dry_run: args.dry_run?)
end
end
def dependent_formulae!(formula_name, args:)
cleanup_during!(@dependent_testing_formulae, args:)
test_header(:FormulaeDependents, method: "dependent_formulae!(#{formula_name})")
@testing_formulae_with_tested_dependents << formula_name
formula = Formulary.factory(formula_name)
source_dependents, bottled_dependents, testable_dependents =
dependents_for_formula(formula, formula_name, args:)
return if source_dependents.blank? && bottled_dependents.blank? && testable_dependents.blank?
# If we installed this from a bottle, then the formula isn't linked.
# If the formula isn't linked, `brew install --only-dependences` does
# nothing with the message:
# Warning: formula x.y.z is already installed, it's just not linked.
# To link this version, run:
# brew link formula
unlink_conflicts formula
test "brew", "link", formula_name unless formula.keg_only?
# Install formula dependencies. These may not be installed.
test "brew", "install", "--only-dependencies",
named_args: formula_name,
ignore_failures: !bottled?(formula, no_older_versions: true),
env: { "HOMEBREW_DEVELOPER" => nil }
return unless steps.last.passed?
# Restore etc/var files that may have been nuked in the build stage.
test "brew", "postinstall",
named_args: formula_name,
ignore_failures: !bottled?(formula, no_older_versions: true)
return unless steps.last.passed?
# Test texlive first to avoid GitHub-hosted runners running out of storage.
# TODO: Try generalising this by sorting dependents according to install size,
# where ideally install size should include recursive dependencies.
[source_dependents, bottled_dependents].each do |dependent_array|
texlive = dependent_array.find { |dependent| dependent.name == "texlive" }
next unless texlive.present?
dependent_array.delete(texlive)
dependent_array.unshift(texlive)
end
source_dependents.each do |dependent|
install_dependent(dependent, testable_dependents, build_from_source: true, args:)
install_dependent(dependent, testable_dependents, args:) if bottled?(dependent)
end
bottled_dependents.each do |dependent|
install_dependent(dependent, testable_dependents, args:)
end
end
def dependents_for_formula(formula, formula_name, args:)
info_header "Determining dependents..."
# Always skip recursive dependents on Intel. It's really slow.
# Also skip recursive dependents on Linux unless it's a Linux-only formula.
#
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
skip_recursive_dependents = args.skip_recursive_dependents? ||
(OS.mac? && Hardware::CPU.intel?) ||
(OS.linux? && formula.requirements.exclude?(LinuxRequirement.new))
# rubocop:enable Homebrew/MoveToExtendOS
uses_args = %w[--formula --eval-all]
uses_include_test_args = [*uses_args, "--include-test"]
uses_include_test_args << "--recursive" unless skip_recursive_dependents
dependents = with_env(HOMEBREW_STDERR: "1") do
Utils.safe_popen_read("brew", "uses", *uses_include_test_args, formula_name)
.split("\n")
end
# TODO: Consider handling the following case better.
# `foo` has a build dependency on `bar`, and `bar` has a runtime dependency on
# `baz`. When testing `baz` with `--build-dependents-from-source`, `foo` is
# not tested, but maybe should be.
dependents += with_env(HOMEBREW_STDERR: "1") do
Utils.safe_popen_read("brew", "uses", *uses_args, "--include-build", formula_name)
.split("\n")
end
dependents&.uniq!
dependents&.sort!
dependents -= @tested_formulae
dependents = dependents.map { |d| Formulary.factory(d) }
dependents = dependents.zip(dependents.map do |f|
if skip_recursive_dependents
f.deps.reject(&:implicit?)
else
begin
Dependency.expand(f, cache_key: "test-bot-dependents") do |_, dependency|
Dependency.skip if dependency.implicit?
Dependency.keep_but_prune_recursive_deps if dependency.build? || dependency.test?
end
rescue TapFormulaUnavailableError => e
raise if e.tap.installed?
e.tap.clear_cache
safe_system "brew", "tap", e.tap.name
retry
end
end.reject(&:optional?)
end)
# Defer formulae which could be tested later
# i.e. formulae that also depend on something else yet to be built in this test run.
dependents.reject! do |_, deps|
still_to_test = @dependent_testing_formulae - @testing_formulae_with_tested_dependents
deps.map { |d| d.to_formula.full_name }.intersect?(still_to_test)
end
# Split into dependents that we could potentially be building from source and those
# we should not. The criteria is that a dependent must have bottled dependencies, and
# either the `--build-dependents-from-source` flag was passed or a dependent has no
# bottle on the current OS.
source_dependents, dependents = dependents.partition do |dependent, deps|
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
next false if OS.linux? && dependent.requirements.exclude?(LinuxRequirement.new)
# rubocop:enable Homebrew/MoveToExtendOS
all_deps_bottled_or_built = deps.all? do |d|
bottled_or_built?(d.to_formula, @dependent_testing_formulae)
end
args.build_dependents_from_source? && all_deps_bottled_or_built
end
# From the non-source list, get rid of any dependents we are only a build dependency to
dependents.select! do |_, deps|
deps.reject { |d| d.build? && !d.test? }
.map(&:to_formula)
.include?(formula)
end
dependents = dependents.transpose.first.to_a
source_dependents = source_dependents.transpose.first.to_a
testable_dependents = source_dependents.select(&:test_defined?)
bottled_dependents = dependents.select { |dep| bottled?(dep) }
testable_dependents += bottled_dependents.select(&:test_defined?)
info_header "Source dependents:"
puts source_dependents
info_header "Bottled dependents:"
puts bottled_dependents
info_header "Testable dependents:"
puts testable_dependents
[source_dependents, bottled_dependents, testable_dependents]
end
def install_dependent(dependent, testable_dependents, args:, build_from_source: false)
if @skip_candidates.include?(dependent.full_name) &&
artifact_cache_valid?(dependent, formulae_dependents: true)
@tested_dependents_list.write(dependent.full_name, mode: "a")
@tested_dependents_list.write("\n", mode: "a")
skipped dependent.name, "#{dependent.full_name} has been tested at #{previous_github_sha}"
return
end
if (messages = unsatisfied_requirements_messages(dependent))
skipped dependent, messages
return
end
if dependent.deprecated? || dependent.disabled?
verb = dependent.deprecated? ? :deprecated : :disabled
skipped dependent.name, "#{dependent.full_name} has been #{verb}!"
return
end
cleanup_during!(@dependent_testing_formulae, args:)
required_dependent_deps = dependent.deps.reject(&:optional?)
bottled_on_current_version = bottled?(dependent, no_older_versions: true)
dependent_was_previously_installed = dependent.latest_version_installed?
dependent_dependencies = Dependency.expand(
dependent,
cache_key: "test-bot-dependent-dependencies-#{dependent.full_name}",
) do |dep_dependent, dependency|
next if !dependency.build? && !dependency.test? && !dependency.optional?
next if dependency.test? &&
dep_dependent == dependent &&
!dependency.optional? &&
testable_dependents.include?(dependent)
Dependency.prune
end
unless dependent_was_previously_installed
build_args = []
fetch_formulae = dependent_dependencies.reject(&:satisfied?).map(&:name)
if build_from_source
required_dependent_reqs = dependent.requirements.reject(&:optional?)
install_curl_if_needed(dependent)
install_mercurial_if_needed(required_dependent_deps, required_dependent_reqs)
install_subversion_if_needed(required_dependent_deps, required_dependent_reqs)
build_args << "--build-from-source"
test "brew", "fetch", "--build-from-source", "--retry", dependent.full_name
return if steps.last.failed?
else
fetch_formulae << dependent.full_name
end
if fetch_formulae.present?
test "brew", "fetch", "--retry", *fetch_formulae
return if steps.last.failed?
end
unlink_conflicts dependent
test "brew", "install", *build_args, "--only-dependencies",
named_args: dependent.full_name,
ignore_failures: !bottled_on_current_version,
env: { "HOMEBREW_DEVELOPER" => nil }
env = {}
env["HOMEBREW_GIT_PATH"] = nil if build_from_source && required_dependent_deps.any? do |d|
d.name == "git" && (!d.test? || d.build?)
end
test "brew", "install", *build_args,
named_args: dependent.full_name,
env: env.merge({ "HOMEBREW_DEVELOPER" => nil }),
ignore_failures: !args.test_default_formula? && !bottled_on_current_version
install_step = steps.last
return unless install_step.passed?
end
return unless dependent.latest_version_installed?
if !dependent.keg_only? && !dependent.linked_keg.exist?
unlink_conflicts dependent
test "brew", "link", dependent.full_name
end
test "brew", "install", "--only-dependencies", dependent.full_name
test "brew", "linkage", "--test",
named_args: dependent.full_name,
ignore_failures: !args.test_default_formula? && !bottled_on_current_version
linkage_step = steps.last
if linkage_step.passed? && !build_from_source
# Check for opportunistic linkage. Ignore failures because
# they can be unavoidable but we still want to know about them.
test "brew", "linkage", "--cached", "--test", "--strict",
named_args: dependent.full_name,
ignore_failures: !args.test_default_formula?
end
if testable_dependents.include? dependent
test "brew", "install", "--only-dependencies", "--include-test", dependent.full_name
dependent_dependencies.each do |dependency|
dependency_f = dependency.to_formula
next if dependency_f.keg_only?
next if dependency_f.linked?
unlink_conflicts dependency_f
test "brew", "link", dependency_f.full_name
end
env = {}
env["HOMEBREW_GIT_PATH"] = nil if required_dependent_deps.any? do |d|
d.name == "git" && (!d.build? || d.test?)
end
test "brew", "test", "--retry", "--verbose",
named_args: dependent.full_name,
env:,
ignore_failures: !args.test_default_formula? && !bottled_on_current_version
test_step = steps.last
end
test "brew", "uninstall", "--force", "--ignore-dependencies", dependent.full_name
all_tests_passed = (dependent_was_previously_installed || install_step.passed?) &&
linkage_step.passed? &&
(testable_dependents.exclude?(dependent) || test_step.passed?)
if all_tests_passed
@tested_dependents_list.write(dependent.full_name, mode: "a")
@tested_dependents_list.write("\n", mode: "a")
end
return unless GitHub::Actions.env_set?
if build_from_source &&
!bottled_on_current_version &&
!dependent_was_previously_installed &&
all_tests_passed &&
dependent.deps.all? { |d| bottled?(d.to_formula, no_older_versions: true) }
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
os_string = if OS.mac?
str = "macOS #{MacOS.version.pretty_name} (#{MacOS.version})"
str << " on Apple Silicon" if Hardware::CPU.arm?
str
else
OS.kernel_name
end
# rubocop:enable Homebrew/MoveToExtendOS
puts GitHub::Actions::Annotation.new(
:notice,
"All tests passed.",
file: dependent.path.to_s.delete_prefix("#{repository}/"),
title: "#{dependent} should be bottled for #{os_string}!",
)
end
end
def unlink_conflicts(formula)
return if formula.keg_only?
return if formula.linked_keg.exist?
conflicts = formula.conflicts.map { |c| Formulary.factory(c.name) }
.select(&:any_version_installed?)
formula_recursive_dependencies = begin
formula.recursive_dependencies
rescue TapFormulaUnavailableError => e
raise if e.tap.installed?
e.tap.clear_cache
safe_system "brew", "tap", e.tap.name
retry
end
formula_recursive_dependencies.each do |dependency|
conflicts += dependency.to_formula.conflicts.map do |c|
Formulary.factory(c.name)
end.select(&:any_version_installed?)
end
conflicts.each do |conflict|
test "brew", "unlink", conflict.name
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/test_bot/test_formulae.rb | Library/Homebrew/test_bot/test_formulae.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class TestFormulae < Test
attr_accessor :skipped_or_failed_formulae
attr_reader :artifact_cache
def initialize(tap:, git:, dry_run:, fail_fast:, verbose:)
super
@skipped_or_failed_formulae = []
@artifact_cache = Pathname.new("artifact-cache")
# Let's keep track of the artifacts we've already downloaded
# to avoid repeatedly trying to download the same thing.
@downloaded_artifacts = Hash.new { |h, k| h[k] = [] }
end
protected
def cached_event_json
return unless (event_json = artifact_cache/"event.json").exist?
event_json
end
def github_event_payload
return if (github_event_path = ENV.fetch("GITHUB_EVENT_PATH", nil)).blank?
JSON.parse(File.read(github_event_path))
end
def previous_github_sha
return if tap.blank?
return unless repository.directory?
return unless GitHub::Actions.env_set?
return if (payload = github_event_payload).blank?
head_repo_owner = payload.dig("pull_request", "head", "repo", "owner", "login")
head_from_fork = head_repo_owner != ENV.fetch("GITHUB_REPOSITORY_OWNER")
return if head_from_fork && head_repo_owner != "BrewTestBot"
# If we have a cached event payload, then we failed to get the artifact we wanted
# from `GITHUB_EVENT_PATH`, so use the cached payload to check for a SHA1.
event_payload = JSON.parse(cached_event_json.read) if cached_event_json.present?
event_payload ||= payload
event_payload.fetch("before", nil)
end
def artifact_metadata(check_suite_nodes, repo, event_name, workflow_name, check_run_name, artifact_pattern)
candidate_nodes = check_suite_nodes.select do |node|
next false if node.fetch("status") != "COMPLETED"
workflow_run = node.fetch("workflowRun")
next false if workflow_run.blank?
next false if workflow_run.fetch("event") != event_name
next false if workflow_run.dig("workflow", "name") != workflow_name
check_run_nodes = node.dig("checkRuns", "nodes")
next false if check_run_nodes.blank?
check_run_nodes.any? do |check_run_node|
check_run_node.fetch("name") == check_run_name && check_run_node.fetch("status") == "COMPLETED"
end
end
return [] if candidate_nodes.blank?
run_id = candidate_nodes.max_by { |node| Time.parse(node.fetch("updatedAt")) }
.dig("workflowRun", "databaseId")
return [] if run_id.blank?
url = GitHub.url_to("repos", repo, "actions", "runs", run_id, "artifacts")
response = GitHub::API.open_rest(url)
return [] if response.fetch("total_count").zero?
artifacts = response.fetch("artifacts")
artifacts.select do |artifact|
File.fnmatch?(artifact_pattern, artifact.fetch("name"), File::FNM_EXTGLOB)
end
end
GRAPHQL_QUERY = <<~GRAPHQL
query ($owner: String!, $repo: String!, $commit: GitObjectID!) {
repository(owner: $owner, name: $repo) {
object(oid: $commit) {
... on Commit {
checkSuites(last: 100) {
nodes {
status
updatedAt
workflowRun {
databaseId
event
workflow {
name
}
}
checkRuns(last: 100) {
nodes {
name
status
}
}
}
}
}
}
}
}
GRAPHQL
def download_artifacts_from_previous_run!(artifact_pattern, dry_run:)
return if dry_run
return if GitHub::API.credentials_type == :none
return if (sha = previous_github_sha).blank?
pull_number = github_event_payload.dig("pull_request", "number")
return if pull_number.blank?
github_repository = ENV.fetch("GITHUB_REPOSITORY")
owner, repo = *github_repository.split("/")
pr_labels = GitHub.pull_request_labels(owner, repo, pull_number)
# Also disable bottle cache for PRs modifying workflows to avoid cache poisoning.
return if pr_labels.include?("CI-no-bottle-cache") || pr_labels.include?("workflows")
variables = {
owner:,
repo:,
commit: sha,
}
response = GitHub::API.open_graphql(GRAPHQL_QUERY, variables:)
check_suite_nodes = response.dig("repository", "object", "checkSuites", "nodes")
return if check_suite_nodes.blank?
wanted_artifacts = artifact_metadata(check_suite_nodes, github_repository, "pull_request",
"CI", "conclusion", artifact_pattern)
wanted_artifacts_pattern = artifact_pattern
if wanted_artifacts.empty?
# If we didn't find the artifacts that we wanted, fall back to the `event_payload` artifact.
wanted_artifacts = artifact_metadata(check_suite_nodes, github_repository, "pull_request_target",
"Triage tasks", "upload-metadata", "event_payload")
wanted_artifacts_pattern = "event_payload"
end
return if wanted_artifacts.empty?
if (attempted_artifact = wanted_artifacts.find do |artifact|
@downloaded_artifacts[sha].include?(artifact.fetch("name"))
end)
opoo "Already tried #{attempted_artifact.fetch("name")} from #{sha}, giving up"
return
end
cached_event_json&.unlink if File.fnmatch?(wanted_artifacts_pattern, "event_payload", File::FNM_EXTGLOB)
require "utils/github/artifacts"
ohai "Downloading artifacts matching pattern #{wanted_artifacts_pattern} from #{sha}"
artifact_cache.mkpath
artifact_cache.cd do
wanted_artifacts.each do |artifact|
name = artifact.fetch("name")
ohai "Downloading artifact #{name} from #{sha}"
@downloaded_artifacts[sha] << name
download_url = artifact.fetch("archive_download_url")
artifact_id = artifact.fetch("id")
GitHub.download_artifact(download_url, artifact_id.to_s)
end
end
return if wanted_artifacts_pattern == artifact_pattern
# If we made it here, then we downloaded an `event_payload` artifact.
# We can now use this `event_payload` artifact to attempt to download the artifact we wanted.
download_artifacts_from_previous_run!(artifact_pattern, dry_run:)
rescue GitHub::API::AuthenticationFailedError => e
opoo e
end
def no_diff?(formula, git_ref)
return false unless repository.directory?
@fetched_refs ||= []
if @fetched_refs.exclude?(git_ref)
test git, "-C", repository, "fetch", "origin", git_ref, ignore_failures: true
@fetched_refs << git_ref if steps.last.passed?
end
relative_formula_path = formula.path.relative_path_from(repository)
system(git, "-C", repository, "diff", "--no-ext-diff", "--quiet", git_ref, "--", relative_formula_path)
end
def local_bottle_hash(formula, bottle_dir:)
return if (local_bottle_json = bottle_glob(formula, bottle_dir, ".json").first).blank?
JSON.parse(local_bottle_json.read)
end
def artifact_cache_valid?(formula, formulae_dependents: false)
sha = if formulae_dependents
previous_github_sha
else
local_bottle_hash(formula, bottle_dir: artifact_cache)&.dig(formula.name, "formula", "tap_git_revision")
end
return false if sha.blank?
return false unless no_diff?(formula, sha)
recursive_dependencies = if formulae_dependents
formula.recursive_dependencies
else
formula.recursive_dependencies do |_, dep|
Dependency.prune if dep.build? || dep.test?
end
end
recursive_dependencies.all? do |dep|
no_diff?(dep.to_formula, sha)
end
end
def bottle_glob(formula_name, bottle_dir = Pathname.pwd, ext = ".tar.gz", bottle_tag: Utils::Bottles.tag.to_s)
bottle_dir.glob("#{formula_name}--*.#{bottle_tag}.bottle*#{ext}")
end
def install_formula_from_bottle!(formula_name, testing_formulae_dependents:, dry_run:,
bottle_dir: Pathname.pwd)
bottle_filename = bottle_glob(formula_name, bottle_dir).first
if bottle_filename.blank?
if testing_formulae_dependents && !dry_run
raise "Failed to find bottle for '#{formula_name}'."
elsif !dry_run
return false
end
bottle_filename = "$BOTTLE_FILENAME"
end
install_args = []
install_args += %w[--ignore-dependencies --skip-post-install] if testing_formulae_dependents
test "brew", "install", *install_args, bottle_filename
install_step = steps.last
if !dry_run && !testing_formulae_dependents && install_step.passed?
bottle_hash = local_bottle_hash(formula_name, bottle_dir:)
bottle_revision = bottle_hash.dig(formula_name, "formula", "tap_git_revision")
bottle_header = "Bottle cache hit"
bottle_commit_details = if @fetched_refs&.include?(bottle_revision)
Utils.safe_popen_read(git, "-C", repository, "show", "--format=reference", bottle_revision)
else
bottle_revision
end
bottle_message = "Bottle for #{formula_name} built at #{bottle_commit_details}".strip
if GitHub::Actions.env_set?
puts GitHub::Actions::Annotation.new(
:notice,
bottle_message,
file: bottle_hash.dig(formula_name, "formula", "tap_git_path"),
title: bottle_header,
)
else
ohai bottle_header, bottle_message
end
end
return install_step.passed? if !testing_formulae_dependents || !install_step.passed?
test "brew", "unlink", formula_name
puts
install_step.passed?
end
def bottled?(formula, no_older_versions: false)
# If a formula has an `:all` bottle, then all its dependencies have
# to be bottled too for us to use it. We only need to recurse
# up the dep tree when we encounter an `:all` bottle because
# a formula is not bottled unless its dependencies are.
if formula.bottle_specification.tag?(Utils::Bottles.tag(:all))
formula.deps.all? do |dep|
bottle_no_older_versions = no_older_versions && (!dep.test? || dep.build?)
bottled?(dep.to_formula, no_older_versions: bottle_no_older_versions)
end
else
formula.bottle_specification.tag?(Utils::Bottles.tag, no_older_versions:)
end
end
def bottled_or_built?(formula, built_formulae, no_older_versions: false)
bottled?(formula, no_older_versions:) || built_formulae.include?(formula.full_name)
end
def downloads_using_homebrew_curl?(formula)
[:stable, :head].any? do |spec_name|
next false unless (spec = formula.send(spec_name))
spec.using == :homebrew_curl || spec.resources.values.any? { |r| r.using == :homebrew_curl }
end
end
def install_curl_if_needed(formula)
return unless downloads_using_homebrew_curl?(formula)
test "brew", "install", "curl",
env: { "HOMEBREW_DEVELOPER" => nil }
end
def install_mercurial_if_needed(deps, reqs)
return if (deps | reqs).none? { |d| d.name == "mercurial" && d.build? }
test "brew", "install", "mercurial",
env: { "HOMEBREW_DEVELOPER" => nil }
end
def install_subversion_if_needed(deps, reqs)
return if (deps | reqs).none? { |d| d.name == "subversion" && d.build? }
test "brew", "install", "subversion",
env: { "HOMEBREW_DEVELOPER" => nil }
end
def skipped(formula_name, reason)
@skipped_or_failed_formulae << formula_name
puts Formatter.headline(
"#{Formatter.warning("SKIPPED")} #{Formatter.identifier(formula_name)}",
color: :yellow,
)
opoo reason
end
def failed(formula_name, reason)
@skipped_or_failed_formulae << formula_name
puts Formatter.headline(
"#{Formatter.error("FAILED")} #{Formatter.identifier(formula_name)}",
color: :red,
)
onoe reason
end
def unsatisfied_requirements_messages(formula)
f = Formulary.factory(formula.full_name)
fi = FormulaInstaller.new(f, build_bottle: true)
unsatisfied_requirements, = fi.expand_requirements
return if unsatisfied_requirements.blank?
unsatisfied_requirements.values.flatten.map(&:message).join("\n").presence
end
def cleanup_during!(keep_formulae = [], args:)
return unless cleanup?(args)
return unless HOMEBREW_CACHE.exist?
free_gb = Utils.safe_popen_read({ "BLOCKSIZE" => (1000 ** 3).to_s }, "df", HOMEBREW_CACHE.to_s)
.lines[1] # HOMEBREW_CACHE
.split[3] # free GB
.to_i
return if free_gb > 10
test_header(:TestFormulae, method: :cleanup_during!)
# HOMEBREW_LOGS can be a subdirectory of HOMEBREW_CACHE.
# Preserve the logs in that case.
logs_are_in_cache = HOMEBREW_LOGS.ascend { |path| break true if path == HOMEBREW_CACHE }
should_save_logs = logs_are_in_cache && HOMEBREW_LOGS.exist?
test "mv", HOMEBREW_LOGS.to_s, (tmpdir = Dir.mktmpdir) if should_save_logs
FileUtils.chmod_R "u+rw", HOMEBREW_CACHE, force: true
test "rm", "-rf", HOMEBREW_CACHE.to_s
if should_save_logs
FileUtils.mkdir_p HOMEBREW_LOGS.parent
test "mv", "#{tmpdir}/#{HOMEBREW_LOGS.basename}", HOMEBREW_LOGS.to_s
end
if @cleaned_up_during.blank?
@cleaned_up_during = true
return
end
installed_formulae = Utils.safe_popen_read("brew", "list", "--full-name", "--formulae").split("\n")
uninstallable_formulae = installed_formulae - keep_formulae
@installed_formulae_deps ||= Hash.new do |h, formula|
h[formula] = Utils.safe_popen_read("brew", "deps", "--full-name", formula).split("\n")
end
uninstallable_formulae.reject! do |name|
keep_formulae.any? { |f| @installed_formulae_deps[f].include?(name) }
end
return if uninstallable_formulae.blank?
test "brew", "uninstall", "--force", "--ignore-dependencies", *uninstallable_formulae
end
def sorted_formulae
changed_formulae_dependents = {}
@testing_formulae.each do |formula|
begin
formula_dependencies =
Utils.popen_read("brew", "deps", "--full-name",
"--include-build",
"--include-test", formula)
.split("\n")
# deps can fail if deps are not tapped
unless $CHILD_STATUS.success?
Formulary.factory(formula).recursive_dependencies
# If we haven't got a TapFormulaUnavailableError, then something else is broken
raise "Failed to determine dependencies for '#{formula}'."
end
rescue TapFormulaUnavailableError => e
raise if e.tap.installed?
e.tap.clear_cache
safe_system "brew", "tap", e.tap.name
retry
end
unchanged_dependencies = formula_dependencies - @testing_formulae
changed_dependencies = formula_dependencies - unchanged_dependencies
changed_dependencies.each do |changed_formula|
changed_formulae_dependents[changed_formula] ||= 0
changed_formulae_dependents[changed_formula] += 1
end
end
changed_formulae = changed_formulae_dependents.sort do |a1, a2|
a2[1].to_i <=> a1[1].to_i
end
changed_formulae.map!(&:first)
unchanged_formulae = @testing_formulae - changed_formulae
changed_formulae + unchanged_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/test_bot/formulae.rb | Library/Homebrew/test_bot/formulae.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Homebrew
module TestBot
class Formulae < TestFormulae
attr_writer :testing_formulae, :added_formulae, :deleted_formulae
def initialize(tap:, git:, dry_run:, fail_fast:, verbose:, output_paths:)
super(tap:, git:, dry_run:, fail_fast:, verbose:)
@built_formulae = []
@bottle_checksums = {}
@bottle_output_path = output_paths[:bottle]
@linkage_output_path = output_paths[:linkage]
@skipped_or_failed_formulae_output_path = output_paths[:skipped_or_failed_formulae]
end
def run!(args:)
test_header(:Formulae)
verify_local_bottles
with_env(HOMEBREW_DISABLE_LOAD_FORMULA: "1") do
# Portable Ruby bottles are handled differently.
next if testing_portable_ruby?
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
bottle_specifier = if OS.linux?
"{linux,ubuntu}"
else
"{macos-#{MacOS.version},#{MacOS.version}-#{Hardware::CPU.arch}}"
end
# rubocop:enable Homebrew/MoveToExtendOS
download_artifacts_from_previous_run!("bottles{,_#{bottle_specifier}*}", dry_run: args.dry_run?)
end
@bottle_checksums.merge!(
bottle_glob("*", artifact_cache, ".{json,tar.gz}", bottle_tag: "*").to_h do |bottle_file|
[bottle_file.realpath, bottle_file.sha256]
end,
)
# #run! modifies `@testing_formulae`, so we need to track this separately.
@testing_formulae_count = @testing_formulae.count
perform_bash_cleanup = @testing_formulae.include?("bash")
@tested_formulae_count = 0
sorted_formulae.each do |f|
verify_local_bottles
if testing_portable_ruby?
portable_formula!(f)
else
formula!(f, args:)
end
puts
next if @testing_formulae_count < 3
progress_text = +"Test progress: "
progress_text += "#{@tested_formulae_count} formula(e) tested, "
progress_text += "#{@testing_formulae_count - @tested_formulae_count} remaining"
info_header progress_text
end
@deleted_formulae.each do |f|
deleted_formula!(f)
verify_local_bottles
puts
end
return unless GitHub::Actions.env_set?
# Remove `bash` after it is tested, since leaving a broken `bash`
# installation in the environment can cause issues with subsequent
# GitHub Actions steps.
test "brew", "uninstall", "--formula", "--force", "bash" if perform_bash_cleanup
File.open(ENV.fetch("GITHUB_OUTPUT"), "a") do |f|
f.puts "skipped_or_failed_formulae=#{@skipped_or_failed_formulae.join(",")}"
end
@skipped_or_failed_formulae_output_path.write(@skipped_or_failed_formulae.join(","))
ensure
verify_local_bottles
FileUtils.rm_rf artifact_cache
end
private
def tap_needed_taps(deps)
deps.each { |d| d.to_formula.recursive_dependencies }
rescue TapFormulaUnavailableError => e
raise if e.tap.installed?
e.tap.clear_cache
safe_system "brew", "tap", e.tap.name
retry
end
def install_ca_certificates_if_needed
return if DevelopmentTools.ca_file_handles_most_https_certificates?
test "brew", "install", "--formulae", "ca-certificates",
env: { "HOMEBREW_DEVELOPER" => nil }
end
def setup_formulae_deps_instances(formula, formula_name, args:)
conflicts = formula.conflicts
formula_recursive_dependencies = formula.recursive_dependencies.map(&:to_formula)
formula_recursive_dependencies.each do |dependency|
conflicts += dependency.conflicts
end
# If we depend on a versioned formula, make sure to unlink any other
# installed versions to make sure that we use the right one.
versioned_dependencies = formula_recursive_dependencies.select(&:versioned_formula?)
versioned_dependencies.each do |dependency|
alternative_versions = dependency.versioned_formulae
begin
unversioned_name = dependency.name.sub(/@\d+(\.\d+)*$/, "")
alternative_versions << Formula[unversioned_name]
rescue FormulaUnavailableError
nil
end
unneeded_alternative_versions = alternative_versions - formula_recursive_dependencies
conflicts += unneeded_alternative_versions
end
unlink_formulae = conflicts.map(&:name)
unlink_formulae.uniq.each do |name|
unlink_formula = Formulary.factory(name)
next unless unlink_formula.latest_version_installed?
next unless unlink_formula.linked_keg.exist?
test "brew", "unlink", name
end
info_header "Determining dependencies..."
installed = Utils.safe_popen_read("brew", "list", "--formula", "--full-name").split("\n")
dependencies =
Utils.safe_popen_read("brew", "deps", "--formula",
"--include-build",
"--include-test",
"--full-name",
formula_name)
.split("\n")
installed_dependencies = installed & dependencies
installed_dependencies.each do |name|
link_formula = Formulary.factory(name)
next if link_formula.keg_only?
next if link_formula.linked_keg.exist?
next if unlink_formulae.include?(name)
test "brew", "link", name
end
dependencies -= installed
@unchanged_dependencies = dependencies - @testing_formulae
unless @unchanged_dependencies.empty?
test "brew", "fetch", "--formulae", "--retry",
*@unchanged_dependencies
end
changed_dependencies = dependencies - @unchanged_dependencies
unless changed_dependencies.empty?
test "brew", "fetch", "--formulae", "--retry", "--build-from-source",
*changed_dependencies
ignore_failures = !args.test_default_formula? && changed_dependencies.any? do |dep|
!bottled?(Formulary.factory(dep), no_older_versions: true)
end
# Install changed dependencies as new bottles so we don't have
# checksum problems. We have to install all `changed_dependencies`
# in one `brew install` command to make sure they are installed in
# the right order.
test("brew", "install", "--formulae", "--build-from-source",
named_args: changed_dependencies,
ignore_failures:)
# Run postinstall on them because the tested formula might depend on
# this step
test "brew", "postinstall", named_args: changed_dependencies, ignore_failures:
end
runtime_or_test_dependencies =
Utils.safe_popen_read("brew", "deps", "--formula", "--include-test", formula_name)
.split("\n")
build_dependencies = dependencies - runtime_or_test_dependencies
@unchanged_build_dependencies = build_dependencies - @testing_formulae
end
def cleanup_bottle_etc_var(formula)
# Restore etc/var files from bottle so dependents can use them.
formula.install_etc_var
end
def verify_local_bottles
# Portable Ruby bottles are handled differently.
return if testing_portable_ruby?
# Setting `HOMEBREW_DISABLE_LOAD_FORMULA` probably doesn't do anything here but let's set it just to be safe.
with_env(HOMEBREW_DISABLE_LOAD_FORMULA: "1") do
missing_bottles = @bottle_checksums.keys.reject do |bottle_path|
next true if bottle_path.exist?
what = (bottle_path.extname == ".json") ? "JSON" : "tarball"
onoe "Missing bottle #{what}: #{bottle_path}"
false
end
mismatched_checksums = @bottle_checksums.reject do |bottle_path, expected_sha256|
next true unless bottle_path.exist?
next true if (actual_sha256 = bottle_path.sha256) == expected_sha256
onoe <<~ERROR
Bottle checksum mismatch for #{bottle_path}!
Expected: #{expected_sha256}
Actual: #{actual_sha256}
ERROR
false
end
unexpected_bottles = bottle_glob(
"**/*", Pathname.pwd, ".{json,tar.gz}", bottle_tag: "*"
).reject do |local_bottle|
next true if @bottle_checksums.key?(local_bottle.realpath)
what = (local_bottle.extname == ".json") ? "JSON" : "tarball"
onoe "Unexpected bottle #{what}: #{local_bottle}"
false
end
return true if missing_bottles.blank? && mismatched_checksums.blank? && unexpected_bottles.blank?
# Delete these files so we don't end up uploading them.
files_to_delete = mismatched_checksums.keys + unexpected_bottles
files_to_delete += files_to_delete.select(&:symlink?).map(&:realpath)
FileUtils.rm_rf files_to_delete
test "false" # ensure that `test-bot` exits with an error.
false
end
end
def bottle_reinstall_formula(formula, new_formula, args:)
unless build_bottle?(formula, args:)
@bottle_filename = nil
return
end
root_url = args.root_url
# GitHub Releases url
root_url ||= if tap.present? && !tap.core_tap? && !args.test_default_formula?
"#{tap.default_remote}/releases/download/#{formula.name}-#{formula.pkg_version}"
end
# This is needed where sparse files may be handled (bsdtar >=3.0).
# We use gnu-tar with sparse files disabled when --only-json-tab is passed.
#
# TODO: move to extend/os
# rubocop:todo Homebrew/MoveToExtendOS
ENV["HOMEBREW_BOTTLE_SUDO_PURGE"] = "1" if OS.mac? && MacOS.version >= :catalina && !args.only_json_tab?
# rubocop:enable Homebrew/MoveToExtendOS
bottle_args = ["--verbose", "--json", formula.full_name]
bottle_args << "--keep-old" if args.keep_old? && !new_formula
bottle_args << "--skip-relocation" if args.skip_relocation?
bottle_args << "--force-core-tap" if args.test_default_formula?
bottle_args << "--root-url=#{root_url}" if root_url
bottle_args << "--only-json-tab" if args.only_json_tab?
verify_local_bottles
test "brew", "bottle", *bottle_args
bottle_step = steps.last
if !bottle_step.passed? || !bottle_step.output?
failed formula.full_name, "bottling failed" unless args.dry_run?
return
end
@bottle_filename = Pathname.new(
bottle_step.output
.gsub(%r{.*(\./\S+#{HOMEBREW_BOTTLES_EXTNAME_REGEX}).*}om, '\1'),
)
@bottle_json_filename = Pathname.new(
@bottle_filename.to_s.gsub(/\.(\d+\.)?tar\.gz$/, ".json"),
)
@bottle_checksums[@bottle_filename.realpath] = @bottle_filename.sha256
@bottle_checksums[@bottle_json_filename.realpath] = @bottle_json_filename.sha256
@bottle_output_path.write(bottle_step.output, mode: "a")
bottle_merge_args =
["--merge", "--write", "--no-commit", "--no-all-checks", @bottle_json_filename]
bottle_merge_args << "--keep-old" if args.keep_old? && !new_formula
test "brew", "bottle", *bottle_merge_args
test "brew", "uninstall", "--formula", "--force", "--ignore-dependencies", formula.full_name
@testing_formulae.delete(formula.name)
unless @unchanged_build_dependencies.empty?
test "brew", "uninstall", "--formulae", "--force", "--ignore-dependencies", *@unchanged_build_dependencies
@unchanged_dependencies -= @unchanged_build_dependencies
end
verify_attestations = if formula.name == "gh"
nil
else
ENV.fetch("HOMEBREW_VERIFY_ATTESTATIONS", nil)
end
test "brew", "install", "--only-dependencies", @bottle_filename,
env: { "HOMEBREW_VERIFY_ATTESTATIONS" => verify_attestations }
test "brew", "install", @bottle_filename,
env: { "HOMEBREW_VERIFY_ATTESTATIONS" => verify_attestations }
end
def build_bottle?(formula, args:)
# Build and runtime dependencies must be bottled on the current OS,
# but accept an older compatible bottle for test dependencies.
return false if formula.deps.any? do |dep|
!bottled_or_built?(
dep.to_formula,
@built_formulae - @skipped_or_failed_formulae,
no_older_versions: !dep.test?,
)
end
!args.build_from_source?
end
def livecheck(formula)
return unless formula.livecheck_defined?
return if formula.livecheck.skip?
livecheck_step = test "brew", "livecheck", "--autobump", "--formula",
"--json", "--full-name", formula.full_name
return if livecheck_step.failed?
return unless livecheck_step.output?
livecheck_info = JSON.parse(livecheck_step.output)&.first
if livecheck_info["status"] == "error"
error_msg = if livecheck_info["messages"].present? && livecheck_info["messages"].length.positive?
livecheck_info["messages"].join("\n")
else
# An error message should always be provided alongside an "error"
# status but this is a failsafe
"Error encountered (no message provided)"
end
if GitHub::Actions.env_set?
puts GitHub::Actions::Annotation.new(
:error,
error_msg,
title: "#{formula}: livecheck error",
file: formula.path.to_s.delete_prefix("#{repository}/"),
)
else
onoe error_msg
end
end
# `status` and `version` are mutually exclusive (the presence of one
# indicates the absence of the other)
return if livecheck_info["status"].present?
return if livecheck_info["version"]["newer_than_upstream"] != true
current_version = livecheck_info["version"]["current"]
latest_version = livecheck_info["version"]["latest"]
newer_than_upstream_msg = if current_version.present? && latest_version.present?
"The formula version (#{current_version}) is newer than the " \
"version from `brew livecheck` (#{latest_version})."
else
"The formula version is newer than the version from `brew livecheck`."
end
if GitHub::Actions.env_set?
puts GitHub::Actions::Annotation.new(
:warning,
newer_than_upstream_msg,
title: "#{formula}: Formula version newer than livecheck",
file: formula.path.to_s.delete_prefix("#{repository}/"),
)
else
opoo newer_than_upstream_msg
end
end
def formula!(formula_name, args:)
cleanup_during!(@testing_formulae, args:)
test_header(:Formulae, method: "formula!(#{formula_name})")
formula = Formulary.factory(formula_name)
if formula.disabled?
skipped formula_name, "#{formula.full_name} has been disabled!"
return
end
test "brew", "deps", "--tree", "--prune", "--annotate", "--include-build", "--include-test",
named_args: formula_name
deps_without_compatible_bottles = formula.deps.map(&:to_formula)
deps_without_compatible_bottles.reject! do |dep|
bottled_or_built?(dep, @built_formulae - @skipped_or_failed_formulae)
end
bottled_on_current_version = bottled?(formula, no_older_versions: true)
if deps_without_compatible_bottles.present? && !bottled_on_current_version
message = <<~EOS
#{formula_name} has dependencies without compatible bottles:
#{deps_without_compatible_bottles * "\n "}
EOS
skipped formula_name, message
return
end
new_formula = @added_formulae.include?(formula_name)
ignore_failures = !args.test_default_formula? && !bottled_on_current_version && !new_formula
deps = []
reqs = []
build_flag = if build_bottle?(formula, args:)
"--build-bottle"
else
if GitHub::Actions.env_set?
puts GitHub::Actions::Annotation.new(
:warning,
"#{formula} has unbottled dependencies, so a bottle will not be built.",
title: "No bottle built for #{formula}!",
file: formula.path.to_s.delete_prefix("#{repository}/"),
)
else
onoe "Not building a bottle for #{formula} because it has unbottled dependencies."
end
skipped formula_name, "No bottle built."
return
end
# Online checks are a bit flaky and less useful for PRs that modify multiple formulae.
skip_online_checks = args.skip_online_checks? || (@testing_formulae_count > 5)
fetch_args = [formula_name]
fetch_args << build_flag
fetch_args << "--force" if cleanup?(args)
audit_args = [formula_name]
audit_args << "--online" unless skip_online_checks
if new_formula
if !args.skip_new?
audit_args << "--new"
elsif !args.skip_new_strict?
audit_args << "--strict"
end
else
audit_args << "--git" << "--skip-style"
audit_args << "--except=unconfirmed_checksum_change" if args.skip_checksum_only_audit?
audit_args << "--except=stable_version" if args.skip_stable_version_audit?
audit_args << "--except=revision" if args.skip_revision_audit?
end
# This needs to be done before any network operation.
install_ca_certificates_if_needed
if (messages = unsatisfied_requirements_messages(formula))
test "brew", "fetch", "--formula", "--retry", *fetch_args
test "brew", "audit", "--formula", *audit_args
skipped formula_name, messages
return
end
deps |= formula.deps.to_a.reject(&:optional?)
reqs |= formula.requirements.to_a.reject(&:optional?)
tap_needed_taps(deps)
install_curl_if_needed(formula)
install_mercurial_if_needed(deps, reqs)
install_subversion_if_needed(deps, reqs)
setup_formulae_deps_instances(formula, formula_name, args:)
test "brew", "uninstall", "--formula", "--force", formula_name if formula.latest_version_installed?
install_args = ["--verbose", "--formula"]
install_args << build_flag
# We can't verify attestations if we're building `gh`.
verify_attestations = if formula_name == "gh"
nil
else
ENV.fetch("HOMEBREW_VERIFY_ATTESTATIONS", nil)
end
# Don't care about e.g. bottle failures for dependencies.
test "brew", "install", "--only-dependencies", *install_args, formula_name,
env: { "HOMEBREW_DEVELOPER" => nil,
"HOMEBREW_VERIFY_ATTESTATIONS" => verify_attestations }
info_header "Starting tests for #{formula_name}"
test "brew", "fetch", "--formula", "--retry", *fetch_args
env = {}
env["HOMEBREW_GIT_PATH"] = nil if deps.any? do |d|
d.name == "git" && (!d.test? || d.build?)
end
install_step_passed = formula_installed_from_bottle =
artifact_cache_valid?(formula) &&
verify_local_bottles && # Checking the artifact cache loads formulae, so do this check second.
install_formula_from_bottle!(formula_name,
bottle_dir: artifact_cache,
testing_formulae_dependents: false,
dry_run: args.dry_run?)
install_step_passed ||= begin
test("brew", "install", *install_args,
named_args: formula_name,
env: env.merge({ "HOMEBREW_DEVELOPER" => nil,
"HOMEBREW_VERIFY_ATTESTATIONS" => verify_attestations }),
ignore_failures:, report_analytics: true)
steps.last.passed?
end
livecheck(formula) if !args.skip_livecheck? && !skip_online_checks
test "brew", "style", "--formula", formula_name, report_analytics: true
test "brew", "audit", "--formula", *audit_args, report_analytics: true unless formula.deprecated?
unless install_step_passed
if ignore_failures
skipped formula_name, "install failed"
else
failed formula_name, "install failed"
end
return
end
if formula_installed_from_bottle
moved_artifacts = bottle_glob(formula_name, artifact_cache, ".{json,tar.gz}").map(&:realpath)
Pathname.pwd.install moved_artifacts
moved_artifacts.each do |old_location|
new_location = old_location.basename.realpath
@bottle_checksums[new_location] = @bottle_checksums.fetch(old_location)
@bottle_checksums.delete(old_location)
end
else
bottle_reinstall_formula(formula, new_formula, args:)
end
@built_formulae << formula.full_name
test("brew", "linkage", "--test", named_args: formula_name, ignore_failures:, report_analytics: true)
failed_linkage_or_test_messages ||= []
failed_linkage_or_test_messages << "linkage failed" unless steps.last.passed?
if steps.last.passed?
# Check for opportunistic linkage. Ignore failures because
# they can be unavoidable but we still want to know about them.
test "brew", "linkage", "--cached", "--test", "--strict",
named_args: formula_name,
ignore_failures: !args.test_default_formula?
end
test "brew", "linkage", "--cached", formula_name
@linkage_output_path.write(Formatter.headline(steps.last.command_trimmed, color: :blue), mode: "a")
@linkage_output_path.write("\n", mode: "a")
@linkage_output_path.write(steps.last.output, mode: "a")
test "brew", "install", "--formula", "--only-dependencies", "--include-test", formula_name
if formula.test_defined?
env = {}
env["HOMEBREW_GIT_PATH"] = nil if deps.any? do |d|
d.name == "git" && (!d.build? || d.test?)
end
# Intentionally not passing --retry here to avoid papering over
# flaky tests when a formula isn't being pulled in as a dependent.
test("brew", "test", "--verbose", named_args: formula_name, env:, ignore_failures:,
report_analytics: true)
failed_linkage_or_test_messages << "test failed" unless steps.last.passed?
end
# Move bottle and don't test dependents if the formula linkage or test failed.
if failed_linkage_or_test_messages.present?
if @bottle_filename
failed_dir = @bottle_filename.dirname/"failed"
moved_artifacts = [@bottle_filename, @bottle_json_filename].map(&:realpath)
failed_dir.install moved_artifacts
moved_artifacts.each do |old_location|
new_location = (failed_dir/old_location.basename).realpath
@bottle_checksums[new_location] = @bottle_checksums.fetch(old_location)
@bottle_checksums.delete(old_location)
end
end
if ignore_failures
skipped formula_name, failed_linkage_or_test_messages.join(", ")
else
failed formula_name, failed_linkage_or_test_messages.join(", ")
end
end
ensure
@tested_formulae_count += 1
cleanup_bottle_etc_var(formula) if cleanup?(args)
if @unchanged_dependencies.present?
test "brew", "uninstall", "--formulae", "--force", "--ignore-dependencies", *@unchanged_dependencies
end
end
def portable_formula!(formula_name)
test_header(:Formulae, method: "portable_formula!(#{formula_name})")
install_ca_certificates_if_needed
# Can't resolve attestations properly on old macOS versions.
ENV["HOMEBREW_NO_VERIFY_ATTESTATIONS"] = "1"
# On Linux, install glibc and linux-headers from bottles and don't install their build dependencies.
bottled_dep_allowlist = /\A(?:glibc|linux-headers)@/
deps = Dependency.expand(Formula[formula_name],
cache_key: "portable-package-#{formula_name}") do |_dependent, dep|
Dependency.prune if dep.test? || dep.optional?
next unless bottled_dep_allowlist.match?(dep.name)
Dependency.keep_but_prune_recursive_deps
end.map(&:name)
bottled_deps, deps = deps.partition { |dep| bottled_dep_allowlist.match?(dep) }
# Install bottled dependencies.
test "brew", "install", *bottled_deps if bottled_deps.present?
# Build bottles for all other dependencies.
test "brew", "install", "--build-bottle", *deps
# Build main bottle.
test "brew", "install", "--build-bottle", formula_name
test "brew", "uninstall", "--force", "--ignore-dependencies", *deps
test "brew", "test", formula_name
test "brew", "linkage", formula_name
test "brew", "bottle", "--skip-relocation", "--json", "--no-rebuild", formula_name
end
def deleted_formula!(formula_name)
test_header(:Formulae, method: "deleted_formula!(#{formula_name})")
test "brew", "uses",
"--formula",
"--eval-all",
"--include-build",
"--include-optional",
"--include-test",
formula_name
end
def testing_portable_ruby?
tap&.core_tap? && @testing_formulae.include?("portable-ruby")
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/services/cli.rb | Library/Homebrew/services/cli.rb | # typed: strict
# frozen_string_literal: true
require "services/formula_wrapper"
require "fileutils"
require "utils/output"
module Homebrew
module Services
module Cli
extend FileUtils
extend Utils::Output::Mixin
sig { returns(T.nilable(String)) }
def self.sudo_service_user
@sudo_service_user
end
sig { params(sudo_service_user: String).void }
def self.sudo_service_user=(sudo_service_user)
@sudo_service_user = T.let(sudo_service_user, T.nilable(String))
end
# Binary name.
sig { returns(String) }
def self.bin
"brew services"
end
# Find all currently running services via launchctl list or systemctl list-units.
sig { returns(T::Array[String]) }
def self.running
if System.launchctl?
Utils.popen_read(System.launchctl, "list")
else
System::Systemctl.popen_read("list-units",
"--type=service",
"--state=running",
"--no-pager",
"--no-legend")
end.chomp.split("\n").filter_map do |svc|
Regexp.last_match(0) if svc =~ /homebrew(?>\.mxcl)?\.([\w+-.@]+)/
end
end
# Check if formula has been found.
sig { params(targets: T::Array[Services::FormulaWrapper]).returns(T::Boolean) }
def self.check!(targets)
raise UsageError, "Formula(e) missing, please provide a formula name or use `--all`." if targets.empty?
true
end
# Kill services that don't have a service file
sig { returns(T::Array[String]) }
def self.kill_orphaned_services
cleaned_labels = []
cleaned_services = []
running.each do |label|
if (service = FormulaWrapper.from(label))
unless service.dest.file?
cleaned_labels << label
cleaned_services << service
end
else
opoo "Service #{label} not managed by `#{bin}` => skipping"
end
end
kill(cleaned_services)
cleaned_labels
end
sig { returns(T::Array[String]) }
def self.remove_unused_service_files
cleaned = []
Dir["#{System.path}homebrew.*.{plist,service}"].each do |file|
next if running.include?(File.basename(file).sub(/\.(plist|service)$/i, ""))
puts "Removing unused service file: #{file}"
rm file
cleaned << file
end
cleaned
end
# Run a service as defined in the formula. This does not clean the service file like `start` does.
sig {
params(
targets: T::Array[Services::FormulaWrapper],
service_file: T.nilable(String),
verbose: T::Boolean,
).void
}
def self.run(targets, service_file = nil, verbose: false)
if service_file.present?
file = Pathname.new service_file
raise UsageError, "Provided service file does not exist." unless file.exist?
end
targets.each do |service|
if service.pid?
puts "Service `#{service.name}` already running, use `#{bin} restart #{service.name}` to restart."
next
elsif System.root?
puts "Service `#{service.name}` cannot be run (but can be started) as root."
next
end
service_load(service, file, enable: false)
end
end
# Start a service.
sig {
params(
targets: T::Array[Services::FormulaWrapper],
service_file: T.nilable(String),
verbose: T::Boolean,
).void
}
def self.start(targets, service_file = nil, verbose: false)
file = T.let(nil, T.nilable(Pathname))
if service_file.present?
file = Pathname.new service_file
raise UsageError, "Provided service file does not exist." unless file.exist?
end
targets.each do |service|
if service.pid?
puts "Service `#{service.name}` already started, use `#{bin} restart #{service.name}` to restart."
next
end
odie "Formula `#{service.name}` is not installed." unless service.installed?
file ||= if service.service_file.exist? || System.systemctl?
nil
elsif service.formula.opt_prefix.exist? &&
(keg = Keg.for service.formula.opt_prefix) &&
keg.plist_installed?
service_file = Dir["#{keg}/*#{service.service_file.extname}"].first
Pathname.new service_file if service_file.present?
end
install_service_file(service, file)
if file.blank? && verbose
ohai "Generated service file for #{service.formula.name}:"
puts " #{service.dest.read.gsub("\n", "\n ")}"
puts
end
next if !take_root_ownership?(service) && System.root?
service_load(service, nil, enable: true)
end
end
# Stop a service and unload it.
sig {
params(
targets: T::Array[Services::FormulaWrapper],
verbose: T::Boolean,
no_wait: T::Boolean,
max_wait: T.nilable(T.any(Integer, Float)),
keep: T::Boolean,
).void
}
def self.stop(targets, verbose: false, no_wait: false, max_wait: 0, keep: false)
targets.each do |service|
unless service.loaded?
rm service.dest if !keep && service.dest.exist? # get rid of installed service file anyway, dude
if service.service_file_present?
odie <<~EOS
Service `#{service.name}` is started as `#{service.owner}`. Try:
#{"sudo " unless System.root?}#{bin} stop #{service.name}
EOS
elsif System.launchctl? &&
quiet_system(System.launchctl, "bootout", "#{System.domain_target}/#{service.service_name}")
ohai "Successfully stopped `#{service.name}` (label: #{service.service_name})"
else
opoo "Service `#{service.name}` is not started."
end
next
end
systemctl_args = []
if no_wait
systemctl_args << "--no-block"
puts "Stopping `#{service.name}`..."
else
puts "Stopping `#{service.name}`... (might take a while)"
end
if System.systemctl?
if keep
System::Systemctl.quiet_run(*systemctl_args, "stop", service.service_name)
else
System::Systemctl.quiet_run(*systemctl_args, "disable", "--now", service.service_name)
end
elsif System.launchctl?
dont_wait_statuses = [
Errno::ESRCH::Errno,
System::LAUNCHCTL_DOMAIN_ACTION_NOT_SUPPORTED,
]
System.candidate_domain_targets.each do |domain_target|
break unless service.loaded?
quiet_system System.launchctl, "bootout", "#{domain_target}/#{service.service_name}"
unless no_wait
time_slept = 0
sleep_time = 1
max_wait = T.must(max_wait)
exit_status = $CHILD_STATUS.exitstatus
while dont_wait_statuses.exclude?(exit_status) &&
(exit_status == Errno::EINPROGRESS::Errno || service.loaded?) &&
(max_wait.zero? || time_slept < max_wait)
sleep(sleep_time)
time_slept += sleep_time
quiet_system System.launchctl, "bootout", "#{domain_target}/#{service.service_name}"
exit_status = $CHILD_STATUS.exitstatus
end
end
service.reset_cache!
quiet_system System.launchctl, "stop", "#{domain_target}/#{service.service_name}" if service.pid?
end
end
unless keep
rm service.dest if service.dest.exist?
# Run daemon-reload on systemctl to finish unloading stopped and deleted service.
System::Systemctl.run(*systemctl_args, "daemon-reload") if System.systemctl?
end
if service.loaded? || service.pid?
opoo "Unable to stop `#{service.name}` (label: #{service.service_name})"
else
ohai "Successfully stopped `#{service.name}` (label: #{service.service_name})"
end
end
end
# Stop a service but keep it registered.
sig { params(targets: T::Array[Services::FormulaWrapper], verbose: T::Boolean).void }
def self.kill(targets, verbose: false)
targets.each do |service|
if !service.pid?
puts "Service `#{service.name}` is not started."
elsif service.keep_alive?
puts "Service `#{service.name}` is set to automatically restart and can't be killed."
else
puts "Killing `#{service.name}`... (might take a while)"
if System.systemctl?
System::Systemctl.quiet_run("stop", service.service_name)
elsif System.launchctl?
System.candidate_domain_targets.each do |domain_target|
break unless service.pid?
quiet_system System.launchctl, "stop", "#{domain_target}/#{service.service_name}"
service.reset_cache!
end
end
if service.pid?
opoo "Unable to kill `#{service.name}` (label: #{service.service_name})"
else
ohai "Successfully killed `#{service.name}` (label: #{service.service_name})"
end
end
end
end
# protections to avoid users editing root services
sig { params(service: Services::FormulaWrapper).returns(T::Boolean) }
def self.take_root_ownership?(service)
return false unless System.root?
return false if sudo_service_user
root_paths = T.let([], T::Array[Pathname])
if System.systemctl?
group = "root"
elsif System.launchctl?
group = "admin"
chown "root", group, service.dest
plist_data = service.dest.read
plist = begin
Plist.parse_xml(plist_data, marshal: false)
rescue
nil
end
return false unless plist
program_location = plist["ProgramArguments"]&.first
key = "first ProgramArguments value"
if program_location.blank?
program_location = plist["Program"]
key = "Program"
end
if program_location.present?
Dir.chdir("/") do
if File.exist?(program_location)
program_location_path = Pathname(program_location).realpath
root_paths += [
program_location_path,
program_location_path.parent.realpath,
]
else
opoo <<~EOS
#{service.name}: the #{key} does not exist:
#{program_location}
EOS
end
end
end
end
if (formula = service.formula)
root_paths += [
formula.opt_prefix,
formula.linked_keg,
formula.bin,
formula.sbin,
]
end
root_paths = root_paths.sort.uniq.select(&:exist?)
opoo <<~EOS
Taking root:#{group} ownership of some #{service.formula} paths:
#{root_paths.join("\n ")}
This will require manual removal of these paths using `sudo rm` on
brew upgrade/reinstall/uninstall.
EOS
chown "root", group, root_paths
chmod "+t", root_paths
true
end
sig {
params(
service: Services::FormulaWrapper,
file: T.nilable(T.any(String, Pathname)),
enable: T::Boolean,
).void
}
def self.launchctl_load(service, file:, enable:)
safe_system System.launchctl, "enable", "#{System.domain_target}/#{service.service_name}" if enable
safe_system System.launchctl, "bootstrap", System.domain_target, file
end
sig { params(service: Services::FormulaWrapper, enable: T::Boolean).void }
def self.systemd_load(service, enable:)
System::Systemctl.run("start", service.service_name)
System::Systemctl.run("enable", service.service_name) if enable
end
sig { params(service: Services::FormulaWrapper, file: T.nilable(Pathname), enable: T::Boolean).void }
def self.service_load(service, file, enable:)
if System.root? && !service.service_startup?
opoo "#{service.name} must be run as non-root to start at user login!"
elsif !System.root? && service.service_startup?
opoo "#{service.name} must be run as root to start at system startup!"
end
if System.launchctl?
file ||= enable ? service.dest : service.service_file
launchctl_load(service, file:, enable:)
elsif System.systemctl?
# Systemctl loads based upon location so only install service
# file when it is not installed. Used with the `run` command.
install_service_file(service, file) unless service.dest.exist?
systemd_load(service, enable:)
end
function = enable ? "started" : "ran"
ohai("Successfully #{function} `#{service.name}` (label: #{service.service_name})")
end
sig { params(service: Services::FormulaWrapper, file: T.nilable(Pathname)).void }
def self.install_service_file(service, file)
raise UsageError, "Formula `#{service.name}` is not installed." unless service.installed?
unless service.service_file.exist?
raise UsageError,
"Formula `#{service.name}` has not implemented #plist, #service or provided a locatable service file."
end
temp = Tempfile.new(service.service_name)
temp << if file.blank?
contents = service.service_file.read
if sudo_service_user && System.launchctl?
# set the username in the new plist file
ohai "Setting username in #{service.service_name} to: #{System.user}"
plist_data = Plist.parse_xml(contents, marshal: false)
plist_data["UserName"] = sudo_service_user
plist_data.to_plist
else
contents
end
else
file.read
end
temp.flush
rm service.dest if service.dest.exist?
service.dest_dir.mkpath unless service.dest_dir.directory?
cp T.must(temp.path), service.dest
# Clear tempfile.
temp.close
chmod 0644, service.dest
System::Systemctl.run("daemon-reload") if System.systemctl?
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/services/system.rb | Library/Homebrew/services/system.rb | # typed: strict
# frozen_string_literal: true
require_relative "system/systemctl"
require "utils/output"
module Homebrew
module Services
module System
extend Utils::Output::Mixin
LAUNCHCTL_DOMAIN_ACTION_NOT_SUPPORTED = T.let(125, Integer)
MISSING_DAEMON_MANAGER_EXCEPTION_MESSAGE = T.let(
"`brew services` is supported only on macOS or Linux (with systemd)!",
String,
)
# Path to launchctl binary.
sig { returns(T.nilable(Pathname)) }
def self.launchctl
@launchctl ||= T.let(which("launchctl"), T.nilable(Pathname))
end
# Is this a launchctl system
sig { returns(T::Boolean) }
def self.launchctl?
launchctl.present?
end
# Is this a systemd system
sig { returns(T::Boolean) }
def self.systemctl?
Systemctl.executable.present?
end
# Woohoo, we are root dude!
sig { returns(T::Boolean) }
def self.root?
Process.euid.zero?
end
# Current user running `[sudo] brew services`.
sig { returns(T.nilable(String)) }
def self.user
@user ||= T.let(ENV["USER"].presence || Utils.safe_popen_read("/usr/bin/whoami").chomp, T.nilable(String))
end
sig { params(pid: T.nilable(Integer)).returns(T.nilable(String)) }
def self.user_of_process(pid)
if pid.nil? || pid.zero?
user
else
Utils.safe_popen_read("ps", "-o", "user", "-p", pid.to_s).lines.second&.chomp
end
end
# Run at boot.
sig { returns(Pathname) }
def self.boot_path
if launchctl?
Pathname.new("/Library/LaunchDaemons")
elsif systemctl?
Pathname.new("/usr/lib/systemd/system")
else
raise UsageError, MISSING_DAEMON_MANAGER_EXCEPTION_MESSAGE
end
end
# Run at login.
sig { returns(Pathname) }
def self.user_path
if launchctl?
Pathname.new("#{Dir.home}/Library/LaunchAgents")
elsif systemctl?
Pathname.new("#{Dir.home}/.config/systemd/user")
else
raise UsageError, MISSING_DAEMON_MANAGER_EXCEPTION_MESSAGE
end
end
# If root, return `boot_path`, else return `user_path`.
sig { returns(Pathname) }
def self.path
root? ? boot_path : user_path
end
sig { returns(String) }
def self.domain_target
if root?
"system"
elsif (ssh_tty = ENV.fetch("HOMEBREW_SSH_TTY", nil).present? &&
File.stat("/dev/console").uid != Process.uid) ||
(sudo_user = ENV.fetch("HOMEBREW_SUDO_USER", nil).present?) ||
(Process.uid != Process.euid)
if @output_warning.blank? && ENV.fetch("HOMEBREW_SERVICES_NO_DOMAIN_WARNING", nil).blank?
if ssh_tty
opoo "running over SSH without /dev/console ownership, using user/* instead of gui/* domain!"
elsif sudo_user
opoo "running through sudo, using user/* instead of gui/* domain!"
else
opoo "uid and euid do not match, using user/* instead of gui/* domain!"
end
unless Homebrew::EnvConfig.no_env_hints?
puts "Hide this warning by setting `HOMEBREW_SERVICES_NO_DOMAIN_WARNING=1`."
puts "Hide these hints with `HOMEBREW_NO_ENV_HINTS=1` (see `man brew`)."
end
@output_warning = T.let(true, T.nilable(TrueClass))
end
"user/#{Process.euid}"
else
"gui/#{Process.uid}"
end
end
sig { returns(T::Array[String]) }
def self.candidate_domain_targets
candidates = [domain_target]
candidates += ["user/#{Process.euid}", "gui/#{Process.uid}"] unless root?
candidates.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/services/formula_wrapper.rb | Library/Homebrew/services/formula_wrapper.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
# Wrapper for a formula to handle service-related stuff like parsing and
# generating the service/plist files.
module Homebrew
module Services
class FormulaWrapper
include Utils::Output::Mixin
# Access the `Formula` instance.
sig { returns(Formula) }
attr_reader :formula
# Create a new `Service` instance from either a path or label.
sig { params(path_or_label: T.any(Pathname, String)).returns(T.nilable(FormulaWrapper)) }
def self.from(path_or_label)
return unless path_or_label =~ path_or_label_regex
begin
new(Formulary.factory(T.must(Regexp.last_match(1))))
rescue
nil
end
end
# Initialize a new `Service` instance with supplied formula.
sig { params(formula: Formula).void }
def initialize(formula)
@formula = formula
@status_output_success_type = T.let(nil, T.nilable(StatusOutputSuccessType))
return if System.launchctl? || System.systemctl?
raise UsageError, System::MISSING_DAEMON_MANAGER_EXCEPTION_MESSAGE
end
# Delegate access to `formula.name`.
sig { returns(String) }
def name
@name ||= T.let(formula.name, T.nilable(String))
end
# Delegate access to `formula.service?`.
sig { returns(T::Boolean) }
def service?
@service ||= T.let(formula.service?, T.nilable(T::Boolean))
end
# Delegate access to `formula.service.timed?`.
# TODO: this should either be T::Boolean or renamed to `timed`
sig { returns(T.nilable(T::Boolean)) }
def timed?
@timed ||= T.let((load_service.timed? if service?), T.nilable(T::Boolean))
end
# Delegate access to `formula.service.keep_alive?`.
# TODO: this should either be T::Boolean or renamed to `keep_alive`
sig { returns(T.nilable(T::Boolean)) }
def keep_alive?
@keep_alive ||= T.let((load_service.keep_alive? if service?), T.nilable(T::Boolean))
end
# service_name delegates with formula.plist_name or formula.service_name
# for systemd (e.g., `homebrew.<formula>`).
sig { returns(String) }
def service_name
@service_name ||= T.let(
if System.launchctl?
formula.plist_name
else # System.systemctl?
formula.service_name
end, T.nilable(String)
)
end
# service_file delegates with formula.launchd_service_path or formula.systemd_service_path for systemd.
sig { returns(Pathname) }
def service_file
@service_file ||= T.let(
if System.launchctl?
formula.launchd_service_path
else # System.systemctl?
formula.systemd_service_path
end, T.nilable(Pathname)
)
end
# Whether the service should be launched at startup
sig { returns(T::Boolean) }
def service_startup?
@service_startup ||= T.let(
if service?
load_service.requires_root?
else
false
end, T.nilable(T::Boolean)
)
end
# Path to destination service directory. If run as root, it's `boot_path`, else `user_path`.
sig { returns(Pathname) }
def dest_dir
System.root? ? System.boot_path : System.user_path
end
# Path to destination service. If run as root, it's in `boot_path`, else `user_path`.
sig { returns(Pathname) }
def dest
dest_dir + service_file.basename
end
# Returns `true` if any version of the formula is installed.
sig { returns(T::Boolean) }
def installed?
formula.any_version_installed?
end
# Returns `true` if the plist file exists.
sig { returns(T::Boolean) }
def plist?
return false unless installed?
return true if service_file.file?
return false unless formula.opt_prefix.exist?
return true if Keg.for(formula.opt_prefix).plist_installed?
false
rescue NotAKegError
false
end
sig { void }
def reset_cache!
@status_output_success_type = nil
end
# Returns `true` if the service is loaded, else false.
sig { params(cached: T::Boolean).returns(T::Boolean) }
def loaded?(cached: false)
if System.launchctl?
reset_cache! unless cached
status_success
else # System.systemctl?
System::Systemctl.quiet_run("status", service_file.basename)
end
end
# Returns `true` if service is present (e.g. .plist is present in boot or user service path), else `false`
# Accepts `type` with values `:root` for boot path or `:user` for user path.
sig { params(type: T.nilable(Symbol)).returns(T::Boolean) }
def service_file_present?(type: nil)
case type
when :root
boot_path_service_file_present?
when :user
user_path_service_file_present?
else
boot_path_service_file_present? || user_path_service_file_present?
end
end
sig { returns(T.nilable(String)) }
def owner
if System.launchctl? && dest.exist?
# read the username from the plist file
plist = begin
Plist.parse_xml(dest.read, marshal: false)
rescue
nil
end
plist_username = plist["UserName"] if plist
return plist_username if plist_username.present?
end
return "root" if boot_path_service_file_present?
return System.user if user_path_service_file_present?
nil
end
sig { returns(T::Boolean) }
def pid?
(pid = self.pid).present? && pid.positive?
end
sig { returns(T::Boolean) }
def error?
return false if pid?
(exit_code = self.exit_code).present? && !exit_code.zero?
end
sig { returns(T::Boolean) }
def unknown_status?
status_output.blank? && !pid?
end
# Get current PID of daemon process from status output.
sig { returns(T.nilable(Integer)) }
def pid
Regexp.last_match(1).to_i if status_output =~ pid_regex(status_type)
end
# Get current exit code of daemon process from status output.
sig { returns(T.nilable(Integer)) }
def exit_code
Regexp.last_match(1).to_i if status_output =~ exit_code_regex(status_type)
end
sig { returns(T.nilable(String)) }
def loaded_file
Regexp.last_match(1) if status_output =~ loaded_file_regex(status_type)
end
sig { returns(T::Hash[Symbol, T.anything]) }
def to_hash
hash = {
name:,
service_name:,
running: pid?,
loaded: loaded?(cached: true),
schedulable: timed?,
pid:,
exit_code:,
user: owner,
status: status_symbol,
file: service_file_present? ? dest : service_file,
registered: service_file_present?,
loaded_file:,
}
return hash unless service?
service = load_service
return hash if service.command.blank?
hash[:command] = service.manual_command
hash[:working_dir] = service.working_dir
hash[:root_dir] = service.root_dir
hash[:log_path] = service.log_path
hash[:error_log_path] = service.error_log_path
hash[:interval] = service.interval
hash[:cron] = service.cron.presence
hash
end
private
# The purpose of this function is to lazy load the Homebrew::Service class
# and avoid nameclashes with the current Service module.
# It should be used instead of calling formula.service directly.
sig { returns(Homebrew::Service) }
def load_service
require "formula"
formula.service
end
sig { returns(StatusOutputSuccessType) }
def status_output_success_type
@status_output_success_type ||= if System.launchctl?
cmd = [System.launchctl.to_s, "print", "#{System.domain_target}/#{service_name}"]
output = Utils.popen_read(*cmd).chomp
if $CHILD_STATUS.present? && $CHILD_STATUS.success? && output.present?
success = true
type = :launchctl_print
else
cmd = [System.launchctl.to_s, "list", service_name]
output = Utils.popen_read(*cmd).chomp
success = T.cast($CHILD_STATUS.present? && $CHILD_STATUS.success? && output.present?, T::Boolean)
type = :launchctl_list
end
odebug cmd.join(" "), output
StatusOutputSuccessType.new(output, success, type)
else # System.systemctl?
cmd = ["status", service_name]
output = System::Systemctl.popen_read(*cmd).chomp
success = T.cast($CHILD_STATUS.present? && $CHILD_STATUS.success? && output.present?, T::Boolean)
odebug [System::Systemctl.executable, System::Systemctl.scope, *cmd].join(" "), output
StatusOutputSuccessType.new(output, success, :systemctl)
end
end
sig { returns(String) }
def status_output
status_output_success_type.output
end
sig { returns(T::Boolean) }
def status_success
status_output_success_type.success
end
sig { returns(Symbol) }
def status_type
status_output_success_type.type
end
sig { returns(Symbol) }
def status_symbol
if pid?
:started
elsif !loaded?(cached: true)
:none
elsif (exit_code = self.exit_code).present? && exit_code.zero?
if timed?
:scheduled
else
:stopped
end
elsif error?
:error
elsif unknown_status?
:unknown
else
:other
end
end
sig { params(status_type: Symbol).returns(Regexp) }
def exit_code_regex(status_type)
@exit_code_regex ||= T.let({
launchctl_list: /"LastExitStatus"\ =\ ([0-9]*);/,
launchctl_print: /last exit code = ([0-9]+)/,
systemctl: /\(code=exited, status=([0-9]*)\)|\(dead\)/,
}, T.nilable(T::Hash[Symbol, Regexp]))
@exit_code_regex.fetch(status_type)
end
sig { params(status_type: Symbol).returns(Regexp) }
def pid_regex(status_type)
@pid_regex ||= T.let({
launchctl_list: /"PID"\ =\ ([0-9]*);/,
launchctl_print: /pid = ([0-9]+)/,
systemctl: /Main PID: ([0-9]*) \((?!code=)/,
}, T.nilable(T::Hash[Symbol, Regexp]))
@pid_regex.fetch(status_type)
end
sig { params(status_type: Symbol).returns(Regexp) }
def loaded_file_regex(status_type)
@loaded_file_regex ||= T.let({
launchctl_list: //, # not available
launchctl_print: /path = (.*)/,
systemctl: /Loaded: .*? \((.*);/,
}, T.nilable(T::Hash[Symbol, Regexp]))
@loaded_file_regex.fetch(status_type)
end
sig { returns(T::Boolean) }
def boot_path_service_file_present?
boot_path = System.boot_path
return false if boot_path.blank?
(boot_path + service_file.basename).exist?
end
sig { returns(T::Boolean) }
def user_path_service_file_present?
user_path = System.user_path
return false if user_path.blank?
(user_path + service_file.basename).exist?
end
sig { returns(Regexp) }
private_class_method def self.path_or_label_regex
/homebrew(?>\.mxcl)?\.([\w+-.@]+)(\.plist|\.service)?\z/
end
class StatusOutputSuccessType
sig { returns(String) }
attr_reader :output
sig { returns(T::Boolean) }
attr_reader :success
sig { returns(Symbol) }
attr_reader :type
sig { params(output: String, success: T::Boolean, type: Symbol).void }
def initialize(output, success, type)
@output = output
@success = success
@type = type
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/services/formulae.rb | Library/Homebrew/services/formulae.rb | # typed: strict
# frozen_string_literal: true
require "services/formula_wrapper"
module Homebrew
module Services
module Formulae
# All available services, with optional filters applied
# @private
sig { params(loaded: T.nilable(T::Boolean), skip_root: T::Boolean).returns(T::Array[Services::FormulaWrapper]) }
def self.available_services(loaded: nil, skip_root: false)
require "formula"
formulae = Formula.installed
.map { |formula| FormulaWrapper.new(formula) }
.select(&:service?)
.sort_by(&:name)
formulae = formulae.select { |formula| formula.loaded? == loaded } unless loaded.nil?
formulae = formulae.reject { |formula| formula.owner == "root" } if skip_root
formulae
end
# List all available services with status, user, and path to the file.
sig { returns(T::Array[T::Hash[Symbol, T.anything]]) }
def self.services_list
available_services.map(&:to_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/services/system/systemctl.rb | Library/Homebrew/services/system/systemctl.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Services
module System
module Systemctl
sig { returns(T.nilable(Pathname)) }
def self.executable
@executable ||= T.let(which("systemctl"), T.nilable(Pathname))
end
sig { void }
def self.reset_executable!
@executable = nil
end
sig { returns(String) }
def self.scope
System.root? ? "--system" : "--user"
end
sig { params(args: T.any(String, Pathname)).void }
def self.run(*args)
_run(*args, mode: :default)
end
sig { params(args: T.any(String, Pathname)).returns(T::Boolean) }
def self.quiet_run(*args)
_run(*args, mode: :quiet)
end
sig { params(args: T.any(String, Pathname)).returns(String) }
def self.popen_read(*args)
_run(*args, mode: :read)
end
sig { params(args: T.any(String, Pathname), mode: Symbol).returns(T.nilable(T.any(String, T::Boolean))) }
private_class_method def self._run(*args, mode:)
require "system_command"
result = SystemCommand.run(T.must(executable),
args: [scope, *args.map(&:to_s)],
print_stdout: mode == :default,
print_stderr: mode == :default,
must_succeed: mode == :default,
reset_uid: true)
if mode == :read
result.stdout
elsif mode == :quiet
result.success?
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/services/commands/start.rb | Library/Homebrew/services/commands/start.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
module Homebrew
module Services
module Commands
module Start
TRIGGERS = %w[start launch load s l].freeze
sig {
params(
targets: T::Array[Services::FormulaWrapper],
custom_plist: T.nilable(String),
verbose: T::Boolean,
).void
}
def self.run(targets, custom_plist, verbose:)
Services::Cli.check!(targets)
Services::Cli.start(targets, custom_plist, verbose:)
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/services/commands/cleanup.rb | Library/Homebrew/services/commands/cleanup.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
module Homebrew
module Services
module Commands
module Cleanup
TRIGGERS = %w[cleanup clean cl rm].freeze
sig { void }
def self.run
cleaned = []
cleaned += Services::Cli.kill_orphaned_services
cleaned += Services::Cli.remove_unused_service_files
puts "All #{System.root? ? "root" : "user-space"} services OK, nothing cleaned..." if cleaned.empty?
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/services/commands/info.rb | Library/Homebrew/services/commands/info.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
module Homebrew
module Services
module Commands
module Info
TRIGGERS = %w[info i].freeze
sig {
params(
targets: T::Array[Services::FormulaWrapper],
verbose: T::Boolean,
json: T::Boolean,
).void
}
def self.run(targets, verbose:, json:)
Services::Cli.check!(targets)
output = targets.map(&:to_hash)
if json
puts JSON.pretty_generate(output)
return
end
output.each do |hash|
puts output(hash, verbose:)
end
end
sig { params(bool: T.nilable(T.any(String, T::Boolean))).returns(String) }
def self.pretty_bool(bool)
return bool.to_s if !$stdout.tty? || Homebrew::EnvConfig.no_emoji?
if bool
"#{Tty.bold}#{Formatter.success("✔")}#{Tty.reset}"
else
"#{Tty.bold}#{Formatter.error("✘")}#{Tty.reset}"
end
end
sig { params(hash: T::Hash[Symbol, T.untyped], verbose: T::Boolean).returns(String) }
def self.output(hash, verbose:)
out = "#{Tty.bold}#{hash[:name]}#{Tty.reset} (#{hash[:service_name]})\n"
out += "Running: #{pretty_bool(hash[:running])}\n"
out += "Loaded: #{pretty_bool(hash[:loaded])}\n"
out += "Schedulable: #{pretty_bool(hash[:schedulable])}\n"
out += "User: #{hash[:user]}\n" unless hash[:pid].nil?
out += "PID: #{hash[:pid]}\n" unless hash[:pid].nil?
return out unless verbose
out += "File: #{hash[:file]} #{pretty_bool(hash[:file].present?)}\n"
out += "Registered at login: #{pretty_bool(hash[:registered])}\n"
out += "Command: #{hash[:command]}\n" unless hash[:command].nil?
out += "Working directory: #{hash[:working_dir]}\n" unless hash[:working_dir].nil?
out += "Root directory: #{hash[:root_dir]}\n" unless hash[:root_dir].nil?
out += "Log: #{hash[:log_path]}\n" unless hash[:log_path].nil?
out += "Error log: #{hash[:error_log_path]}\n" unless hash[:error_log_path].nil?
out += "Interval: #{hash[:interval]}s\n" unless hash[:interval].nil?
out += "Cron: #{hash[:cron]}\n" unless hash[:cron].nil?
out
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/services/commands/list.rb | Library/Homebrew/services/commands/list.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
require "services/formulae"
require "utils/output"
module Homebrew
module Services
module Commands
module List
extend Utils::Output::Mixin
TRIGGERS = T.let([nil, "list", "ls"].freeze, T::Array[T.nilable(String)])
sig { params(json: T::Boolean).void }
def self.run(json: false)
formulae = Formulae.services_list
if formulae.blank?
opoo "No services available to control with `#{Services::Cli.bin}`" if $stderr.tty?
return
end
if json
print_json(formulae)
else
print_table(formulae)
end
end
JSON_FIELDS = T.let([:name, :status, :user, :file, :exit_code].freeze, T::Array[Symbol])
# Print the JSON representation in the CLI
# @private
sig { params(formulae: T::Array[T::Hash[Symbol, T.untyped]]).void }
def self.print_json(formulae)
services = formulae.map do |formula|
formula.slice(*JSON_FIELDS)
end
puts JSON.pretty_generate(services)
end
# Print the table in the CLI
# @private
sig { params(formulae: T::Array[T::Hash[Symbol, T.untyped]]).void }
def self.print_table(formulae)
services = formulae.map do |formula|
status = T.must(get_status_string(formula[:status]))
status += formula[:exit_code].to_s if formula[:status] == :error
file = formula[:file].to_s.gsub(Dir.home, "~").presence if formula[:loaded]
{ name: formula[:name], status:, user: formula[:user], file: }
end
longest_name = [*services.map { |service| service[:name].length }, 4].max
longest_status = [*services.map { |service| service[:status].length }, 15].max
longest_user = [*services.map { |service| service[:user]&.length }, 4].compact.max
# `longest_status` includes 9 color characters from `Tty.color` and `Tty.reset`.
# We don't have these in the header row, so we don't need to add the extra padding.
headers = "#{Tty.bold}%-#{longest_name}.#{longest_name}<name>s " \
"%-#{longest_status - 9}.#{longest_status - 9}<status>s " \
"%-#{longest_user}.#{longest_user}<user>s %<file>s#{Tty.reset}"
row = "%-#{longest_name}.#{longest_name}<name>s " \
"%-#{longest_status}.#{longest_status}<status>s " \
"%-#{longest_user}.#{longest_user}<user>s %<file>s"
puts format(headers, name: "Name", status: "Status", user: "User", file: "File")
services.each do |service|
puts format(row, **service)
end
end
# Get formula status output
# @private
sig { params(status: Symbol).returns(T.nilable(String)) }
def self.get_status_string(status)
case status
when :started, :scheduled then "#{Tty.green}#{status}#{Tty.reset}"
when :stopped, :none then "#{Tty.default}#{status}#{Tty.reset}"
when :error then "#{Tty.red}error #{Tty.reset}"
when :unknown then "#{Tty.yellow}unknown#{Tty.reset}"
when :other then "#{Tty.yellow}other#{Tty.reset}"
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/services/commands/stop.rb | Library/Homebrew/services/commands/stop.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
module Homebrew
module Services
module Commands
module Stop
TRIGGERS = %w[stop unload terminate term t u].freeze
sig {
params(
targets: T::Array[Services::FormulaWrapper],
verbose: T::Boolean,
no_wait: T::Boolean,
max_wait: T.nilable(Float),
keep: T::Boolean,
).void
}
def self.run(targets, verbose:, no_wait:, max_wait:, keep:)
Services::Cli.check!(targets)
Services::Cli.stop(targets, verbose:, no_wait:, max_wait:, keep:)
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/services/commands/run.rb | Library/Homebrew/services/commands/run.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
module Homebrew
module Services
module Commands
module Run
TRIGGERS = ["run"].freeze
sig {
params(
targets: T::Array[Services::FormulaWrapper],
custom_plist: T.nilable(String),
verbose: T::Boolean,
).void
}
def self.run(targets, custom_plist, verbose:)
Services::Cli.check!(targets)
Services::Cli.run(targets, custom_plist, verbose:)
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/services/commands/kill.rb | Library/Homebrew/services/commands/kill.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
module Homebrew
module Services
module Commands
module Kill
TRIGGERS = %w[kill k].freeze
sig { params(targets: T::Array[Services::FormulaWrapper], verbose: T::Boolean).void }
def self.run(targets, verbose:)
Services::Cli.check!(targets)
Services::Cli.kill(targets, verbose:)
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.