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/services/commands/restart.rb | Library/Homebrew/services/commands/restart.rb | # typed: strict
# frozen_string_literal: true
require "services/cli"
module Homebrew
module Services
module Commands
module Restart
# NOTE: The restart command is used to update service files
# after a package gets updated through `brew upgrade`.
# This works by removing the old file with `brew services stop`
# and installing the new one with `brew services start|run`.
TRIGGERS = %w[restart relaunch reload r].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)
ran = []
started = []
targets.each do |service|
if service.loaded? && !service.service_file_present?
ran << service
else
# group not-started services with started ones for restart
started << service
end
Services::Cli.stop([service], verbose:) if service.loaded?
end
Services::Cli.run(targets, custom_plist, verbose:) if ran.present?
Services::Cli.start(started, custom_plist, verbose:) if started.present?
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/cmd/command.rb | Library/Homebrew/cmd/command.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "commands"
module Homebrew
module Cmd
class Command < AbstractCommand
cmd_args do
description <<~EOS
Display the path to the file being used when invoking `brew` <cmd>.
EOS
named_args :command, min: 1
end
sig { override.void }
def run
args.named.each do |cmd|
path = Commands.path(cmd)
odie "Unknown command: brew #{cmd}" unless path
puts path
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/cmd/gist-logs.rb | Library/Homebrew/cmd/gist-logs.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "install"
require "system_config"
require "stringio"
require "socket"
module Homebrew
module Cmd
class GistLogs < AbstractCommand
include Install
cmd_args do
description <<~EOS
Upload logs for a failed build of <formula> to a new Gist. Presents an
error message if no logs are found.
EOS
switch "--with-hostname",
description: "Include the hostname in the Gist."
switch "-n", "--new-issue",
description: "Automatically create a new issue in the appropriate GitHub repository " \
"after creating the Gist."
switch "-p", "--private",
description: "The Gist will be marked private and will not appear in listings but will " \
"be accessible with its link."
named_args :formula, number: 1
end
sig { override.void }
def run
Install.perform_preinstall_checks_once(all_fatal: true)
Install.perform_build_from_source_checks(all_fatal: true)
return unless (formula = args.named.to_resolved_formulae.first)
gistify_logs(formula)
end
private
sig { params(formula: Formula).void }
def gistify_logs(formula)
files = load_logs(formula.logs)
build_time = formula.logs.ctime
timestamp = build_time.strftime("%Y-%m-%d_%H-%M-%S")
s = StringIO.new
SystemConfig.dump_verbose_config s
# Dummy summary file, asciibetically first, to control display title of gist
files["# #{formula.name} - #{timestamp}.txt"] = {
content: brief_build_info(formula, with_hostname: args.with_hostname?),
}
files["00.config.out"] = { content: s.string }
files["00.doctor.out"] = { content: Utils.popen_read("#{HOMEBREW_PREFIX}/bin/brew", "doctor", err: :out) }
unless formula.core_formula?
tap = <<~EOS
Formula: #{formula.name}
Tap: #{formula.tap}
Path: #{formula.path}
EOS
files["00.tap.out"] = { content: tap }
end
if GitHub::API.credentials_type == :none
odie "`brew gist-logs` requires `$HOMEBREW_GITHUB_API_TOKEN` to be set!"
end
# Description formatted to work well as page title when viewing gist
descr = if formula.core_formula?
"#{formula.name} on #{OS_VERSION} - Homebrew build logs"
else
"#{formula.name} (#{formula.full_name}) on #{OS_VERSION} - Homebrew build logs"
end
begin
url = GitHub.create_gist(files, descr, private: args.private?)
rescue GitHub::API::HTTPNotFoundError
odie <<~EOS
Your GitHub API token likely doesn't have the `gist` scope.
#{GitHub.pat_blurb(GitHub::CREATE_GIST_SCOPES)}
EOS
end
if args.new_issue?
url = GitHub.create_issue(formula.tap, "#{formula.name} failed to build on #{OS_VERSION}",
url)
end
puts url if url
end
sig { params(formula: Formula, with_hostname: T::Boolean).returns(String) }
def brief_build_info(formula, with_hostname:)
build_time_string = formula.logs.ctime.strftime("%Y-%m-%d %H:%M:%S")
string = <<~EOS
Homebrew build logs for #{formula.full_name} on #{OS_VERSION}
EOS
if with_hostname
hostname = Socket.gethostname
string << "Host: #{hostname}\n"
end
string << "Build date: #{build_time_string}\n"
string.freeze
end
# Causes some terminals to display secure password entry indicators.
sig { void }
def noecho_gets
system "stty", "-echo"
result = $stdin.gets
system "stty", "echo"
puts
result
end
sig { params(dir: Pathname, basedir: Pathname).returns(T::Hash[String, T::Hash[Symbol, String]]) }
def load_logs(dir, basedir = dir)
logs = {}
if dir.exist?
dir.children.sort.each do |file|
if file.directory?
logs.merge! load_logs(file, basedir)
else
contents = file.size? ? file.read : "empty log"
# small enough to avoid GitHub "unicorn" page-load-timeout errors
max_file_size = 1_000_000
contents = truncate_text_to_approximate_size(contents, max_file_size, front_weight: 0.2)
logs[file.relative_path_from(basedir).to_s.tr("/", ":")] = { content: contents }
end
end
end
odie "No logs." if logs.empty?
logs
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/cmd/readall.rb | Library/Homebrew/cmd/readall.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "readall"
require "env_config"
module Homebrew
module Cmd
class ReadallCmd < AbstractCommand
cmd_args do
description <<~EOS
Import all items from the specified <tap>, or from all installed taps if none is provided.
This can be useful for debugging issues across all items when making
significant changes to `formula.rb`, testing the performance of loading
all items or checking if any current formulae/casks have Ruby issues.
EOS
flag "--os=",
description: "Read using the given operating system. (Pass `all` to simulate all operating systems.)"
flag "--arch=",
description: "Read using the given CPU architecture. (Pass `all` to simulate all architectures.)"
switch "--aliases",
description: "Verify any alias symlinks in each tap."
switch "--syntax",
description: "Syntax-check all of Homebrew's Ruby files (if no <tap> is passed)."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not.",
env: :eval_all
switch "--no-simulate",
description: "Don't simulate other system configurations when checking formulae and casks."
named_args :tap
end
sig { override.void }
def run
Homebrew.with_no_api_env do
if args.syntax? && args.no_named?
scan_files = "#{HOMEBREW_LIBRARY_PATH}/**/*.rb"
ruby_files = Dir.glob(scan_files).grep_v(%r{/(vendor)/})
Homebrew.failed = true unless Readall.valid_ruby_syntax?(ruby_files)
end
options = {
aliases: args.aliases?,
no_simulate: args.no_simulate?,
}
options[:os_arch_combinations] = args.os_arch_combinations if args.os || args.arch
taps = if args.no_named?
unless args.eval_all?
raise UsageError, "`brew readall` needs a tap or `--eval-all` passed or `HOMEBREW_EVAL_ALL=1` set!"
end
Tap.installed
else
args.named.to_installed_taps
end
taps.each do |tap|
Homebrew.failed = true unless Readall.valid_tap?(tap, **options)
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/cmd/vendor-install.rb | Library/Homebrew/cmd/vendor-install.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class VendorInstall < AbstractCommand
include ShellCommand
cmd_args do
description <<~EOS
Install Homebrew's portable Ruby.
EOS
named_args :target
hide_from_man_page!
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/cmd/update-reset.rb | Library/Homebrew/cmd/update-reset.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class UpdateReset < AbstractCommand
include ShellCommand
cmd_args do
description <<~EOS
Fetch and reset Homebrew and all tap repositories (or any specified <repository>) using `git`(1) to their latest `origin/HEAD`.
*Note:* this will destroy all your uncommitted or committed changes.
EOS
named_args :repository
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/source.rb | Library/Homebrew/cmd/source.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module Cmd
class Source < AbstractCommand
cmd_args do
description <<~EOS
Open a <formula>'s source repository in a browser, or open
Homebrew's own repository if no argument is provided.
The repository URL is determined from the formula's head URL,
stable URL, or homepage. Supports GitHub, GitLab, Bitbucket, Codeberg and
SourceHut repositories.
EOS
named_args :formula
end
sig { override.void }
def run
if args.no_named?
exec_browser "https://github.com/Homebrew/brew"
return
end
formulae = args.named.to_formulae
repo_urls = formulae.filter_map do |formula|
repo_url = extract_repo_url(formula)
if repo_url
puts "Opening repository for #{formula.name}"
repo_url
else
opoo "Could not determine repository URL for #{formula.name}"
nil
end
end
return if repo_urls.empty?
exec_browser(*repo_urls)
end
private
sig { params(formula: Formula).returns(T.nilable(String)) }
def extract_repo_url(formula)
urls_to_check = [
formula.head&.url,
formula.stable&.url,
formula.homepage,
]
urls_to_check.each do |url|
next if url.nil?
repo_url = url_to_repo(url)
return repo_url if repo_url
end
nil
end
sig { params(url: String).returns(T.nilable(String)) }
def url_to_repo(url)
github_repo_url(url) ||
gitlab_repo_url(url) ||
bitbucket_repo_url(url) ||
codeberg_repo_url(url) ||
sourcehut_repo_url(url)
end
sig { params(url: String).returns(T.nilable(String)) }
def github_repo_url(url)
regex = %r{
https?://github\.com/
(?<user>[\w.-]+)/
(?<repo>[\w.-]+)
(?:/.*)?
}x
match = url.match(regex)
return unless match
user = match[:user]
repo = match[:repo]&.delete_suffix(".git")
"https://github.com/#{user}/#{repo}"
end
sig { params(url: String).returns(T.nilable(String)) }
def gitlab_repo_url(url)
regex = %r{
https?://gitlab\.com/
(?<path>(?:[\w.-]+/)*?[\w.-]+)
(?:/-/|\.git|/archive/)
}x
match = url.match(regex)
return unless match
path = match[:path]&.delete_suffix(".git")
"https://gitlab.com/#{path}"
end
sig { params(url: String).returns(T.nilable(String)) }
def bitbucket_repo_url(url)
regex = %r{
https?://bitbucket\.org/
(?<user>[\w.-]+)/
(?<repo>[\w.-]+)
(?:/.*)?
}x
match = url.match(regex)
return unless match
user = match[:user]
repo = match[:repo]&.delete_suffix(".git")
"https://bitbucket.org/#{user}/#{repo}"
end
sig { params(url: String).returns(T.nilable(String)) }
def codeberg_repo_url(url)
regex = %r{
https?://codeberg\.org/
(?<user>[\w.-]+)/
(?<repo>[\w.-]+)
(?:/.*)?
}x
match = url.match(regex)
return unless match
user = match[:user]
repo = match[:repo]&.delete_suffix(".git")
"https://codeberg.org/#{user}/#{repo}"
end
sig { params(url: String).returns(T.nilable(String)) }
def sourcehut_repo_url(url)
regex = %r{
https?://(?:git\.)?sr\.ht/
~(?<user>[\w.-]+)/
(?<repo>[\w.-]+)
(?:/.*)?
}x
match = url.match(regex)
return unless match
user = match[:user]
repo = match[:repo]&.delete_suffix(".git")
"https://sr.ht/~#{user}/#{repo}"
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/cmd/bundle.rb | Library/Homebrew/cmd/bundle.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class Bundle < AbstractCommand
cmd_args do
usage_banner <<~EOS
`bundle` [<subcommand>]
Bundler for non-Ruby dependencies from Homebrew, Homebrew Cask, Mac App Store, Visual Studio Code (and forks/variants), Go packages, Cargo packages and Flatpak.
Note: Flatpak support is only available on Linux.
`brew bundle` [`install`]:
Install and upgrade (by default) all dependencies from the `Brewfile`.
You can specify the `Brewfile` location using `--file` or by setting the `$HOMEBREW_BUNDLE_FILE` environment variable.
You can skip the installation of dependencies by adding space-separated values to one or more of the following environment variables: `$HOMEBREW_BUNDLE_BREW_SKIP`, `$HOMEBREW_BUNDLE_CASK_SKIP`, `$HOMEBREW_BUNDLE_MAS_SKIP`, `$HOMEBREW_BUNDLE_TAP_SKIP`.
`brew bundle upgrade`:
Shorthand for `brew bundle install --upgrade`.
`brew bundle dump`:
Write all installed casks/formulae/images/taps into a `Brewfile` in the current directory or to a custom file specified with the `--file` option.
`brew bundle cleanup`:
Uninstall all dependencies not present in the `Brewfile`.
This workflow is useful for maintainers or testers who regularly install lots of formulae.
Unless `--force` is passed, this returns a 1 exit code if anything would be removed.
`brew bundle check`:
Check if all dependencies present in the `Brewfile` are installed.
This provides a successful exit code if everything is up-to-date, making it useful for scripting.
`brew bundle list`:
List all dependencies present in the `Brewfile`.
By default, only Homebrew formula dependencies are listed.
`brew bundle edit`:
Edit the `Brewfile` in your editor.
`brew bundle add` <name> [...]:
Add entries to your `Brewfile`. Adds formulae by default. Use `--cask`, `--tap` or `--vscode` to add the corresponding entry instead.
`brew bundle remove` <name> [...]:
Remove entries that match `name` from your `Brewfile`. Use `--formula`, `--cask`, `--tap`, `--mas` or `--vscode` to remove only entries of the corresponding type. Passing `--formula` also removes matches against formula aliases and old formula names.
`brew bundle exec` [`--check`] [`--no-secrets`] <command>:
Run an external command in an isolated build environment based on the `Brewfile` dependencies.
This sanitized build environment ignores unrequested dependencies, which makes sure that things you didn't specify in your `Brewfile` won't get picked up by commands like `bundle install`, `npm install`, etc. It will also add compiler flags which will help with finding keg-only dependencies like `openssl`, `icu4c`, etc.
`brew bundle sh` [`--check`] [`--no-secrets`]:
Run your shell in a `brew bundle exec` environment.
`brew bundle env` [`--check`] [`--no-secrets`]:
Print the environment variables that would be set in a `brew bundle exec` environment.
EOS
flag "--file=",
description: "Read from or write to the `Brewfile` from this location. " \
"Use `--file=-` to pipe to stdin/stdout."
switch "-g", "--global",
description: "Read from or write to the `Brewfile` from `$HOMEBREW_BUNDLE_FILE_GLOBAL` (if set), " \
"`${XDG_CONFIG_HOME}/homebrew/Brewfile` (if `$XDG_CONFIG_HOME` is set), " \
"`~/.homebrew/Brewfile` or `~/.Brewfile` otherwise."
switch "-v", "--verbose",
description: "`install` prints output from commands as they are run. " \
"`check` lists all missing dependencies."
switch "--no-upgrade",
description: "`install` does not run `brew upgrade` on outdated dependencies. " \
"`check` does not check for outdated dependencies. " \
"Note they may still be upgraded by `brew install` if needed.",
env: :bundle_no_upgrade
switch "--upgrade",
description: "`install` runs `brew upgrade` on outdated dependencies, " \
"even if `$HOMEBREW_BUNDLE_NO_UPGRADE` is set."
flag "--upgrade-formulae=", "--upgrade-formula=",
description: "`install` runs `brew upgrade` on any of these comma-separated formulae, " \
"even if `$HOMEBREW_BUNDLE_NO_UPGRADE` is set."
switch "--install",
description: "Run `install` before continuing to other operations, e.g. `exec`."
switch "--services",
description: "Temporarily start services while running the `exec` or `sh` command.",
env: :bundle_services
switch "-f", "--force",
description: "`install` runs with `--force`/`--overwrite`. " \
"`dump` overwrites an existing `Brewfile`. " \
"`cleanup` actually performs its cleanup operations."
switch "--cleanup",
description: "`install` performs cleanup operation, same as running `cleanup --force`.",
env: [:bundle_install_cleanup, "--global"]
switch "--all",
description: "`list` all dependencies."
switch "--formula", "--formulae", "--brews",
description: "`list`, `dump` or `cleanup` Homebrew formula dependencies."
switch "--cask", "--casks",
description: "`list`, `dump` or `cleanup` Homebrew cask dependencies."
switch "--tap", "--taps",
description: "`list`, `dump` or `cleanup` Homebrew tap dependencies."
switch "--mas",
description: "`list` or `dump` Mac App Store dependencies."
switch "--vscode",
description: "`list`, `dump` or `cleanup` VSCode (and forks/variants) extensions."
switch "--go",
description: "`list` or `dump` Go packages."
switch "--cargo",
description: "`list` or `dump` Cargo packages."
switch "--flatpak",
description: "`list` or `dump` Flatpak packages. Note: Linux only."
switch "--no-vscode",
description: "`dump` without VSCode (and forks/variants) extensions.",
env: :bundle_dump_no_vscode
switch "--no-go",
description: "`dump` without Go packages.",
env: :bundle_dump_no_go
switch "--no-cargo",
description: "`dump` without Cargo packages.",
env: :bundle_dump_no_cargo
switch "--no-flatpak",
description: "`dump` without Flatpak packages.",
env: :bundle_dump_no_flatpak
switch "--describe",
description: "`dump` adds a description comment above each line, unless the " \
"dependency does not have a description.",
env: :bundle_dump_describe
switch "--no-restart",
description: "`dump` does not add `restart_service` to formula lines."
switch "--zap",
description: "`cleanup` casks using the `zap` command instead of `uninstall`."
switch "--check",
description: "Check that all dependencies in the Brewfile are installed before " \
"running `exec`, `sh`, or `env`.",
env: :bundle_check
switch "--no-secrets",
description: "Attempt to remove secrets from the environment before `exec`, `sh`, or `env`.",
env: :bundle_no_secrets
conflicts "--all", "--no-vscode"
conflicts "--vscode", "--no-vscode"
conflicts "--all", "--no-go"
conflicts "--go", "--no-go"
conflicts "--all", "--no-cargo"
conflicts "--cargo", "--no-cargo"
conflicts "--all", "--no-flatpak"
conflicts "--flatpak", "--no-flatpak"
conflicts "--install", "--upgrade"
conflicts "--file", "--global"
named_args %w[install dump cleanup check exec list sh env edit]
end
BUNDLE_EXEC_COMMANDS = %w[exec sh env].freeze
sig { override.void }
def run
# Keep this inside `run` to keep --help fast.
require "bundle"
# Don't want to ask for input in Bundle
ENV["HOMEBREW_ASK"] = nil
subcommand = args.named.first.presence
if %w[exec add remove].exclude?(subcommand) && args.named.size > 1
raise UsageError, "This command does not take more than 1 subcommand argument."
end
if args.check? && BUNDLE_EXEC_COMMANDS.exclude?(subcommand)
raise UsageError, "`--check` can be used only with #{BUNDLE_EXEC_COMMANDS.join(", ")}."
end
if args.no_secrets? && BUNDLE_EXEC_COMMANDS.exclude?(subcommand)
raise UsageError, "`--no-secrets` can be used only with #{BUNDLE_EXEC_COMMANDS.join(", ")}."
end
global = args.global?
file = args.file
no_upgrade = if args.upgrade? || subcommand == "upgrade"
false
else
args.no_upgrade?.present?
end
verbose = args.verbose?
force = args.force?
zap = args.zap?
Homebrew::Bundle.upgrade_formulae = args.upgrade_formulae
no_type_args = [args.formulae?, args.casks?, args.taps?, args.mas?, args.vscode?, args.go?,
args.cargo?, args.flatpak?].none?
if args.install?
if [nil, "install", "upgrade"].include?(subcommand)
raise UsageError, "`--install` cannot be used with `install`, `upgrade` or no subcommand."
end
require "bundle/commands/install"
redirect_stdout($stderr) do
Homebrew::Bundle::Commands::Install.run(global:, file:, no_upgrade:, verbose:, force:, quiet: true)
end
end
case subcommand
when nil, "install", "upgrade"
require "bundle/commands/install"
Homebrew::Bundle::Commands::Install.run(global:, file:, no_upgrade:, verbose:, force:, quiet: args.quiet?)
cleanup = if ENV.fetch("HOMEBREW_BUNDLE_INSTALL_CLEANUP", nil)
args.global?
else
args.cleanup?
end
if cleanup
require "bundle/commands/cleanup"
# Don't need to reset cleanup specifically but this resets all the dumper modules.
Homebrew::Bundle::Commands::Cleanup.reset!
Homebrew::Bundle::Commands::Cleanup.run(
global:, file:, zap:,
force: true,
dsl: Homebrew::Bundle::Commands::Install.dsl
)
end
when "dump"
vscode = if args.no_vscode?
false
elsif args.vscode?
true
else
no_type_args
end
go = if args.no_go?
false
elsif args.go?
true
else
no_type_args
end
cargo = if args.no_cargo?
false
elsif args.cargo?
true
else
no_type_args
end
flatpak = if args.no_flatpak?
false
elsif args.flatpak?
true
else
no_type_args
end
require "bundle/commands/dump"
Homebrew::Bundle::Commands::Dump.run(
global:, file:, force:,
describe: args.describe?,
no_restart: args.no_restart?,
taps: args.taps? || no_type_args,
formulae: args.formulae? || no_type_args,
casks: args.casks? || no_type_args,
mas: args.mas? || no_type_args,
vscode:,
go:,
cargo:,
flatpak:
)
when "edit"
require "bundle/brewfile"
exec_editor(Homebrew::Bundle::Brewfile.path(global:, file:))
when "cleanup"
require "bundle/commands/cleanup"
Homebrew::Bundle::Commands::Cleanup.run(
global:, file:, force:, zap:,
formulae: args.formulae? || no_type_args,
casks: args.casks? || no_type_args,
taps: args.taps? || no_type_args,
vscode: args.vscode? || no_type_args,
flatpak: args.flatpak? || no_type_args
)
when "check"
require "bundle/commands/check"
Homebrew::Bundle::Commands::Check.run(global:, file:, no_upgrade:, verbose:)
when "list"
require "bundle/commands/list"
Homebrew::Bundle::Commands::List.run(
global:,
file:,
formulae: args.formulae? || args.all? || no_type_args,
casks: args.casks? || args.all?,
taps: args.taps? || args.all?,
mas: args.mas? || args.all?,
vscode: args.vscode? || args.all?,
go: args.go? || args.all?,
cargo: args.cargo? || args.all?,
flatpak: args.flatpak? || args.all?,
)
when "add", "remove"
# We intentionally omit the s from `brews`, `casks`, and `taps` for ease of handling later.
type_hash = {
brew: args.formulae?,
cask: args.casks?,
tap: args.taps?,
mas: args.mas?,
vscode: args.vscode?,
go: args.go?,
cargo: args.cargo?,
flatpak: args.flatpak?,
none: no_type_args,
}
selected_types = type_hash.select { |_, v| v }.keys
raise UsageError, "`#{subcommand}` supports only one type of entry at a time." if selected_types.count != 1
_, *named_args = args.named
if subcommand == "add"
type = case (t = selected_types.first)
when :none then :brew
when :mas then raise UsageError, "`add` does not support `--mas`."
else t
end
require "bundle/commands/add"
Homebrew::Bundle::Commands::Add.run(*named_args, type:, global:, file:)
else
require "bundle/commands/remove"
Homebrew::Bundle::Commands::Remove.run(*named_args, type: selected_types.first, global:, file:)
end
when *BUNDLE_EXEC_COMMANDS
named_args = case subcommand
when "exec"
_subcommand, *named_args = args.named
named_args
when "sh"
["sh"]
when "env"
["env"]
end
require "bundle/commands/exec"
Homebrew::Bundle::Commands::Exec.run(
*named_args,
global:,
file:,
subcommand:,
services: args.services?,
no_secrets: args.no_secrets?,
)
else
raise UsageError, "unknown subcommand: #{subcommand}"
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/cmd/--repository.rb | Library/Homebrew/cmd/--repository.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class Repository < AbstractCommand
include ShellCommand
sig { override.returns(String) }
def self.command_name = "--repository"
cmd_args do
description <<~EOS
Display where Homebrew's Git repository is located.
If <user>`/`<repo> are provided, display where tap <user>`/`<repo>'s directory is located.
EOS
named_args :tap
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/cmd/desc.rb | Library/Homebrew/cmd/desc.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "descriptions"
require "search"
require "description_cache_store"
module Homebrew
module Cmd
class Desc < AbstractCommand
cmd_args do
description <<~EOS
Display <formula>'s name and one-line description.
The cache is created on the first search, making that search slower than subsequent ones.
EOS
switch "-s", "--search",
description: "Search both names and descriptions for <text>. If <text> is flanked by " \
"slashes, it is interpreted as a regular expression."
switch "-n", "--name",
description: "Search just names for <text>. If <text> is flanked by slashes, it is " \
"interpreted as a regular expression."
switch "-d", "--description",
description: "Search just descriptions for <text>. If <text> is flanked by slashes, " \
"it is interpreted as a regular expression."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to search their " \
"descriptions.",
env: :eval_all
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--search", "--name", "--description"
named_args [:formula, :cask, :text_or_regex], min: 1
end
sig { override.void }
def run
search_type = if args.search?
:either
elsif args.name?
:name
elsif args.description?
:desc
end
if search_type.present?
if !args.eval_all? && Homebrew::EnvConfig.no_install_from_api?
raise UsageError, "`brew desc --search` needs `--eval-all` passed or `HOMEBREW_EVAL_ALL=1` set!"
end
query = args.named.join(" ")
string_or_regex = Search.query_regexp(query)
return Search.search_descriptions(string_or_regex, args, search_type:)
end
desc = {}
args.named.to_formulae_and_casks.each do |formula_or_cask|
case formula_or_cask
when Formula
desc[formula_or_cask.full_name] = formula_or_cask.desc
when Cask::Cask
description = formula_or_cask.desc.presence || Formatter.warning("[no description]")
desc[formula_or_cask.full_name] = "(#{formula_or_cask.name.join(", ")}) #{description}"
else
raise TypeError, "Unsupported formula_or_cask type: #{formula_or_cask.class}"
end
end
Descriptions.new(desc).print
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/cmd/update.rb | Library/Homebrew/cmd/update.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class Update < AbstractCommand
include ShellCommand
cmd_args do
description <<~EOS
Fetch the newest version of Homebrew and all formulae from GitHub using `git`(1) and perform any necessary migrations.
EOS
switch "--merge",
description: "Use `git merge` to apply updates (rather than `git rebase`)."
switch "--auto-update",
description: "Run on auto-updates (e.g. before `brew install`). Skips some slower steps."
switch "-f", "--force",
description: "Always do a slower, full update check (even if unnecessary)."
switch "-q", "--quiet",
description: "Make some output more quiet."
switch "-v", "--verbose",
description: "Print the directories checked and `git` operations performed."
switch "-d", "--debug",
description: "Display a trace of all shell commands as they are executed."
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/cmd/doctor.rb | Library/Homebrew/cmd/doctor.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "diagnostic"
require "cask/caskroom"
module Homebrew
module Cmd
class Doctor < AbstractCommand
cmd_args do
description <<~EOS
Check your system for potential problems. Will exit with a non-zero status
if any potential problems are found.
Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for
is working fine: please don't worry or file an issue; just ignore this.
EOS
switch "--list-checks",
description: "List all audit methods, which can be run individually " \
"if provided as arguments."
switch "-D", "--audit-debug",
description: "Enable debugging and profiling of audit methods."
named_args :diagnostic_check
end
sig { override.void }
def run
Homebrew.inject_dump_stats!(Diagnostic::Checks, /^check_*/) if args.audit_debug?
checks = Diagnostic::Checks.new(verbose: args.verbose?)
if args.list_checks?
puts checks.all
return
end
if args.no_named?
slow_checks = %w[
check_for_broken_symlinks
check_missing_deps
]
methods = (checks.all - slow_checks) + slow_checks
methods -= checks.cask_checks unless Cask::Caskroom.any_casks_installed?
else
methods = args.named
end
first_warning = T.let(true, T::Boolean)
methods.each do |method|
$stderr.puts Formatter.headline("Checking #{method}", color: :magenta) if args.debug?
unless checks.respond_to?(method)
ofail "No check available by the name: #{method}"
next
end
out = checks.send(method)
next if out.blank?
if first_warning && !args.quiet?
$stderr.puts <<~EOS
#{Tty.bold}Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry or file an issue; just ignore this. Thanks!#{Tty.reset}
EOS
end
$stderr.puts
opoo out
Homebrew.failed = true
first_warning = false
end
puts "Your system is ready to brew." if !Homebrew.failed? && !args.quiet?
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/cmd/tap-info.rb | Library/Homebrew/cmd/tap-info.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class TapInfo < AbstractCommand
cmd_args do
description <<~EOS
Show detailed information about one or more <tap>s.
If no <tap> names are provided, display brief statistics for all installed taps.
EOS
switch "--installed",
description: "Show information on each installed tap."
flag "--json",
description: "Print a JSON representation of <tap>. Currently the default and only accepted " \
"value for <version> is `v1`. See the docs for examples of using the JSON " \
"output: <https://docs.brew.sh/Querying-Brew>"
named_args :tap
end
sig { override.void }
def run
require "tap"
taps = if args.installed?
Tap
else
args.named.to_taps
end
if args.json
raise UsageError, "invalid JSON version: #{args.json}" unless ["v1", true].include? args.json
print_tap_json(taps.sort_by(&:to_s))
else
print_tap_info(taps.sort_by(&:to_s))
end
end
private
sig { params(taps: T::Array[Tap]).void }
def print_tap_info(taps)
if taps.none?
tap_count = 0
formula_count = 0
command_count = 0
private_count = 0
Tap.installed.each do |tap|
tap_count += 1
formula_count += tap.formula_files.size
command_count += tap.command_files.size
private_count += 1 if tap.private?
end
info = Utils.pluralize("tap", tap_count, include_count: true)
info += ", #{private_count} private"
info += ", #{Utils.pluralize("formula", formula_count, include_count: true)}"
info += ", #{Utils.pluralize("command", command_count, include_count: true)}"
info += ", #{HOMEBREW_TAP_DIRECTORY.dup.abv}" if HOMEBREW_TAP_DIRECTORY.directory?
puts info
else
info = ""
default_branches = %w[main master].freeze
taps.each_with_index do |tap, i|
puts unless i.zero?
info = "#{tap}: "
if tap.installed?
info += "Installed"
info += if (contents = tap.contents).blank?
"\nNo commands/casks/formulae"
else
"\n#{contents.join(", ")}"
end
info += "\nPrivate" if tap.private?
info += "\n#{tap.path} (#{tap.path.abv})"
info += "\nFrom: #{tap.remote.presence || "N/A"}"
info += "\norigin: #{tap.remote}" if tap.remote != tap.default_remote
info += "\nHEAD: #{tap.git_head || "(none)"}"
info += "\nlast commit: #{tap.git_last_commit || "never"}"
info += "\nbranch: #{tap.git_branch || "(none)"}" if default_branches.exclude?(tap.git_branch)
else
info += "Not installed"
Homebrew.failed = true
end
puts info
end
end
end
sig { params(taps: T::Array[Tap]).void }
def print_tap_json(taps)
taps_hashes = taps.map do |tap|
Homebrew.failed = true unless tap.installed?
tap.to_hash
end
puts JSON.pretty_generate(taps_hashes)
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/cmd/uses.rb | Library/Homebrew/cmd/uses.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "cask/caskroom"
require "dependencies_helpers"
module Homebrew
module Cmd
# `brew uses foo bar` returns formulae that use both foo and bar
# If you want the union, run the command twice and concatenate the results.
# The intersection is harder to achieve with shell tools.
class Uses < AbstractCommand
include DependenciesHelpers
class UnavailableFormula < T::Struct
const :name, String
const :full_name, String
end
cmd_args do
description <<~EOS
Show formulae and casks that specify <formula> as a dependency; that is, show dependents
of <formula>. When given multiple formula arguments, show the intersection
of formulae that use <formula>. By default, `uses` shows all formulae and casks that
specify <formula> as a required or recommended dependency for their stable builds.
*Note:* `--missing` and `--skip-recommended` have precedence over `--include-*`.
EOS
switch "--recursive",
description: "Resolve more than one level of dependencies."
switch "--installed",
description: "Only list formulae and casks that are currently installed."
switch "--missing",
description: "Only list formulae and casks that are not currently installed."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to show " \
"their dependents.",
env: :eval_all
switch "--include-implicit",
description: "Include formulae that have <formula> as an implicit dependency for " \
"downloading and unpacking source files."
switch "--include-build",
description: "Include formulae that specify <formula> as a `:build` dependency."
switch "--include-test",
description: "Include formulae that specify <formula> as a `:test` dependency."
switch "--include-optional",
description: "Include formulae that specify <formula> as an `:optional` dependency."
switch "--skip-recommended",
description: "Skip all formulae that specify <formula> as a `:recommended` dependency."
switch "--formula", "--formulae",
description: "Include only formulae."
switch "--cask", "--casks",
description: "Include only casks."
conflicts "--formula", "--cask"
conflicts "--installed", "--eval-all"
conflicts "--missing", "--installed"
named_args :formula, min: 1
end
sig { override.void }
def run
Formulary.enable_factory_cache!
used_formulae_missing = false
used_formulae = begin
args.named.to_formulae
rescue FormulaUnavailableError => e
opoo e
used_formulae_missing = true
# If the formula doesn't exist: fake the needed formula object name.
args.named.map { |name| UnavailableFormula.new name:, full_name: name }
end
use_runtime_dependents = args.installed? &&
!used_formulae_missing &&
!args.include_implicit? &&
!args.include_build? &&
!args.include_test? &&
!args.include_optional? &&
!args.skip_recommended?
uses = intersection_of_dependents(use_runtime_dependents, used_formulae)
return if uses.empty?
puts Formatter.columns(uses.map(&:full_name).sort)
odie "Missing formulae should not have dependents!" if used_formulae_missing
end
private
sig {
params(use_runtime_dependents: T::Boolean, used_formulae: T::Array[T.any(Formula, UnavailableFormula)])
.returns(T::Array[T.any(Formula, CaskDependent)])
}
def intersection_of_dependents(use_runtime_dependents, used_formulae)
recursive = args.recursive?
show_formulae_and_casks = !args.formula? && !args.cask?
includes, ignores = args_includes_ignores(args)
deps = []
if use_runtime_dependents
# We can only get here if `used_formulae_missing` is false, thus there are no UnavailableFormula.
used_formulae = T.cast(used_formulae, T::Array[Formula])
if show_formulae_and_casks || args.formula?
deps += T.must(used_formulae.map(&:runtime_installed_formula_dependents)
.reduce(&:&))
.select(&:any_version_installed?)
end
if show_formulae_and_casks || args.cask?
deps += select_used_dependents(
dependents(Cask::Caskroom.casks),
used_formulae, recursive, includes, ignores
)
end
deps
else
eval_all = args.eval_all?
if !args.installed? && !eval_all
raise UsageError, "`brew uses` needs `--installed` or `--eval-all` passed or `HOMEBREW_EVAL_ALL=1` set!"
end
if show_formulae_and_casks || args.formula?
deps += args.installed? ? Formula.installed : Formula.all(eval_all:)
end
if show_formulae_and_casks || args.cask?
deps += args.installed? ? Cask::Caskroom.casks : Cask::Cask.all(eval_all:)
end
if args.missing?
deps.reject! do |dep|
case dep
when Formula
dep.any_version_installed?
when Cask::Cask
dep.installed?
end
end
ignores.delete(:satisfied?)
end
select_used_dependents(dependents(deps), used_formulae, recursive, includes, ignores)
end
end
sig {
params(
dependents: T::Array[T.any(Formula, CaskDependent)],
used_formulae: T::Array[T.any(Formula, UnavailableFormula)],
recursive: T::Boolean,
includes: T::Array[Symbol],
ignores: T::Array[Symbol],
).returns(T::Array[T.any(Formula, CaskDependent)])
}
def select_used_dependents(dependents, used_formulae, recursive, includes, ignores)
dependents.select do |d|
deps = if recursive
recursive_dep_includes(d, includes, ignores)
else
select_includes(d.deps, ignores, includes)
end
used_formulae.all? do |ff|
deps.any? do |dep|
match = case dep
when Dependency
dep.to_formula.full_name == ff.full_name if dep.name.include?("/")
when Requirement
nil
else
T.absurd(dep)
end
next match unless match.nil?
dep.name == ff.name
end
rescue FormulaUnavailableError
# Silently ignore this case as we don't care about things used in
# taps that aren't currently tapped.
next
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/cmd/--caskroom.rb | Library/Homebrew/cmd/--caskroom.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class Caskroom < AbstractCommand
sig { override.returns(String) }
def self.command_name = "--caskroom"
cmd_args do
description <<~EOS
Display Homebrew's Caskroom path.
If <cask> is provided, display the location in the Caskroom where <cask>
would be installed, without any sort of versioned directory as the last path.
EOS
named_args :cask
end
sig { override.void }
def run
if args.named.to_casks.blank?
puts Cask::Caskroom.path
else
args.named.to_casks.each do |cask|
puts "#{Cask::Caskroom.path}/#{cask.token}"
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/cmd/reinstall.rb | Library/Homebrew/cmd/reinstall.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula_installer"
require "development_tools"
require "messages"
require "install"
require "reinstall"
require "cleanup"
require "cask/utils"
require "cask/macos"
require "cask/reinstall"
require "upgrade"
require "api"
module Homebrew
module Cmd
class Reinstall < AbstractCommand
cmd_args do
description <<~EOS
Uninstall and then reinstall a <formula> or <cask> using the same options it was
originally installed with, plus any appended options specific to a <formula>.
Unless `$HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK` is set, `brew upgrade` or `brew reinstall` will be run for
outdated dependents and dependents with broken linkage, respectively.
Unless `$HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for the
reinstalled formulae or, every 30 days, for all formulae.
EOS
switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB " \
"or a shell inside the temporary build directory."
switch "--display-times",
description: "Print install times for each package at the end of the run.",
env: :display_install_times
switch "-f", "--force",
description: "Install without checking for previously installed keg-only or " \
"non-migrated versions."
switch "-v", "--verbose",
description: "Print the verification and post-install steps."
switch "--ask",
description: "Ask for confirmation before downloading and upgrading formulae. " \
"Print download, install and net install sizes of bottles and dependencies.",
env: :ask
[
[:switch, "--formula", "--formulae", {
description: "Treat all named arguments as formulae.",
}],
[:switch, "-s", "--build-from-source", {
description: "Compile <formula> from source even if a bottle is available.",
}],
[:switch, "-i", "--interactive", {
description: "Download and patch <formula>, then open a shell. This allows the user to " \
"run `./configure --help` and otherwise determine how to turn the software " \
"package into a Homebrew package.",
}],
[:switch, "--force-bottle", {
description: "Install from a bottle if it exists for the current or newest version of " \
"macOS, even if it would not normally be used for installation.",
}],
[:switch, "--keep-tmp", {
description: "Retain the temporary files created during installation.",
}],
[:switch, "--debug-symbols", {
depends_on: "--build-from-source",
description: "Generate debug symbols on build. Source will be retained in a cache directory.",
}],
[:switch, "-g", "--git", {
description: "Create a Git repository, useful for creating patches to the software.",
}],
].each do |args|
options = args.pop
send(*args, **options)
conflicts "--cask", args.last
end
formula_options
[
[:switch, "--cask", "--casks", {
description: "Treat all named arguments as casks.",
}],
[:switch, "--[no-]binaries", {
description: "Disable/enable linking of helper executables (default: enabled).",
env: :cask_opts_binaries,
}],
[:switch, "--require-sha", {
description: "Require all casks to have a checksum.",
env: :cask_opts_require_sha,
}],
[:switch, "--[no-]quarantine", {
env: :cask_opts_quarantine,
odeprecated: true,
}],
[:switch, "--adopt", {
description: "Adopt existing artifacts in the destination that are identical to those being installed. " \
"Cannot be combined with `--force`.",
}],
[:switch, "--skip-cask-deps", {
description: "Skip installing cask dependencies.",
}],
[:switch, "--zap", {
description: "For use with `brew reinstall --cask`. Remove all files associated with a cask. " \
"*May remove files which are shared between applications.*",
}],
].each do |args|
options = args.pop
send(*args, **options)
conflicts "--formula", args.last
end
cask_options
conflicts "--build-from-source", "--force-bottle"
named_args [:formula, :cask], min: 1
end
sig { override.void }
def run
formulae, casks = args.named.to_resolved_formulae_to_casks
if args.build_from_source?
unless DevelopmentTools.installed?
raise BuildFlagsError.new(["--build-from-source"], bottled: formulae.all?(&:bottled?))
end
unless Homebrew::EnvConfig.developer?
opoo "building from source is not supported!"
puts "You're on your own. Failures are expected so don't create any issues, please!"
end
end
formulae = Homebrew::Attestation.sort_formulae_for_install(formulae) if Homebrew::Attestation.enabled?
unless formulae.empty?
Install.perform_preinstall_checks_once
reinstall_contexts = formulae.filter_map do |formula|
if formula.pinned?
onoe "#{formula.full_name} is pinned. You must unpin it to reinstall."
next
end
Migrator.migrate_if_needed(formula, force: args.force?)
Homebrew::Reinstall.build_install_context(
formula.latest_formula,
flags: args.flags_only,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?,
git: args.git?,
)
end
dependants = Upgrade.dependants(
formulae,
flags: args.flags_only,
ask: args.ask?,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?,
)
formulae_installers = reinstall_contexts.map(&:formula_installer)
# Main block: if asking the user is enabled, show dependency and size information.
Install.ask_formulae(formulae_installers, dependants, args: args) if args.ask?
valid_formula_installers = Install.fetch_formulae(formulae_installers)
exit 1 if Homebrew.failed?
reinstall_contexts.each do |reinstall_context|
next unless valid_formula_installers.include?(reinstall_context.formula_installer)
Homebrew::Reinstall.reinstall_formula(reinstall_context)
Cleanup.install_formula_clean!(reinstall_context.formula)
end
Upgrade.upgrade_dependents(
dependants, formulae,
flags: args.flags_only,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?
)
end
if casks.any?
Install.ask_casks casks if args.ask?
Cask::Reinstall.reinstall_casks(
*casks,
binaries: args.binaries?,
verbose: args.verbose?,
force: args.force?,
require_sha: args.require_sha?,
skip_cask_deps: args.skip_cask_deps?,
quarantine: args.quarantine?,
zap: args.zap?,
)
end
Cleanup.periodic_clean!
Homebrew.messages.display_messages(display_times: args.display_times?)
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/cmd/migrate.rb | Library/Homebrew/cmd/migrate.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "migrator"
require "cask/migrator"
module Homebrew
module Cmd
class Migrate < AbstractCommand
cmd_args do
description <<~EOS
Migrate renamed packages to new names, where <formula> are old names of
packages.
EOS
switch "-f", "--force",
description: "Treat installed <formula> and provided <formula> as if they are from " \
"the same taps and migrate them anyway."
switch "-n", "--dry-run",
description: "Show what would be migrated, but do not actually migrate anything."
switch "--formula", "--formulae",
description: "Only migrate formulae."
switch "--cask", "--casks",
description: "Only migrate casks."
conflicts "--formula", "--cask"
named_args [:installed_formula, :installed_cask], min: 1
end
sig { override.void }
def run
args.named.to_formulae_and_casks(warn: false).each do |formula_or_cask|
case formula_or_cask
when Formula
Migrator.migrate_if_needed(formula_or_cask, force: args.force?, dry_run: args.dry_run?)
when Cask::Cask
Cask::Migrator.migrate_if_needed(formula_or_cask, dry_run: args.dry_run?)
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/cmd/completions.rb | Library/Homebrew/cmd/completions.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "completions"
module Homebrew
module Cmd
class CompletionsCmd < AbstractCommand
cmd_args do
description <<~EOS
Control whether Homebrew automatically links external tap shell completion files.
Read more at <https://docs.brew.sh/Shell-Completion>.
`brew completions` [`state`]:
Display the current state of Homebrew's completions.
`brew completions` (`link`|`unlink`):
Link or unlink Homebrew's completions.
EOS
named_args %w[state link unlink], max: 1
end
sig { override.void }
def run
case args.named.first
when nil, "state"
if Completions.link_completions?
puts "Completions are linked."
else
puts "Completions are not linked."
end
when "link"
Completions.link!
puts "Completions are now linked."
when "unlink"
Completions.unlink!
puts "Completions are no longer linked."
else
raise UsageError, "unknown subcommand: #{args.named.first}"
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/cmd/shellenv.rb | Library/Homebrew/cmd/shellenv.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class Shellenv < AbstractCommand
include ShellCommand
cmd_args do
description <<~EOS
Valid shells: bash|csh|fish|pwsh|sh|tcsh|zsh
Print export statements. When run in a shell, this installation of Homebrew will be added to your
`$PATH`, `$MANPATH`, and `$INFOPATH`.
The variables `$HOMEBREW_PREFIX`, `$HOMEBREW_CELLAR` and `$HOMEBREW_REPOSITORY` are also exported to avoid
querying them multiple times.
To help guarantee idempotence, this command produces no output when Homebrew's `bin` and `sbin` directories
are first and second respectively in your `$PATH`. Consider adding evaluation of this command's output to
your dotfiles (e.g. `~/.bash_profile` or ~/.zprofile` on macOS and ~/.bashrc` or ~/.zshrc` on Linux) with:
`eval "$(brew shellenv)"`
The shell can be specified explicitly with a supported shell name parameter. Unknown shells will output
POSIX exports.
EOS
named_args :shell
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/cmd/home.rb | Library/Homebrew/cmd/home.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module Cmd
class Home < AbstractCommand
cmd_args do
description <<~EOS
Open a <formula> or <cask>'s homepage in a browser, or open
Homebrew's own homepage if no argument is provided.
EOS
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--formula", "--cask"
named_args [:formula, :cask]
end
sig { override.void }
def run
if args.no_named?
exec_browser HOMEBREW_WWW
return
end
# to_formulae_and_casks is typed to possibly return Kegs (but won't without explicitly asking)
formulae_or_casks = T.cast(args.named.to_formulae_and_casks, T::Array[T.any(Formula, Cask::Cask)])
homepages = formulae_or_casks.map do |formula_or_cask|
puts "Opening homepage for #{name_of(formula_or_cask)}"
formula_or_cask.homepage
end
exec_browser(*homepages)
end
private
sig { params(formula_or_cask: T.any(Formula, Cask::Cask)).returns(String) }
def name_of(formula_or_cask)
if formula_or_cask.is_a? Formula
"Formula #{formula_or_cask.name}"
else
"Cask #{formula_or_cask.token}"
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/cmd/cleanup.rb | Library/Homebrew/cmd/cleanup.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "cleanup"
module Homebrew
module Cmd
class CleanupCmd < AbstractCommand
cmd_args do
days = Homebrew::EnvConfig::ENVS[:HOMEBREW_CLEANUP_MAX_AGE_DAYS]&.dig(:default)
description <<~EOS
Remove stale lock files and outdated downloads for all formulae and casks,
and remove old versions of installed formulae. If arguments are specified,
only do this for the given formulae and casks. Removes all downloads more than
#{days} days old. This can be adjusted with `$HOMEBREW_CLEANUP_MAX_AGE_DAYS`.
EOS
flag "--prune=",
description: "Remove all cache files older than specified <days>. " \
"If you want to remove everything, use `--prune=all`."
switch "-n", "--dry-run",
description: "Show what would be removed, but do not actually remove anything."
switch "-s", "--scrub",
description: "Scrub the cache, including downloads for even the latest versions. " \
"Note that downloads for any installed formulae or casks will still not be deleted. " \
"If you want to delete those too: `rm -rf \"$(brew --cache)\"`"
switch "--prune-prefix",
description: "Only prune the symlinks and directories from the prefix and remove no other files."
named_args [:formula, :cask]
end
sig { override.void }
def run
days = args.prune.presence&.then do |prune|
case prune
when /\A\d+\Z/
prune.to_i
when "all"
0
else
raise UsageError, "`--prune` expects an integer or `all`."
end
end
cleanup = Cleanup.new(*args.named, dry_run: args.dry_run?, scrub: args.s?, days:)
if args.prune_prefix?
cleanup.prune_prefix_symlinks_and_directories
return
end
cleanup.clean!(quiet: args.quiet?, periodic: false)
unless cleanup.disk_cleanup_size.zero?
disk_space = disk_usage_readable(cleanup.disk_cleanup_size)
if args.dry_run?
ohai "This operation would free approximately #{disk_space} of disk space."
else
ohai "This operation has freed approximately #{disk_space} of disk space."
end
end
return if cleanup.unremovable_kegs.empty?
ofail <<~EOS
Could not cleanup old kegs! Fix your permissions on:
#{cleanup.unremovable_kegs.join "\n "}
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/options.rb | Library/Homebrew/cmd/options.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "options"
module Homebrew
module Cmd
class OptionsCmd < AbstractCommand
cmd_args do
description <<~EOS
Show install options specific to <formula>.
EOS
switch "--compact",
description: "Show all options on a single line separated by spaces."
switch "--installed",
description: "Show options for formulae that are currently installed."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to show their " \
"options.",
env: :eval_all
flag "--command=",
description: "Show options for the specified <command>."
conflicts "--command", "--installed", "--eval-all"
named_args :formula
end
sig { override.void }
def run
eval_all = args.eval_all?
if eval_all
puts_options(Formula.all(eval_all:).sort)
elsif args.installed?
puts_options(Formula.installed.sort)
elsif args.command.present?
cmd_options = Commands.command_options(T.must(args.command))
odie "Unknown command: brew #{args.command}" if cmd_options.nil?
if args.compact?
puts cmd_options.sort.map(&:first) * " "
else
cmd_options.sort.each { |option, desc| puts "#{option}\n\t#{desc}" }
puts
end
elsif args.no_named?
raise UsageError, "`brew options` needs a formula or `--eval-all` passed or `HOMEBREW_EVAL_ALL=1` set!"
else
puts_options args.named.to_formulae
end
end
private
sig { params(formulae: T::Array[Formula]).void }
def puts_options(formulae)
formulae.each do |f|
next if f.options.empty?
if args.compact?
puts f.options.as_flags.sort * " "
else
puts f.full_name if formulae.length > 1
Options.dump_for_formula f
puts
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/cmd/outdated.rb | Library/Homebrew/cmd/outdated.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "keg"
require "cask/caskroom"
require "api"
module Homebrew
module Cmd
class Outdated < AbstractCommand
cmd_args do
description <<~EOS
List installed casks and formulae that have an updated version available. By default, version
information is displayed in interactive shells and suppressed otherwise.
EOS
switch "-q", "--quiet",
description: "List only the names of outdated kegs (takes precedence over `--verbose`)."
switch "-v", "--verbose",
description: "Include detailed version information."
switch "--formula", "--formulae",
description: "List only outdated formulae."
switch "--cask", "--casks",
description: "List only outdated casks."
flag "--json",
description: "Print output in JSON format. There are two versions: `v1` and `v2`. " \
"`v1` is deprecated and is currently the default if no version is specified. " \
"`v2` prints outdated formulae and casks."
switch "--fetch-HEAD",
description: "Fetch the upstream repository to detect if the HEAD installation of the " \
"formula is outdated. Otherwise, the repository's HEAD will only be checked for " \
"updates when a new stable or development version has been released."
switch "-g", "--greedy",
description: "Also include outdated casks with `auto_updates true` or `version :latest`.",
env: :upgrade_greedy
switch "--greedy-latest",
description: "Also include outdated casks including those with `version :latest`."
switch "--greedy-auto-updates",
description: "Also include outdated casks including those with `auto_updates true`."
conflicts "--quiet", "--verbose", "--json"
conflicts "--formula", "--cask"
named_args [:formula, :cask]
end
sig { override.void }
def run
case json_version(args.json)
when :v1
odie "`brew outdated --json=v1` is no longer supported. Use brew outdated --json=v2 instead."
when :v2, :default
formulae, casks = if args.formula?
[outdated_formulae, []]
elsif args.cask?
[[], outdated_casks]
else
outdated_formulae_casks
end
json = {
formulae: json_info(formulae),
casks: json_info(casks),
}
# json v2.8.1 is inconsistent it how it renders empty arrays,
# so we use `[]` for consistency:
puts JSON.pretty_generate(json).gsub(/\[\n\n\s*\]/, "[]")
outdated = formulae + casks
else
outdated = if args.formula?
outdated_formulae
elsif args.cask?
outdated_casks
else
outdated_formulae_casks.flatten
end
print_outdated(outdated)
end
Homebrew.failed = args.named.present? && outdated.present?
end
private
sig { params(formulae_or_casks: T::Array[T.any(Formula, Cask::Cask)]).void }
def print_outdated(formulae_or_casks)
formulae_or_casks.each do |formula_or_cask|
if formula_or_cask.is_a?(Formula)
f = formula_or_cask
if verbose?
outdated_kegs = f.outdated_kegs(fetch_head: args.fetch_HEAD?)
latest_formula = f.latest_formula(prefer_stub: true)
current_version = if f.alias_changed? && !latest_formula.latest_version_installed?
"#{latest_formula.name} (#{latest_formula.pkg_version})"
elsif f.head?
latest_head_version = f.latest_head_pkg_version(fetch_head: args.fetch_HEAD?)
if outdated_kegs.any? { |k| k.version.to_s == latest_head_version.to_s }
# There is a newer HEAD but the version number has not changed.
"latest HEAD"
else
latest_head_version.to_s
end
else
latest_formula.pkg_version.to_s
end
outdated_versions = outdated_kegs.group_by { |keg| Formulary.from_keg(keg).full_name }
.sort_by { |full_name, _kegs| full_name }
.map do |full_name, kegs|
"#{full_name} (#{kegs.map(&:version).join(", ")})"
end.join(", ")
pinned_version = " [pinned at #{f.pinned_version}]" if f.pinned?
puts "#{outdated_versions} < #{current_version}#{pinned_version}"
else
puts f.full_installed_specified_name
end
else
c = formula_or_cask
puts c.outdated_info(upgrade_greedy_cask?(args.greedy?, formula_or_cask), verbose?,
false, args.greedy_latest?, args.greedy_auto_updates?)
end
end
end
sig {
params(
formulae_or_casks: T::Array[T.any(Formula, Cask::Cask)],
).returns(T::Array[T::Hash[Symbol, T.untyped]])
}
def json_info(formulae_or_casks)
formulae_or_casks.map do |formula_or_cask|
if formula_or_cask.is_a?(Formula)
f = formula_or_cask
outdated_versions = f.outdated_kegs(fetch_head: args.fetch_HEAD?).map(&:version)
current_version = if f.head? && outdated_versions.any? { |v| v.to_s == f.pkg_version.to_s }
"HEAD"
else
f.pkg_version.to_s
end
{ name: f.full_name,
installed_versions: outdated_versions.map(&:to_s),
current_version:,
pinned: f.pinned?,
pinned_version: f.pinned_version }
else
c = formula_or_cask
c.outdated_info(upgrade_greedy_cask?(args.greedy?, formula_or_cask),
verbose?, true, args.greedy_latest?, args.greedy_auto_updates?)
end
end
end
sig { returns(T::Boolean) }
def verbose?
($stdout.tty? || Context.current.verbose?) && !Context.current.quiet?
end
sig { params(version: T.nilable(T.any(TrueClass, String))).returns(T.nilable(Symbol)) }
def json_version(version)
version_hash = {
nil => nil,
true => :default,
"v1" => :v1,
"v2" => :v2,
}
version_hash.fetch(version) { raise UsageError, "invalid JSON version: #{version}" }
end
sig { returns(T::Array[Formula]) }
def outdated_formulae
T.cast(
select_outdated(args.named.to_resolved_formulae.presence || Formula.installed).sort,
T::Array[Formula],
)
end
sig { returns(T::Array[Cask::Cask]) }
def outdated_casks
outdated = if args.named.present?
select_outdated(args.named.to_casks)
else
select_outdated(Cask::Caskroom.casks)
end
T.cast(outdated, T::Array[Cask::Cask])
end
sig { returns([T::Array[T.any(Formula, Cask::Cask)], T::Array[T.any(Formula, Cask::Cask)]]) }
def outdated_formulae_casks
formulae, casks = args.named.to_resolved_formulae_to_casks
if formulae.blank? && casks.blank?
formulae = Formula.installed
casks = Cask::Caskroom.casks
end
[select_outdated(formulae).sort, select_outdated(casks)]
end
sig {
params(formulae_or_casks: T::Array[T.any(Formula, Cask::Cask)]).returns(T::Array[T.any(Formula, Cask::Cask)])
}
def select_outdated(formulae_or_casks)
formulae_or_casks.select do |formula_or_cask|
if formula_or_cask.is_a?(Formula)
formula_or_cask.outdated?(fetch_head: args.fetch_HEAD?)
else
formula_or_cask.outdated?(greedy: upgrade_greedy_cask?(args.greedy?, formula_or_cask),
greedy_latest: args.greedy_latest?,
greedy_auto_updates: args.greedy_auto_updates?)
end
end
end
sig { params(greedy: T::Boolean, cask: Cask::Cask).returns(T::Boolean) }
def upgrade_greedy_cask?(greedy, cask)
return true if greedy
@greedy_list ||= T.let(
begin
upgrade_greedy_casks = Homebrew::EnvConfig.upgrade_greedy_casks.presence
upgrade_greedy_casks&.split || []
end, T.nilable(T::Array[String])
)
@greedy_list.include?(cask.token)
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/cmd/update-report.rb | Library/Homebrew/cmd/update-report.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "migrator"
require "formulary"
require "cask/cask_loader"
require "cask/migrator"
require "descriptions"
require "cleanup"
require "description_cache_store"
require "settings"
require "reinstall"
module Homebrew
module Cmd
class UpdateReport < AbstractCommand
cmd_args do
description <<~EOS
The Ruby implementation of `brew update`. Never called manually.
EOS
switch "--auto-update", "--preinstall",
description: "Run in 'auto-update' mode (faster, less output)."
switch "-f", "--force",
description: "Treat installed and updated formulae as if they are from " \
"the same taps and migrate them anyway."
hide_from_man_page!
end
sig { override.void }
def run
return output_update_report if $stdout.tty?
redirect_stdout($stderr) do
output_update_report
end
end
private
sig { void }
def auto_update_header
@auto_update_header ||= T.let(begin
ohai "Auto-updated Homebrew!" if args.auto_update?
true
end, T.nilable(T::Boolean))
end
sig { void }
def output_update_report
if ENV["HOMEBREW_ADDITIONAL_GOOGLE_ANALYTICS_ID"].present?
opoo "HOMEBREW_ADDITIONAL_GOOGLE_ANALYTICS_ID is now a no-op so can be unset."
puts "All Homebrew Google Analytics code and data was destroyed."
end
if ENV["HOMEBREW_NO_GOOGLE_ANALYTICS"].present?
opoo "HOMEBREW_NO_GOOGLE_ANALYTICS is now a no-op so can be unset."
puts "All Homebrew Google Analytics code and data was destroyed."
end
unless args.quiet?
analytics_message
donation_message
install_from_api_message
end
tap_or_untap_core_taps_if_necessary
updated = false
new_tag = nil
initial_revision = ENV["HOMEBREW_UPDATE_BEFORE"].to_s
current_revision = ENV["HOMEBREW_UPDATE_AFTER"].to_s
odie "update-report should not be called directly!" if initial_revision.empty? || current_revision.empty?
if initial_revision != current_revision
auto_update_header
updated = true
old_tag = Settings.read "latesttag"
new_tag = Utils.popen_read(
"git", "-C", HOMEBREW_REPOSITORY, "tag", "--list", "--sort=-version:refname", "*.*"
).lines.first.chomp
Settings.write "latesttag", new_tag if new_tag != old_tag
if new_tag == old_tag
ohai "Updated Homebrew from #{shorten_revision(initial_revision)} " \
"to #{shorten_revision(current_revision)}."
elsif old_tag.blank?
ohai "Updated Homebrew from #{shorten_revision(initial_revision)} " \
"to #{new_tag} (#{shorten_revision(current_revision)})."
else
ohai "Updated Homebrew from #{old_tag} (#{shorten_revision(initial_revision)}) " \
"to #{new_tag} (#{shorten_revision(current_revision)})."
end
end
# Check if we can parse the JSON and do any Ruby-side follow-up.
Homebrew::API.write_names_and_aliases unless Homebrew::EnvConfig.no_install_from_api?
Homebrew.failed = true if ENV["HOMEBREW_UPDATE_FAILED"]
return if Homebrew::EnvConfig.disable_load_formula?
migrate_gcc_dependents_if_needed
hub = ReporterHub.new
updated_taps = []
Tap.installed.each do |tap|
next if !tap.git? || tap.git_repository.origin_url.nil?
next if (tap.core_tap? || tap.core_cask_tap?) && !Homebrew::EnvConfig.no_install_from_api?
begin
reporter = Reporter.new(tap)
rescue Reporter::ReporterRevisionUnsetError => e
if Homebrew::EnvConfig.developer?
require "utils/backtrace"
onoe "#{e.message}\n#{Utils::Backtrace.clean(e)&.join("\n")}"
end
next
end
if reporter.updated?
updated_taps << tap.name
hub.add(reporter, auto_update: args.auto_update?)
end
end
# If we're installing from the API: we cannot use Git to check for #
# differences in packages so instead use {formula,cask}_names.txt to do so.
# The first time this runs: we won't yet have a base state
# ({formula,cask}_names.before.txt) to compare against so we don't output a
# anything and just copy the files for next time.
unless Homebrew::EnvConfig.no_install_from_api?
api_cache = Homebrew::API::HOMEBREW_CACHE_API
core_tap = CoreTap.instance
cask_tap = CoreCaskTap.instance
[
[:formula, core_tap, core_tap.formula_dir],
[:cask, cask_tap, cask_tap.cask_dir],
].each do |type, tap, dir|
names_txt = api_cache/"#{type}_names.txt"
next unless names_txt.exist?
names_before_txt = api_cache/"#{type}_names.before.txt"
if names_before_txt.exist?
reporter = Reporter.new(
tap,
api_names_txt: names_txt,
api_names_before_txt: names_before_txt,
api_dir_prefix: dir,
)
if reporter.updated?
updated_taps << tap.name
hub.add(reporter, auto_update: args.auto_update?)
end
else
FileUtils.cp names_txt, names_before_txt
end
end
end
unless updated_taps.empty?
auto_update_header
puts "Updated #{Utils.pluralize("tap", updated_taps.count,
include_count: true)} (#{updated_taps.to_sentence})."
updated = true
end
if updated
if hub.empty?
puts no_changes_message unless args.quiet?
else
if ENV.fetch("HOMEBREW_UPDATE_REPORT_ONLY_INSTALLED", false)
opoo "HOMEBREW_UPDATE_REPORT_ONLY_INSTALLED is now the default behaviour, " \
"so you can unset it from your environment."
end
hub.dump(auto_update: args.auto_update?) unless args.quiet?
hub.reporters.each(&:migrate_tap_migration)
hub.reporters.each(&:migrate_cask_rename)
hub.reporters.each { |r| r.migrate_formula_rename(force: args.force?, verbose: args.verbose?) }
CacheStoreDatabase.use(:descriptions) do |db|
DescriptionCacheStore.new(db)
.update_from_report!(hub)
end
CacheStoreDatabase.use(:cask_descriptions) do |db|
CaskDescriptionCacheStore.new(db)
.update_from_report!(hub)
end
end
puts if args.auto_update?
elsif !args.auto_update? && !ENV["HOMEBREW_UPDATE_FAILED"]
puts "Already up-to-date." unless args.quiet?
end
Homebrew::Reinstall.reinstall_pkgconf_if_needed!
Commands.rebuild_commands_completion_list
link_completions_manpages_and_docs
Tap.installed.each(&:link_completions_and_manpages)
failed_fetch_dirs = ENV["HOMEBREW_MISSING_REMOTE_REF_DIRS"]&.split("\n")
if failed_fetch_dirs.present?
failed_fetch_taps = failed_fetch_dirs.map { |dir| Tap.from_path(dir) }
ofail <<~EOS
Some taps failed to update!
The following taps can not read their remote branches:
#{failed_fetch_taps.join("\n ")}
This is happening because the remote branch was renamed or deleted.
Reset taps to point to the correct remote branches by running `brew tap --repair`
EOS
end
return if new_tag.blank? || new_tag == old_tag || args.quiet?
puts
new_major_version, new_minor_version, new_patch_version = new_tag.split(".").map(&:to_i)
old_major_version, old_minor_version = T.must(old_tag.split(".")[0, 2]).map(&:to_i) if old_tag.present?
if old_tag.blank? || new_major_version > old_major_version || new_minor_version > old_minor_version
puts <<~EOS
The #{new_major_version}.#{new_minor_version}.0 release notes are available on the Homebrew Blog:
#{Formatter.url("https://brew.sh/blog/#{new_major_version}.#{new_minor_version}.0")}
EOS
end
return if new_patch_version.zero?
puts <<~EOS
The #{new_tag} changelog can be found at:
#{Formatter.url("https://github.com/Homebrew/brew/releases/tag/#{new_tag}")}
EOS
end
sig { returns(String) }
def no_changes_message
"No changes to formulae or casks."
end
sig { params(revision: String).returns(String) }
def shorten_revision(revision)
Utils.popen_read("git", "-C", HOMEBREW_REPOSITORY, "rev-parse", "--short", revision).chomp
end
sig { void }
def tap_or_untap_core_taps_if_necessary
return if ENV["HOMEBREW_UPDATE_TEST"]
if Homebrew::EnvConfig.no_install_from_api?
return if Homebrew::EnvConfig.automatically_set_no_install_from_api?
core_tap = CoreTap.instance
return if core_tap.installed?
core_tap.ensure_installed!
revision = CoreTap.instance.git_head
ENV["HOMEBREW_UPDATE_BEFORE_HOMEBREW_HOMEBREW_CORE"] = revision
ENV["HOMEBREW_UPDATE_AFTER_HOMEBREW_HOMEBREW_CORE"] = revision
else
return if Homebrew::EnvConfig.developer? || ENV["HOMEBREW_DEV_CMD_RUN"]
return if ENV["HOMEBREW_GITHUB_HOSTED_RUNNER"] || ENV["GITHUB_ACTIONS_HOMEBREW_SELF_HOSTED"]
return if (HOMEBREW_PREFIX/".homebrewdocker").exist?
tap_output_header_printed = T.let(false, T::Boolean)
default_branches = %w[main master].freeze
[CoreTap.instance, CoreCaskTap.instance].each do |tap|
next unless tap.installed?
if default_branches.include?(tap.git_branch) &&
(Date.parse(T.must(tap.git_repository.last_commit_date)) <= Date.today.prev_month)
ohai "#{tap.name} is old and unneeded, untapping to save space..."
tap.uninstall
else
unless tap_output_header_printed
puts "Installing from the API is now the default behaviour!"
puts "You can save space and time by running:"
tap_output_header_printed = true
end
puts " brew untap #{tap.name}"
end
end
end
end
sig { params(repository: Pathname).void }
def link_completions_manpages_and_docs(repository = HOMEBREW_REPOSITORY)
command = "brew update"
Utils::Link.link_completions(repository, command)
Utils::Link.link_manpages(repository, command)
Utils::Link.link_docs(repository, command)
rescue => e
ofail <<~EOS
Failed to link all completions, docs and manpages:
#{e}
EOS
end
sig { void }
def migrate_gcc_dependents_if_needed
# do nothing
end
sig { void }
def analytics_message
return if Utils::Analytics.messages_displayed?
return if Utils::Analytics.no_message_output?
if Utils::Analytics.disabled? && !Utils::Analytics.influx_message_displayed?
ohai "Homebrew's analytics have entirely moved to our InfluxDB instance in the EU."
puts "We gather less data than before and have destroyed all Google Analytics data:"
puts " #{Formatter.url("https://docs.brew.sh/Analytics")}#{Tty.reset}"
puts "Please reconsider re-enabling analytics to help our volunteer maintainers with:"
puts " brew analytics on"
elsif !Utils::Analytics.disabled?
ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"] = "1"
# Use the shell's audible bell.
print "\a"
# Use an extra newline and bold to avoid this being missed.
ohai "Homebrew collects anonymous analytics."
puts <<~EOS
#{Tty.bold}Read the analytics documentation (and how to opt-out) here:
#{Formatter.url("https://docs.brew.sh/Analytics")}#{Tty.reset}
No analytics have been recorded yet (nor will be during this `brew` run).
EOS
end
# Consider the messages possibly missed if not a TTY.
Utils::Analytics.messages_displayed! if $stdout.tty?
end
sig { void }
def donation_message
return if Settings.read("donationmessage") == "true"
ohai "Homebrew is run entirely by unpaid volunteers. Please consider donating:"
puts " #{Formatter.url("https://github.com/Homebrew/brew#donations")}\n\n"
# Consider the message possibly missed if not a TTY.
Settings.write "donationmessage", true if $stdout.tty?
end
sig { void }
def install_from_api_message
return if Settings.read("installfromapimessage") == "true"
no_install_from_api_set = Homebrew::EnvConfig.no_install_from_api? &&
!Homebrew::EnvConfig.automatically_set_no_install_from_api?
return unless no_install_from_api_set
ohai "You have `$HOMEBREW_NO_INSTALL_FROM_API` set"
puts "Homebrew >=4.1.0 is dramatically faster and less error-prone when installing"
puts "from the JSON API. Please consider unsetting `$HOMEBREW_NO_INSTALL_FROM_API`."
puts "This message will only be printed once."
puts "\n\n"
# Consider the message possibly missed if not a TTY.
Settings.write "installfromapimessage", true if $stdout.tty?
end
end
end
end
require "extend/os/cmd/update-report"
class Reporter
include Utils::Output::Mixin
Report = T.type_alias do
{
A: T::Array[String],
AC: T::Array[String],
D: T::Array[String],
DC: T::Array[String],
M: T::Array[String],
MC: T::Array[String],
R: T::Array[[String, String]],
RC: T::Array[[String, String]],
T: T::Array[String],
}
end
class ReporterRevisionUnsetError < RuntimeError
sig { params(var_name: String).void }
def initialize(var_name)
super "#{var_name} is unset!"
end
end
sig {
params(tap: Tap, api_names_txt: T.nilable(Pathname), api_names_before_txt: T.nilable(Pathname),
api_dir_prefix: T.nilable(Pathname)).void
}
def initialize(tap, api_names_txt: nil, api_names_before_txt: nil, api_dir_prefix: nil)
@tap = tap
# This is slightly involved/weird but all the #report logic is shared so it's worth it.
if installed_from_api?(api_names_txt, api_names_before_txt, api_dir_prefix)
@api_names_txt = T.let(api_names_txt, T.nilable(Pathname))
@api_names_before_txt = T.let(api_names_before_txt, T.nilable(Pathname))
@api_dir_prefix = T.let(api_dir_prefix, T.nilable(Pathname))
else
initial_revision_var = "HOMEBREW_UPDATE_BEFORE#{tap.repository_var_suffix}"
@initial_revision = T.let(ENV[initial_revision_var].to_s, String)
raise ReporterRevisionUnsetError, initial_revision_var if @initial_revision.empty?
current_revision_var = "HOMEBREW_UPDATE_AFTER#{tap.repository_var_suffix}"
@current_revision = T.let(ENV[current_revision_var].to_s, String)
raise ReporterRevisionUnsetError, current_revision_var if @current_revision.empty?
end
@report = T.let(nil, T.nilable(Report))
end
sig { params(auto_update: T::Boolean).returns(Report) }
def report(auto_update: false)
return @report if @report
@report = {
A: [], AC: [], D: [], DC: [], M: [], MC: [], R: T.let([], T::Array[[String, String]]),
RC: T.let([], T::Array[[String, String]]), T: []
}
return @report unless updated?
diff.each_line do |line|
status, *paths = line.split
src = Pathname.new paths.first
dst = Pathname.new paths.last
next if dst.extname != ".rb"
if paths.any? { |p| tap.cask_file?(p) }
case status
when "A"
# Have a dedicated report array for new casks.
@report[:AC] << tap.formula_file_to_name(src)
when "D"
# Have a dedicated report array for deleted casks.
@report[:DC] << tap.formula_file_to_name(src)
when "M"
# Report updated casks
@report[:MC] << tap.formula_file_to_name(src)
when /^R\d{0,3}/
src_full_name = tap.formula_file_to_name(src)
dst_full_name = tap.formula_file_to_name(dst)
# Don't report formulae that are moved within a tap but not renamed
next if src_full_name == dst_full_name
@report[:DC] << src_full_name
@report[:AC] << dst_full_name
end
end
next unless paths.any? do |p|
tap.formula_file?(p) ||
# Need to check for case where Formula directory was deleted
(status == "D" && File.fnmatch?("{Homebrew,}Formula/**/*.rb", p, File::FNM_EXTGLOB | File::FNM_PATHNAME))
end
case status
when "A", "D"
full_name = tap.formula_file_to_name(src)
name = full_name.split("/").fetch(-1)
new_tap = tap.tap_migrations[name]
if new_tap.blank?
@report[T.must(status).to_sym] << full_name
elsif status == "D"
# Retain deleted formulae for tap migrations separately to avoid reporting as deleted
@report[:T] << full_name
end
when "M"
name = tap.formula_file_to_name(src)
@report[:M] << name
when /^R\d{0,3}/
src_full_name = tap.formula_file_to_name(src)
dst_full_name = tap.formula_file_to_name(dst)
# Don't report formulae that are moved within a tap but not renamed
next if src_full_name == dst_full_name
@report[:D] << src_full_name
@report[:A] << dst_full_name
end
end
renamed_casks = Set.new
@report[:DC].each do |old_full_name|
old_name = old_full_name.split("/").last
new_name = tap.cask_renames[old_name]
next unless new_name
new_full_name = if tap.core_cask_tap?
new_name
else
"#{tap}/#{new_name}"
end
renamed_casks << [old_full_name, new_full_name] if @report[:AC].include?(new_full_name)
end
@report[:AC].each do |new_full_name|
new_name = new_full_name.split("/").last
old_name = tap.cask_renames.key(new_name)
next unless old_name
old_full_name = if tap.core_cask_tap?
old_name
else
"#{tap}/#{old_name}"
end
renamed_casks << [old_full_name, new_full_name]
end
if renamed_casks.any?
@report[:AC] -= renamed_casks.map(&:last)
@report[:DC] -= renamed_casks.map(&:first)
@report[:RC] = renamed_casks.to_a
end
renamed_formulae = Set.new
@report[:D].each do |old_full_name|
old_name = old_full_name.split("/").last
new_name = tap.formula_renames[old_name]
next unless new_name
new_full_name = if tap.core_tap?
new_name
else
"#{tap}/#{new_name}"
end
renamed_formulae << [old_full_name, new_full_name] if @report[:A].include? new_full_name
end
@report[:A].each do |new_full_name|
new_name = new_full_name.split("/").last
old_name = tap.formula_renames.key(new_name)
next unless old_name
old_full_name = if tap.core_tap?
old_name
else
"#{tap}/#{old_name}"
end
renamed_formulae << [old_full_name, new_full_name]
end
if renamed_formulae.any?
@report[:A] -= renamed_formulae.map(&:last)
@report[:D] -= renamed_formulae.map(&:first)
@report[:R] = renamed_formulae.to_a
end
# If any formulae/casks are marked as added and deleted, remove them from
# the report as we've not detected things correctly.
if (added_and_deleted_formulae = (@report[:A] & @report[:D]).presence)
@report[:A] -= added_and_deleted_formulae
@report[:D] -= added_and_deleted_formulae
end
if (added_and_deleted_casks = (@report[:AC] & @report[:DC]).presence)
@report[:AC] -= added_and_deleted_casks
@report[:DC] -= added_and_deleted_casks
end
@report
end
sig { returns(T::Boolean) }
def updated?
if installed_from_api?
diff.present?
else
initial_revision != current_revision
end
end
sig { void }
def migrate_tap_migration
[report[:D], report[:DC], report[:T]].flatten.each do |full_name|
name = full_name.split("/").fetch(-1)
new_tap_name = tap.tap_migrations[name]
next if new_tap_name.nil? # skip if not in tap_migrations list.
new_tap_user, new_tap_repo, new_tap_new_name = new_tap_name.split("/")
new_name = if new_tap_new_name
new_full_name = new_tap_new_name
new_tap_name = "#{new_tap_user}/#{new_tap_repo}"
new_tap_new_name
elsif new_tap_repo
new_full_name = "#{new_tap_name}/#{name}"
name
else
new_tap_name = tap.name
new_full_name = "#{new_tap_name}/#{new_tap_user}"
new_tap_user
end
# This means it is a cask
if Array(report[:DC]).include? full_name
next unless (HOMEBREW_PREFIX/"Caskroom"/new_name).exist?
new_tap = Tap.fetch(new_tap_name)
new_tap.ensure_installed!
ohai "#{name} has been moved to Homebrew.", <<~EOS
To uninstall the cask, run:
brew uninstall --cask --force #{name}
EOS
next if (HOMEBREW_CELLAR/new_name.split("/").last).directory?
ohai "Installing #{new_name}..."
system HOMEBREW_BREW_FILE, "install", new_full_name
begin
unless Formulary.factory(new_full_name).keg_only?
system HOMEBREW_BREW_FILE, "link", new_full_name, "--overwrite"
end
# Rescue any possible exception types.
rescue Exception => e # rubocop:disable Lint/RescueException
if Homebrew::EnvConfig.developer?
require "utils/backtrace"
onoe "#{e.message}\n#{Utils::Backtrace.clean(e)&.join("\n")}"
end
end
next
end
next unless (dir = HOMEBREW_CELLAR/name).exist? # skip if formula is not installed.
tabs = dir.subdirs.map { |d| Keg.new(d).tab }
next if tabs.first.tap != tap # skip if installed formula is not from this tap.
new_tap = Tap.fetch(new_tap_name)
# For formulae migrated to cask: Auto-install cask or provide install instructions.
# Check if the migration target is a cask (either in homebrew/cask or any other tap)
if new_tap.core_cask_tap? || new_tap.cask_tokens.intersect?([new_full_name, new_name])
migration_message = if new_tap == tap
"#{full_name} has been migrated from a formula to a cask."
else
"#{name} has been moved to #{new_tap_name}."
end
if new_tap.installed? && (HOMEBREW_PREFIX/"Caskroom").directory?
ohai migration_message
ohai "brew unlink #{name}"
system HOMEBREW_BREW_FILE, "unlink", name
ohai "brew cleanup"
system HOMEBREW_BREW_FILE, "cleanup"
ohai "brew install --cask #{new_full_name}"
system HOMEBREW_BREW_FILE, "install", "--cask", new_full_name
ohai migration_message, <<~EOS
The existing keg has been unlinked.
Please uninstall the formula when convenient by running:
brew uninstall --formula --force #{name}
EOS
else
ohai migration_message, <<~EOS
To uninstall the formula and install the cask, run:
brew uninstall --formula --force #{name}
brew tap #{new_tap_name}
brew install --cask #{new_full_name}
EOS
end
else
new_tap.ensure_installed!
# update tap for each Tab
tabs.each { |tab| tab.tap = new_tap }
tabs.each(&:write)
end
end
end
sig { void }
def migrate_cask_rename
Cask::Caskroom.casks.each do |cask|
Cask::Migrator.migrate_if_needed(cask)
end
end
sig { params(force: T::Boolean, verbose: T::Boolean).void }
def migrate_formula_rename(force:, verbose:)
Formula.installed.each do |formula|
next unless Migrator.needs_migration?(formula)
oldnames_to_migrate = formula.oldnames.select do |oldname|
oldname_rack = HOMEBREW_CELLAR/oldname
next false unless oldname_rack.exist?
if oldname_rack.subdirs.empty?
oldname_rack.rmdir_if_possible
next false
end
true
end
next if oldnames_to_migrate.empty?
Migrator.migrate_if_needed(formula, force:)
end
end
private
sig { returns(Tap) }
attr_reader :tap
sig { returns(String) }
attr_reader :initial_revision
sig { returns(String) }
attr_reader :current_revision
sig { returns(T.nilable(Pathname)) }
attr_reader :api_names_txt
sig { returns(T.nilable(Pathname)) }
attr_reader :api_names_before_txt
sig { returns(T.nilable(Pathname)) }
attr_reader :api_dir_prefix
sig {
params(api_names_txt: T.nilable(Pathname), api_names_before_txt: T.nilable(Pathname),
api_dir_prefix: T.nilable(Pathname)).returns(T::Boolean)
}
def installed_from_api?(api_names_txt = @api_names_txt, api_names_before_txt = @api_names_before_txt,
api_dir_prefix = @api_dir_prefix)
!api_names_txt.nil? && !api_names_before_txt.nil? && !api_dir_prefix.nil?
end
sig { returns(String) }
def diff
@diff ||= T.let(nil, T.nilable(String))
@diff ||= if installed_from_api?
# Hack `git diff` output with regexes to look like `git diff-tree` output.
# Yes, I know this is a bit filthy but it saves duplicating the #report logic.
diff_output = Utils.popen_read("git", "diff", "--no-ext-diff", api_names_before_txt, api_names_txt)
header_regex = /^(---|\+\+\+) /
add_delete_characters = ["+", "-"].freeze
api_dir_prefix_basename = T.must(api_dir_prefix).basename
diff_hash = diff_output.lines.each_with_object({}) do |line, hash|
next if line.match?(header_regex)
next unless add_delete_characters.include?(line[0])
name = line.chomp.delete_prefix("+").delete_prefix("-")
file = "#{api_dir_prefix_basename}/#{name}.rb"
hash[file] ||= 0
if line.start_with?("+")
hash[file] += 1
elsif line.start_with?("-")
hash[file] -= 1
end
end
diff_hash.filter_map do |file, count|
if count.positive?
"A #{file}"
elsif count.negative?
"D #{file}"
end
end.join("\n")
else
Utils.popen_read(
"git", "-C", tap.path, "diff-tree", "-r", "--name-status", "--diff-filter=AMDR",
"-M85%", initial_revision, current_revision
)
end
end
end
class ReporterHub
include Utils::Output::Mixin
sig { returns(T::Array[Reporter]) }
attr_reader :reporters
sig { void }
def initialize
@hash = T.let({}, T::Hash[Symbol, T::Array[T.any(String, [String, String])]])
@reporters = T.let([], T::Array[Reporter])
end
sig { params(key: Symbol).returns(T::Array[String]) }
def select_formula_or_cask(key)
raise "Unsupported key #{key}" unless [:A, :AC, :D, :DC, :M, :MC, :R, :RC, :T].include?(key)
T.cast(@hash.fetch(key, []), T::Array[String])
end
sig { params(reporter: Reporter, auto_update: T::Boolean).void }
def add(reporter, auto_update: false)
@reporters << reporter
report = reporter.report(auto_update:).reject { |_k, v| v.empty? }
@hash.update(report) { |_key, oldval, newval| oldval.concat(newval) }
end
sig { returns(T::Boolean) }
def empty?
@hash.empty?
end
sig { params(auto_update: T::Boolean).void }
def dump(auto_update: false)
unless Homebrew::EnvConfig.no_update_report_new?
dump_new_formula_report
dump_new_cask_report
end
dump_deleted_formula_report
dump_deleted_cask_report
outdated_formulae = Formula.installed.select(&:outdated?).map(&:name)
outdated_casks = Cask::Caskroom.casks.select(&:outdated?).map(&:token)
unless auto_update
output_dump_formula_or_cask_report "Outdated Formulae", outdated_formulae
output_dump_formula_or_cask_report "Outdated Casks", outdated_casks
end
return if outdated_formulae.blank? && outdated_casks.blank?
outdated_formulae = outdated_formulae.count
outdated_casks = outdated_casks.count
update_pronoun = if (outdated_formulae + outdated_casks) == 1
"it"
else
"them"
end
msg = ""
if outdated_formulae.positive?
noun = Utils.pluralize("formula", outdated_formulae)
msg += "#{Tty.bold}#{outdated_formulae}#{Tty.reset} outdated #{noun}"
end
if outdated_casks.positive?
msg += " and " if msg.present?
msg += "#{Tty.bold}#{outdated_casks}#{Tty.reset} outdated #{Utils.pluralize("cask", outdated_casks)}"
end
return if msg.blank?
puts
puts "You have #{msg} installed."
# If we're auto-updating, don't need to suggest commands that we're perhaps
# already running.
return if auto_update
puts <<~EOS
You can upgrade #{update_pronoun} with #{Tty.bold}brew upgrade#{Tty.reset}
or list #{update_pronoun} with #{Tty.bold}brew outdated#{Tty.reset}.
EOS
end
private
sig { void }
def dump_new_formula_report
formulae = select_formula_or_cask(:A).sort.reject { |name| installed?(name) }
return if formulae.blank?
ohai "New Formulae"
should_display_descriptions = if Homebrew::EnvConfig.no_install_from_api?
formulae.size <= 100
else
true
end
formulae.each do |formula|
if should_display_descriptions && (desc = description(formula))
puts "#{formula}: #{desc}"
else
puts formula
end
end
end
sig { void }
def dump_new_cask_report
return unless Cask::Caskroom.any_casks_installed?
casks = select_formula_or_cask(:AC).sort.reject { |name| cask_installed?(name) }
return if casks.blank?
ohai "New Casks"
should_display_descriptions = if Homebrew::EnvConfig.no_install_from_api?
casks.size <= 100
else
true
end
casks.each do |cask|
cask_token = cask.split("/").fetch(-1)
if should_display_descriptions && (desc = cask_description(cask))
puts "#{cask_token}: #{desc}"
else
puts cask_token
end
end
end
sig { void }
def dump_deleted_formula_report
formulae = select_formula_or_cask(:D).sort.filter_map do |name|
pretty_uninstalled(name) if installed?(name)
end
output_dump_formula_or_cask_report "Deleted Installed Formulae", formulae
end
sig { void }
def dump_deleted_cask_report
return if Homebrew::SimulateSystem.simulating_or_running_on_linux?
casks = select_formula_or_cask(:DC).sort.filter_map do |name|
name = name.split("/").fetch(-1)
pretty_uninstalled(name) if cask_installed?(name)
end
output_dump_formula_or_cask_report "Deleted Installed Casks", casks
end
sig { params(title: String, formulae_or_casks: T::Array[String]).void }
def output_dump_formula_or_cask_report(title, formulae_or_casks)
return if formulae_or_casks.blank?
ohai title, Formatter.columns(formulae_or_casks.sort)
end
sig { params(formula: String).returns(T::Boolean) }
def installed?(formula)
(HOMEBREW_CELLAR/formula.split("/").last).directory?
end
sig { params(cask: String).returns(T::Boolean) }
def cask_installed?(cask)
(Cask::Caskroom.path/cask).directory?
end
sig { returns(T::Array[T.untyped]) }
def all_formula_json
return @all_formula_json if @all_formula_json
@all_formula_json = T.let(nil, T.nilable(T::Array[T.untyped]))
all_formula_json, = Homebrew::API.fetch_json_api_file "formula.jws.json"
all_formula_json = T.cast(all_formula_json, T::Array[T.untyped])
@all_formula_json = all_formula_json
end
sig { returns(T::Array[T.untyped]) }
def all_cask_json
return @all_cask_json if @all_cask_json
@all_cask_json = T.let(nil, T.nilable(T::Array[T.untyped]))
all_cask_json, = Homebrew::API.fetch_json_api_file "cask.jws.json"
all_cask_json = T.cast(all_cask_json, T::Array[T.untyped])
@all_cask_json = all_cask_json
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/log.rb | Library/Homebrew/cmd/log.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module Cmd
class Log < AbstractCommand
include FileUtils
cmd_args do
description <<~EOS
Show the `git log` for <formula> or <cask>, or show the log for the Homebrew repository
if no formula or cask is provided.
EOS
switch "-p", "-u", "--patch",
description: "Also print patch from commit."
switch "--stat",
description: "Also print diffstat from commit."
switch "--oneline",
description: "Print only one line per commit."
switch "-1",
description: "Print only one commit."
flag "-n", "--max-count=",
description: "Print only a specified number of commits."
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "-1", "--max-count"
conflicts "--formula", "--cask"
named_args [:formula, :cask], max: 1, without_api: true
end
sig { override.void }
def run
# As this command is simplifying user-run commands then let's just use a
# user path, too.
ENV["PATH"] = PATH.new(ORIGINAL_PATHS).to_s
if args.no_named?
git_log(HOMEBREW_REPOSITORY)
else
path = args.named.to_paths.fetch(0)
tap = Tap.from_path(path)
git_log path.dirname, path, tap
end
end
private
sig { params(cd_dir: Pathname, path: T.nilable(Pathname), tap: T.nilable(Tap)).void }
def git_log(cd_dir, path = nil, tap = nil)
cd cd_dir do
repo = Utils.popen_read("git", "rev-parse", "--show-toplevel").chomp
if tap
name = tap.to_s
git_cd = "$(brew --repo #{tap})"
elsif cd_dir == HOMEBREW_REPOSITORY
name = "Homebrew/brew"
git_cd = "$(brew --repo)"
else
name, git_cd = cd_dir
end
if File.exist? "#{repo}/.git/shallow"
opoo <<~EOS
#{name} is a shallow clone so only partial output will be shown.
To get a full clone, run:
git -C "#{git_cd}" fetch --unshallow
EOS
end
git_args = []
git_args << "--patch" if args.patch?
git_args << "--stat" if args.stat?
git_args << "--oneline" if args.oneline?
git_args << "-1" if args.public_send(:"1?")
git_args << "--max-count" << args.max_count if args.max_count
git_args += ["--follow", "--", path] if path&.file?
system "git", "log", *git_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/cmd/pin.rb | Library/Homebrew/cmd/pin.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module Cmd
class Pin < AbstractCommand
cmd_args do
description <<~EOS
Pin the specified <formula>, preventing them from being upgraded when
issuing the `brew upgrade` <formula> command. See also `unpin`.
*Note:* Other packages which depend on newer versions of a pinned formula
might not install or run correctly.
EOS
named_args :installed_formula, min: 1
end
sig { override.void }
def run
args.named.to_resolved_formulae.each do |f|
if f.pinned?
opoo "#{f.name} already pinned"
elsif !f.pinnable?
ofail "#{f.name} not installed"
else
f.pin
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/cmd/docs.rb | Library/Homebrew/cmd/docs.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class Docs < AbstractCommand
cmd_args do
description <<~EOS
Open Homebrew's online documentation at <#{HOMEBREW_DOCS_WWW}> in a browser.
EOS
end
sig { override.void }
def run
exec_browser HOMEBREW_DOCS_WWW
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/cmd/uninstall.rb | Library/Homebrew/cmd/uninstall.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "keg"
require "formula"
require "diagnostic"
require "migrator"
require "cask/cask_loader"
require "cask/exceptions"
require "cask/installer"
require "cask/uninstall"
require "uninstall"
module Homebrew
module Cmd
class UninstallCmd < AbstractCommand
cmd_args do
description <<~EOS
Uninstall a <formula> or <cask>.
EOS
switch "-f", "--force",
description: "Delete all installed versions of <formula>. Uninstall even if <cask> is not " \
"installed, overwrite existing files and ignore errors when removing files."
switch "--zap",
description: "Remove all files associated with a <cask>. " \
"*May remove files which are shared between applications.*"
switch "--ignore-dependencies",
description: "Don't fail uninstall, even if <formula> is a dependency of any installed " \
"formulae."
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--formula", "--cask"
conflicts "--formula", "--zap"
named_args [:installed_formula, :installed_cask], min: 1
end
sig { override.void }
def run
all_kegs, casks = args.named.to_kegs_to_casks(
ignore_unavailable: args.force?,
all_kegs: args.force?,
)
# If ignore_unavailable is true and the named args
# are a series of invalid kegs and casks,
# #to_kegs_to_casks will return empty arrays.
return if all_kegs.blank? && casks.blank?
kegs_by_rack = all_kegs.group_by(&:rack)
Uninstall.uninstall_kegs(
kegs_by_rack,
casks:,
force: args.force?,
ignore_dependencies: args.ignore_dependencies?,
named_args: args.named,
)
Cask::Uninstall.check_dependent_casks(*casks, named_args: args.named) unless args.ignore_dependencies?
return if Homebrew.failed?
if args.zap?
casks.each do |cask|
odebug "Zapping Cask #{cask}"
raise Cask::CaskNotInstalledError, cask if !cask.installed? && !args.force?
Cask::Installer.new(cask, verbose: args.verbose?, force: args.force?).zap
end
else
Cask::Uninstall.uninstall_casks(
*casks,
verbose: args.verbose?,
force: args.force?,
)
end
if ENV["HOMEBREW_AUTOREMOVE"].present?
opoo "`$HOMEBREW_AUTOREMOVE` is now a no-op as it is the default behaviour. " \
"Set `HOMEBREW_NO_AUTOREMOVE=1` to disable it."
end
Cleanup.autoremove unless Homebrew::EnvConfig.no_autoremove?
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/cmd/which-formula.rb | Library/Homebrew/cmd/which-formula.rb | # typed: strict
# frozen_string_literal: true
# License: MIT
# The license text can be found in Library/Homebrew/command-not-found/LICENSE
require "abstract_command"
require "api"
require "shell_command"
module Homebrew
module Cmd
class WhichFormula < AbstractCommand
ENDPOINT = "internal/executables.txt"
DATABASE_FILE = T.let((Homebrew::API::HOMEBREW_CACHE_API/ENDPOINT).freeze, Pathname)
include ShellCommand
cmd_args do
description <<~EOS
Show which formula(e) provides the given command.
EOS
switch "--explain",
description: "Output explanation of how to get <command> by installing one of the providing formulae."
switch "--skip-update",
description: "Skip updating the executables database if any version exists on disk, no matter how old."
named_args :command, min: 1
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/cmd/command-not-found-init.rb | Library/Homebrew/cmd/command-not-found-init.rb | # typed: strict
# frozen_string_literal: true
# License: MIT
# The license text can be found in Library/Homebrew/command-not-found/LICENSE
require "abstract_command"
require "utils/shell"
module Homebrew
module Cmd
class CommandNotFoundInit < AbstractCommand
cmd_args do
description <<~EOS
Print instructions for setting up the command-not-found hook for your shell.
If the output is not to a tty, print the appropriate handler script for your shell.
For more information, see:
https://docs.brew.sh/Command-Not-Found
EOS
named_args :none
end
sig { override.void }
def run
if $stdout.tty?
help
else
init
end
end
sig { returns(T.nilable(Symbol)) }
def shell
Utils::Shell.parent || Utils::Shell.preferred
end
sig { void }
def init
case shell
when :bash, :zsh
puts File.read(File.expand_path("#{File.dirname(__FILE__)}/../command-not-found/handler.sh"))
when :fish
puts File.read(File.expand_path("#{File.dirname(__FILE__)}/../command-not-found/handler.fish"))
else
raise "Unsupported shell type #{shell}"
end
end
sig { void }
def help
case shell
when :bash, :zsh
puts <<~EOS
# To enable command-not-found
# Add the following lines to ~/.#{shell}rc
HOMEBREW_COMMAND_NOT_FOUND_HANDLER="$(brew --repository)/Library/Homebrew/command-not-found/handler.sh"
if [ -f "$HOMEBREW_COMMAND_NOT_FOUND_HANDLER" ]; then
source "$HOMEBREW_COMMAND_NOT_FOUND_HANDLER";
fi
EOS
when :fish
puts <<~EOS
# To enable command-not-found
# Add the following line to ~/.config/fish/config.fish
set HOMEBREW_COMMAND_NOT_FOUND_HANDLER (brew --repository)/Library/Homebrew/command-not-found/handler.fish
if test -f $HOMEBREW_COMMAND_NOT_FOUND_HANDLER
source $HOMEBREW_COMMAND_NOT_FOUND_HANDLER
end
EOS
else
raise "Unsupported shell type #{shell}"
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/cmd/--prefix.rb | Library/Homebrew/cmd/--prefix.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module Cmd
class Prefix < AbstractCommand
include FileUtils
UNBREWED_EXCLUDE_FILES = %w[.DS_Store].freeze
UNBREWED_EXCLUDE_PATHS = %w[
*/.keepme
.github/*
bin/brew
completions/zsh/_brew
docs/*
lib/gdk-pixbuf-2.0/*
lib/gio/*
lib/node_modules/*
lib/python[23].[0-9]/*
lib/python3.[0-9][0-9]/*
lib/pypy/*
lib/pypy3/*
lib/ruby/gems/[12].*
lib/ruby/site_ruby/[12].*
lib/ruby/vendor_ruby/[12].*
manpages/brew.1
share/pypy/*
share/pypy3/*
share/info/dir
share/man/whatis
share/mime/*
texlive/*
].freeze
sig { override.returns(String) }
def self.command_name = "--prefix"
cmd_args do
description <<~EOS
Display Homebrew's install path. *Default:*
- macOS ARM: `#{HOMEBREW_MACOS_ARM_DEFAULT_PREFIX}`
- macOS Intel: `#{HOMEBREW_DEFAULT_PREFIX}`
- Linux: `#{HOMEBREW_LINUX_DEFAULT_PREFIX}`
If <formula> is provided, display the location where <formula> is or would be installed.
EOS
switch "--unbrewed",
description: "List files in Homebrew's prefix not installed by Homebrew."
switch "--installed",
description: "Outputs nothing and returns a failing status code if <formula> is not installed."
conflicts "--unbrewed", "--installed"
named_args :formula
end
sig { override.void }
def run
raise UsageError, "`--installed` requires a formula argument." if args.installed? && args.no_named?
if args.unbrewed?
raise UsageError, "`--unbrewed` does not take a formula argument." unless args.no_named?
list_unbrewed
elsif args.no_named?
puts HOMEBREW_PREFIX
else
formulae = args.named.to_resolved_formulae
prefixes = formulae.filter_map do |f|
next nil if args.installed? && !f.opt_prefix.exist?
# this case will be short-circuited by brew.sh logic for a single formula
f.opt_prefix
end
puts prefixes
if args.installed?
missing_formulae = formulae.reject(&:optlinked?)
.map(&:name)
return if missing_formulae.blank?
raise NotAKegError, <<~EOS
The following formulae are not installed:
#{missing_formulae.join(" ")}
EOS
end
end
end
private
sig { void }
def list_unbrewed
dirs = HOMEBREW_PREFIX.subdirs.map { |dir| dir.basename.to_s }
dirs -= %w[Library Cellar Caskroom .git]
# Exclude cache, logs and repository, if they are located under the prefix.
[HOMEBREW_CACHE, HOMEBREW_LOGS, HOMEBREW_REPOSITORY].each do |dir|
dirs.delete dir.relative_path_from(HOMEBREW_PREFIX).to_s
end
dirs.delete "etc"
dirs.delete "var"
arguments = dirs.sort + %w[-type f (]
arguments.concat UNBREWED_EXCLUDE_FILES.flat_map { |f| %W[! -name #{f}] }
arguments.concat UNBREWED_EXCLUDE_PATHS.flat_map { |d| %W[! -path #{d}] }
arguments.push ")"
cd(HOMEBREW_PREFIX) { safe_system("find", *arguments) }
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/cmd/postinstall.rb | Library/Homebrew/cmd/postinstall.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "sandbox"
require "formula_installer"
module Homebrew
module Cmd
class Postinstall < AbstractCommand
cmd_args do
description <<~EOS
Rerun the post-install steps for <formula>.
EOS
named_args :installed_formula, min: 1
end
sig { override.void }
def run
args.named.to_resolved_formulae.each do |f|
ohai "Postinstalling #{f}"
f.install_etc_var
if f.post_install_defined?
fi = FormulaInstaller.new(f, **{ debug: args.debug?, quiet: args.quiet?, verbose: args.verbose? }.compact)
fi.post_install
else
opoo "#{f}: no `post_install` method was defined in the formula!"
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/cmd/--taps.rb | Library/Homebrew/cmd/--taps.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class Taps < AbstractCommand
include ShellCommand
sig { override.returns(String) }
def self.command_name = "--taps"
cmd_args do
description <<~EOS
Display the path to Homebrew’s Taps directory.
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/autoremove.rb | Library/Homebrew/cmd/autoremove.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "cleanup"
module Homebrew
module Cmd
class Autoremove < AbstractCommand
cmd_args do
description <<~EOS
Uninstall formulae that were only installed as a dependency of another formula and are now no longer needed.
EOS
switch "-n", "--dry-run",
description: "List what would be uninstalled, but do not actually uninstall anything."
named_args :none
end
sig { override.void }
def run
Cleanup.autoremove(dry_run: args.dry_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/cmd/--env.rb | Library/Homebrew/cmd/--env.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "extend/ENV"
require "build_environment"
require "utils/shell"
module Homebrew
module Cmd
class Env < AbstractCommand
sig { override.returns(String) }
def self.command_name = "--env"
cmd_args do
description <<~EOS
Summarise Homebrew's build environment as a plain list.
If the command's output is sent through a pipe and no shell is specified,
the list is formatted for export to `bash`(1) unless `--plain` is passed.
EOS
flag "--shell=",
description: "Generate a list of environment variables for the specified shell, " \
"or `--shell=auto` to detect the current shell."
switch "--plain",
description: "Generate plain output even when piped."
named_args :formula
end
sig { override.void }
def run
ENV.activate_extensions!
ENV.deps = args.named.to_formulae if superenv?(nil)
ENV.setup_build_environment
shell = if args.plain?
nil
elsif args.shell.nil?
:bash unless $stdout.tty?
elsif args.shell == "auto"
Utils::Shell.parent || Utils::Shell.preferred
elsif args.shell
Utils::Shell.from_path(T.must(args.shell))
end
if shell.nil?
BuildEnvironment.dump ENV.to_h
else
BuildEnvironment.keys(ENV.to_h).each do |key|
puts Utils::Shell.export_value(key, ENV.fetch(key), shell)
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/cmd/mcp-server.rb | Library/Homebrew/cmd/mcp-server.rb | # typed: strong
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class McpServerCmd < AbstractCommand
# This is a shell command as MCP servers need a faster startup time
# than a normal Homebrew Ruby command allows.
include ShellCommand
cmd_args do
description <<~EOS
Starts the Homebrew MCP (Model Context Protocol) server.
EOS
switch "-d", "--debug", description: "Enable debug logging to stderr."
switch "--ping", description: "Start the server, act as if receiving a ping and then exit.", hidden: true
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/tab.rb | Library/Homebrew/cmd/tab.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "tab"
module Homebrew
module Cmd
class TabCmd < AbstractCommand
cmd_args do
description <<~EOS
Edit tab information for installed formulae or casks.
This can be useful when you want to control whether an installed
formula should be removed by `brew autoremove`.
To prevent removal, mark the formula as installed on request;
to allow removal, mark the formula as not installed on request.
EOS
switch "--installed-on-request",
description: "Mark <installed_formula> or <installed_cask> as installed on request."
switch "--no-installed-on-request",
description: "Mark <installed_formula> or <installed_cask> as not installed on request."
switch "--formula", "--formulae",
description: "Only mark formulae."
switch "--cask", "--casks",
description: "Only mark casks."
conflicts "--formula", "--cask"
conflicts "--installed-on-request", "--no-installed-on-request"
named_args [:installed_formula, :installed_cask], min: 1
end
sig { override.void }
def run
installed_on_request = if args.installed_on_request?
true
elsif args.no_installed_on_request?
false
end
raise UsageError, "No marking option specified." if installed_on_request.nil?
formulae, casks = T.cast(args.named.to_formulae_to_casks, [T::Array[Formula], T::Array[Cask::Cask]])
formulae_not_installed = formulae.reject(&:any_version_installed?)
casks_not_installed = casks.reject(&:installed?)
if formulae_not_installed.any? || casks_not_installed.any?
names = formulae_not_installed.map(&:name) + casks_not_installed.map(&:token)
is_or_are = (names.length == 1) ? "is" : "are"
odie "#{names.to_sentence} #{is_or_are} not installed."
end
[*formulae, *casks].each do |formula_or_cask|
update_tab formula_or_cask, installed_on_request:
end
end
private
sig { params(formula_or_cask: T.any(Formula, Cask::Cask), installed_on_request: T::Boolean).void }
def update_tab(formula_or_cask, installed_on_request:)
name, tab = if formula_or_cask.is_a?(Formula)
[formula_or_cask.name, Tab.for_formula(formula_or_cask)]
else
[formula_or_cask.token, formula_or_cask.tab]
end
if tab.tabfile.blank? || !tab.tabfile.exist?
raise ArgumentError,
"Tab file for #{name} does not exist."
end
installed_on_request_str = "#{"not " unless installed_on_request}installed on request"
if (tab.installed_on_request && installed_on_request) ||
(!tab.installed_on_request && !installed_on_request)
ohai "#{name} is already marked as #{installed_on_request_str}."
return
end
tab.installed_on_request = installed_on_request
tab.write
ohai "#{name} is now marked as #{installed_on_request_str}."
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/cmd/untap.rb | Library/Homebrew/cmd/untap.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class Untap < AbstractCommand
cmd_args do
description <<~EOS
Remove a tapped formula repository.
EOS
switch "-f", "--force",
description: "Untap even if formulae or casks from this tap are currently installed."
named_args :tap, min: 1
end
sig { override.void }
def run
args.named.to_installed_taps.each do |tap|
odie "Untapping #{tap} is not allowed" if tap.core_tap? && Homebrew::EnvConfig.no_install_from_api?
if Homebrew::EnvConfig.no_install_from_api? || (!tap.core_tap? && !tap.core_cask_tap?)
installed_tap_formulae = installed_formulae_for(tap:)
installed_tap_casks = installed_casks_for(tap:)
if installed_tap_formulae.present? || installed_tap_casks.present?
installed_names = (installed_tap_formulae + installed_tap_casks.map(&:token)).join("\n")
if args.force? || Homebrew::EnvConfig.developer?
opoo <<~EOS
Untapping #{tap} even though it contains the following installed formulae or casks:
#{installed_names}
EOS
else
odie <<~EOS
Refusing to untap #{tap} because it contains the following installed formulae or casks:
#{installed_names}
EOS
end
end
end
tap.uninstall manual: true
end
end
# All installed formulae currently available in a tap by formula full name.
sig { params(tap: Tap).returns(T::Array[Formula]) }
def installed_formulae_for(tap:)
tap.formula_names.filter_map do |formula_name|
next unless installed_formulae_names.include?(formula_name.split("/").fetch(-1))
formula = begin
Formulary.factory(formula_name)
rescue FormulaUnavailableError
# Don't blow up because of a single unavailable formula.
next
end
# Can't use Formula#any_version_installed? because it doesn't consider
# taps correctly.
formula if formula.installed_kegs.any? { |keg| keg.tab.tap == tap }
end
end
# All installed casks currently available in a tap by cask full name.
sig { params(tap: Tap).returns(T::Array[Cask::Cask]) }
def installed_casks_for(tap:)
tap.cask_tokens.filter_map do |cask_token|
next unless installed_cask_tokens.include?(cask_token.split("/").fetch(-1))
cask = begin
Cask::CaskLoader.load(cask_token)
rescue Cask::CaskUnavailableError
# Don't blow up because of a single unavailable cask.
next
end
cask if cask.installed?
end
end
private
sig { returns(T::Set[String]) }
def installed_formulae_names
@installed_formulae_names ||= T.let(Formula.installed_formula_names.to_set.freeze, T.nilable(T::Set[String]))
end
sig { returns(T::Set[String]) }
def installed_cask_tokens
@installed_cask_tokens ||= T.let(Cask::Caskroom.tokens.to_set.freeze, T.nilable(T::Set[String]))
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/missing.rb | Library/Homebrew/cmd/missing.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "tab"
require "diagnostic"
module Homebrew
module Cmd
class Missing < AbstractCommand
cmd_args do
description <<~EOS
Check the given <formula> kegs for missing dependencies. If no <formula> are
provided, check all kegs. Will exit with a non-zero status if any kegs are found
to be missing dependencies.
EOS
comma_array "--hide",
description: "Act as if none of the specified <hidden> are installed. <hidden> should be " \
"a comma-separated list of formulae."
named_args :formula
end
sig { override.void }
def run
return unless HOMEBREW_CELLAR.exist?
ff = if args.no_named?
Formula.installed.sort
else
args.named.to_resolved_formulae.sort
end
ff.each do |f|
missing = f.missing_dependencies(hide: args.hide || [])
next if missing.empty?
Homebrew.failed = true
print "#{f}: " if ff.size > 1
puts missing.join(" ")
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/cmd/search.rb | Library/Homebrew/cmd/search.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "missing_formula"
require "descriptions"
require "search"
module Homebrew
module Cmd
class SearchCmd < AbstractCommand
PACKAGE_MANAGERS = T.let({
alpine: ->(query) { "https://pkgs.alpinelinux.org/packages?name=#{query}" },
repology: ->(query) { "https://repology.org/projects/?search=#{query}" },
macports: ->(query) { "https://ports.macports.org/search/?q=#{query}" },
fink: ->(query) { "https://pdb.finkproject.org/pdb/browse.php?summary=#{query}" },
opensuse: ->(query) { "https://software.opensuse.org/search?q=#{query}" },
fedora: ->(query) { "https://packages.fedoraproject.org/search?query=#{query}" },
archlinux: ->(query) { "https://archlinux.org/packages/?q=#{query}" },
debian: lambda { |query|
"https://packages.debian.org/search?keywords=#{query}&searchon=names&suite=all§ion=all"
},
ubuntu: lambda { |query|
"https://packages.ubuntu.com/search?keywords=#{query}&searchon=names&suite=all§ion=all"
},
}.freeze, T::Hash[Symbol, T.proc.params(query: String).returns(String)])
cmd_args do
description <<~EOS
Perform a substring search of cask tokens and formula names for <text>. If <text>
is flanked by slashes, it is interpreted as a regular expression.
EOS
switch "--formula", "--formulae",
description: "Search for formulae."
switch "--cask", "--casks",
description: "Search for casks."
switch "--desc",
description: "Search for formulae with a description matching <text> and casks with " \
"a name or description matching <text>."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to search their " \
"descriptions.",
env: :eval_all
switch "--pull-request",
description: "Search for GitHub pull requests containing <text>."
switch "--open",
depends_on: "--pull-request",
description: "Search for only open GitHub pull requests."
switch "--closed",
depends_on: "--pull-request",
description: "Search for only closed GitHub pull requests."
package_manager_switches = PACKAGE_MANAGERS.keys.map { |name| "--#{name}" }
package_manager_switches.each do |s|
switch s,
description: "Search for <text> in the given database."
end
conflicts "--desc", "--pull-request"
conflicts "--open", "--closed"
conflicts(*package_manager_switches)
named_args :text_or_regex, min: 1
end
sig { override.void }
def run
return if search_package_manager!
query = args.named.join(" ")
string_or_regex = Search.query_regexp(query)
if args.desc?
if !args.eval_all? && Homebrew::EnvConfig.no_install_from_api?
raise UsageError, "`brew search --desc` needs `--eval-all` passed or `HOMEBREW_EVAL_ALL=1` set!"
end
Search.search_descriptions(string_or_regex, args)
elsif args.pull_request?
search_pull_requests(query)
else
formulae, casks = Search.search_names(string_or_regex, args)
print_results(formulae, casks, query)
end
puts "Use `brew desc` to list packages with a short description." if args.verbose?
print_regex_help
end
private
sig { void }
def print_regex_help
return unless $stdout.tty?
metacharacters = %w[\\ | ( ) [ ] { } ^ $ * + ?].freeze
return unless metacharacters.any? do |char|
args.named.any? do |arg|
arg.include?(char) && !arg.start_with?("/")
end
end
opoo <<~EOS
Did you mean to perform a regular expression search?
Surround your query with /slashes/ to search locally by regex.
EOS
end
sig { returns(T::Boolean) }
def search_package_manager!
package_manager = PACKAGE_MANAGERS.find { |name,| args.public_send(:"#{name}?") }
return false if package_manager.nil?
_, url = package_manager
exec_browser url.call(URI.encode_www_form_component(args.named.join(" ")))
true
end
sig { params(query: String).returns(String) }
def search_pull_requests(query)
only = if args.open? && !args.closed?
"open"
elsif args.closed? && !args.open?
"closed"
end
GitHub.print_pull_requests_matching(query, only)
end
sig { params(all_formulae: T::Array[String], all_casks: T::Array[String], query: String).void }
def print_results(all_formulae, all_casks, query)
count = all_formulae.size + all_casks.size
if all_formulae.any?
if $stdout.tty?
ohai "Formulae", Formatter.columns(all_formulae)
else
puts all_formulae
end
end
puts if all_formulae.any? && all_casks.any?
if all_casks.any?
if $stdout.tty?
ohai "Casks", Formatter.columns(all_casks)
else
puts all_casks
end
end
print_missing_formula_help(query, count.positive?) if all_casks.exclude?(query)
odie "No formulae or casks found for #{query.inspect}." if count.zero?
end
sig { params(query: String, found_matches: T::Boolean).void }
def print_missing_formula_help(query, found_matches)
return unless $stdout.tty?
reason = MissingFormula.reason(query, silent: true)
return if reason.nil?
if found_matches
puts
puts "If you meant #{query.inspect} specifically:"
end
puts reason
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/cmd/nodenv-sync.rb | Library/Homebrew/cmd/nodenv-sync.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module Cmd
class NodenvSync < AbstractCommand
cmd_args do
description <<~EOS
Create symlinks for Homebrew's installed NodeJS versions in `~/.nodenv/versions`.
Note that older version symlinks will also be created so e.g. NodeJS 19.1.0 will
also be symlinked to 19.0.0.
EOS
named_args :none
end
sig { override.void }
def run
nodenv_root = Pathname(ENV.fetch("HOMEBREW_NODENV_ROOT", Pathname(Dir.home)/".nodenv"))
# Don't run multiple times at once.
nodenv_sync_running = nodenv_root/".nodenv_sync_running"
return if nodenv_sync_running.exist?
begin
nodenv_versions = nodenv_root/"versions"
nodenv_versions.mkpath
FileUtils.touch nodenv_sync_running
HOMEBREW_CELLAR.glob("node{,@*}")
.flat_map(&:children)
.each { |path| link_nodenv_versions(path, nodenv_versions) }
nodenv_versions.children
.select(&:symlink?)
.reject(&:exist?)
.each { |path| FileUtils.rm_f path }
ensure
nodenv_sync_running.unlink if nodenv_sync_running.exist?
end
end
private
sig { params(path: Pathname, nodenv_versions: Pathname).void }
def link_nodenv_versions(path, nodenv_versions)
nodenv_versions.mkpath
version = Keg.new(path).version
major_version = version.major.to_i
minor_version = version.minor.to_i
patch_version = version.patch.to_i
minor_version_range, patch_version_range = if Homebrew::EnvConfig.env_sync_strict?
# Only create symlinks for the exact installed patch version.
# e.g. 23.9.0 => 23.9.0
[[minor_version], [patch_version]]
else
# Create folder symlinks for all patch versions to the latest patch version
# e.g. 23.9.0 => 23.10.1
[0..minor_version, 0..patch_version]
end
minor_version_range.each do |minor|
patch_version_range.each do |patch|
link_path = nodenv_versions/"#{major_version}.#{minor}.#{patch}"
# Don't clobber existing user installations.
next if link_path.exist? && !link_path.symlink?
FileUtils.rm_f link_path
FileUtils.ln_s path, link_path
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/cmd/link.rb | Library/Homebrew/cmd/link.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "caveats"
require "unlink"
module Homebrew
module Cmd
class Link < AbstractCommand
cmd_args do
description <<~EOS
Symlink all of <formula>'s installed files into Homebrew's prefix.
This is done automatically when you install formulae but can be useful
for manual installations.
EOS
switch "--overwrite",
description: "Delete files that already exist in the prefix while linking."
switch "-n", "--dry-run",
description: "List files which would be linked or deleted by " \
"`brew link --overwrite` without actually linking or deleting any files."
switch "-f", "--force",
description: "Allow keg-only formulae to be linked."
switch "--HEAD",
description: "Link the HEAD version of the formula if it is installed."
named_args :installed_formula, min: 1
end
sig { override.void }
def run
options = {
overwrite: args.overwrite?,
dry_run: args.dry_run?,
verbose: args.verbose?,
}
kegs = if args.HEAD?
args.named.to_kegs.group_by(&:name).filter_map do |name, resolved_kegs|
head_keg = resolved_kegs.find { |keg| keg.version.head? }
next head_keg if head_keg.present?
opoo <<~EOS
No HEAD keg installed for #{name}
To install, run:
brew install --HEAD #{name}
EOS
nil
end
else
args.named.to_latest_kegs
end
kegs.freeze.each do |keg|
keg_only = Formulary.keg_only?(keg.rack)
if keg.linked?
opoo "Already linked: #{keg}"
name_and_flag = "#{"--HEAD " if args.HEAD?}#{"--force " if keg_only}#{keg.name}"
puts <<~EOS
To relink, run:
brew unlink #{keg.name} && brew link #{name_and_flag}
EOS
next
end
if args.dry_run?
if args.overwrite?
puts "Would remove:"
else
puts "Would link:"
end
keg.link(**options)
puts_keg_only_path_message(keg) if keg_only
next
end
formula = begin
keg.to_formula
rescue FormulaUnavailableError
# Not all kegs may belong to formulae
nil
end
if keg_only
if HOMEBREW_PREFIX.to_s == HOMEBREW_DEFAULT_PREFIX && formula.present? &&
formula.keg_only_reason.by_macos?
caveats = Caveats.new(formula)
opoo <<~EOS
Refusing to link macOS provided/shadowed software: #{keg.name}
#{T.must(caveats.keg_only_text(skip_reason: true)).strip}
EOS
next
end
if !args.force? && (formula.blank? || !formula.keg_only_reason.versioned_formula?)
opoo "#{keg.name} is keg-only and must be linked with `--force`."
puts_keg_only_path_message(keg)
next
end
end
Unlink.unlink_versioned_formulae(formula, verbose: args.verbose?) if formula
keg.lock do
print "Linking #{keg}... "
puts if args.verbose?
begin
n = keg.link(**options)
rescue Keg::LinkError
puts
raise
else
puts "#{n} symlinks created."
end
puts_keg_only_path_message(keg) if keg_only && !Homebrew::EnvConfig.developer?
end
end
end
private
sig { params(keg: Keg).void }
def puts_keg_only_path_message(keg)
bin = keg/"bin"
sbin = keg/"sbin"
return if !bin.directory? && !sbin.directory?
opt = HOMEBREW_PREFIX/"opt/#{keg.name}"
puts "\nIf you need to have this software first in your PATH instead consider running:"
puts " #{Utils::Shell.prepend_path_in_profile(opt/"bin")}" if bin.directory?
puts " #{Utils::Shell.prepend_path_in_profile(opt/"sbin")}" if sbin.directory?
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/cmd/help.rb | Library/Homebrew/cmd/help.rb | # typed: strong
# frozen_string_literal: true
require "abstract_command"
require "help"
module Homebrew
module Cmd
class HelpCmd < AbstractCommand
cmd_args do
description <<~EOS
Outputs the usage instructions for `brew` <command>.
Equivalent to `brew --help` <command>.
EOS
named_args [:command]
end
sig { override.void }
def run
Help.help
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/cmd/info.rb | Library/Homebrew/cmd/info.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "missing_formula"
require "caveats"
require "options"
require "formula"
require "keg"
require "tab"
require "json"
require "utils/spdx"
require "deprecate_disable"
require "api"
module Homebrew
module Cmd
class Info < AbstractCommand
class NameSize < T::Struct
const :name, String
const :size, Integer
end
private_constant :NameSize
VALID_DAYS = %w[30 90 365].freeze
VALID_FORMULA_CATEGORIES = %w[install install-on-request build-error].freeze
VALID_CATEGORIES = T.let((VALID_FORMULA_CATEGORIES + %w[cask-install os-version]).freeze, T::Array[String])
cmd_args do
description <<~EOS
Display brief statistics for your Homebrew installation.
If a <formula> or <cask> is provided, show summary of information about it.
EOS
switch "--analytics",
description: "List global Homebrew analytics data or, if specified, installation and " \
"build error data for <formula> (provided neither `$HOMEBREW_NO_ANALYTICS` " \
"nor `$HOMEBREW_NO_GITHUB_API` are set)."
flag "--days=",
depends_on: "--analytics",
description: "How many days of analytics data to retrieve. " \
"The value for <days> must be `30`, `90` or `365`. The default is `30`."
flag "--category=",
depends_on: "--analytics",
description: "Which type of analytics data to retrieve. " \
"The value for <category> must be `install`, `install-on-request` or `build-error`; " \
"`cask-install` or `os-version` may be specified if <formula> is not. " \
"The default is `install`."
switch "--github-packages-downloads",
description: "Scrape GitHub Packages download counts from HTML for a core formula.",
hidden: true
switch "--github",
description: "Open the GitHub source page for <formula> and <cask> in a browser. " \
"To view the history locally: `brew log -p` <formula> or <cask>"
switch "--fetch-manifest",
description: "Fetch GitHub Packages manifest for extra information when <formula> is not installed."
flag "--json",
description: "Print a JSON representation. Currently the default value for <version> is `v1` for " \
"<formula>. For <formula> and <cask> use `v2`. See the docs for examples of using the " \
"JSON output: <https://docs.brew.sh/Querying-Brew>"
switch "--installed",
depends_on: "--json",
description: "Print JSON of formulae that are currently installed."
switch "--eval-all",
depends_on: "--json",
description: "Evaluate all available formulae and casks, whether installed or not, to print their " \
"JSON."
switch "--variations",
depends_on: "--json",
description: "Include the variations hash in each formula's JSON output."
switch "-v", "--verbose",
description: "Show more verbose analytics data for <formula>."
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
switch "--sizes",
description: "Show the size of installed formulae and casks."
conflicts "--installed", "--eval-all"
conflicts "--formula", "--cask"
conflicts "--fetch-manifest", "--cask"
conflicts "--fetch-manifest", "--json"
named_args [:formula, :cask]
end
sig { override.void }
def run
if args.sizes?
if args.no_named?
print_sizes
else
formulae, casks = args.named.to_formulae_to_casks
formulae = T.cast(formulae, T::Array[Formula])
print_sizes(formulae:, casks:)
end
elsif args.analytics?
if args.days.present? && VALID_DAYS.exclude?(args.days)
raise UsageError, "`--days` must be one of #{VALID_DAYS.join(", ")}."
end
if args.category.present?
if args.named.present? && VALID_FORMULA_CATEGORIES.exclude?(args.category)
raise UsageError,
"`--category` must be one of #{VALID_FORMULA_CATEGORIES.join(", ")} when querying formulae."
end
unless VALID_CATEGORIES.include?(args.category)
raise UsageError, "`--category` must be one of #{VALID_CATEGORIES.join(", ")}."
end
end
print_analytics
elsif (json = args.json)
print_json(json, args.eval_all?)
elsif args.github?
raise FormulaOrCaskUnspecifiedError if args.no_named?
exec_browser(*args.named.to_formulae_and_casks.map do |formula_keg_or_cask|
formula_or_cask = T.cast(formula_keg_or_cask, T.any(Formula, Cask::Cask))
github_info(formula_or_cask)
end)
elsif args.no_named?
print_statistics
else
print_info
end
end
sig { params(remote: String, path: String).returns(String) }
def github_remote_path(remote, path)
if remote =~ %r{^(?:https?://|git(?:@|://))github\.com[:/](.+)/(.+?)(?:\.git)?$}
"https://github.com/#{Regexp.last_match(1)}/#{Regexp.last_match(2)}/blob/HEAD/#{path}"
else
"#{remote}/#{path}"
end
end
private
sig { void }
def print_statistics
return unless HOMEBREW_CELLAR.exist?
count = Formula.racks.length
puts "#{Utils.pluralize("keg", count, include_count: true)}, #{HOMEBREW_CELLAR.dup.abv}"
end
sig { void }
def print_analytics
if args.no_named?
Utils::Analytics.output(args:)
return
end
args.named.to_formulae_and_casks_and_unavailable.each_with_index do |obj, i|
puts unless i.zero?
case obj
when Formula
Utils::Analytics.formula_output(obj, args:) if obj.core_formula?
when Cask::Cask
Utils::Analytics.cask_output(obj, args:) if obj.tap.core_cask_tap?
when FormulaOrCaskUnavailableError
Utils::Analytics.output(filter: obj.name, args:)
else
raise
end
end
end
sig { void }
def print_info
args.named.to_formulae_and_casks_and_unavailable.each_with_index do |obj, i|
puts unless i.zero?
case obj
when Formula
info_formula(obj)
when Cask::Cask
info_cask(obj)
when FormulaOrCaskUnavailableError
# The formula/cask could not be found
ofail obj.message
# No formula with this name, try a missing formula lookup
if (reason = MissingFormula.reason(obj.name, show_info: true))
$stderr.puts reason
end
else
raise
end
end
end
sig { params(version: T.any(T::Boolean, String)).returns(Symbol) }
def json_version(version)
version_hash = {
true => :default,
"v1" => :v1,
"v2" => :v2,
}
raise UsageError, "invalid JSON version: #{version}" unless version_hash.include?(version)
version_hash[version]
end
sig { params(json: T.any(T::Boolean, String), eval_all: T::Boolean).void }
def print_json(json, eval_all)
raise FormulaOrCaskUnspecifiedError if !(eval_all || args.installed?) && args.no_named?
json = case json_version(json)
when :v1, :default
raise UsageError, "Cannot specify `--cask` when using `--json=v1`!" if args.cask?
formulae = if eval_all
Formula.all(eval_all:).sort
elsif args.installed?
Formula.installed.sort
else
args.named.to_formulae
end
if args.variations?
formulae.map(&:to_hash_with_variations)
else
formulae.map(&:to_hash)
end
when :v2
formulae, casks = T.let(
if eval_all
[
Formula.all(eval_all:).sort,
Cask::Cask.all(eval_all:).sort_by(&:full_name),
]
elsif args.installed?
[Formula.installed.sort, Cask::Caskroom.casks.sort_by(&:full_name)]
else
T.cast(args.named.to_formulae_to_casks, [T::Array[Formula], T::Array[Cask::Cask]])
end, [T::Array[Formula], T::Array[Cask::Cask]]
)
if args.variations?
{
"formulae" => formulae.map(&:to_hash_with_variations),
"casks" => casks.map(&:to_hash_with_variations),
}
else
{
"formulae" => formulae.map(&:to_hash),
"casks" => casks.map(&:to_h),
}
end
else
raise
end
puts JSON.pretty_generate(json)
end
sig { params(formula_or_cask: T.any(Formula, Cask::Cask)).returns(String) }
def github_info(formula_or_cask)
path = case formula_or_cask
when Formula
formula = formula_or_cask
tap = formula.tap
return formula.path.to_s if tap.blank? || tap.remote.blank?
formula.path.relative_path_from(tap.path)
when Cask::Cask
cask = formula_or_cask
tap = cask.tap
return cask.sourcefile_path.to_s if tap.blank? || tap.remote.blank?
if cask.sourcefile_path.blank? || cask.sourcefile_path.extname != ".rb"
return "#{tap.default_remote}/blob/HEAD/#{tap.relative_cask_path(cask.token)}"
end
cask.sourcefile_path.relative_path_from(tap.path)
end
github_remote_path(tap.remote, path.to_s)
end
sig { params(formula: Formula).void }
def info_formula(formula)
specs = []
if (stable = formula.stable)
string = "stable #{stable.version}"
string += " (bottled)" if stable.bottled? && formula.pour_bottle?
specs << string
end
specs << "HEAD" if formula.head
attrs = []
attrs << "pinned at #{formula.pinned_version}" if formula.pinned?
attrs << "keg-only" if formula.keg_only?
puts "#{oh1_title(formula.full_name)}: #{specs * ", "}#{" [#{attrs * ", "}]" unless attrs.empty?}"
puts formula.desc if formula.desc
puts Formatter.url(formula.homepage) if formula.homepage
deprecate_disable_info_string = DeprecateDisable.message(formula)
if deprecate_disable_info_string.present?
deprecate_disable_info_string.tap { |info_string| info_string[0] = info_string[0].upcase }
puts deprecate_disable_info_string
end
conflicts = formula.conflicts.map do |conflict|
reason = " (because #{conflict.reason})" if conflict.reason
"#{conflict.name}#{reason}"
end.sort!
unless conflicts.empty?
puts <<~EOS
Conflicts with:
#{conflicts.join("\n ")}
EOS
end
kegs = formula.installed_kegs
heads, versioned = kegs.partition { |keg| keg.version.head? }
kegs = [
*heads.sort_by { |keg| -keg.tab.time.to_i },
*versioned.sort_by(&:scheme_and_version),
]
if kegs.empty?
puts "Not installed"
if (bottle = formula.bottle)
begin
bottle.fetch_tab(quiet: !args.debug?) if args.fetch_manifest?
bottle_size = bottle.bottle_size
installed_size = bottle.installed_size
puts "Bottle Size: #{disk_usage_readable(bottle_size)}" if bottle_size
puts "Installed Size: #{disk_usage_readable(installed_size)}" if installed_size
rescue RuntimeError => e
odebug e
end
end
else
puts "Installed"
kegs.each do |keg|
puts "#{keg} (#{keg.abv})#{" *" if keg.linked?}"
tab = keg.tab.to_s
puts " #{tab}" unless tab.empty?
end
end
puts "From: #{Formatter.url(github_info(formula))}"
puts "License: #{SPDX.license_expression_to_string formula.license}" if formula.license.present?
unless formula.deps.empty?
ohai "Dependencies"
%w[build required recommended optional].map do |type|
deps = formula.deps.send(type).uniq
puts "#{type.capitalize}: #{decorate_dependencies deps}" unless deps.empty?
end
end
unless formula.requirements.to_a.empty?
ohai "Requirements"
%w[build required recommended optional].map do |type|
reqs = formula.requirements.select(&:"#{type}?")
next if reqs.to_a.empty?
puts "#{type.capitalize}: #{decorate_requirements(reqs)}"
end
end
if !formula.options.empty? || formula.head
ohai "Options"
Options.dump_for_formula formula
end
caveats = Caveats.new(formula)
if (caveats_string = caveats.to_s.presence)
ohai "Caveats", caveats_string
end
return unless formula.core_formula?
Utils::Analytics.formula_output(formula, args:)
end
sig { params(dependencies: T::Array[Dependency]).returns(String) }
def decorate_dependencies(dependencies)
deps_status = dependencies.map do |dep|
if dep.satisfied?
pretty_installed(dep_display_s(dep))
else
pretty_uninstalled(dep_display_s(dep))
end
end
deps_status.join(", ")
end
sig { params(requirements: T::Array[Requirement]).returns(String) }
def decorate_requirements(requirements)
req_status = requirements.map do |req|
req_s = req.display_s
req.satisfied? ? pretty_installed(req_s) : pretty_uninstalled(req_s)
end
req_status.join(", ")
end
sig { params(dep: Dependency).returns(String) }
def dep_display_s(dep)
return dep.name if dep.option_tags.empty?
"#{dep.name} #{dep.option_tags.map { |o| "--#{o}" }.join(" ")}"
end
sig { params(cask: Cask::Cask).void }
def info_cask(cask)
require "cask/info"
Cask::Info.info(cask, args:)
end
sig { params(title: String, items: T::Array[NameSize]).void }
def print_sizes_table(title, items)
return if items.blank?
ohai title
total_size = items.sum(&:size)
total_size_str = disk_usage_readable(total_size)
name_width = (items.map { |item| item.name.length } + [5]).max
size_width = (items.map { |item| disk_usage_readable(item.size).length } + [total_size_str.length]).max
items.each do |item|
puts format("%-#{name_width}s %#{size_width}s", item.name,
disk_usage_readable(item.size))
end
puts format("%-#{name_width}s %#{size_width}s", "Total", total_size_str)
end
sig { params(formulae: T::Array[Formula], casks: T::Array[Cask::Cask]).void }
def print_sizes(formulae: [], casks: [])
if formulae.blank? &&
(args.formulae? || (!args.casks? && args.no_named?))
formulae = Formula.installed
end
if casks.blank? &&
(args.casks? || (!args.formulae? && args.no_named?))
casks = Cask::Caskroom.casks
end
unless args.casks?
formula_sizes = formulae.map do |formula|
kegs = formula.installed_kegs
size = kegs.sum(&:disk_usage)
NameSize.new(name: formula.full_name, size:)
end
formula_sizes.sort_by! { |f| -f.size }
print_sizes_table("Formulae sizes:", formula_sizes)
end
return if casks.blank? || args.formulae?
cask_sizes = casks.filter_map do |cask|
installed_version = cask.installed_version
next unless installed_version.present?
versioned_staged_path = cask.caskroom_path.join(installed_version)
next unless versioned_staged_path.exist?
size = versioned_staged_path.children.sum(&:disk_usage)
NameSize.new(name: cask.full_name, size:)
end
cask_sizes.sort_by! { |c| -c.size }
print_sizes_table("Casks sizes:", cask_sizes)
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/cmd/upgrade.rb | Library/Homebrew/cmd/upgrade.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula_installer"
require "install"
require "upgrade"
require "cask/utils"
require "cask/upgrade"
require "cask/macos"
require "api"
require "reinstall"
module Homebrew
module Cmd
class UpgradeCmd < AbstractCommand
cmd_args do
description <<~EOS
Upgrade outdated casks and outdated, unpinned formulae using the same options they were originally
installed with, plus any appended brew formula options. If <cask> or <formula> are specified,
upgrade only the given <cask> or <formula> kegs (unless they are pinned; see `pin`, `unpin`).
Unless `$HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK` is set, `brew upgrade` or `brew reinstall` will be run for
outdated dependents and dependents with broken linkage, respectively.
Unless `$HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for the
upgraded formulae or, every 30 days, for all formulae.
EOS
switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB " \
"or a shell inside the temporary build directory."
switch "--display-times",
description: "Print install times for each package at the end of the run.",
env: :display_install_times
switch "-f", "--force",
description: "Install formulae without checking for previously installed keg-only or " \
"non-migrated versions. When installing casks, overwrite existing files " \
"(binaries and symlinks are excluded, unless originally from the same cask)."
switch "-v", "--verbose",
description: "Print the verification and post-install steps."
switch "-n", "--dry-run",
description: "Show what would be upgraded, but do not actually upgrade anything."
switch "--ask",
description: "Ask for confirmation before downloading and upgrading formulae. " \
"Print download, install and net install sizes of bottles and dependencies.",
env: :ask
[
[:switch, "--formula", "--formulae", {
description: "Treat all named arguments as formulae. If no named arguments " \
"are specified, upgrade only outdated formulae.",
}],
[:switch, "-s", "--build-from-source", {
description: "Compile <formula> from source even if a bottle is available.",
}],
[:switch, "-i", "--interactive", {
description: "Download and patch <formula>, then open a shell. This allows the user to " \
"run `./configure --help` and otherwise determine how to turn the software " \
"package into a Homebrew package.",
}],
[:switch, "--force-bottle", {
description: "Install from a bottle if it exists for the current or newest version of " \
"macOS, even if it would not normally be used for installation.",
}],
[:switch, "--fetch-HEAD", {
description: "Fetch the upstream repository to detect if the HEAD installation of the " \
"formula is outdated. Otherwise, the repository's HEAD will only be checked for " \
"updates when a new stable or development version has been released.",
}],
[:switch, "--keep-tmp", {
description: "Retain the temporary files created during installation.",
}],
[:switch, "--debug-symbols", {
depends_on: "--build-from-source",
description: "Generate debug symbols on build. Source will be retained in a cache directory.",
}],
[:switch, "--overwrite", {
description: "Delete files that already exist in the prefix while linking.",
}],
].each do |args|
options = args.pop
send(*args, **options)
conflicts "--cask", args.last
end
formula_options
[
[:switch, "--cask", "--casks", {
description: "Treat all named arguments as casks. If no named arguments " \
"are specified, upgrade only outdated casks.",
}],
[:switch, "--skip-cask-deps", {
description: "Skip installing cask dependencies.",
}],
[:switch, "-g", "--greedy", {
description: "Also include casks with `auto_updates true` or `version :latest`.",
env: :upgrade_greedy,
}],
[:switch, "--greedy-latest", {
description: "Also include casks with `version :latest`.",
}],
[:switch, "--greedy-auto-updates", {
description: "Also include casks with `auto_updates true`.",
}],
[:switch, "--[no-]binaries", {
description: "Disable/enable linking of helper executables (default: enabled).",
env: :cask_opts_binaries,
}],
[:switch, "--require-sha", {
description: "Require all casks to have a checksum.",
env: :cask_opts_require_sha,
}],
[:switch, "--[no-]quarantine", {
env: :cask_opts_quarantine,
odeprecated: true,
}],
].each do |args|
options = args.pop
send(*args, **options)
conflicts "--formula", args.last
end
cask_options
conflicts "--build-from-source", "--force-bottle"
named_args [:installed_formula, :installed_cask]
end
sig { override.void }
def run
if args.build_from_source? && args.named.empty?
raise ArgumentError, "`--build-from-source` requires at least one formula"
end
formulae, casks = args.named.to_resolved_formulae_to_casks
# If one or more formulae are specified, but no casks were
# specified, we want to make note of that so we don't
# try to upgrade all outdated casks.
only_upgrade_formulae = formulae.present? && casks.blank?
only_upgrade_casks = casks.present? && formulae.blank?
formulae = Homebrew::Attestation.sort_formulae_for_install(formulae) if Homebrew::Attestation.enabled?
upgrade_outdated_formulae!(formulae) unless only_upgrade_casks
upgrade_outdated_casks!(casks) unless only_upgrade_formulae
Cleanup.periodic_clean!(dry_run: args.dry_run?)
Homebrew::Reinstall.reinstall_pkgconf_if_needed!(dry_run: args.dry_run?)
Homebrew.messages.display_messages(display_times: args.display_times?)
end
private
sig { params(formulae: T::Array[Formula]).returns(T::Boolean) }
def upgrade_outdated_formulae!(formulae)
return false if args.cask?
if args.build_from_source?
unless DevelopmentTools.installed?
raise BuildFlagsError.new(["--build-from-source"], bottled: formulae.all?(&:bottled?))
end
unless Homebrew::EnvConfig.developer?
opoo "building from source is not supported!"
puts "You're on your own. Failures are expected so don't create any issues, please!"
end
end
if formulae.blank?
outdated = Formula.installed.select do |f|
f.outdated?(fetch_head: args.fetch_HEAD?)
end
else
outdated, not_outdated = formulae.partition do |f|
f.outdated?(fetch_head: args.fetch_HEAD?)
end
not_outdated.each do |f|
latest_keg = f.installed_kegs.max_by(&:scheme_and_version)
if latest_keg.nil?
ofail "#{f.full_specified_name} not installed"
else
opoo "#{f.full_specified_name} #{latest_keg.version} already installed" unless args.quiet?
end
end
end
return false if outdated.blank?
pinned = outdated.select(&:pinned?)
outdated -= pinned
formulae_to_install = outdated.map do |f|
f_latest = f.latest_formula
if f_latest.latest_version_installed?
f
else
f_latest
end
end
if pinned.any?
message = "Not upgrading #{pinned.count} pinned #{Utils.pluralize("package", pinned.count)}:"
# only fail when pinned formulae are named explicitly
if formulae.any?
ofail message
else
opoo message
end
puts pinned.map { |f| "#{f.full_specified_name} #{f.pkg_version}" } * ", "
end
if formulae_to_install.empty?
oh1 "No packages to upgrade"
else
verb = args.dry_run? ? "Would upgrade" : "Upgrading"
oh1 "#{verb} #{formulae_to_install.count} outdated #{Utils.pluralize("package",
formulae_to_install.count)}:"
formulae_upgrades = formulae_to_install.map do |f|
if f.optlinked?
"#{f.full_specified_name} #{Keg.new(f.opt_prefix).version} -> #{f.pkg_version}"
else
"#{f.full_specified_name} #{f.pkg_version}"
end
end
puts formulae_upgrades.join("\n") unless args.ask?
end
Install.perform_preinstall_checks_once
formulae_installer = Upgrade.formula_installers(
formulae_to_install,
flags: args.flags_only,
dry_run: args.dry_run?,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
overwrite: args.overwrite?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?,
)
return false if formulae_installer.blank?
dependants = Upgrade.dependants(
formulae_to_install,
flags: args.flags_only,
dry_run: args.dry_run?,
ask: args.ask?,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?,
)
# Main block: if asking the user is enabled, show dependency and size information.
Install.ask_formulae(formulae_installer, dependants, args: args) if args.ask?
Upgrade.upgrade_formulae(formulae_installer,
dry_run: args.dry_run?,
verbose: args.verbose?)
Upgrade.upgrade_dependents(
dependants, formulae_to_install,
flags: args.flags_only,
dry_run: args.dry_run?,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?
)
true
end
sig { params(casks: T::Array[Cask::Cask]).returns(T::Boolean) }
def upgrade_outdated_casks!(casks)
return false if args.formula?
Install.ask_casks casks if args.ask?
Cask::Upgrade.upgrade_casks!(
*casks,
force: args.force?,
greedy: args.greedy?,
greedy_latest: args.greedy_latest?,
greedy_auto_updates: args.greedy_auto_updates?,
dry_run: args.dry_run?,
binaries: args.binaries?,
quarantine: args.quarantine?,
require_sha: args.require_sha?,
skip_cask_deps: args.skip_cask_deps?,
verbose: args.verbose?,
quiet: args.quiet?,
args:,
)
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/cmd/--cache.rb | Library/Homebrew/cmd/--cache.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fetch"
require "cask/download"
module Homebrew
module Cmd
class Cache < AbstractCommand
include Fetch
sig { override.returns(String) }
def self.command_name = "--cache"
cmd_args do
description <<~EOS
Display Homebrew's download cache. See also `$HOMEBREW_CACHE`.
If a <formula> or <cask> is provided, display the file or directory used to cache it.
EOS
flag "--os=",
description: "Show cache file for the given operating system. " \
"(Pass `all` to show cache files for all operating systems.)"
flag "--arch=",
description: "Show cache file for the given CPU architecture. " \
"(Pass `all` to show cache files for all architectures.)"
switch "-s", "--build-from-source",
description: "Show the cache file used when building from source."
switch "--force-bottle",
description: "Show the cache file used when pouring a bottle."
flag "--bottle-tag=",
description: "Show the cache file used when pouring a bottle for the given tag."
switch "--HEAD",
description: "Show the cache file used when building from HEAD."
switch "--formula", "--formulae",
description: "Only show cache files for formulae."
switch "--cask", "--casks",
description: "Only show cache files for casks."
conflicts "--build-from-source", "--force-bottle", "--bottle-tag", "--HEAD", "--cask"
conflicts "--formula", "--cask"
conflicts "--os", "--bottle-tag"
conflicts "--arch", "--bottle-tag"
named_args [:formula, :cask]
end
sig { override.void }
def run
if args.no_named?
puts HOMEBREW_CACHE
return
end
formulae_or_casks = args.named.to_formulae_and_casks
os_arch_combinations = args.os_arch_combinations
formulae_or_casks.each do |formula_or_cask|
case formula_or_cask
when Formula
formula = formula_or_cask
ref = formula.loaded_from_api? ? formula.full_name : formula.path
os_arch_combinations.each do |os, arch|
SimulateSystem.with(os:, arch:) do
formula = Formulary.factory(ref)
print_formula_cache(formula, os:, arch:)
end
end
when Cask::Cask
cask = formula_or_cask
ref = cask.loaded_from_api? ? cask.full_name : cask.sourcefile_path
os_arch_combinations.each do |os, arch|
next if os == :linux
SimulateSystem.with(os:, arch:) do
loaded_cask = Cask::CaskLoader.load(ref)
print_cask_cache(loaded_cask)
end
end
else
raise "Invalid type: #{formula_or_cask.class}"
end
end
end
private
sig { params(formula: Formula, os: Symbol, arch: Symbol).void }
def print_formula_cache(formula, os:, arch:)
if fetch_bottle?(
formula,
force_bottle: args.force_bottle?,
bottle_tag: args.bottle_tag&.to_sym,
build_from_source_formulae: args.build_from_source_formulae,
os: args.os&.to_sym,
arch: args.arch&.to_sym,
)
bottle_tag = if (bottle_tag = args.bottle_tag&.to_sym)
Utils::Bottles::Tag.from_symbol(bottle_tag)
else
Utils::Bottles::Tag.new(system: os, arch:)
end
bottle = formula.bottle_for_tag(bottle_tag)
if bottle.nil?
opoo "Bottle for tag #{bottle_tag.to_sym.inspect} is unavailable."
return
end
puts bottle.cached_download
elsif args.HEAD?
if (head = formula.head)
puts head.cached_download
else
opoo "No head is defined for #{formula.full_name}."
end
else
puts formula.cached_download
end
end
sig { params(cask: Cask::Cask).void }
def print_cask_cache(cask)
puts Cask::Download.new(cask).downloader.cached_location
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/tap.rb | Library/Homebrew/cmd/tap.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "tap"
module Homebrew
module Cmd
class TapCmd < AbstractCommand
cmd_args do
usage_banner "`tap` [<options>] [<user>`/`<repo>] [<URL>]"
description <<~EOS
Tap a formula repository.
If no arguments are provided, list all installed taps.
With <URL> unspecified, tap a formula repository from GitHub using HTTPS.
Since so many taps are hosted on GitHub, this command is a shortcut for
`brew tap` <user>`/`<repo> `https://github.com/`<user>`/homebrew-`<repo>.
With <URL> specified, tap a formula repository from anywhere, using
any transport protocol that `git`(1) handles. The one-argument form of `tap`
simplifies but also limits. This two-argument command makes no
assumptions, so taps can be cloned from places other than GitHub and
using protocols other than HTTPS, e.g. SSH, git, HTTP, FTP(S), rsync.
EOS
switch "--custom-remote",
description: "Install or change a tap with a custom remote. Useful for mirrors."
switch "--repair",
description: "Add missing symlinks to tap manpages and shell completions. Correct git remote " \
"refs for any taps where upstream HEAD branch has been renamed."
switch "--eval-all",
description: "Evaluate all formulae, casks and aliases in the new tap to check their validity.",
env: :eval_all
switch "-f", "--force",
description: "Force install core taps even under API mode."
named_args :tap, max: 2
end
sig { override.void }
def run
if args.repair?
Tap.installed.each do |tap|
tap.link_completions_and_manpages
tap.fix_remote_configuration
end
elsif args.no_named?
puts Tap.installed.sort_by(&:name)
else
begin
tap = Tap.fetch(args.named.fetch(0))
tap.install clone_target: args.named.second,
custom_remote: args.custom_remote?,
quiet: args.quiet?,
verify: args.eval_all?,
force: args.force?
rescue Tap::InvalidNameError, TapRemoteMismatchError, TapNoCustomRemoteError => e
odie e
rescue TapAlreadyTappedError
nil
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/cmd/fetch.rb | Library/Homebrew/cmd/fetch.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "fetch"
require "cask/download"
require "download_queue"
module Homebrew
module Cmd
class FetchCmd < AbstractCommand
include Fetch
FETCH_MAX_TRIES = 5
cmd_args do
description <<~EOS
Download a bottle (if available) or source packages for <formula>e
and binaries for <cask>s. For files, also print SHA-256 checksums.
EOS
flag "--os=",
description: "Download for the given operating system. " \
"(Pass `all` to download for all operating systems.)"
flag "--arch=",
description: "Download for the given CPU architecture. " \
"(Pass `all` to download for all architectures.)"
flag "--bottle-tag=",
description: "Download a bottle for given tag."
switch "--HEAD",
description: "Fetch HEAD version instead of stable version."
switch "-f", "--force",
description: "Remove a previously cached version and re-fetch."
switch "-v", "--verbose",
description: "Do a verbose VCS checkout, if the URL represents a VCS. This is useful for " \
"seeing if an existing VCS cache has been updated."
switch "--retry",
description: "Retry if downloading fails or re-download if the checksum of a previously cached " \
"version no longer matches. Tries at most #{FETCH_MAX_TRIES} times with " \
"exponential backoff."
switch "--deps",
description: "Also download dependencies for any listed <formula>."
switch "-s", "--build-from-source",
description: "Download source packages rather than a bottle."
switch "--build-bottle",
description: "Download source packages (for eventual bottling) rather than a bottle."
switch "--force-bottle",
description: "Download a bottle if it exists for the current or newest version of macOS, " \
"even if it would not be used during installation."
switch "--[no-]quarantine",
env: :cask_opts_quarantine,
odeprecated: true
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--build-from-source", "--build-bottle", "--force-bottle", "--bottle-tag"
conflicts "--cask", "--HEAD"
conflicts "--cask", "--deps"
conflicts "--cask", "-s"
conflicts "--cask", "--build-bottle"
conflicts "--cask", "--force-bottle"
conflicts "--cask", "--bottle-tag"
conflicts "--formula", "--cask"
conflicts "--os", "--bottle-tag"
conflicts "--arch", "--bottle-tag"
named_args [:formula, :cask], min: 1
end
sig { override.void }
def run
Formulary.enable_factory_cache!
bucket = if args.deps?
args.named.to_formulae_and_casks.flat_map do |formula_or_cask|
case formula_or_cask
when Formula
formula = formula_or_cask
[formula, *formula.recursive_dependencies.map(&:to_formula)]
else
formula_or_cask
end
end
else
args.named.to_formulae_and_casks
end.uniq
os_arch_combinations = args.os_arch_combinations
puts "Fetching: #{bucket * ", "}" if bucket.size > 1
bucket.each do |formula_or_cask|
case formula_or_cask
when Formula
formula = formula_or_cask
ref = formula.loaded_from_api? ? formula.full_name : formula.path
os_arch_combinations.each do |os, arch|
SimulateSystem.with(os:, arch:) do
formula = Formulary.factory(ref, args.HEAD? ? :head : :stable)
formula.print_tap_action verb: "Fetching"
fetched_bottle = false
if fetch_bottle?(
formula,
force_bottle: args.force_bottle?,
bottle_tag: args.bottle_tag&.to_sym,
build_from_source_formulae: args.build_from_source_formulae,
os: args.os&.to_sym,
arch: args.arch&.to_sym,
)
begin
formula.clear_cache if args.force?
bottle_tag = if (bottle_tag = args.bottle_tag&.to_sym)
Utils::Bottles::Tag.from_symbol(bottle_tag)
else
Utils::Bottles::Tag.new(system: os, arch:)
end
bottle = formula.bottle_for_tag(bottle_tag)
if bottle.nil?
opoo "Bottle for tag #{bottle_tag.to_sym.inspect} is unavailable."
next
end
if (manifest_resource = bottle.github_packages_manifest_resource)
download_queue.enqueue(manifest_resource)
end
download_queue.enqueue(bottle)
rescue Interrupt
raise
rescue => e
raise if Homebrew::EnvConfig.developer?
fetched_bottle = false
onoe e.message
opoo "Bottle fetch failed, fetching the source instead."
else
fetched_bottle = true
end
end
next if fetched_bottle
if (resource = formula.resource)
download_queue.enqueue(resource)
end
formula.enqueue_resources_and_patches(download_queue:)
end
end
else
cask = formula_or_cask
ref = cask.loaded_from_api? ? cask.full_name : cask.sourcefile_path
os_arch_combinations.each do |os, arch|
SimulateSystem.with(os:, arch:) do
cask = Cask::CaskLoader.load(ref)
if cask.url.nil? || cask.sha256.nil?
opoo "Cask #{cask} is not supported on os #{os} and arch #{arch}"
next
end
quarantine = args.quarantine?
quarantine = true if quarantine.nil?
download = Cask::Download.new(cask, quarantine:)
download_queue.enqueue(download)
end
end
end
end
download_queue.fetch
ensure
download_queue.shutdown
end
private
sig { returns(Integer) }
def retries
@retries ||= T.let(args.retry? ? FETCH_MAX_TRIES : 1, T.nilable(Integer))
end
sig { returns(DownloadQueue) }
def download_queue
@download_queue ||= T.let(begin
DownloadQueue.new(retries:, force: args.force?)
end, T.nilable(DownloadQueue))
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/cmd/unpin.rb | Library/Homebrew/cmd/unpin.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module Cmd
class Unpin < AbstractCommand
cmd_args do
description <<~EOS
Unpin <formula>, allowing them to be upgraded by `brew upgrade` <formula>.
See also `pin`.
EOS
named_args :installed_formula, min: 1
end
sig { override.void }
def run
args.named.to_resolved_formulae.each do |f|
if f.pinned?
f.unpin
elsif !f.pinnable?
onoe "#{f.name} not installed"
else
opoo "#{f.name} not pinned"
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/cmd/unlink.rb | Library/Homebrew/cmd/unlink.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "unlink"
module Homebrew
module Cmd
class UnlinkCmd < AbstractCommand
cmd_args do
description <<~EOS
Remove symlinks for <formula> from Homebrew's prefix. This can be useful
for temporarily disabling a formula:
`brew unlink` <formula> `&&` <commands> `&& brew link` <formula>
EOS
switch "-n", "--dry-run",
description: "List files which would be unlinked without actually unlinking or " \
"deleting any files."
named_args :installed_formula, min: 1
end
sig { override.void }
def run
options = { dry_run: args.dry_run?, verbose: args.verbose? }
args.named.to_default_kegs.each do |keg|
if args.dry_run?
puts "Would remove:"
keg.unlink(**options)
next
end
Unlink.unlink(keg, dry_run: args.dry_run?, verbose: args.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/cmd/commands.rb | Library/Homebrew/cmd/commands.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class CommandsCmd < AbstractCommand
cmd_args do
description <<~EOS
Show lists of built-in and external commands.
EOS
switch "-q", "--quiet",
description: "List only the names of commands without category headers."
switch "--include-aliases",
depends_on: "--quiet",
description: "Include aliases of internal commands."
named_args :none
end
sig { override.void }
def run
if args.quiet?
puts Formatter.columns(Commands.commands(aliases: args.include_aliases?))
return
end
prepend_separator = T.let(false, T::Boolean)
{
"Built-in commands" => Commands.internal_commands,
"Built-in developer commands" => Commands.internal_developer_commands,
"External commands" => Commands.external_commands,
}.each do |title, commands|
next if commands.blank?
puts if prepend_separator
ohai title, Formatter.columns(commands)
prepend_separator ||= true
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/cmd/deps.rb | Library/Homebrew/cmd/deps.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "cask/caskroom"
require "dependencies_helpers"
module Homebrew
module Cmd
class Deps < AbstractCommand
include DependenciesHelpers
cmd_args do
description <<~EOS
Show dependencies for <formula>. When given multiple formula arguments,
show the intersection of dependencies for each formula. By default, `deps`
shows all required and recommended dependencies.
If any version of each formula argument is installed and no other options
are passed, this command displays their actual runtime dependencies (similar
to `brew linkage`), which may differ from a formula's declared dependencies.
*Note:* `--missing` and `--skip-recommended` have precedence over `--include-*`.
EOS
switch "-n", "--topological",
description: "Sort dependencies in topological order."
switch "-1", "--direct", "--declared", "--1",
description: "Show only the direct dependencies declared in the formula."
switch "--union",
description: "Show the union of dependencies for multiple <formula>, instead of the intersection."
switch "--full-name",
description: "List dependencies by their full name."
switch "--include-implicit",
description: "Include implicit dependencies used to download and unpack source files."
switch "--include-build",
description: "Include `:build` dependencies for <formula>."
switch "--include-optional",
description: "Include `:optional` dependencies for <formula>."
switch "--include-test",
description: "Include `:test` dependencies for <formula> (non-recursive unless `--graph` or `--tree`)."
switch "--skip-recommended",
description: "Skip `:recommended` dependencies for <formula>."
switch "--include-requirements",
description: "Include requirements in addition to dependencies for <formula>."
switch "--tree",
description: "Show dependencies as a tree. When given multiple formula arguments, " \
"show individual trees for each formula."
switch "--prune",
depends_on: "--tree",
description: "Prune parts of tree already seen."
switch "--graph",
description: "Show dependencies as a directed graph."
switch "--dot",
depends_on: "--graph",
description: "Show text-based graph description in DOT format."
switch "--annotate",
description: "Mark any build, test, implicit, optional, or recommended dependencies as " \
"such in the output."
switch "--installed",
description: "List dependencies for formulae that are currently installed. If <formula> is " \
"specified, list only its dependencies that are currently installed."
switch "--missing",
description: "Show only missing dependencies."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to list " \
"their dependencies."
switch "--for-each",
description: "Switch into the mode used by the `--eval-all` option, but only list dependencies " \
"for each provided <formula>, one formula per line. This is used for " \
"debugging the `--installed`/`--eval-all` display mode."
switch "--HEAD",
description: "Show dependencies for HEAD version instead of stable version."
flag "--os=",
description: "Show dependencies for the given operating system."
flag "--arch=",
description: "Show dependencies for the given CPU architecture."
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--tree", "--graph"
conflicts "--installed", "--missing"
conflicts "--installed", "--eval-all"
conflicts "--formula", "--cask"
formula_options
named_args [:formula, :cask]
end
sig { override.void }
def run
raise UsageError, "`brew deps --os=all` is not supported." if args.os == "all"
raise UsageError, "`brew deps --arch=all` is not supported." if args.arch == "all"
os, arch = args.os_arch_combinations.fetch(0)
eval_all = args.eval_all?
Formulary.enable_factory_cache!
SimulateSystem.with(os:, arch:) do
@use_runtime_dependencies = true
installed = args.installed? || dependents(args.named.to_formulae_and_casks).all?(&:any_version_installed?)
unless installed
not_using_runtime_dependencies_reason = if args.installed?
"not all the named formulae were installed"
else
"`--installed` was not passed"
end
@use_runtime_dependencies = false
end
%w[direct tree graph HEAD skip_recommended missing
include_implicit include_build include_test include_optional].each do |arg|
next unless args.public_send("#{arg}?")
not_using_runtime_dependencies_reason = "--#{arg.tr("_", "-")} was passed"
@use_runtime_dependencies = false
end
%w[os arch].each do |arg|
next if args.public_send(arg).nil?
not_using_runtime_dependencies_reason = "--#{arg.tr("_", "-")} was passed"
@use_runtime_dependencies = false
end
if !@use_runtime_dependencies && !Homebrew::EnvConfig.no_env_hints?
opoo <<~EOS
`brew deps` is not the actual runtime dependencies because #{not_using_runtime_dependencies_reason}!
This means dependencies may differ from a formula's declared dependencies.
Hide these hints with `HOMEBREW_NO_ENV_HINTS=1` (see `man brew`).
EOS
end
recursive = !args.direct?
if args.tree? || args.graph?
dependents = if args.named.present?
sorted_dependents(args.named.to_formulae_and_casks)
elsif args.installed?
case args.only_formula_or_cask
when :formula
sorted_dependents(Formula.installed)
when :cask
sorted_dependents(Cask::Caskroom.casks)
else
sorted_dependents(Formula.installed + Cask::Caskroom.casks)
end
else
raise FormulaUnspecifiedError
end
if args.graph?
dot_code = dot_code(dependents, recursive:)
if args.dot?
puts dot_code
else
exec_browser "https://dreampuf.github.io/GraphvizOnline/##{ERB::Util.url_encode(dot_code)}"
end
return
end
puts_deps_tree(dependents, recursive:)
return
elsif eval_all
puts_deps(sorted_dependents(
Formula.all(eval_all:) + Cask::Cask.all(eval_all:),
), recursive:)
return
elsif !args.no_named? && args.for_each?
puts_deps(sorted_dependents(args.named.to_formulae_and_casks), recursive:)
return
end
if args.no_named?
raise FormulaUnspecifiedError unless args.installed?
sorted_dependents_formulae_and_casks = case args.only_formula_or_cask
when :formula
sorted_dependents(Formula.installed)
when :cask
sorted_dependents(Cask::Caskroom.casks)
else
sorted_dependents(Formula.installed + Cask::Caskroom.casks)
end
puts_deps(sorted_dependents_formulae_and_casks, recursive:)
return
end
dependents = dependents(args.named.to_formulae_and_casks)
check_head_spec(dependents) if args.HEAD?
all_deps = deps_for_dependents(dependents, recursive:, &(args.union? ? :| : :&))
condense_requirements(all_deps)
all_deps.map! { |d| dep_display_name(d) }
all_deps.uniq!
all_deps.sort! unless args.topological?
puts all_deps
end
end
private
def sorted_dependents(formulae_or_casks)
dependents(formulae_or_casks).sort_by(&:name)
end
def condense_requirements(deps)
deps.select! { |dep| dep.is_a?(Dependency) } unless args.include_requirements?
deps.select! { |dep| dep.is_a?(Requirement) || dep.installed? } if args.installed?
end
def dep_display_name(dep)
str = if dep.is_a? Requirement
if args.include_requirements?
":#{dep.display_s}"
else
# This shouldn't happen, but we'll put something here to help debugging
"::#{dep.name}"
end
elsif args.full_name?
dep.to_formula.full_name
else
dep.name
end
if args.annotate?
str = "#{str} " if args.tree?
str = "#{str} [build]" if dep.build?
str = "#{str} [test]" if dep.test?
str = "#{str} [optional]" if dep.optional?
str = "#{str} [recommended]" if dep.recommended?
str = "#{str} [implicit]" if dep.implicit?
end
str
end
def deps_for_dependent(dependency, recursive: false)
includes, ignores = args_includes_ignores(args)
deps = dependency.runtime_dependencies if @use_runtime_dependencies
if recursive
deps ||= recursive_dep_includes(dependency, includes, ignores)
reqs = recursive_req_includes(dependency, includes, ignores)
else
deps ||= select_includes(dependency.deps, ignores, includes)
reqs = select_includes(dependency.requirements, ignores, includes)
end
deps + reqs.to_a
end
def deps_for_dependents(dependents, recursive: false, &block)
dependents.map { |d| deps_for_dependent(d, recursive:) }.reduce(&block)
end
def check_head_spec(dependents)
headless = dependents.select { |d| d.is_a?(Formula) && d.active_spec_sym != :head }
.to_sentence two_words_connector: " or ", last_word_connector: " or "
opoo "No head spec for #{headless}, using stable spec instead" unless headless.empty?
end
def puts_deps(dependents, recursive: false)
check_head_spec(dependents) if args.HEAD?
dependents.each do |dependent|
deps = deps_for_dependent(dependent, recursive:)
condense_requirements(deps)
deps.sort_by!(&:name)
deps.map! { |d| dep_display_name(d) }
puts "#{dependent.full_name}: #{deps.join(" ")}"
end
end
def dot_code(dependents, recursive:)
dep_graph = {}
dependents.each do |d|
graph_deps(d, dep_graph:, recursive:)
end
dot_code = dep_graph.map do |d, deps|
deps.map do |dep|
attributes = []
attributes << "style = dotted" if dep.build?
attributes << "arrowhead = empty" if dep.test?
if dep.optional?
attributes << "color = red"
elsif dep.recommended?
attributes << "color = green"
end
comment = " # #{dep.tags.map(&:inspect).join(", ")}" if dep.tags.any?
" \"#{d.name}\" -> \"#{dep}\"#{" [#{attributes.join(", ")}]" if attributes.any?}#{comment}"
end
end.flatten.join("\n")
"digraph {\n#{dot_code}\n}"
end
def graph_deps(formula, dep_graph:, recursive:)
return if dep_graph.key?(formula)
dependables = dependables(formula)
dep_graph[formula] = dependables
return unless recursive
dependables.each do |dep|
next unless dep.is_a? Dependency
graph_deps(Formulary.factory(dep.name),
dep_graph:,
recursive: true)
end
end
def puts_deps_tree(dependents, recursive: false)
check_head_spec(dependents) if args.HEAD?
dependents.each do |d|
puts d.full_name
recursive_deps_tree(d, deps_seen: {}, prefix: "", recursive:)
puts
end
end
def dependables(formula)
includes, ignores = args_includes_ignores(args)
deps = @use_runtime_dependencies ? formula.runtime_dependencies : formula.deps
deps = select_includes(deps, ignores, includes)
reqs = select_includes(formula.requirements, ignores, includes) if args.include_requirements?
reqs ||= []
reqs + deps
end
def recursive_deps_tree(formula, deps_seen:, prefix:, recursive:)
dependables = dependables(formula)
max = dependables.length - 1
deps_seen[formula.name] = true
dependables.each_with_index do |dep, i|
tree_lines = if i == max
"└──"
else
"├──"
end
display_s = "#{tree_lines} #{dep_display_name(dep)}"
# Detect circular dependencies and consider them a failure if present.
is_circular = deps_seen.fetch(dep.name, false)
pruned = args.prune? && deps_seen.include?(dep.name)
if is_circular
display_s = "#{display_s} (CIRCULAR DEPENDENCY)"
Homebrew.failed = true
elsif pruned
display_s = "#{display_s} (PRUNED)"
end
puts "#{prefix}#{display_s}"
next if !recursive || is_circular || pruned
prefix_addition = if i == max
" "
else
"│ "
end
next unless dep.is_a? Dependency
recursive_deps_tree(Formulary.factory(dep.name),
deps_seen:,
prefix: prefix + prefix_addition,
recursive: true)
end
deps_seen[formula.name] = 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/cmd/--version.rb | Library/Homebrew/cmd/--version.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class Version < AbstractCommand
include ShellCommand
sig { override.returns(String) }
def self.command_name = "--version"
cmd_args do
description <<~EOS
Print the version numbers of Homebrew, Homebrew/homebrew-core and
Homebrew/homebrew-cask (if tapped) to standard output.
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/list.rb | Library/Homebrew/cmd/list.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "metafiles"
require "formula"
require "cli/parser"
require "cask/list"
require "system_command"
require "tab"
module Homebrew
module Cmd
class List < AbstractCommand
include SystemCommand::Mixin
cmd_args do
description <<~EOS
List all installed formulae and casks.
If <formula> is provided, summarise the paths within its current keg.
If <cask> is provided, list its artifacts.
EOS
switch "--formula", "--formulae",
description: "List only formulae, or treat all named arguments as formulae."
switch "--cask", "--casks",
description: "List only casks, or treat all named arguments as casks."
switch "--full-name",
description: "Print formulae with fully-qualified names. Unless `--full-name`, `--versions` " \
"or `--pinned` are passed, other options (i.e. `-1`, `-l`, `-r` and `-t`) are " \
"passed to `ls`(1) which produces the actual output."
switch "--versions",
description: "Show the version number for installed formulae, or only the specified " \
"formulae if <formula> are provided."
switch "--multiple",
depends_on: "--versions",
description: "Only show formulae with multiple versions installed."
switch "--pinned",
description: "List only pinned formulae, or only the specified (pinned) " \
"formulae if <formula> are provided. See also `pin`, `unpin`."
switch "--installed-on-request",
description: "List the formulae installed on request."
switch "--installed-as-dependency",
description: "List the formulae installed as dependencies."
switch "--poured-from-bottle",
description: "List the formulae installed from a bottle."
switch "--built-from-source",
description: "List the formulae compiled from source."
# passed through to ls
switch "-1",
description: "Force output to be one entry per line. " \
"This is the default when output is not to a terminal."
switch "-l",
description: "List formulae and/or casks in long format. " \
"Has no effect when a formula or cask name is passed as an argument."
switch "-r",
description: "Reverse the order of formula and/or cask sorting to list the oldest entries first. " \
"Has no effect when a formula or cask name is passed as an argument."
switch "-t",
description: "Sort formulae and/or casks by time modified, listing most recently modified first. " \
"Has no effect when a formula or cask name is passed as an argument."
conflicts "--formula", "--cask"
conflicts "--pinned", "--cask"
conflicts "--multiple", "--cask"
conflicts "--pinned", "--multiple"
["--installed-on-request", "--installed-as-dependency",
"--poured-from-bottle", "--built-from-source"].each do |flag|
conflicts "--cask", flag
conflicts "--versions", flag
conflicts "--pinned", flag
conflicts "-l", flag
end
["-1", "-l", "-r", "-t"].each do |flag|
conflicts "--versions", flag
conflicts "--pinned", flag
end
["--versions", "--pinned", "-l", "-r", "-t"].each do |flag|
conflicts "--full-name", flag
end
named_args [:installed_formula, :installed_cask]
end
sig { override.void }
def run
if args.full_name? &&
!(args.installed_on_request? || args.installed_as_dependency? ||
args.poured_from_bottle? || args.built_from_source?)
unless args.cask?
formula_names = args.no_named? ? Formula.installed : args.named.to_resolved_formulae
full_formula_names = formula_names.map(&:full_name).sort(&tap_and_name_comparison)
full_formula_names = Formatter.columns(full_formula_names) unless args.public_send(:"1?")
puts full_formula_names if full_formula_names.present?
end
if args.cask? || (!args.formula? && args.no_named?)
cask_names = if args.no_named?
Cask::Caskroom.casks
else
args.named.to_formulae_and_casks(only: :cask, method: :resolve)
end
# The cast is because `Keg`` does not define `full_name`
full_cask_names = T.cast(cask_names, T::Array[T.any(Formula, Cask::Cask)])
.map(&:full_name).sort(&tap_and_name_comparison)
full_cask_names = Formatter.columns(full_cask_names) unless args.public_send(:"1?")
puts full_cask_names if full_cask_names.present?
end
elsif args.pinned?
filtered_list
elsif args.versions?
filtered_list unless args.cask?
list_casks if args.cask? || (!args.formula? && !args.multiple? && args.no_named?)
elsif args.installed_on_request? ||
args.installed_as_dependency? ||
args.poured_from_bottle? ||
args.built_from_source?
flags = []
flags << "`--installed-on-request`" if args.installed_on_request?
flags << "`--installed-as-dependency`" if args.installed_as_dependency?
flags << "`--poured-from-bottle`" if args.poured_from_bottle?
flags << "`--built-from-source`" if args.built_from_source?
raise UsageError, "Cannot use #{flags.join(", ")} with formula arguments." unless args.no_named?
formulae = if args.t?
# See https://ruby-doc.org/3.2/Kernel.html#method-i-test
Formula.installed.sort_by { |formula| T.cast(test("M", formula.rack.to_s), Time) }.reverse!
elsif args.full_name?
Formula.installed.sort { |a, b| tap_and_name_comparison.call(a.full_name, b.full_name) }
else
Formula.installed.sort
end
formulae.reverse! if args.r?
formulae.each do |formula|
tab = Tab.for_formula(formula)
statuses = []
statuses << "installed on request" if args.installed_on_request? && tab.installed_on_request
statuses << "installed as dependency" if args.installed_as_dependency? && tab.installed_as_dependency
statuses << "poured from bottle" if args.poured_from_bottle? && tab.poured_from_bottle
statuses << "built from source" if args.built_from_source? && !tab.poured_from_bottle
next if statuses.empty?
name = args.full_name? ? formula.full_name : formula.name
if flags.count > 1
puts "#{name}: #{statuses.join(", ")}"
else
puts name
end
end
elsif args.no_named?
ENV["CLICOLOR"] = nil
ls_args = []
ls_args << "-1" if args.public_send(:"1?")
ls_args << "-l" if args.l?
ls_args << "-r" if args.r?
ls_args << "-t" if args.t?
if !args.cask? && HOMEBREW_CELLAR.exist? && HOMEBREW_CELLAR.children.any?
ohai "Formulae" if $stdout.tty? && !args.formula?
safe_system "ls", *ls_args, HOMEBREW_CELLAR
puts if $stdout.tty? && !args.formula?
end
if !args.formula? && Cask::Caskroom.any_casks_installed?
ohai "Casks" if $stdout.tty? && !args.cask?
safe_system "ls", *ls_args, Cask::Caskroom.path
end
else
kegs, casks = args.named.to_kegs_to_casks
if args.verbose? || !$stdout.tty?
find_args = %w[-not -type d -not -name .DS_Store -print]
system_command! "find", args: kegs.map(&:to_s) + find_args, print_stdout: true if kegs.present?
system_command! "find", args: casks.map(&:caskroom_path) + find_args, print_stdout: true if casks.present?
else
kegs.each { |keg| PrettyListing.new keg } if kegs.present?
Cask::List.list_casks(*casks, one: args.public_send(:"1?")) if casks.present?
end
end
end
private
sig { void }
def filtered_list
names = if args.no_named?
Formula.racks
else
racks = args.named.map { |n| Formulary.to_rack(n) }
racks.select do |rack|
Homebrew.failed = true unless rack.exist?
rack.exist?
end
end
if args.pinned?
pinned_versions = {}
names.sort.each do |d|
keg_pin = (HOMEBREW_PINNED_KEGS/d.basename.to_s)
pinned_versions[d] = keg_pin.readlink.basename.to_s if keg_pin.exist? || keg_pin.symlink?
end
pinned_versions.each do |d, version|
puts d.basename.to_s.concat(args.versions? ? " #{version}" : "")
end
else # --versions without --pinned
names.sort.each do |d|
versions = d.subdirs.map { |pn| pn.basename.to_s }
next if args.multiple? && versions.length < 2
puts "#{d.basename} #{versions * " "}"
end
end
end
sig { void }
def list_casks
casks = if args.no_named?
cask_paths = Cask::Caskroom.path.children.reject(&:file?).map do |path|
if path.symlink?
real_path = path.realpath
real_path.basename.to_s
else
path.basename.to_s
end
end.uniq.sort
cask_paths.map { |name| Cask::CaskLoader.load(name) }
else
filtered_args = args.named.dup.delete_if do |n|
Homebrew.failed = true unless Cask::Caskroom.path.join(n).exist?
!Cask::Caskroom.path.join(n).exist?
end
# NamedAargs subclasses array
T.cast(filtered_args, Homebrew::CLI::NamedArgs).to_formulae_and_casks(only: :cask)
end
return if casks.blank?
Cask::List.list_casks(
*casks,
one: args.public_send(:"1?"),
full_name: args.full_name?,
versions: args.versions?,
)
end
end
class PrettyListing
sig { params(path: T.any(String, Pathname, Keg)).void }
def initialize(path)
valid_lib_extensions = [".dylib", ".pc"]
Pathname.new(path).children.sort_by { |p| p.to_s.downcase }.each do |pn|
case pn.basename.to_s
when "bin", "sbin"
pn.find { |pnn| puts pnn unless pnn.directory? }
when "lib"
print_dir pn do |pnn|
# dylibs have multiple symlinks and we don't care about them
valid_lib_extensions.include?(pnn.extname) && !pnn.symlink?
end
when ".brew"
next # Ignore .brew
else
if pn.directory?
if pn.symlink?
puts "#{pn} -> #{pn.readlink}"
else
print_dir pn
end
elsif Metafiles.list?(pn.basename.to_s)
puts pn
end
end
end
end
private
sig { params(root: Pathname, block: T.nilable(T.proc.params(arg0: Pathname).returns(T::Boolean))).void }
def print_dir(root, &block)
dirs = []
remaining_root_files = []
other = ""
root.children.sort.each do |pn|
if pn.directory?
dirs << pn
elsif block && yield(pn)
puts pn
other = "other "
elsif pn.basename.to_s != ".DS_Store"
remaining_root_files << pn
end
end
dirs.each do |d|
files = []
d.find { |pn| files << pn unless pn.directory? }
print_remaining_files files, d
end
print_remaining_files remaining_root_files, root, other
end
sig { params(files: T::Array[Pathname], root: Pathname, other: String).void }
def print_remaining_files(files, root, other = "")
if files.length == 1
puts files
elsif files.length > 1
puts "#{root}/ (#{files.length} #{other}files)"
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/cmd/unalias.rb | Library/Homebrew/cmd/unalias.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "aliases/aliases"
module Homebrew
module Cmd
class Unalias < AbstractCommand
cmd_args do
description <<~EOS
Remove aliases.
EOS
named_args :alias, min: 1
end
sig { override.void }
def run
Aliases.init
args.named.each { |a| Aliases.remove a }
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/cmd/pyenv-sync.rb | Library/Homebrew/cmd/pyenv-sync.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module Cmd
class PyenvSync < AbstractCommand
cmd_args do
description <<~EOS
Create symlinks for Homebrew's installed Python versions in `~/.pyenv/versions`.
Note that older patch version symlinks will be created and linked to the minor
version so e.g. Python 3.11.0 will also be symlinked to 3.11.3.
EOS
named_args :none
end
sig { override.void }
def run
pyenv_root = Pathname(ENV.fetch("HOMEBREW_PYENV_ROOT", Pathname(Dir.home)/".pyenv"))
# Don't run multiple times at once.
pyenv_sync_running = pyenv_root/".pyenv_sync_running"
return if pyenv_sync_running.exist?
begin
pyenv_versions = pyenv_root/"versions"
pyenv_versions.mkpath
FileUtils.touch pyenv_sync_running
HOMEBREW_CELLAR.glob("python{,@*}")
.flat_map(&:children)
.each { |path| link_pyenv_versions(path, pyenv_versions) }
pyenv_versions.children
.select(&:symlink?)
.reject(&:exist?)
.each { |path| FileUtils.rm_f path }
ensure
pyenv_sync_running.unlink if pyenv_sync_running.exist?
end
end
private
sig { params(path: Pathname, pyenv_versions: Pathname).void }
def link_pyenv_versions(path, pyenv_versions)
pyenv_versions.mkpath
version = Keg.new(path).version
major_version = version.major.to_i
minor_version = version.minor.to_i
patch_version = version.patch.to_i
patch_version_range = if Homebrew::EnvConfig.env_sync_strict?
# Only create symlinks for the exact installed patch version.
# e.g. 3.11.0 => 3.11.0
[patch_version]
else
# Create folder symlinks for all patch versions to the latest patch version
# e.g. 3.11.0 => 3.11.3
0..patch_version
end
patch_version_range.each do |patch|
link_path = pyenv_versions/"#{major_version}.#{minor_version}.#{patch}"
# Don't clobber existing user installations.
next if link_path.exist? && !link_path.symlink?
FileUtils.rm_f link_path
FileUtils.ln_s path, link_path
# Create an unversioned symlinks
# This is what pyenv expects to find in ~/.pyenv/versions/___/bin'.
# Without this, `python3`, `pip3` do not exist and pyenv falls back to system Python.
# (eg. python3 -> python3.11, pip3 -> pip3.11)
executables = %w[python3 pip3 wheel3 idle3 pydoc3]
executables.each do |executable|
major_link_path = link_path/"bin/#{executable}"
# Don't clobber existing user installations.
next if major_link_path.exist? && !major_link_path.symlink?
executable_link_path = link_path/"bin/#{executable}.#{minor_version}"
FileUtils.rm_f major_link_path
begin
FileUtils.ln_s executable_link_path, major_link_path
rescue => e
opoo "Failed to link #{executable_link_path} to #{major_link_path}: #{e}"
end
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/cmd/config.rb | Library/Homebrew/cmd/config.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "system_config"
module Homebrew
module Cmd
class Config < AbstractCommand
cmd_args do
description <<~EOS
Show Homebrew and system configuration info useful for debugging. If you file
a bug report, you will be required to provide this information.
EOS
named_args :none
end
sig { override.void }
def run
SystemConfig.dump_verbose_config
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/cmd/alias.rb | Library/Homebrew/cmd/alias.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "aliases/aliases"
module Homebrew
module Cmd
class Alias < AbstractCommand
cmd_args do
usage_banner "`alias` [`--edit`] [<alias>|<alias>=<command>]"
description <<~EOS
Show an alias's command. If no alias is given, print the whole list.
EOS
switch "--edit",
description: "Edit aliases in a text editor. Either one or all aliases may be opened at once. " \
"If the given alias doesn't exist it'll be pre-populated with a template."
named_args max: 1
end
sig { override.void }
def run
name = args.named.first
name, command = name.split("=", 2) if name.present?
Aliases.init
if name.nil?
if args.edit?
Aliases.edit_all
else
Aliases.show
end
elsif command.nil?
if args.edit?
Aliases.edit name
else
Aliases.show name
end
else
Aliases.add name, command
Aliases.edit name if args.edit?
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/cmd/casks.rb | Library/Homebrew/cmd/casks.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
# This Ruby command exists to allow generation of completions for the Bash
# version. It is not meant to be run.
module Homebrew
module Cmd
class Casks < AbstractCommand
include ShellCommand
cmd_args do
description "List all locally installable casks including short names."
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/analytics.rb | Library/Homebrew/cmd/analytics.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class Analytics < AbstractCommand
cmd_args do
description <<~EOS
Control Homebrew's anonymous aggregate user behaviour analytics.
Read more at <https://docs.brew.sh/Analytics>.
`brew analytics` [`state`]:
Display the current state of Homebrew's analytics.
`brew analytics` (`on`|`off`):
Turn Homebrew's analytics on or off respectively.
EOS
named_args %w[state on off regenerate-uuid], max: 1
end
sig { override.void }
def run
case args.named.first
when nil, "state"
if Utils::Analytics.disabled?
puts "InfluxDB analytics are disabled."
else
puts "InfluxDB analytics are enabled."
end
puts "Google Analytics were destroyed."
when "on"
Utils::Analytics.enable!
when "off"
Utils::Analytics.disable!
when "regenerate-uuid"
Utils::Analytics.delete_uuid!
opoo "Homebrew no longer uses an analytics UUID so this has been deleted!"
puts "brew analytics regenerate-uuid is no longer necessary."
else
raise UsageError, "unknown subcommand: #{args.named.first}"
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/cmd/install.rb | Library/Homebrew/cmd/install.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "cask/config"
require "cask/installer"
require "cask/upgrade"
require "cask_dependent"
require "missing_formula"
require "formula_installer"
require "development_tools"
require "install"
require "cleanup"
require "upgrade"
module Homebrew
module Cmd
class InstallCmd < AbstractCommand
cmd_args do
description <<~EOS
Install a <formula> or <cask>. Additional options specific to a <formula> may be
appended to the command.
Unless `$HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK` is set, `brew upgrade` or `brew reinstall` will be run for
outdated dependents and dependents with broken linkage, respectively.
Unless `$HOMEBREW_NO_INSTALL_CLEANUP` is set, `brew cleanup` will then be run for
the installed formulae or, every 30 days, for all formulae.
Unless `$HOMEBREW_NO_INSTALL_UPGRADE` is set, `brew install` <formula> will upgrade <formula> if it
is already installed but outdated.
EOS
switch "-d", "--debug",
description: "If brewing fails, open an interactive debugging session with access to IRB " \
"or a shell inside the temporary build directory."
switch "--display-times",
description: "Print install times for each package at the end of the run.",
env: :display_install_times
switch "-f", "--force",
description: "Install formulae without checking for previously installed keg-only or " \
"non-migrated versions. When installing casks, overwrite existing files " \
"(binaries and symlinks are excluded, unless originally from the same cask)."
switch "-v", "--verbose",
description: "Print the verification and post-install steps."
switch "-n", "--dry-run",
description: "Show what would be installed, but do not actually install anything."
switch "--ask",
description: "Ask for confirmation before downloading and installing formulae. " \
"Print download and install sizes of bottles and dependencies.",
env: :ask
[
[:switch, "--formula", "--formulae", {
description: "Treat all named arguments as formulae.",
}],
[:flag, "--env=", {
description: "Disabled other than for internal Homebrew use.",
hidden: true,
}],
[:switch, "--ignore-dependencies", {
description: "An unsupported Homebrew development option to skip installing any dependencies of any " \
"kind. If the dependencies are not already present, the formula will have issues. If " \
"you're not developing Homebrew, consider adjusting your PATH rather than using this " \
"option.",
}],
[:switch, "--only-dependencies", {
description: "Install the dependencies with specified options but do not install the " \
"formula itself.",
}],
[:flag, "--cc=", {
description: "Attempt to compile using the specified <compiler>, which should be the name of the " \
"compiler's executable, e.g. `gcc-9` for GCC 9. In order to use LLVM's clang, specify " \
"`llvm_clang`. To use the Apple-provided clang, specify `clang`. This option will only " \
"accept compilers that are provided by Homebrew or bundled with macOS. Please do not " \
"file issues if you encounter errors while using this option.",
}],
[:switch, "-s", "--build-from-source", {
description: "Compile <formula> from source even if a bottle is provided. " \
"Dependencies will still be installed from bottles if they are available.",
}],
[:switch, "--force-bottle", {
description: "Install from a bottle if it exists for the current or newest version of " \
"macOS, even if it would not normally be used for installation.",
}],
[:switch, "--include-test", {
description: "Install testing dependencies required to run `brew test` <formula>.",
}],
[:switch, "--HEAD", {
description: "If <formula> defines it, install the HEAD version, aka. main, trunk, unstable, master.",
}],
[:switch, "--fetch-HEAD", {
description: "Fetch the upstream repository to detect if the HEAD installation of the " \
"formula is outdated. Otherwise, the repository's HEAD will only be checked for " \
"updates when a new stable or development version has been released.",
}],
[:switch, "--keep-tmp", {
description: "Retain the temporary files created during installation.",
}],
[:switch, "--debug-symbols", {
depends_on: "--build-from-source",
description: "Generate debug symbols on build. Source will be retained in a cache directory.",
}],
[:switch, "--build-bottle", {
description: "Prepare the formula for eventual bottling during installation, skipping any " \
"post-install steps.",
}],
[:switch, "--skip-post-install", {
description: "Install but skip any post-install steps.",
}],
[:switch, "--skip-link", {
description: "Install but skip linking the keg into the prefix.",
}],
[:switch, "--as-dependency", {
description: "Install but mark as installed as a dependency and not installed on request.",
}],
[:flag, "--bottle-arch=", {
depends_on: "--build-bottle",
description: "Optimise bottles for the specified architecture rather than the oldest " \
"architecture supported by the version of macOS the bottles are built on.",
}],
[:switch, "-i", "--interactive", {
description: "Download and patch <formula>, then open a shell. This allows the user to " \
"run `./configure --help` and otherwise determine how to turn the software " \
"package into a Homebrew package.",
}],
[:switch, "-g", "--git", {
description: "Create a Git repository, useful for creating patches to the software.",
}],
[:switch, "--overwrite", {
description: "Delete files that already exist in the prefix while linking.",
}],
].each do |args|
options = args.pop
send(*args, **options)
conflicts "--cask", args.last
end
formula_options
[
[:switch, "--cask", "--casks", {
description: "Treat all named arguments as casks.",
}],
[:switch, "--[no-]binaries", {
description: "Disable/enable linking of helper executables (default: enabled).",
env: :cask_opts_binaries,
}],
[:switch, "--require-sha", {
description: "Require all casks to have a checksum.",
env: :cask_opts_require_sha,
}],
[:switch, "--[no-]quarantine", {
env: :cask_opts_quarantine,
odeprecated: true,
}],
[:switch, "--adopt", {
description: "Adopt existing artifacts in the destination that are identical to those being installed. " \
"Cannot be combined with `--force`.",
}],
[:switch, "--skip-cask-deps", {
description: "Skip installing cask dependencies.",
}],
[:switch, "--zap", {
description: "For use with `brew reinstall --cask`. Remove all files associated with a cask. " \
"*May remove files which are shared between applications.*",
}],
].each do |args|
options = args.pop
send(*args, **options)
conflicts "--formula", args.last
end
cask_options
conflicts "--ignore-dependencies", "--only-dependencies"
conflicts "--build-from-source", "--build-bottle", "--force-bottle"
conflicts "--adopt", "--force"
named_args [:formula, :cask], min: 1
end
sig { override.void }
def run
if args.env.present?
# Can't use `replacement: false` because `install_args` are used by
# `build.rb`. Instead, `hide_from_man_page` and don't do anything with
# this argument here.
# This odisabled should stick around indefinitely.
odisabled "`brew install --env`", "`env :std` in specific formula files"
end
args.named.each do |name|
if (tap_with_name = Tap.with_formula_name(name))
tap, = tap_with_name
elsif (tap_with_token = Tap.with_cask_token(name))
tap, = tap_with_token
end
tap&.ensure_installed!
end
if args.ignore_dependencies?
opoo <<~EOS
#{Tty.bold}`--ignore-dependencies` is an unsupported Homebrew developer option!#{Tty.reset}
Adjust your PATH to put any preferred versions of applications earlier in the
PATH rather than using this unsupported option!
EOS
end
begin
formulae, casks = T.cast(
args.named.to_formulae_and_casks(warn: false).partition { it.is_a?(Formula) },
[T::Array[Formula], T::Array[Cask::Cask]],
)
rescue FormulaOrCaskUnavailableError, Cask::CaskUnavailableError
cask_tap = CoreCaskTap.instance
if !cask_tap.installed? && (args.cask? || Tap.untapped_official_taps.exclude?(cask_tap.name))
cask_tap.ensure_installed!
retry if cask_tap.installed?
end
raise
end
if casks.any?
Install.ask_casks casks if args.ask?
if args.dry_run?
if (casks_to_install = casks.reject(&:installed?).presence)
ohai "Would install #{::Utils.pluralize("cask", casks_to_install.count, include_count: true)}:"
puts casks_to_install.map(&:full_name).join(" ")
end
casks.each do |cask|
dep_names = CaskDependent.new(cask)
.runtime_dependencies
.reject(&:installed?)
.map(&:name)
next if dep_names.blank?
ohai "Would install #{::Utils.pluralize("dependency", dep_names.count, include_count: true)} " \
"for #{cask.full_name}:"
puts dep_names.join(" ")
end
return
end
require "cask/installer"
installed_casks, new_casks = casks.partition(&:installed?)
download_queue = Homebrew::DownloadQueue.new_if_concurrency_enabled(pour: true)
fetch_casks = Homebrew::EnvConfig.no_install_upgrade? ? new_casks : casks
outdated_casks = Cask::Upgrade.outdated_casks(fetch_casks, args:, force: true, quiet: true)
fetch_casks = outdated_casks.intersection(fetch_casks)
if download_queue && fetch_casks.any?
binaries = args.binaries?
verbose = args.verbose?
force = args.force?
require_sha = args.require_sha?
quarantine = args.quarantine?
skip_cask_deps = args.skip_cask_deps?
zap = args.zap?
fetch_cask_installers = fetch_casks.map do |cask|
Cask::Installer.new(cask, reinstall: true, binaries:, verbose:, force:, skip_cask_deps:,
require_sha:, quarantine:, zap:, download_queue:)
end
# Run prelude checks for all casks before enqueueing downloads
fetch_cask_installers.each(&:prelude)
fetch_casks_sentence = fetch_casks.map { |cask| Formatter.identifier(cask.full_name) }.to_sentence
oh1 "Fetching downloads for: #{fetch_casks_sentence}", truncate: false
fetch_cask_installers.each(&:enqueue_downloads)
download_queue.fetch
end
exit 1 if Homebrew.failed?
new_casks.each do |cask|
Cask::Installer.new(
cask,
adopt: args.adopt?,
binaries: args.binaries?,
force: args.force?,
quarantine: args.quarantine?,
quiet: args.quiet?,
require_sha: args.require_sha?,
skip_cask_deps: args.skip_cask_deps?,
verbose: args.verbose?,
).install
end
if !Homebrew::EnvConfig.no_install_upgrade? && installed_casks.any?
Cask::Upgrade.upgrade_casks!(
*installed_casks,
force: args.force?,
dry_run: args.dry_run?,
binaries: args.binaries?,
quarantine: args.quarantine?,
require_sha: args.require_sha?,
skip_cask_deps: args.skip_cask_deps?,
verbose: args.verbose?,
quiet: args.quiet?,
args:,
)
end
end
formulae = Homebrew::Attestation.sort_formulae_for_install(formulae) if Homebrew::Attestation.enabled?
# if the user's flags will prevent bottle only-installations when no
# developer tools are available, we need to stop them early on
build_flags = []
unless DevelopmentTools.installed?
build_flags << "--HEAD" if args.HEAD?
build_flags << "--build-bottle" if args.build_bottle?
build_flags << "--build-from-source" if args.build_from_source?
raise BuildFlagsError.new(build_flags, bottled: formulae.all?(&:bottled?)) if build_flags.present?
end
if build_flags.present? && !Homebrew::EnvConfig.developer?
opoo "building from source is not supported!"
puts "You're on your own. Failures are expected so don't create any issues, please!"
end
installed_formulae = formulae.select do |f|
Install.install_formula?(
f,
head: args.HEAD?,
fetch_head: args.fetch_HEAD?,
only_dependencies: args.only_dependencies?,
force: args.force?,
quiet: args.quiet?,
skip_link: args.skip_link?,
overwrite: args.overwrite?,
)
end
return if formulae.any? && installed_formulae.empty?
Install.perform_preinstall_checks_once
Install.check_cc_argv(args.cc)
formulae_installer = Install.formula_installers(
installed_formulae,
installed_on_request: !args.as_dependency?,
installed_as_dependency: args.as_dependency?,
build_bottle: args.build_bottle?,
force_bottle: args.force_bottle?,
bottle_arch: args.bottle_arch,
ignore_deps: args.ignore_dependencies?,
only_deps: args.only_dependencies?,
include_test_formulae: args.include_test_formulae,
build_from_source_formulae: args.build_from_source_formulae,
cc: args.cc,
git: args.git?,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
overwrite: args.overwrite?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?,
dry_run: args.dry_run?,
skip_post_install: args.skip_post_install?,
skip_link: args.skip_link?,
)
dependants = Upgrade.dependants(
installed_formulae,
flags: args.flags_only,
ask: args.ask?,
installed_on_request: !args.as_dependency?,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?,
dry_run: args.dry_run?,
)
# Main block: if asking the user is enabled, show dependency and size information.
Install.ask_formulae(formulae_installer, dependants, args: args) if args.ask?
formulae_installer = Install.fetch_formulae(formulae_installer) unless args.dry_run?
exit 1 if Homebrew.failed?
Install.install_formulae(formulae_installer,
dry_run: args.dry_run?,
verbose: args.verbose?)
Upgrade.upgrade_dependents(
dependants, installed_formulae,
flags: args.flags_only,
dry_run: args.dry_run?,
force_bottle: args.force_bottle?,
build_from_source_formulae: args.build_from_source_formulae,
interactive: args.interactive?,
keep_tmp: args.keep_tmp?,
debug_symbols: args.debug_symbols?,
force: args.force?,
debug: args.debug?,
quiet: args.quiet?,
verbose: args.verbose?
)
Cleanup.periodic_clean!(dry_run: args.dry_run?)
Homebrew.messages.display_messages(display_times: args.display_times?)
rescue FormulaUnreadableError, FormulaClassUnavailableError,
TapFormulaUnreadableError, TapFormulaClassUnavailableError => e
require "utils/backtrace"
# Need to rescue before `FormulaUnavailableError` (superclass of this)
# is handled, as searching for a formula doesn't make sense here (the
# formula was found, but there's a problem with its implementation).
$stderr.puts Utils::Backtrace.clean(e) if Homebrew::EnvConfig.developer?
ofail e.message
rescue FormulaOrCaskUnavailableError, Cask::CaskUnavailableError => e
Homebrew.failed = true
# formula name or cask token
name = case e
when FormulaOrCaskUnavailableError then e.name
when Cask::CaskUnavailableError then e.token
else T.absurd(e)
end
if name == "updog"
ofail "What's updog?"
return
end
opoo e
reason = MissingFormula.reason(name, silent: true)
if !args.cask? && reason
$stderr.puts reason
return
end
# We don't seem to get good search results when the tap is specified
# so we might as well return early.
return if name.include?("/")
require "search"
package_types = []
package_types << "formulae" unless args.cask?
package_types << "casks" unless args.formula?
ohai "Searching for similarly named #{package_types.join(" and ")}..."
# Don't treat formula/cask name as a regex
string_or_regex = name
all_formulae, all_casks = Search.search_names(string_or_regex, args)
if all_formulae.any?
ohai "Formulae", Formatter.columns(all_formulae)
first_formula = all_formulae.first.to_s
puts <<~EOS
To install #{first_formula}, run:
brew install #{first_formula}
EOS
end
puts if all_formulae.any? && all_casks.any?
if all_casks.any?
ohai "Casks", Formatter.columns(all_casks)
first_cask = all_casks.first.to_s
puts <<~EOS
To install #{first_cask}, run:
brew install --cask #{first_cask}
EOS
end
return if all_formulae.any? || all_casks.any?
odie "No #{package_types.join(" or ")} found for #{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/cmd/--cellar.rb | Library/Homebrew/cmd/--cellar.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class Cellar < AbstractCommand
sig { override.returns(String) }
def self.command_name = "--cellar"
cmd_args do
description <<~EOS
Display Homebrew's Cellar path. *Default:* `$(brew --prefix)/Cellar`, or if
that directory doesn't exist, `$(brew --repository)/Cellar`.
If <formula> is provided, display the location in the Cellar where <formula>
would be installed, without any sort of versioned directory as the last path.
EOS
named_args :formula
end
sig { override.void }
def run
if args.no_named?
puts HOMEBREW_CELLAR
else
puts args.named.to_resolved_formulae.map(&:rack)
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/cmd/setup-ruby.rb | Library/Homebrew/cmd/setup-ruby.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class SetupRuby < AbstractCommand
include ShellCommand
cmd_args do
description <<~EOS
Installs and configures Homebrew's Ruby. If `command` is passed, it will only run Bundler if necessary for that command.
EOS
named_args :command
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/cmd/services.rb | Library/Homebrew/cmd/services.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "services/system"
require "services/commands/list"
require "services/commands/cleanup"
require "services/commands/info"
require "services/commands/restart"
require "services/commands/run"
require "services/commands/start"
require "services/commands/stop"
require "services/commands/kill"
module Homebrew
module Cmd
class Services < AbstractCommand
cmd_args do
usage_banner <<~EOS
`services` [<subcommand>]
Manage background services with macOS' `launchctl`(1) daemon manager or
Linux's `systemctl`(1) service manager.
If `sudo` is passed, operate on `/Library/LaunchDaemons` or `/usr/lib/systemd/system` (started at boot).
Otherwise, operate on `~/Library/LaunchAgents` or `~/.config/systemd/user` (started at login).
[`sudo`] `brew services` [`list`] [`--json`] [`--debug`]:
List information about all managed services for the current user (or root).
Provides more output from Homebrew and `launchctl`(1) or `systemctl`(1) if run with `--debug`.
[`sudo`] `brew services info` (<formula>|`--all`) [`--json`]:
List all managed services for the current user (or root).
[`sudo`] `brew services run` (<formula>|`--all`) [`--file=`]:
Run the service <formula> without registering to launch at login (or boot).
[`sudo`] `brew services start` (<formula>|`--all`) [`--file=`]:
Start the service <formula> immediately and register it to launch at login (or boot).
[`sudo`] `brew services stop` [`--keep`] [`--no-wait`|`--max-wait=`] (<formula>|`--all`):
Stop the service <formula> immediately and unregister it from launching at login (or boot),
unless `--keep` is specified.
[`sudo`] `brew services kill` (<formula>|`--all`):
Stop the service <formula> immediately but keep it registered to launch at login (or boot).
[`sudo`] `brew services restart` (<formula>|`--all`) [`--file=`]:
Stop (if necessary) and start the service <formula> immediately and register it to launch at login (or boot).
[`sudo`] `brew services cleanup`:
Remove all unused services.
EOS
flag "--file=",
description: "Use the service file from this location to `start` the service."
flag "--sudo-service-user=",
description: "When run as root on macOS, run the service(s) as this user."
flag "--max-wait=",
description: "Wait at most this many seconds for `stop` to finish stopping a service. " \
"Defaults to 60. Set this to zero (0) seconds to wait indefinitely."
switch "--no-wait",
description: "Don't wait for `stop` to finish stopping the service."
switch "--keep",
description: "When stopped, don't unregister the service from launching at login (or boot)."
switch "--all",
description: "Run <subcommand> on all services."
switch "--json",
description: "Output as JSON."
conflicts "--all", "--file"
conflicts "--max-wait", "--no-wait"
named_args %w[list info run start stop kill restart cleanup]
end
sig { override.void }
def run
# pbpaste's exit status is a proxy for detecting the use of reattach-to-user-namespace
if ENV.fetch("HOMEBREW_TMUX", nil) && File.exist?("/usr/bin/pbpaste") && !quiet_system("/usr/bin/pbpaste")
raise UsageError,
"`brew services` cannot run under tmux!"
end
# Keep this after the .parse to keep --help fast.
require "utils"
if !Homebrew::Services::System.launchctl? && !Homebrew::Services::System.systemctl?
raise UsageError, Homebrew::Services::System::MISSING_DAEMON_MANAGER_EXCEPTION_MESSAGE
end
if (sudo_service_user = args.sudo_service_user)
unless Homebrew::Services::System.root?
raise UsageError,
"`brew services` is supported only when running as root!"
end
unless Homebrew::Services::System.launchctl?
raise UsageError,
"`brew services --sudo-service-user` is currently supported only on macOS " \
"(but we'd love a PR to add Linux support)!"
end
Homebrew::Services::Cli.sudo_service_user = sudo_service_user
end
# Parse arguments.
subcommand, *formulae = args.named
no_named_formula_commands = [
*Homebrew::Services::Commands::List::TRIGGERS,
*Homebrew::Services::Commands::Cleanup::TRIGGERS,
]
if no_named_formula_commands.include?(subcommand)
raise UsageError, "The `#{subcommand}` subcommand does not accept a formula argument!" if formulae.present?
raise UsageError, "The `#{subcommand}` subcommand does not accept the `--all` argument!" if args.all?
end
if args.file
file_commands = [
*Homebrew::Services::Commands::Start::TRIGGERS,
*Homebrew::Services::Commands::Run::TRIGGERS,
*Homebrew::Services::Commands::Restart::TRIGGERS,
]
if file_commands.exclude?(subcommand)
raise UsageError, "The `#{subcommand}` subcommand does not accept the `--file=` argument!"
end
end
unless Homebrew::Services::Commands::Stop::TRIGGERS.include?(subcommand)
raise UsageError, "The `#{subcommand}` subcommand does not accept the `--keep` argument!" if args.keep?
if args.no_wait?
raise UsageError, "The `#{subcommand}` subcommand does not accept the `--no-wait` argument!"
end
if args.max_wait
raise UsageError, "The `#{subcommand}` subcommand does not accept the `--max-wait=` argument!"
end
end
opoo "The `--all` argument overrides provided formula argument!" if formulae.present? && args.all?
targets = if args.all?
if subcommand == "start"
Homebrew::Services::Formulae.available_services(
loaded: false,
skip_root: !Homebrew::Services::System.root?,
)
elsif subcommand == "stop"
Homebrew::Services::Formulae.available_services(
loaded: true,
skip_root: !Homebrew::Services::System.root?,
)
else
Homebrew::Services::Formulae.available_services
end
elsif formulae.present?
formulae.map { |formula| Homebrew::Services::FormulaWrapper.new(Formulary.factory(formula)) }
else
[]
end
# Exit successfully if --all was used but there is nothing to do
return if args.all? && targets.empty?
if Homebrew::Services::System.systemctl?
ENV["DBUS_SESSION_BUS_ADDRESS"] = ENV.fetch("HOMEBREW_DBUS_SESSION_BUS_ADDRESS", nil)
ENV["XDG_RUNTIME_DIR"] = ENV.fetch("HOMEBREW_XDG_RUNTIME_DIR", nil)
end
# Dispatch commands and aliases.
case subcommand.presence
when *Homebrew::Services::Commands::List::TRIGGERS
Homebrew::Services::Commands::List.run(json: args.json?)
when *Homebrew::Services::Commands::Cleanup::TRIGGERS
Homebrew::Services::Commands::Cleanup.run
when *Homebrew::Services::Commands::Info::TRIGGERS
Homebrew::Services::Commands::Info.run(targets, verbose: args.verbose?, json: args.json?)
when *Homebrew::Services::Commands::Restart::TRIGGERS
Homebrew::Services::Commands::Restart.run(targets, args.file, verbose: args.verbose?)
when *Homebrew::Services::Commands::Run::TRIGGERS
Homebrew::Services::Commands::Run.run(targets, args.file, verbose: args.verbose?)
when *Homebrew::Services::Commands::Start::TRIGGERS
Homebrew::Services::Commands::Start.run(targets, args.file, verbose: args.verbose?)
when *Homebrew::Services::Commands::Stop::TRIGGERS
Homebrew::Services::Commands::Stop.run(
targets,
verbose: args.verbose?,
no_wait: args.no_wait?,
max_wait: args.max_wait&.to_f || 60.0,
keep: args.keep?,
)
when *Homebrew::Services::Commands::Kill::TRIGGERS
Homebrew::Services::Commands::Kill.run(targets, verbose: args.verbose?)
else
raise UsageError, "unknown subcommand: `#{subcommand}`"
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/cmd/update-if-needed.rb | Library/Homebrew/cmd/update-if-needed.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class UpdateIfNeeded < AbstractCommand
include ShellCommand
cmd_args do
description <<~EOS
Runs `brew update --auto-update` only if needed.
This is a good replacement for `brew update` in scripts where you want
the no-op case to be both possible and really fast.
EOS
named_args :none
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/cmd/formulae.rb | Library/Homebrew/cmd/formulae.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module Cmd
class Formulae < AbstractCommand
include ShellCommand
cmd_args do
description "List all locally installable formulae including short names."
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/developer.rb | Library/Homebrew/cmd/developer.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module Cmd
class Developer < AbstractCommand
cmd_args do
description <<~EOS
Control Homebrew's developer mode. When developer mode is enabled,
`brew update` will update Homebrew to the latest commit on the `main`
branch instead of the latest stable version along with some other behaviour changes.
`brew developer` [`state`]:
Display the current state of Homebrew's developer mode.
`brew developer` (`on`|`off`):
Turn Homebrew's developer mode on or off respectively.
EOS
named_args %w[state on off], max: 1
end
sig { override.void }
def run
case args.named.first
when nil, "state"
if Homebrew::EnvConfig.developer?
puts "Developer mode is enabled because #{Tty.bold}HOMEBREW_DEVELOPER#{Tty.reset} is set."
elsif Homebrew::EnvConfig.devcmdrun?
puts "Developer mode is enabled because a developer command or `brew developer on` was run."
else
puts "Developer mode is disabled."
end
if Homebrew::EnvConfig.developer? || Homebrew::EnvConfig.devcmdrun?
if Homebrew::EnvConfig.update_to_tag?
puts "However, `brew update` will update to the latest stable tag because " \
"#{Tty.bold}HOMEBREW_UPDATE_TO_TAG#{Tty.reset} is set."
else
puts "`brew update` will update to the latest commit on the `main` branch."
end
else
puts "`brew update` will update to the latest stable tag."
end
when "on"
Homebrew::Settings.write "devcmdrun", true
if Homebrew::EnvConfig.update_to_tag?
puts "To fully enable developer mode, you must unset #{Tty.bold}HOMEBREW_UPDATE_TO_TAG#{Tty.reset}."
end
when "off"
Homebrew::Settings.delete "devcmdrun"
if Homebrew::EnvConfig.developer?
puts "To fully disable developer mode, you must unset #{Tty.bold}HOMEBREW_DEVELOPER#{Tty.reset}."
end
else
raise UsageError, "unknown subcommand: #{args.named.first}"
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/cmd/leaves.rb | Library/Homebrew/cmd/leaves.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "cask_dependent"
module Homebrew
module Cmd
class Leaves < AbstractCommand
cmd_args do
description <<~EOS
List installed formulae that are not dependencies of another installed formula or cask.
EOS
switch "-r", "--installed-on-request",
description: "Only list leaves that were manually installed."
switch "-p", "--installed-as-dependency",
description: "Only list leaves that were installed as dependencies."
conflicts "--installed-on-request", "--installed-as-dependency"
named_args :none
end
sig { override.void }
def run
leaves_list = Formula.installed - Formula.installed.flat_map(&:installed_runtime_formula_dependencies)
casks_runtime_dependencies = Cask::Caskroom.casks.flat_map do |cask|
CaskDependent.new(cask).runtime_dependencies.map(&:to_installed_formula)
end
leaves_list -= casks_runtime_dependencies
leaves_list.select! { |leaf| installed_on_request?(leaf) } if args.installed_on_request?
leaves_list.select! { |leaf| installed_as_dependency?(leaf) } if args.installed_as_dependency?
leaves_list.map(&:full_name)
.sort
.each { |leaf| puts(leaf) }
end
private
sig { params(formula: Formula).returns(T::Boolean) }
def installed_on_request?(formula)
formula.any_installed_keg&.tab&.installed_on_request == true
end
sig { params(formula: Formula).returns(T::Boolean) }
def installed_as_dependency?(formula)
formula.any_installed_keg&.tab&.installed_as_dependency == true
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cmd/rbenv-sync.rb | Library/Homebrew/cmd/rbenv-sync.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module Cmd
class RbenvSync < AbstractCommand
cmd_args do
description <<~EOS
Create symlinks for Homebrew's installed Ruby versions in `~/.rbenv/versions`.
Note that older version symlinks will also be created so e.g. Ruby 3.2.1 will
also be symlinked to 3.2.0.
EOS
named_args :none
end
sig { override.void }
def run
rbenv_root = Pathname(ENV.fetch("HOMEBREW_RBENV_ROOT", Pathname(Dir.home)/".rbenv"))
# Don't run multiple times at once.
rbenv_sync_running = rbenv_root/".rbenv_sync_running"
return if rbenv_sync_running.exist?
begin
rbenv_versions = rbenv_root/"versions"
rbenv_versions.mkpath
FileUtils.touch rbenv_sync_running
HOMEBREW_CELLAR.glob("ruby{,@*}")
.flat_map(&:children)
.each { |path| link_rbenv_versions(path, rbenv_versions) }
rbenv_versions.children
.select(&:symlink?)
.reject(&:exist?)
.each { |path| FileUtils.rm_f path }
ensure
rbenv_sync_running.unlink if rbenv_sync_running.exist?
end
end
private
sig { params(path: Pathname, rbenv_versions: Pathname).void }
def link_rbenv_versions(path, rbenv_versions)
rbenv_versions.mkpath
version = Keg.new(path).version
major_version = version.major.to_i
minor_version = version.minor.to_i
patch_version = version.patch.to_i
patch_version_range = if Homebrew::EnvConfig.env_sync_strict?
# Only create symlinks for the exact installed patch version.
# e.g. 3.4.0 => 3.4.0
[patch_version]
else
# Create folder symlinks for all patch versions to the latest patch version
# e.g. 3.4.0 => 3.4.2
0..patch_version
end
patch_version_range.each do |patch|
link_path = rbenv_versions/"#{major_version}.#{minor_version}.#{patch}"
# Don't clobber existing user installations.
next if link_path.exist? && !link_path.symlink?
FileUtils.rm_f link_path
FileUtils.ln_s path, link_path
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/vendor/gems/mechanize-2.14.0/lib/mechanize/version.rb | Library/Homebrew/vendor/gems/mechanize-2.14.0/lib/mechanize/version.rb | # frozen_string_literal: true
class Mechanize
VERSION = "2.14.0"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/gems/mechanize-2.14.0/lib/mechanize/http/content_disposition_parser.rb | Library/Homebrew/vendor/gems/mechanize-2.14.0/lib/mechanize/http/content_disposition_parser.rb | # frozen_string_literal: true
# coding: BINARY
require 'strscan'
require 'time'
class Mechanize::HTTP
ContentDisposition = Struct.new :type, :filename, :creation_date,
:modification_date, :read_date, :size, :parameters
end
##
# Parser Content-Disposition headers that loosely follows RFC 2183.
#
# Beyond RFC 2183, this parser allows:
#
# * Missing disposition-type
# * Multiple semicolons
# * Whitespace around semicolons
# * Dates in ISO 8601 format
class Mechanize::HTTP::ContentDispositionParser
attr_accessor :scanner # :nodoc:
@parser = nil
##
# Parses the disposition type and params in the +content_disposition+
# string. The "Content-Disposition:" must be removed.
def self.parse content_disposition
@parser ||= self.new
@parser.parse content_disposition
end
##
# Creates a new parser Content-Disposition headers
def initialize
@scanner = nil
end
##
# Parses the +content_disposition+ header. If +header+ is set to true the
# "Content-Disposition:" portion will be parsed
def parse content_disposition, header = false
return nil if content_disposition.empty?
@scanner = StringScanner.new content_disposition
if header then
return nil unless @scanner.scan(/Content-Disposition/i)
return nil unless @scanner.scan(/:/)
spaces
end
type = rfc_2045_token
@scanner.scan(/;+/)
if @scanner.peek(1) == '=' then
@scanner.pos = 0
type = nil
end
disposition = Mechanize::HTTP::ContentDisposition.new type
spaces
return nil unless parameters = parse_parameters
disposition.filename = parameters.delete 'filename'
disposition.creation_date = parameters.delete 'creation-date'
disposition.modification_date = parameters.delete 'modification-date'
disposition.read_date = parameters.delete 'read-date'
disposition.size = parameters.delete 'size'
disposition.parameters = parameters
disposition
end
##
# Extracts disposition-param and returns a Hash.
def parse_parameters
parameters = {}
while true do
return nil unless param = rfc_2045_token
param.downcase!
return nil unless @scanner.scan(/=/)
value = case param
when /^filename$/ then
rfc_2045_value
when /^(creation|modification|read)-date$/ then
date = rfc_2045_quoted_string
begin
Time.rfc822 date
rescue ArgumentError
begin
Time.iso8601 date
rescue ArgumentError
nil
end
end
when /^size$/ then
rfc_2045_value.to_i(10)
else
rfc_2045_value
end
return nil unless value
parameters[param] = value
spaces
break if @scanner.eos? or not @scanner.scan(/;+/)
spaces
end
parameters
end
##
# quoted-string = <"> *(qtext/quoted-pair) <">
# qtext = <any CHAR excepting <">, "\" & CR,
# and including linear-white-space
# quoted-pair = "\" CHAR
#
# Parses an RFC 2045 quoted-string
def rfc_2045_quoted_string
return nil unless @scanner.scan(/"/)
text = String.new
while true do
chunk = @scanner.scan(/[\000-\014\016-\041\043-\133\135-\177]+/) # not \r "
if chunk then
text << chunk
if @scanner.peek(1) == '\\' then
@scanner.get_byte
return nil if @scanner.eos?
text << @scanner.get_byte
elsif @scanner.scan(/\r\n[\t ]+/) then
text << " "
end
else
if '\\"' == @scanner.peek(2) then
@scanner.skip(/\\/)
text << @scanner.get_byte
elsif '"' == @scanner.peek(1) then
@scanner.get_byte
break
else
return nil
end
end
end
text
end
##
# token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials>
#
# Parses an RFC 2045 token
def rfc_2045_token
@scanner.scan(/[^\000-\037\177()<>@,;:\\"\/\[\]?= ]+/)
end
##
# value := token / quoted-string
#
# Parses an RFC 2045 value
def rfc_2045_value
if @scanner.peek(1) == '"' then
rfc_2045_quoted_string
else
rfc_2045_token
end
end
##
# 1*SP
#
# Parses spaces
def spaces
@scanner.scan(/ +/)
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/vendor/bundle/bundler/setup.rb | Library/Homebrew/vendor/bundle/bundler/setup.rb | require 'rbconfig'
module Kernel
remove_method(:gem) if private_method_defined?(:gem)
def gem(*)
end
private :gem
end
unless defined?(Gem)
module Gem
def self.ruby_api_version
RbConfig::CONFIG["ruby_version"]
end
def self.extension_api_version
if 'no' == RbConfig::CONFIG['ENABLE_SHARED']
"#{ruby_api_version}-static"
else
ruby_api_version
end
end
end
end
if Gem.respond_to?(:discover_gems_on_require=)
Gem.discover_gems_on_require = false
else
[::Kernel.singleton_class, ::Kernel].each do |k|
if k.private_method_defined?(:gem_original_require)
private_require = k.private_method_defined?(:require)
k.send(:remove_method, :require)
k.send(:define_method, :require, k.instance_method(:gem_original_require))
k.send(:private, :require) if private_require
end
end
end
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/public_suffix-7.0.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/addressable-2.8.8/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/ast-2.4.3/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/base64-0.3.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/benchmark-0.5.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/bigdecimal-4.0.1")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/bigdecimal-4.0.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/bindata-2.5.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/coderay-1.1.3/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/concurrent-ruby-1.3.6/lib/concurrent-ruby")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/csv-3.3.5/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/diff-lcs-1.6.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/docile-1.4.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/elftools-1.3.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/erubi-1.13.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/hana-1.3.7/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/json-2.18.0")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/json-2.18.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/regexp_parser-2.11.3/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/simpleidn-0.2.3/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/json_schemer-2.5.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rexml-3.4.4/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/kramdown-2.5.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/language_server-protocol-3.17.0.5/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/lint_roller-1.1.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/logger-1.7.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/method_source-1.1.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/prism-1.7.0")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/prism-1.7.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/minitest-6.0.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/netrc-0.11.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/parallel-1.27.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/parallel_tests-5.5.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/racc-1.8.1")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/racc-1.8.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/parser-3.3.10.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/patchelf-1.5.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/plist-3.7.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/pry-0.15.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/pycall-1.5.2")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/pycall-1.5.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rainbow-3.1.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/rbs-4.0.0.dev.4")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rbs-4.0.0.dev.4/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rbi-0.3.8/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/redcarpet-3.6.1")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/redcarpet-3.6.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/require-hooks-0.2.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-support-3.13.6/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-core-3.13.6/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-expectations-3.13.5/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-mocks-3.13.7/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-3.13.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-github-3.0.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-retry-0.6.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/sorbet-runtime-0.6.12872/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec-sorbet-1.9.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rspec_junit_formatter-0.6.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rubocop-ast-1.48.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/ruby-progressbar-1.13.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/unicode-emoji-4.2.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/unicode-display_width-3.2.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rubocop-1.82.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rubocop-md-2.0.3/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rubocop-performance-1.26.1/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rubocop-rspec-3.8.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/rubocop-sorbet-0.11.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/ruby-lsp-0.26.4/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/ruby-macho-4.1.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/ruby-prof-1.7.2")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/ruby-prof-1.7.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/simplecov-html-0.13.2/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/simplecov_json_formatter-0.1.4/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/simplecov-0.22.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/simplecov-cobertura-3.1.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/sorbet-static-0.6.12872-universal-darwin/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/sorbet-0.6.12872/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/sorbet-static-and-runtime-0.6.12872/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/thor-1.4.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/spoom-1.7.11/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/stackprof-0.2.27")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/stackprof-0.2.27/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/yard-0.9.38/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/yard-sorbet-0.9.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/tapioca-0.17.10/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/test-prof-1.5.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/extensions/arm64-darwin-20/#{Gem.extension_api_version}/vernier-1.9.0")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/vernier-1.9.0/lib")
$:.unshift File.expand_path("#{__dir__}/../#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/warning-1.5.0/lib")
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/base64-0.3.0/lib/base64.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/base64-0.3.0/lib/base64.rb | # frozen_string_literal: true
#
# \Module \Base64 provides methods for:
#
# - \Encoding a binary string (containing non-ASCII characters)
# as a string of printable ASCII characters.
# - Decoding such an encoded string.
#
# \Base64 is commonly used in contexts where binary data
# is not allowed or supported:
#
# - Images in HTML or CSS files, or in URLs.
# - Email attachments.
#
# A \Base64-encoded string is about one-third larger that its source.
# See the {Wikipedia article}[https://en.wikipedia.org/wiki/Base64]
# for more information.
#
# This module provides three pairs of encode/decode methods.
# Your choices among these methods should depend on:
#
# - Which character set is to be used for encoding and decoding.
# - Whether "padding" is to be used.
# - Whether encoded strings are to contain newlines.
#
# Note: Examples on this page assume that the including program has executed:
#
# require 'base64'
#
# == \Encoding Character Sets
#
# A \Base64-encoded string consists only of characters from a 64-character set:
#
# - <tt>('A'..'Z')</tt>.
# - <tt>('a'..'z')</tt>.
# - <tt>('0'..'9')</tt>.
# - <tt>=</tt>, the 'padding' character.
# - Either:
# - <tt>%w[+ /]</tt>:
# {RFC-2045-compliant}[https://datatracker.ietf.org/doc/html/rfc2045];
# _not_ safe for URLs.
# - <tt>%w[- _]</tt>:
# {RFC-4648-compliant}[https://datatracker.ietf.org/doc/html/rfc4648];
# safe for URLs.
#
# If you are working with \Base64-encoded strings that will come from
# or be put into URLs, you should choose this encoder-decoder pair
# of RFC-4648-compliant methods:
#
# - Base64.urlsafe_encode64 and Base64.urlsafe_decode64.
#
# Otherwise, you may choose any of the pairs in this module,
# including the pair above, or the RFC-2045-compliant pairs:
#
# - Base64.encode64 and Base64.decode64.
# - Base64.strict_encode64 and Base64.strict_decode64.
#
# == Padding
#
# \Base64-encoding changes a triplet of input bytes
# into a quartet of output characters.
#
# <b>Padding in Encode Methods</b>
#
# Padding -- extending an encoded string with zero, one, or two trailing
# <tt>=</tt> characters -- is performed by methods Base64.encode64,
# Base64.strict_encode64, and, by default, Base64.urlsafe_encode64:
#
# Base64.encode64('s') # => "cw==\n"
# Base64.strict_encode64('s') # => "cw=="
# Base64.urlsafe_encode64('s') # => "cw=="
# Base64.urlsafe_encode64('s', padding: false) # => "cw"
#
# When padding is performed, the encoded string is always of length <em>4n</em>,
# where +n+ is a non-negative integer:
#
# - Input bytes of length <em>3n</em> generate unpadded output characters
# of length <em>4n</em>:
#
# # n = 1: 3 bytes => 4 characters.
# Base64.strict_encode64('123') # => "MDEy"
# # n = 2: 6 bytes => 8 characters.
# Base64.strict_encode64('123456') # => "MDEyMzQ1"
#
# - Input bytes of length <em>3n+1</em> generate padded output characters
# of length <em>4(n+1)</em>, with two padding characters at the end:
#
# # n = 1: 4 bytes => 8 characters.
# Base64.strict_encode64('1234') # => "MDEyMw=="
# # n = 2: 7 bytes => 12 characters.
# Base64.strict_encode64('1234567') # => "MDEyMzQ1Ng=="
#
# - Input bytes of length <em>3n+2</em> generate padded output characters
# of length <em>4(n+1)</em>, with one padding character at the end:
#
# # n = 1: 5 bytes => 8 characters.
# Base64.strict_encode64('12345') # => "MDEyMzQ="
# # n = 2: 8 bytes => 12 characters.
# Base64.strict_encode64('12345678') # => "MDEyMzQ1Njc="
#
# When padding is suppressed, for a positive integer <em>n</em>:
#
# - Input bytes of length <em>3n</em> generate unpadded output characters
# of length <em>4n</em>:
#
# # n = 1: 3 bytes => 4 characters.
# Base64.urlsafe_encode64('123', padding: false) # => "MDEy"
# # n = 2: 6 bytes => 8 characters.
# Base64.urlsafe_encode64('123456', padding: false) # => "MDEyMzQ1"
#
# - Input bytes of length <em>3n+1</em> generate unpadded output characters
# of length <em>4n+2</em>, with two padding characters at the end:
#
# # n = 1: 4 bytes => 6 characters.
# Base64.urlsafe_encode64('1234', padding: false) # => "MDEyMw"
# # n = 2: 7 bytes => 10 characters.
# Base64.urlsafe_encode64('1234567', padding: false) # => "MDEyMzQ1Ng"
#
# - Input bytes of length <em>3n+2</em> generate unpadded output characters
# of length <em>4n+3</em>, with one padding character at the end:
#
# # n = 1: 5 bytes => 7 characters.
# Base64.urlsafe_encode64('12345', padding: false) # => "MDEyMzQ"
# # m = 2: 8 bytes => 11 characters.
# Base64.urlsafe_encode64('12345678', padding: false) # => "MDEyMzQ1Njc"
#
# <b>Padding in Decode Methods</b>
#
# All of the \Base64 decode methods support (but do not require) padding.
#
# \Method Base64.decode64 does not check the size of the padding:
#
# Base64.decode64("MDEyMzQ1Njc") # => "01234567"
# Base64.decode64("MDEyMzQ1Njc=") # => "01234567"
# Base64.decode64("MDEyMzQ1Njc==") # => "01234567"
#
# \Method Base64.strict_decode64 strictly enforces padding size:
#
# Base64.strict_decode64("MDEyMzQ1Njc") # Raises ArgumentError
# Base64.strict_decode64("MDEyMzQ1Njc=") # => "01234567"
# Base64.strict_decode64("MDEyMzQ1Njc==") # Raises ArgumentError
#
# \Method Base64.urlsafe_decode64 allows padding in the encoded string,
# which if present, must be correct:
# see {Padding}[Base64.html#module-Base64-label-Padding], above:
#
# Base64.urlsafe_decode64("MDEyMzQ1Njc") # => "01234567"
# Base64.urlsafe_decode64("MDEyMzQ1Njc=") # => "01234567"
# Base64.urlsafe_decode64("MDEyMzQ1Njc==") # Raises ArgumentError.
#
# == Newlines
#
# An encoded string returned by Base64.encode64 or Base64.urlsafe_encode64
# has an embedded newline character
# after each 60-character sequence, and, if non-empty, at the end:
#
# # No newline if empty.
# encoded = Base64.encode64("\x00" * 0)
# encoded.index("\n") # => nil
#
# # Newline at end of short output.
# encoded = Base64.encode64("\x00" * 1)
# encoded.size # => 4
# encoded.index("\n") # => 4
#
# # Newline at end of longer output.
# encoded = Base64.encode64("\x00" * 45)
# encoded.size # => 60
# encoded.index("\n") # => 60
#
# # Newlines embedded and at end of still longer output.
# encoded = Base64.encode64("\x00" * 46)
# encoded.size # => 65
# encoded.rindex("\n") # => 65
# encoded.split("\n").map {|s| s.size } # => [60, 4]
#
# The string to be encoded may itself contain newlines,
# which are encoded as \Base64:
#
# # Base64.encode64("\n\n\n") # => "CgoK\n"
# s = "This is line 1\nThis is line 2\n"
# Base64.encode64(s) # => "VGhpcyBpcyBsaW5lIDEKVGhpcyBpcyBsaW5lIDIK\n"
#
module Base64
VERSION = "0.3.0"
module_function
# :call-seq:
# Base64.encode64(string) -> encoded_string
#
# Returns a string containing the RFC-2045-compliant \Base64-encoding of +string+.
#
# Per RFC 2045, the returned string may contain the URL-unsafe characters
# <tt>+</tt> or <tt>/</tt>;
# see {Encoding Character Set}[Base64.html#module-Base64-label-Encoding+Character+Sets] above:
#
# Base64.encode64("\xFB\xEF\xBE") # => "++++\n"
# Base64.encode64("\xFF\xFF\xFF") # => "////\n"
#
# The returned string may include padding;
# see {Padding}[Base64.html#module-Base64-label-Padding] above.
#
# Base64.encode64('*') # => "Kg==\n"
#
# The returned string ends with a newline character, and if sufficiently long
# will have one or more embedded newline characters;
# see {Newlines}[Base64.html#module-Base64-label-Newlines] above:
#
# Base64.encode64('*') # => "Kg==\n"
# Base64.encode64('*' * 46)
# # => "KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioq\nKg==\n"
#
# The string to be encoded may itself contain newlines,
# which will be encoded as ordinary \Base64:
#
# Base64.encode64("\n\n\n") # => "CgoK\n"
# s = "This is line 1\nThis is line 2\n"
# Base64.encode64(s) # => "VGhpcyBpcyBsaW5lIDEKVGhpcyBpcyBsaW5lIDIK\n"
#
def encode64(bin)
[bin].pack("m")
end
# :call-seq:
# Base64.decode(encoded_string) -> decoded_string
#
# Returns a string containing the decoding of an RFC-2045-compliant
# \Base64-encoded string +encoded_string+:
#
# s = "VGhpcyBpcyBsaW5lIDEKVGhpcyBpcyBsaW5lIDIK\n"
# Base64.decode64(s) # => "This is line 1\nThis is line 2\n"
#
# Non-\Base64 characters in +encoded_string+ are ignored;
# see {Encoding Character Set}[Base64.html#module-Base64-label-Encoding+Character+Sets] above:
# these include newline characters and characters <tt>-</tt> and <tt>/</tt>:
#
# Base64.decode64("\x00\n-_") # => ""
#
# Padding in +encoded_string+ (even if incorrect) is ignored:
#
# Base64.decode64("MDEyMzQ1Njc") # => "01234567"
# Base64.decode64("MDEyMzQ1Njc=") # => "01234567"
# Base64.decode64("MDEyMzQ1Njc==") # => "01234567"
#
def decode64(str)
str.unpack1("m")
end
# :call-seq:
# Base64.strict_encode64(string) -> encoded_string
#
# Returns a string containing the RFC-2045-compliant \Base64-encoding of +string+.
#
# Per RFC 2045, the returned string may contain the URL-unsafe characters
# <tt>+</tt> or <tt>/</tt>;
# see {Encoding Character Set}[Base64.html#module-Base64-label-Encoding+Character+Sets] above:
#
# Base64.strict_encode64("\xFB\xEF\xBE") # => "++++\n"
# Base64.strict_encode64("\xFF\xFF\xFF") # => "////\n"
#
# The returned string may include padding;
# see {Padding}[Base64.html#module-Base64-label-Padding] above.
#
# Base64.strict_encode64('*') # => "Kg==\n"
#
# The returned string will have no newline characters, regardless of its length;
# see {Newlines}[Base64.html#module-Base64-label-Newlines] above:
#
# Base64.strict_encode64('*') # => "Kg=="
# Base64.strict_encode64('*' * 46)
# # => "KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg=="
#
# The string to be encoded may itself contain newlines,
# which will be encoded as ordinary \Base64:
#
# Base64.strict_encode64("\n\n\n") # => "CgoK"
# s = "This is line 1\nThis is line 2\n"
# Base64.strict_encode64(s) # => "VGhpcyBpcyBsaW5lIDEKVGhpcyBpcyBsaW5lIDIK"
#
def strict_encode64(bin)
[bin].pack("m0")
end
# :call-seq:
# Base64.strict_decode64(encoded_string) -> decoded_string
#
# Returns a string containing the decoding of an RFC-2045-compliant
# \Base64-encoded string +encoded_string+:
#
# s = "VGhpcyBpcyBsaW5lIDEKVGhpcyBpcyBsaW5lIDIK"
# Base64.strict_decode64(s) # => "This is line 1\nThis is line 2\n"
#
# Non-\Base64 characters in +encoded_string+ are not allowed;
# see {Encoding Character Set}[Base64.html#module-Base64-label-Encoding+Character+Sets] above:
# these include newline characters and characters <tt>-</tt> and <tt>/</tt>:
#
# Base64.strict_decode64("\n") # Raises ArgumentError
# Base64.strict_decode64('-') # Raises ArgumentError
# Base64.strict_decode64('_') # Raises ArgumentError
#
# Padding in +encoded_string+, if present, must be correct:
#
# Base64.strict_decode64("MDEyMzQ1Njc") # Raises ArgumentError
# Base64.strict_decode64("MDEyMzQ1Njc=") # => "01234567"
# Base64.strict_decode64("MDEyMzQ1Njc==") # Raises ArgumentError
#
def strict_decode64(str)
str.unpack1("m0")
end
# :call-seq:
# Base64.urlsafe_encode64(string) -> encoded_string
#
# Returns the RFC-4648-compliant \Base64-encoding of +string+.
#
# Per RFC 4648, the returned string will not contain the URL-unsafe characters
# <tt>+</tt> or <tt>/</tt>,
# but instead may contain the URL-safe characters
# <tt>-</tt> and <tt>_</tt>;
# see {Encoding Character Set}[Base64.html#module-Base64-label-Encoding+Character+Sets] above:
#
# Base64.urlsafe_encode64("\xFB\xEF\xBE") # => "----"
# Base64.urlsafe_encode64("\xFF\xFF\xFF") # => "____"
#
# By default, the returned string may have padding;
# see {Padding}[Base64.html#module-Base64-label-Padding], above:
#
# Base64.urlsafe_encode64('*') # => "Kg=="
#
# Optionally, you can suppress padding:
#
# Base64.urlsafe_encode64('*', padding: false) # => "Kg"
#
# The returned string will have no newline characters, regardless of its length;
# see {Newlines}[Base64.html#module-Base64-label-Newlines] above:
#
# Base64.urlsafe_encode64('*') # => "Kg=="
# Base64.urlsafe_encode64('*' * 46)
# # => "KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKg=="
#
def urlsafe_encode64(bin, padding: true)
str = strict_encode64(bin)
str.chomp!("==") or str.chomp!("=") unless padding
str.tr!("+/", "-_")
str
end
# :call-seq:
# Base64.urlsafe_decode64(encoded_string) -> decoded_string
#
# Returns the decoding of an RFC-4648-compliant \Base64-encoded string +encoded_string+:
#
# +encoded_string+ may not contain non-Base64 characters;
# see {Encoding Character Set}[Base64.html#module-Base64-label-Encoding+Character+Sets] above:
#
# Base64.urlsafe_decode64('+') # Raises ArgumentError.
# Base64.urlsafe_decode64('/') # Raises ArgumentError.
# Base64.urlsafe_decode64("\n") # Raises ArgumentError.
#
# Padding in +encoded_string+, if present, must be correct:
# see {Padding}[Base64.html#module-Base64-label-Padding], above:
#
# Base64.urlsafe_decode64("MDEyMzQ1Njc") # => "01234567"
# Base64.urlsafe_decode64("MDEyMzQ1Njc=") # => "01234567"
# Base64.urlsafe_decode64("MDEyMzQ1Njc==") # Raises ArgumentError.
#
def urlsafe_decode64(str)
# NOTE: RFC 4648 does say nothing about unpadded input, but says that
# "the excess pad characters MAY also be ignored", so it is inferred that
# unpadded input is also acceptable.
if !str.end_with?("=") && str.length % 4 != 0
str = str.ljust((str.length + 3) & ~3, "=")
str.tr!("-_", "+/")
else
str = str.tr("-_", "+/")
end
strict_decode64(str)
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/vendor/bundle/ruby/3.4.0/gems/warning-1.5.0/lib/warning.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/warning-1.5.0/lib/warning.rb | require 'monitor'
module Warning
module Processor
# Map of symbols to regexps for warning messages to ignore.
IGNORE_MAP = {
ambiguous_slash: /: warning: ambiguous first argument; put parentheses or a space even after [`']\/' operator\n\z|: warning: ambiguity between regexp and two divisions: wrap regexp in parentheses or add a space after [`']\/' operator\n\z|ambiguous `\/`; wrap regexp in parentheses or add a space after `\/` operator\n\z/,
arg_prefix: /: warning: ([`'][&\*]'||ambiguous `[\*&]` has been) interpreted as( an)? argument prefix\n\z/,
bignum: /: warning: constant ::Bignum is deprecated\n\z/,
default_gem_removal: /: warning: .+? was loaded from the standard library, but will no longer be part of the default gems starting from Ruby [\d.]+\./,
fixnum: /: warning: constant ::Fixnum is deprecated\n\z/,
ignored_block: /: warning: the block passed to '.+' defined at .+:\d+ may be ignored\n\z/,
method_redefined: /: warning: method redefined; discarding old .+\n\z|: warning: previous definition of .+ was here\n\z/,
missing_gvar: /: warning: global variable [`']\$.+' not initialized\n\z/,
missing_ivar: /: warning: instance variable @.+ not initialized\n\z/,
not_reached: /: warning: statement not reached\n\z/,
shadow: /: warning: shadowing outer local variable - \w+\n\z/,
unused_var: /: warning: assigned but unused variable - \w+\n\z/,
useless_operator: /: warning: possibly useless use of [><!=]+ in void context\n\z/,
keyword_separation: /: warning: (?:Using the last argument (?:for [`'].+' )?as keyword parameters is deprecated; maybe \*\* should be added to the call|Passing the keyword argument (?:for [`'].+' )?as the last hash parameter is deprecated|Splitting the last argument (?:for [`'].+' )?into positional and keyword parameters is deprecated|The called method (?:[`'].+' )?is defined here)\n\z/,
safe: /: warning: (?:rb_safe_level_2_warning|rb_safe_level|rb_set_safe_level_force|rb_set_safe_level|rb_secure|rb_insecure_operation|rb_check_safe_obj|\$SAFE) will (?:be removed|become a normal global variable) in Ruby 3\.0\n\z/,
taint: /: warning: (?:rb_error_untrusted|rb_check_trusted|Pathname#taint|Pathname#untaint|rb_env_path_tainted|Object#tainted\?|Object#taint|Object#untaint|Object#untrusted\?|Object#untrust|Object#trust|rb_obj_infect|rb_tainted_str_new|rb_tainted_str_new_cstr) is deprecated and will be removed in Ruby 3\.2\.?\n\z/,
mismatched_indentations: /: warning: mismatched indentations at '.+' with '.+' at \d+\n\z/,
void_context: /possibly useless use of (?:a )?\S+ in void context/,
}
# Map of action symbols to procs that return the symbol
ACTION_PROC_MAP = {
raise: proc{|_| :raise},
default: proc{|_| :default},
backtrace: proc{|_| :backtrace},
}
private_constant :ACTION_PROC_MAP
# Clear all current ignored warnings, warning processors, and duplicate check cache.
# Also disables deduplicating warnings if that is currently enabled.
#
# If a block is passed, the previous values are restored after the block exits.
#
# Examples:
#
# # Clear warning state
# Warning.clear
#
# Warning.clear do
# # Clear warning state inside the block
# ...
# end
# # Previous warning state restored when block exists
def clear
if block_given?
ignore = process = dedup = nil
synchronize do
ignore = @ignore.dup
process = @process.dup
dedup = @dedup.dup
end
begin
clear
yield
ensure
synchronize do
@ignore = ignore
@process = process
@dedup = dedup
end
end
else
synchronize do
@ignore.clear
@process.clear
@dedup = false
end
end
end
# Deduplicate warnings, suppress warning messages if the same warning message
# has already occurred. Note that this can lead to unbounded memory use
# if unique warnings are generated.
def dedup
@dedup = {}
end
def freeze
@ignore.freeze
@process.freeze
super
end
# Ignore any warning messages matching the given regexp, if they
# start with the given path.
# The regexp can also be one of the following symbols (or an array including them), which will
# use an appropriate regexp for the given warning:
#
# :arg_prefix :: Ignore warnings when using * or & as an argument prefix
# :ambiguous_slash :: Ignore warnings for things like <tt>method /regexp/</tt>
# :bignum :: Ignore warnings when referencing the ::Bignum constant.
# :default_gem_removal :: Ignore warnings that a gem will be removed from the default gems
# in a future Ruby version.
# :fixnum :: Ignore warnings when referencing the ::Fixnum constant.
# :keyword_separation :: Ignore warnings related to keyword argument separation.
# :method_redefined :: Ignore warnings when defining a method in a class/module where a
# method of the same name was already defined in that class/module.
# :missing_gvar :: Ignore warnings for accesses to global variables
# that have not yet been initialized
# :missing_ivar :: Ignore warnings for accesses to instance variables
# that have not yet been initialized
# :not_reached :: Ignore statement not reached warnings.
# :safe :: Ignore warnings related to $SAFE and related C-API functions.
# :shadow :: Ignore warnings related to shadowing outer local variables.
# :taint :: Ignore warnings related to taint and related methods and C-API functions.
# :unused_var :: Ignore warnings for unused variables.
# :useless_operator :: Ignore warnings when using operators such as == and > when the
# result is not used.
# :void_context :: Ignore warnings for :: to reference constants when the result is not
# used (often used to trigger autoload).
#
# Examples:
#
# # Ignore all uninitialized instance variable warnings
# Warning.ignore(/instance variable @\w+ not initialized/)
#
# # Ignore all uninitialized instance variable warnings in current file
# Warning.ignore(/instance variable @\w+ not initialized/, __FILE__)
#
# # Ignore all uninitialized instance variable warnings in current file
# Warning.ignore(:missing_ivar, __FILE__)
#
# # Ignore all uninitialized instance variable and method redefined warnings in current file
# Warning.ignore([:missing_ivar, :method_redefined], __FILE__)
def ignore(regexp, path='')
unless regexp = convert_regexp(regexp)
raise TypeError, "first argument to Warning.ignore should be Regexp, Symbol, or Array of Symbols, got #{regexp.inspect}"
end
synchronize do
@ignore << [path, regexp]
end
nil
end
# Handle all warnings starting with the given path, instead of
# the default behavior of printing them to $stderr. Examples:
#
# # Write warning to LOGGER at level warning
# Warning.process do |warning|
# LOGGER.warning(warning)
# end
#
# # Write warnings in the current file to LOGGER at level error level
# Warning.process(__FILE__) do |warning|
# LOGGER.error(warning)
# end
#
# The block can return one of the following symbols:
#
# :default :: Take the default action (call super, printing to $stderr).
# :backtrace :: Take the default action (call super, printing to $stderr),
# and also print the backtrace.
# :raise :: Raise a RuntimeError with the warning as the message.
#
# If the block returns anything else, it is assumed the block completely handled
# the warning and takes no other action.
#
# Instead of passing a block, you can pass a hash of actions to take for specific
# warnings, using regexp as keys and a callable objects as values:
#
# Warning.process(__FILE__,
# /instance variable @\w+ not initialized/ => proc do |warning|
# LOGGER.warning(warning)
# end,
# /global variable [`']\$\w+' not initialized/ => proc do |warning|
# LOGGER.error(warning)
# end
# )
#
# Instead of passing a regexp as a key, you can pass a symbol that is recognized
# by Warning.ignore. Instead of passing a callable object as a value, you can
# pass a symbol, which will be treated as a callable object that returns that symbol:
#
# Warning.process(__FILE__, :missing_ivar=>:backtrace, :keyword_separation=>:raise)
def process(path='', actions=nil, &block)
unless path.is_a?(String)
raise ArgumentError, "path must be a String (given an instance of #{path.class})"
end
if block
if actions
raise ArgumentError, "cannot pass both actions and block to Warning.process"
end
elsif actions
block = {}
actions.each do |regexp, value|
unless regexp = convert_regexp(regexp)
raise TypeError, "action provided to Warning.process should be Regexp, Symbol, or Array of Symbols, got #{regexp.inspect}"
end
block[regexp] = ACTION_PROC_MAP[value] || value
end
else
raise ArgumentError, "must pass either actions or block to Warning.process"
end
synchronize do
@process << [path, block]
@process.sort_by!(&:first)
@process.reverse!
end
nil
end
if RUBY_VERSION >= '3.0'
method_args = ', category: nil'
super_ = "category ? super : super(str)"
# :nocov:
else
super_ = "super"
# :nocov:
end
class_eval(<<-END, __FILE__, __LINE__+1)
def warn(str#{method_args})
synchronize{@ignore.dup}.each do |path, regexp|
if str.start_with?(path) && regexp.match?(str)
return
end
end
if @dedup
if synchronize{@dedup[str]}
return
end
synchronize{@dedup[str] = true}
end
action = catch(:action) do
synchronize{@process.dup}.each do |path, block|
if str.start_with?(path)
if block.is_a?(Hash)
block.each do |regexp, blk|
if regexp.match?(str)
throw :action, blk.call(str)
end
end
else
throw :action, block.call(str)
end
end
end
:default
end
case action
when :default
#{super_}
when :backtrace
#{super_}
$stderr.puts caller
when :raise
raise str
else
# nothing
end
nil
end
END
private
# Convert the given Regexp, Symbol, or Array of Symbols into a Regexp.
def convert_regexp(regexp)
case regexp
when Regexp
regexp
when Symbol
IGNORE_MAP.fetch(regexp)
when Array
Regexp.union(regexp.map{|re| IGNORE_MAP.fetch(re)})
else
# nothing
end
end
def synchronize(&block)
@monitor.synchronize(&block)
end
end
@ignore = []
@process = []
@dedup = false
@monitor = Monitor.new
extend Processor
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho.rb | # frozen_string_literal: true
require "open3"
require_relative "macho/utils"
require_relative "macho/structure"
require_relative "macho/view"
require_relative "macho/headers"
require_relative "macho/load_commands"
require_relative "macho/sections"
require_relative "macho/macho_file"
require_relative "macho/fat_file"
require_relative "macho/exceptions"
require_relative "macho/tools"
# The primary namespace for ruby-macho.
module MachO
# release version
VERSION = "4.1.0"
# Opens the given filename as a MachOFile or FatFile, depending on its magic.
# @param filename [String] the file being opened
# @return [MachOFile] if the file is a Mach-O
# @return [FatFile] if the file is a Fat file
# @raise [ArgumentError] if the given file does not exist
# @raise [TruncatedFileError] if the file is too small to have a valid header
# @raise [MagicError] if the file's magic is not valid Mach-O magic
def self.open(filename)
raise ArgumentError, "#{filename}: no such file" unless File.file?(filename)
raise TruncatedFileError unless File.stat(filename).size >= 4
magic = File.open(filename, "rb") { |f| f.read(4) }.unpack1("N")
if Utils.fat_magic?(magic)
file = FatFile.new(filename)
elsif Utils.magic?(magic)
file = MachOFile.new(filename)
else
raise MagicError, magic
end
file
end
# Signs the dylib using an ad-hoc identity.
# Necessary after making any changes to a dylib, since otherwise
# changing a signed file invalidates its signature.
# @param filename [String] the file being opened
# @return [void]
# @raise [ModificationError] if the operation fails
def self.codesign!(filename)
raise ArgumentError, "codesign binary is not available on Linux" if RUBY_PLATFORM !~ /darwin/
raise ArgumentError, "#{filename}: no such file" unless File.file?(filename)
_, _, status = Open3.capture3("codesign", "--sign", "-", "--force",
"--preserve-metadata=entitlements,requirements,flags,runtime",
filename)
raise CodeSigningError, "#{filename}: signing failed!" unless status.success?
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/sections.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/sections.rb | # frozen_string_literal: true
module MachO
# Classes and constants for parsing sections in Mach-O binaries.
module Sections
# type mask
SECTION_TYPE_MASK = 0x000000ff
# attributes mask
SECTION_ATTRIBUTES_MASK = 0xffffff00
# user settable attributes mask
SECTION_ATTRIBUTES_USR_MASK = 0xff000000
# system settable attributes mask
SECTION_ATTRIBUTES_SYS_MASK = 0x00ffff00
# maximum specifiable section alignment, as a power of 2
# @note see `MAXSECTALIGN` macro in `cctools/misc/lipo.c`
MAX_SECT_ALIGN = 15
# association of section type symbols to values
# @api private
SECTION_TYPES = {
:S_REGULAR => 0x0,
:S_ZEROFILL => 0x1,
:S_CSTRING_LITERALS => 0x2,
:S_4BYTE_LITERALS => 0x3,
:S_8BYTE_LITERALS => 0x4,
:S_LITERAL_POINTERS => 0x5,
:S_NON_LAZY_SYMBOL_POINTERS => 0x6,
:S_LAZY_SYMBOL_POINTERS => 0x7,
:S_SYMBOL_STUBS => 0x8,
:S_MOD_INIT_FUNC_POINTERS => 0x9,
:S_MOD_TERM_FUNC_POINTERS => 0xa,
:S_COALESCED => 0xb,
:S_GB_ZEROFILE => 0xc,
:S_INTERPOSING => 0xd,
:S_16BYTE_LITERALS => 0xe,
:S_DTRACE_DOF => 0xf,
:S_LAZY_DYLIB_SYMBOL_POINTERS => 0x10,
:S_THREAD_LOCAL_REGULAR => 0x11,
:S_THREAD_LOCAL_ZEROFILL => 0x12,
:S_THREAD_LOCAL_VARIABLES => 0x13,
:S_THREAD_LOCAL_VARIABLE_POINTERS => 0x14,
:S_THREAD_LOCAL_INIT_FUNCTION_POINTERS => 0x15,
:S_INIT_FUNC_OFFSETS => 0x16,
}.freeze
# association of section attribute symbols to values
# @api private
SECTION_ATTRIBUTES = {
:S_ATTR_PURE_INSTRUCTIONS => 0x80000000,
:S_ATTR_NO_TOC => 0x40000000,
:S_ATTR_STRIP_STATIC_SYMS => 0x20000000,
:S_ATTR_NO_DEAD_STRIP => 0x10000000,
:S_ATTR_LIVE_SUPPORT => 0x08000000,
:S_ATTR_SELF_MODIFYING_CODE => 0x04000000,
:S_ATTR_DEBUG => 0x02000000,
:S_ATTR_SOME_INSTRUCTIONS => 0x00000400,
:S_ATTR_EXT_RELOC => 0x00000200,
:S_ATTR_LOC_RELOC => 0x00000100,
}.freeze
# association of section flag symbols to values
# @api private
SECTION_FLAGS = {
**SECTION_TYPES,
**SECTION_ATTRIBUTES,
}.freeze
# association of section name symbols to names
# @api private
SECTION_NAMES = {
:SECT_TEXT => "__text",
:SECT_FVMLIB_INIT0 => "__fvmlib_init0",
:SECT_FVMLIB_INIT1 => "__fvmlib_init1",
:SECT_DATA => "__data",
:SECT_BSS => "__bss",
:SECT_COMMON => "__common",
:SECT_OBJC_SYMBOLS => "__symbol_table",
:SECT_OBJC_MODULES => "__module_info",
:SECT_OBJC_STRINGS => "__selector_strs",
:SECT_OBJC_REFS => "__selector_refs",
:SECT_ICON_HEADER => "__header",
:SECT_ICON_TIFF => "__tiff",
}.freeze
# Represents a section of a segment for 32-bit architectures.
class Section < MachOStructure
# @return [String] the name of the section, including null pad bytes
field :sectname, :string, :padding => :null, :size => 16
# @return [String] the name of the segment's section, including null
# pad bytes
field :segname, :string, :padding => :null, :size => 16
# @return [Integer] the memory address of the section
field :addr, :uint32
# @return [Integer] the size, in bytes, of the section
field :size, :uint32
# @return [Integer] the file offset of the section
field :offset, :uint32
# @return [Integer] the section alignment (power of 2) of the section
field :align, :uint32
# @return [Integer] the file offset of the section's relocation entries
field :reloff, :uint32
# @return [Integer] the number of relocation entries
field :nreloc, :uint32
# @return [Integer] flags for type and attributes of the section
field :flags, :uint32
# @return [void] reserved (for offset or index)
field :reserved1, :uint32
# @return [void] reserved (for count or sizeof)
field :reserved2, :uint32
# @return [String] the section's name
def section_name
sectname
end
# @return [String] the parent segment's name
def segment_name
segname
end
# @return [Boolean] whether the section is empty (i.e, {size} is 0)
def empty?
size.zero?
end
# @return [Integer] the raw numeric type of this section
def type
flags & SECTION_TYPE_MASK
end
# @example
# puts "this section is regular" if sect.type?(:S_REGULAR)
# @param type_sym [Symbol] a section type symbol
# @return [Boolean] whether this section is of the given type
def type?(type_sym)
type == SECTION_TYPES[type_sym]
end
# @return [Integer] the raw numeric attributes of this section
def attributes
flags & SECTION_ATTRIBUTES_MASK
end
# @example
# puts "pure instructions" if sect.attribute?(:S_ATTR_PURE_INSTRUCTIONS)
# @param attr_sym [Symbol] a section attribute symbol
# @return [Boolean] whether this section is of the given type
def attribute?(attr_sym)
!!(attributes & SECTION_ATTRIBUTES[attr_sym])
end
# @deprecated Use {#type?} or {#attribute?} instead.
# @example
# puts "this section is regular" if sect.flag?(:S_REGULAR)
# @param flag [Symbol] a section flag symbol
# @return [Boolean] whether the flag is present in the section's {flags}
def flag?(flag)
flag = SECTION_FLAGS[flag]
return false if flag.nil?
flags & flag == flag
end
# @return [Hash] a hash representation of this {Section}
def to_h
{
"sectname" => sectname,
"segname" => segname,
"addr" => addr,
"size" => size,
"offset" => offset,
"align" => align,
"reloff" => reloff,
"nreloc" => nreloc,
"flags" => flags,
"reserved1" => reserved1,
"reserved2" => reserved2,
}.merge super
end
end
# Represents a section of a segment for 64-bit architectures.
class Section64 < Section
# @return [Integer] the memory address of the section
field :addr, :uint64
# @return [Integer] the size, in bytes, of the section
field :size, :uint64
# @return [void] reserved
field :reserved3, :uint32
# @return [Hash] a hash representation of this {Section64}
def to_h
{
"reserved3" => reserved3,
}.merge super
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/macho_file.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/macho_file.rb | # frozen_string_literal: true
require "forwardable"
module MachO
# Represents a Mach-O file, which contains a header and load commands
# as well as binary executable instructions. Mach-O binaries are
# architecture specific.
# @see https://en.wikipedia.org/wiki/Mach-O
# @see FatFile
class MachOFile
extend Forwardable
# @return [String, nil] the filename loaded from, or nil if loaded from a binary
# string
attr_accessor :filename
# @return [Hash] any parser options that the instance was created with
attr_reader :options
# @return [Symbol] the endianness of the file, :big or :little
attr_reader :endianness
# @return [Headers::MachHeader] if the Mach-O is 32-bit
# @return [Headers::MachHeader64] if the Mach-O is 64-bit
attr_reader :header
# @return [Array<LoadCommands::LoadCommand>] an array of the file's load
# commands
# @note load commands are provided in order of ascending offset.
attr_reader :load_commands
# Creates a new instance from a binary string.
# @param bin [String] a binary string containing raw Mach-O data
# @param opts [Hash] options to control the parser with
# @option opts [Boolean] :permissive whether to ignore unknown load commands
# @option opts [Boolean] :decompress whether to decompress, if capable
# @return [MachOFile] a new MachOFile
# @note The `:decompress` option relies on non-default dependencies. Compression
# is only used in niche Mach-Os, so leaving this disabled is a reasonable default for
# virtually all normal uses.
def self.new_from_bin(bin, **opts)
instance = allocate
instance.initialize_from_bin(bin, opts)
instance
end
# Creates a new instance from data read from the given filename.
# @param filename [String] the Mach-O file to load from
# @param opts [Hash] options to control the parser with
# @option opts [Boolean] :permissive whether to ignore unknown load commands
# @option opts [Boolean] :decompress whether to decompress, if capable
# @raise [ArgumentError] if the given file does not exist
# @note The `:decompress` option relies on non-default dependencies. Compression
# is only used in niche Mach-Os, so leaving this disabled is a reasonable default for
# virtually all normal uses.
def initialize(filename, **opts)
raise ArgumentError, "#{filename}: no such file" unless File.file?(filename)
@filename = filename
@options = opts
@raw_data = File.binread(@filename)
populate_fields
end
# Initializes a new MachOFile instance from a binary string with the given options.
# @see MachO::MachOFile.new_from_bin
# @api private
def initialize_from_bin(bin, opts)
@filename = nil
@options = opts
@raw_data = bin
populate_fields
end
# The file's raw Mach-O data.
# @return [String] the raw Mach-O data
def serialize
@raw_data
end
# @!method magic
# @return (see MachO::Headers::MachHeader#magic)
# @!method ncmds
# @return (see MachO::Headers::MachHeader#ncmds)
# @!method sizeofcmds
# @return (see MachO::Headers::MachHeader#sizeofcmds)
# @!method flags
# @return (see MachO::Headers::MachHeader#flags)
# @!method object?
# @return (see MachO::Headers::MachHeader#object?)
# @!method executable?
# @return (see MachO::Headers::MachHeader#executable?)
# @!method fvmlib?
# @return (see MachO::Headers::MachHeader#fvmlib?)
# @!method core?
# @return (see MachO::Headers::MachHeader#core?)
# @!method preload?
# @return (see MachO::Headers::MachHeader#preload?)
# @!method dylib?
# @return (see MachO::Headers::MachHeader#dylib?)
# @!method dylinker?
# @return (see MachO::Headers::MachHeader#dylinker?)
# @!method bundle?
# @return (see MachO::Headers::MachHeader#bundle?)
# @!method dsym?
# @return (see MachO::Headers::MachHeader#dsym?)
# @!method kext?
# @return (see MachO::Headers::MachHeader#kext?)
# @!method magic32?
# @return (see MachO::Headers::MachHeader#magic32?)
# @!method magic64?
# @return (see MachO::Headers::MachHeader#magic64?)
# @!method alignment
# @return (see MachO::Headers::MachHeader#alignment)
def_delegators :header, :magic, :ncmds, :sizeofcmds, :flags, :object?,
:executable?, :fvmlib?, :core?, :preload?, :dylib?,
:dylinker?, :bundle?, :dsym?, :kext?, :magic32?, :magic64?,
:alignment
# @return [String] a string representation of the file's magic number
def magic_string
Headers::MH_MAGICS[magic]
end
# @return [Symbol] a string representation of the Mach-O's filetype
def filetype
Headers::MH_FILETYPES[header.filetype]
end
# @return [Symbol] a symbol representation of the Mach-O's CPU type
def cputype
Headers::CPU_TYPES[header.cputype]
end
# @return [Symbol] a symbol representation of the Mach-O's CPU subtype
def cpusubtype
Headers::CPU_SUBTYPES[header.cputype][header.cpusubtype]
end
# All load commands of a given name.
# @example
# file.command("LC_LOAD_DYLIB")
# file[:LC_LOAD_DYLIB]
# @param [String, Symbol] name the load command ID
# @return [Array<LoadCommands::LoadCommand>] an array of load commands
# corresponding to `name`
def command(name)
load_commands.select { |lc| lc.type == name.to_sym }
end
alias [] command
# Inserts a load command at the given offset.
# @param offset [Integer] the offset to insert at
# @param lc [LoadCommands::LoadCommand] the load command to insert
# @param options [Hash]
# @option options [Boolean] :repopulate (true) whether or not to repopulate
# the instance fields
# @raise [OffsetInsertionError] if the offset is not in the load command region
# @raise [HeaderPadError] if the new command exceeds the header pad buffer
# @note Calling this method with an arbitrary offset in the load command region
# **will leave the object in an inconsistent state**.
def insert_command(offset, lc, options = {})
context = LoadCommands::LoadCommand::SerializationContext.context_for(self)
cmd_raw = lc.serialize(context)
fileoff = offset + cmd_raw.bytesize
raise OffsetInsertionError, offset if offset < header.class.bytesize || fileoff > low_fileoff
new_sizeofcmds = sizeofcmds + cmd_raw.bytesize
raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff
# update Mach-O header fields to account for inserted load command
update_ncmds(ncmds + 1)
update_sizeofcmds(new_sizeofcmds)
@raw_data.insert(offset, cmd_raw)
@raw_data.slice!(header.class.bytesize + new_sizeofcmds, cmd_raw.bytesize)
populate_fields if options.fetch(:repopulate, true)
end
# Replace a load command with another command in the Mach-O, preserving location.
# @param old_lc [LoadCommands::LoadCommand] the load command being replaced
# @param new_lc [LoadCommands::LoadCommand] the load command being added
# @return [void]
# @raise [HeaderPadError] if the new command exceeds the header pad buffer
# @see #insert_command
# @note This is public, but methods like {#dylib_id=} should be preferred.
def replace_command(old_lc, new_lc)
context = LoadCommands::LoadCommand::SerializationContext.context_for(self)
cmd_raw = new_lc.serialize(context)
new_sizeofcmds = sizeofcmds + cmd_raw.bytesize - old_lc.cmdsize
raise HeaderPadError, @filename if header.class.bytesize + new_sizeofcmds > low_fileoff
delete_command(old_lc)
insert_command(old_lc.view.offset, new_lc)
end
# Appends a new load command to the Mach-O.
# @param lc [LoadCommands::LoadCommand] the load command being added
# @param options [Hash]
# @option f [Boolean] :repopulate (true) whether or not to repopulate
# the instance fields
# @return [void]
# @see #insert_command
# @note This is public, but methods like {#add_rpath} should be preferred.
# Setting `repopulate` to false **will leave the instance in an
# inconsistent state** unless {#populate_fields} is called **immediately**
# afterwards.
def add_command(lc, options = {})
insert_command(header.class.bytesize + sizeofcmds, lc, options)
end
# Delete a load command from the Mach-O.
# @param lc [LoadCommands::LoadCommand] the load command being deleted
# @param options [Hash]
# @option options [Boolean] :repopulate (true) whether or not to repopulate
# the instance fields
# @return [void]
# @note This is public, but methods like {#delete_rpath} should be preferred.
# Setting `repopulate` to false **will leave the instance in an
# inconsistent state** unless {#populate_fields} is called **immediately**
# afterwards.
def delete_command(lc, options = {})
@raw_data.slice!(lc.view.offset, lc.cmdsize)
# update Mach-O header fields to account for deleted load command
update_ncmds(ncmds - 1)
update_sizeofcmds(sizeofcmds - lc.cmdsize)
# pad the space after the load commands to preserve offsets
@raw_data.insert(header.class.bytesize + sizeofcmds - lc.cmdsize, Utils.nullpad(lc.cmdsize))
populate_fields if options.fetch(:repopulate, true)
end
# Populate the instance's fields with the raw Mach-O data.
# @return [void]
# @note This method is public, but should (almost) never need to be called.
# The exception to this rule is when methods like {#add_command} and
# {#delete_command} have been called with `repopulate = false`.
def populate_fields
@header = populate_mach_header
@load_commands = populate_load_commands
end
# All load commands responsible for loading dylibs.
# @return [Array<LoadCommands::DylibCommand>] an array of DylibCommands
def dylib_load_commands
load_commands.select { |lc| LoadCommands::DYLIB_LOAD_COMMANDS.include?(lc.type) }
end
# All segment load commands in the Mach-O.
# @return [Array<LoadCommands::SegmentCommand>] if the Mach-O is 32-bit
# @return [Array<LoadCommands::SegmentCommand64>] if the Mach-O is 64-bit
def segments
if magic32?
command(:LC_SEGMENT)
else
command(:LC_SEGMENT_64)
end
end
# The segment alignment for the Mach-O. Guesses conservatively.
# @return [Integer] the alignment, as a power of 2
# @note This is **not** the same as {#alignment}!
# @note See `get_align` and `get_align_64` in `cctools/misc/lipo.c`
def segment_alignment
# special cases: 12 for x86/64/PPC/PP64, 14 for ARM/ARM64
return 12 if %i[i386 x86_64 ppc ppc64].include?(cputype)
return 14 if %i[arm arm64].include?(cputype)
cur_align = Sections::MAX_SECT_ALIGN
segments.each do |segment|
if filetype == :object
# start with the smallest alignment, and work our way up
align = magic32? ? 2 : 3
segment.sections.each do |section|
align = section.align unless section.align <= align
end
else
align = segment.guess_align
end
cur_align = align if align < cur_align
end
cur_align
end
# The Mach-O's dylib ID, or `nil` if not a dylib.
# @example
# file.dylib_id # => 'libBar.dylib'
# @return [String, nil] the Mach-O's dylib ID
def dylib_id
return unless dylib?
dylib_id_cmd = command(:LC_ID_DYLIB).first
dylib_id_cmd.name.to_s
end
# Changes the Mach-O's dylib ID to `new_id`. Does nothing if not a dylib.
# @example
# file.change_dylib_id("libFoo.dylib")
# @param new_id [String] the dylib's new ID
# @param _options [Hash]
# @return [void]
# @raise [ArgumentError] if `new_id` is not a String
# @note `_options` is currently unused and is provided for signature
# compatibility with {MachO::FatFile#change_dylib_id}
def change_dylib_id(new_id, _options = {})
raise ArgumentError, "new ID must be a String" unless new_id.is_a?(String)
return unless dylib?
old_lc = command(:LC_ID_DYLIB).first
raise DylibIdMissingError unless old_lc
new_lc = LoadCommands::LoadCommand.create(:LC_ID_DYLIB, new_id,
old_lc.timestamp,
old_lc.current_version,
old_lc.compatibility_version)
replace_command(old_lc, new_lc)
end
alias dylib_id= change_dylib_id
# All shared libraries linked to the Mach-O.
# @return [Array<String>] an array of all shared libraries
def linked_dylibs
# Some linkers produce multiple `LC_LOAD_DYLIB` load commands for the same
# library, but at this point we're really only interested in a list of
# unique libraries this Mach-O file links to, thus: `uniq`. (This is also
# for consistency with `FatFile` that merges this list across all archs.)
dylib_load_commands.map(&:name).map(&:to_s).uniq
end
# Changes the shared library `old_name` to `new_name`
# @example
# file.change_install_name("abc.dylib", "def.dylib")
# @param old_name [String] the shared library's old name
# @param new_name [String] the shared library's new name
# @param _options [Hash]
# @return [void]
# @raise [DylibUnknownError] if no shared library has the old name
# @note `_options` is currently unused and is provided for signature
# compatibility with {MachO::FatFile#change_install_name}
def change_install_name(old_name, new_name, _options = {})
old_lc = dylib_load_commands.find { |d| d.name.to_s == old_name }
raise DylibUnknownError, old_name if old_lc.nil?
new_lc = LoadCommands::LoadCommand.create(old_lc.type, new_name,
old_lc.timestamp,
old_lc.current_version,
old_lc.compatibility_version)
replace_command(old_lc, new_lc)
end
alias change_dylib change_install_name
# All runtime paths searched by the dynamic linker for the Mach-O.
# @return [Array<String>] an array of all runtime paths
def rpaths
command(:LC_RPATH).map(&:path).map(&:to_s)
end
# Changes the runtime path `old_path` to `new_path`
# @example
# file.change_rpath("/usr/lib", "/usr/local/lib")
# @param old_path [String] the old runtime path
# @param new_path [String] the new runtime path
# @param options [Hash]
# @option options [Boolean] :uniq (false) if true, change duplicate
# rpaths simultaneously.
# @return [void]
# @raise [RpathUnknownError] if no such old runtime path exists
def change_rpath(old_path, new_path, options = {})
old_lc = command(:LC_RPATH).find { |r| r.path.to_s == old_path }
raise RpathUnknownError, old_path if old_lc.nil?
new_lc = LoadCommands::LoadCommand.create(:LC_RPATH, new_path)
delete_rpath(old_path, options)
insert_command(old_lc.view.offset, new_lc)
end
# Add the given runtime path to the Mach-O.
# @example
# file.rpaths # => ["/lib"]
# file.add_rpath("/usr/lib")
# file.rpaths # => ["/lib", "/usr/lib"]
# @param path [String] the new runtime path
# @param _options [Hash]
# @return [void]
# @raise [RpathExistsError] if the runtime path already exists
# @note `_options` is currently unused and is provided for signature
# compatibility with {MachO::FatFile#add_rpath}
def add_rpath(path, _options = {})
raise RpathExistsError, path if rpaths.include?(path)
rpath_cmd = LoadCommands::LoadCommand.create(:LC_RPATH, path)
add_command(rpath_cmd)
end
# Delete the given runtime path from the Mach-O.
# @example
# file1.rpaths # => ["/lib", "/usr/lib", "/lib"]
# file1.delete_rpath("/lib")
# file1.rpaths # => ["/usr/lib", "/lib"]
# file2.rpaths # => ["foo", "foo"]
# file2.delete_rpath("foo", :uniq => true)
# file2.rpaths # => []
# file3.rpaths # => ["foo", "bar", "foo"]
# file3.delete_rpath("foo", :last => true)
# file3.rpaths # => ["foo", "bar"]
# @param path [String] the runtime path to delete
# @param options [Hash]
# @option options [Boolean] :uniq (false) if true, also delete
# duplicates of the requested path. If false, delete the first
# instance (by offset) of the requested path, unless :last is true.
# Incompatible with :last.
# @option options [Boolean] :last (false) if true, delete the last
# instance (by offset) of the requested path. Incompatible with :uniq.
# @return void
# @raise [RpathUnknownError] if no such runtime path exists
# @raise [ArgumentError] if both :uniq and :last are true
def delete_rpath(path, options = {})
uniq = options.fetch(:uniq, false)
last = options.fetch(:last, false)
raise ArgumentError, "Cannot set both :uniq and :last to true" if uniq && last
search_method = uniq || last ? :select : :find
rpath_cmds = command(:LC_RPATH).public_send(search_method) { |r| r.path.to_s == path }
rpath_cmds = rpath_cmds.last if last
# Cast rpath_cmds into an Array so we can handle the uniq and non-uniq cases the same way
rpath_cmds = Array(rpath_cmds)
raise RpathUnknownError, path if rpath_cmds.empty?
# delete the commands in reverse order, offset descending.
rpath_cmds.reverse_each { |cmd| delete_command(cmd) }
end
# Write all Mach-O data to the given filename.
# @param filename [String] the file to write to
# @return [void]
def write(filename)
File.binwrite(filename, @raw_data)
end
# Write all Mach-O data to the file used to initialize the instance.
# @return [void]
# @raise [MachOError] if the instance was initialized without a file
# @note Overwrites all data in the file!
def write!
raise MachOError, "no initial file to write to" if @filename.nil?
File.binwrite(@filename, @raw_data)
end
# @return [Hash] a hash representation of this {MachOFile}
def to_h
{
"header" => header.to_h,
"load_commands" => load_commands.map(&:to_h),
}
end
private
# The file's Mach-O header structure.
# @return [Headers::MachHeader] if the Mach-O is 32-bit
# @return [Headers::MachHeader64] if the Mach-O is 64-bit
# @raise [TruncatedFileError] if the file is too small to have a valid header
# @api private
def populate_mach_header
# the smallest Mach-O header is 28 bytes
raise TruncatedFileError if @raw_data.size < 28
magic = @raw_data[0..3].unpack1("N")
populate_prelinked_kernel_header if Utils.compressed_magic?(magic)
magic = populate_and_check_magic
mh_klass = Utils.magic32?(magic) ? Headers::MachHeader : Headers::MachHeader64
mh = mh_klass.new_from_bin(endianness, @raw_data[0, mh_klass.bytesize])
check_cputype(mh.cputype)
check_cpusubtype(mh.cputype, mh.cpusubtype)
check_filetype(mh.filetype)
mh
end
# Read a compressed Mach-O header and check its validity, as well as whether we're able
# to parse it.
# @return [void]
# @raise [CompressedMachOError] if we weren't asked to perform decompression
# @raise [DecompressionError] if decompression is impossible or fails
# @api private
def populate_prelinked_kernel_header
raise CompressedMachOError unless options.fetch(:decompress, false)
@plh = Headers::PrelinkedKernelHeader.new_from_bin :big, @raw_data[0, Headers::PrelinkedKernelHeader.bytesize]
raise DecompressionError, "unsupported compression type: LZSS" if @plh.lzss?
raise DecompressionError, "unknown compression type: 0x#{plh.compress_type.to_s 16}" unless @plh.lzvn?
decompress_macho_lzvn
end
# Attempt to decompress a Mach-O file from the data specified in a prelinked kernel header.
# @return [void]
# @raise [DecompressionError] if decompression is impossible or fails
# @api private
# @note This method rewrites the internal state of {MachOFile} to pretend as if it was never
# compressed to begin with, allowing all other APIs to transparently act on compressed Mach-Os.
def decompress_macho_lzvn
begin
require "lzfse"
rescue LoadError
raise DecompressionError, "LZVN required but the optional 'lzfse' gem is not installed"
end
# From this point onwards, the internal buffer of this MachOFile refers to the decompressed
# contents specified by the prelinked kernel header.
begin
@raw_data = LZFSE.lzvn_decompress @raw_data.slice(Headers::PrelinkedKernelHeader.bytesize, @plh.compressed_size)
# Sanity checks.
raise DecompressionError if @raw_data.size != @plh.uncompressed_size
# TODO: check the adler32 CRC in @plh
rescue LZFSE::DecodeError
raise DecompressionError, "LZVN decompression failed"
end
end
# Read just the file's magic number and check its validity.
# @return [Integer] the magic
# @raise [MagicError] if the magic is not valid Mach-O magic
# @raise [FatBinaryError] if the magic is for a Fat file
# @api private
def populate_and_check_magic
magic = @raw_data[0..3].unpack1("N")
raise MagicError, magic unless Utils.magic?(magic)
raise FatBinaryError if Utils.fat_magic?(magic)
@endianness = Utils.little_magic?(magic) ? :little : :big
magic
end
# Check the file's CPU type.
# @param cputype [Integer] the CPU type
# @raise [CPUTypeError] if the CPU type is unknown
# @api private
def check_cputype(cputype)
raise CPUTypeError, cputype unless Headers::CPU_TYPES.key?(cputype)
end
# Check the file's CPU type/subtype pair.
# @param cpusubtype [Integer] the CPU subtype
# @raise [CPUSubtypeError] if the CPU sub-type is unknown
# @api private
def check_cpusubtype(cputype, cpusubtype)
# Only check sub-type w/o capability bits (see `populate_mach_header`).
raise CPUSubtypeError.new(cputype, cpusubtype) unless Headers::CPU_SUBTYPES[cputype].key?(cpusubtype)
end
# Check the file's type.
# @param filetype [Integer] the file type
# @raise [FiletypeError] if the file type is unknown
# @api private
def check_filetype(filetype)
raise FiletypeError, filetype unless Headers::MH_FILETYPES.key?(filetype)
end
# All load commands in the file.
# @return [Array<LoadCommands::LoadCommand>] an array of load commands
# @raise [LoadCommandError] if an unknown load command is encountered
# @api private
def populate_load_commands
permissive = options.fetch(:permissive, false)
offset = header.class.bytesize
load_commands = []
header.ncmds.times do
fmt = Utils.specialize_format("L=", endianness)
cmd = @raw_data.slice(offset, 4).unpack1(fmt)
cmd_sym = LoadCommands::LOAD_COMMANDS[cmd]
raise LoadCommandError, cmd unless cmd_sym || permissive
# If we're here, then either cmd_sym represents a valid load
# command *or* we're in permissive mode.
klass = if (klass_str = LoadCommands::LC_STRUCTURES[cmd_sym])
LoadCommands.const_get klass_str
else
LoadCommands::LoadCommand
end
view = MachOView.new(self, @raw_data, endianness, offset)
command = klass.new_from_bin(view)
load_commands << command
offset += command.cmdsize
end
load_commands
end
# The low file offset (offset to first section data).
# @return [Integer] the offset
# @api private
def low_fileoff
offset = @raw_data.size
segments.each do |seg|
seg.sections.each do |sect|
next if sect.empty?
next if sect.type?(:S_ZEROFILL)
next if sect.type?(:S_THREAD_LOCAL_ZEROFILL)
next unless sect.offset < offset
offset = sect.offset
end
end
offset
end
# Updates the number of load commands in the raw data.
# @param ncmds [Integer] the new number of commands
# @return [void]
# @api private
def update_ncmds(ncmds)
fmt = Utils.specialize_format("L=", endianness)
ncmds_raw = [ncmds].pack(fmt)
@raw_data[16..19] = ncmds_raw
end
# Updates the size of all load commands in the raw data.
# @param size [Integer] the new size, in bytes
# @return [void]
# @api private
def update_sizeofcmds(size)
fmt = Utils.specialize_format("L=", endianness)
size_raw = [size].pack(fmt)
@raw_data[20..23] = size_raw
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/tools.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/tools.rb | # frozen_string_literal: true
module MachO
# A collection of convenient methods for common operations on Mach-O and Fat
# binaries.
module Tools
# @param filename [String] the Mach-O or Fat binary being read
# @return [Array<String>] an array of all dylibs linked to the binary
def self.dylibs(filename)
file = MachO.open(filename)
file.linked_dylibs
end
# Changes the dylib ID of a Mach-O or Fat binary, overwriting the source
# file.
# @param filename [String] the Mach-O or Fat binary being modified
# @param new_id [String] the new dylib ID for the binary
# @param options [Hash]
# @option options [Boolean] :strict (true) whether or not to fail loudly
# with an exception if the change cannot be performed
# @return [void]
def self.change_dylib_id(filename, new_id, options = {})
file = MachO.open(filename)
file.change_dylib_id(new_id, options)
file.write!
end
# Changes a shared library install name in a Mach-O or Fat binary,
# overwriting the source file.
# @param filename [String] the Mach-O or Fat binary being modified
# @param old_name [String] the old shared library name
# @param new_name [String] the new shared library name
# @param options [Hash]
# @option options [Boolean] :strict (true) whether or not to fail loudly
# with an exception if the change cannot be performed
# @return [void]
def self.change_install_name(filename, old_name, new_name, options = {})
file = MachO.open(filename)
file.change_install_name(old_name, new_name, options)
file.write!
end
# Changes a runtime path in a Mach-O or Fat binary, overwriting the source
# file.
# @param filename [String] the Mach-O or Fat binary being modified
# @param old_path [String] the old runtime path
# @param new_path [String] the new runtime path
# @param options [Hash]
# @option options [Boolean] :strict (true) whether or not to fail loudly
# with an exception if the change cannot be performed
# @option options [Boolean] :uniq (false) whether or not to change duplicate
# rpaths simultaneously
# @return [void]
def self.change_rpath(filename, old_path, new_path, options = {})
file = MachO.open(filename)
file.change_rpath(old_path, new_path, options)
file.write!
end
# Add a runtime path to a Mach-O or Fat binary, overwriting the source file.
# @param filename [String] the Mach-O or Fat binary being modified
# @param new_path [String] the new runtime path
# @param options [Hash]
# @option options [Boolean] :strict (true) whether or not to fail loudly
# with an exception if the change cannot be performed
# @return [void]
def self.add_rpath(filename, new_path, options = {})
file = MachO.open(filename)
file.add_rpath(new_path, options)
file.write!
end
# Delete a runtime path from a Mach-O or Fat binary, overwriting the source
# file.
# @param filename [String] the Mach-O or Fat binary being modified
# @param old_path [String] the old runtime path
# @param options [Hash]
# @option options [Boolean] :strict (true) whether or not to fail loudly
# with an exception if the change cannot be performed
# @option options [Boolean] :uniq (false) whether or not to delete duplicate
# rpaths simultaneously
# @return [void]
def self.delete_rpath(filename, old_path, options = {})
file = MachO.open(filename)
file.delete_rpath(old_path, options)
file.write!
end
# Merge multiple Mach-Os into one universal (Fat) binary.
# @param filename [String] the fat binary to create
# @param files [Array<String>] the files to merge
# @param fat64 [Boolean] whether to use {Headers::FatArch64}s to represent each slice
# @return [void]
def self.merge_machos(filename, *files, fat64: false)
machos = files.map do |file|
macho = MachO.open(file)
case macho
when MachO::MachOFile
macho
else
macho.machos
end
end.flatten
fat_macho = MachO::FatFile.new_from_machos(*machos, :fat64 => fat64)
fat_macho.write(filename)
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/exceptions.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/exceptions.rb | # frozen_string_literal: true
module MachO
# A generic Mach-O error in execution.
class MachOError < RuntimeError
end
# Raised when a Mach-O file modification fails.
class ModificationError < MachOError
end
# Raised when codesigning fails. Certain environments
# may want to rescue this to treat it as non-fatal.
class CodeSigningError < MachOError
end
# Raised when a Mach-O file modification fails but can be recovered when
# operating on multiple Mach-O slices of a fat binary in non-strict mode.
class RecoverableModificationError < ModificationError
# @return [Integer, nil] The index of the Mach-O slice of a fat binary for
# which modification failed or `nil` if not a fat binary. This is used to
# make the error message more useful.
attr_accessor :macho_slice
# @return [String] The exception message.
def to_s
s = super.to_s
s = "While modifying Mach-O slice #{@macho_slice}: #{s}" if @macho_slice
s
end
end
# Raised when a file is not a Mach-O.
class NotAMachOError < MachOError
end
# Raised when a file is too short to be a valid Mach-O file.
class TruncatedFileError < NotAMachOError
def initialize
super "File is too short to be a valid Mach-O"
end
end
# Raised when a file's magic bytes are not valid Mach-O magic.
class MagicError < NotAMachOError
# @param num [Integer] the unknown number
def initialize(magic)
super "Unrecognized Mach-O magic: 0x%02<magic>x" % { :magic => magic }
end
end
# Raised when a file is a Java classfile instead of a fat Mach-O.
class JavaClassFileError < NotAMachOError
def initialize
super "File is a Java class file"
end
end
# Raised when a a fat Mach-O file has zero architectures
class ZeroArchitectureError < NotAMachOError
def initialize
super "Fat file has zero internal architectures"
end
end
# Raised when there is a mismatch between the fat arch
# and internal slice cputype or cpusubtype.
class CPUTypeMismatchError < NotAMachOError
def initialize(fat_cputype, fat_cpusubtype, macho_cputype, macho_cpusubtype)
# @param cputype_fat [Integer] the CPU type in the fat header
# @param cpusubtype_fat [Integer] the CPU subtype in the fat header
# @param cputype_macho [Integer] the CPU type in the macho header
# @param cpusubtype_macho [Integer] the CPU subtype in the macho header
super ("Mismatch between cputypes >> 0x%08<fat_cputype>x and 0x%08<macho_cputype>x\n" \
"and/or cpusubtypes >> 0x%08<fat_cpusubtype>x and 0x%08<macho_cpusubtype>x" %
{ :fat_cputype => fat_cputype, :macho_cputype => macho_cputype,
:fat_cpusubtype => fat_cpusubtype, :macho_cpusubtype => macho_cpusubtype })
end
end
# Raised when a fat binary is loaded with MachOFile.
class FatBinaryError < MachOError
def initialize
super "Fat binaries must be loaded with MachO::FatFile"
end
end
# Raised when a Mach-O is loaded with FatFile.
class MachOBinaryError < MachOError
def initialize
super "Normal binaries must be loaded with MachO::MachOFile"
end
end
# Raised when the CPU type is unknown.
class CPUTypeError < MachOError
# @param cputype [Integer] the unknown CPU type
def initialize(cputype)
super "Unrecognized CPU type: 0x%08<cputype>x" % { :cputype => cputype }
end
end
# Raised when the CPU type/sub-type pair is unknown.
class CPUSubtypeError < MachOError
# @param cputype [Integer] the CPU type of the unknown pair
# @param cpusubtype [Integer] the CPU sub-type of the unknown pair
def initialize(cputype, cpusubtype)
super "Unrecognized CPU sub-type: 0x%08<cpusubtype>x " \
"(for CPU type: 0x%08<cputype>x" % { :cputype => cputype, :cpusubtype => cpusubtype }
end
end
# Raised when a mach-o file's filetype field is unknown.
class FiletypeError < MachOError
# @param num [Integer] the unknown number
def initialize(num)
super "Unrecognized Mach-O filetype code: 0x%02<num>x" % { :num => num }
end
end
# Raised when an unknown load command is encountered.
class LoadCommandError < MachOError
# @param num [Integer] the unknown number
def initialize(num)
super "Unrecognized Mach-O load command: 0x%02<num>x" % { :num => num }
end
end
# Raised when a load command can't be created manually.
class LoadCommandNotCreatableError < MachOError
# @param cmd_sym [Symbol] the uncreatable load command's symbol
def initialize(cmd_sym)
super "Load commands of type #{cmd_sym} cannot be created manually"
end
end
# Raised when the number of arguments used to create a load command manually
# is wrong.
class LoadCommandCreationArityError < MachOError
# @param cmd_sym [Symbol] the load command's symbol
# @param expected_arity [Integer] the number of arguments expected
# @param actual_arity [Integer] the number of arguments received
def initialize(cmd_sym, expected_arity, actual_arity)
super "Expected #{expected_arity} arguments for #{cmd_sym} creation, " \
"got #{actual_arity}"
end
end
# Raised when a load command can't be serialized.
class LoadCommandNotSerializableError < MachOError
# @param cmd_sym [Symbol] the load command's symbol
def initialize(cmd_sym)
super "Load commands of type #{cmd_sym} cannot be serialized"
end
end
# Raised when a load command string is malformed in some way.
class LCStrMalformedError < MachOError
# @param lc [MachO::LoadCommand] the load command containing the string
def initialize(lc)
super "Load command #{lc.type} at offset #{lc.view.offset} contains a " \
"malformed string"
end
end
# Raised when a change at an offset is not valid.
class OffsetInsertionError < ModificationError
# @param offset [Integer] the invalid offset
def initialize(offset)
super "Insertion at offset #{offset} is not valid"
end
end
# Raised when load commands are too large to fit in the current file.
class HeaderPadError < ModificationError
# @param filename [String] the filename
def initialize(filename)
super "Updated load commands do not fit in the header of " \
"#{filename}. #{filename} needs to be relinked, possibly with " \
"-headerpad or -headerpad_max_install_names"
end
end
# Raised when attempting to change a dylib name that doesn't exist.
class DylibUnknownError < RecoverableModificationError
# @param dylib [String] the unknown shared library name
def initialize(dylib)
super "No such dylib name: #{dylib}"
end
end
# Raised when a dylib is missing an ID
class DylibIdMissingError < RecoverableModificationError
def initialize
super "Dylib is missing a dylib ID"
end
end
# Raised when attempting to change an rpath that doesn't exist.
class RpathUnknownError < RecoverableModificationError
# @param path [String] the unknown runtime path
def initialize(path)
super "No such runtime path: #{path}"
end
end
# Raised when attempting to add an rpath that already exists.
class RpathExistsError < RecoverableModificationError
# @param path [String] the extant path
def initialize(path)
super "#{path} already exists"
end
end
# Raised whenever unfinished code is called.
class UnimplementedError < MachOError
# @param thing [String] the thing that is unimplemented
def initialize(thing)
super "Unimplemented: #{thing}"
end
end
# Raised when attempting to create a {FatFile} from one or more {MachOFile}s
# whose offsets will not fit within the resulting 32-bit {Headers::FatArch#offset} fields.
class FatArchOffsetOverflowError < MachOError
# @param offset [Integer] the offending offset
def initialize(offset)
super "Offset #{offset} exceeds the 32-bit width of a fat_arch offset. " \
"Consider merging with `fat64: true`"
end
end
# Raised when attempting to parse a compressed Mach-O without explicitly
# requesting decompression.
class CompressedMachOError < MachOError
end
# Raised when attempting to decompress a compressed Mach-O without adequate
# dependencies, or on other decompression errors.
class DecompressionError < MachOError
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/view.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/view.rb | # frozen_string_literal: true
module MachO
# A representation of some unspecified Mach-O data.
class MachOView
# @return [MachOFile] that this view belongs to
attr_reader :macho_file
# @return [String] the raw Mach-O data
attr_reader :raw_data
# @return [Symbol] the endianness of the data (`:big` or `:little`)
attr_reader :endianness
# @return [Integer] the offset of the relevant data (in {#raw_data})
attr_reader :offset
# Creates a new MachOView.
# @param macho_file [MachOFile] the file this view slice is from
# @param raw_data [String] the raw Mach-O data
# @param endianness [Symbol] the endianness of the data
# @param offset [Integer] the offset of the relevant data
def initialize(macho_file, raw_data, endianness, offset)
@macho_file = macho_file
@raw_data = raw_data
@endianness = endianness
@offset = offset
end
# @return [Hash] a hash representation of this {MachOView}.
def to_h
{
"endianness" => endianness,
"offset" => offset,
}
end
def inspect
"#<#{self.class}:0x#{(object_id << 1).to_s(16)} @endianness=#{@endianness.inspect}, @offset=#{@offset.inspect}, length=#{@raw_data.length}>"
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/utils.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/utils.rb | # frozen_string_literal: true
module MachO
# A collection of utility functions used throughout ruby-macho.
module Utils
# Rounds a value to the next multiple of the given round.
# @param value [Integer] the number being rounded
# @param round [Integer] the number being rounded with
# @return [Integer] the rounded value
# @see http://www.opensource.apple.com/source/cctools/cctools-870/libstuff/rnd.c
def self.round(value, round)
round -= 1
value += round
value &= ~round
value
end
# Returns the number of bytes needed to pad the given size to the given
# alignment.
# @param size [Integer] the unpadded size
# @param alignment [Integer] the number to alignment the size with
# @return [Integer] the number of pad bytes required
def self.padding_for(size, alignment)
round(size, alignment) - size
end
# Returns a string of null bytes of the requested (non-negative) size
# @param size [Integer] the size of the nullpad
# @return [String] the null string (or empty string, for `size = 0`)
# @raise [ArgumentError] if a non-positive nullpad is requested
def self.nullpad(size)
raise ArgumentError, "size < 0: #{size}" if size.negative?
"\x00" * size
end
# Converts an abstract (native-endian) String#unpack format to big or
# little.
# @param format [String] the format string being converted
# @param endianness [Symbol] either `:big` or `:little`
# @return [String] the converted string
def self.specialize_format(format, endianness)
modifier = endianness == :big ? ">" : "<"
format.tr("=", modifier)
end
# Packs tagged strings into an aligned payload.
# @param fixed_offset [Integer] the baseline offset for the first packed
# string
# @param alignment [Integer] the alignment value to use for packing
# @param strings [Hash] the labeled strings to pack
# @return [Array<String, Hash>] the packed string and labeled offsets
def self.pack_strings(fixed_offset, alignment, strings = {})
offsets = {}
next_offset = fixed_offset
payload = +""
strings.each do |key, string|
offsets[key] = next_offset
payload << string
payload << Utils.nullpad(1)
next_offset += string.bytesize + 1
end
payload << Utils.nullpad(padding_for(fixed_offset + payload.bytesize, alignment))
[payload.freeze, offsets]
end
# Compares the given number to valid Mach-O magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid Mach-O magic number
def self.magic?(num)
Headers::MH_MAGICS.key?(num)
end
# Compares the given number to valid Fat magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid Fat magic number
def self.fat_magic?(num)
[Headers::FAT_MAGIC, Headers::FAT_MAGIC_64].include? num
end
# Compares the given number to valid 32-bit Fat magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid 32-bit fat magic number
def self.fat_magic32?(num)
num == Headers::FAT_MAGIC
end
# Compares the given number to valid 64-bit Fat magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid 64-bit fat magic number
def self.fat_magic64?(num)
num == Headers::FAT_MAGIC_64
end
# Compares the given number to valid 32-bit Mach-O magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid 32-bit magic number
def self.magic32?(num)
[Headers::MH_MAGIC, Headers::MH_CIGAM].include? num
end
# Compares the given number to valid 64-bit Mach-O magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid 64-bit magic number
def self.magic64?(num)
[Headers::MH_MAGIC_64, Headers::MH_CIGAM_64].include? num
end
# Compares the given number to valid little-endian magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid little-endian magic number
def self.little_magic?(num)
[Headers::MH_CIGAM, Headers::MH_CIGAM_64].include? num
end
# Compares the given number to valid big-endian magic numbers.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid big-endian magic number
def self.big_magic?(num)
[Headers::MH_MAGIC, Headers::MH_MAGIC_64].include? num
end
# Compares the given number to the known magic number for a compressed Mach-O slice.
# @param num [Integer] the number being checked
# @return [Boolean] whether `num` is a valid compressed header magic number
def self.compressed_magic?(num)
num == Headers::COMPRESSED_MAGIC
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/fat_file.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/fat_file.rb | # frozen_string_literal: true
require "forwardable"
module MachO
# Represents a "Fat" file, which contains a header, a listing of available
# architectures, and one or more Mach-O binaries.
# @see https://en.wikipedia.org/wiki/Mach-O#Multi-architecture_binaries
# @see MachOFile
class FatFile
extend Forwardable
# @return [String] the filename loaded from, or nil if loaded from a binary string
attr_accessor :filename
# @return [Hash] any parser options that the instance was created with
# @note Options specified in a {FatFile} trickle down into the internal {MachOFile}s.
attr_reader :options
# @return [Headers::FatHeader] the file's header
attr_reader :header
# @return [Array<Headers::FatArch>, Array<Headers::FatArch64] an array of fat architectures
attr_reader :fat_archs
# @return [Array<MachOFile>] an array of Mach-O binaries
attr_reader :machos
# Creates a new FatFile from the given (single-arch) Mach-Os
# @param machos [Array<MachOFile>] the machos to combine
# @param fat64 [Boolean] whether to use {Headers::FatArch64}s to represent each slice
# @return [FatFile] a new FatFile containing the give machos
# @raise [ArgumentError] if less than one Mach-O is given
# @raise [FatArchOffsetOverflowError] if the Mach-Os are too big to be represented
# in a 32-bit {Headers::FatArch} and `fat64` is `false`.
def self.new_from_machos(*machos, fat64: false)
raise ArgumentError, "expected at least one Mach-O" if machos.empty?
fa_klass, magic = if fat64
[Headers::FatArch64, Headers::FAT_MAGIC_64]
else
[Headers::FatArch, Headers::FAT_MAGIC]
end
# put the smaller alignments further forwards in fat macho, so that we do less padding
machos = machos.sort_by(&:segment_alignment)
bin = +""
bin << Headers::FatHeader.new(magic, machos.size).serialize
offset = Headers::FatHeader.bytesize + (machos.size * fa_klass.bytesize)
macho_pads = {}
machos.each do |macho|
macho_offset = Utils.round(offset, 2**macho.segment_alignment)
raise FatArchOffsetOverflowError, macho_offset if !fat64 && macho_offset > ((2**32) - 1)
macho_pads[macho] = Utils.padding_for(offset, 2**macho.segment_alignment)
bin << fa_klass.new(macho.header.cputype, macho.header.cpusubtype,
macho_offset, macho.serialize.bytesize,
macho.segment_alignment).serialize
offset += (macho.serialize.bytesize + macho_pads[macho])
end
machos.each do |macho| # rubocop:disable Style/CombinableLoops
bin << Utils.nullpad(macho_pads[macho])
bin << macho.serialize
end
new_from_bin(bin)
end
# Creates a new FatFile instance from a binary string.
# @param bin [String] a binary string containing raw Mach-O data
# @param opts [Hash] options to control the parser with
# @note see {MachOFile#initialize} for currently valid options
# @return [FatFile] a new FatFile
def self.new_from_bin(bin, **opts)
instance = allocate
instance.initialize_from_bin(bin, opts)
instance
end
# Creates a new FatFile from the given filename.
# @param filename [String] the fat file to load from
# @param opts [Hash] options to control the parser with
# @note see {MachOFile#initialize} for currently valid options
# @raise [ArgumentError] if the given file does not exist
def initialize(filename, **opts)
raise ArgumentError, "#{filename}: no such file" unless File.file?(filename)
@filename = filename
@options = opts
@raw_data = File.binread(@filename)
populate_fields
end
# Initializes a new FatFile instance from a binary string with the given options.
# @see new_from_bin
# @api private
def initialize_from_bin(bin, opts)
@filename = nil
@options = opts
@raw_data = bin
populate_fields
end
# The file's raw fat data.
# @return [String] the raw fat data
def serialize
@raw_data
end
# @!method object?
# @return (see MachO::MachOFile#object?)
# @!method executable?
# @return (see MachO::MachOFile#executable?)
# @!method fvmlib?
# @return (see MachO::MachOFile#fvmlib?)
# @!method core?
# @return (see MachO::MachOFile#core?)
# @!method preload?
# @return (see MachO::MachOFile#preload?)
# @!method dylib?
# @return (see MachO::MachOFile#dylib?)
# @!method dylinker?
# @return (see MachO::MachOFile#dylinker?)
# @!method bundle?
# @return (see MachO::MachOFile#bundle?)
# @!method dsym?
# @return (see MachO::MachOFile#dsym?)
# @!method kext?
# @return (see MachO::MachOFile#kext?)
# @!method filetype
# @return (see MachO::MachOFile#filetype)
# @!method dylib_id
# @return (see MachO::MachOFile#dylib_id)
def_delegators :canonical_macho, :object?, :executable?, :fvmlib?,
:core?, :preload?, :dylib?, :dylinker?, :bundle?,
:dsym?, :kext?, :filetype, :dylib_id
# @!method magic
# @return (see MachO::Headers::FatHeader#magic)
def_delegators :header, :magic
# @return [String] a string representation of the file's magic number
def magic_string
Headers::MH_MAGICS[magic]
end
# Populate the instance's fields with the raw Fat Mach-O data.
# @return [void]
# @note This method is public, but should (almost) never need to be called.
def populate_fields
@header = populate_fat_header
@fat_archs = populate_fat_archs
@machos = populate_machos
end
# All load commands responsible for loading dylibs in the file's Mach-O's.
# @return [Array<LoadCommands::DylibCommand>] an array of DylibCommands
def dylib_load_commands
machos.map(&:dylib_load_commands).flatten
end
# Changes the file's dylib ID to `new_id`. If the file is not a dylib,
# does nothing.
# @example
# file.change_dylib_id('libFoo.dylib')
# @param new_id [String] the new dylib ID
# @param options [Hash]
# @option options [Boolean] :strict (true) if true, fail if one slice fails.
# if false, fail only if all slices fail.
# @return [void]
# @raise [ArgumentError] if `new_id` is not a String
# @see MachOFile#linked_dylibs
def change_dylib_id(new_id, options = {})
raise ArgumentError, "argument must be a String" unless new_id.is_a?(String)
return unless machos.all?(&:dylib?)
each_macho(options) do |macho|
macho.change_dylib_id(new_id, options)
end
repopulate_raw_machos
end
alias dylib_id= change_dylib_id
# All shared libraries linked to the file's Mach-Os.
# @return [Array<String>] an array of all shared libraries
# @see MachOFile#linked_dylibs
def linked_dylibs
# Individual architectures in a fat binary can link to different subsets
# of libraries, but at this point we want to have the full picture, i.e.
# the union of all libraries used by all architectures.
machos.map(&:linked_dylibs).flatten.uniq
end
# Changes all dependent shared library install names from `old_name` to
# `new_name`. In a fat file, this changes install names in all internal
# Mach-Os.
# @example
# file.change_install_name('/usr/lib/libFoo.dylib', '/usr/lib/libBar.dylib')
# @param old_name [String] the shared library name being changed
# @param new_name [String] the new name
# @param options [Hash]
# @option options [Boolean] :strict (true) if true, fail if one slice fails.
# if false, fail only if all slices fail.
# @return [void]
# @see MachOFile#change_install_name
def change_install_name(old_name, new_name, options = {})
each_macho(options) do |macho|
macho.change_install_name(old_name, new_name, options)
end
repopulate_raw_machos
end
alias change_dylib change_install_name
# All runtime paths associated with the file's Mach-Os.
# @return [Array<String>] an array of all runtime paths
# @see MachOFile#rpaths
def rpaths
# Can individual architectures have different runtime paths?
machos.map(&:rpaths).flatten.uniq
end
# Change the runtime path `old_path` to `new_path` in the file's Mach-Os.
# @param old_path [String] the old runtime path
# @param new_path [String] the new runtime path
# @param options [Hash]
# @option options [Boolean] :strict (true) if true, fail if one slice fails.
# if false, fail only if all slices fail.
# @option options [Boolean] :uniq (false) for each slice: if true, change
# each rpath simultaneously.
# @return [void]
# @see MachOFile#change_rpath
def change_rpath(old_path, new_path, options = {})
each_macho(options) do |macho|
macho.change_rpath(old_path, new_path, options)
end
repopulate_raw_machos
end
# Add the given runtime path to the file's Mach-Os.
# @param path [String] the new runtime path
# @param options [Hash]
# @option options [Boolean] :strict (true) if true, fail if one slice fails.
# if false, fail only if all slices fail.
# @return [void]
# @see MachOFile#add_rpath
def add_rpath(path, options = {})
each_macho(options) do |macho|
macho.add_rpath(path, options)
end
repopulate_raw_machos
end
# Delete the given runtime path from the file's Mach-Os.
# @param path [String] the runtime path to delete
# @param options [Hash]
# @option options [Boolean] :strict (true) if true, fail if one slice fails.
# if false, fail only if all slices fail.
# @option options [Boolean] :uniq (false) for each slice: if true, delete
# only the first runtime path that matches. if false, delete all duplicate
# paths that match.
# @return void
# @see MachOFile#delete_rpath
def delete_rpath(path, options = {})
each_macho(options) do |macho|
macho.delete_rpath(path, options)
end
repopulate_raw_machos
end
# Extract a Mach-O with the given CPU type from the file.
# @example
# file.extract(:i386) # => MachO::MachOFile
# @param cputype [Symbol] the CPU type of the Mach-O being extracted
# @return [MachOFile, nil] the extracted Mach-O or nil if no Mach-O has the given CPU type
def extract(cputype)
machos.select { |macho| macho.cputype == cputype }.first
end
# Write all (fat) data to the given filename.
# @param filename [String] the file to write to
# @return [void]
def write(filename)
File.binwrite(filename, @raw_data)
end
# Write all (fat) data to the file used to initialize the instance.
# @return [void]
# @raise [MachOError] if the instance was initialized without a file
# @note Overwrites all data in the file!
def write!
raise MachOError, "no initial file to write to" if filename.nil?
File.binwrite(@filename, @raw_data)
end
# @return [Hash] a hash representation of this {FatFile}
def to_h
{
"header" => header.to_h,
"fat_archs" => fat_archs.map(&:to_h),
"machos" => machos.map(&:to_h),
}
end
private
# Obtain the fat header from raw file data.
# @return [Headers::FatHeader] the fat header
# @raise [TruncatedFileError] if the file is too small to have a
# valid header
# @raise [MagicError] if the magic is not valid Mach-O magic
# @raise [MachOBinaryError] if the magic is for a non-fat Mach-O file
# @raise [JavaClassFileError] if the file is a Java classfile
# @raise [ZeroArchitectureError] if the file has no internal slices
# (i.e., nfat_arch == 0) and the permissive option is not set
# @api private
def populate_fat_header
# the smallest fat Mach-O header is 8 bytes
raise TruncatedFileError if @raw_data.size < 8
fh = Headers::FatHeader.new_from_bin(:big, @raw_data[0, Headers::FatHeader.bytesize])
raise MagicError, fh.magic unless Utils.magic?(fh.magic)
raise MachOBinaryError unless Utils.fat_magic?(fh.magic)
# Rationale: Java classfiles have the same magic as big-endian fat
# Mach-Os. Classfiles encode their version at the same offset as
# `nfat_arch` and the lowest version number is 43, so we error out
# if a file claims to have over 30 internal architectures. It's
# technically possible for a fat Mach-O to have over 30 architectures,
# but this is extremely unlikely and in practice distinguishes the two
# formats.
raise JavaClassFileError if fh.nfat_arch > 30
# Rationale: return an error if the file has no internal slices.
raise ZeroArchitectureError if fh.nfat_arch.zero?
fh
end
# Obtain an array of fat architectures from raw file data.
# @return [Array<Headers::FatArch>] an array of fat architectures
# @api private
def populate_fat_archs
archs = []
fa_klass = Utils.fat_magic32?(header.magic) ? Headers::FatArch : Headers::FatArch64
fa_off = Headers::FatHeader.bytesize
fa_len = fa_klass.bytesize
header.nfat_arch.times do |i|
archs << fa_klass.new_from_bin(:big, @raw_data[fa_off + (fa_len * i), fa_len])
end
archs
end
# Obtain an array of Mach-O blobs from raw file data.
# @return [Array<MachOFile>] an array of Mach-Os
# @api private
def populate_machos
machos = []
fat_archs.each do |arch|
machos << MachOFile.new_from_bin(@raw_data[arch.offset, arch.size], **options)
# Make sure that each fat_arch and internal slice.
# contain matching cputypes and cpusubtypes
next if machos.last.header.cputype == arch.cputype &&
machos.last.header.cpusubtype == arch.cpusubtype
raise CPUTypeMismatchError.new(arch.cputype, arch.cpusubtype, machos.last.header.cputype, machos.last.header.cpusubtype)
end
machos
end
# Repopulate the raw Mach-O data with each internal Mach-O object.
# @return [void]
# @api private
def repopulate_raw_machos
machos.each_with_index do |macho, i|
arch = fat_archs[i]
@raw_data[arch.offset, arch.size] = macho.serialize
end
end
# Yield each Mach-O object in the file, rescuing and accumulating errors.
# @param options [Hash]
# @option options [Boolean] :strict (true) whether or not to fail loudly
# with an exception if at least one Mach-O raises an exception. If false,
# only raises an exception if *all* Mach-Os raise exceptions.
# @raise [RecoverableModificationError] under the conditions of
# the `:strict` option above.
# @api private
def each_macho(options = {})
strict = options.fetch(:strict, true)
errors = []
machos.each_with_index do |macho, index|
yield macho
rescue RecoverableModificationError => e
e.macho_slice = index
# Strict mode: Immediately re-raise. Otherwise: Retain, check later.
raise e if strict
errors << e
end
# Non-strict mode: Raise first error if *all* Mach-O slices failed.
raise errors.first if errors.size == machos.size
end
# Return a single-arch Mach-O that represents this fat Mach-O for purposes
# of delegation.
# @return [MachOFile] the Mach-O file
# @api private
def canonical_macho
machos.first
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/structure.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/structure.rb | # frozen_string_literal: true
module MachO
# A general purpose pseudo-structure. Described in detail in docs/machostructure-dsl.md.
# @abstract
class MachOStructure
# Constants used for parsing MachOStructure fields
module Fields
# 1. All fields with empty strings and zeros aren't used
# to calculate the format and sizeof variables.
# 2. All fields with nil should provide those values manually
# via the :size parameter.
# association of field types to byte size
# @api private
BYTE_SIZE = {
# Binary slices
:string => nil,
:null_padded_string => nil,
:int32 => 4,
:uint32 => 4,
:uint64 => 8,
# Classes
:view => 0,
:lcstr => 4,
:two_level_hints_table => 0,
:tool_entries => 4,
}.freeze
# association of field types with ruby format codes
# Binary format codes can be found here:
# https://docs.ruby-lang.org/en/2.6.0/String.html#method-i-unpack
#
# The equals sign is used to manually change endianness using
# the Utils#specialize_format() method.
# @api private
FORMAT_CODE = {
# Binary slices
:string => "a",
:null_padded_string => "Z",
:int32 => "l=",
:uint32 => "L=",
:uint64 => "Q=",
# Classes
:view => "",
:lcstr => "L=",
:two_level_hints_table => "",
:tool_entries => "L=",
}.freeze
# A list of classes that must get initialized
# To add a new class append it here and add the init method to the def_class_reader method
# @api private
CLASSES_TO_INIT = %i[lcstr tool_entries two_level_hints_table].freeze
# A list of fields that don't require arguments in the initializer
# Used to calculate MachOStructure#min_args
# @api private
NO_ARG_REQUIRED = %i[two_level_hints_table].freeze
end
# map of field names to indices
@field_idxs = {}
# array of fields sizes
@size_list = []
# array of field format codes
@fmt_list = []
# minimum number of required arguments
@min_args = 0
# @param args [Array[Value]] list of field parameters
def initialize(*args)
raise ArgumentError, "Invalid number of arguments" if args.size < self.class.min_args
@values = args
end
# @return [Hash] a hash representation of this {MachOStructure}.
def to_h
{
"structure" => {
"format" => self.class.format,
"bytesize" => self.class.bytesize,
},
}
end
class << self
attr_reader :min_args
# @param endianness [Symbol] either `:big` or `:little`
# @param bin [String] the string to be unpacked into the new structure
# @return [MachO::MachOStructure] the resulting structure
# @api private
def new_from_bin(endianness, bin)
format = Utils.specialize_format(self.format, endianness)
new(*bin.unpack(format))
end
def format
@format ||= @fmt_list.join
end
def bytesize
@bytesize ||= @size_list.sum
end
private
# @param subclass [Class] subclass type
# @api private
def inherited(subclass) # rubocop:disable Lint/MissingSuper
# Clone all class instance variables
field_idxs = @field_idxs.dup
size_list = @size_list.dup
fmt_list = @fmt_list.dup
min_args = @min_args.dup
# Add those values to the inheriting class
subclass.class_eval do
@field_idxs = field_idxs
@size_list = size_list
@fmt_list = fmt_list
@min_args = min_args
end
end
# @param name [Symbol] name of internal field
# @param type [Symbol] type of field in terms of binary size
# @param options [Hash] set of additional options
# Expected options
# :size [Integer] size in bytes
# :mask [Integer] bitmask
# :unpack [String] string format
# :default [Value] default value
# :to_s [Boolean] flag for generating #to_s
# :endian [Symbol] optionally specify :big or :little endian
# :padding [Symbol] optionally specify :null padding
# @api private
def field(name, type, **options)
raise ArgumentError, "Invalid field type #{type}" unless Fields::FORMAT_CODE.key?(type)
# Get field idx for size_list and fmt_list
idx = if @field_idxs.key?(name)
@field_idxs[name]
else
@min_args += 1 unless options.key?(:default) || Fields::NO_ARG_REQUIRED.include?(type)
@field_idxs[name] = @field_idxs.size
@size_list << nil
@fmt_list << nil
@field_idxs.size - 1
end
# Update string type if padding is specified
type = :null_padded_string if type == :string && options[:padding] == :null
# Add to size_list and fmt_list
@size_list[idx] = Fields::BYTE_SIZE[type] || options[:size]
@fmt_list[idx] = if options[:endian]
Utils.specialize_format(Fields::FORMAT_CODE[type], options[:endian])
else
Fields::FORMAT_CODE[type]
end
@fmt_list[idx] += options[:size].to_s if options.key?(:size)
# Generate methods
if Fields::CLASSES_TO_INIT.include?(type)
def_class_reader(name, type, idx)
elsif options.key?(:mask)
def_mask_reader(name, idx, options[:mask])
elsif options.key?(:unpack)
def_unpack_reader(name, idx, options[:unpack])
elsif options.key?(:default)
def_default_reader(name, idx, options[:default])
else
def_reader(name, idx)
end
def_to_s(name) if options[:to_s]
end
#
# Method Generators
#
# Generates a reader method for classes that need to be initialized.
# These classes are defined in the Fields::CLASSES_TO_INIT array.
# @param name [Symbol] name of internal field
# @param type [Symbol] type of field in terms of binary size
# @param idx [Integer] the index of the field value in the @values array
# @api private
def def_class_reader(name, type, idx)
case type
when :lcstr
define_method(name) do
instance_variable_defined?("@#{name}") ||
instance_variable_set("@#{name}", LoadCommands::LoadCommand::LCStr.new(self, @values[idx]))
instance_variable_get("@#{name}")
end
when :two_level_hints_table
define_method(name) do
instance_variable_defined?("@#{name}") ||
instance_variable_set("@#{name}", LoadCommands::TwolevelHintsCommand::TwolevelHintsTable.new(view, htoffset, nhints))
instance_variable_get("@#{name}")
end
when :tool_entries
define_method(name) do
instance_variable_defined?("@#{name}") ||
instance_variable_set("@#{name}", LoadCommands::BuildVersionCommand::ToolEntries.new(view, @values[idx]))
instance_variable_get("@#{name}")
end
end
end
# Generates a reader method for fields that need to be bitmasked.
# @param name [Symbol] name of internal field
# @param idx [Integer] the index of the field value in the @values array
# @param mask [Integer] the bitmask
# @api private
def def_mask_reader(name, idx, mask)
define_method(name) do
instance_variable_defined?("@#{name}") ||
instance_variable_set("@#{name}", @values[idx] & ~mask)
instance_variable_get("@#{name}")
end
end
# Generates a reader method for fields that need further unpacking.
# @param name [Symbol] name of internal field
# @param idx [Integer] the index of the field value in the @values array
# @param unpack [String] the format code used for further binary unpacking
# @api private
def def_unpack_reader(name, idx, unpack)
define_method(name) do
instance_variable_defined?("@#{name}") ||
instance_variable_set("@#{name}", @values[idx].unpack(unpack))
instance_variable_get("@#{name}")
end
end
# Generates a reader method for fields that have default values.
# @param name [Symbol] name of internal field
# @param idx [Integer] the index of the field value in the @values array
# @param default [Value] the default value
# @api private
def def_default_reader(name, idx, default)
define_method(name) do
instance_variable_defined?("@#{name}") ||
instance_variable_set("@#{name}", @values.size > idx ? @values[idx] : default)
instance_variable_get("@#{name}")
end
end
# Generates an attr_reader like method for a field.
# @param name [Symbol] name of internal field
# @param idx [Integer] the index of the field value in the @values array
# @api private
def def_reader(name, idx)
define_method(name) do
@values[idx]
end
end
# Generates the to_s method based on the named field.
# @param name [Symbol] name of the field
# @api private
def def_to_s(name)
define_method(:to_s) do
send(name).to_s
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/headers.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/headers.rb | # frozen_string_literal: true
module MachO
# Classes and constants for parsing the headers of Mach-O binaries.
module Headers
# big-endian fat magic
# @api private
FAT_MAGIC = 0xcafebabe
# little-endian fat magic
# @note This is defined for completeness, but should never appear in ruby-macho code,
# since fat headers are always big-endian.
# @api private
FAT_CIGAM = 0xbebafeca
# 64-bit big-endian fat magic
FAT_MAGIC_64 = 0xcafebabf
# 64-bit little-endian fat magic
# @note This is defined for completeness, but should never appear in ruby-macho code,
# since fat headers are always big-endian.
FAT_CIGAM_64 = 0xbfbafeca
# 32-bit big-endian magic
# @api private
MH_MAGIC = 0xfeedface
# 32-bit little-endian magic
# @api private
MH_CIGAM = 0xcefaedfe
# 64-bit big-endian magic
# @api private
MH_MAGIC_64 = 0xfeedfacf
# 64-bit little-endian magic
# @api private
MH_CIGAM_64 = 0xcffaedfe
# compressed mach-o magic
# @api private
COMPRESSED_MAGIC = 0x636f6d70 # "comp"
# a compressed mach-o slice, using LZSS for compression
# @api private
COMP_TYPE_LZSS = 0x6c7a7373 # "lzss"
# a compressed mach-o slice, using LZVN ("FastLib") for compression
# @api private
COMP_TYPE_FASTLIB = 0x6c7a766e # "lzvn"
# association of magic numbers to string representations
# @api private
MH_MAGICS = {
FAT_MAGIC => "FAT_MAGIC",
FAT_MAGIC_64 => "FAT_MAGIC_64",
MH_MAGIC => "MH_MAGIC",
MH_CIGAM => "MH_CIGAM",
MH_MAGIC_64 => "MH_MAGIC_64",
MH_CIGAM_64 => "MH_CIGAM_64",
}.freeze
# mask for CPUs with 64-bit architectures (when running a 64-bit ABI?)
# @api private
CPU_ARCH_ABI64 = 0x01000000
# mask for CPUs with 64-bit architectures (when running a 32-bit ABI?)
# @see https://github.com/Homebrew/ruby-macho/issues/113
# @api private
CPU_ARCH_ABI32 = 0x02000000
# any CPU (unused?)
# @api private
CPU_TYPE_ANY = -1
# m68k compatible CPUs
# @api private
CPU_TYPE_MC680X0 = 0x06
# i386 and later compatible CPUs
# @api private
CPU_TYPE_I386 = 0x07
# x86_64 (AMD64) compatible CPUs
# @api private
CPU_TYPE_X86_64 = (CPU_TYPE_I386 | CPU_ARCH_ABI64)
# 32-bit ARM compatible CPUs
# @api private
CPU_TYPE_ARM = 0x0c
# m88k compatible CPUs
# @api private
CPU_TYPE_MC88000 = 0xd
# 64-bit ARM compatible CPUs
# @api private
CPU_TYPE_ARM64 = (CPU_TYPE_ARM | CPU_ARCH_ABI64)
# 64-bit ARM compatible CPUs (running in 32-bit mode?)
# @see https://github.com/Homebrew/ruby-macho/issues/113
CPU_TYPE_ARM64_32 = (CPU_TYPE_ARM | CPU_ARCH_ABI32)
# PowerPC compatible CPUs
# @api private
CPU_TYPE_POWERPC = 0x12
# PowerPC64 compatible CPUs
# @api private
CPU_TYPE_POWERPC64 = (CPU_TYPE_POWERPC | CPU_ARCH_ABI64)
# association of cpu types to symbol representations
# @api private
CPU_TYPES = {
CPU_TYPE_ANY => :any,
CPU_TYPE_I386 => :i386,
CPU_TYPE_X86_64 => :x86_64,
CPU_TYPE_ARM => :arm,
CPU_TYPE_ARM64 => :arm64,
CPU_TYPE_ARM64_32 => :arm64_32,
CPU_TYPE_POWERPC => :ppc,
CPU_TYPE_POWERPC64 => :ppc64,
}.freeze
# mask for CPU subtype capabilities
# @api private
CPU_SUBTYPE_MASK = 0xff000000
# 64-bit libraries (undocumented!)
# @see http://llvm.org/docs/doxygen/html/Support_2MachO_8h_source.html
# @api private
CPU_SUBTYPE_LIB64 = 0x80000000
# the lowest common sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_I386 = 3
# the i486 sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_486 = 4
# the i486SX sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_486SX = 132
# the i586 (P5, Pentium) sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_586 = 5
# @see CPU_SUBTYPE_586
# @api private
CPU_SUBTYPE_PENT = CPU_SUBTYPE_586
# the Pentium Pro (P6) sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_PENTPRO = 22
# the Pentium II (P6, M3?) sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_PENTII_M3 = 54
# the Pentium II (P6, M5?) sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_PENTII_M5 = 86
# the Pentium 4 (Netburst) sub-type for `CPU_TYPE_I386`
# @api private
CPU_SUBTYPE_PENTIUM_4 = 10
# the lowest common sub-type for `CPU_TYPE_MC680X0`
# @api private
CPU_SUBTYPE_MC680X0_ALL = 1
# @see CPU_SUBTYPE_MC680X0_ALL
# @api private
CPU_SUBTYPE_MC68030 = CPU_SUBTYPE_MC680X0_ALL
# the 040 subtype for `CPU_TYPE_MC680X0`
# @api private
CPU_SUBTYPE_MC68040 = 2
# the 030 subtype for `CPU_TYPE_MC680X0`
# @api private
CPU_SUBTYPE_MC68030_ONLY = 3
# the lowest common sub-type for `CPU_TYPE_X86_64`
# @api private
CPU_SUBTYPE_X86_64_ALL = CPU_SUBTYPE_I386
# the Haskell sub-type for `CPU_TYPE_X86_64`
# @api private
CPU_SUBTYPE_X86_64_H = 8
# the lowest common sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_ALL = 0
# the v4t sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V4T = 5
# the v6 sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V6 = 6
# the v5 sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V5TEJ = 7
# the xscale (v5 family) sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_XSCALE = 8
# the v7 sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V7 = 9
# the v7f (Cortex A9) sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V7F = 10
# the v7s ("Swift") sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V7S = 11
# the v7k ("Kirkwood40") sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V7K = 12
# the v6m sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V6M = 14
# the v7m sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V7M = 15
# the v7em sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V7EM = 16
# the v8 sub-type for `CPU_TYPE_ARM`
# @api private
CPU_SUBTYPE_ARM_V8 = 13
# the lowest common sub-type for `CPU_TYPE_ARM64`
# @api private
CPU_SUBTYPE_ARM64_ALL = 0
# the v8 sub-type for `CPU_TYPE_ARM64`
# @api private
CPU_SUBTYPE_ARM64_V8 = 1
# the v8 sub-type for `CPU_TYPE_ARM64_32`
# @api private
CPU_SUBTYPE_ARM64_32_V8 = 1
# the e (A12) sub-type for `CPU_TYPE_ARM64`
# @api private
CPU_SUBTYPE_ARM64E = 2
# the lowest common sub-type for `CPU_TYPE_MC88000`
# @api private
CPU_SUBTYPE_MC88000_ALL = 0
# @see CPU_SUBTYPE_MC88000_ALL
# @api private
CPU_SUBTYPE_MMAX_JPC = CPU_SUBTYPE_MC88000_ALL
# the 100 sub-type for `CPU_TYPE_MC88000`
# @api private
CPU_SUBTYPE_MC88100 = 1
# the 110 sub-type for `CPU_TYPE_MC88000`
# @api private
CPU_SUBTYPE_MC88110 = 2
# the lowest common sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_ALL = 0
# the 601 sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_601 = 1
# the 602 sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_602 = 2
# the 603 sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_603 = 3
# the 603e (G2) sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_603E = 4
# the 603ev sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_603EV = 5
# the 604 sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_604 = 6
# the 604e sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_604E = 7
# the 620 sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_620 = 8
# the 750 (G3) sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_750 = 9
# the 7400 (G4) sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_7400 = 10
# the 7450 (G4 "Voyager") sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_7450 = 11
# the 970 (G5) sub-type for `CPU_TYPE_POWERPC`
# @api private
CPU_SUBTYPE_POWERPC_970 = 100
# any CPU sub-type for CPU type `CPU_TYPE_POWERPC64`
# @api private
CPU_SUBTYPE_POWERPC64_ALL = CPU_SUBTYPE_POWERPC_ALL
# association of CPU types/subtype pairs to symbol representations in
# (very) roughly descending order of commonness
# @see https://opensource.apple.com/source/cctools/cctools-877.8/libstuff/arch.c
# @api private
CPU_SUBTYPES = {
CPU_TYPE_I386 => {
CPU_SUBTYPE_I386 => :i386,
CPU_SUBTYPE_486 => :i486,
CPU_SUBTYPE_486SX => :i486SX,
CPU_SUBTYPE_586 => :i586, # also "pentium" in arch(3)
CPU_SUBTYPE_PENTPRO => :i686, # also "pentpro" in arch(3)
CPU_SUBTYPE_PENTII_M3 => :pentIIm3,
CPU_SUBTYPE_PENTII_M5 => :pentIIm5,
CPU_SUBTYPE_PENTIUM_4 => :pentium4,
}.freeze,
CPU_TYPE_X86_64 => {
CPU_SUBTYPE_X86_64_ALL => :x86_64,
CPU_SUBTYPE_X86_64_H => :x86_64h,
}.freeze,
CPU_TYPE_ARM => {
CPU_SUBTYPE_ARM_ALL => :arm,
CPU_SUBTYPE_ARM_V4T => :armv4t,
CPU_SUBTYPE_ARM_V6 => :armv6,
CPU_SUBTYPE_ARM_V5TEJ => :armv5,
CPU_SUBTYPE_ARM_XSCALE => :xscale,
CPU_SUBTYPE_ARM_V7 => :armv7,
CPU_SUBTYPE_ARM_V7F => :armv7f,
CPU_SUBTYPE_ARM_V7S => :armv7s,
CPU_SUBTYPE_ARM_V7K => :armv7k,
CPU_SUBTYPE_ARM_V6M => :armv6m,
CPU_SUBTYPE_ARM_V7M => :armv7m,
CPU_SUBTYPE_ARM_V7EM => :armv7em,
CPU_SUBTYPE_ARM_V8 => :armv8,
}.freeze,
CPU_TYPE_ARM64 => {
CPU_SUBTYPE_ARM64_ALL => :arm64,
CPU_SUBTYPE_ARM64_V8 => :arm64v8,
CPU_SUBTYPE_ARM64E => :arm64e,
}.freeze,
CPU_TYPE_ARM64_32 => {
CPU_SUBTYPE_ARM64_32_V8 => :arm64_32v8,
}.freeze,
CPU_TYPE_POWERPC => {
CPU_SUBTYPE_POWERPC_ALL => :ppc,
CPU_SUBTYPE_POWERPC_601 => :ppc601,
CPU_SUBTYPE_POWERPC_603 => :ppc603,
CPU_SUBTYPE_POWERPC_603E => :ppc603e,
CPU_SUBTYPE_POWERPC_603EV => :ppc603ev,
CPU_SUBTYPE_POWERPC_604 => :ppc604,
CPU_SUBTYPE_POWERPC_604E => :ppc604e,
CPU_SUBTYPE_POWERPC_750 => :ppc750,
CPU_SUBTYPE_POWERPC_7400 => :ppc7400,
CPU_SUBTYPE_POWERPC_7450 => :ppc7450,
CPU_SUBTYPE_POWERPC_970 => :ppc970,
}.freeze,
CPU_TYPE_POWERPC64 => {
CPU_SUBTYPE_POWERPC64_ALL => :ppc64,
# apparently the only exception to the naming scheme
CPU_SUBTYPE_POWERPC_970 => :ppc970_64,
}.freeze,
CPU_TYPE_MC680X0 => {
CPU_SUBTYPE_MC680X0_ALL => :m68k,
CPU_SUBTYPE_MC68030 => :mc68030,
CPU_SUBTYPE_MC68040 => :mc68040,
},
CPU_TYPE_MC88000 => {
CPU_SUBTYPE_MC88000_ALL => :m88k,
},
}.freeze
# relocatable object file
# @api private
MH_OBJECT = 0x1
# demand paged executable file
# @api private
MH_EXECUTE = 0x2
# fixed VM shared library file
# @api private
MH_FVMLIB = 0x3
# core dump file
# @api private
MH_CORE = 0x4
# preloaded executable file
# @api private
MH_PRELOAD = 0x5
# dynamically bound shared library
# @api private
MH_DYLIB = 0x6
# dynamic link editor
# @api private
MH_DYLINKER = 0x7
# dynamically bound bundle file
# @api private
MH_BUNDLE = 0x8
# shared library stub for static linking only, no section contents
# @api private
MH_DYLIB_STUB = 0x9
# companion file with only debug sections
# @api private
MH_DSYM = 0xa
# x86_64 kexts
# @api private
MH_KEXT_BUNDLE = 0xb
# a set of Mach-Os, running in the same userspace, sharing a linkedit. The kext collection files are an example
# of this object type
# @api private
MH_FILESET = 0xc
# association of filetypes to Symbol representations
# @api private
MH_FILETYPES = {
MH_OBJECT => :object,
MH_EXECUTE => :execute,
MH_FVMLIB => :fvmlib,
MH_CORE => :core,
MH_PRELOAD => :preload,
MH_DYLIB => :dylib,
MH_DYLINKER => :dylinker,
MH_BUNDLE => :bundle,
MH_DYLIB_STUB => :dylib_stub,
MH_DSYM => :dsym,
MH_KEXT_BUNDLE => :kext_bundle,
MH_FILESET => :fileset,
}.freeze
# association of mach header flag symbols to values
# @api private
MH_FLAGS = {
:MH_NOUNDEFS => 0x1,
:MH_INCRLINK => 0x2,
:MH_DYLDLINK => 0x4,
:MH_BINDATLOAD => 0x8,
:MH_PREBOUND => 0x10,
:MH_SPLIT_SEGS => 0x20,
:MH_LAZY_INIT => 0x40,
:MH_TWOLEVEL => 0x80,
:MH_FORCE_FLAT => 0x100,
:MH_NOMULTIDEFS => 0x200,
:MH_NOPREFIXBINDING => 0x400,
:MH_PREBINDABLE => 0x800,
:MH_ALLMODSBOUND => 0x1000,
:MH_SUBSECTIONS_VIA_SYMBOLS => 0x2000,
:MH_CANONICAL => 0x4000,
:MH_WEAK_DEFINES => 0x8000,
:MH_BINDS_TO_WEAK => 0x10000,
:MH_ALLOW_STACK_EXECUTION => 0x20000,
:MH_ROOT_SAFE => 0x40000,
:MH_SETUID_SAFE => 0x80000,
:MH_NO_REEXPORTED_DYLIBS => 0x100000,
:MH_PIE => 0x200000,
:MH_DEAD_STRIPPABLE_DYLIB => 0x400000,
:MH_HAS_TLV_DESCRIPTORS => 0x800000,
:MH_NO_HEAP_EXECUTION => 0x1000000,
:MH_APP_EXTENSION_SAFE => 0x02000000,
:MH_NLIST_OUTOFSYNC_WITH_DYLDINFO => 0x04000000,
:MH_SIM_SUPPORT => 0x08000000,
:MH_DYLIB_IN_CACHE => 0x80000000,
}.freeze
# Fat binary header structure
# @see MachO::FatArch
class FatHeader < MachOStructure
# @return [Integer] the magic number of the header (and file)
field :magic, :uint32, :endian => :big
# @return [Integer] the number of fat architecture structures following the header
field :nfat_arch, :uint32, :endian => :big
# @return [String] the serialized fields of the fat header
def serialize
[magic, nfat_arch].pack(self.class.format)
end
# @return [Hash] a hash representation of this {FatHeader}
def to_h
{
"magic" => magic,
"magic_sym" => MH_MAGICS[magic],
"nfat_arch" => nfat_arch,
}.merge super
end
end
# 32-bit fat binary header architecture structure. A 32-bit fat Mach-O has one or more of
# these, indicating one or more internal Mach-O blobs.
# @note "32-bit" indicates the fact that this structure stores 32-bit offsets, not that the
# Mach-Os that it points to necessarily *are* 32-bit.
# @see MachO::Headers::FatHeader
class FatArch < MachOStructure
# @return [Integer] the CPU type of the Mach-O
field :cputype, :uint32, :endian => :big
# @return [Integer] the CPU subtype of the Mach-O
field :cpusubtype, :uint32, :endian => :big, :mask => CPU_SUBTYPE_MASK
# @return [Integer] the file offset to the beginning of the Mach-O data
field :offset, :uint32, :endian => :big
# @return [Integer] the size, in bytes, of the Mach-O data
field :size, :uint32, :endian => :big
# @return [Integer] the alignment, as a power of 2
field :align, :uint32, :endian => :big
# @return [String] the serialized fields of the fat arch
def serialize
[cputype, cpusubtype, offset, size, align].pack(self.class.format)
end
# @return [Hash] a hash representation of this {FatArch}
def to_h
{
"cputype" => cputype,
"cputype_sym" => CPU_TYPES[cputype],
"cpusubtype" => cpusubtype,
"cpusubtype_sym" => CPU_SUBTYPES[cputype][cpusubtype],
"offset" => offset,
"size" => size,
"align" => align,
}.merge super
end
end
# 64-bit fat binary header architecture structure. A 64-bit fat Mach-O has one or more of
# these, indicating one or more internal Mach-O blobs.
# @note "64-bit" indicates the fact that this structure stores 64-bit offsets, not that the
# Mach-Os that it points to necessarily *are* 64-bit.
# @see MachO::Headers::FatHeader
class FatArch64 < FatArch
# @return [Integer] the file offset to the beginning of the Mach-O data
field :offset, :uint64, :endian => :big
# @return [Integer] the size, in bytes, of the Mach-O data
field :size, :uint64, :endian => :big
# @return [void]
field :reserved, :uint32, :endian => :big, :default => 0
# @return [String] the serialized fields of the fat arch
def serialize
[cputype, cpusubtype, offset, size, align, reserved].pack(self.class.format)
end
# @return [Hash] a hash representation of this {FatArch64}
def to_h
{
"reserved" => reserved,
}.merge super
end
end
# 32-bit Mach-O file header structure
class MachHeader < MachOStructure
# @return [Integer] the magic number
field :magic, :uint32
# @return [Integer] the CPU type of the Mach-O
field :cputype, :uint32
# @return [Integer] the CPU subtype of the Mach-O
field :cpusubtype, :uint32, :mask => CPU_SUBTYPE_MASK
# @return [Integer] the file type of the Mach-O
field :filetype, :uint32
# @return [Integer] the number of load commands in the Mach-O
field :ncmds, :uint32
# @return [Integer] the size of all load commands, in bytes, in the Mach-O
field :sizeofcmds, :uint32
# @return [Integer] the header flags associated with the Mach-O
field :flags, :uint32
# @example
# puts "this mach-o has position-independent execution" if header.flag?(:MH_PIE)
# @param flag [Symbol] a mach header flag symbol
# @return [Boolean] true if `flag` is present in the header's flag section
def flag?(flag)
flag = MH_FLAGS[flag]
return false if flag.nil?
flags & flag == flag
end
# @return [Boolean] whether or not the file is of type `MH_OBJECT`
def object?
filetype == Headers::MH_OBJECT
end
# @return [Boolean] whether or not the file is of type `MH_EXECUTE`
def executable?
filetype == Headers::MH_EXECUTE
end
# @return [Boolean] whether or not the file is of type `MH_FVMLIB`
def fvmlib?
filetype == Headers::MH_FVMLIB
end
# @return [Boolean] whether or not the file is of type `MH_CORE`
def core?
filetype == Headers::MH_CORE
end
# @return [Boolean] whether or not the file is of type `MH_PRELOAD`
def preload?
filetype == Headers::MH_PRELOAD
end
# @return [Boolean] whether or not the file is of type `MH_DYLIB`
def dylib?
filetype == Headers::MH_DYLIB
end
# @return [Boolean] whether or not the file is of type `MH_DYLINKER`
def dylinker?
filetype == Headers::MH_DYLINKER
end
# @return [Boolean] whether or not the file is of type `MH_BUNDLE`
def bundle?
filetype == Headers::MH_BUNDLE
end
# @return [Boolean] whether or not the file is of type `MH_DSYM`
def dsym?
filetype == Headers::MH_DSYM
end
# @return [Boolean] whether or not the file is of type `MH_KEXT_BUNDLE`
def kext?
filetype == Headers::MH_KEXT_BUNDLE
end
# @return [Boolean] whether or not the file is of type `MH_FILESET`
def fileset?
filetype == Headers::MH_FILESET
end
# @return [Boolean] true if the Mach-O has 32-bit magic, false otherwise
def magic32?
Utils.magic32?(magic)
end
# @return [Boolean] true if the Mach-O has 64-bit magic, false otherwise
def magic64?
Utils.magic64?(magic)
end
# @return [Integer] the file's internal alignment
def alignment
magic32? ? 4 : 8
end
# @return [Hash] a hash representation of this {MachHeader}
def to_h
{
"magic" => magic,
"magic_sym" => MH_MAGICS[magic],
"cputype" => cputype,
"cputype_sym" => CPU_TYPES[cputype],
"cpusubtype" => cpusubtype,
"cpusubtype_sym" => CPU_SUBTYPES[cputype][cpusubtype],
"filetype" => filetype,
"filetype_sym" => MH_FILETYPES[filetype],
"ncmds" => ncmds,
"sizeofcmds" => sizeofcmds,
"flags" => flags,
"alignment" => alignment,
}.merge super
end
end
# 64-bit Mach-O file header structure
class MachHeader64 < MachHeader
# @return [void]
field :reserved, :uint32
# @return [Hash] a hash representation of this {MachHeader64}
def to_h
{
"reserved" => reserved,
}.merge super
end
end
# Prelinked kernel/"kernelcache" header structure
class PrelinkedKernelHeader < MachOStructure
# @return [Integer] the magic number for a compressed header ({COMPRESSED_MAGIC})
field :signature, :uint32, :endian => :big
# @return [Integer] the type of compression used
field :compress_type, :uint32, :endian => :big
# @return [Integer] a checksum for the uncompressed data
field :adler32, :uint32, :endian => :big
# @return [Integer] the size of the uncompressed data, in bytes
field :uncompressed_size, :uint32, :endian => :big
# @return [Integer] the size of the compressed data, in bytes
field :compressed_size, :uint32, :endian => :big
# @return [Integer] the version of the prelink format
field :prelink_version, :uint32, :endian => :big
# @return [void]
field :reserved, :string, :size => 40, :unpack => "L>10"
# @return [void]
field :platform_name, :string, :size => 64
# @return [void]
field :root_path, :string, :size => 256
# @return [Boolean] whether this prelinked kernel supports KASLR
def kaslr?
prelink_version >= 1
end
# @return [Boolean] whether this prelinked kernel is compressed with LZSS
def lzss?
compress_type == COMP_TYPE_LZSS
end
# @return [Boolean] whether this prelinked kernel is compressed with LZVN
def lzvn?
compress_type == COMP_TYPE_FASTLIB
end
# @return [Hash] a hash representation of this {PrelinkedKernelHeader}
def to_h
{
"signature" => signature,
"compress_type" => compress_type,
"adler32" => adler32,
"uncompressed_size" => uncompressed_size,
"compressed_size" => compressed_size,
"prelink_version" => prelink_version,
"reserved" => reserved,
"platform_name" => platform_name,
"root_path" => root_path,
}.merge super
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/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/load_commands.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/ruby-macho-4.1.0/lib/macho/load_commands.rb | # frozen_string_literal: true
module MachO
# Classes and constants for parsing load commands in Mach-O binaries.
module LoadCommands
# load commands added after OS X 10.1 need to be bitwise ORed with
# LC_REQ_DYLD to be recognized by the dynamic linker (dyld)
# @api private
LC_REQ_DYLD = 0x80000000
# association of load commands to symbol representations
# @api private
LOAD_COMMANDS = {
0x1 => :LC_SEGMENT,
0x2 => :LC_SYMTAB,
0x3 => :LC_SYMSEG,
0x4 => :LC_THREAD,
0x5 => :LC_UNIXTHREAD,
0x6 => :LC_LOADFVMLIB,
0x7 => :LC_IDFVMLIB,
0x8 => :LC_IDENT,
0x9 => :LC_FVMFILE,
0xa => :LC_PREPAGE,
0xb => :LC_DYSYMTAB,
0xc => :LC_LOAD_DYLIB,
0xd => :LC_ID_DYLIB,
0xe => :LC_LOAD_DYLINKER,
0xf => :LC_ID_DYLINKER,
0x10 => :LC_PREBOUND_DYLIB,
0x11 => :LC_ROUTINES,
0x12 => :LC_SUB_FRAMEWORK,
0x13 => :LC_SUB_UMBRELLA,
0x14 => :LC_SUB_CLIENT,
0x15 => :LC_SUB_LIBRARY,
0x16 => :LC_TWOLEVEL_HINTS,
0x17 => :LC_PREBIND_CKSUM,
(LC_REQ_DYLD | 0x18) => :LC_LOAD_WEAK_DYLIB,
0x19 => :LC_SEGMENT_64,
0x1a => :LC_ROUTINES_64,
0x1b => :LC_UUID,
(LC_REQ_DYLD | 0x1c) => :LC_RPATH,
0x1d => :LC_CODE_SIGNATURE,
0x1e => :LC_SEGMENT_SPLIT_INFO,
(LC_REQ_DYLD | 0x1f) => :LC_REEXPORT_DYLIB,
0x20 => :LC_LAZY_LOAD_DYLIB,
0x21 => :LC_ENCRYPTION_INFO,
0x22 => :LC_DYLD_INFO,
(LC_REQ_DYLD | 0x22) => :LC_DYLD_INFO_ONLY,
(LC_REQ_DYLD | 0x23) => :LC_LOAD_UPWARD_DYLIB,
0x24 => :LC_VERSION_MIN_MACOSX,
0x25 => :LC_VERSION_MIN_IPHONEOS,
0x26 => :LC_FUNCTION_STARTS,
0x27 => :LC_DYLD_ENVIRONMENT,
(LC_REQ_DYLD | 0x28) => :LC_MAIN,
0x29 => :LC_DATA_IN_CODE,
0x2a => :LC_SOURCE_VERSION,
0x2b => :LC_DYLIB_CODE_SIGN_DRS,
0x2c => :LC_ENCRYPTION_INFO_64,
0x2d => :LC_LINKER_OPTION,
0x2e => :LC_LINKER_OPTIMIZATION_HINT,
0x2f => :LC_VERSION_MIN_TVOS,
0x30 => :LC_VERSION_MIN_WATCHOS,
0x31 => :LC_NOTE,
0x32 => :LC_BUILD_VERSION,
(LC_REQ_DYLD | 0x33) => :LC_DYLD_EXPORTS_TRIE,
(LC_REQ_DYLD | 0x34) => :LC_DYLD_CHAINED_FIXUPS,
(LC_REQ_DYLD | 0x35) => :LC_FILESET_ENTRY,
0x36 => :LC_ATOM_INFO,
}.freeze
# association of symbol representations to load command constants
# @api private
LOAD_COMMAND_CONSTANTS = LOAD_COMMANDS.invert.freeze
# load commands responsible for loading dylibs
# @api private
DYLIB_LOAD_COMMANDS = %i[
LC_LOAD_DYLIB
LC_LOAD_WEAK_DYLIB
LC_REEXPORT_DYLIB
LC_LAZY_LOAD_DYLIB
LC_LOAD_UPWARD_DYLIB
].freeze
# load commands that can be created manually via {LoadCommand.create}
# @api private
CREATABLE_LOAD_COMMANDS = DYLIB_LOAD_COMMANDS + %i[
LC_ID_DYLIB
LC_RPATH
LC_LOAD_DYLINKER
].freeze
# association of load command symbols to string representations of classes
# @api private
LC_STRUCTURES = {
:LC_SEGMENT => "SegmentCommand",
:LC_SYMTAB => "SymtabCommand",
# "obsolete"
:LC_SYMSEG => "SymsegCommand",
# seems obsolete, but not documented as such
:LC_THREAD => "ThreadCommand",
:LC_UNIXTHREAD => "ThreadCommand",
# "obsolete"
:LC_LOADFVMLIB => "FvmlibCommand",
# "obsolete"
:LC_IDFVMLIB => "FvmlibCommand",
# "obsolete"
:LC_IDENT => "IdentCommand",
# "reserved for internal use only"
:LC_FVMFILE => "FvmfileCommand",
# "reserved for internal use only", no public struct
:LC_PREPAGE => "LoadCommand",
:LC_DYSYMTAB => "DysymtabCommand",
:LC_LOAD_DYLIB => "DylibUseCommand",
:LC_ID_DYLIB => "DylibCommand",
:LC_LOAD_DYLINKER => "DylinkerCommand",
:LC_ID_DYLINKER => "DylinkerCommand",
:LC_PREBOUND_DYLIB => "PreboundDylibCommand",
:LC_ROUTINES => "RoutinesCommand",
:LC_SUB_FRAMEWORK => "SubFrameworkCommand",
:LC_SUB_UMBRELLA => "SubUmbrellaCommand",
:LC_SUB_CLIENT => "SubClientCommand",
:LC_SUB_LIBRARY => "SubLibraryCommand",
:LC_TWOLEVEL_HINTS => "TwolevelHintsCommand",
:LC_PREBIND_CKSUM => "PrebindCksumCommand",
:LC_LOAD_WEAK_DYLIB => "DylibUseCommand",
:LC_SEGMENT_64 => "SegmentCommand64",
:LC_ROUTINES_64 => "RoutinesCommand64",
:LC_UUID => "UUIDCommand",
:LC_RPATH => "RpathCommand",
:LC_CODE_SIGNATURE => "LinkeditDataCommand",
:LC_SEGMENT_SPLIT_INFO => "LinkeditDataCommand",
:LC_REEXPORT_DYLIB => "DylibCommand",
:LC_LAZY_LOAD_DYLIB => "DylibCommand",
:LC_ENCRYPTION_INFO => "EncryptionInfoCommand",
:LC_DYLD_INFO => "DyldInfoCommand",
:LC_DYLD_INFO_ONLY => "DyldInfoCommand",
:LC_LOAD_UPWARD_DYLIB => "DylibCommand",
:LC_VERSION_MIN_MACOSX => "VersionMinCommand",
:LC_VERSION_MIN_IPHONEOS => "VersionMinCommand",
:LC_FUNCTION_STARTS => "LinkeditDataCommand",
:LC_DYLD_ENVIRONMENT => "DylinkerCommand",
:LC_MAIN => "EntryPointCommand",
:LC_DATA_IN_CODE => "LinkeditDataCommand",
:LC_SOURCE_VERSION => "SourceVersionCommand",
:LC_DYLIB_CODE_SIGN_DRS => "LinkeditDataCommand",
:LC_ENCRYPTION_INFO_64 => "EncryptionInfoCommand64",
:LC_LINKER_OPTION => "LinkerOptionCommand",
:LC_LINKER_OPTIMIZATION_HINT => "LinkeditDataCommand",
:LC_VERSION_MIN_TVOS => "VersionMinCommand",
:LC_VERSION_MIN_WATCHOS => "VersionMinCommand",
:LC_NOTE => "NoteCommand",
:LC_BUILD_VERSION => "BuildVersionCommand",
:LC_DYLD_EXPORTS_TRIE => "LinkeditDataCommand",
:LC_DYLD_CHAINED_FIXUPS => "LinkeditDataCommand",
:LC_FILESET_ENTRY => "FilesetEntryCommand",
:LC_ATOM_INFO => "LinkeditDataCommand",
}.freeze
# association of segment name symbols to names
# @api private
SEGMENT_NAMES = {
:SEG_PAGEZERO => "__PAGEZERO",
:SEG_TEXT => "__TEXT",
:SEG_TEXT_EXEC => "__TEXT_EXEC",
:SEG_DATA => "__DATA",
:SEG_DATA_CONST => "__DATA_CONST",
:SEG_OBJC => "__OBJC",
:SEG_OBJC_CONST => "__OBJC_CONST",
:SEG_ICON => "__ICON",
:SEG_LINKEDIT => "__LINKEDIT",
:SEG_LINKINFO => "__LINKINFO",
:SEG_UNIXSTACK => "__UNIXSTACK",
:SEG_IMPORT => "__IMPORT",
:SEG_KLD => "__KLD",
:SEG_KLDDATA => "__KLDDATA",
:SEG_HIB => "__HIB",
:SEG_VECTORS => "__VECTORS",
:SEG_LAST => "__LAST",
:SEG_LASTDATA_CONST => "__LASTDATA_CONST",
:SEG_PRELINK_TEXT => "__PRELINK_TEXT",
:SEG_PRELINK_INFO => "__PRELINK_INFO",
:SEG_CTF => "__CTF",
:SEG_AUTH => "__AUTH",
:SEG_AUTH_CONST => "__AUTH_CONST",
}.freeze
# association of segment flag symbols to values
# @api private
SEGMENT_FLAGS = {
:SG_HIGHVM => 0x1,
:SG_FVMLIB => 0x2,
:SG_NORELOC => 0x4,
:SG_PROTECTED_VERSION_1 => 0x8,
:SG_READ_ONLY => 0x10,
}.freeze
# association of dylib use flag symbols to values
# @api private
DYLIB_USE_FLAGS = {
:DYLIB_USE_WEAK_LINK => 0x1,
:DYLIB_USE_REEXPORT => 0x2,
:DYLIB_USE_UPWARD => 0x4,
:DYLIB_USE_DELAYED_INIT => 0x8,
}.freeze
# the marker used to denote a newer style dylib use command.
# the value is the timestamp 24 January 1984 18:12:16
# @api private
DYLIB_USE_MARKER = 0x1a741800
# The top-level Mach-O load command structure.
#
# This is the most generic load command -- only the type ID and size are
# represented. Used when a more specific class isn't available or isn't implemented.
class LoadCommand < MachOStructure
# @return [MachO::MachOView, nil] the raw view associated with the load command,
# or nil if the load command was created via {create}.
field :view, :view
# @return [Integer] the load command's type ID
field :cmd, :uint32
# @return [Integer] the size of the load command, in bytes
field :cmdsize, :uint32
# Instantiates a new LoadCommand given a view into its origin Mach-O
# @param view [MachO::MachOView] the load command's raw view
# @return [LoadCommand] the new load command
# @api private
def self.new_from_bin(view)
bin = view.raw_data.slice(view.offset, bytesize)
format = Utils.specialize_format(self.format, view.endianness)
new(view, *bin.unpack(format))
end
# Creates a new (viewless) command corresponding to the symbol provided
# @param cmd_sym [Symbol] the symbol of the load command being created
# @param args [Array] the arguments for the load command being created
def self.create(cmd_sym, *args)
raise LoadCommandNotCreatableError, cmd_sym unless CREATABLE_LOAD_COMMANDS.include?(cmd_sym)
klass = LoadCommands.const_get LC_STRUCTURES[cmd_sym]
cmd = LOAD_COMMAND_CONSTANTS[cmd_sym]
# cmd will be filled in, view and cmdsize will be left unpopulated
klass_arity = klass.min_args - 3
# macOS 15 introduces a new dylib load command that adds a flags field to the end.
# It uses the same commands with it dynamically being created if the dylib has a flags field
if klass == DylibUseCommand && (args[1] != DYLIB_USE_MARKER || args.size <= DylibCommand.min_args - 3)
klass = DylibCommand
klass_arity = klass.min_args - 3
end
raise LoadCommandCreationArityError.new(cmd_sym, klass_arity, args.size) if klass_arity > args.size
klass.new(nil, cmd, nil, *args)
end
# @return [Boolean] whether the load command can be serialized
def serializable?
CREATABLE_LOAD_COMMANDS.include?(LOAD_COMMANDS[cmd])
end
# @param context [SerializationContext] the context
# to serialize into
# @return [String, nil] the serialized fields of the load command, or nil
# if the load command can't be serialized
# @api private
def serialize(context)
raise LoadCommandNotSerializableError, LOAD_COMMANDS[cmd] unless serializable?
format = Utils.specialize_format(self.class.format, context.endianness)
[cmd, self.class.bytesize].pack(format)
end
# @return [Integer] the load command's offset in the source file
# @deprecated use {#view} instead
def offset
view.offset
end
# @return [Symbol, nil] a symbol representation of the load command's
# type ID, or nil if the ID doesn't correspond to a known load command class
def type
LOAD_COMMANDS[cmd]
end
alias to_sym type
# @return [String] a string representation of the load command's
# identifying number
def to_s
type.to_s
end
# @return [Hash] a hash representation of this load command
# @note Children should override this to include additional information.
def to_h
{
"view" => view.to_h,
"cmd" => cmd,
"cmdsize" => cmdsize,
"type" => type,
}.merge super
end
# Represents a Load Command string. A rough analogue to the lc_str
# struct used internally by OS X. This class allows ruby-macho to
# pretend that strings stored in LCs are immediately available without
# explicit operations on the raw Mach-O data.
class LCStr
# @param lc [LoadCommand] the load command
# @param lc_str [Integer, String] the offset to the beginning of the
# string, or the string itself if not being initialized with a view.
# @raise [MachO::LCStrMalformedError] if the string is malformed
# @todo devise a solution such that the `lc_str` parameter is not
# interpreted differently depending on `lc.view`. The current behavior
# is a hack to allow viewless load command creation.
# @api private
def initialize(lc, lc_str)
view = lc.view
if view
lc_str_abs = view.offset + lc_str
lc_end = view.offset + lc.cmdsize - 1
raw_string = view.raw_data.slice(lc_str_abs..lc_end)
@string, null_byte, _padding = raw_string.partition("\x00")
raise LCStrMalformedError, lc if null_byte.empty?
@string_offset = lc_str
else
@string = lc_str
@string_offset = 0
end
end
# @return [String] a string representation of the LCStr
def to_s
@string
end
# @return [Integer] the offset to the beginning of the string in the
# load command
def to_i
@string_offset
end
# @return [Hash] a hash representation of this {LCStr}.
def to_h
{
"string" => to_s,
"offset" => to_i,
}
end
end
# Represents the contextual information needed by a load command to
# serialize itself correctly into a binary string.
class SerializationContext
# @return [Symbol] the endianness of the serialized load command
attr_reader :endianness
# @return [Integer] the constant alignment value used to pad the
# serialized load command
attr_reader :alignment
# @param macho [MachO::MachOFile] the file to contextualize
# @return [SerializationContext] the
# resulting context
def self.context_for(macho)
new(macho.endianness, macho.alignment)
end
# @param endianness [Symbol] the endianness of the context
# @param alignment [Integer] the alignment of the context
# @api private
def initialize(endianness, alignment)
@endianness = endianness
@alignment = alignment
end
end
end
# A load command containing a single 128-bit unique random number
# identifying an object produced by static link editor. Corresponds to
# LC_UUID.
class UUIDCommand < LoadCommand
# @return [Array<Integer>] the UUID
field :uuid, :string, :size => 16, :unpack => "C16"
# @return [String] a string representation of the UUID
def uuid_string
hexes = uuid.map { |elem| "%02<elem>x" % { :elem => elem } }
segs = [
hexes[0..3].join, hexes[4..5].join, hexes[6..7].join,
hexes[8..9].join, hexes[10..15].join
]
segs.join("-")
end
# @return [String] an alias for uuid_string
def to_s
uuid_string
end
# @return [Hash] returns a hash representation of this {UUIDCommand}
def to_h
{
"uuid" => uuid,
"uuid_string" => uuid_string,
}.merge super
end
end
# A load command indicating that part of this file is to be mapped into
# the task's address space. Corresponds to LC_SEGMENT.
class SegmentCommand < LoadCommand
# @return [String] the name of the segment
field :segname, :string, :padding => :null, :size => 16, :to_s => true
# @return [Integer] the memory address of the segment
field :vmaddr, :uint32
# @return [Integer] the memory size of the segment
field :vmsize, :uint32
# @return [Integer] the file offset of the segment
field :fileoff, :uint32
# @return [Integer] the amount to map from the file
field :filesize, :uint32
# @return [Integer] the maximum VM protection
field :maxprot, :int32
# @return [Integer] the initial VM protection
field :initprot, :int32
# @return [Integer] the number of sections in the segment
field :nsects, :uint32
# @return [Integer] any flags associated with the segment
field :flags, :uint32
# All sections referenced within this segment.
# @return [Array<MachO::Sections::Section>] if the Mach-O is 32-bit
# @return [Array<MachO::Sections::Section64>] if the Mach-O is 64-bit
def sections
klass = case self
when SegmentCommand64
MachO::Sections::Section64
when SegmentCommand
MachO::Sections::Section
end
offset = view.offset + self.class.bytesize
length = nsects * klass.bytesize
bins = view.raw_data[offset, length]
bins.unpack("a#{klass.bytesize}" * nsects).map do |bin|
klass.new_from_bin(view.endianness, bin)
end
end
# @example
# puts "this segment relocated in/to it" if sect.flag?(:SG_NORELOC)
# @param flag [Symbol] a segment flag symbol
# @return [Boolean] true if `flag` is present in the segment's flag field
def flag?(flag)
flag = SEGMENT_FLAGS[flag]
return false if flag.nil?
flags & flag == flag
end
# Guesses the alignment of the segment.
# @return [Integer] the guessed alignment, as a power of 2
# @note See `guess_align` in `cctools/misc/lipo.c`
def guess_align
return Sections::MAX_SECT_ALIGN if vmaddr.zero?
align = 0
segalign = 1
while (segalign & vmaddr).zero?
segalign <<= 1
align += 1
end
return 2 if align < 2
return Sections::MAX_SECT_ALIGN if align > Sections::MAX_SECT_ALIGN
align
end
# @return [Hash] a hash representation of this {SegmentCommand}
def to_h
{
"segname" => segname,
"vmaddr" => vmaddr,
"vmsize" => vmsize,
"fileoff" => fileoff,
"filesize" => filesize,
"maxprot" => maxprot,
"initprot" => initprot,
"nsects" => nsects,
"flags" => flags,
"sections" => sections.map(&:to_h),
}.merge super
end
end
# A load command indicating that part of this file is to be mapped into
# the task's address space. Corresponds to LC_SEGMENT_64.
class SegmentCommand64 < SegmentCommand
# @return [Integer] the memory address of the segment
field :vmaddr, :uint64
# @return [Integer] the memory size of the segment
field :vmsize, :uint64
# @return [Integer] the file offset of the segment
field :fileoff, :uint64
# @return [Integer] the amount to map from the file
field :filesize, :uint64
end
# A load command representing some aspect of shared libraries, depending
# on filetype. Corresponds to LC_ID_DYLIB, LC_LOAD_DYLIB,
# LC_LOAD_WEAK_DYLIB, and LC_REEXPORT_DYLIB.
class DylibCommand < LoadCommand
# @return [LCStr] the library's path
# name as an LCStr
field :name, :lcstr, :to_s => true
# @return [Integer] the library's build time stamp
field :timestamp, :uint32
# @return [Integer] the library's current version number
field :current_version, :uint32
# @return [Integer] the library's compatibility version number
field :compatibility_version, :uint32
# @example
# puts "this dylib is weakly loaded" if dylib_command.flag?(:DYLIB_USE_WEAK_LINK)
# @param flag [Symbol] a dylib use command flag symbol
# @return [Boolean] true if `flag` applies to this dylib command
def flag?(flag)
case cmd
when LOAD_COMMAND_CONSTANTS[:LC_LOAD_WEAK_DYLIB]
flag == :DYLIB_USE_WEAK_LINK
when LOAD_COMMAND_CONSTANTS[:LC_REEXPORT_DYLIB]
flag == :DYLIB_USE_REEXPORT
when LOAD_COMMAND_CONSTANTS[:LC_LOAD_UPWARD_DYLIB]
flag == :DYLIB_USE_UPWARD
else
false
end
end
# @param context [SerializationContext]
# the context
# @return [String] the serialized fields of the load command
# @api private
def serialize(context)
format = Utils.specialize_format(self.class.format, context.endianness)
string_payload, string_offsets = Utils.pack_strings(self.class.bytesize,
context.alignment,
:name => name.to_s)
cmdsize = self.class.bytesize + string_payload.bytesize
[cmd, cmdsize, string_offsets[:name], timestamp, current_version,
compatibility_version].pack(format) + string_payload
end
# @return [Hash] a hash representation of this {DylibCommand}
def to_h
{
"name" => name.to_h,
"timestamp" => timestamp,
"current_version" => current_version,
"compatibility_version" => compatibility_version,
}.merge super
end
end
# The newer format of load command representing some aspect of shared libraries,
# depending on filetype. Corresponds to LC_LOAD_DYLIB or LC_LOAD_WEAK_DYLIB.
class DylibUseCommand < DylibCommand
# @return [Integer] any flags associated with this dylib use command
field :flags, :uint32
alias marker timestamp
# Instantiates a new DylibCommand or DylibUseCommand.
# macOS 15 and later use a new format for dylib commands (DylibUseCommand),
# which is determined based on a special timestamp and the name offset.
# @param view [MachO::MachOView] the load command's raw view
# @return [DylibCommand] the new dylib load command
# @api private
def self.new_from_bin(view)
dylib_command = DylibCommand.new_from_bin(view)
if dylib_command.timestamp == DYLIB_USE_MARKER &&
dylib_command.name.to_i == DylibUseCommand.bytesize
super(view)
else
dylib_command
end
end
# @example
# puts "this dylib is weakly loaded" if dylib_command.flag?(:DYLIB_USE_WEAK_LINK)
# @param flag [Symbol] a dylib use command flag symbol
# @return [Boolean] true if `flag` applies to this dylib command
def flag?(flag)
flag = DYLIB_USE_FLAGS[flag]
return false if flag.nil?
flags & flag == flag
end
# @param context [SerializationContext]
# the context
# @return [String] the serialized fields of the load command
# @api private
def serialize(context)
format = Utils.specialize_format(self.class.format, context.endianness)
string_payload, string_offsets = Utils.pack_strings(self.class.bytesize,
context.alignment,
:name => name.to_s)
cmdsize = self.class.bytesize + string_payload.bytesize
[cmd, cmdsize, string_offsets[:name], marker, current_version,
compatibility_version, flags].pack(format) + string_payload
end
# @return [Hash] a hash representation of this {DylibUseCommand}
def to_h
{
"flags" => flags,
}.merge super
end
end
# A load command representing some aspect of the dynamic linker, depending
# on filetype. Corresponds to LC_ID_DYLINKER, LC_LOAD_DYLINKER, and
# LC_DYLD_ENVIRONMENT.
class DylinkerCommand < LoadCommand
# @return [LCStr] the dynamic linker's
# path name as an LCStr
field :name, :lcstr, :to_s => true
# @param context [SerializationContext]
# the context
# @return [String] the serialized fields of the load command
# @api private
def serialize(context)
format = Utils.specialize_format(self.class.format, context.endianness)
string_payload, string_offsets = Utils.pack_strings(self.class.bytesize,
context.alignment,
:name => name.to_s)
cmdsize = self.class.bytesize + string_payload.bytesize
[cmd, cmdsize, string_offsets[:name]].pack(format) + string_payload
end
# @return [Hash] a hash representation of this {DylinkerCommand}
def to_h
{
"name" => name.to_h,
}.merge super
end
end
# A load command used to indicate dynamic libraries used in prebinding.
# Corresponds to LC_PREBOUND_DYLIB.
class PreboundDylibCommand < LoadCommand
# @return [LCStr] the library's path
# name as an LCStr
field :name, :lcstr, :to_s => true
# @return [Integer] the number of modules in the library
field :nmodules, :uint32
# @return [Integer] a bit vector of linked modules
field :linked_modules, :uint32
# @return [Hash] a hash representation of this {PreboundDylibCommand}
def to_h
{
"name" => name.to_h,
"nmodules" => nmodules,
"linked_modules" => linked_modules,
}.merge super
end
end
# A load command used to represent threads.
# @note cctools-870 and onwards have all fields of thread_command commented
# out except the common ones (cmd, cmdsize)
class ThreadCommand < LoadCommand
end
# A load command containing the address of the dynamic shared library
# initialization routine and an index into the module table for the module
# that defines the routine. Corresponds to LC_ROUTINES.
class RoutinesCommand < LoadCommand
# @return [Integer] the address of the initialization routine
field :init_address, :uint32
# @return [Integer] the index into the module table that the init routine
# is defined in
field :init_module, :uint32
# @return [void]
field :reserved1, :uint32
# @return [void]
field :reserved2, :uint32
# @return [void]
field :reserved3, :uint32
# @return [void]
field :reserved4, :uint32
# @return [void]
field :reserved5, :uint32
# @return [void]
field :reserved6, :uint32
# @return [Hash] a hash representation of this {RoutinesCommand}
def to_h
{
"init_address" => init_address,
"init_module" => init_module,
"reserved1" => reserved1,
"reserved2" => reserved2,
"reserved3" => reserved3,
"reserved4" => reserved4,
"reserved5" => reserved5,
"reserved6" => reserved6,
}.merge super
end
end
# A load command containing the address of the dynamic shared library
# initialization routine and an index into the module table for the module
# that defines the routine. Corresponds to LC_ROUTINES_64.
class RoutinesCommand64 < RoutinesCommand
# @return [Integer] the address of the initialization routine
field :init_address, :uint64
# @return [Integer] the index into the module table that the init routine
# is defined in
field :init_module, :uint64
# @return [void]
field :reserved1, :uint64
# @return [void]
field :reserved2, :uint64
# @return [void]
field :reserved3, :uint64
# @return [void]
field :reserved4, :uint64
# @return [void]
field :reserved5, :uint64
# @return [void]
field :reserved6, :uint64
end
# A load command signifying membership of a subframework containing the name
# of an umbrella framework. Corresponds to LC_SUB_FRAMEWORK.
class SubFrameworkCommand < LoadCommand
# @return [LCStr] the umbrella framework name as an LCStr
field :umbrella, :lcstr, :to_s => true
# @return [Hash] a hash representation of this {SubFrameworkCommand}
def to_h
{
"umbrella" => umbrella.to_h,
}.merge super
end
end
# A load command signifying membership of a subumbrella containing the name
# of an umbrella framework. Corresponds to LC_SUB_UMBRELLA.
class SubUmbrellaCommand < LoadCommand
# @return [LCStr] the subumbrella framework name as an LCStr
field :sub_umbrella, :lcstr, :to_s => true
# @return [Hash] a hash representation of this {SubUmbrellaCommand}
def to_h
{
"sub_umbrella" => sub_umbrella.to_h,
}.merge super
end
end
# A load command signifying a sublibrary of a shared library. Corresponds
# to LC_SUB_LIBRARY.
class SubLibraryCommand < LoadCommand
# @return [LCStr] the sublibrary name as an LCStr
field :sub_library, :lcstr, :to_s => true
# @return [Hash] a hash representation of this {SubLibraryCommand}
def to_h
{
"sub_library" => sub_library.to_h,
}.merge super
end
end
# A load command signifying a shared library that is a subframework of
# an umbrella framework. Corresponds to LC_SUB_CLIENT.
class SubClientCommand < LoadCommand
# @return [LCStr] the subclient name as an LCStr
field :sub_client, :lcstr, :to_s => true
# @return [Hash] a hash representation of this {SubClientCommand}
def to_h
{
"sub_client" => sub_client.to_h,
}.merge super
end
end
# A load command containing the offsets and sizes of the link-edit 4.3BSD
# "stab" style symbol table information. Corresponds to LC_SYMTAB.
class SymtabCommand < LoadCommand
# @return [Integer] the symbol table's offset
field :symoff, :uint32
# @return [Integer] the number of symbol table entries
field :nsyms, :uint32
# @return [Integer] the string table's offset
field :stroff, :uint32
# @return [Integer] the string table size in bytes
field :strsize, :uint32
# @return [Hash] a hash representation of this {SymtabCommand}
def to_h
{
"symoff" => symoff,
"nsyms" => nsyms,
"stroff" => stroff,
"strsize" => strsize,
}.merge super
end
end
# A load command containing symbolic information needed to support data
# structures used by the dynamic link editor. Corresponds to LC_DYSYMTAB.
class DysymtabCommand < LoadCommand
# @return [Integer] the index to local symbols
field :ilocalsym, :uint32
# @return [Integer] the number of local symbols
field :nlocalsym, :uint32
# @return [Integer] the index to externally defined symbols
field :iextdefsym, :uint32
# @return [Integer] the number of externally defined symbols
field :nextdefsym, :uint32
# @return [Integer] the index to undefined symbols
field :iundefsym, :uint32
# @return [Integer] the number of undefined symbols
field :nundefsym, :uint32
# @return [Integer] the file offset to the table of contents
field :tocoff, :uint32
# @return [Integer] the number of entries in the table of contents
field :ntoc, :uint32
# @return [Integer] the file offset to the module table
field :modtaboff, :uint32
# @return [Integer] the number of entries in the module table
field :nmodtab, :uint32
# @return [Integer] the file offset to the referenced symbol table
field :extrefsymoff, :uint32
# @return [Integer] the number of entries in the referenced symbol table
field :nextrefsyms, :uint32
# @return [Integer] the file offset to the indirect symbol table
field :indirectsymoff, :uint32
# @return [Integer] the number of entries in the indirect symbol table
field :nindirectsyms, :uint32
# @return [Integer] the file offset to the external relocation entries
field :extreloff, :uint32
# @return [Integer] the number of external relocation entries
field :nextrel, :uint32
# @return [Integer] the file offset to the local relocation entries
field :locreloff, :uint32
# @return [Integer] the number of local relocation entries
field :nlocrel, :uint32
# @return [Hash] a hash representation of this {DysymtabCommand}
def to_h
{
"ilocalsym" => ilocalsym,
"nlocalsym" => nlocalsym,
"iextdefsym" => iextdefsym,
"nextdefsym" => nextdefsym,
"iundefsym" => iundefsym,
"nundefsym" => nundefsym,
"tocoff" => tocoff,
"ntoc" => ntoc,
"modtaboff" => modtaboff,
"nmodtab" => nmodtab,
"extrefsymoff" => extrefsymoff,
"nextrefsyms" => nextrefsyms,
"indirectsymoff" => indirectsymoff,
"nindirectsyms" => nindirectsyms,
"extreloff" => extreloff,
"nextrel" => nextrel,
"locreloff" => locreloff,
"nlocrel" => nlocrel,
}.merge super
end
end
# A load command containing the offset and number of hints in the two-level
# namespace lookup hints table. Corresponds to LC_TWOLEVEL_HINTS.
class TwolevelHintsCommand < LoadCommand
# @return [Integer] the offset to the hint table
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist.rb | # encoding: utf-8
# = plist
#
# This is the main file for plist. Everything interesting happens in
# Plist and Plist::Emit.
#
# Copyright 2006-2010 Ben Bleything and Patrick May
# Distributed under the MIT License
#
require 'cgi'
require 'stringio'
require_relative 'plist/generator'
require_relative 'plist/parser'
require_relative 'plist/version'
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist/version.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist/version.rb | # encoding: utf-8
module Plist
VERSION = '3.7.2'.freeze
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist/parser.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist/parser.rb | # encoding: utf-8
# = plist
#
# Copyright 2006-2010 Ben Bleything and Patrick May
# Distributed under the MIT License
#
# Plist parses Mac OS X xml property list files into ruby data structures.
#
# === Load a plist file
# This is the main point of the library:
#
# r = Plist.parse_xml(filename_or_xml)
module Plist
# Raised when an element is not implemented
class UnimplementedElementError < RuntimeError; end
# Note that I don't use these two elements much:
#
# + Date elements are returned as DateTime objects.
# + Data elements are implemented as Tempfiles
#
# Plist.parse_xml will blow up if it encounters a Date element.
# If you encounter such an error, or if you have a Date element which
# can't be parsed into a Time object, please create an issue
# attaching your plist file at https://github.com/patsplat/plist/issues
# so folks can implement the proper support.
#
# By default, <data> will be assumed to be a marshaled Ruby object and
# interpreted with <tt>Marshal.load</tt>. Pass <tt>marshal: false</tt>
# to disable this behavior and return the raw binary data as an IO
# object instead.
def self.parse_xml(filename_or_xml, options={})
listener = Listener.new(options)
# parser = REXML::Parsers::StreamParser.new(File.new(filename), listener)
parser = StreamParser.new(filename_or_xml, listener)
parser.parse
listener.result
end
class Listener
# include REXML::StreamListener
attr_accessor :result, :open
def initialize(options={})
@result = nil
@open = []
@options = { :marshal => true }.merge(options).freeze
end
def tag_start(name, attributes)
@open.push PTag.mappings[name].new(@options)
end
def text(contents)
if @open.last
@open.last.text ||= ''.dup
@open.last.text.concat(contents)
end
end
def tag_end(name)
last = @open.pop
if @open.empty?
@result = last.to_ruby
else
@open.last.children.push last
end
end
end
class StreamParser
def initialize(plist_data_or_file, listener)
if plist_data_or_file.respond_to? :read
@xml = plist_data_or_file.read
elsif File.exist? plist_data_or_file
@xml = File.read(plist_data_or_file)
else
@xml = plist_data_or_file
end
@listener = listener
end
TEXT = /([^<]+)/
CDATA = /<!\[CDATA\[(.*?)\]\]>/
XMLDECL_PATTERN = /<\?xml\s+(.*?)\?>*/m
DOCTYPE_PATTERN = /\s*<!DOCTYPE\s+(.*?)(\[|>)/m
COMMENT_START = /\A<!--/
COMMENT_END = /.*?-->/m
UNIMPLEMENTED_ERROR = 'Unimplemented element. ' \
'Consider reporting via https://github.com/patsplat/plist/issues'
def parse
plist_tags = PTag.mappings.keys.join('|')
start_tag = /<(#{plist_tags})([^>]*)>/i
end_tag = /<\/(#{plist_tags})[^>]*>/i
require 'strscan'
@scanner = StringScanner.new(@xml)
until @scanner.eos?
if @scanner.scan(COMMENT_START)
@scanner.scan(COMMENT_END)
elsif @scanner.scan(XMLDECL_PATTERN)
encoding = parse_encoding_from_xml_declaration(@scanner[1])
next if encoding.nil?
# use the specified encoding for the rest of the file
next unless String.method_defined?(:force_encoding)
@scanner.string = @scanner.rest.force_encoding(encoding)
elsif @scanner.scan(DOCTYPE_PATTERN)
next
elsif @scanner.scan(start_tag)
@listener.tag_start(@scanner[1], nil)
if (@scanner[2] =~ /\/$/)
@listener.tag_end(@scanner[1])
end
elsif @scanner.scan(TEXT)
@listener.text(@scanner[1])
elsif @scanner.scan(CDATA)
@listener.text(@scanner[1])
elsif @scanner.scan(end_tag)
@listener.tag_end(@scanner[1])
else
raise UnimplementedElementError.new(UNIMPLEMENTED_ERROR)
end
end
end
private
def parse_encoding_from_xml_declaration(xml_declaration)
return unless defined?(Encoding)
xml_encoding = xml_declaration.match(/(?:\A|\s)encoding=(?:"(.*?)"|'(.*?)')(?:\s|\Z)/)
return if xml_encoding.nil?
begin
Encoding.find(xml_encoding[1])
rescue ArgumentError
nil
end
end
end
class PTag
def self.mappings
@mappings ||= {}
end
def self.inherited(sub_class)
key = sub_class.to_s.downcase
key.gsub!(/^plist::/, '')
key.gsub!(/^p/, '') unless key == "plist"
mappings[key] = sub_class
end
attr_accessor :text, :children, :options
def initialize(options)
@children = []
@options = options
end
def to_ruby
raise "Unimplemented: " + self.class.to_s + "#to_ruby on #{self.inspect}"
end
end
class PList < PTag
def to_ruby
children.first.to_ruby if children.first
end
end
class PDict < PTag
def to_ruby
dict = {}
key = nil
children.each do |c|
if key.nil?
key = c.to_ruby
else
dict[key] = c.to_ruby
key = nil
end
end
dict
end
end
class PKey < PTag
def to_ruby
CGI.unescapeHTML(text || '')
end
end
class PString < PTag
def to_ruby
CGI.unescapeHTML(text || '')
end
end
class PArray < PTag
def to_ruby
children.collect do |c|
c.to_ruby
end
end
end
class PInteger < PTag
def to_ruby
text.to_i
end
end
class PTrue < PTag
def to_ruby
true
end
end
class PFalse < PTag
def to_ruby
false
end
end
class PReal < PTag
def to_ruby
text.to_f
end
end
require 'date'
class PDate < PTag
def to_ruby
DateTime.parse(text)
end
end
class PData < PTag
def to_ruby
# unpack("m")[0] is equivalent to Base64.decode64
data = text.gsub(/\s+/, '').unpack("m")[0] unless text.nil?
begin
return Marshal.load(data) if options[:marshal]
rescue Exception
end
io = StringIO.new
io.write data
io.rewind
io
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/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist/generator.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/plist-3.7.2/lib/plist/generator.rb | # encoding: utf-8
# = plist
#
# Copyright 2006-2010 Ben Bleything and Patrick May
# Distributed under the MIT License
#
module Plist
# === Create a plist
# You can dump an object to a plist in one of two ways:
#
# * <tt>Plist::Emit.dump(obj)</tt>
# * <tt>obj.to_plist</tt>
# * This requires that you mixin the <tt>Plist::Emit</tt> module, which is already done for +Array+ and +Hash+.
#
# The following Ruby classes are converted into native plist types:
# Array, Bignum, Date, DateTime, Fixnum, Float, Hash, Integer, String, Symbol, Time, true, false
# * +Array+ and +Hash+ are both recursive; their elements will be converted into plist nodes inside the <array> and <dict> containers (respectively).
# * +IO+ (and its descendants) and +StringIO+ objects are read from and their contents placed in a <data> element.
# * User classes may implement +to_plist_node+ to dictate how they should be serialized; otherwise the object will be passed to <tt>Marshal.dump</tt> and the result placed in a <data> element.
#
# For detailed usage instructions, refer to USAGE[link:files/docs/USAGE.html] and the methods documented below.
module Emit
DEFAULT_INDENT = "\t"
# Helper method for injecting into classes. Calls <tt>Plist::Emit.dump</tt> with +self+.
def to_plist(envelope = true, options = {})
Plist::Emit.dump(self, envelope, options)
end
# Helper method for injecting into classes. Calls <tt>Plist::Emit.save_plist</tt> with +self+.
def save_plist(filename, options = {})
Plist::Emit.save_plist(self, filename, options)
end
# The following Ruby classes are converted into native plist types:
# Array, Bignum, Date, DateTime, Fixnum, Float, Hash, Integer, String, Symbol, Time
#
# Write us (via RubyForge) if you think another class can be coerced safely into one of the expected plist classes.
#
# +IO+ and +StringIO+ objects are encoded and placed in <data> elements; other objects are <tt>Marshal.dump</tt>'ed unless they implement +to_plist_node+.
#
# The +envelope+ parameters dictates whether or not the resultant plist fragment is wrapped in the normal XML/plist header and footer. Set it to false if you only want the fragment.
def self.dump(obj, envelope = true, options = {})
options = { :indent => DEFAULT_INDENT }.merge(options)
output = PlistBuilder.new(options[:indent]).build(obj)
output = wrap(output) if envelope
output
end
# Writes the serialized object's plist to the specified filename.
def self.save_plist(obj, filename, options = {})
File.open(filename, 'wb') do |f|
f.write(obj.to_plist(true, options))
end
end
private
class PlistBuilder
def initialize(indent_str)
@indent_str = indent_str.to_s
end
def build(element, level=0)
if element.respond_to? :to_plist_node
element.to_plist_node
else
case element
when Array
if element.empty?
tag('array', nil, level)
else
tag('array', nil, level) {
element.collect {|e| build(e, level + 1) }.join
}
end
when Hash
if element.empty?
tag('dict', nil, level)
else
tag('dict', '', level) do
element.sort_by{|k,v| k.to_s }.collect do |k,v|
tag('key', CGI.escapeHTML(k.to_s), level + 1) +
build(v, level + 1)
end.join
end
end
when true, false
tag(element, nil, level)
when Time
tag('date', element.utc.strftime('%Y-%m-%dT%H:%M:%SZ'), level)
when Date # also catches DateTime
tag('date', element.strftime('%Y-%m-%dT%H:%M:%SZ'), level)
when String, Symbol, Integer, Float
tag(element_type(element), CGI.escapeHTML(element.to_s), level)
when IO, StringIO
data = element.tap(&:rewind).read
data_tag(data, level)
else
data = Marshal.dump(element)
comment_tag('The <data> element below contains a Ruby object which has been serialized with Marshal.dump.') +
data_tag(data, level)
end
end
end
private
def tag(type, contents, level, &block)
if block_given?
indent("<#{type}>\n", level) +
block.call +
indent("</#{type}>\n", level)
elsif contents.to_s.empty?
indent("<#{type}/>\n", level)
else
indent("<#{type}>#{contents.to_s}</#{type}>\n", level)
end
end
def data_tag(data, level)
# note that apple plists are wrapped at a different length then
# what ruby's pack wraps by default.
tag('data', nil, level) do
[data].pack("m") # equivalent to Base64.encode64(data)
.gsub(/\s+/, '')
.scan(/.{1,68}/o)
.collect { |line| indent(line, level) }
.join("\n")
.concat("\n")
end
end
def indent(str, level)
@indent_str.to_s * level + str
end
def element_type(item)
case item
when String, Symbol
'string'
when Integer
'integer'
when Float
'real'
else
raise "Don't know about this data type... something must be wrong!"
end
end
def comment_tag(content)
return "<!-- #{content} -->\n"
end
end
def self.wrap(contents)
output = '<?xml version="1.0" encoding="UTF-8"?>' + "\n"
output << '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' + "\n"
output << '<plist version="1.0">' + "\n"
output << contents
output << '</plist>' + "\n"
output
end
end
end
class Array #:nodoc:
include Plist::Emit
end
class Hash #:nodoc:
include Plist::Emit
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/sorbet-runtime.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/sorbet-runtime.rb | # frozen_string_literal: true
# typed: true
# This file is hand-crafted to encode the dependencies. They load the whole type
# system since there is such a high chance of it being used, using an autoloader
# wouldn't buy us any startup time saving.
# Namespaces without any implementation
module T; end
module T::Helpers; end
module T::Private; end
module T::Private::Abstract; end
module T::Private::Types; end
# Each section is a group that I believe need a fixed ordering. There is also
# an ordering between groups.
# These are pre-reqs for almost everything in here.
require_relative 'types/configuration'
require_relative 'types/_types'
require_relative 'types/private/decl_state'
require_relative 'types/private/caller_utils'
require_relative 'types/private/class_utils'
require_relative 'types/private/runtime_levels'
require_relative 'types/private/methods/_methods'
require_relative 'types/sig'
require_relative 'types/helpers'
require_relative 'types/private/final'
require_relative 'types/private/sealed'
# The types themselves. First base classes
require_relative 'types/types/base'
require_relative 'types/types/typed_enumerable'
# Everything else
require_relative 'types/types/class_of'
require_relative 'types/types/enum'
require_relative 'types/types/fixed_array'
require_relative 'types/types/fixed_hash'
require_relative 'types/types/intersection'
require_relative 'types/types/noreturn'
require_relative 'types/types/anything'
require_relative 'types/types/proc'
require_relative 'types/types/attached_class'
require_relative 'types/types/self_type'
require_relative 'types/types/simple'
require_relative 'types/types/t_enum'
require_relative 'types/types/type_parameter'
require_relative 'types/types/typed_enumerator'
require_relative 'types/types/typed_enumerator_chain'
require_relative 'types/types/typed_enumerator_lazy'
require_relative 'types/types/typed_hash'
require_relative 'types/types/typed_range'
require_relative 'types/types/typed_set'
require_relative 'types/types/union'
require_relative 'types/types/untyped'
require_relative 'types/private/types/not_typed'
require_relative 'types/private/types/void'
require_relative 'types/private/types/string_holder'
require_relative 'types/private/types/type_alias'
require_relative 'types/private/types/simple_pair_union'
require_relative 'types/types/type_variable'
require_relative 'types/types/type_member'
require_relative 'types/types/type_template'
# Call validation
require_relative 'types/private/methods/modes'
require_relative 'types/private/methods/call_validation'
# Signature validation
require_relative 'types/private/methods/signature_validation'
require_relative 'types/abstract_utils'
require_relative 'types/private/abstract/validate'
# Catch all. Sort of built by `cd extn; find types -type f | grep -v test | sort`
require_relative 'types/generic'
require_relative 'types/private/abstract/declare'
require_relative 'types/private/abstract/hooks'
require_relative 'types/private/casts'
require_relative 'types/private/methods/decl_builder'
require_relative 'types/private/methods/signature'
require_relative 'types/private/retry'
require_relative 'types/utils'
require_relative 'types/boolean'
# Depends on types/utils
require_relative 'types/types/typed_array'
require_relative 'types/types/typed_module'
require_relative 'types/types/typed_class'
# Props dependencies
require_relative 'types/private/abstract/data'
require_relative 'types/private/mixins/mixins'
require_relative 'types/props/_props'
require_relative 'types/props/custom_type'
require_relative 'types/props/decorator'
require_relative 'types/props/errors'
require_relative 'types/props/plugin'
require_relative 'types/props/utils'
require_relative 'types/enum'
# Props that run sigs statically so have to be after all the others :(
require_relative 'types/props/private/setter_factory'
require_relative 'types/props/private/apply_default'
require_relative 'types/props/has_lazily_specialized_methods'
require_relative 'types/props/optional'
require_relative 'types/props/weak_constructor'
require_relative 'types/props/constructor'
require_relative 'types/props/pretty_printable'
require_relative 'types/props/private/serde_transform'
require_relative 'types/props/private/deserializer_generator'
require_relative 'types/props/private/serializer_generator'
require_relative 'types/props/serializable'
require_relative 'types/props/type_validation'
require_relative 'types/props/private/parser'
require_relative 'types/props/generated_code_validation'
require_relative 'types/struct'
require_relative 'types/compatibility_patches'
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/generic.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/generic.rb | # frozen_string_literal: true
# typed: true
# Use as a mixin with extend (`extend T::Generic`).
module T::Generic
include T::Helpers
include Kernel
### Class/Module Helpers ###
def [](*types)
self
end
def type_member(variance=:invariant, &blk)
T::Types::TypeMember.new(variance)
end
def type_template(variance=:invariant, &blk)
T::Types::TypeTemplate.new(variance)
end
def has_attached_class!(variance=:invariant, &blk); 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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/struct.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/struct.rb | # frozen_string_literal: true
# typed: true
class T::InexactStruct
include T::Props
include T::Props::Serializable
include T::Props::Constructor
end
class T::Struct < T::InexactStruct
def self.inherited(subclass)
super(subclass)
T::Private::ClassUtils.replace_method(subclass.singleton_class, :inherited, true) do |s|
super(s)
raise "#{self.name} is a subclass of T::Struct and cannot be subclassed"
end
end
end
class T::ImmutableStruct < T::InexactStruct
extend T::Sig
def self.inherited(subclass)
super(subclass)
T::Private::ClassUtils.replace_method(subclass.singleton_class, :inherited, true) do |s|
super(s)
raise "#{self.name} is a subclass of T::ImmutableStruct and cannot be subclassed"
end
end
# Matches the one in WeakConstructor, but freezes the object
sig { params(hash: T::Hash[Symbol, T.untyped]).void.checked(:never) }
def initialize(hash={})
super
freeze
end
# Matches the signature in Props, but raises since this is an immutable struct and only const is allowed
sig { params(name: Symbol, cls: T.untyped, rules: T.untyped).void }
def self.prop(name, cls, **rules)
return super if (cls.is_a?(Hash) && cls[:immutable]) || rules[:immutable]
raise "Cannot use `prop` in #{self.name} because it is an immutable struct. Use `const` instead"
end
def with(changed_props)
raise "Cannot use `with` in #{self.class.name} because it is an immutable struct"
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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/sig.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/sig.rb | # frozen_string_literal: true
# typed: strict
# Used as a mixin to any class so that you can call `sig`.
# Docs at https://sorbet.org/docs/sigs
module T::Sig
module WithoutRuntime
# At runtime, does nothing, but statically it is treated exactly the same
# as T::Sig#sig. Only use it in cases where you can't use T::Sig#sig.
def self.sig(arg0=nil, &blk); end
original_verbose = $VERBOSE
$VERBOSE = false
# At runtime, does nothing, but statically it is treated exactly the same
# as T::Sig#sig. Only use it in cases where you can't use T::Sig#sig.
T::Sig::WithoutRuntime.sig { params(arg0: T.nilable(Symbol), blk: T.proc.bind(T::Private::Methods::DeclBuilder).void).void }
def self.sig(arg0=nil, &blk); end # rubocop:disable Lint/DuplicateMethods
$VERBOSE = original_verbose
end
# Declares a method with type signatures and/or
# abstract/override/... helpers. See the documentation URL on
# {T::Helpers}
T::Sig::WithoutRuntime.sig { params(arg0: T.nilable(Symbol), blk: T.proc.bind(T::Private::Methods::DeclBuilder).void).void }
def sig(arg0=nil, &blk)
T::Private::Methods.declare_sig(self, Kernel.caller_locations(1, 1)&.first, arg0, &blk)
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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/utils.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/utils.rb | # frozen_string_literal: true
# typed: true
module T::Utils
module Private
def self.coerce_and_check_module_types(val, check_val, check_module_type)
# rubocop:disable Style/CaseLikeIf
if val.is_a?(T::Types::Base)
if val.is_a?(T::Private::Types::TypeAlias)
val.aliased_type
else
val
end
elsif val.is_a?(Module)
if check_module_type && check_val.is_a?(val)
nil
else
T::Types::Simple::Private::Pool.type_for_module(val)
end
elsif val.is_a?(::Array)
T::Types::FixedArray.new(val)
elsif val.is_a?(::Hash)
T::Types::FixedHash.new(val)
elsif val.is_a?(T::Private::Methods::DeclBuilder)
T::Private::Methods.finalize_proc(val.decl)
elsif val.is_a?(::T::Enum)
T::Types::TEnum.new(val)
elsif val.is_a?(::String)
raise "Invalid String literal for type constraint. Must be an #{T::Types::Base}, a " \
"class/module, or an array. Got a String with value `#{val}`."
else
raise "Invalid value for type constraint. Must be an #{T::Types::Base}, a " \
"class/module, or an array. Got a `#{val.class}`."
end
# rubocop:enable Style/CaseLikeIf
end
end
# Used to convert from a type specification to a `T::Types::Base`.
def self.coerce(val)
Private.coerce_and_check_module_types(val, nil, false)
end
# Dynamically confirm that `value` is recursively a valid value of
# type `type`, including recursively through collections. Note that
# in some cases this runtime check can be very expensive, especially
# with large collections of objects.
def self.check_type_recursive!(value, type)
T::Private::Casts.cast_recursive(value, type, "T.check_type_recursive!")
end
# Returns the set of all methods (public, protected, private) defined on a module or its
# ancestors, excluding Object and its ancestors. Overrides of methods from Object (and its
# ancestors) are included.
def self.methods_excluding_object(mod)
# We can't just do mod.instance_methods - Object.instance_methods, because that would leave out
# any methods from Object that are overridden in mod.
mod.ancestors.flat_map do |ancestor|
# equivalent to checking Object.ancestors.include?(ancestor)
next [] if Object <= ancestor
ancestor.instance_methods(false) + ancestor.private_instance_methods(false)
end.uniq
end
# Returns the signature for the `UnboundMethod`, or nil if it's not sig'd
#
# @example T::Utils.signature_for_method(x.method(:foo))
def self.signature_for_method(method)
T::Private::Methods.signature_for_method(method)
end
# Returns the signature for the instance method on the supplied module, or nil if it's not found or not typed.
#
# @example T::Utils.signature_for_instance_method(MyClass, :my_method)
def self.signature_for_instance_method(mod, method_name)
T::Private::Methods.signature_for_method(mod.instance_method(method_name))
end
def self.wrap_method_with_call_validation_if_needed(mod, method_sig, original_method)
T::Private::Methods::CallValidation.wrap_method_if_needed(mod, method_sig, original_method)
end
# Unwraps all the sigs.
def self.run_all_sig_blocks(force_type_init: true)
T::Private::Methods.run_all_sig_blocks(force_type_init: force_type_init)
end
# Return the underlying type for a type alias. Otherwise returns type.
def self.resolve_alias(type)
case type
when T::Private::Types::TypeAlias
type.aliased_type
else
type
end
end
# Give a type which is a subclass of T::Types::Base, determines if the type is a simple nilable type (union of NilClass and something else).
# If so, returns the T::Types::Base of the something else. Otherwise, returns nil.
def self.unwrap_nilable(type)
case type
when T::Types::Union
type.unwrap_nilable
else
nil
end
end
# Returns the arity of a method, unwrapping the sig if needed
def self.arity(method)
arity = method.arity
return arity if arity != -1 || method.is_a?(Proc)
sig = T::Private::Methods.signature_for_method(method)
sig ? sig.method.arity : arity
end
# Elide the middle of a string as needed and replace it with an ellipsis.
# Keep the given number of characters at the start and end of the string.
#
# This method operates on string length, not byte length.
#
# If the string is shorter than the requested truncation length, return it
# without adding an ellipsis. This method may return a longer string than
# the original if the characters removed are shorter than the ellipsis.
#
# @param [String] str
#
# @param [Fixnum] start_len The length of string before the ellipsis
# @param [Fixnum] end_len The length of string after the ellipsis
#
# @param [String] ellipsis The string to add in place of the elided text
#
# @return [String]
#
def self.string_truncate_middle(str, start_len, end_len, ellipsis='...')
return unless str
raise ArgumentError.new('must provide start_len') unless start_len
raise ArgumentError.new('must provide end_len') unless end_len
raise ArgumentError.new('start_len must be >= 0') if start_len < 0
raise ArgumentError.new('end_len must be >= 0') if end_len < 0
str = str.to_s
return str if str.length <= start_len + end_len
start_part = str[0...start_len - ellipsis.length]
end_part = end_len == 0 ? '' : str[-end_len..-1]
"#{start_part}#{ellipsis}#{end_part}"
end
def self.lift_enum(enum)
unless enum.is_a?(T::Types::Enum)
raise ArgumentError.new("#{enum.inspect} is not a T.deprecated_enum")
end
classes = T.unsafe(enum.values).map(&:class).uniq
if classes.empty?
T.untyped
elsif classes.length > 1
T::Types::Union.new(classes)
else
T::Types::Simple::Private::Pool.type_for_module(classes.first)
end
end
module Nilable
# :is_union_type, T::Boolean: whether the type is an T::Types::Union type
# :non_nilable_type, Class: if it is an T.nilable type, the corresponding underlying type; otherwise, nil.
TypeInfo = Struct.new(:is_union_type, :non_nilable_type)
NIL_TYPE = T::Utils.coerce(NilClass)
def self.get_type_info(prop_type)
if prop_type.is_a?(T::Types::Union)
non_nilable_type = prop_type.unwrap_nilable
if non_nilable_type.is_a?(T::Types::Simple)
non_nilable_type = non_nilable_type.raw_type
end
TypeInfo.new(true, non_nilable_type)
else
TypeInfo.new(false, nil)
end
end
# Get the underlying type inside prop_type:
# - if the type is A, the function returns A
# - if the type is T.nilable(A), the function returns A
def self.get_underlying_type(prop_type)
if prop_type.is_a?(T::Types::Union)
non_nilable_type = prop_type.unwrap_nilable
if non_nilable_type.is_a?(T::Types::Simple)
non_nilable_type = non_nilable_type.raw_type
end
non_nilable_type || prop_type
elsif prop_type.is_a?(T::Types::Simple)
prop_type.raw_type
else
prop_type
end
end
# The difference between this function and the above function is that the Sorbet type, like T::Types::Simple
# is preserved.
def self.get_underlying_type_object(prop_type)
T::Utils.unwrap_nilable(prop_type) || prop_type
end
def self.is_union_with_nilclass(prop_type)
case prop_type
when T::Types::Union
prop_type.types.include?(NIL_TYPE)
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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/boolean.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/boolean.rb | # typed: strict
# frozen_string_literal: true
module T
# T::Boolean is a type alias helper for the common `T.any(TrueClass, FalseClass)`.
# Defined separately from _types.rb because it has a dependency on T::Types::Union.
Boolean = T.type_alias { T.any(TrueClass, FalseClass) }
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/abstract_utils.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/abstract_utils.rb | # frozen_string_literal: true
# typed: true
module T::AbstractUtils
Methods = T::Private::Methods
# Returns whether a module is declared as abstract. After the module is finished being declared,
# this is equivalent to whether it has any abstract methods that haven't been implemented
# (because we validate that and raise an error otherwise).
#
# Note that checking `mod.is_a?(Abstract::Hooks)` is not a safe substitute for this method; when
# a class extends `Abstract::Hooks`, all of its subclasses, including the eventual concrete
# ones, will still have `Abstract::Hooks` as an ancestor.
def self.abstract_module?(mod)
!T::Private::Abstract::Data.get(mod, :abstract_type).nil?
end
def self.abstract_method?(method)
signature = Methods.signature_for_method(method)
signature&.mode == Methods::Modes.abstract
end
# Given a module, returns the set of methods declared as abstract (in itself or ancestors)
# that have not been implemented.
def self.abstract_methods_for(mod)
declared_methods = declared_abstract_methods_for(mod)
declared_methods.select do |declared_method|
actual_method = mod.instance_method(declared_method.name)
# Note that in the case where an abstract method is overridden by another abstract method,
# this method will return them both. This is intentional to ensure we validate the final
# implementation against all declarations of an abstract method (they might not all have the
# same signature).
abstract_method?(actual_method)
end
end
# Given a module, returns the set of methods declared as abstract (in itself or ancestors)
# regardless of whether they have been implemented.
def self.declared_abstract_methods_for(mod)
methods = []
mod.ancestors.each do |ancestor|
ancestor_methods = ancestor.private_instance_methods(false) + ancestor.instance_methods(false)
ancestor_methods.each do |method_name|
method = ancestor.instance_method(method_name)
methods << method if abstract_method?(method)
end
end
methods
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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/helpers.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/helpers.rb | # frozen_string_literal: true
# typed: true
# Use as a mixin with extend (`extend T::Helpers`).
# Docs at https://sorbet.org/docs/
module T::Helpers
extend T::Sig
Private = T::Private
### Class/Module Helpers ###
def abstract!
if defined?(super)
# This is to play nicely with Rails' AbstractController::Base,
# which also defines an `abstract!` method.
# https://api.rubyonrails.org/classes/AbstractController/Base.html#method-c-abstract-21
super
end
Private::Abstract::Declare.declare_abstract(self, type: :abstract)
end
def interface!
Private::Abstract::Declare.declare_abstract(self, type: :interface)
end
def final!
Private::Final.declare(self)
end
def sealed!
Private::Sealed.declare(self, Kernel.caller(1..1)&.first&.split(':')&.first)
end
# Causes a mixin to also mix in class methods from the named module.
#
# Nearly equivalent to
#
# def self.included(other)
# other.extend(mod)
# end
#
# Except that it is statically analyzed by sorbet.
def mixes_in_class_methods(mod, *mods)
Private::Mixins.declare_mixes_in_class_methods(self, [mod].concat(mods))
end
# Specify an inclusion or inheritance requirement for `self`.
#
# Example:
#
# module MyHelper
# extend T::Helpers
#
# requires_ancestor { Kernel }
# end
#
# class MyClass < BasicObject # error: `MyClass` must include `Kernel` (required by `MyHelper`)
# include MyHelper
# end
#
# TODO: implement the checks in sorbet-runtime.
def requires_ancestor(&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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/_types.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/_types.rb | # frozen_string_literal: true
# typed: true
# This is where we define the shortcuts, so we can't use them here
# _____
# |_ _| _ _ __ ___ ___
# | || | | | '_ \ / _ \/ __|
# | || |_| | |_) | __/\__ \
# |_| \__, | .__/ \___||___/
# |___/|_|
#
# Docs at https://sorbet.org/docs/sigs
#
# Types that you can pass to `sig`:
#
# - a Ruby class
#
# - [<Type>, <Type>, ...] -- to specify a "tuple"; a fixed-size array with known types for each member
#
# - {key: <Type>, key2: <Type>, ...} -- to speicfy a "shape"; a fixed-size hash
# with known keys and type values
#
# - Any of the `T.foo` methods below
module T
# T.any(<Type>, <Type>, ...) -- matches any of the types listed
def self.any(type_a, type_b, *types)
type_a = T::Utils.coerce(type_a)
type_b = T::Utils.coerce(type_b)
types = types.map { |t| T::Utils.coerce(t) } if !types.empty?
T::Types::Union::Private::Pool.union_of_types(type_a, type_b, types)
end
# Shorthand for T.any(type, NilClass)
def self.nilable(type)
T::Types::Union::Private::Pool.union_of_types(T::Utils.coerce(type), T::Utils::Nilable::NIL_TYPE)
end
# Matches any object. In the static checker, T.untyped allows any
# method calls or operations.
def self.untyped
T::Types::Untyped::Private::INSTANCE
end
# Indicates a function never returns (e.g. "Kernel#raise")
def self.noreturn
T::Types::NoReturn::Private::INSTANCE
end
def self.anything
T::Types::Anything::Private::INSTANCE
end
# T.all(<Type>, <Type>, ...) -- matches an object that has all of the types listed
def self.all(type_a, type_b, *types)
T::Types::Intersection.new([type_a, type_b] + types)
end
# Matches any of the listed values
# @deprecated Use T::Enum instead.
def self.deprecated_enum(values)
T::Types::Enum.new(values)
end
# Creates a proc type
def self.proc
T::Private::Methods.start_proc
end
# Matches `self`:
def self.self_type
T::Types::SelfType::Private::INSTANCE
end
# Matches the instance type in a singleton-class context
def self.attached_class
T::Types::AttachedClassType::Private::INSTANCE
end
# Matches any class that subclasses or includes the provided class
# or module
def self.class_of(klass)
T::Types::ClassOf.new(klass)
end
## END OF THE METHODS TO PASS TO `sig`.
# Constructs a type alias. Used to create a short name for a larger type. In Ruby this returns a
# wrapper that contains a proc that is evaluated to get the underlying type. This syntax however
# is needed for support by the static checker.
#
# @example
# NilableString = T.type_alias {T.nilable(String)}
#
# sig {params(arg: NilableString, default: String).returns(String)}
# def or_else(arg, default)
# arg || default
# end
#
# The name of the type alias is not preserved; Error messages will
# be printed with reference to the underlying type.
#
# TODO Remove `type` parameter. This was left in to make life easier while migrating.
def self.type_alias(type=nil, &blk)
if blk
T::Private::Types::TypeAlias.new(blk)
else
T::Utils.coerce(type)
end
end
# References a type parameter which was previously defined with
# `type_parameters`.
#
# This is used for generic methods.
#
# @example
# sig
# .type_parameters(:U)
# .params(
# blk: T.proc.params(arg0: Elem).returns(T.type_parameter(:U)),
# )
# .returns(T::Array[T.type_parameter(:U)])
# def map(&blk); end
def self.type_parameter(name)
T::Types::TypeParameter.make(name)
end
# Tells the typechecker that `value` is of type `type`. Use this to get additional checking after
# an expression that the typechecker is unable to analyze. If `checked` is true, raises an
# exception at runtime if the value doesn't match the type.
#
# Compared to `T.let`, `T.cast` is _trusted_ by static system.
def self.cast(value, type, checked: true)
return value unless checked
Private::Casts.cast(value, type, "T.cast")
end
# Tells the typechecker to declare a variable of type `type`. Use
# like:
#
# seconds = T.let(0.0, Float)
#
# Compared to `T.cast`, `T.let` is _checked_ by static system.
#
# If `checked` is true, raises an exception at runtime if the value
# doesn't match the type.
def self.let(value, type, checked: true)
return value unless checked
Private::Casts.cast(value, type, "T.let")
end
# Tells the type checker to treat `self` in the current block as `type`.
# Useful for blocks that are captured and executed later with instance_exec.
# Use like:
#
# seconds = lambda do
# T.bind(self, NewBinding)
# ...
# end
#
# `T.bind` behaves like `T.cast` in that it is assumed to be true statically.
#
# If `checked` is true, raises an exception at runtime if the value
# doesn't match the type (this is the default).
def self.bind(value, type, checked: true)
return value unless checked
Private::Casts.cast(value, type, "T.bind")
end
# Tells the typechecker to ensure that `value` is of type `type` (if not, the typechecker will
# fail). Use this for debugging typechecking errors, or to ensure that type information is
# statically known and being checked appropriately. If `checked` is true, raises an exception at
# runtime if the value doesn't match the type.
def self.assert_type!(value, type, checked: true)
return value unless checked
Private::Casts.cast(value, type, "T.assert_type!")
end
# For the static type checker, strips all type information from a value
# and returns the same value, but statically-typed as `T.untyped`.
# Can be used to tell the static checker to "trust you" by discarding type information
# you know to be incorrect. Use with care!
# (This has no effect at runtime.)
#
# We can't actually write this sig because we ourselves are inside
# the `T::` module and doing this would create a bootstrapping
# cycle. However, we also don't actually need to do so; An untyped
# identity method works just as well here.
#
# `sig {params(value: T.untyped).returns(T.untyped)}`
def self.unsafe(value)
value
end
# A convenience method to `raise` when the argument is `nil` and return it
# otherwise.
#
# Intended to be used as:
#
# needs_foo(T.must(maybe_gives_foo))
#
# Equivalent to:
#
# foo = maybe_gives_foo
# raise "nil" if foo.nil?
# needs_foo(foo)
#
# Intended to be used to promise sorbet that a given nilable value happens
# to contain a non-nil value at this point.
#
# `sig {params(arg: T.nilable(A)).returns(A)}`
def self.must(arg)
return arg if arg
return arg if arg == false
begin
raise TypeError.new("Passed `nil` into T.must")
rescue TypeError => e # raise into rescue to ensure e.backtrace is populated
T::Configuration.inline_type_error_handler(e, {kind: 'T.must', value: arg, type: nil})
end
end
# A convenience method to `raise` with a provided error reason when the argument
# is `nil` and return it otherwise.
#
# Intended to be used as:
#
# needs_foo(T.must_because(maybe_gives_foo) {"reason_foo_should_not_be_nil"})
#
# Equivalent to:
#
# foo = maybe_gives_foo
# raise "reason_foo_should_not_be_nil" if foo.nil?
# needs_foo(foo)
#
# Intended to be used to promise sorbet that a given nilable value happens
# to contain a non-nil value at this point.
#
# `sig {params(arg: T.nilable(A), reason_blk: T.proc.returns(String)).returns(A)}`
def self.must_because(arg)
return arg if arg
return arg if arg == false
begin
raise TypeError.new("Unexpected `nil` because #{yield}")
rescue TypeError => e # raise into rescue to ensure e.backtrace is populated
T::Configuration.inline_type_error_handler(e, {kind: 'T.must_because', value: arg, type: nil})
end
end
# A way to ask Sorbet to show what type it thinks an expression has.
# This can be useful for debugging and checking assumptions.
# In the runtime, merely returns the value passed in.
def self.reveal_type(value)
value
end
# A way to ask Sorbet to prove that a certain branch of control flow never
# happens. Commonly used to assert that a case or if statement exhausts all
# possible cases.
def self.absurd(value)
msg = "Control flow reached T.absurd."
case value
when Kernel
msg += " Got value: #{value}"
end
begin
raise TypeError.new(msg)
rescue TypeError => e # raise into rescue to ensure e.backtrace is populated
T::Configuration.inline_type_error_handler(e, {kind: 'T.absurd', value: value, type: nil})
end
end
### Generic classes ###
module Array
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedArray::Untyped::Private::INSTANCE
else
T::Types::TypedArray::Private::Pool.type_for_module(type)
end
end
end
module Hash
def self.[](keys, values)
if keys.is_a?(T::Types::Untyped) && values.is_a?(T::Types::Untyped)
T::Types::TypedHash::Untyped.new
else
T::Types::TypedHash.new(keys: keys, values: values)
end
end
end
module Enumerable
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedEnumerable::Untyped.new
else
T::Types::TypedEnumerable.new(type)
end
end
end
module Enumerator
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedEnumerator::Untyped.new
else
T::Types::TypedEnumerator.new(type)
end
end
module Lazy
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedEnumeratorLazy::Untyped.new
else
T::Types::TypedEnumeratorLazy.new(type)
end
end
end
module Chain
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedEnumeratorChain::Untyped.new
else
T::Types::TypedEnumeratorChain.new(type)
end
end
end
end
module Range
def self.[](type)
T::Types::TypedRange.new(type)
end
end
module Set
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedSet::Untyped.new
else
T::Types::TypedSet.new(type)
end
end
end
module Class
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedClass::Untyped::Private::INSTANCE
elsif type.is_a?(T::Types::Anything)
T::Types::TypedClass::Anything::Private::INSTANCE
else
T::Types::TypedClass::Private::Pool.type_for_module(type)
end
end
end
module Module
def self.[](type)
if type.is_a?(T::Types::Untyped)
T::Types::TypedModule::Untyped::Private::INSTANCE
elsif type.is_a?(T::Types::Anything)
T::Types::TypedModule::Anything::Private::INSTANCE
else
T::Types::TypedModule::Private::Pool.type_for_module(type)
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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/configuration.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/configuration.rb | # typed: true
# frozen_string_literal: true
module T::Configuration
# Announces to Sorbet that we are currently in a test environment, so it
# should treat any sigs which are marked `.checked(:tests)` as if they were
# just a normal sig.
#
# If this method is not called, sigs marked `.checked(:tests)` will not be
# checked. In fact, such methods won't even be wrapped--the runtime will put
# back the original method.
#
# Note: Due to the way sigs are evaluated and methods are wrapped, this
# method MUST be called before any code calls `sig`. This method raises if
# it has been called too late.
def self.enable_checking_for_sigs_marked_checked_tests
T::Private::RuntimeLevels.enable_checking_in_tests
end
# Announce to Sorbet that we would like the final checks to be enabled when
# including and extending modules. Iff this is not called, then the following
# example will not raise an error.
#
# ```ruby
# module M
# extend T::Sig
# sig(:final) {void}
# def foo; end
# end
# class C
# include M
# def foo; end
# end
# ```
def self.enable_final_checks_on_hooks
T::Private::Methods.set_final_checks_on_hooks(true)
end
# Undo the effects of a previous call to
# `enable_final_checks_on_hooks`.
def self.reset_final_checks_on_hooks
T::Private::Methods.set_final_checks_on_hooks(false)
end
@include_value_in_type_errors = true
# Whether to include values in TypeError messages.
#
# Including values is useful for debugging, but can potentially leak
# sensitive information to logs.
#
# @return [T::Boolean]
def self.include_value_in_type_errors?
@include_value_in_type_errors
end
# Configure if type errors excludes the value of the problematic type.
#
# The default is to include values in type errors:
# TypeError: Expected type Integer, got String with value "foo"
#
# When values are excluded from type errors:
# TypeError: Expected type Integer, got String
def self.exclude_value_in_type_errors
@include_value_in_type_errors = false
end
# Opposite of exclude_value_in_type_errors.
# (Including values in type errors is the default)
def self.include_value_in_type_errors
@include_value_in_type_errors = true
end
# Whether VM-defined prop serialization/deserialization routines can be enabled.
#
# @return [T::Boolean]
def self.can_enable_vm_prop_serde?
T::Props::Private::DeserializerGenerator.respond_to?(:generate2)
end
@use_vm_prop_serde = false
# Whether to use VM-defined prop serialization/deserialization routines.
#
# The default is to use runtime codegen inside sorbet-runtime itself.
#
# @return [T::Boolean]
def self.use_vm_prop_serde?
@use_vm_prop_serde || false
end
# Enable using VM-defined prop serialization/deserialization routines.
#
# This method is likely to break things outside of Stripe's systems.
def self.enable_vm_prop_serde
if !can_enable_vm_prop_serde?
hard_assert_handler('Ruby VM is not setup to use VM-defined prop serde')
end
@use_vm_prop_serde = true
end
# Disable using VM-defined prop serialization/deserialization routines.
def self.disable_vm_prop_serde
@use_vm_prop_serde = false
end
# Configure the default checked level for a sig with no explicit `.checked`
# builder. When unset, the default checked level is `:always`.
#
# Note: setting this option is potentially dangerous! Sorbet can't check all
# code statically. The runtime checks complement the checks that Sorbet does
# statically, so that methods don't have to guard themselves from being
# called incorrectly by untyped code.
#
# @param [:never, :tests, :always] default_checked_level
def self.default_checked_level=(default_checked_level)
T::Private::RuntimeLevels.default_checked_level = default_checked_level
end
@inline_type_error_handler = nil
# Set a handler to handle `TypeError`s raised by any in-line type assertions,
# including `T.must`, `T.let`, `T.cast`, and `T.assert_type!`.
#
# By default, any `TypeError`s detected by this gem will be raised. Setting
# inline_type_error_handler to an object that implements :call (e.g. proc or
# lambda) allows users to customize the behavior when a `TypeError` is
# raised on any inline type assertion.
#
# @param [Lambda, Proc, Object, nil] value Proc that handles the error (pass
# nil to reset to default behavior)
#
# Parameters passed to value.call:
#
# @param [TypeError] error TypeError that was raised
# @param [Hash] opts A hash containing contextual information on the error:
# @option opts [String] :kind One of:
# ['T.cast', 'T.let', 'T.bind', 'T.assert_type!', 'T.must', 'T.absurd']
# @option opts [Object, nil] :type Expected param/return value type
# @option opts [Object] :value Actual param/return value
#
# @example
# T::Configuration.inline_type_error_handler = lambda do |error, opts|
# puts error.message
# end
def self.inline_type_error_handler=(value)
validate_lambda_given!(value)
@inline_type_error_handler = value
end
private_class_method def self.inline_type_error_handler_default(error, opts)
raise error
end
def self.inline_type_error_handler(error, opts={})
if @inline_type_error_handler
# Backwards compatibility before `inline_type_error_handler` took a second arg
if @inline_type_error_handler.arity == 1
@inline_type_error_handler.call(error)
else
@inline_type_error_handler.call(error, opts)
end
else
inline_type_error_handler_default(error, opts)
end
nil
end
@sig_builder_error_handler = nil
# Set a handler to handle errors that occur when the builder methods in the
# body of a sig are executed. The sig builder methods are inside a proc so
# that they can be lazily evaluated the first time the method being sig'd is
# called.
#
# By default, improper use of the builder methods within the body of a sig
# cause an ArgumentError to be raised. Setting sig_builder_error_handler to an
# object that implements :call (e.g. proc or lambda) allows users to
# customize the behavior when a sig can't be built for some reason.
#
# @param [Lambda, Proc, Object, nil] value Proc that handles the error (pass
# nil to reset to default behavior)
#
# Parameters passed to value.call:
#
# @param [StandardError] error The error that was raised
# @param [Thread::Backtrace::Location] location Location of the error
#
# @example
# T::Configuration.sig_builder_error_handler = lambda do |error, location|
# puts error.message
# end
def self.sig_builder_error_handler=(value)
validate_lambda_given!(value)
@sig_builder_error_handler = value
end
private_class_method def self.sig_builder_error_handler_default(error, location)
raise ArgumentError.new("#{location.path}:#{location.lineno}: Error interpreting `sig`:\n #{error.message}\n\n")
end
def self.sig_builder_error_handler(error, location)
if @sig_builder_error_handler
@sig_builder_error_handler.call(error, location)
else
sig_builder_error_handler_default(error, location)
end
nil
end
@sig_validation_error_handler = nil
# Set a handler to handle sig validation errors.
#
# Sig validation errors include things like abstract checks, override checks,
# and type compatibility of arguments. They happen after a sig has been
# successfully built, but the built sig is incompatible with other sigs in
# some way.
#
# By default, sig validation errors cause an exception to be raised.
# Setting sig_validation_error_handler to an object that implements :call
# (e.g. proc or lambda) allows users to customize the behavior when a method
# signature's build fails.
#
# @param [Lambda, Proc, Object, nil] value Proc that handles the error (pass
# nil to reset to default behavior)
#
# Parameters passed to value.call:
#
# @param [StandardError] error The error that was raised
# @param [Hash] opts A hash containing contextual information on the error:
# @option opts [Method, UnboundMethod] :method Method on which the signature build failed
# @option opts [T::Private::Methods::Declaration] :declaration Method
# signature declaration struct
# @option opts [T::Private::Methods::Signature, nil] :signature Signature
# that failed (nil if sig build failed before Signature initialization)
# @option opts [T::Private::Methods::Signature, nil] :super_signature Super
# method's signature (nil if method is not an override or super method
# does not have a method signature)
#
# @example
# T::Configuration.sig_validation_error_handler = lambda do |error, opts|
# puts error.message
# end
def self.sig_validation_error_handler=(value)
validate_lambda_given!(value)
@sig_validation_error_handler = value
end
private_class_method def self.sig_validation_error_handler_default(error, opts)
raise error
end
def self.sig_validation_error_handler(error, opts={})
if @sig_validation_error_handler
@sig_validation_error_handler.call(error, opts)
else
sig_validation_error_handler_default(error, opts)
end
nil
end
@call_validation_error_handler = nil
# Set a handler for type errors that result from calling a method.
#
# By default, errors from calling a method cause an exception to be raised.
# Setting call_validation_error_handler to an object that implements :call
# (e.g. proc or lambda) allows users to customize the behavior when a method
# is called with invalid parameters, or returns an invalid value.
#
# @param [Lambda, Proc, Object, nil] value Proc that handles the error
# report (pass nil to reset to default behavior)
#
# Parameters passed to value.call:
#
# @param [T::Private::Methods::Signature] signature Signature that failed
# @param [Hash] opts A hash containing contextual information on the error:
# @option opts [String] :message Error message
# @option opts [String] :kind One of:
# ['Parameter', 'Block parameter', 'Return value']
# @option opts [Symbol] :name Param or block param name (nil for return
# value)
# @option opts [Object] :type Expected param/return value type
# @option opts [Object] :value Actual param/return value
# @option opts [Thread::Backtrace::Location] :location Location of the
# caller
#
# @example
# T::Configuration.call_validation_error_handler = lambda do |signature, opts|
# puts opts[:message]
# end
def self.call_validation_error_handler=(value)
validate_lambda_given!(value)
@call_validation_error_handler = value
end
private_class_method def self.call_validation_error_handler_default(signature, opts)
raise TypeError.new(opts[:pretty_message])
end
def self.call_validation_error_handler(signature, opts={})
if @call_validation_error_handler
@call_validation_error_handler.call(signature, opts)
else
call_validation_error_handler_default(signature, opts)
end
nil
end
@log_info_handler = nil
# Set a handler for logging
#
# @param [Lambda, Proc, Object, nil] value Proc that handles the error
# report (pass nil to reset to default behavior)
#
# Parameters passed to value.call:
#
# @param [String] str Message to be logged
# @param [Hash] extra A hash containing additional parameters to be passed along to the logger.
#
# @example
# T::Configuration.log_info_handler = lambda do |str, extra|
# puts "#{str}, context: #{extra}"
# end
def self.log_info_handler=(value)
validate_lambda_given!(value)
@log_info_handler = value
end
private_class_method def self.log_info_handler_default(str, extra)
puts "#{str}, extra: #{extra}"
end
def self.log_info_handler(str, extra)
if @log_info_handler
@log_info_handler.call(str, extra)
else
log_info_handler_default(str, extra)
end
end
@soft_assert_handler = nil
# Set a handler for soft assertions
#
# These generally shouldn't stop execution of the program, but rather inform
# some party of the assertion to action on later.
#
# @param [Lambda, Proc, Object, nil] value Proc that handles the error
# report (pass nil to reset to default behavior)
#
# Parameters passed to value.call:
#
# @param [String] str Assertion message
# @param [Hash] extra A hash containing additional parameters to be passed along to the handler.
#
# @example
# T::Configuration.soft_assert_handler = lambda do |str, extra|
# puts "#{str}, context: #{extra}"
# end
def self.soft_assert_handler=(value)
validate_lambda_given!(value)
@soft_assert_handler = value
end
private_class_method def self.soft_assert_handler_default(str, extra)
puts "#{str}, extra: #{extra}"
end
def self.soft_assert_handler(str, extra)
if @soft_assert_handler
@soft_assert_handler.call(str, extra)
else
soft_assert_handler_default(str, extra)
end
end
@hard_assert_handler = nil
# Set a handler for hard assertions
#
# These generally should stop execution of the program, and optionally inform
# some party of the assertion.
#
# @param [Lambda, Proc, Object, nil] value Proc that handles the error
# report (pass nil to reset to default behavior)
#
# Parameters passed to value.call:
#
# @param [String] str Assertion message
# @param [Hash] extra A hash containing additional parameters to be passed along to the handler.
#
# @example
# T::Configuration.hard_assert_handler = lambda do |str, extra|
# raise "#{str}, context: #{extra}"
# end
def self.hard_assert_handler=(value)
validate_lambda_given!(value)
@hard_assert_handler = value
end
private_class_method def self.hard_assert_handler_default(str, _)
raise str
end
def self.hard_assert_handler(str, extra={})
if @hard_assert_handler
@hard_assert_handler.call(str, extra)
else
hard_assert_handler_default(str, extra)
end
end
@scalar_types = nil
# Set a list of class strings that are to be considered scalar.
# (pass nil to reset to default behavior)
#
# @param [String] values Class name.
#
# @example
# T::Configuration.scalar_types = ["NilClass", "TrueClass", "FalseClass", ...]
def self.scalar_types=(values)
if values.nil?
@scalar_types = values
else
bad_values = values.reject { |v| v.class == String }
unless bad_values.empty?
raise ArgumentError.new("Provided values must all be class name strings.")
end
@scalar_types = values.each_with_object({}) { |x, acc| acc[x] = true }.freeze
end
end
@default_scalar_types = {
"NilClass" => true,
"TrueClass" => true,
"FalseClass" => true,
"Integer" => true,
"Float" => true,
"String" => true,
"Symbol" => true,
"Time" => true,
"T::Enum" => true,
}.freeze
def self.scalar_types
@scalar_types || @default_scalar_types
end
# Guard against overrides of `name` or `to_s`
MODULE_NAME = Module.instance_method(:name)
private_constant :MODULE_NAME
@default_module_name_mangler = ->(type) { MODULE_NAME.bind_call(type) }
@module_name_mangler = nil
def self.module_name_mangler
@module_name_mangler || @default_module_name_mangler
end
# Set to override the default behavior for converting types
# to names in generated code. Used by the runtime implementation
# associated with `--sorbet-packages` mode.
#
# @param [Lambda, Proc, nil] handler Proc that converts a type (Class/Module)
# to a String (pass nil to reset to default behavior)
def self.module_name_mangler=(handler)
@module_name_mangler = handler
end
@sensitivity_and_pii_handler = nil
# Set to a PII handler function. This will be called with the `sensitivity:`
# annotations on things that use `T::Props` and can modify them ahead-of-time.
#
# @param [Lambda, Proc, nil] handler Proc that takes a hash mapping symbols to the
# prop values. Pass nil to avoid changing `sensitivity:` annotations.
def self.normalize_sensitivity_and_pii_handler=(handler)
@sensitivity_and_pii_handler = handler
end
def self.normalize_sensitivity_and_pii_handler
@sensitivity_and_pii_handler
end
@redaction_handler = nil
# Set to a redaction handling function. This will be called when the
# `_redacted` version of a prop reader is used. By default this is set to
# `nil` and will raise an exception when the redacted version of a prop is
# accessed.
#
# @param [Lambda, Proc, nil] handler Proc that converts a value into its
# redacted version according to the spec passed as the second argument.
def self.redaction_handler=(handler)
@redaction_handler = handler
end
def self.redaction_handler
@redaction_handler
end
@class_owner_finder = nil
# Set to a function which can get the 'owner' of a class. This is
# used in reporting deserialization errors
#
# @param [Lambda, Proc, nil] handler Proc that takes a class and
# produces its owner, or `nil` if it does not have one.
def self.class_owner_finder=(handler)
@class_owner_finder = handler
end
def self.class_owner_finder
@class_owner_finder
end
# Temporarily disable ruby warnings while executing the given block. This is
# useful when doing something that would normally cause a warning to be
# emitted in Ruby verbose mode ($VERBOSE = true).
#
# @yield
#
def self.without_ruby_warnings
if $VERBOSE
begin
original_verbose = $VERBOSE
$VERBOSE = false
yield
ensure
$VERBOSE = original_verbose
end
else
yield
end
end
@legacy_t_enum_migration_mode = false
def self.enable_legacy_t_enum_migration_mode
T::Enum.include(T::Enum::LegacyMigrationMode)
@legacy_t_enum_migration_mode = true
end
def self.disable_legacy_t_enum_migration_mode
@legacy_t_enum_migration_mode = false
end
def self.legacy_t_enum_migration_mode?
@legacy_t_enum_migration_mode || false
end
@sealed_violation_whitelist = nil
# @param [Array] sealed_violation_whitelist An array of Regexp to validate
# whether inheriting /including a sealed module outside the defining module
# should be allowed. Useful to whitelist benign violations, like shim files
# generated for an autoloader.
def self.sealed_violation_whitelist=(sealed_violation_whitelist)
if !@sealed_violation_whitelist.nil?
raise ArgumentError.new("Cannot overwrite sealed_violation_whitelist after setting it")
end
case sealed_violation_whitelist
when Array
sealed_violation_whitelist.each do |x|
case x
when Regexp then nil
else raise TypeError.new("sealed_violation_whitelist accepts an Array of Regexp")
end
end
else
raise TypeError.new("sealed_violation_whitelist= accepts an Array of Regexp")
end
@sealed_violation_whitelist = sealed_violation_whitelist
end
def self.sealed_violation_whitelist
@sealed_violation_whitelist
end
private_class_method def self.validate_lambda_given!(value)
if !value.nil? && !value.respond_to?(:call)
raise ArgumentError.new("Provided value must respond to :call")
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/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/enum.rb | Library/Homebrew/vendor/bundle/ruby/3.4.0/gems/sorbet-runtime-0.6.12872/lib/types/enum.rb | # frozen_string_literal: true
# typed: strict
# Enumerations allow for type-safe declarations of a fixed set of values.
#
# Every value is a singleton instance of the class (i.e. `Suit::SPADE.is_a?(Suit) == true`).
#
# Each value has a corresponding serialized value. By default this is the constant's name converted
# to lowercase (e.g. `Suit::Club.serialize == 'club'`); however a custom value may be passed to the
# constructor. Enum will `freeze` the serialized value.
#
# @example Declaring an Enum:
# class Suit < T::Enum
# enums do
# CLUB = new
# SPADE = new
# DIAMOND = new
# HEART = new
# end
# end
#
# @example Custom serialization value:
# class Status < T::Enum
# enums do
# READY = new('rdy')
# ...
# end
# end
#
# @example Accessing values:
# Suit::SPADE
#
# @example Converting from serialized value to enum instance:
# Suit.deserialize('club') == Suit::CLUB
#
# @example Using enums in type signatures:
# sig {params(suit: Suit).returns(Boolean)}
# def is_red?(suit); ...; end
#
# WARNING: Enum instances are singletons that are shared among all their users. Their internals
# should be kept immutable to avoid unpredictable action at a distance.
class T::Enum
extend T::Sig
extend T::Props::CustomType
# TODO(jez) Might want to restrict this, or make subclasses provide this type
SerializedVal = T.type_alias { T.untyped }
private_constant :SerializedVal
### Enum class methods ###
sig { returns(T::Array[T.attached_class]) }
def self.values
if @values.nil?
raise "Attempting to access values of #{self.class} before it has been initialized." \
" Enums are not initialized until the 'enums do' block they are defined in has finished running."
end
@values
end
# This exists for compatibility with the interface of `Hash` & mostly to support
# the HashEachMethods Rubocop.
sig { params(blk: T.nilable(T.proc.params(arg0: T.attached_class).void)).returns(T.any(T::Enumerator[T.attached_class], T::Array[T.attached_class])) }
def self.each_value(&blk)
if blk
values.each(&blk)
else
values.each
end
end
# Convert from serialized value to enum instance
#
# Note: It would have been nice to make this method final before people started overriding it.
# Note: Failed CriticalMethodsNoRuntimeTypingTest
sig { params(serialized_val: SerializedVal).returns(T.nilable(T.attached_class)).checked(:never) }
def self.try_deserialize(serialized_val)
if @mapping.nil?
raise "Attempting to access serialization map of #{self.class} before it has been initialized." \
" Enums are not initialized until the 'enums do' block they are defined in has finished running."
end
@mapping[serialized_val]
end
# Convert from serialized value to enum instance.
#
# Note: It would have been nice to make this method final before people started overriding it.
# Note: Failed CriticalMethodsNoRuntimeTypingTest
#
# @return [self]
# @raise [KeyError] if serialized value does not match any instance.
sig { overridable.params(serialized_val: SerializedVal).returns(T.attached_class).checked(:never) }
def self.from_serialized(serialized_val)
res = try_deserialize(serialized_val)
if res.nil?
raise KeyError.new("Enum #{self} key not found: #{serialized_val.inspect}")
end
res
end
# Note: It would have been nice to make this method final before people started overriding it.
# @return [Boolean] Does the given serialized value correspond with any of this enum's values.
sig { overridable.params(serialized_val: SerializedVal).returns(T::Boolean).checked(:never) }
def self.has_serialized?(serialized_val)
if @mapping.nil?
raise "Attempting to access serialization map of #{self.class} before it has been initialized." \
" Enums are not initialized until the 'enums do' block they are defined in has finished running."
end
@mapping.include?(serialized_val)
end
# Note: Failed CriticalMethodsNoRuntimeTypingTest
sig { override.params(instance: T.nilable(T::Enum)).returns(SerializedVal).checked(:never) }
def self.serialize(instance)
# This is needed otherwise if a Chalk::ODM::Document with a property of the shape
# T::Hash[T.nilable(MyEnum), Integer] and a value that looks like {nil => 0} is
# serialized, we throw the error on L102.
return nil if instance.nil?
if self == T::Enum
raise "Cannot call T::Enum.serialize directly. You must call on a specific child class."
end
if instance.class != self
raise "Cannot call #serialize on a value that is not an instance of #{self}."
end
instance.serialize
end
# Note: Failed CriticalMethodsNoRuntimeTypingTest
sig { override.params(mongo_value: SerializedVal).returns(T.attached_class).checked(:never) }
def self.deserialize(mongo_value)
if self == T::Enum
raise "Cannot call T::Enum.deserialize directly. You must call on a specific child class."
end
self.from_serialized(mongo_value)
end
### Enum instance methods ###
sig { returns(T.self_type) }
def dup
self
end
sig { returns(T.self_type).checked(:tests) }
def clone
self
end
# Note: Failed CriticalMethodsNoRuntimeTypingTest
sig { returns(SerializedVal).checked(:never) }
def serialize
assert_bound!
@serialized_val
end
sig { params(args: T.untyped).returns(T.untyped) }
def to_json(*args)
serialize.to_json(*args)
end
sig { params(args: T.untyped).returns(T.untyped) }
def as_json(*args)
serialized_val = serialize
return serialized_val unless serialized_val.respond_to?(:as_json)
serialized_val.as_json(*args)
end
sig { returns(String) }
def to_s
inspect
end
sig { returns(String) }
def inspect
"#<#{self.class.name}::#{@const_name || '__UNINITIALIZED__'}>"
end
sig { params(other: BasicObject).returns(T.nilable(Integer)) }
def <=>(other)
case other
when self.class
self.serialize <=> other.serialize
else
nil
end
end
# NB: Do not call this method. This exists to allow for a safe migration path in places where enum
# values are compared directly against string values.
#
# Ruby's string has a weird quirk where `'my_string' == obj` calls obj.==('my_string') if obj
# responds to the `to_str` method. It does not actually call `to_str` however.
#
# See https://ruby-doc.org/core-2.4.0/String.html#method-i-3D-3D
T::Sig::WithoutRuntime.sig { returns(String) }
def to_str
msg = 'Implicit conversion of Enum instances to strings is not allowed. Call #serialize instead.'
if T::Configuration.legacy_t_enum_migration_mode?
T::Configuration.soft_assert_handler(
msg,
storytime: {
class: self.class.name,
caller_location: Kernel.caller_locations(1..1)&.[](0)&.then { "#{_1.path}:#{_1.lineno}" },
},
)
serialize.to_s
else
Kernel.raise NoMethodError.new(msg)
end
end
module LegacyMigrationMode
include Kernel
extend T::Helpers
abstract!
if T.unsafe(false)
# Declare to the type system that the `serialize` method for sure exists
# on whatever we mix this into.
T::Sig::WithoutRuntime.sig { abstract.returns(T.untyped) }
def serialize; end
end
# WithoutRuntime so that comparison_assertion_failed can assume a constant stack depth
T::Sig::WithoutRuntime.sig { params(other: BasicObject).returns(T::Boolean) }
def ==(other)
case other
when String
if T::Configuration.legacy_t_enum_migration_mode?
comparison_assertion_failed(:==, other)
self.serialize == other
else
false
end
else
super(other)
end
end
# WithoutRuntime so that comparison_assertion_failed can assume a constant stack depth
T::Sig::WithoutRuntime.sig { params(other: BasicObject).returns(T::Boolean) }
def ===(other)
case other
when String
if T::Configuration.legacy_t_enum_migration_mode?
comparison_assertion_failed(:===, other)
self.serialize == other
else
false
end
else
super(other)
end
end
# WithoutRuntime so that caller_locations can assume a constant stack depth
# (Otherwise, the first call would be the method with the wrapping, which would have a different stack depth.)
T::Sig::WithoutRuntime.sig { params(method: Symbol, other: T.untyped).void }
private def comparison_assertion_failed(method, other)
T::Configuration.soft_assert_handler(
'Enum to string comparison not allowed. Compare to the Enum instance directly instead. See go/enum-migration',
storytime: {
class: self.class.name,
self: self.inspect,
other: other,
other_class: other.class.name,
method: method,
caller_location: Kernel.caller_locations(2..2)&.[](0)&.then { "#{_1.path}:#{_1.lineno}" },
}
)
end
end
### Private implementation ###
UNSET = T.let(Module.new.freeze, T::Module[T.anything])
private_constant :UNSET
sig { params(serialized_val: SerializedVal).void }
def initialize(serialized_val=UNSET)
raise 'T::Enum is abstract' if self.class == T::Enum
if !self.class.started_initializing?
raise "Must instantiate all enum values of #{self.class} inside 'enums do'."
end
if self.class.fully_initialized?
raise "Cannot instantiate a new enum value of #{self.class} after it has been initialized."
end
serialized_val = serialized_val.frozen? ? serialized_val : serialized_val.dup.freeze
@serialized_val = T.let(serialized_val, T.nilable(SerializedVal))
@const_name = T.let(nil, T.nilable(Symbol))
self.class._register_instance(self)
end
sig { returns(NilClass).checked(:never) }
private def assert_bound!
if @const_name.nil?
raise "Attempting to access Enum value on #{self.class} before it has been initialized." \
" Enums are not initialized until the 'enums do' block they are defined in has finished running."
end
end
sig { params(const_name: Symbol).void }
def _bind_name(const_name)
@const_name = const_name
@serialized_val = const_to_serialized_val(const_name) if @serialized_val.equal?(UNSET)
freeze
end
sig { params(const_name: Symbol).returns(String) }
private def const_to_serialized_val(const_name)
# Historical note: We convert to lowercase names because the majority of existing calls to
# `make_accessible` were arrays of lowercase strings. Doing this conversion allowed for the
# least amount of repetition in migrated declarations.
-const_name.to_s.downcase.freeze
end
sig { returns(T::Boolean) }
def self.started_initializing?
unless defined?(@started_initializing)
@started_initializing = T.let(false, T.nilable(T::Boolean))
end
T.must(@started_initializing)
end
sig { returns(T::Boolean) }
def self.fully_initialized?
unless defined?(@fully_initialized)
@fully_initialized = T.let(false, T.nilable(T::Boolean))
end
T.must(@fully_initialized)
end
# Maintains the order in which values are defined
sig { params(instance: T.untyped).void }
def self._register_instance(instance)
@values ||= []
@values << T.cast(instance, T.attached_class)
end
# Entrypoint for allowing people to register new enum values.
# All enum values must be defined within this block.
sig { params(blk: T.proc.void).void }
def self.enums(&blk)
raise "enums cannot be defined for T::Enum" if self == T::Enum
raise "Enum #{self} was already initialized" if fully_initialized?
raise "Enum #{self} is still initializing" if started_initializing?
@started_initializing = true
@values = T.let(nil, T.nilable(T::Array[T.attached_class]))
yield
@mapping = T.let(nil, T.nilable(T::Hash[SerializedVal, T.attached_class]))
@mapping = {}
# Freeze the Enum class and bind the constant names into each of the instances.
self.constants(false).each do |const_name|
instance = self.const_get(const_name, false)
if !instance.is_a?(self)
raise "Invalid constant #{self}::#{const_name} on enum. " \
"All constants defined for an enum must be instances itself (e.g. `Foo = new`)."
end
instance._bind_name(const_name)
serialized = instance.serialize
if @mapping.include?(serialized)
raise "Enum values must have unique serializations. Value '#{serialized}' is repeated on #{self}."
end
@mapping[serialized] = instance
end
@values.freeze
@mapping.freeze
orphaned_instances = T.must(@values) - @mapping.values
if !orphaned_instances.empty?
raise "Enum values must be assigned to constants: #{orphaned_instances.map { |v| v.instance_variable_get('@serialized_val') }}"
end
@fully_initialized = true
end
sig { params(child_class: T::Class[T.anything]).void }
def self.inherited(child_class)
super
raise "Inheriting from children of T::Enum is prohibited" if self != T::Enum
# "oj" gem JSON support
if Object.const_defined?(:Oj)
Object.const_get(:Oj).register_odd(child_class, child_class, :try_deserialize, :serialize)
end
end
# Marshal support
sig { params(_level: Integer).returns(String) }
def _dump(_level)
Marshal.dump(serialize)
end
sig { params(args: String).returns(T.attached_class) }
def self._load(args)
deserialize(Marshal.load(args)) # rubocop:disable Security/MarshalLoad
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.