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/extend/os/linux/linkage_checker.rb | Library/Homebrew/extend/os/linux/linkage_checker.rb | # typed: strict
# frozen_string_literal: true
require "compilers"
require "os/linux/libstdcxx"
module OS
module Linux
module LinkageChecker
extend T::Helpers
requires_ancestor { ::LinkageChecker }
# Libraries provided by glibc and gcc.
SYSTEM_LIBRARY_ALLOWLIST = T.let(%W[
ld-linux-x86-64.so.2
ld-linux-aarch64.so.1
libanl.so.1
libatomic.so.1
libc.so.6
libdl.so.2
libm.so.6
libmvec.so.1
libnss_files.so.2
libpthread.so.0
libresolv.so.2
librt.so.1
libthread_db.so.1
libutil.so.1
libgcc_s.so.1
libgomp.so.1
#{OS::Linux::Libstdcxx::SONAME}
libquadmath.so.0
].freeze, T::Array[String])
private
sig { params(rebuild_cache: T::Boolean).void }
def check_dylibs(rebuild_cache:)
super
# glibc and gcc are implicit dependencies.
# No other linkage to system libraries is expected or desired.
unwanted_system_dylibs.replace(system_dylibs.reject do |s|
SYSTEM_LIBRARY_ALLOWLIST.include? File.basename(s)
end)
# We build all formulae with an RPATH that includes the gcc formula's runtime lib directory.
# See: https://github.com/Homebrew/brew/blob/e689cc07/Library/Homebrew/extend/os/linux/extend/ENV/super.rb#L53
# This results in formulae showing linkage with gcc whenever it is installed, even if no dependency is
# declared.
# See discussions at:
# https://github.com/Homebrew/brew/pull/13659
# https://github.com/Homebrew/brew/pull/13796
# TODO: Find a nicer way to handle this. (e.g. examining the ELF file to determine the required libstdc++.)
undeclared_deps.delete("gcc")
indirect_deps.delete("gcc")
end
end
end
end
LinkageChecker.prepend(OS::Linux::LinkageChecker)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/formula.rb | Library/Homebrew/extend/os/linux/formula.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Formula
extend T::Helpers
requires_ancestor { ::Formula }
sig { params(name: String, version: T.nilable(T.any(String, Integer))).returns(String) }
def shared_library(name, version = nil)
suffix = if version == "*" || (name == "*" && version.blank?)
"{,.*}"
elsif version.present?
".#{version}"
end
"#{name}.so#{suffix}"
end
sig { returns(String) }
def loader_path
"$ORIGIN"
end
sig { params(targets: T.nilable(T.any(::Pathname, String))).void }
def deuniversalize_machos(*targets); end
sig { params(spec: SoftwareSpec).void }
def add_global_deps_to_spec(spec)
return unless ::DevelopmentTools.needs_build_formulae?
@global_deps ||= T.let(nil, T.nilable(T::Array[Dependency]))
@global_deps ||= begin
dependency_collector = spec.dependency_collector
related_formula_names = Set.new([
name,
*aliases,
*versioned_formulae_names,
])
[
dependency_collector.gcc_dep_if_needed(related_formula_names),
dependency_collector.glibc_dep_if_needed(related_formula_names),
].compact.freeze
end
@global_deps.each { |dep| spec.dependency_collector.add(dep) }
end
sig { returns(T::Boolean) }
def valid_platform?
requirements.none?(MacOSRequirement)
end
end
end
end
Formula.prepend(OS::Linux::Formula)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/keg.rb | Library/Homebrew/extend/os/linux/keg.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Keg
sig { returns(T::Array[ELFShim]) }
def binary_executable_or_library_files = elf_files
end
end
end
Keg.prepend(OS::Linux::Keg)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/install.rb | Library/Homebrew/extend/os/linux/install.rb | # typed: strict
# frozen_string_literal: true
require "os/linux/ld"
require "os/linux/libstdcxx"
require "utils/output"
module OS
module Linux
module Install
module ClassMethods
# We link GCC runtime libraries that are not specifically used for Fortran,
# which are linked by the GCC formula. We only use the versioned shared libraries
# as the other shared and static libraries are only used at build time where
# GCC can find its own libraries.
GCC_RUNTIME_LIBS = T.let(%W[
libatomic.so.1
libgcc_s.so.1
libgomp.so.1
#{OS::Linux::Libstdcxx::SONAME}
].freeze, T::Array[String])
sig { params(all_fatal: T::Boolean).void }
def perform_preinstall_checks(all_fatal: false)
super
symlink_ld_so
setup_preferred_gcc_libs
end
sig { void }
def global_post_install
super
symlink_ld_so
setup_preferred_gcc_libs
end
sig { void }
def check_cpu
return if ::Hardware::CPU.intel? && ::Hardware::CPU.is_64_bit?
return if ::Hardware::CPU.arm?
message = "Sorry, Homebrew does not support your computer's CPU architecture!"
if ::Hardware::CPU.ppc64le?
message += <<~EOS
For OpenPOWER Linux (PPC64LE) support, see:
#{Formatter.url("https://github.com/homebrew-ppc64le/brew")}
EOS
end
::Kernel.abort message
end
sig { void }
def symlink_ld_so
brew_ld_so = HOMEBREW_PREFIX/"lib/ld.so"
ld_so = HOMEBREW_PREFIX/"opt/glibc/bin/ld.so"
unless ld_so.readable?
ld_so = OS::Linux::Ld.system_ld_so
if ld_so.blank?
::Kernel.raise "Unable to locate the system's dynamic linker" unless brew_ld_so.readable?
return
end
end
return if brew_ld_so.readable? && (brew_ld_so.readlink == ld_so)
FileUtils.mkdir_p HOMEBREW_PREFIX/"lib"
FileUtils.ln_sf ld_so, brew_ld_so
end
sig { void }
def setup_preferred_gcc_libs
gcc_opt_prefix = HOMEBREW_PREFIX/"opt/#{OS::LINUX_PREFERRED_GCC_RUNTIME_FORMULA}"
glibc_installed = (HOMEBREW_PREFIX/"opt/glibc/bin/ld.so").readable?
return unless gcc_opt_prefix.readable?
if glibc_installed
ld_so_conf_d = HOMEBREW_PREFIX/"etc/ld.so.conf.d"
unless ld_so_conf_d.exist?
ld_so_conf_d.mkpath
FileUtils.chmod "go-w", ld_so_conf_d
end
# Add gcc to ld search paths
ld_gcc_conf = ld_so_conf_d/"50-homebrew-preferred-gcc.conf"
ld_gcc_conf_content = <<~EOS
# This file is generated by Homebrew. Do not modify.
#{gcc_opt_prefix}/lib/gcc/current
EOS
if !ld_gcc_conf.exist? || (ld_gcc_conf.read != ld_gcc_conf_content)
ld_gcc_conf.atomic_write ld_gcc_conf_content
FileUtils.chmod "u=rw,go-wx", ld_gcc_conf
FileUtils.rm_f HOMEBREW_PREFIX/"etc/ld.so.cache"
::Kernel.system HOMEBREW_PREFIX/"opt/glibc/sbin/ldconfig"
end
else
Utils::Output.odie "#{HOMEBREW_PREFIX}/lib does not exist!" unless (HOMEBREW_PREFIX/"lib").readable?
end
GCC_RUNTIME_LIBS.each do |library|
gcc_library_symlink = HOMEBREW_PREFIX/"lib/#{library}"
if glibc_installed
# Remove legacy symlinks
FileUtils.rm gcc_library_symlink if gcc_library_symlink.symlink?
else
gcc_library = gcc_opt_prefix/"lib/gcc/current/#{library}"
# Skip if the link target doesn't exist.
next unless gcc_library.readable?
# Also skip if the symlink already exists.
next if gcc_library_symlink.readable? && (gcc_library_symlink.readlink == gcc_library)
FileUtils.ln_sf gcc_library, gcc_library_symlink
end
end
end
end
end
end
end
Homebrew::Install.singleton_class.prepend(OS::Linux::Install::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/simulate_system.rb | Library/Homebrew/extend/os/linux/simulate_system.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module SimulateSystem
module ClassMethods
sig { returns(T.nilable(Symbol)) }
def os
@os ||= T.let(nil, T.nilable(Symbol))
return :macos if @os.blank? && Homebrew::EnvConfig.simulate_macos_on_linux?
@os
end
sig { returns(T::Boolean) }
def simulating_or_running_on_linux?
os.blank? || os == :linux
end
sig { returns(Symbol) }
def current_os
os || :linux
end
end
end
end
end
Homebrew::SimulateSystem.singleton_class.prepend(OS::Linux::SimulateSystem::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/development_tools.rb | Library/Homebrew/extend/os/linux/development_tools.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module DevelopmentTools
module ClassMethods
extend T::Helpers
requires_ancestor { ::DevelopmentTools }
sig { params(tool: T.any(String, Symbol)).returns(T.nilable(::Pathname)) }
def locate(tool)
@locate ||= T.let({}, T.nilable(T::Hash[T.any(String, Symbol), Pathname]))
@locate.fetch(tool) do |key|
@locate[key] = if ::DevelopmentTools.needs_build_formulae? &&
(binutils_path = HOMEBREW_PREFIX/"opt/binutils/bin/#{tool}").executable?
binutils_path
elsif ::DevelopmentTools.needs_build_formulae? &&
(glibc_path = HOMEBREW_PREFIX/"opt/glibc/bin/#{tool}").executable?
glibc_path
elsif (homebrew_path = HOMEBREW_PREFIX/"bin/#{tool}").executable?
homebrew_path
elsif File.executable?(system_path = "/usr/bin/#{tool}")
::Pathname.new system_path
end
end
end
sig { returns(Symbol) }
def default_compiler = :gcc
sig { returns(T::Boolean) }
def needs_libc_formula?
return @needs_libc_formula unless @needs_libc_formula.nil?
@needs_libc_formula = T.let(nil, T.nilable(T::Boolean))
# Undocumented environment variable to make it easier to test libc
# formula automatic installation.
@needs_libc_formula = true if ENV["HOMEBREW_FORCE_LIBC_FORMULA"]
@needs_libc_formula ||= OS::Linux::Glibc.below_ci_version?
end
sig { returns(::Pathname) }
def host_gcc_path
# Prioritise versioned path if installed
path = ::Pathname.new("/usr/bin/#{OS::LINUX_PREFERRED_GCC_COMPILER_FORMULA.tr("@", "-")}")
return path if path.exist?
super
end
sig { returns(T::Boolean) }
def needs_compiler_formula?
return @needs_compiler_formula unless @needs_compiler_formula.nil?
@needs_compiler_formula = T.let(nil, T.nilable(T::Boolean))
# Undocumented environment variable to make it easier to test compiler
# formula automatic installation.
@needs_compiler_formula = true if ENV["HOMEBREW_FORCE_COMPILER_FORMULA"]
@needs_compiler_formula ||= OS::Linux::Libstdcxx.below_ci_version?
end
sig { returns(T::Hash[String, T.nilable(String)]) }
def build_system_info
super.merge({
"glibc_version" => OS::Linux::Glibc.version.to_s.presence,
"oldest_cpu_family" => ::Hardware.oldest_cpu.to_s,
})
end
end
end
end
end
DevelopmentTools.singleton_class.prepend(OS::Linux::DevelopmentTools::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/formula_installer.rb | Library/Homebrew/extend/os/linux/formula_installer.rb | # typed: strict
# frozen_string_literal: true
class FormulaInstaller
sig { params(formula: Formula).returns(T.nilable(T::Boolean)) }
def fresh_install?(formula)
!Homebrew::EnvConfig.developer? &&
(!installed_as_dependency? || !formula.any_version_installed?)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/cmd/update-report.rb | Library/Homebrew/extend/os/linux/cmd/update-report.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module_function
sig { returns(String) }
def no_changes_message
"No changes to formulae."
end
sig { void }
def migrate_gcc_dependents_if_needed
return if Settings.read("gcc-rpaths.fixed") == "true"
Formula.installed.each do |formula|
next unless formula.tap&.core_tap?
recursive_runtime_dependencies = Dependency.expand(
formula,
cache_key: "update-report",
) do |_, dependency|
Dependency.prune if dependency.build? || dependency.test?
end
next unless recursive_runtime_dependencies.map(&:name).include? "gcc"
keg = formula.installed_kegs.fetch(-1)
tab = keg.tab
# Force reinstallation upon `brew upgrade` to fix the bottle RPATH.
tab.source["versions"]["version_scheme"] = -1
tab.write
rescue TapFormulaUnavailableError
nil
end
Settings.write "gcc-rpaths.fixed", true
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/dev-cmd/update-test.rb | Library/Homebrew/extend/os/linux/dev-cmd/update-test.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module DevCmd
module UpdateTest
private
sig { returns(String) }
def git_tags
super.presence || Utils.popen_read("git tag --list | sort -rV")
end
end
end
end
end
Homebrew::DevCmd::UpdateTest.prepend(OS::Linux::DevCmd::UpdateTest)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/dev-cmd/bottle.rb | Library/Homebrew/extend/os/linux/dev-cmd/bottle.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module DevCmd
module Bottle
sig { params(formula: Formula).returns(T::Array[Regexp]) }
def formula_ignores(formula)
ignores = super
cellar_regex = Regexp.escape(HOMEBREW_CELLAR)
prefix_regex = Regexp.escape(HOMEBREW_PREFIX)
ignores << case formula.name
# On Linux, GCC installation can be moved so long as the whole directory tree is moved together:
# https://gcc-help.gcc.gnu.narkive.com/GnwuCA7l/moving-gcc-from-the-installation-path-is-it-allowed.
when Version.formula_optionally_versioned_regex(:gcc)
Regexp.union(%r{#{cellar_regex}/gcc}, %r{#{prefix_regex}/opt/gcc})
# binutils is relocatable for the same reason: https://github.com/Homebrew/brew/pull/11899#issuecomment-906804451.
when Version.formula_optionally_versioned_regex(:binutils)
%r{#{cellar_regex}/binutils}
end
ignores.compact
end
end
end
end
end
Homebrew::DevCmd::Bottle.prepend(OS::Linux::DevCmd::Bottle)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/dev-cmd/tests.rb | Library/Homebrew/extend/os/linux/dev-cmd/tests.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module DevCmd
module Tests
extend T::Helpers
requires_ancestor { Homebrew::DevCmd::Tests }
private
sig { params(bundle_args: T::Array[String]).returns(T::Array[String]) }
def os_bundle_args(bundle_args)
non_macos_bundle_args(bundle_args)
end
sig { params(files: T::Array[String]).returns(T::Array[String]) }
def os_files(files)
non_macos_files(files)
end
end
end
end
end
Homebrew::DevCmd::Tests.prepend(OS::Linux::DevCmd::Tests)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/hardware/cpu.rb | Library/Homebrew/extend/os/linux/hardware/cpu.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Hardware
module CPU
module ClassMethods
extend T::Helpers
requires_ancestor { T.class_of(::Hardware::CPU) }
sig { returns(T::Hash[Symbol, String]) }
def optimization_flags
@optimization_flags ||= T.let(begin
flags = super.dup
flags[:native] = arch_flag(Homebrew::EnvConfig.arch)
flags
end, T.nilable(T::Hash[Symbol, String]))
end
sig { returns(Symbol) }
def family
return :arm if arm?
return :ppc if ppc?
return :dunno unless intel?
# See https://software.intel.com/en-us/articles/intel-architecture-and-processor-identification-with-cpuid-model-and-family-numbers
# and https://github.com/llvm/llvm-project/blob/main/llvm/lib/TargetParser/Host.cpp
# and https://en.wikipedia.org/wiki/List_of_Intel_CPU_microarchitectures#Roadmap
vendor_id = cpuinfo[/^vendor_id\s*: (.*)/, 1]
cpu_family = cpuinfo[/^cpu family\s*: ([0-9]+)/, 1].to_i
cpu_model = cpuinfo[/^model\s*: ([0-9]+)/, 1].to_i
unknown = :"unknown_0x#{cpu_family.to_s(16)}_0x#{cpu_model.to_s(16)}"
case vendor_id
when "GenuineIntel"
intel_family(cpu_family, cpu_model)
when "AuthenticAMD"
amd_family(cpu_family, cpu_model)
end || unknown
end
sig { params(family: Integer, cpu_model: Integer).returns(T.nilable(Symbol)) }
def intel_family(family, cpu_model)
case family
when 0x06
case cpu_model
when 0x3a, 0x3e
:ivybridge
when 0x2a, 0x2d
:sandybridge
when 0x25, 0x2c, 0x2f
:westmere
when 0x1a, 0x1e, 0x1f, 0x2e
:nehalem
when 0x17, 0x1d
:penryn
when 0x0f, 0x16
:merom
when 0x0d
:dothan
when 0x1c, 0x26, 0x27, 0x35, 0x36
:atom
when 0x3c, 0x3f, 0x45, 0x46
:haswell
when 0x3d, 0x47, 0x4f, 0x56
:broadwell
when 0x4e, 0x5e, 0x8e, 0x9e, 0xa5, 0xa6
:skylake
when 0x66
:cannonlake
when 0x6a, 0x6c, 0x7d, 0x7e
:icelake
when 0xa7
:rocketlake
when 0x8c, 0x8d
:tigerlake
when 0x97, 0x9a, 0xbe, 0xb7, 0xba, 0xbf, 0xaa, 0xac
:alderlake
when 0xc5, 0xb5, 0xc6, 0xbd
:arrowlake
when 0xcc
:pantherlake
when 0xad, 0xae
:graniterapids
when 0xcf, 0x8f
:sapphirerapids
end
when 0x0f
case cpu_model
when 0x06
:presler
when 0x03, 0x04
:prescott
end
end
end
sig { params(family: Integer, cpu_model: Integer).returns(T.nilable(Symbol)) }
def amd_family(family, cpu_model)
case family
when 0x06
:amd_k7
when 0x0f
:amd_k8
when 0x10
:amd_k10
when 0x11
:amd_k8_k10_hybrid
when 0x12
:amd_k10_llano
when 0x14
:bobcat
when 0x15
:bulldozer
when 0x16
:jaguar
when 0x17
case cpu_model
when 0x10..0x2f
:zen
when 0x30..0x3f, 0x47, 0x60..0x7f, 0x84..0x87, 0x90..0xaf
:zen2
end
when 0x19
case cpu_model
when ..0x0f, 0x20..0x5f
:zen3
when 0x10..0x1f, 0x60..0x7f, 0xa0..0xaf
:zen4
end
when 0x1a
:zen5
end
end
# Supported CPU instructions
sig { returns(T::Array[String]) }
def flags
@flags ||= T.let(cpuinfo[/^(?:flags|Features)\s*: (.*)/, 1]&.split, T.nilable(T::Array[String]))
@flags ||= []
end
# Compatibility with Mac method, which returns lowercase symbols
# instead of strings.
sig { returns(T::Array[Symbol]) }
def features
@features ||= T.let(flags.map(&:intern), T.nilable(T::Array[Symbol]))
end
%w[aes altivec avx avx2 lm ssse3 sse4_2].each do |flag|
define_method(:"#{flag}?") do
T.bind(self, OS::Linux::Hardware::CPU::ClassMethods)
flags.include? flag
end
end
sig { returns(T::Boolean) }
def sse3?
flags.include?("pni") || flags.include?("sse3")
end
sig { returns(T::Boolean) }
def sse4?
flags.include? "sse4_1"
end
private
sig { returns(String) }
def cpuinfo
@cpuinfo ||= T.let(File.read("/proc/cpuinfo"), T.nilable(String))
end
end
end
end
end
end
Hardware::CPU.singleton_class.prepend(OS::Linux::Hardware::CPU::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/cask/caskroom.rb | Library/Homebrew/extend/os/linux/cask/caskroom.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Cask
module Caskroom
module ClassMethods
sig { params(path: ::Pathname, _sudo: T::Boolean).void }
def chgrp_path(path, _sudo)
SystemCommand.run("chgrp", args: ["root", path], sudo: true)
end
end
end
end
end
end
Cask::Caskroom.singleton_class.prepend(OS::Linux::Cask::Caskroom::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/cask/installer.rb | Library/Homebrew/extend/os/linux/cask/installer.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Cask
module Installer
extend T::Helpers
requires_ancestor { ::Cask::Installer }
sig { void }
def check_stanza_os_requirements
return if artifacts.all? { |artifact| supported_artifact?(artifact) }
raise ::Cask::CaskError, "macOS is required for this software."
end
private
sig { params(artifact: ::Cask::Artifact::AbstractArtifact).returns(T::Boolean) }
def supported_artifact?(artifact)
return !artifact.manual_install if artifact.is_a?(::Cask::Artifact::Installer)
::Cask::Artifact::MACOS_ONLY_ARTIFACTS.exclude?(artifact.class)
end
end
end
end
end
Cask::Installer.prepend(OS::Linux::Cask::Installer)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/cask/config.rb | Library/Homebrew/extend/os/linux/cask/config.rb | # typed: strict
# frozen_string_literal: true
require "os/linux"
module OS
module Linux
module Cask
module Config
module ClassMethods
DEFAULT_DIRS = T.let({
vst_plugindir: "~/.vst",
vst3_plugindir: "~/.vst3",
fontdir: "#{ENV.fetch("XDG_DATA_HOME", "~/.local/share")}/fonts",
appdir: "~/.config/apps",
}.freeze, T::Hash[Symbol, String])
sig { returns(T::Hash[Symbol, T.any(LazyObject, String)]) }
def defaults
{
languages: LazyObject.new { Linux.languages },
}.merge(DEFAULT_DIRS).freeze
end
end
end
end
end
end
Cask::Config.singleton_class.prepend(OS::Linux::Cask::Config::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/cask/quarantine.rb | Library/Homebrew/extend/os/linux/cask/quarantine.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Cask
module Quarantine
module ClassMethods
extend T::Helpers
requires_ancestor { ::Cask::Quarantine }
sig { returns(T::Boolean) }
def available? = false
end
end
end
end
end
Cask::Quarantine.singleton_class.prepend(OS::Linux::Cask::Quarantine::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/cask/artifact/relocated.rb | Library/Homebrew/extend/os/linux/cask/artifact/relocated.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Cask
module Artifact
module Relocated
extend T::Helpers
requires_ancestor { ::Cask::Artifact::Relocated }
sig { params(file: ::Pathname, altname: ::Pathname, command: T.class_of(SystemCommand)).returns(T.nilable(SystemCommand::Result)) }
def add_altname_metadata(file, altname, command:)
# no-op on Linux: /usr/bin/xattr for setting extended attributes is not available there.
end
end
end
end
end
end
Cask::Artifact::Relocated.prepend(OS::Linux::Cask::Artifact::Relocated)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/requirements/xcode_requirement.rb | Library/Homebrew/extend/os/linux/requirements/xcode_requirement.rb | # typed: strict
# frozen_string_literal: true
require "requirement"
class XcodeRequirement < Requirement
sig { returns(T::Boolean) }
def xcode_installed_version!
true
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/bundle/bundle.rb | Library/Homebrew/extend/os/linux/bundle/bundle.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Bundle
module ClassMethods
sig { returns(T::Boolean) }
def mas_installed?
false
end
# Setup pkg-config, if present, to help locate packages
# Only need this on Linux as Homebrew provides a shim on macOS
sig { void }
def prepend_pkgconf_path_if_needed!
pkgconf = Formulary.factory("pkgconf")
return unless pkgconf.any_version_installed?
ENV.prepend_path "PATH", pkgconf.opt_bin.to_s
end
end
end
end
end
Homebrew::Bundle.singleton_class.prepend(OS::Linux::Bundle::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/bundle/skipper.rb | Library/Homebrew/extend/os/linux/bundle/skipper.rb | # typed: strict
# frozen_string_literal: true
require "cask/cask_loader"
require "cask/installer"
module OS
module Linux
module Bundle
module Skipper
module ClassMethods
sig { params(entry: Homebrew::Bundle::Dsl::Entry).returns(T::Boolean) }
def macos_only_entry?(entry)
entry.type == :mas
end
sig { params(entry: Homebrew::Bundle::Dsl::Entry).returns(T::Boolean) }
def macos_only_cask?(entry)
return false if entry.type != :cask
cask = ::Cask::CaskLoader.load(entry.name)
installer = ::Cask::Installer.new(cask)
installer.check_stanza_os_requirements
false
rescue ::Cask::CaskError
true
end
sig { params(entry: Homebrew::Bundle::Dsl::Entry, silent: T::Boolean).returns(T::Boolean) }
def skip?(entry, silent: false)
if macos_only_entry?(entry) || macos_only_cask?(entry)
unless silent
$stdout.puts Formatter.warning "Skipping #{entry.type} #{entry.name} (unsupported on Linux)"
end
true
else
super(entry)
end
end
end
end
end
end
end
Homebrew::Bundle::Skipper.singleton_class.prepend(OS::Linux::Bundle::Skipper::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/extend/pathname.rb | Library/Homebrew/extend/os/linux/extend/pathname.rb | # typed: strict
# frozen_string_literal: true
require "os/linux/elf"
module ELFPathname
module ClassMethods
sig { params(path: T.any(Pathname, String, ELFShim)).returns(ELFShim) }
def wrap(path)
return path if path.is_a?(ELFShim)
path = ::Pathname.new(path)
path.extend(ELFShim)
T.cast(path, ELFShim)
end
end
extend ClassMethods
end
BinaryPathname.singleton_class.prepend(ELFPathname::ClassMethods)
module OS
module Linux
module Pathname
module ClassMethods
extend T::Helpers
requires_ancestor { T.class_of(::Pathname) }
sig { void }
def activate_extensions!
super
prepend(ELFShim)
end
end
end
end
end
Pathname.singleton_class.prepend(OS::Linux::Pathname::ClassMethods)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/extend/ENV/std.rb | Library/Homebrew/extend/os/linux/extend/ENV/std.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Stdenv
extend T::Helpers
requires_ancestor { ::SharedEnvExtension }
sig {
params(
formula: T.nilable(::Formula),
cc: T.nilable(String),
build_bottle: T.nilable(T::Boolean),
bottle_arch: T.nilable(String),
testing_formula: T::Boolean,
debug_symbols: T.nilable(T::Boolean),
).void
}
def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_arch: nil,
testing_formula: false, debug_symbols: false)
super
prepend_path "CPATH", HOMEBREW_PREFIX/"include"
prepend_path "LIBRARY_PATH", HOMEBREW_PREFIX/"lib"
prepend_path "LD_RUN_PATH", HOMEBREW_PREFIX/"lib"
return unless formula
prepend_path "CPATH", formula.include
prepend_path "LIBRARY_PATH", formula.lib
prepend_path "LD_RUN_PATH", formula.lib
end
sig { void }
def libxml2
append "CPPFLAGS", "-I#{::Formula["libxml2"].include/"libxml2"}"
rescue FormulaUnavailableError
nil
end
end
end
end
Stdenv.prepend(OS::Linux::Stdenv)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/extend/ENV/super.rb | Library/Homebrew/extend/os/linux/extend/ENV/super.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module Superenv
extend T::Helpers
requires_ancestor { SharedEnvExtension }
requires_ancestor { ::Superenv }
module ClassMethods
sig { returns(::Pathname) }
def shims_path
HOMEBREW_SHIMS_PATH/"linux/super"
end
sig { returns(T.nilable(::Pathname)) }
def bin
shims_path.realpath
end
end
sig {
params(
formula: T.nilable(Formula),
cc: T.nilable(String),
build_bottle: T.nilable(T::Boolean),
bottle_arch: T.nilable(String),
testing_formula: T::Boolean,
debug_symbols: T.nilable(T::Boolean),
).void
}
def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_arch: nil,
testing_formula: false, debug_symbols: false)
super
self["HOMEBREW_OPTIMIZATION_LEVEL"] = "O2"
self["HOMEBREW_DYNAMIC_LINKER"] = determine_dynamic_linker_path
self["HOMEBREW_RPATH_PATHS"] = determine_rpath_paths(formula)
m4_path_deps = ["libtool", "bison"]
self["M4"] = "#{HOMEBREW_PREFIX}/opt/m4/bin/m4" if deps.any? { m4_path_deps.include?(it.name) }
return unless ::Hardware::CPU.arm64?
# Build jemalloc-sys rust crate on ARM64/AArch64 with support for page sizes up to 64K.
self["JEMALLOC_SYS_WITH_LG_PAGE"] = "16"
# Workaround patchelf.rb bug causing segfaults and preventing bottling on ARM64/AArch64
# https://github.com/Homebrew/homebrew-core/issues/163826
self["CGO_ENABLED"] = "0"
# Pointer authentication and BTI are hardening techniques most distros
# use by default on their packages. arm64 Linux we're packaging
# everything from scratch so the entire dependency tree can have it.
append_to_cccfg "b" if ::DevelopmentTools.gcc_version("gcc") >= 9
end
sig { returns(T::Array[::Pathname]) }
def homebrew_extra_paths
paths = super
paths += %w[binutils make].filter_map do |f|
bin = Formulary.factory(f).opt_bin
bin if bin.directory?
rescue FormulaUnavailableError
nil
end
paths
end
sig { returns(T::Array[::Pathname]) }
def homebrew_extra_isystem_paths
paths = []
# Add paths for GCC headers when building against versioned glibc because we have to use -nostdinc.
if deps.any? { |d| d.name.match?(/^glibc@.+$/) }
gcc_include_dir = Utils.safe_popen_read(cc, "--print-file-name=include").chomp
gcc_include_fixed_dir = Utils.safe_popen_read(cc, "--print-file-name=include-fixed").chomp
paths << gcc_include_dir << gcc_include_fixed_dir
end
paths.map { |p| ::Pathname.new(p) }
end
sig { params(formula: T.nilable(Formula)).returns(PATH) }
def determine_rpath_paths(formula)
PATH.new(
*formula&.lib,
"#{HOMEBREW_PREFIX}/opt/gcc/lib/gcc/current",
PATH.new(run_time_deps.map { |dep| dep.opt_lib.to_s }).existing,
"#{HOMEBREW_PREFIX}/lib",
)
end
sig { returns(T.nilable(String)) }
def determine_dynamic_linker_path
path = "#{HOMEBREW_PREFIX}/lib/ld.so"
return unless File.readable? path
path
end
end
end
end
Superenv.singleton_class.prepend(OS::Linux::Superenv::ClassMethods)
Superenv.prepend(OS::Linux::Superenv)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/linux/extend/ENV/shared.rb | Library/Homebrew/extend/os/linux/extend/ENV/shared.rb | # typed: strict
# frozen_string_literal: true
module OS
module Linux
module SharedEnvExtension
extend T::Helpers
requires_ancestor { ::SharedEnvExtension }
sig { returns(Symbol) }
def effective_arch
if build_bottle && (bottle_arch = self.bottle_arch)
bottle_arch.to_sym
elsif build_bottle
::Hardware.oldest_cpu
elsif ::Hardware::CPU.intel? || ::Hardware::CPU.arm?
:native
else
:dunno
end
end
end
end
end
SharedEnvExtension.prepend(OS::Linux::SharedEnvExtension)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/extend/ENV/std.rb | Library/Homebrew/extend/os/extend/ENV/std.rb | # typed: strict
# frozen_string_literal: true
if OS.mac?
require "extend/os/mac/extend/ENV/std"
elsif OS.linux?
require "extend/os/linux/extend/ENV/std"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/extend/ENV/super.rb | Library/Homebrew/extend/os/extend/ENV/super.rb | # typed: strict
# frozen_string_literal: true
if OS.mac?
require "extend/os/mac/extend/ENV/super"
elsif OS.linux?
require "extend/os/linux/extend/ENV/super"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/extend/ENV/shared.rb | Library/Homebrew/extend/os/extend/ENV/shared.rb | # typed: strict
# frozen_string_literal: true
if OS.mac?
require "extend/os/mac/extend/ENV/shared"
elsif OS.linux?
require "extend/os/linux/extend/ENV/shared"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/unpack_strategy/zip.rb | Library/Homebrew/extend/os/unpack_strategy/zip.rb | # typed: strict
# frozen_string_literal: true
require "extend/os/mac/unpack_strategy/zip" if OS.mac?
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/os/language/java.rb | Library/Homebrew/extend/os/language/java.rb | # typed: strict
# frozen_string_literal: true
require "extend/os/mac/language/java" if OS.mac?
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/ENV/std.rb | Library/Homebrew/extend/ENV/std.rb | # typed: strict
# frozen_string_literal: true
require "hardware"
require "extend/ENV/shared"
module Stdenv
include SharedEnvExtension
SAFE_CFLAGS_FLAGS = "-w -pipe"
private_constant :SAFE_CFLAGS_FLAGS
sig {
params(
formula: T.nilable(Formula),
cc: T.nilable(String),
build_bottle: T.nilable(T::Boolean),
bottle_arch: T.nilable(String),
testing_formula: T::Boolean,
debug_symbols: T.nilable(T::Boolean),
).void
}
def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_arch: nil, testing_formula: false,
debug_symbols: false)
super
self["HOMEBREW_ENV"] = "std"
ORIGINAL_PATHS.reverse_each { |p| prepend_path "PATH", p }
prepend_path "PATH", HOMEBREW_SHIMS_PATH/"shared"
# Set the default pkg-config search path, overriding the built-in paths
# Anything in PKG_CONFIG_PATH is searched before paths in this variable
self["PKG_CONFIG_LIBDIR"] = determine_pkg_config_libdir
self["MAKEFLAGS"] = "-j#{make_jobs}"
self["RUSTC_WRAPPER"] = "#{HOMEBREW_SHIMS_PATH}/shared/rustc_wrapper"
self["HOMEBREW_RUSTFLAGS"] = Hardware.rustflags_target_cpu(effective_arch)
if HOMEBREW_PREFIX.to_s != "/usr/local"
# /usr/local is already an -isystem and -L directory so we skip it
self["CPPFLAGS"] = "-isystem#{HOMEBREW_PREFIX}/include"
self["LDFLAGS"] = "-L#{HOMEBREW_PREFIX}/lib"
# CMake ignores the variables above
self["CMAKE_PREFIX_PATH"] = HOMEBREW_PREFIX.to_s
end
frameworks = HOMEBREW_PREFIX.join("Frameworks")
if frameworks.directory?
append "CPPFLAGS", "-F#{frameworks}"
append "LDFLAGS", "-F#{frameworks}"
self["CMAKE_FRAMEWORK_PATH"] = frameworks.to_s
end
# Os is the default Apple uses for all its stuff so let's trust them
define_cflags "-Os #{SAFE_CFLAGS_FLAGS}"
begin
send(compiler)
rescue CompilerSelectionError
# We don't care if our compiler fails to build the formula during `brew test`.
raise unless testing_formula
send(DevelopmentTools.default_compiler)
end
return unless cc&.match?(GNU_GCC_REGEXP)
gcc_formula = gcc_version_formula(cc)
append_path "PATH", gcc_formula.opt_bin.to_s
end
sig { returns(T.nilable(PATH)) }
def determine_pkg_config_libdir
PATH.new(
HOMEBREW_PREFIX/"lib/pkgconfig",
HOMEBREW_PREFIX/"share/pkgconfig",
homebrew_extra_pkg_config_paths,
"/usr/lib/pkgconfig",
).existing
end
# Removes the MAKEFLAGS environment variable, causing make to use a single job.
# This is useful for makefiles with race conditions.
# When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion.
sig { params(block: T.proc.returns(T.untyped)).returns(T.untyped) }
def deparallelize(&block)
old = self["MAKEFLAGS"]
remove "MAKEFLAGS", /-j\d+/
if block
begin
yield
ensure
self["MAKEFLAGS"] = old
end
end
old
end
%w[O1 O0].each do |opt|
define_method opt do
send(:remove_from_cflags, /-O./)
send(:append_to_cflags, "-#{opt}")
end
end
sig { returns(T.any(String, Pathname)) }
def determine_cc
s = super
begin
return Formulary.factory("llvm").opt_bin/"clang" if s == "llvm_clang"
rescue FormulaUnavailableError
# Don't fail and just let callee handle Pathname("llvm_clang")
end
DevelopmentTools.locate(s) || Pathname(s)
end
private :determine_cc
sig { returns(Pathname) }
def determine_cxx
dir, base = Pathname(determine_cc).split
dir/base.to_s.sub("gcc", "g++").sub("clang", "clang++")
end
private :determine_cxx
GNU_GCC_VERSIONS.each do |n|
define_method(:"gcc-#{n}") do
super()
send(:set_cpu_cflags)
end
end
sig { void }
def clang
super
replace_in_cflags(/-Xarch_#{Hardware::CPU.arch_32_bit} (-march=\S*)/, '\1')
map = Hardware::CPU.optimization_flags.dup
if DevelopmentTools.clang_build_version < 700
# Clang mistakenly enables AES-NI on plain Nehalem
map[:nehalem] = "-march=nehalem -Xclang -target-feature -Xclang -aes"
end
set_cpu_cflags(map)
end
sig { void }
def cxx11
append "CXX", "-std=c++11"
libcxx
end
sig { void }
def libcxx
append "CXX", "-stdlib=libc++" if compiler == :clang
end
private
sig { params(before: Regexp, after: String).void }
def replace_in_cflags(before, after)
CC_FLAG_VARS.each do |key|
self[key] = fetch(key).sub(before, after) if key?(key)
end
end
# Convenience method to set all C compiler flags in one shot.
sig { params(val: String).void }
def define_cflags(val)
CC_FLAG_VARS.each { |key| self[key] = val }
end
# Sets architecture-specific flags for every environment variable
# given in the list `flags`.
sig { params(flags: T::Array[String], map: T::Hash[Symbol, String]).void }
def set_cpu_flags(flags, map = Hardware::CPU.optimization_flags)
cflags =~ /(-Xarch_#{Hardware::CPU.arch_32_bit} )-march=/
xarch = Regexp.last_match(1).to_s
remove flags, /(-Xarch_#{Hardware::CPU.arch_32_bit} )?-march=\S*/
remove flags, /( -Xclang \S+)+/
remove flags, /-mssse3/
remove flags, /-msse4(\.\d)?/
append flags, xarch unless xarch.empty?
append flags, map.fetch(effective_arch)
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_pkg_config_paths
[]
end
sig { params(map: T::Hash[Symbol, String]).void }
def set_cpu_cflags(map = Hardware::CPU.optimization_flags)
set_cpu_flags(CC_FLAG_VARS, map)
end
end
require "extend/os/extend/ENV/std"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/ENV/super.rb | Library/Homebrew/extend/ENV/super.rb | # typed: strict
# frozen_string_literal: true
require "extend/ENV/shared"
require "development_tools"
require "utils/output"
# ### Why `superenv`?
#
# 1. Only specify the environment we need (*NO* LDFLAGS for cmake)
# 2. Only apply compiler-specific options when we are calling that compiler
# 3. Force all incpaths and libpaths into the cc instantiation (fewer bugs)
# 4. Cater toolchain usage to specific Xcode versions
# 5. Remove flags that we don't want or that will break builds
# 6. Simpler code
# 7. Simpler formulae that *just work*
# 8. Build-system agnostic configuration of the toolchain
module Superenv
include SharedEnvExtension
include Utils::Output::Mixin
sig { returns(T::Array[Formula]) }
attr_accessor :keg_only_deps
sig { returns(T::Array[Formula]) }
attr_accessor :deps
sig { returns(T::Array[Formula]) }
attr_accessor :run_time_deps
sig { params(base: Superenv).void }
def self.extended(base)
base.keg_only_deps = []
base.deps = []
base.run_time_deps = []
end
# The location of Homebrew's shims.
#
# @api public
sig { returns(Pathname) }
def self.shims_path
HOMEBREW_SHIMS_PATH/"super"
end
sig { returns(T.nilable(Pathname)) }
def self.bin; end
sig { void }
def initialize
@keg_only_deps = T.let([], T::Array[Formula])
@deps = T.let([], T::Array[Formula])
@run_time_deps = T.let([], T::Array[Formula])
@formula = T.let(nil, T.nilable(Formula))
end
sig { void }
def reset
super
# Configure scripts generated by autoconf 2.61 or later export as_nl, which
# we use as a heuristic for running under configure
delete("as_nl")
end
sig {
params(
formula: T.nilable(Formula),
cc: T.nilable(String),
build_bottle: T.nilable(T::Boolean),
bottle_arch: T.nilable(String),
testing_formula: T::Boolean,
debug_symbols: T.nilable(T::Boolean),
).void
}
def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_arch: nil, testing_formula: false,
debug_symbols: false)
super
send(compiler)
self["HOMEBREW_ENV"] = "super"
self["MAKEFLAGS"] ||= "-j#{determine_make_jobs}"
self["RUSTC_WRAPPER"] = "#{HOMEBREW_SHIMS_PATH}/shared/rustc_wrapper"
self["HOMEBREW_RUSTFLAGS"] = Hardware.rustflags_target_cpu(effective_arch)
self["PATH"] = determine_path
self["PKG_CONFIG_PATH"] = determine_pkg_config_path
self["PKG_CONFIG_LIBDIR"] = determine_pkg_config_libdir || ""
self["HOMEBREW_CCCFG"] = determine_cccfg
self["HOMEBREW_OPTIMIZATION_LEVEL"] = compiler.match?(GNU_GCC_REGEXP) ? "O2" : "Os"
self["HOMEBREW_BREW_FILE"] = HOMEBREW_BREW_FILE.to_s
self["HOMEBREW_PREFIX"] = HOMEBREW_PREFIX.to_s
self["HOMEBREW_CELLAR"] = HOMEBREW_CELLAR.to_s
self["HOMEBREW_OPT"] = "#{HOMEBREW_PREFIX}/opt"
self["HOMEBREW_TEMP"] = HOMEBREW_TEMP.to_s
self["HOMEBREW_OPTFLAGS"] = determine_optflags
self["HOMEBREW_ARCHFLAGS"] = ""
self["HOMEBREW_MAKE_JOBS"] = determine_make_jobs.to_s
self["CMAKE_PREFIX_PATH"] = determine_cmake_prefix_path
self["CMAKE_FRAMEWORK_PATH"] = determine_cmake_frameworks_path
self["CMAKE_INCLUDE_PATH"] = determine_cmake_include_path
self["CMAKE_LIBRARY_PATH"] = determine_cmake_library_path
self["ACLOCAL_PATH"] = determine_aclocal_path
self["M4"] = "#{HOMEBREW_PREFIX}/opt/m4/bin/m4" if deps.any? { |d| d.name == "libtool" }
self["HOMEBREW_ISYSTEM_PATHS"] = determine_isystem_paths
self["HOMEBREW_INCLUDE_PATHS"] = determine_include_paths
self["HOMEBREW_LIBRARY_PATHS"] = determine_library_paths
self["HOMEBREW_DEPENDENCIES"] = determine_dependencies
self["HOMEBREW_FORMULA_PREFIX"] = @formula.prefix unless @formula.nil?
# Prevent the OpenSSL rust crate from building a vendored OpenSSL.
# https://github.com/sfackler/rust-openssl/blob/994e5ff8c63557ab2aa85c85cc6956b0b0216ca7/openssl/src/lib.rs#L65
self["OPENSSL_NO_VENDOR"] = "1"
# Prevent Go from automatically downloading a newer toolchain than the one that we have.
# https://tip.golang.org/doc/toolchain
self["GOTOOLCHAIN"] = "local"
# Prevent maturin from automatically downloading its own rust
self["MATURIN_NO_INSTALL_RUST"] = "1"
# Prevent Python packages from using bundled libraries by default.
# Currently for hidapi, pyzmq and pynacl
self["HIDAPI_SYSTEM_HIDAPI"] = "1"
self["PYZMQ_NO_BUNDLE"] = "1"
self["SODIUM_INSTALL"] = "system"
set_debug_symbols if debug_symbols
# The HOMEBREW_CCCFG ENV variable is used by the ENV/cc tool to control
# compiler flag stripping. It consists of a string of characters which act
# as flags. Some of these flags are mutually exclusive.
#
# O - Enables argument refurbishing. Only active under the
# make/bsdmake wrappers currently.
# x - Enable C++11 mode.
# g - Enable "-stdlib=libc++" for clang.
# h - Enable "-stdlib=libstdc++" for clang.
# K - Don't strip -arch <arch>, -m32, or -m64
# d - Don't strip -march=<target>. Use only in formulae that
# have runtime detection of CPU features.
# D - Generate debugging information
# w - Pass `-no_weak_imports` to the linker
# f - Pass `-no_fixup_chains` to `ld` whenever it
# is invoked with `-undefined dynamic_lookup`
# o - Pass `-oso_prefix` to `ld` whenever it is invoked
# c - Pass `-ld_classic` to `ld` whenever it is invoked
# with `-dead_strip_dylibs`
# b - Pass `-mbranch-protection=standard` to the compiler
#
# These flags will also be present:
# a - apply fix for apr-1-config path
end
private
sig { params(val: T.any(String, Pathname)).returns(String) }
def cc=(val)
self["HOMEBREW_CC"] = super
end
sig { params(val: T.any(String, Pathname)).returns(String) }
def cxx=(val)
self["HOMEBREW_CXX"] = super
end
sig { returns(String) }
def determine_cxx
determine_cc.to_s.gsub("gcc", "g++").gsub("clang", "clang++")
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_paths
# Reverse sort by version so that we prefer the newest when there are multiple.
deps.select { |d| d.name.match? Version.formula_optionally_versioned_regex(:python) }
.sort_by(&:version)
.reverse
.map { |d| d.opt_libexec/"bin" }
end
sig { returns(T.nilable(PATH)) }
def determine_path
path = PATH.new(Superenv.bin)
# Formula dependencies can override standard tools.
path.append(deps.map(&:opt_bin))
path.append(homebrew_extra_paths)
path.append("/usr/bin", "/bin", "/usr/sbin", "/sbin")
begin
path.append(gcc_version_formula(T.must(homebrew_cc)).opt_bin) if homebrew_cc&.match?(GNU_GCC_REGEXP)
rescue FormulaUnavailableError
# Don't fail and don't add these formulae to the path if they don't exist.
nil
end
path.existing
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_pkg_config_paths
[]
end
sig { returns(T.nilable(PATH)) }
def determine_pkg_config_path
PATH.new(
deps.map { |d| d.opt_lib/"pkgconfig" },
deps.map { |d| d.opt_share/"pkgconfig" },
).existing
end
sig { returns(T.nilable(PATH)) }
def determine_pkg_config_libdir
PATH.new(
homebrew_extra_pkg_config_paths,
).existing
end
sig { returns(T.nilable(PATH)) }
def determine_aclocal_path
PATH.new(
keg_only_deps.map { |d| d.opt_share/"aclocal" },
HOMEBREW_PREFIX/"share/aclocal",
).existing
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_isystem_paths
[]
end
sig { returns(T.nilable(PATH)) }
def determine_isystem_paths
PATH.new(
HOMEBREW_PREFIX/"include",
homebrew_extra_isystem_paths,
).existing
end
sig { returns(T.nilable(PATH)) }
def determine_include_paths
PATH.new(keg_only_deps.map(&:opt_include)).existing
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_library_paths
[]
end
sig { returns(T.nilable(PATH)) }
def determine_library_paths
paths = []
if compiler.match?(GNU_GCC_REGEXP)
# Add path to GCC runtime libs for version being used to compile,
# so that the linker will find those libs before any that may be linked in $HOMEBREW_PREFIX/lib.
# https://github.com/Homebrew/brew/pull/11459#issuecomment-851075936
begin
f = gcc_version_formula(compiler.to_s)
rescue FormulaUnavailableError
nil
else
paths << (f.opt_lib/"gcc"/f.version.major) if f.any_version_installed?
end
end
# Don't add `llvm` to library paths; this leads to undesired linkage to LLVM's `libunwind`
paths += keg_only_deps.reject { |dep| dep.name.match?(/^llvm(@\d+)?$/) }
.map(&:opt_lib)
paths << (HOMEBREW_PREFIX/"lib")
paths += homebrew_extra_library_paths
PATH.new(paths).existing
end
sig { returns(String) }
def determine_dependencies
deps.map(&:name).join(",")
end
sig { returns(T.nilable(PATH)) }
def determine_cmake_prefix_path
PATH.new(
keg_only_deps.map(&:opt_prefix),
HOMEBREW_PREFIX.to_s,
).existing
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_cmake_include_paths
[]
end
sig { returns(T.nilable(PATH)) }
def determine_cmake_include_path
PATH.new(homebrew_extra_cmake_include_paths).existing
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_cmake_library_paths
[]
end
sig { returns(T.nilable(PATH)) }
def determine_cmake_library_path
PATH.new(homebrew_extra_cmake_library_paths).existing
end
sig { returns(T::Array[Pathname]) }
def homebrew_extra_cmake_frameworks_paths
[]
end
sig { returns(T.nilable(PATH)) }
def determine_cmake_frameworks_path
PATH.new(
deps.map(&:opt_frameworks),
homebrew_extra_cmake_frameworks_paths,
).existing
end
sig { returns(String) }
def determine_make_jobs
Homebrew::EnvConfig.make_jobs
end
sig { returns(String) }
def determine_optflags
Hardware::CPU.optimization_flags.fetch(effective_arch)
rescue KeyError
odebug "Building a bottle for custom architecture (#{effective_arch})..."
Hardware::CPU.arch_flag(effective_arch)
end
sig { returns(String) }
def determine_cccfg
""
end
public
# Removes the MAKEFLAGS environment variable, causing make to use a single job.
# This is useful for makefiles with race conditions.
# When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion.
sig { params(block: T.nilable(T.proc.returns(T.untyped))).returns(T.untyped) }
def deparallelize(&block)
old_makeflags = delete("MAKEFLAGS")
old_make_jobs = delete("HOMEBREW_MAKE_JOBS")
self["HOMEBREW_MAKE_JOBS"] = "1"
if block
begin
yield
ensure
self["MAKEFLAGS"] = old_makeflags
self["HOMEBREW_MAKE_JOBS"] = old_make_jobs
end
end
old_makeflags
end
sig { returns(Integer) }
def make_jobs
self["MAKEFLAGS"] =~ /-\w*j(\d+)/
[Regexp.last_match(1).to_i, 1].max
end
sig { void }
def permit_arch_flags
append_to_cccfg "K"
end
sig { void }
def runtime_cpu_detection
append_to_cccfg "d"
end
sig { void }
def cxx11
append_to_cccfg "x"
append_to_cccfg "g" if homebrew_cc == "clang"
end
sig { void }
def libcxx
append_to_cccfg "g" if compiler == :clang
end
sig { void }
def set_debug_symbols
append_to_cccfg "D"
end
sig { void }
def refurbish_args
append_to_cccfg "O"
end
# This is an exception where we want to use this method name format.
# rubocop: disable Naming/MethodName
sig { params(block: T.nilable(T.proc.void)).void }
def O0(&block)
if block
with_env(HOMEBREW_OPTIMIZATION_LEVEL: "O0", &block)
else
self["HOMEBREW_OPTIMIZATION_LEVEL"] = "O0"
end
end
sig { params(block: T.nilable(T.proc.void)).void }
def O1(&block)
if block
with_env(HOMEBREW_OPTIMIZATION_LEVEL: "O1", &block)
else
self["HOMEBREW_OPTIMIZATION_LEVEL"] = "O1"
end
end
sig { params(block: T.nilable(T.proc.void)).void }
def O3(&block)
if block
with_env(HOMEBREW_OPTIMIZATION_LEVEL: "O3", &block)
else
self["HOMEBREW_OPTIMIZATION_LEVEL"] = "O3"
end
end
# rubocop: enable Naming/MethodName
end
require "extend/os/extend/ENV/super"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/extend/ENV/shared.rb | Library/Homebrew/extend/ENV/shared.rb | # typed: strict
# frozen_string_literal: true
require "compilers"
require "development_tools"
# Homebrew extends Ruby's `ENV` to make our code more readable.
# Implemented in {SharedEnvExtension} and either {Superenv} or
# {Stdenv} (depending on the build mode).
# @see Superenv
# @see Stdenv
# @see https://www.rubydoc.info/stdlib/Env Ruby's ENV API
module SharedEnvExtension
extend T::Helpers
include CompilerConstants
include Utils::Output::Mixin
requires_ancestor { Sorbet::Private::Static::ENVClass }
CC_FLAG_VARS = %w[CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS].freeze
private_constant :CC_FLAG_VARS
FC_FLAG_VARS = %w[FCFLAGS FFLAGS].freeze
private_constant :FC_FLAG_VARS
SANITIZED_VARS = %w[
CDPATH CLICOLOR_FORCE
CPATH C_INCLUDE_PATH CPLUS_INCLUDE_PATH OBJC_INCLUDE_PATH
CC CXX OBJC OBJCXX CPP MAKE LD LDSHARED
CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS LDFLAGS CPPFLAGS
MACOSX_DEPLOYMENT_TARGET SDKROOT DEVELOPER_DIR
CMAKE_PREFIX_PATH CMAKE_INCLUDE_PATH CMAKE_FRAMEWORK_PATH
GOBIN GOPATH GOROOT PERL_MB_OPT PERL_MM_OPT
LIBRARY_PATH LD_LIBRARY_PATH LD_PRELOAD LD_RUN_PATH
RUSTFLAGS
].freeze
private_constant :SANITIZED_VARS
sig { returns(T.nilable(T::Boolean)) }
attr_reader :build_bottle
sig { returns(T.nilable(String)) }
attr_reader :bottle_arch
sig {
params(
formula: T.nilable(Formula),
cc: T.nilable(String),
build_bottle: T.nilable(T::Boolean),
bottle_arch: T.nilable(String),
testing_formula: T::Boolean,
debug_symbols: T.nilable(T::Boolean),
).void
}
def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_arch: nil, testing_formula: false,
debug_symbols: false)
@formula = T.let(formula, T.nilable(Formula))
@cc = T.let(cc, T.nilable(String))
@build_bottle = T.let(build_bottle, T.nilable(T::Boolean))
@bottle_arch = T.let(bottle_arch, T.nilable(String))
@debug_symbols = T.let(debug_symbols, T.nilable(T::Boolean))
@testing_formula = T.let(testing_formula, T.nilable(T::Boolean))
reset
end
sig { void }
def reset
SANITIZED_VARS.each { |k| delete(k) }
end
private :reset
sig { returns(T::Hash[String, T.nilable(String)]) }
def remove_cc_etc
keys = %w[CC CXX OBJC OBJCXX LD CPP CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS LDFLAGS CPPFLAGS]
keys.to_h { |key| [key, delete(key)] }
end
sig { params(newflags: String).void }
def append_to_cflags(newflags)
append(CC_FLAG_VARS, newflags)
end
sig { params(val: T.any(Regexp, String)).void }
def remove_from_cflags(val)
remove CC_FLAG_VARS, val
end
sig { params(value: String).void }
def append_to_cccfg(value)
append("HOMEBREW_CCCFG", value, "")
end
sig { params(keys: T.any(String, T::Array[String]), value: T.untyped, separator: String).void }
def append(keys, value, separator = " ")
value = value.to_s
Array(keys).each do |key|
old_value = self[key]
self[key] = if old_value.blank?
value
else
old_value + separator + value
end
end
end
sig { params(keys: T.any(String, T::Array[String]), value: T.untyped, separator: String).void }
def prepend(keys, value, separator = " ")
value = value.to_s
Array(keys).each do |key|
old_value = self[key]
self[key] = if old_value.blank?
value
else
value + separator + old_value
end
end
end
sig { params(key: String, path: T.any(String, Pathname)).void }
def append_path(key, path)
self[key] = PATH.new(self[key]).append(path)
end
sig { params(rustflags: String).void }
def append_to_rustflags(rustflags)
append("HOMEBREW_RUSTFLAGS", rustflags)
end
# Prepends a directory to `PATH`.
# Is the formula struggling to find the pkgconfig file? Point it to it.
# This is done automatically for keg-only formulae.
# <pre>ENV.prepend_path "PKG_CONFIG_PATH", "#{Formula["glib"].opt_lib}/pkgconfig"</pre>
# Prepending a system path such as /usr/bin is a no-op so that requirements
# don't accidentally override superenv shims or formulae's `bin` directories.
# <pre>ENV.prepend_path "PATH", which("emacs").dirname</pre>
sig { params(key: String, path: T.any(String, Pathname)).void }
def prepend_path(key, path)
return if %w[/usr/bin /bin /usr/sbin /sbin].include? path.to_s
self[key] = PATH.new(self[key]).prepend(path)
end
sig { params(key: String, path: T.any(String, Pathname)).void }
def prepend_create_path(key, path)
path = Pathname(path)
path.mkpath
prepend_path key, path
end
sig { params(keys: T.any(String, T::Array[String]), value: T.untyped).void }
def remove(keys, value)
return if value.nil?
Array(keys).each do |key|
old_value = self[key]
next if old_value.nil?
new_value = old_value.sub(value, "")
if new_value.empty?
delete(key)
else
self[key] = new_value
end
end
end
sig { returns(T.nilable(String)) }
def cc
self["CC"]
end
sig { returns(T.nilable(String)) }
def cxx
self["CXX"]
end
sig { returns(T.nilable(String)) }
def cflags
self["CFLAGS"]
end
sig { returns(T.nilable(String)) }
def cxxflags
self["CXXFLAGS"]
end
sig { returns(T.nilable(String)) }
def cppflags
self["CPPFLAGS"]
end
sig { returns(T.nilable(String)) }
def ldflags
self["LDFLAGS"]
end
sig { returns(T.nilable(String)) }
def fc
self["FC"]
end
sig { returns(T.nilable(String)) }
def fflags
self["FFLAGS"]
end
sig { returns(T.nilable(String)) }
def fcflags
self["FCFLAGS"]
end
# Outputs the current compiler.
# <pre># Do something only for the system clang
# if ENV.compiler == :clang
# # modify CFLAGS CXXFLAGS OBJCFLAGS OBJCXXFLAGS in one go:
# ENV.append_to_cflags "-I ./missing/includes"
# end</pre>
sig { returns(T.any(Symbol, String)) }
def compiler
@compiler ||= T.let(nil, T.nilable(T.any(Symbol, String)))
@compiler ||= if (cc = @cc)
warn_about_non_apple_gcc(cc) if cc.match?(GNU_GCC_REGEXP)
fetch_compiler(cc, "--cc")
elsif (cc = homebrew_cc)
warn_about_non_apple_gcc(cc) if cc.match?(GNU_GCC_REGEXP)
compiler = fetch_compiler(cc, "HOMEBREW_CC")
if @formula
compilers = [compiler] + CompilerSelector.compilers
compiler = CompilerSelector.select_for(@formula, compilers, testing_formula: @testing_formula == true)
end
compiler
elsif @formula
CompilerSelector.select_for(@formula, testing_formula: @testing_formula == true)
else
DevelopmentTools.default_compiler
end
end
sig { returns(T.any(String, Pathname)) }
def determine_cc
case (cc = compiler)
when Symbol
COMPILER_SYMBOL_MAP.invert.fetch(cc)
else
cc
end
end
private :determine_cc
COMPILERS.each do |compiler|
define_method(compiler) do
@compiler = T.let(compiler, T.nilable(T.any(Symbol, String)))
send(:cc=, send(:determine_cc))
send(:cxx=, send(:determine_cxx))
end
end
sig { void }
def fortran
# Ignore repeated calls to this function as it will misleadingly warn about
# building with an alternative Fortran compiler without optimization flags,
# despite it often being the Homebrew-provided one set up in the first call.
return if @fortran_setup_done
@fortran_setup_done = T.let(true, T.nilable(TrueClass))
flags = []
if fc
opoo "Building with an unsupported Fortran compiler"
self["F77"] ||= fc
else
if (gfortran = which("gfortran", (HOMEBREW_PREFIX/"bin").to_s))
ohai "Using Homebrew-provided Fortran compiler"
elsif (gfortran = which("gfortran", PATH.new(ORIGINAL_PATHS)))
ohai "Using a Fortran compiler found at #{gfortran}"
end
if gfortran
puts "This may be changed by setting the `$FC` environment variable."
self["FC"] = self["F77"] = gfortran
flags = FC_FLAG_VARS
end
end
flags.each { |key| self[key] = cflags }
set_cpu_flags(flags)
end
sig { returns(Symbol) }
def effective_arch
if @build_bottle && @bottle_arch
@bottle_arch.to_sym
else
Hardware.oldest_cpu
end
end
sig { params(name: String).returns(Formula) }
def gcc_version_formula(name)
version = name[GNU_GCC_REGEXP, 1]
gcc_version_name = "gcc@#{version}"
gcc = Formulary.factory("gcc")
if gcc.respond_to?(:version_suffix) && T.unsafe(gcc).version_suffix == version
gcc
else
Formulary.factory(gcc_version_name)
end
end
private :gcc_version_formula
sig { params(name: String).void }
def warn_about_non_apple_gcc(name)
begin
gcc_formula = gcc_version_formula(name)
rescue FormulaUnavailableError => e
raise <<~EOS
Homebrew GCC requested, but formula #{e.name} not found!
EOS
end
return if gcc_formula.opt_prefix.exist?
raise <<~EOS
The requested Homebrew GCC was not installed. You must:
brew install #{gcc_formula.full_name}
EOS
end
private :warn_about_non_apple_gcc
sig { void }
def permit_arch_flags; end
sig { returns(Integer) }
def make_jobs
Homebrew::EnvConfig.make_jobs.to_i
end
sig { void }
def refurbish_args; end
private
sig { params(_flags: T::Array[String], _map: T::Hash[Symbol, String]).void }
def set_cpu_flags(_flags, _map = {}); end
sig { params(val: T.any(String, Pathname)).returns(String) }
def cc=(val)
self["CC"] = self["OBJC"] = val.to_s
end
sig { params(val: T.any(String, Pathname)).returns(String) }
def cxx=(val)
self["CXX"] = self["OBJCXX"] = val.to_s
end
sig { returns(T.nilable(String)) }
def homebrew_cc
self["HOMEBREW_CC"]
end
sig { params(value: String, source: String).returns(Symbol) }
def fetch_compiler(value, source)
COMPILER_SYMBOL_MAP.fetch(value) do |other|
case other
when GNU_GCC_REGEXP
other.to_sym
else
raise "Invalid value for #{source}: #{other}"
end
end
end
sig { void }
def check_for_compiler_universal_support
raise "Non-Apple GCC can't build universal binaries" if homebrew_cc&.match?(GNU_GCC_REGEXP)
end
end
require "extend/os/extend/ENV/shared"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cli/named_args.rb | Library/Homebrew/cli/named_args.rb | # typed: strict
# frozen_string_literal: true
require "cli/args"
require "utils/output"
module Homebrew
module CLI
# Helper class for loading formulae/casks from named arguments.
class NamedArgs < Array
include Utils::Output::Mixin
extend T::Generic
Elem = type_member(:out) { { fixed: String } }
sig { returns(Args) }
attr_reader :parent
sig {
params(
args: String,
parent: Args,
override_spec: T.nilable(Symbol),
force_bottle: T::Boolean,
flags: T::Array[String],
cask_options: T::Boolean,
without_api: T::Boolean,
).void
}
def initialize(
*args,
parent: Args.new,
override_spec: nil,
force_bottle: false,
flags: [],
cask_options: false,
without_api: false
)
super(args)
@override_spec = override_spec
@force_bottle = force_bottle
@flags = flags
@cask_options = cask_options
@without_api = without_api
@parent = parent
end
sig { returns(T::Array[Cask::Cask]) }
def to_casks
@to_casks ||= T.let(
to_formulae_and_casks(only: :cask).freeze, T.nilable(T::Array[T.any(Formula, Keg, Cask::Cask)])
)
T.cast(@to_casks, T::Array[Cask::Cask])
end
sig { returns(T::Array[Formula]) }
def to_formulae
@to_formulae ||= T.let(
to_formulae_and_casks(only: :formula).freeze, T.nilable(T::Array[T.any(Formula, Keg, Cask::Cask)])
)
T.cast(@to_formulae, T::Array[Formula])
end
# Convert named arguments to {Formula} or {Cask} objects.
# If both a formula and cask with the same name exist, returns
# the formula and prints a warning unless `only` is specified.
sig {
params(
only: T.nilable(Symbol),
ignore_unavailable: T::Boolean,
method: T.nilable(Symbol),
uniq: T::Boolean,
warn: T::Boolean,
).returns(T::Array[T.any(Formula, Keg, Cask::Cask)])
}
def to_formulae_and_casks(
only: parent.only_formula_or_cask, ignore_unavailable: false, method: nil, uniq: true, warn: false
)
@to_formulae_and_casks ||= T.let(
{}, T.nilable(T::Hash[T.nilable(Symbol), T::Array[T.any(Formula, Keg, Cask::Cask)]])
)
@to_formulae_and_casks[only] ||= begin
download_queue = Homebrew::DownloadQueue.new_if_concurrency_enabled
formulae_and_casks = downcased_unique_named.flat_map do |name|
load_and_fetch_full_formula_or_cask(name, only:, method:, warn:, download_queue:)
rescue FormulaUnreadableError, FormulaClassUnavailableError,
TapFormulaUnreadableError, TapFormulaClassUnavailableError,
Cask::CaskUnreadableError
# Need to rescue before `*UnavailableError` (superclass of this)
# The formula/cask was found, but there's a problem with its implementation
raise
rescue NoSuchKegError, FormulaUnavailableError, Cask::CaskUnavailableError, FormulaOrCaskUnavailableError
ignore_unavailable ? [] : raise
end
download_queue&.fetch
map_to_fully_loaded(formulae_and_casks)
end.freeze
if uniq
@to_formulae_and_casks.fetch(only).uniq.freeze
else
@to_formulae_and_casks.fetch(only)
end
end
sig {
params(only: T.nilable(Symbol), method: T.nilable(Symbol))
.returns([T::Array[T.any(Formula, Keg)], T::Array[Cask::Cask]])
}
def to_formulae_to_casks(only: parent.only_formula_or_cask, method: nil)
@to_formulae_to_casks ||= T.let(
{}, T.nilable(T::Hash[[T.nilable(Symbol), T.nilable(Symbol)],
[T::Array[T.any(Formula, Keg)], T::Array[Cask::Cask]]])
)
@to_formulae_to_casks[[method, only]] =
T.cast(
to_formulae_and_casks(only:, method:).partition { |o| o.is_a?(Formula) || o.is_a?(Keg) }
.map(&:freeze).freeze,
[T::Array[T.any(Formula, Keg)], T::Array[Cask::Cask]],
)
end
# Returns formulae and casks after validating that a tap is present for each of them.
sig { returns(T::Array[T.any(Formula, Keg, Cask::Cask)]) }
def to_formulae_and_casks_with_taps
formulae_and_casks_with_taps, formulae_and_casks_without_taps =
to_formulae_and_casks.partition do |formula_or_cask|
T.cast(formula_or_cask, T.any(Formula, Cask::Cask)).tap&.installed?
end
return formulae_and_casks_with_taps if formulae_and_casks_without_taps.empty?
types = []
types << "formulae" if formulae_and_casks_without_taps.any?(Formula)
types << "casks" if formulae_and_casks_without_taps.any?(Cask::Cask)
odie <<~ERROR
These #{types.join(" and ")} are not in any locally installed taps!
#{formulae_and_casks_without_taps.sort_by(&:to_s).join("\n ")}
You may need to run `brew tap` to install additional taps.
ERROR
end
sig {
params(only: T.nilable(Symbol), method: T.nilable(Symbol))
.returns(T::Array[T.any(Formula, Keg, Cask::Cask, T::Array[Keg], FormulaOrCaskUnavailableError)])
}
def to_formulae_and_casks_and_unavailable(only: parent.only_formula_or_cask, method: nil)
@to_formulae_casks_unknowns ||= T.let(
{},
T.nilable(T::Hash[
T.nilable(Symbol),
T::Array[T.any(Formula, Keg, Cask::Cask, T::Array[Keg], FormulaOrCaskUnavailableError)],
]),
)
@to_formulae_casks_unknowns[method] = begin
download_queue = Homebrew::DownloadQueue.new_if_concurrency_enabled
formulae_and_casks = downcased_unique_named.map do |name|
load_and_fetch_full_formula_or_cask(name, only:, method:, download_queue:)
rescue FormulaOrCaskUnavailableError => e
e
end.uniq
download_queue&.fetch
map_to_fully_loaded(formulae_and_casks)
end.freeze
end
sig { params(uniq: T::Boolean).returns(T::Array[Formula]) }
def to_resolved_formulae(uniq: true)
@to_resolved_formulae ||= T.let(
to_formulae_and_casks(only: :formula, method: :resolve, uniq:).freeze,
T.nilable(T::Array[T.any(Formula, Keg, Cask::Cask)]),
)
T.cast(@to_resolved_formulae, T::Array[Formula])
end
sig { params(only: T.nilable(Symbol)).returns([T::Array[Formula], T::Array[Cask::Cask]]) }
def to_resolved_formulae_to_casks(only: parent.only_formula_or_cask)
T.cast(to_formulae_to_casks(only:, method: :resolve), [T::Array[Formula], T::Array[Cask::Cask]])
end
LOCAL_PATH_REGEX = %r{^/|[.]|/$}
TAP_NAME_REGEX = %r{^[^./]+/[^./]+$}
private_constant :LOCAL_PATH_REGEX, :TAP_NAME_REGEX
# Keep existing paths and try to convert others to tap, formula or cask paths.
# If a cask and formula with the same name exist, includes both their paths
# unless `only` is specified.
sig { params(only: T.nilable(Symbol), recurse_tap: T::Boolean).returns(T::Array[Pathname]) }
def to_paths(only: parent.only_formula_or_cask, recurse_tap: false)
@to_paths ||= T.let({}, T.nilable(T::Hash[T.nilable(Symbol), T::Array[Pathname]]))
@to_paths[only] ||= Homebrew.with_no_api_env_if_needed(@without_api) do
downcased_unique_named.flat_map do |name|
path = Pathname(name).expand_path
if only.nil? && name.match?(LOCAL_PATH_REGEX) && path.exist?
path
elsif name.match?(TAP_NAME_REGEX)
tap = Tap.fetch(name)
if recurse_tap
next tap.formula_files if only == :formula
next tap.cask_files if only == :cask
end
tap.path
else
next Formulary.path(name) if only == :formula
next Cask::CaskLoader.path(name) if only == :cask
formula_path = Formulary.path(name)
cask_path = Cask::CaskLoader.path(name)
paths = []
if formula_path.exist? ||
(!Homebrew::EnvConfig.no_install_from_api? &&
!CoreTap.instance.installed? &&
Homebrew::API.formula_names.include?(path.basename.to_s))
paths << formula_path
end
if cask_path.exist? ||
(!Homebrew::EnvConfig.no_install_from_api? &&
!CoreCaskTap.instance.installed? &&
Homebrew::API.cask_tokens.include?(path.basename.to_s))
paths << cask_path
end
paths.empty? ? path : paths
end
end.uniq.freeze
end
end
sig { returns(T::Array[Keg]) }
def to_default_kegs
require "missing_formula"
@to_default_kegs ||= T.let(begin
to_formulae_and_casks(only: :formula, method: :default_kegs).freeze
rescue NoSuchKegError => e
if (reason = MissingFormula.suggest_command(e.name, "uninstall"))
$stderr.puts reason
end
raise e
end, T.nilable(T::Array[T.any(Formula, Keg, Cask::Cask)]))
T.cast(@to_default_kegs, T::Array[Keg])
end
sig { returns(T::Array[Keg]) }
def to_latest_kegs
require "missing_formula"
@to_latest_kegs ||= T.let(begin
to_formulae_and_casks(only: :formula, method: :latest_kegs).freeze
rescue NoSuchKegError => e
if (reason = MissingFormula.suggest_command(e.name, "uninstall"))
$stderr.puts reason
end
raise e
end, T.nilable(T::Array[T.any(Formula, Keg, Cask::Cask)]))
T.cast(@to_latest_kegs, T::Array[Keg])
end
sig { returns(T::Array[Keg]) }
def to_kegs
require "missing_formula"
@to_kegs ||= T.let(begin
to_formulae_and_casks(only: :formula, method: :kegs).freeze
rescue NoSuchKegError => e
if (reason = MissingFormula.suggest_command(e.name, "uninstall"))
$stderr.puts reason
end
raise e
end, T.nilable(T::Array[T.any(Formula, Keg, Cask::Cask)]))
T.cast(@to_kegs, T::Array[Keg])
end
sig {
params(only: T.nilable(Symbol), ignore_unavailable: T::Boolean, all_kegs: T.nilable(T::Boolean))
.returns([T::Array[Keg], T::Array[Cask::Cask]])
}
def to_kegs_to_casks(only: parent.only_formula_or_cask, ignore_unavailable: false, all_kegs: nil)
method = all_kegs ? :kegs : :default_kegs
key = [method, only, ignore_unavailable]
@to_kegs_to_casks ||= T.let(
{},
T.nilable(
T::Hash[
[T.nilable(Symbol), T.nilable(Symbol), T::Boolean],
[T::Array[Keg], T::Array[Cask::Cask]],
],
),
)
@to_kegs_to_casks[key] ||= T.cast(
to_formulae_and_casks(only:, ignore_unavailable:, method:)
.partition { |o| o.is_a?(Keg) }
.map(&:freeze).freeze,
[T::Array[Keg], T::Array[Cask::Cask]],
)
end
sig { returns(T::Array[Tap]) }
def to_taps
@to_taps ||= T.let(downcased_unique_named.map { |name| Tap.fetch name }.uniq.freeze, T.nilable(T::Array[Tap]))
end
sig { returns(T::Array[Tap]) }
def to_installed_taps
@to_installed_taps ||= T.let(to_taps.each do |tap|
raise TapUnavailableError, tap.name unless tap.installed?
end.uniq.freeze, T.nilable(T::Array[Tap]))
end
sig { returns(T::Array[String]) }
def homebrew_tap_cask_names
downcased_unique_named.grep(HOMEBREW_CASK_TAP_CASK_REGEX)
end
private
sig { returns(T::Array[String]) }
def downcased_unique_named
# Only lowercase names, not paths, bottle filenames or URLs
map do |arg|
if arg.include?("/") || arg.end_with?(".tar.gz") || File.exist?(arg)
arg
else
arg.downcase
end
end.uniq
end
sig {
params(name: String, only: T.nilable(Symbol), method: T.nilable(Symbol), warn: T::Boolean,
download_queue: T.nilable(Homebrew::DownloadQueue))
.returns(T.any(Formula, Keg, Cask::Cask, T::Array[Keg]))
}
def load_and_fetch_full_formula_or_cask(name, only: nil, method: nil, warn: false, download_queue: nil)
formula_or_cask = load_formula_or_cask(name, only:, method:, warn:)
formula_or_cask.fetch_fully_loaded_formula!(download_queue:) if formula_or_cask.is_a?(Formula)
formula_or_cask
end
sig {
params(name: String, only: T.nilable(Symbol), method: T.nilable(Symbol), warn: T::Boolean)
.returns(T.any(Formula, Keg, Cask::Cask, T::Array[Keg]))
}
def load_formula_or_cask(name, only: nil, method: nil, warn: false)
Homebrew.with_no_api_env_if_needed(@without_api) do
unreadable_error = nil
formula_or_kegs = if only != :cask
begin
case method
when nil, :factory
Formulary.factory_stub(name, *@override_spec, warn:, force_bottle: @force_bottle, flags: @flags)
when :resolve
resolve_formula(name)
when :latest_kegs
resolve_latest_keg(name)
when :default_kegs
resolve_default_keg(name)
when :kegs
_, kegs = resolve_kegs(name)
kegs
else
raise
end
rescue FormulaUnreadableError, FormulaClassUnavailableError,
TapFormulaUnreadableError, TapFormulaClassUnavailableError,
FormulaSpecificationError => e
# Need to rescue before `FormulaUnavailableError` (superclass of this)
# The formula was found, but there's a problem with its implementation
unreadable_error ||= e
nil
rescue NoSuchKegError, FormulaUnavailableError => e
raise e if only == :formula
nil
end
end
if only == :formula
return formula_or_kegs if formula_or_kegs
elsif formula_or_kegs && (!formula_or_kegs.is_a?(Formula) || formula_or_kegs.tap&.core_tap?)
warn_if_cask_conflicts(name, "formula")
return formula_or_kegs
else
want_keg_like_cask = [:latest_kegs, :default_kegs, :kegs].include?(method)
cask = begin
config = Cask::Config.from_args(@parent) if @cask_options
options = { warn: }.compact
candidate_cask = Cask::CaskLoader.load(name, config:, **options)
if unreadable_error
onoe <<~EOS
Failed to load formula: #{name}
#{unreadable_error}
EOS
opoo "Treating #{name} as a cask."
end
# If we're trying to get a keg-like Cask, do our best to use the same cask
# file that was used for installation, if possible.
if want_keg_like_cask &&
(installed_caskfile = candidate_cask.installed_caskfile) &&
installed_caskfile.exist?
cask = Cask::CaskLoader.load_from_installed_caskfile(installed_caskfile)
requested_tap, requested_token = Tap.with_cask_token(name)
if requested_tap && requested_token
installed_cask_tap = cask.tab.tap
if installed_cask_tap && installed_cask_tap != requested_tap
raise Cask::TapCaskUnavailableError.new(requested_tap, requested_token)
end
end
cask
else
candidate_cask
end
rescue Cask::CaskUnreadableError, Cask::CaskInvalidError => e
# If we're trying to get a keg-like Cask, do our best to handle it
# not being readable and return something that can be used.
if want_keg_like_cask
cask_version = Cask::Cask.new(name, config:).installed_version
Cask::Cask.new(name, config:) do
version cask_version if cask_version
end
else
# Need to rescue before `CaskUnavailableError` (superclass of this)
# The cask was found, but there's a problem with its implementation
unreadable_error ||= e
nil
end
rescue Cask::CaskUnavailableError => e
raise e if only == :cask
nil
end
# Prioritise formulae unless it's a core tap cask (we already prioritised core tap formulae above)
if formula_or_kegs && !cask&.tap&.core_cask_tap?
if cask || unreadable_error
onoe <<~EOS if unreadable_error
Failed to load cask: #{name}
#{unreadable_error}
EOS
opoo package_conflicts_message(name, "formula", cask) unless Context.current.quiet?
end
return formula_or_kegs
elsif cask
if formula_or_kegs && !Context.current.quiet?
opoo package_conflicts_message(name, "cask", formula_or_kegs)
end
return cask
end
end
raise unreadable_error if unreadable_error
user, repo, short_name = name.downcase.split("/", 3)
if repo.present? && short_name.present?
tap = Tap.fetch(T.must(user), repo)
raise TapFormulaOrCaskUnavailableError.new(tap, short_name)
end
raise NoSuchKegError, name if resolve_formula(name)
end
end
sig { params(name: String).returns(Formula) }
def resolve_formula(name)
Formulary.resolve(name, spec: @override_spec, force_bottle: @force_bottle, flags: @flags, prefer_stub: true)
end
sig { params(name: String).returns([Pathname, T::Array[Keg]]) }
def resolve_kegs(name)
raise UsageError if name.blank?
require "keg"
rack = Formulary.to_rack(name.downcase)
kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : []
requested_tap, requested_formula = Tap.with_formula_name(name)
if requested_tap && requested_formula
kegs = kegs.select do |keg|
keg.tab.tap == requested_tap
end
raise NoSuchKegError.new(requested_formula, tap: requested_tap) if kegs.none?
end
raise NoSuchKegError, name if kegs.none?
[rack, kegs]
end
sig { params(name: String).returns(Keg) }
def resolve_latest_keg(name)
_, kegs = resolve_kegs(name)
# Return keg if it is the only installed keg
return kegs.fetch(0) if kegs.length == 1
stable_kegs = kegs.reject { |keg| keg.version.head? }
latest_keg = if stable_kegs.empty?
kegs.max_by do |keg|
[keg.tab.source_modified_time, keg.version.revision]
end
else
stable_kegs.max_by(&:scheme_and_version)
end
T.must(latest_keg)
end
sig { params(name: String).returns(Keg) }
def resolve_default_keg(name)
rack, kegs = resolve_kegs(name)
linked_keg_ref = HOMEBREW_LINKED_KEGS/rack.basename
opt_prefix = HOMEBREW_PREFIX/"opt/#{rack.basename}"
begin
return Keg.new(opt_prefix.resolved_path) if opt_prefix.symlink? && opt_prefix.directory?
return Keg.new(linked_keg_ref.resolved_path) if linked_keg_ref.symlink? && linked_keg_ref.directory?
return kegs.fetch(0) if kegs.length == 1
f = if name.include?("/") || File.exist?(name)
Formulary.factory(name)
else
Formulary.from_rack(rack)
end
unless (prefix = f.latest_installed_prefix).directory?
raise MultipleVersionsInstalledError, <<~EOS
#{rack.basename} has multiple installed versions
Run `brew uninstall --force #{rack.basename}` to remove all versions.
EOS
end
Keg.new(prefix)
rescue FormulaUnavailableError
raise MultipleVersionsInstalledError, <<~EOS
Multiple kegs installed to #{rack}
However we don't know which one you refer to.
Please delete (with `rm -rf`!) all but one and then try again.
EOS
end
end
sig {
params(
ref: String, loaded_type: String,
package: T.nilable(T.any(T::Array[T.any(Formula, Keg)], Cask::Cask, Formula, Keg))
).returns(String)
}
def package_conflicts_message(ref, loaded_type, package)
message = "Treating #{ref} as a #{loaded_type}."
case package
when Formula, Keg, Array
message += " For the formula, "
if package.is_a?(Formula) && (tap = package.tap)
message += "use #{tap.name}/#{package.name} or "
end
message += "specify the `--formula` flag. To silence this message, use the `--cask` flag."
when Cask::Cask
message += " For the cask, "
if (tap = package.tap)
message += "use #{tap.name}/#{package.token} or "
end
message += "specify the `--cask` flag. To silence this message, use the `--formula` flag."
end
message.freeze
end
sig { params(ref: String, loaded_type: String).void }
def warn_if_cask_conflicts(ref, loaded_type)
available = true
cask = begin
Cask::CaskLoader.load(ref, warn: false)
rescue Cask::CaskUnreadableError => e
# Need to rescue before `CaskUnavailableError` (superclass of this)
# The cask was found, but there's a problem with its implementation
onoe <<~EOS
Failed to load cask: #{ref}
#{e}
EOS
nil
rescue Cask::CaskUnavailableError
# No ref conflict with a cask, do nothing
available = false
nil
end
return unless available
return if Context.current.quiet?
return if cask&.old_tokens&.include?(ref)
opoo package_conflicts_message(ref, loaded_type, cask)
end
sig {
type_parameters(:U)
.params(formulae_and_casks: T::Array[T.all(T.type_parameter(:U), Object)])
.returns(T::Array[T.all(T.type_parameter(:U), Object)])
}
def map_to_fully_loaded(formulae_and_casks)
formulae_and_casks.map do |formula_or_cask|
next formula_or_cask unless formula_or_cask.is_a?(Formula)
T.cast(formula_or_cask.fully_loaded_formula, T.all(T.type_parameter(:U), Object))
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/cli/parser.rb | Library/Homebrew/cli/parser.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "env_config"
require "cask/config"
require "cli/args"
require "cli/error"
require "commands"
require "optparse"
require "utils/tty"
require "utils/formatter"
require "utils/output"
module Homebrew
module CLI
class Parser
include Utils::Output::Mixin
ArgType = T.type_alias { T.nilable(T.any(Symbol, T::Array[String], T::Array[Symbol])) }
HIDDEN_DESC_PLACEHOLDER = "@@HIDDEN@@"
SYMBOL_TO_USAGE_MAPPING = T.let({
text_or_regex: "<text>|`/`<regex>`/`",
url: "<URL>",
}.freeze, T::Hash[Symbol, String])
private_constant :ArgType, :HIDDEN_DESC_PLACEHOLDER, :SYMBOL_TO_USAGE_MAPPING
sig { returns(Args) }
attr_reader :args
sig { returns(Args::OptionsType) }
attr_reader :processed_options
sig { returns(T::Boolean) }
attr_reader :hide_from_man_page
sig { returns(ArgType) }
attr_reader :named_args_type
sig { params(cmd_path: Pathname).returns(T.nilable(CLI::Parser)) }
def self.from_cmd_path(cmd_path)
cmd_args_method_name = Commands.args_method_name(cmd_path)
cmd_name = cmd_args_method_name.to_s.delete_suffix("_args").tr("_", "-")
begin
if Homebrew.require?(cmd_path)
cmd = Homebrew::AbstractCommand.command(cmd_name)
if cmd
cmd.parser
else
# FIXME: remove once commands are all subclasses of `AbstractCommand`:
Homebrew.send(cmd_args_method_name)
end
end
rescue NoMethodError => e
raise if e.name.to_sym != cmd_args_method_name
nil
end
end
sig { returns(T::Array[[Symbol, String, { description: String }]]) }
def self.global_cask_options
[
[:flag, "--appdir=", {
description: "Target location for Applications " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:appdir]}`).",
}],
[:flag, "--keyboard-layoutdir=", {
description: "Target location for Keyboard Layouts " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:keyboard_layoutdir]}`).",
}],
[:flag, "--colorpickerdir=", {
description: "Target location for Color Pickers " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:colorpickerdir]}`).",
}],
[:flag, "--prefpanedir=", {
description: "Target location for Preference Panes " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:prefpanedir]}`).",
}],
[:flag, "--qlplugindir=", {
description: "Target location for Quick Look Plugins " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:qlplugindir]}`).",
}],
[:flag, "--mdimporterdir=", {
description: "Target location for Spotlight Plugins " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:mdimporterdir]}`).",
}],
[:flag, "--dictionarydir=", {
description: "Target location for Dictionaries " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:dictionarydir]}`).",
}],
[:flag, "--fontdir=", {
description: "Target location for Fonts " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:fontdir]}`).",
}],
[:flag, "--servicedir=", {
description: "Target location for Services " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:servicedir]}`).",
}],
[:flag, "--input-methoddir=", {
description: "Target location for Input Methods " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:input_methoddir]}`).",
}],
[:flag, "--internet-plugindir=", {
description: "Target location for Internet Plugins " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:internet_plugindir]}`).",
}],
[:flag, "--audio-unit-plugindir=", {
description: "Target location for Audio Unit Plugins " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:audio_unit_plugindir]}`).",
}],
[:flag, "--vst-plugindir=", {
description: "Target location for VST Plugins " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:vst_plugindir]}`).",
}],
[:flag, "--vst3-plugindir=", {
description: "Target location for VST3 Plugins " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:vst3_plugindir]}`).",
}],
[:flag, "--screen-saverdir=", {
description: "Target location for Screen Savers " \
"(default: `#{Cask::Config::DEFAULT_DIRS[:screen_saverdir]}`).",
}],
[:comma_array, "--language", {
description: "Comma-separated list of language codes to prefer for cask installation. " \
"The first matching language is used, otherwise it reverts to the cask's " \
"default language. The default value is the language of your system.",
}],
]
end
sig { returns(T::Array[[String, String, String]]) }
def self.global_options
[
["-d", "--debug", "Display any debugging information."],
["-q", "--quiet", "Make some output more quiet."],
["-v", "--verbose", "Make some output more verbose."],
["-h", "--help", "Show this message."],
]
end
sig { params(option: String).returns(String) }
def self.option_to_name(option)
option.sub(/\A--?(\[no-\])?/, "").tr("-", "_").delete("=")
end
sig {
params(cmd: T.nilable(T.class_of(Homebrew::AbstractCommand)), block: T.nilable(T.proc.bind(Parser).void)).void
}
def initialize(cmd = nil, &block)
@parser = T.let(OptionParser.new, OptionParser)
@parser.summary_indent = " "
# Disable default handling of `--version` switch.
@parser.base.long.delete("version")
# Disable default handling of `--help` switch.
@parser.base.long.delete("help")
@args = T.let((cmd&.args_class || Args).new, Args)
if cmd
@command_name = T.let(cmd.command_name, String)
@is_dev_cmd = T.let(cmd.dev_cmd?, T::Boolean)
else
# FIXME: remove once commands are all subclasses of `AbstractCommand`:
# Filter out Sorbet runtime type checking method calls.
cmd_location = caller_locations.select do |location|
T.must(location.path).exclude?("/gems/sorbet-runtime-")
end.fetch(1)
@command_name = T.let(T.must(cmd_location.label).chomp("_args").tr("_", "-"), String)
@is_dev_cmd = T.let(T.must(cmd_location.absolute_path).start_with?(Commands::HOMEBREW_DEV_CMD_PATH.to_s),
T::Boolean)
odisabled(
"`brew #{@command_name}'. This command needs to be refactored, as it is written in a style that",
"subclassing of `Homebrew::AbstractCommand' ( see https://docs.brew.sh/External-Commands )",
disable_for_developers: false,
)
end
@constraints = T.let([], T::Array[[String, String]])
@conflicts = T.let([], T::Array[T::Array[String]])
@switch_sources = T.let({}, T::Hash[String, Symbol])
@processed_options = T.let([], Args::OptionsType)
@non_global_processed_options = T.let([], T::Array[[String, ArgType]])
@named_args_type = T.let(nil, T.nilable(ArgType))
@max_named_args = T.let(nil, T.nilable(Integer))
@min_named_args = T.let(nil, T.nilable(Integer))
@named_args_without_api = T.let(false, T::Boolean)
@description = T.let(nil, T.nilable(String))
@usage_banner = T.let(nil, T.nilable(String))
@hide_from_man_page = T.let(false, T::Boolean)
@formula_options = T.let(false, T::Boolean)
@cask_options = T.let(false, T::Boolean)
self.class.global_options.each do |short, long, desc|
switch short, long, description: desc, env: option_to_name(long), method: :on_tail
end
instance_eval(&block) if block
generate_banner
end
sig {
params(names: String, description: T.nilable(String), env: T.untyped,
depends_on: T.nilable(String), method: Symbol,
hidden: T::Boolean, replacement: T.nilable(T.any(String, FalseClass)),
odeprecated: T::Boolean, odisabled: T::Boolean, disable: T::Boolean).void
}
def switch(*names, description: nil, env: nil,
depends_on: nil, method: :on,
hidden: false, replacement: nil,
odeprecated: false, odisabled: false, disable: false)
global_switch = names.first.is_a?(Symbol)
return if global_switch
if disable
# this odeprecated should turn into odisabled in 5.1.0
odeprecated "disable:", "odisabled:"
odisabled = disable
end
if !odeprecated && !odisabled && replacement
# this odeprecated should turn into odisabled in 5.1.0
odeprecated "replacement: without :odeprecated or :odisabled",
"replacement: with :odeprecated or :odisabled"
odeprecated = true
end
hidden = true if odisabled || odeprecated
description = option_description(description, *names, hidden:)
env, counterpart = env
if env && @non_global_processed_options.any?
affix = counterpart ? " and `#{counterpart}` is passed." : "."
description += " Enabled by default if `$HOMEBREW_#{env.upcase}` is set#{affix}"
end
if odeprecated || odisabled
description += " (#{odisabled ? "disabled" : "deprecated"}#{"; replaced by #{replacement}" if replacement})"
end
process_option(*names, description, type: :switch, hidden:) unless odisabled
@parser.public_send(method, *names, *wrap_option_desc(description)) do |value|
# This odeprecated should stick around indefinitely.
replacement_string = replacement if replacement
if odeprecated || odisabled
odeprecated "the `#{names.first}` switch", replacement_string, disable: odisabled
end
value = true if names.none? { |name| name.start_with?("--[no-]") }
set_switch(*names, value:, from: :args)
end
names.each do |name|
set_constraints(name, depends_on:)
end
env_value = value_for_env(env)
value = env_value&.present?
set_switch(*names, value:, from: :env) unless value.nil?
end
alias switch_option switch
sig { params(text: T.nilable(String)).returns(T.nilable(String)) }
def description(text = nil)
return @description if text.blank?
@description = text.chomp
end
sig { params(text: String).void }
def usage_banner(text)
@usage_banner, @description = text.chomp.split("\n\n", 2)
end
sig { returns(T.nilable(String)) }
def usage_banner_text = @parser.banner
sig { params(name: String, description: T.nilable(String), hidden: T::Boolean).void }
def comma_array(name, description: nil, hidden: false)
name = name.chomp "="
description = option_description(description, name, hidden:)
process_option(name, description, type: :comma_array, hidden:)
@parser.on(name, OptionParser::REQUIRED_ARGUMENT, Array, *wrap_option_desc(description)) do |list|
set_args_method(option_to_name(name).to_sym, list)
end
end
sig {
params(names: String, description: T.nilable(String), replacement: T.nilable(T.any(Symbol, String)),
depends_on: T.nilable(String), hidden: T::Boolean).void
}
def flag(*names, description: nil, replacement: nil, depends_on: nil, hidden: false)
required, flag_type = if names.any? { |name| name.end_with? "=" }
[OptionParser::REQUIRED_ARGUMENT, :required_flag]
else
[OptionParser::OPTIONAL_ARGUMENT, :optional_flag]
end
names.map! { |name| name.chomp "=" }
description = option_description(description, *names, hidden:)
if replacement.nil?
process_option(*names, description, type: flag_type, hidden:)
else
description += " (disabled#{"; replaced by #{replacement}" if replacement.present?})"
end
@parser.on(*names, *wrap_option_desc(description), required) do |option_value|
# This odisabled should stick around indefinitely.
odisabled "the `#{names.first}` flag", replacement unless replacement.nil?
names.each do |name|
set_args_method(option_to_name(name).to_sym, option_value)
end
end
names.each do |name|
set_constraints(name, depends_on:)
end
end
sig { params(name: Symbol, value: T.untyped).void }
def set_args_method(name, value)
@args.set_arg(name, value)
return if @args.respond_to?(name)
@args.define_singleton_method(name) do
# We cannot reference the ivar directly due to https://github.com/sorbet/sorbet/issues/8106
instance_variable_get(:@table).fetch(name)
end
end
sig { params(options: String).returns(T::Array[T::Array[String]]) }
def conflicts(*options)
@conflicts << options.map { |option| option_to_name(option) }
end
sig { params(option: String).returns(String) }
def option_to_name(option) = self.class.option_to_name(option)
sig { params(name: String).returns(String) }
def name_to_option(name)
if name.length == 1
"-#{name}"
else
"--#{name.tr("_", "-")}"
end
end
sig { params(names: String).returns(T.nilable(String)) }
def option_to_description(*names)
names.map { |name| name.to_s.sub(/\A--?/, "").tr("-", " ") }.max
end
sig { params(description: T.nilable(String), names: String, hidden: T::Boolean).returns(String) }
def option_description(description, *names, hidden: false)
return HIDDEN_DESC_PLACEHOLDER if hidden
return description if description.present?
option_to_description(*names)
end
sig {
params(argv: T::Array[String], ignore_invalid_options: T::Boolean)
.returns([T::Array[String], T::Array[String]])
}
def parse_remaining(argv, ignore_invalid_options: false)
i = 0
remaining = []
argv, non_options = split_non_options(argv)
allow_commands = Array(@named_args_type).include?(:command)
while i < argv.count
begin
begin
arg = argv[i]
remaining << arg unless @parser.parse([arg]).empty?
rescue OptionParser::MissingArgument
raise if i + 1 >= argv.count
args = argv[i..(i + 1)]
@parser.parse(args)
i += 1
end
rescue OptionParser::InvalidOption
if ignore_invalid_options || (allow_commands && arg && Commands.path(arg))
remaining << arg
else
$stderr.puts generate_help_text
raise
end
end
i += 1
end
[remaining, non_options]
end
sig { params(argv: T::Array[String], ignore_invalid_options: T::Boolean).returns(Args) }
def parse(argv = ARGV.freeze, ignore_invalid_options: false)
raise "Arguments were already parsed!" if @args_parsed
# If we accept formula options, but the command isn't scoped only
# to casks, parse once allowing invalid options so we can get the
# remaining list containing formula names.
if @formula_options && !only_casks?(argv)
remaining, non_options = parse_remaining(argv, ignore_invalid_options: true)
argv = [*remaining, "--", *non_options]
formulae(argv).each do |f|
next if f.options.empty?
f.options.each do |o|
name = o.flag
description = "`#{f.name}`: #{o.description}"
if name.end_with? "="
flag(name, description:)
else
switch name, description:
end
conflicts "--cask", name
end
end
end
remaining, non_options = parse_remaining(argv, ignore_invalid_options:)
named_args = if ignore_invalid_options
[]
else
remaining + non_options
end
unless ignore_invalid_options
unless @is_dev_cmd
set_default_options
validate_options
end
check_constraint_violations
check_named_args(named_args)
end
@args.freeze_named_args!(named_args, cask_options: @cask_options, without_api: @named_args_without_api)
@args.freeze_remaining_args!(non_options.empty? ? remaining : [*remaining, "--", non_options])
@args.freeze_processed_options!(@processed_options)
@args.freeze
@args_parsed = T.let(true, T.nilable(TrueClass))
if !ignore_invalid_options && @args.help?
puts generate_help_text
exit
end
@args
end
sig { void }
def set_default_options; end
sig { void }
def validate_options; end
sig { returns(String) }
def generate_help_text
Formatter.format_help_text(@parser.to_s, width: Formatter::COMMAND_DESC_WIDTH)
.gsub(/\n.*?@@HIDDEN@@.*?(?=\n)/, "")
.sub(/^/, "#{Tty.bold}Usage: brew#{Tty.reset} ")
.gsub(/`(.*?)`/m, "#{Tty.bold}\\1#{Tty.reset}")
.gsub(%r{<([^\s]+?://[^\s]+?)>}) { |url| Formatter.url(url) }
.gsub(/\*(.*?)\*|<(.*?)>/m) do |underlined|
T.must(underlined[1...-1]).gsub(/^(\s*)(.*?)$/, "\\1#{Tty.underline}\\2#{Tty.reset}")
end
end
sig { void }
def cask_options
self.class.global_cask_options.each do |args|
options = T.cast(args.pop, T::Hash[Symbol, String])
send(*args, **options)
conflicts "--formula", args[1]
end
@cask_options = true
end
sig { void }
def formula_options
@formula_options = true
end
sig {
params(
type: ArgType,
number: T.nilable(Integer),
min: T.nilable(Integer),
max: T.nilable(Integer),
without_api: T::Boolean,
).void
}
def named_args(type = nil, number: nil, min: nil, max: nil, without_api: false)
raise ArgumentError, "Do not specify both `number` and `min` or `max`" if number && (min || max)
if type == :none && (number || min || max)
raise ArgumentError, "Do not specify both `number`, `min` or `max` with `named_args :none`"
end
@named_args_type = type
if type == :none
@max_named_args = 0
elsif number
@min_named_args = @max_named_args = number
elsif min || max
@min_named_args = min
@max_named_args = max
end
@named_args_without_api = without_api
end
sig { void }
def hide_from_man_page!
@hide_from_man_page = true
end
private
sig { returns(String) }
def generate_usage_banner
command_names = ["`#{@command_name}`"]
aliases_to_skip = %w[instal uninstal]
command_names += Commands::HOMEBREW_INTERNAL_COMMAND_ALIASES.filter_map do |command_alias, command|
next if aliases_to_skip.include? command_alias
"`#{command_alias}`" if command == @command_name
end.sort
options = if @non_global_processed_options.empty?
""
elsif @non_global_processed_options.count > 2
" [<options>]"
else
required_argument_types = [:required_flag, :comma_array]
@non_global_processed_options.map do |option, type|
next " [`#{option}=`]" if required_argument_types.include? type
" [`#{option}`]"
end.join
end
named_args = ""
if @named_args_type.present? && @named_args_type != :none
arg_type = if @named_args_type.is_a? Array
types = @named_args_type.filter_map do |type|
next unless type.is_a? Symbol
next SYMBOL_TO_USAGE_MAPPING[type] if SYMBOL_TO_USAGE_MAPPING.key?(type)
"<#{type}>"
end
types << "<subcommand>" if @named_args_type.any?(String)
types.join("|")
elsif SYMBOL_TO_USAGE_MAPPING.key? @named_args_type
SYMBOL_TO_USAGE_MAPPING[@named_args_type]
else
"<#{@named_args_type}>"
end
named_args = if @min_named_args.nil? && @max_named_args == 1
" [#{arg_type}]"
elsif @min_named_args.nil?
" [#{arg_type} ...]"
elsif @min_named_args == 1 && @max_named_args == 1
" #{arg_type}"
elsif @min_named_args == 1
" #{arg_type} [...]"
else
" #{arg_type} ..."
end
end
"#{command_names.join(", ")}#{options}#{named_args}"
end
sig { returns(String) }
def generate_banner
@usage_banner ||= generate_usage_banner
@parser.banner = <<~BANNER
#{@usage_banner}
#{@description}
BANNER
end
sig { params(names: String, value: T.untyped, from: Symbol).void }
def set_switch(*names, value:, from:)
names.each do |name|
@switch_sources[option_to_name(name)] = from
set_args_method(:"#{option_to_name(name)}?", value)
end
end
sig { params(args: String).void }
def disable_switch(*args)
args.each do |name|
result = if name.start_with?("--[no-]")
nil
else
false
end
set_args_method(:"#{option_to_name(name)}?", result)
end
end
sig { params(name: String).returns(T::Boolean) }
def option_passed?(name)
[name.to_sym, :"#{name}?"].any? do |method|
@args.public_send(method) if @args.respond_to?(method)
end
end
sig { params(desc: String).returns(T::Array[String]) }
def wrap_option_desc(desc)
Formatter.format_help_text(desc, width: Formatter::OPTION_DESC_WIDTH).split("\n")
end
sig { params(name: String, depends_on: T.nilable(String)).returns(T.nilable(T::Array[[String, String]])) }
def set_constraints(name, depends_on:)
return if depends_on.nil?
primary = option_to_name(depends_on)
secondary = option_to_name(name)
@constraints << [primary, secondary]
end
sig { void }
def check_constraints
@constraints.each do |primary, secondary|
primary_passed = option_passed?(primary)
secondary_passed = option_passed?(secondary)
next if !secondary_passed || (primary_passed && secondary_passed)
primary = name_to_option(primary)
secondary = name_to_option(secondary)
raise OptionConstraintError.new(primary, secondary, missing: true)
end
end
sig { void }
def check_conflicts
@conflicts.each do |mutually_exclusive_options_group|
violations = mutually_exclusive_options_group.select do |option|
option_passed? option
end
next if violations.count < 2
env_var_options = violations.select do |option|
@switch_sources[option_to_name(option)] == :env
end
select_cli_arg = violations.count - env_var_options.count == 1
raise OptionConflictError, violations.map { name_to_option(it) } unless select_cli_arg
env_var_options.each { disable_switch(it) }
end
end
sig { void }
def check_invalid_constraints
@conflicts.each do |mutually_exclusive_options_group|
@constraints.each do |p, s|
next unless Set[p, s].subset?(Set[*mutually_exclusive_options_group])
raise InvalidConstraintError.new(p, s)
end
end
end
sig { void }
def check_constraint_violations
check_invalid_constraints
check_conflicts
check_constraints
end
sig { params(args: T::Array[String]).void }
def check_named_args(args)
types = Array(@named_args_type).filter_map do |type|
next type if type.is_a? Symbol
:subcommand
end.uniq
exception = if @min_named_args && @max_named_args && @min_named_args == @max_named_args &&
args.size != @max_named_args
NumberOfNamedArgumentsError.new(@min_named_args, types:)
elsif @min_named_args && args.size < @min_named_args
MinNamedArgumentsError.new(@min_named_args, types:)
elsif @max_named_args && args.size > @max_named_args
MaxNamedArgumentsError.new(@max_named_args, types:)
end
raise exception if exception
end
sig { params(args: String, type: Symbol, hidden: T::Boolean).void }
def process_option(*args, type:, hidden: false)
option, = @parser.make_switch(args)
@processed_options.reject! { |existing| existing.second == option.long.first } if option.long.first.present?
@processed_options << [option.short.first, option.long.first, option.desc.first, hidden]
args.pop # last argument is the description
if type == :switch
disable_switch(*args)
else
args.each do |name|
set_args_method(option_to_name(name).to_sym, nil)
end
end
return if hidden
return if self.class.global_options.include? [option.short.first, option.long.first, option.desc.first]
@non_global_processed_options << [option.long.first || option.short.first, type]
end
sig { params(argv: T::Array[String]).returns([T::Array[String], T::Array[String]]) }
def split_non_options(argv)
if (sep = argv.index("--"))
[argv.take(sep), argv.drop(sep + 1)]
else
[argv, []]
end
end
sig { params(argv: T::Array[String]).returns(T::Array[Formula]) }
def formulae(argv)
argv, non_options = split_non_options(argv)
named_args = argv.reject { |arg| arg.start_with?("-") } + non_options
spec = if argv.include?("--HEAD")
:head
else
:stable
end
# Only lowercase names, not paths, bottle filenames or URLs
named_args.filter_map do |arg|
next if arg.match?(HOMEBREW_CASK_TAP_CASK_REGEX)
begin
Formulary.factory_stub(arg, spec, flags: argv.select { |a| a.start_with?("--") })
rescue FormulaUnavailableError, FormulaSpecificationError
nil
end
end.uniq(&:name)
end
sig { params(argv: T::Array[String]).returns(T::Boolean) }
def only_casks?(argv)
argv.include?("--casks") || argv.include?("--cask")
end
sig { params(env: T.nilable(T.any(String, Symbol))).returns(T.untyped) }
def value_for_env(env)
return if env.blank?
method_name = :"#{env}?"
if Homebrew::EnvConfig.respond_to?(method_name)
Homebrew::EnvConfig.public_send(method_name)
else
ENV.fetch("HOMEBREW_#{env.upcase}", nil)
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/cli/args.rb | Library/Homebrew/cli/args.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module CLI
class Args
# Represents a processed option. The array elements are:
# 0: short option name (e.g. "-d")
# 1: long option name (e.g. "--debug")
# 2: option description (e.g. "Print debugging information")
# 3: whether the option is hidden
OptionsType = T.type_alias { T::Array[[T.nilable(String), T.nilable(String), String, T::Boolean]] }
sig { returns(T::Array[String]) }
attr_reader :options_only, :flags_only, :remaining
sig { void }
def initialize
require "cli/named_args"
@cli_args = T.let(nil, T.nilable(T::Array[String]))
@processed_options = T.let([], OptionsType)
@options_only = T.let([], T::Array[String])
@flags_only = T.let([], T::Array[String])
@cask_options = T.let(false, T::Boolean)
@table = T.let({}, T::Hash[Symbol, T.untyped])
# Can set these because they will be overwritten by freeze_named_args!
# (whereas other values below will only be overwritten if passed).
@named = T.let(NamedArgs.new(parent: self), T.nilable(NamedArgs))
@remaining = T.let([], T::Array[String])
end
sig { params(remaining_args: T::Array[T.any(T::Array[String], String)]).void }
def freeze_remaining_args!(remaining_args) = @remaining.replace(remaining_args).freeze
sig { params(named_args: T::Array[String], cask_options: T::Boolean, without_api: T::Boolean).void }
def freeze_named_args!(named_args, cask_options:, without_api:)
@named = T.let(
NamedArgs.new(
*named_args.freeze,
cask_options:,
flags: flags_only,
force_bottle: @table[:force_bottle?] || false,
override_spec: @table[:HEAD?] ? :head : nil,
parent: self,
without_api:,
),
T.nilable(NamedArgs),
)
end
sig { params(name: Symbol, value: T.untyped).void }
def set_arg(name, value)
@table[name] = value
end
sig { override.params(_blk: T.nilable(T.proc.params(x: T.untyped).void)).returns(T.untyped) }
def tap(&_blk)
return super if block_given? # Object#tap
@table[:tap]
end
sig { params(processed_options: OptionsType).void }
def freeze_processed_options!(processed_options)
# Reset cache values reliant on processed_options
@cli_args = nil
@processed_options += processed_options
@processed_options.freeze
@options_only = cli_args.select { it.start_with?("-") }.freeze
@flags_only = cli_args.select { it.start_with?("--") }.freeze
end
sig { returns(NamedArgs) }
def named
require "formula"
T.must(@named)
end
sig { returns(T::Boolean) }
def no_named? = named.empty?
sig { returns(T::Array[String]) }
def build_from_source_formulae
if @table[:build_from_source?] || @table[:HEAD?] || @table[:build_bottle?]
named.to_formulae.map(&:full_name)
else
[]
end
end
sig { returns(T::Array[String]) }
def include_test_formulae
if @table[:include_test?]
named.to_formulae.map(&:full_name)
else
[]
end
end
sig { params(name: String).returns(T.nilable(String)) }
def value(name)
arg_prefix = "--#{name}="
flag_with_value = flags_only.find { |arg| arg.start_with?(arg_prefix) }
return unless flag_with_value
flag_with_value.delete_prefix(arg_prefix)
end
sig { returns(Context::ContextStruct) }
def context
Context::ContextStruct.new(debug: debug?, quiet: quiet?, verbose: verbose?)
end
sig { returns(T.nilable(Symbol)) }
def only_formula_or_cask
if @table[:formula?] && !@table[:cask?]
:formula
elsif @table[:cask?] && !@table[:formula?]
:cask
end
end
sig { returns(T::Array[[Symbol, Symbol]]) }
def os_arch_combinations
skip_invalid_combinations = false
oses = case (os_sym = @table[:os]&.to_sym)
when nil
[SimulateSystem.current_os]
when :all
skip_invalid_combinations = true
OnSystem::ALL_OS_OPTIONS
else
[os_sym]
end
arches = case (arch_sym = @table[:arch]&.to_sym)
when nil
[SimulateSystem.current_arch]
when :all
skip_invalid_combinations = true
OnSystem::ARCH_OPTIONS
else
[arch_sym]
end
oses.product(arches).select do |os, arch|
if skip_invalid_combinations
bottle_tag = Utils::Bottles::Tag.new(system: os, arch:)
bottle_tag.valid_combination?
else
true
end
end
end
private
sig { params(option: String).returns(String) }
def option_to_name(option)
option.sub(/\A--?/, "")
.tr("-", "_")
end
sig { returns(T::Array[String]) }
def cli_args
@cli_args ||= @processed_options.filter_map do |short, long|
option = T.must(long || short)
switch = :"#{option_to_name(option)}?"
flag = option_to_name(option).to_sym
if @table[switch] == true || @table[flag] == true
option
elsif @table[flag].instance_of? String
"#{option}=#{@table[flag]}"
elsif @table[flag].instance_of? Array
"#{option}=#{@table[flag].join(",")}"
end
end.freeze
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/cli/error.rb | Library/Homebrew/cli/error.rb | # typed: strict
# frozen_string_literal: true
require "utils/formatter"
module Homebrew
module CLI
class OptionConstraintError < UsageError
sig { params(arg1: String, arg2: String, missing: T::Boolean).void }
def initialize(arg1, arg2, missing: false)
message = if missing
"`#{arg2}` cannot be passed without `#{arg1}`."
else
"`#{arg1}` and `#{arg2}` should be passed together."
end
super message
end
end
class OptionConflictError < UsageError
sig { params(args: T::Array[String]).void }
def initialize(args)
args_list = args.map { Formatter.option(it) }.join(" and ")
super "Options #{args_list} are mutually exclusive."
end
end
class InvalidConstraintError < UsageError
sig { params(arg1: String, arg2: String).void }
def initialize(arg1, arg2)
super "`#{arg1}` and `#{arg2}` cannot be mutually exclusive and mutually dependent simultaneously."
end
end
class MaxNamedArgumentsError < UsageError
sig { params(maximum: Integer, types: T::Array[Symbol]).void }
def initialize(maximum, types: [])
super case maximum
when 0
"This command does not take named arguments."
else
types << :named if types.empty?
arg_types = types.map { |type| type.to_s.tr("_", " ") }
.to_sentence two_words_connector: " or ", last_word_connector: " or "
"This command does not take more than #{maximum} #{arg_types} #{Utils.pluralize("argument", maximum)}."
end
end
end
class MinNamedArgumentsError < UsageError
sig { params(minimum: Integer, types: T::Array[Symbol]).void }
def initialize(minimum, types: [])
types << :named if types.empty?
arg_types = types.map { |type| type.to_s.tr("_", " ") }
.to_sentence two_words_connector: " or ", last_word_connector: " or "
super "This command requires at least #{minimum} #{arg_types} #{Utils.pluralize("argument", minimum)}."
end
end
class NumberOfNamedArgumentsError < UsageError
sig { params(minimum: Integer, types: T::Array[Symbol]).void }
def initialize(minimum, types: [])
types << :named if types.empty?
arg_types = types.map { |type| type.to_s.tr("_", " ") }
.to_sentence two_words_connector: " or ", last_word_connector: " or "
super "This command requires exactly #{minimum} #{arg_types} #{Utils.pluralize("argument", minimum)}."
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/unpack_strategy/air.rb | Library/Homebrew/unpack_strategy/air.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking Adobe Air archives.
class Air
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".air"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
mime_type = "application/vnd.adobe.air-application-installer-package+zip"
path.magic_number.match?(/.{59}#{Regexp.escape(mime_type)}/)
end
sig { returns(T::Array[Cask::Cask]) }
def dependencies
@dependencies ||= T.let([Cask::CaskLoader.load("adobe-air")], T.nilable(T::Array[Cask::Cask]))
end
AIR_APPLICATION_INSTALLER =
"/Applications/Utilities/Adobe AIR Application Installer.app/Contents/MacOS/Adobe AIR Application Installer"
private_constant :AIR_APPLICATION_INSTALLER
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! AIR_APPLICATION_INSTALLER,
args: ["-silent", "-location", unpack_dir, path],
verbose:
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/unpack_strategy/executable.rb | Library/Homebrew/unpack_strategy/executable.rb | # typed: strict
# frozen_string_literal: true
require_relative "uncompressed"
module UnpackStrategy
# Strategy for unpacking executables.
class Executable < Uncompressed
sig { override.returns(T::Array[String]) }
def self.extensions
[".sh", ".bash"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\A#!\s*\S+/n) ||
path.magic_number.match?(/\AMZ/n)
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/unpack_strategy/mercurial.rb | Library/Homebrew/unpack_strategy/mercurial.rb | # typed: strict
# frozen_string_literal: true
require_relative "directory"
module UnpackStrategy
# Strategy for unpacking Mercurial repositories.
class Mercurial < Directory
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
!!(super && (path/".hg").directory?)
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "hg",
args: ["--cwd", path, "archive", "--subrepos", "-y", "-t", "files", unpack_dir],
env: { "PATH" => PATH.new(Formula["mercurial"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/directory.rb | Library/Homebrew/unpack_strategy/directory.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking directories.
class Directory
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.directory?
end
sig {
params(
path: T.any(String, Pathname),
ref_type: T.nilable(Symbol),
ref: T.nilable(String),
merge_xattrs: T::Boolean,
move: T::Boolean,
).void
}
def initialize(path, ref_type: nil, ref: nil, merge_xattrs: false, move: false)
super(path, ref_type:, ref:, merge_xattrs:)
@move = move
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
move_to_dir(unpack_dir, verbose:) if @move
path_children = path.children
return if path_children.empty?
system_command!("cp", args: ["-pR", *path_children, unpack_dir], verbose:)
end
# Move all files from source `path` to target `unpack_dir`. Any existing
# subdirectories are not modified and only the contents are moved.
#
# @raise [RuntimeError] on unsupported `mv` operation, e.g. overwriting a file with a directory
sig { params(unpack_dir: Pathname, verbose: T::Boolean).void }
def move_to_dir(unpack_dir, verbose:)
path.find do |src|
next if src == path
dst = unpack_dir/src.relative_path_from(path)
if dst.exist?
dst_real_dir = dst.directory? && !dst.symlink?
src_real_dir = src.directory? && !src.symlink?
# Avoid moving a directory over an existing non-directory and vice versa.
# This outputs the same error message as GNU mv which is more readable than macOS mv.
raise "mv: cannot overwrite non-directory '#{dst}' with directory '#{src}'" if src_real_dir && !dst_real_dir
raise "mv: cannot overwrite directory '#{dst}' with non-directory '#{src}'" if !src_real_dir && dst_real_dir
# Defer writing over existing directories. Handle this later on to copy attributes
next if dst_real_dir
FileUtils.rm(dst, verbose:)
end
FileUtils.mv(src, dst, verbose:)
Find.prune
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/unpack_strategy/jar.rb | Library/Homebrew/unpack_strategy/jar.rb | # typed: strict
# frozen_string_literal: true
require_relative "uncompressed"
module UnpackStrategy
# Strategy for unpacking Java archives.
class Jar < Uncompressed
sig { override.returns(T::Array[String]) }
def self.extensions
[".apk", ".jar"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
return false unless Zip.can_extract?(path)
# Check further if the ZIP is a JAR/WAR.
path.zipinfo.include?("META-INF/MANIFEST.MF")
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/unpack_strategy/compress.rb | Library/Homebrew/unpack_strategy/compress.rb | # typed: strict
# frozen_string_literal: true
require_relative "tar"
module UnpackStrategy
# Strategy for unpacking compress archives.
class Compress < Tar
sig { override.returns(T::Array[String]) }
def self.extensions
[".Z"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\A\037\235/n)
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/unpack_strategy/p7zip.rb | Library/Homebrew/unpack_strategy/p7zip.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking P7ZIP archives.
class P7Zip
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".7z"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\A7z\xBC\xAF\x27\x1C/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["p7zip"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "7zr",
args: ["x", "-y", "-bd", "-bso0", path, "-o#{unpack_dir}"],
env: { "PATH" => PATH.new(Formula["p7zip"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/pax.rb | Library/Homebrew/unpack_strategy/pax.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking pax archives.
class Pax
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".pax"]
end
sig { override.params(_path: Pathname).returns(T::Boolean) }
def self.can_extract?(_path)
false
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "pax",
args: ["-rf", path],
chdir: unpack_dir,
verbose:
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/unpack_strategy/tar.rb | Library/Homebrew/unpack_strategy/tar.rb | # typed: strict
# frozen_string_literal: true
require "system_command"
module UnpackStrategy
# Strategy for unpacking tar archives.
class Tar
include UnpackStrategy
extend SystemCommand::Mixin
sig { override.returns(T::Array[String]) }
def self.extensions
[
".tar",
".tbz", ".tbz2", ".tar.bz2",
".tgz", ".tar.gz",
".tlzma", ".tar.lzma",
".txz", ".tar.xz",
".tar.zst",
".crate"
]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
return true if path.magic_number.match?(/\A.{257}ustar/n)
return false unless [Bzip2, Gzip, Lzip, Xz, Zstd].any? { |s| s.can_extract?(path) }
# Check if `tar` can list the contents, then it can also extract it.
stdout, _, status = system_command("tar", args: ["--list", "--file", path], print_stderr: false).to_a
(status.success? && !stdout.empty?) || false
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
Dir.mktmpdir("homebrew-tar", HOMEBREW_TEMP) do |tmpdir|
tar_path = if DependencyCollector.tar_needs_xz_dependency? && Xz.can_extract?(path)
subextract(Xz, Pathname(tmpdir), verbose)
elsif Zstd.can_extract?(path)
subextract(Zstd, Pathname(tmpdir), verbose)
else
path
end
system_command! "tar",
args: ["--extract", "--no-same-owner",
"--file", tar_path,
"--directory", unpack_dir],
verbose:
end
end
sig {
params(extractor: T.any(T.class_of(Xz), T.class_of(Zstd)), dir: Pathname, verbose: T::Boolean).returns(Pathname)
}
def subextract(extractor, dir, verbose)
extractor.new(path).extract(to: dir, verbose:)
dir.children.fetch(0)
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/unpack_strategy/cab.rb | Library/Homebrew/unpack_strategy/cab.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking Cabinet archives.
class Cab
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".cab"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\AMSCF/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["cabextract"]], T.nilable(T::Array[Formula]))
end
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "cabextract",
args: ["-d", unpack_dir, "--", path],
env: { "PATH" => PATH.new(Formula["cabextract"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/subversion.rb | Library/Homebrew/unpack_strategy/subversion.rb | # typed: strict
# frozen_string_literal: true
require_relative "directory"
module UnpackStrategy
# Strategy for unpacking Subversion repositories.
class Subversion < Directory
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
!!(super && (path/".svn").directory?)
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "svn",
args: ["export", "--force", ".", unpack_dir],
chdir: path.to_s,
verbose:
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/unpack_strategy/bazaar.rb | Library/Homebrew/unpack_strategy/bazaar.rb | # typed: strict
# frozen_string_literal: true
require_relative "directory"
module UnpackStrategy
# Strategy for unpacking Bazaar archives.
class Bazaar < Directory
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
!!(super && (path/".bzr").directory?)
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
super
# The export command doesn't work on checkouts (see https://bugs.launchpad.net/bzr/+bug/897511).
FileUtils.rm_r(unpack_dir/".bzr")
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/unpack_strategy/bzip2.rb | Library/Homebrew/unpack_strategy/bzip2.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking bzip2 archives.
class Bzip2
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".bz2"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\ABZh/n)
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
FileUtils.cp path, unpack_dir/basename, preserve: true
quiet_flags = verbose ? [] : ["-q"]
system_command! "bunzip2",
args: [*quiet_flags, unpack_dir/basename],
verbose:
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/unpack_strategy/zstd.rb | Library/Homebrew/unpack_strategy/zstd.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking zstd archives.
class Zstd
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".zst"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\x28\xB5\x2F\xFD/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["zstd"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
FileUtils.cp path, unpack_dir/basename, preserve: true
quiet_flags = verbose ? [] : ["-q"]
system_command! "unzstd",
args: [*quiet_flags, "-T0", "--rm", "--", unpack_dir/basename],
env: { "PATH" => PATH.new(Formula["zstd"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/lha.rb | Library/Homebrew/unpack_strategy/lha.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking LHa archives.
class Lha
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".lha", ".lzh"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\A..-(lh0|lh1|lz4|lz5|lzs|lh\\40|lhd|lh2|lh3|lh4|lh5)-/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["lha"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "lha",
args: ["xq2w=#{unpack_dir}", path],
env: { "PATH" => PATH.new(Formula["lha"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/zip.rb | Library/Homebrew/unpack_strategy/zip.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking ZIP archives.
class Zip
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".zip"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\APK(\003\004|\005\006)/n)
end
private
sig {
override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean)
.returns(SystemCommand::Result)
}
def extract_to_dir(unpack_dir, basename:, verbose:)
odebug "in unpack_strategy, zip, extract_to_dir, verbose: #{verbose.inspect}"
unzip = if which("unzip").blank?
begin
Formula["unzip"]
rescue FormulaUnavailableError
nil
end
end
with_env(TZ: "UTC") do
quiet_flags = verbose ? [] : ["-qq"]
result = system_command! "unzip",
args: [*quiet_flags, "-o", path, "-d", unpack_dir],
env: { "PATH" => PATH.new(unzip&.opt_bin, ENV.fetch("PATH")).to_s },
verbose:,
print_stderr: false
FileUtils.rm_rf unpack_dir/"__MACOSX"
result
end
end
end
end
require "extend/os/unpack_strategy/zip"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/unpack_strategy/cvs.rb | Library/Homebrew/unpack_strategy/cvs.rb | # typed: strict
# frozen_string_literal: true
require_relative "directory"
module UnpackStrategy
# Strategy for unpacking CVS repositories.
class Cvs < Directory
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
!!(super && (path/"CVS").directory?)
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/unpack_strategy/rar.rb | Library/Homebrew/unpack_strategy/rar.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking RAR archives.
class Rar
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".rar"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\ARar!/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["libarchive"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "bsdtar",
args: ["x", "-f", path, "-C", unpack_dir],
env: { "PATH" => PATH.new(Formula["libarchive"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/lua_rock.rb | Library/Homebrew/unpack_strategy/lua_rock.rb | # typed: strict
# frozen_string_literal: true
require_relative "uncompressed"
module UnpackStrategy
# Strategy for unpacking LuaRock archives.
class LuaRock < Uncompressed
sig { override.returns(T::Array[String]) }
def self.extensions
[".rock"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
return false unless Zip.can_extract?(path)
# Check further if the ZIP is a LuaRocks package.
path.zipinfo.grep(%r{\A[^/]+.rockspec\Z}).any?
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/unpack_strategy/gzip.rb | Library/Homebrew/unpack_strategy/gzip.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking gzip archives.
class Gzip
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".gz"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\A\037\213/n)
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
FileUtils.cp path, unpack_dir/basename, preserve: true
quiet_flags = verbose ? [] : ["-q"]
system_command! "gunzip",
args: [*quiet_flags, "-N", "--", unpack_dir/basename],
verbose:
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/unpack_strategy/otf.rb | Library/Homebrew/unpack_strategy/otf.rb | # typed: strict
# frozen_string_literal: true
require_relative "uncompressed"
module UnpackStrategy
# Strategy for unpacking OpenType fonts.
class Otf < Uncompressed
sig { override.returns(T::Array[String]) }
def self.extensions
[".otf"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\AOTTO/n)
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/unpack_strategy/xz.rb | Library/Homebrew/unpack_strategy/xz.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking xz archives.
class Xz
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".xz"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\A\xFD7zXZ\x00/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["xz"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
FileUtils.cp path, unpack_dir/basename, preserve: true
quiet_flags = verbose ? [] : ["-q"]
system_command! "unxz",
args: [*quiet_flags, "-T0", "--", unpack_dir/basename],
env: { "PATH" => PATH.new(Formula["xz"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/uncompressed.rb | Library/Homebrew/unpack_strategy/uncompressed.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking uncompressed files.
class Uncompressed
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions = []
sig { override.params(_path: Pathname).returns(T::Boolean) }
def self.can_extract?(_path) = false
sig {
params(
to: T.nilable(Pathname),
basename: T.nilable(T.any(String, Pathname)),
verbose: T::Boolean,
prioritize_extension: T::Boolean,
).returns(T.untyped)
}
def extract_nestedly(to: nil, basename: nil, verbose: false, prioritize_extension: false)
extract(to:, basename:, verbose:)
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose: false)
FileUtils.cp path, unpack_dir/basename.sub(/^[\da-f]{64}--/, ""), preserve: true, verbose:
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/unpack_strategy/dmg.rb | Library/Homebrew/unpack_strategy/dmg.rb | # typed: strict
# frozen_string_literal: true
require "tempfile"
require "system_command"
require "utils/output"
module UnpackStrategy
# Strategy for unpacking disk images.
class Dmg
extend SystemCommand::Mixin
include UnpackStrategy
# Helper module for listing the contents of a volume mounted from a disk image.
module Bom
extend Utils::Output::Mixin
extend SystemCommand::Mixin
DMG_METADATA = T.let(Set.new([
".background",
".com.apple.timemachine.donotpresent",
".com.apple.timemachine.supported",
".DocumentRevisions-V100",
".DS_Store",
".fseventsd",
".MobileBackups",
".Spotlight-V100",
".TemporaryItems",
".Trashes",
".VolumeIcon.icns",
".HFS+ Private Directory Data\r", # do not remove `\r`, it is a part of directory name
".HFS+ Private Data\r",
]).freeze, T::Set[String])
private_constant :DMG_METADATA
class Error < RuntimeError; end
class EmptyError < Error
sig { params(path: Pathname).void }
def initialize(path)
super "BOM for path '#{path}' is empty."
end
end
# Check if path is considered disk image metadata.
sig { params(pathname: Pathname).returns(T::Boolean) }
def self.dmg_metadata?(pathname)
DMG_METADATA.include?(pathname.cleanpath.ascend.to_a.last.to_s)
end
# Check if path is a symlink to a system directory (commonly to /Applications).
sig { params(pathname: Pathname).returns(T::Boolean) }
def self.system_dir_symlink?(pathname)
pathname.symlink? && MacOS.system_dir?(pathname.dirname.join(pathname.readlink))
end
sig { params(pathname: Pathname).returns(String) }
def self.bom(pathname)
tries = 0
result = loop do
# We need to use `find` here instead of Ruby in order to properly handle
# file names containing special characters, such as “e” + “´” vs. “é”.
r = system_command("find", args: [".", "-print0"], chdir: pathname, print_stderr: false, reset_uid: true)
tries += 1
# Spurious bug on CI, which in most cases can be worked around by retrying.
break r unless r.stderr.match?(/Interrupted system call/i)
raise "Command `#{r.command.shelljoin}` was interrupted." if tries >= 3
end
odebug "Command `#{result.command.shelljoin}` in '#{pathname}' took #{tries} tries." if tries > 1
bom_paths = result.stdout.split("\0")
raise EmptyError, pathname if bom_paths.empty?
bom_paths
.reject { |path| dmg_metadata?(Pathname(path)) }
.reject { |path| system_dir_symlink?(pathname/path) }
.join("\n")
end
end
# Strategy for unpacking a volume mounted from a disk image.
class Mount
include UnpackStrategy
sig { params(verbose: T::Boolean).void }
def eject(verbose: false)
tries = 3
begin
return unless path.exist?
if tries > 1
disk_info = system_command!(
"diskutil",
args: ["info", "-plist", path],
print_stderr: false,
verbose:,
)
# For HFS, just use <mount-path>
# For APFS, find the <physical-store> corresponding to <mount-path>
eject_paths = disk_info.plist
.fetch("APFSPhysicalStores", [])
.filter_map { |store| store["APFSPhysicalStore"] }
.presence || [path]
eject_paths.each do |eject_path|
system_command! "diskutil",
args: ["eject", eject_path],
print_stderr: false,
verbose:
end
else
system_command! "diskutil",
args: ["unmount", "force", path],
print_stderr: false,
verbose:
end
rescue ErrorDuringExecution => e
raise e if (tries -= 1).zero?
sleep 1
retry
end
end
sig { override.returns(T::Array[String]) }
def self.extensions = []
sig { override.params(_path: Pathname).returns(T::Boolean) }
def self.can_extract?(_path) = false
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
tries = 3
bom = begin
Bom.bom(path)
rescue Bom::EmptyError => e
raise e if (tries -= 1).zero?
sleep 1
retry
end
Tempfile.open(["", ".bom"]) do |bomfile|
bomfile.close
Tempfile.open(["", ".list"]) do |filelist|
filelist.puts(bom)
filelist.close
system_command! "mkbom",
args: ["-s", "-i", T.must(filelist.path), "--", T.must(bomfile.path)],
verbose:
end
bomfile_path = T.must(bomfile.path)
system_command!("ditto",
args: ["--bom", bomfile_path, "--", path, unpack_dir],
verbose:,
reset_uid: true)
FileUtils.chmod "u+w", Pathname.glob(unpack_dir/"**/*", File::FNM_DOTMATCH).reject(&:symlink?)
end
end
end
private_constant :Mount
sig { override.returns(T::Array[String]) }
def self.extensions
[".dmg"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
stdout, _, status = system_command("hdiutil", args: ["imageinfo", "-format", path], print_stderr: false).to_a
(status.success? && !stdout.empty?) || false
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
mount(verbose:) do |mounts|
raise "No mounts found in '#{path}'; perhaps this is a bad disk image?" if mounts.empty?
mounts.each do |mount|
mount.extract(to: unpack_dir, verbose:)
end
end
end
sig { params(verbose: T::Boolean, _block: T.proc.params(arg0: T::Array[Mount]).void).void }
def mount(verbose: false, &_block)
Dir.mktmpdir("homebrew-dmg", HOMEBREW_TEMP) do |mount_dir|
mount_dir = Pathname(mount_dir)
without_eula = system_command(
"hdiutil",
args: [
"attach", "-plist", "-nobrowse", "-readonly",
"-mountrandom", mount_dir, path
],
input: "qn\n",
print_stderr: false,
verbose:,
)
# If mounting without agreeing to EULA succeeded, there is none.
plist = if without_eula.success?
without_eula.plist
else
cdr_path = mount_dir/path.basename.sub_ext(".cdr")
quiet_flag = "-quiet" unless verbose
system_command!(
"hdiutil",
args: [
"convert", *quiet_flag, "-format", "UDTO", "-o", cdr_path, path
],
verbose:,
)
with_eula = system_command!(
"hdiutil",
args: [
"attach", "-plist", "-nobrowse", "-readonly",
"-mountrandom", mount_dir, cdr_path
],
verbose:,
)
if verbose && !(eula_text = without_eula.stdout).empty?
ohai "Software License Agreement for '#{path}':", eula_text
end
with_eula.plist
end
mounts = if plist.respond_to?(:fetch)
plist.fetch("system-entities", [])
.filter_map { |entity| entity["mount-point"] }
.map { |path| Mount.new(path) }
else
[]
end
begin
yield mounts
ensure
mounts.each do |mount|
mount.eject(verbose:)
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/unpack_strategy/fossil.rb | Library/Homebrew/unpack_strategy/fossil.rb | # typed: strict
# frozen_string_literal: true
require "system_command"
module UnpackStrategy
# Strategy for unpacking Fossil repositories.
class Fossil
include UnpackStrategy
extend SystemCommand::Mixin
sig { override.returns(T::Array[String]) }
def self.extensions
[]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
return false unless path.magic_number.match?(/\ASQLite format 3\000/n)
# Fossil database is made up of artifacts, so the `artifact` table must exist.
query = "select count(*) from sqlite_master where type = 'view' and name = 'artifact'"
system_command("sqlite3", args: [path, query]).stdout.to_i == 1
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
args = if @ref_type && @ref
[@ref]
else
[]
end
system_command! "fossil",
args: ["open", path, *args],
chdir: unpack_dir,
env: { "PATH" => PATH.new(Formula["fossil"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/xar.rb | Library/Homebrew/unpack_strategy/xar.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking xar archives.
class Xar
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".xar"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\Axar!/n)
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "xar",
args: ["-x", "-f", path, "-C", unpack_dir],
verbose:
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/unpack_strategy/microsoft_office_xml.rb | Library/Homebrew/unpack_strategy/microsoft_office_xml.rb | # typed: strict
# frozen_string_literal: true
require_relative "uncompressed"
module UnpackStrategy
# Strategy for unpacking Microsoft Office documents.
class MicrosoftOfficeXml < Uncompressed
sig { override.returns(T::Array[String]) }
def self.extensions
[
".doc", ".docx",
".ppt", ".pptx",
".xls", ".xlsx"
]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
return false unless Zip.can_extract?(path)
# Check further if the ZIP is a Microsoft Office XML document.
path.magic_number.match?(/\APK\003\004/n) &&
path.magic_number.match?(%r{\A.{30}(\[Content_Types\]\.xml|_rels/\.rels)}n)
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/unpack_strategy/pkg.rb | Library/Homebrew/unpack_strategy/pkg.rb | # typed: strict
# frozen_string_literal: true
require_relative "uncompressed"
module UnpackStrategy
# Strategy for unpacking macOS package installers.
class Pkg < Uncompressed
sig { override.returns(T::Array[String]) }
def self.extensions
[".pkg", ".mkpg"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.extname.match?(/\A.m?pkg\Z/) &&
(path.directory? || path.magic_number.match?(/\Axar!/n))
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/unpack_strategy/self_extracting_executable.rb | Library/Homebrew/unpack_strategy/self_extracting_executable.rb | # typed: strict
# frozen_string_literal: true
require_relative "generic_unar"
module UnpackStrategy
# Strategy for unpacking self-extracting executables.
class SelfExtractingExecutable < GenericUnar
sig { override.returns(T::Array[String]) }
def self.extensions
[]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\AMZ/n) &&
path.file_type.include?("self-extracting archive")
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/unpack_strategy/generic_unar.rb | Library/Homebrew/unpack_strategy/generic_unar.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking archives with `unar`.
class GenericUnar
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[]
end
sig { override.params(_path: Pathname).returns(T::Boolean) }
def self.can_extract?(_path)
false
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["unar"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
system_command! "unar",
args: [
"-force-overwrite", "-quiet", "-no-directory",
"-output-directory", unpack_dir, "--", path
],
env: { "PATH" => PATH.new(Formula["unar"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/git.rb | Library/Homebrew/unpack_strategy/git.rb | # typed: strict
# frozen_string_literal: true
require_relative "directory"
module UnpackStrategy
# Strategy for unpacking Git repositories.
class Git < Directory
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
!!(super && (path/".git").directory?)
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/unpack_strategy/ttf.rb | Library/Homebrew/unpack_strategy/ttf.rb | # typed: strict
# frozen_string_literal: true
require_relative "uncompressed"
module UnpackStrategy
# Strategy for unpacking TrueType fonts.
class Ttf < Uncompressed
sig { override.returns(T::Array[String]) }
def self.extensions
[".ttc", ".ttf"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
# TrueType Font
path.magic_number.match?(/\A\000\001\000\000\000/n) ||
# Truetype Font Collection
path.magic_number.match?(/\Attcf/n)
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/unpack_strategy/lzip.rb | Library/Homebrew/unpack_strategy/lzip.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking lzip archives.
class Lzip
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".lz"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\ALZIP/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["lzip"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
FileUtils.cp path, unpack_dir/basename, preserve: true
quiet_flags = verbose ? [] : ["-q"]
system_command! "lzip",
args: ["-d", *quiet_flags, unpack_dir/basename],
env: { "PATH" => PATH.new(Formula["lzip"].opt_bin, ENV.fetch("PATH")) },
verbose:
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/unpack_strategy/sit.rb | Library/Homebrew/unpack_strategy/sit.rb | # typed: strict
# frozen_string_literal: true
require_relative "generic_unar"
module UnpackStrategy
# Strategy for unpacking Stuffit archives.
class Sit < GenericUnar
sig { override.returns(T::Array[String]) }
def self.extensions
[".sit"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\AStuffIt/n)
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/unpack_strategy/lzma.rb | Library/Homebrew/unpack_strategy/lzma.rb | # typed: strict
# frozen_string_literal: true
module UnpackStrategy
# Strategy for unpacking LZMA archives.
class Lzma
include UnpackStrategy
sig { override.returns(T::Array[String]) }
def self.extensions
[".lzma"]
end
sig { override.params(path: Pathname).returns(T::Boolean) }
def self.can_extract?(path)
path.magic_number.match?(/\A\]\000\000\200\000/n)
end
sig { returns(T::Array[Formula]) }
def dependencies
@dependencies ||= T.let([Formula["xz"]], T.nilable(T::Array[Formula]))
end
private
sig { override.params(unpack_dir: Pathname, basename: Pathname, verbose: T::Boolean).void }
def extract_to_dir(unpack_dir, basename:, verbose:)
FileUtils.cp path, unpack_dir/basename, preserve: true
quiet_flags = verbose ? [] : ["-q"]
system_command! "unlzma",
args: [*quiet_flags, "--", unpack_dir/basename],
env: { "PATH" => PATH.new(Formula["xz"].opt_bin, ENV.fetch("PATH")) },
verbose:
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/standalone/sorbet.rb | Library/Homebrew/standalone/sorbet.rb | # typed: true
# frozen_string_literal: true
require "sorbet-runtime"
require "extend/module"
# Disable runtime checking unless enabled.
# In the future we should consider not doing this monkey patch,
# if assured that there is no performance hit from removing this.
# There are mechanisms to achieve a middle ground (`default_checked_level`).
if ENV["HOMEBREW_SORBET_RUNTIME"]
T::Configuration.enable_final_checks_on_hooks
if ENV["HOMEBREW_SORBET_RECURSIVE"] == "1"
module T
module Types
class FixedArray < Base
def valid?(obj) = recursively_valid?(obj)
end
class FixedHash < Base
def valid?(obj) = recursively_valid?(obj)
end
class Intersection < Base
def valid?(obj) = recursively_valid?(obj)
end
class TypedArray < TypedEnumerable
def valid?(obj) = recursively_valid?(obj)
end
class TypedEnumerable < Base
def valid?(obj) = recursively_valid?(obj)
end
class TypedEnumeratorChain < TypedEnumerable
def valid?(obj) = recursively_valid?(obj)
end
class TypedEnumeratorLazy < TypedEnumerable
def valid?(obj) = recursively_valid?(obj)
end
class TypedHash < TypedEnumerable
def valid?(obj) = recursively_valid?(obj)
end
class TypedRange < TypedEnumerable
def valid?(obj) = recursively_valid?(obj)
end
class TypedSet < TypedEnumerable
def valid?(obj) = recursively_valid?(obj)
end
class Union < Base
def valid?(obj) = recursively_valid?(obj)
end
end
end
end
else
# Redefine `T.let`, etc. to make the `checked` parameter default to `false` rather than `true`.
# @private
module TNoChecks
def cast(value, type, checked: false)
super
end
def let(value, type, checked: false)
super
end
def bind(value, type, checked: false)
super
end
def assert_type!(value, type, checked: false)
super
end
end
# @private
module T
class << self
prepend TNoChecks
end
# Redefine `T.sig` to be a no-op.
module Sig
def sig(arg0 = nil, &blk); end
end
end
# For any cases the above doesn't handle: make sure we don't let TypeError slip through.
T::Configuration.call_validation_error_handler = ->(signature, opts) {}
T::Configuration.inline_type_error_handler = ->(error, opts) {}
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/standalone/init.rb | Library/Homebrew/standalone/init.rb | # typed: true
# frozen_string_literal: true
# This file is included before any other files.
# It intentionally has typing disabled and uses `Homebrew::FastBootRequire`
# or `require_relative` to load all files
# (except "rbconfig" which is needed by `Homebrew::FastBootRequire`)
required_ruby_major, required_ruby_minor, = ENV.fetch("HOMEBREW_REQUIRED_RUBY_VERSION", "").split(".").map(&:to_i)
gems_vendored = if required_ruby_minor.nil?
# We're likely here if running RuboCop etc, so just assume we don't need to install gems as we likely already have
true
else
ruby_major, ruby_minor, = RUBY_VERSION.split(".").map(&:to_i)
raise "Could not parse Ruby requirements" if !ruby_major || !ruby_minor || !required_ruby_major
if ruby_major < required_ruby_major || (ruby_major == required_ruby_major && ruby_minor < required_ruby_minor)
raise "Homebrew must be run under Ruby #{required_ruby_major}.#{required_ruby_minor}! " \
"You're running #{RUBY_VERSION}."
end
# This list should match .gitignore
vendored_versions = ["3.4"].freeze
vendored_versions.include?("#{ruby_major}.#{ruby_minor}")
end.freeze
if ENV["HOMEBREW_DEVELOPER"]
Warning.categories.each do |category|
Warning[category] = true
end
end
# Setup Homebrew::FastBootRequire for faster boot requires.
# Inspired by https://github.com/Shopify/bootsnap/wiki/Bootlib::Require
require "rbconfig"
module Homebrew
module FastBootRequire
ARCHDIR = RbConfig::CONFIG["archdir"].freeze
RUBYLIBDIR = RbConfig::CONFIG["rubylibdir"].freeze
def self.from_archdir(feature)
require(File.join(ARCHDIR, feature.to_s))
end
def self.from_rubylibdir(feature)
require(File.join(RUBYLIBDIR, "#{feature}.rb"))
end
end
end
# We trust base Ruby to provide what we need.
# Don't look into the user-installed sitedir, which may contain older versions of RubyGems.
$LOAD_PATH.reject! { |path| path.start_with?(RbConfig::CONFIG["sitedir"]) }
Homebrew::FastBootRequire.from_rubylibdir("pathname")
dir = __dir__ || raise("__dir__ is not defined")
HOMEBREW_LIBRARY_PATH = Pathname(dir).parent.realpath.freeze
HOMEBREW_USING_PORTABLE_RUBY = RbConfig.ruby.include?("/vendor/portable-ruby/").freeze
HOMEBREW_BUNDLER_VERSION = ENV.fetch("HOMEBREW_BUNDLER_VERSION").freeze
ENV["BUNDLER_VERSION"] = HOMEBREW_BUNDLER_VERSION
require_relative "../utils/gems"
Homebrew.setup_gem_environment!(setup_path: false)
# Install gems for Rubies we don't vendor for.
if !gems_vendored && !ENV["HOMEBREW_SKIP_INITIAL_GEM_INSTALL"]
Homebrew.install_bundler_gems!(setup_path: false)
ENV["HOMEBREW_SKIP_INITIAL_GEM_INSTALL"] = "1"
end
unless $LOAD_PATH.include?(HOMEBREW_LIBRARY_PATH.to_s)
# Insert the path after any existing Homebrew paths (e.g. those inserted by tests and parent processes)
last_homebrew_path_idx = $LOAD_PATH.rindex do |path|
path.start_with?(HOMEBREW_LIBRARY_PATH.to_s) && !path.include?("vendor/portable-ruby")
end || -1
$LOAD_PATH.insert(last_homebrew_path_idx + 1, HOMEBREW_LIBRARY_PATH.to_s)
end
require_relative "../vendor/bundle/bundler/setup"
Homebrew::FastBootRequire.from_archdir("portable_ruby_gems") if HOMEBREW_USING_PORTABLE_RUBY
$LOAD_PATH.unshift "#{HOMEBREW_LIBRARY_PATH}/vendor/bundle/#{RUBY_ENGINE}/#{Gem.ruby_api_version}/gems/" \
"bundler-#{HOMEBREW_BUNDLER_VERSION}/lib"
$LOAD_PATH.uniq!
# These warnings are nice but often flag problems that are not even our responsibly,
# including in some cases from other Ruby standard library gems.
# We strictly only allow one version of Ruby at a time so future compatibility
# doesn't need to be handled ahead of time.
if defined?(Gem::BUNDLED_GEMS)
[Kernel.singleton_class, Kernel].each do |kernel_class|
next unless kernel_class.respond_to?(:no_warning_require, true)
kernel_class.alias_method :require, :no_warning_require
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/language/perl.rb | Library/Homebrew/language/perl.rb | # typed: strict
# frozen_string_literal: true
module Language
# Helper functions for Perl formulae.
#
# @api public
module Perl
# Helper module for replacing `perl` shebangs.
module Shebang
extend T::Helpers
requires_ancestor { Formula }
module_function
# A regex to match potential shebang permutations.
PERL_SHEBANG_REGEX = %r{\A#! ?(?:/usr/bin/(?:env )?)?perl( |$)}
# The length of the longest shebang matching `SHEBANG_REGEX`.
PERL_SHEBANG_MAX_LENGTH = T.let("#! /usr/bin/env perl ".length, Integer)
# @private
sig { params(perl_path: T.any(String, Pathname)).returns(Utils::Shebang::RewriteInfo) }
def perl_shebang_rewrite_info(perl_path)
Utils::Shebang::RewriteInfo.new(
PERL_SHEBANG_REGEX,
PERL_SHEBANG_MAX_LENGTH,
"#{perl_path}\\1",
)
end
sig { params(formula: Formula).returns(Utils::Shebang::RewriteInfo) }
def detected_perl_shebang(formula = T.cast(self, Formula))
perl_deps = formula.declared_deps.select { |dep| dep.required? && dep.name == "perl" }
raise ShebangDetectionError.new("Perl", "formula does not depend on Perl") if perl_deps.empty?
perl_path = if perl_deps.any? { |dep| !dep.uses_from_macos? || !dep.use_macos_install? }
Formula["perl"].opt_bin/"perl"
else
"/usr/bin/perl#{MacOS.preferred_perl_version}"
end
perl_shebang_rewrite_info(perl_path)
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/language/python.rb | Library/Homebrew/language/python.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Language
# Helper functions for Python formulae.
#
# @api public
module Python
extend ::Utils::Output::Mixin
sig { params(python: T.any(String, Pathname)).returns(T.nilable(Version)) }
def self.major_minor_version(python)
version = `#{python} --version 2>&1`.chomp[/(\d\.\d+)/, 1]
return unless version
Version.new(version)
end
sig { params(python: T.any(String, Pathname)).returns(Pathname) }
def self.homebrew_site_packages(python = "python3.7")
HOMEBREW_PREFIX/site_packages(python)
end
sig { params(python: T.any(String, Pathname)).returns(String) }
def self.site_packages(python = "python3.7")
if (python == "pypy") || (python == "pypy3")
"site-packages"
else
"lib/python#{major_minor_version python}/site-packages"
end
end
sig {
params(
build: T.any(BuildOptions, Tab),
block: T.nilable(T.proc.params(python: String, version: T.nilable(Version)).void),
).void
}
def self.each_python(build, &block)
original_pythonpath = ENV.fetch("PYTHONPATH", nil)
pythons = { "python@3" => "python3",
"pypy" => "pypy",
"pypy3" => "pypy3" }
pythons.each do |python_formula, python|
python_formula = Formulary.factory(python_formula)
next if build.without? python_formula.to_s
version = major_minor_version python
ENV["PYTHONPATH"] = if python_formula.latest_version_installed?
nil
else
homebrew_site_packages(python).to_s
end
block&.call python, version
end
ENV["PYTHONPATH"] = original_pythonpath
end
sig { params(python: T.any(String, Pathname)).returns(T::Boolean) }
def self.reads_brewed_pth_files?(python)
return false unless homebrew_site_packages(python).directory?
return false unless homebrew_site_packages(python).writable?
probe_file = homebrew_site_packages(python)/"homebrew-pth-probe.pth"
begin
probe_file.atomic_write("import site; site.homebrew_was_here = True")
with_homebrew_path { quiet_system python, "-c", "import site; assert(site.homebrew_was_here)" }
ensure
probe_file.unlink if probe_file.exist?
end
end
sig { params(python: T.any(String, Pathname)).returns(Pathname) }
def self.user_site_packages(python)
Pathname.new(`#{python} -c "import site; print(site.getusersitepackages())"`.chomp)
end
sig { params(python: T.any(String, Pathname), path: T.any(String, Pathname)).returns(T::Boolean) }
def self.in_sys_path?(python, path)
script = <<~PYTHON
import os, sys
[os.path.realpath(p) for p in sys.path].index(os.path.realpath("#{path}"))
PYTHON
quiet_system python, "-c", script
end
sig { params(prefix: Pathname, python: T.any(String, Pathname)).returns(T::Array[String]) }
def self.setup_install_args(prefix, python = "python3")
odeprecated "Language::Python.setup_install_args", "pip and `std_pip_args`"
shim = <<~PYTHON
import setuptools, tokenize
__file__ = 'setup.py'
exec(compile(getattr(tokenize, 'open', open)(__file__).read()
.replace('\\r\\n', '\\n'), __file__, 'exec'))
PYTHON
%W[
-c
#{shim}
--no-user-cfg
install
--prefix=#{prefix}
--install-scripts=#{prefix}/bin
--install-lib=#{prefix/site_packages(python)}
--single-version-externally-managed
--record=installed.txt
]
end
# Mixin module for {Formula} adding shebang rewrite features.
module Shebang
extend T::Helpers
requires_ancestor { Formula }
module_function
# A regex to match potential shebang permutations.
PYTHON_SHEBANG_REGEX = %r{\A#! ?(?:/usr/bin/(?:env )?)?python(?:[23](?:\.\d{1,2})?)?( |$)}
# The length of the longest shebang matching `SHEBANG_REGEX`.
PYTHON_SHEBANG_MAX_LENGTH = T.let("#! /usr/bin/env pythonx.yyy ".length, Integer)
# @private
sig { params(python_path: T.any(String, Pathname)).returns(Utils::Shebang::RewriteInfo) }
def python_shebang_rewrite_info(python_path)
Utils::Shebang::RewriteInfo.new(
PYTHON_SHEBANG_REGEX,
PYTHON_SHEBANG_MAX_LENGTH,
"#{python_path}\\1",
)
end
sig { params(formula: Formula, use_python_from_path: T::Boolean).returns(Utils::Shebang::RewriteInfo) }
def detected_python_shebang(formula = T.cast(self, Formula), use_python_from_path: false)
python_path = if use_python_from_path
"/usr/bin/env python3"
else
python_deps = formula.deps.select(&:required?).map(&:name).grep(/^python(@.+)?$/)
raise ShebangDetectionError.new("Python", "formula does not depend on Python") if python_deps.empty?
if python_deps.length > 1
raise ShebangDetectionError.new("Python", "formula has multiple Python dependencies")
end
python_dep = python_deps.first
Formula[python_dep].opt_bin/python_dep.sub("@", "")
end
python_shebang_rewrite_info(python_path)
end
end
# Mixin module for {Formula} adding virtualenv support features.
module Virtualenv
extend T::Helpers
requires_ancestor { Formula }
# Instantiates, creates and yields a {Virtualenv} object for use from
# {Formula#install}, which provides helper methods for instantiating and
# installing packages into a Python virtualenv.
#
# @param venv_root [Pathname, String] the path to the root of the virtualenv
# (often `libexec/"venv"`)
# @param python [String, Pathname] which interpreter to use (e.g. `"python3"`
# or `"python3.x"`)
# @param formula [Formula] the active {Formula}
# @return [Virtualenv] a {Virtualenv} instance
sig {
params(
venv_root: T.any(String, Pathname),
python: T.any(String, Pathname),
formula: Formula,
system_site_packages: T::Boolean,
without_pip: T::Boolean,
).returns(Virtualenv)
}
def virtualenv_create(venv_root, python = "python", formula = T.cast(self, Formula),
system_site_packages: true, without_pip: true)
# Limit deprecation to 3.12+ for now (or if we can't determine the version).
# Some used this argument for `setuptools`, which we no longer bundle since 3.12.
unless without_pip
python_version = Language::Python.major_minor_version(python)
if python_version.nil? || python_version.null? || python_version >= "3.12"
raise ArgumentError, "virtualenv_create's without_pip is deprecated starting with Python 3.12"
end
end
ENV.refurbish_args
venv = Virtualenv.new formula, venv_root, python
venv.create(system_site_packages:, without_pip:)
# Find any Python bindings provided by recursive dependencies
pth_contents = []
formula.recursive_dependencies do |dependent, dep|
Dependency.prune if dep.build? || dep.test?
# Apply default filter
Dependency.prune if (dep.optional? || dep.recommended?) && !dependent.build.with?(dep)
# Do not add the main site-package provided by the brewed
# Python formula, to keep the virtual-env's site-package pristine
Dependency.prune if python_names.include? dep.name
# Skip uses_from_macos dependencies as these imply no Python bindings
Dependency.prune if dep.uses_from_macos?
dep_site_packages = dep.to_formula.opt_prefix/Language::Python.site_packages(python)
Dependency.prune unless dep_site_packages.exist?
pth_contents << "import site; site.addsitedir('#{dep_site_packages}')\n"
end
(venv.site_packages/"homebrew_deps.pth").write pth_contents.join unless pth_contents.empty?
venv
end
# Returns true if a formula option for the specified python is currently
# active or if the specified python is required by the formula. Valid
# inputs are `"python"`, `"python2"` and `:python3`. Note that
# `"with-python"`, `"without-python"`, `"with-python@2"` and `"without-python@2"`
# formula options are handled correctly even if not associated with any
# corresponding depends_on statement.
sig { params(python: String).returns(T::Boolean) }
def needs_python?(python)
return true if build.with?(python)
(requirements.to_a | deps).any? { |r| r.name.split("/").last == python && r.required? }
end
# Helper method for the common case of installing a Python application.
# Creates a virtualenv in `libexec`, installs all `resource`s defined
# on the formula and then installs the formula. An options hash may be
# passed (e.g. `:using => "python"`) to override the default, guessed
# formula preference for python or python@x.y, or to resolve an ambiguous
# case where it's not clear whether python or python@x.y should be the
# default guess.
sig {
params(
using: T.nilable(String),
system_site_packages: T::Boolean,
without_pip: T::Boolean,
link_manpages: T::Boolean,
without: T.nilable(T.any(String, T::Array[String])),
start_with: T.nilable(T.any(String, T::Array[String])),
end_with: T.nilable(T.any(String, T::Array[String])),
).returns(Virtualenv)
}
def virtualenv_install_with_resources(using: nil, system_site_packages: true, without_pip: true,
link_manpages: true, without: nil, start_with: nil, end_with: nil)
python = using
if python.nil?
wanted = python_names.select { |py| needs_python?(py) }
raise FormulaUnknownPythonError, self if wanted.empty?
raise FormulaAmbiguousPythonError, self if wanted.size > 1
python = wanted.fetch(0)
python = "python3" if python == "python"
end
venv_resources = if without.nil? && start_with.nil? && end_with.nil?
resources
else
remaining_resources = resources.to_h { |resource| [resource.name, resource] }
slice_resources!(remaining_resources, Array(without))
start_with_resources = slice_resources!(remaining_resources, Array(start_with))
end_with_resources = slice_resources!(remaining_resources, Array(end_with))
start_with_resources + remaining_resources.values + end_with_resources
end
venv = virtualenv_create(libexec, python.delete("@"), system_site_packages:,
without_pip:)
venv.pip_install venv_resources
venv.pip_install_and_link(T.must(buildpath), link_manpages:)
venv
end
sig { returns(T::Array[String]) }
def python_names
%w[python python3 pypy pypy3] + Formula.names.select { |name| name.start_with? "python@" }
end
private
sig {
params(
resources_hash: T::Hash[String, Resource],
resource_names: T::Array[String],
).returns(T::Array[Resource])
}
def slice_resources!(resources_hash, resource_names)
resource_names.map do |resource_name|
resources_hash.delete(resource_name) do
raise ArgumentError, "Resource \"#{resource_name}\" is not defined in formula or is already used."
end
end
end
# Convenience wrapper for creating and installing packages into Python
# virtualenvs.
class Virtualenv
# Initializes a Virtualenv instance. This does not create the virtualenv
# on disk; {#create} does that.
#
# @param formula [Formula] the active {Formula}
# @param venv_root [Pathname, String] the path to the root of the
# virtualenv
# @param python [String, Pathname] which interpreter to use, e.g.
# "python" or "python2"
sig { params(formula: Formula, venv_root: T.any(String, Pathname), python: T.any(String, Pathname)).void }
def initialize(formula, venv_root, python)
@formula = formula
@venv_root = T.let(Pathname(venv_root), Pathname)
@python = python
end
sig { returns(Pathname) }
def root
@venv_root
end
sig { returns(Pathname) }
def site_packages
@venv_root/Language::Python.site_packages(@python)
end
# Obtains a copy of the virtualenv library and creates a new virtualenv on disk.
#
# @return [void]
sig { params(system_site_packages: T::Boolean, without_pip: T::Boolean).void }
def create(system_site_packages: true, without_pip: true)
return if (@venv_root/"bin/python").exist?
args = ["-m", "venv"]
args << "--system-site-packages" if system_site_packages
args << "--without-pip" if without_pip
@formula.system @python, *args, @venv_root
# Robustify symlinks to survive python patch upgrades
@venv_root.find do |f|
next unless f.symlink?
next unless f.readlink.expand_path.to_s.start_with? HOMEBREW_CELLAR
rp = f.realpath.to_s
version = rp.match %r{^#{HOMEBREW_CELLAR}/python@(.*?)/}o
version = "@#{version.captures.first}" unless version.nil?
new_target = rp.sub(
%r{#{HOMEBREW_CELLAR}/python#{version}/[^/]+},
Formula["python#{version}"].opt_prefix.to_s,
)
f.unlink
f.make_symlink new_target
end
Pathname.glob(@venv_root/"lib/python*/orig-prefix.txt").each do |prefix_file|
prefix_path = prefix_file.read
version = prefix_path.match %r{^#{HOMEBREW_CELLAR}/python@(.*?)/}o
version = "@#{version.captures.first}" unless version.nil?
prefix_path.sub!(
%r{^#{HOMEBREW_CELLAR}/python#{version}/[^/]+},
Formula["python#{version}"].opt_prefix.to_s,
)
prefix_file.atomic_write prefix_path
end
# Reduce some differences between macOS and Linux venv
lib64 = @venv_root/"lib64"
lib64.make_symlink "lib" unless lib64.exist?
if (cfg_file = @venv_root/"pyvenv.cfg").exist?
cfg = cfg_file.read
framework = "Frameworks/Python.framework/Versions"
cfg.match(%r{= *(#{HOMEBREW_CELLAR}/(python@[\d.]+)/[^/]+(?:/#{framework}/[\d.]+)?/bin)}) do |match|
cfg.sub! match[1].to_s, Formula[T.must(match[2])].opt_bin.to_s
cfg_file.atomic_write cfg
end
end
# Remove unnecessary activate scripts
(@venv_root/"bin").glob("[Aa]ctivate*").map(&:unlink)
end
# Installs packages represented by `targets` into the virtualenv.
#
# @param targets [String, Pathname, Resource,
# Array<String, Pathname, Resource>] (A) token(s) passed to `pip`
# representing the object to be installed. This can be a directory
# containing a setup.py, a {Resource} which will be staged and
# installed, or a package identifier to be fetched from PyPI.
# Multiline strings are allowed and treated as though they represent
# the contents of a `requirements.txt`.
# @return [void]
sig {
params(
targets: T.any(String, Pathname, Resource, T::Array[T.any(String, Pathname, Resource)]),
build_isolation: T::Boolean,
).void
}
def pip_install(targets, build_isolation: true)
targets = Array(targets)
targets.each do |t|
if t.is_a?(Resource)
t.stage do
target = Pathname.pwd
target /= t.downloader.basename if t.url&.match?("[.-]py3[^-]*-none-any.whl$")
do_install(target, build_isolation:)
end
else
t = t.lines.map(&:strip) if t.is_a?(String) && t.include?("\n")
do_install(t, build_isolation:)
end
end
end
# Installs packages represented by `targets` into the virtualenv, but
# unlike {#pip_install} also links new scripts to {Formula#bin}.
#
# @param (see #pip_install)
# @return (see #pip_install)
sig {
params(
targets: T.any(String, Pathname, Resource, T::Array[T.any(String, Pathname, Resource)]),
link_manpages: T::Boolean,
build_isolation: T::Boolean,
).void
}
def pip_install_and_link(targets, link_manpages: true, build_isolation: true)
bin_before = Dir[@venv_root/"bin/*"].to_set
man_before = Dir[@venv_root/"share/man/man*/*"].to_set if link_manpages
pip_install(targets, build_isolation:)
bin_after = Dir[@venv_root/"bin/*"].to_set
bin_to_link = (bin_after - bin_before).to_a
@formula.bin.install_symlink(bin_to_link)
return unless link_manpages
man_after = Dir[@venv_root/"share/man/man*/*"].to_set
man_to_link = (man_after - man_before).to_a
man_to_link.each do |manpage|
(@formula.man/Pathname.new(manpage).dirname.basename).install_symlink manpage
end
end
private
sig {
params(
targets: T.any(String, Pathname, T::Array[T.any(String, Pathname)]),
build_isolation: T::Boolean,
).void
}
def do_install(targets, build_isolation: true)
targets = Array(targets)
args = @formula.std_pip_args(prefix: false, build_isolation:)
@formula.system @python, "-m", "pip", "--python=#{@venv_root}/bin/python", "install", *args, *targets
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/language/node.rb | Library/Homebrew/language/node.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Language
# Helper functions for Node formulae.
#
# @api public
module Node
extend ::Utils::Output::Mixin
sig { returns(String) }
def self.npm_cache_config
"cache=#{HOMEBREW_CACHE}/npm_cache"
end
sig { returns(String) }
def self.pack_for_installation
# Homebrew assumes the buildpath/testpath will always be disposable
# and from npm 5.0.0 the logic changed so that when a directory is
# fed to `npm install` only symlinks are created linking back to that
# directory, consequently breaking that assumption. We require a tarball
# because npm install creates a "real" installation when fed a tarball.
package = Pathname("package.json")
if package.exist?
begin
pkg_json = JSON.parse(package.read)
rescue JSON::ParserError
opoo "Could not parse package.json!"
raise
end
prepare_removed = pkg_json["scripts"]&.delete("prepare")
prepack_removed = pkg_json["scripts"]&.delete("prepack")
postpack_removed = pkg_json["scripts"]&.delete("postpack")
package.atomic_write(JSON.pretty_generate(pkg_json)) if prepare_removed || prepack_removed || postpack_removed
end
output = Utils.popen_read("npm", "pack", "--ignore-scripts")
raise "npm failed to pack #{Dir.pwd}" if !$CHILD_STATUS.exitstatus.zero? || output.lines.empty?
output.lines.last.chomp
end
sig { void }
def self.setup_npm_environment
# guard that this is only run once
return if @env_set
@env_set = T.let(true, T.nilable(T::Boolean))
# explicitly use our npm and node-gyp executables instead of the user
# managed ones in HOMEBREW_PREFIX/lib/node_modules which might be broken
begin
ENV.prepend_path "PATH", Formula["node"].opt_libexec/"bin"
rescue FormulaUnavailableError
nil
end
end
sig { params(libexec: Pathname, ignore_scripts: T::Boolean).returns(T::Array[String]) }
def self.std_npm_install_args(libexec, ignore_scripts: true)
setup_npm_environment
pack = pack_for_installation
# npm 7 requires that these dirs exist before install
(libexec/"lib").mkpath
# npm install args for global style module format installed into libexec
args = %W[
--loglevel=silly
--global
--build-from-source
--#{npm_cache_config}
--prefix=#{libexec}
#{Dir.pwd}/#{pack}
]
args << "--ignore-scripts" if ignore_scripts
args << "--unsafe-perm" if Process.uid.zero?
args
end
sig { params(ignore_scripts: T::Boolean).returns(T::Array[String]) }
def self.local_npm_install_args(ignore_scripts: true)
setup_npm_environment
# npm install args for local style module format
args = %W[
--loglevel=silly
--build-from-source
--#{npm_cache_config}
]
args << "--ignore-scripts" if ignore_scripts
args
end
# Mixin module for {Formula} adding shebang rewrite features.
module Shebang
extend T::Helpers
requires_ancestor { Formula }
module_function
# A regex to match potential shebang permutations.
NODE_SHEBANG_REGEX = %r{\A#! ?(?:/usr/bin/(?:env )?)?node( |$)}
# The length of the longest shebang matching `SHEBANG_REGEX`.
NODE_SHEBANG_MAX_LENGTH = T.let("#! /usr/bin/env node ".length, Integer)
# @private
sig { params(node_path: T.any(String, Pathname)).returns(Utils::Shebang::RewriteInfo) }
def node_shebang_rewrite_info(node_path)
Utils::Shebang::RewriteInfo.new(
NODE_SHEBANG_REGEX,
NODE_SHEBANG_MAX_LENGTH,
"#{node_path}\\1",
)
end
sig { params(formula: Formula).returns(Utils::Shebang::RewriteInfo) }
def detected_node_shebang(formula = T.cast(self, Formula))
node_deps = formula.deps.select(&:required?).map(&:name).grep(/^node(@.+)?$/)
raise ShebangDetectionError.new("Node", "formula does not depend on Node") if node_deps.empty?
raise ShebangDetectionError.new("Node", "formula has multiple Node dependencies") if node_deps.length > 1
node_shebang_rewrite_info(Formula[node_deps.first].opt_bin/"node")
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/language/php.rb | Library/Homebrew/language/php.rb | # typed: strict
# frozen_string_literal: true
module Language
# Helper functions for PHP formulae.
#
# @api public
module PHP
# Helper module for replacing `php` shebangs.
module Shebang
extend T::Helpers
requires_ancestor { Formula }
module_function
# A regex to match potential shebang permutations.
PHP_SHEBANG_REGEX = %r{\A#! ?(?:/usr/bin/(?:env )?)?php( |$)}
# The length of the longest shebang matching `SHEBANG_REGEX`.
PHP_SHEBANG_MAX_LENGTH = T.let("#! /usr/bin/env php ".length, Integer)
# @private
sig { params(php_path: T.any(String, Pathname)).returns(Utils::Shebang::RewriteInfo) }
def php_shebang_rewrite_info(php_path)
Utils::Shebang::RewriteInfo.new(
PHP_SHEBANG_REGEX,
PHP_SHEBANG_MAX_LENGTH,
"#{php_path}\\1",
)
end
sig { params(formula: Formula).returns(Utils::Shebang::RewriteInfo) }
def detected_php_shebang(formula = T.cast(self, Formula))
php_deps = formula.deps.select(&:required?).map(&:name).grep(/^php(@.+)?$/)
raise ShebangDetectionError.new("PHP", "formula does not depend on PHP") if php_deps.empty?
raise ShebangDetectionError.new("PHP", "formula has multiple PHP dependencies") if php_deps.length > 1
php_shebang_rewrite_info(Formula[php_deps.first].opt_bin/"php")
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/language/java.rb | Library/Homebrew/language/java.rb | # typed: strict
# frozen_string_literal: true
module Language
# Helper functions for Java formulae.
#
# @api public
module Java
sig { params(version: T.nilable(String)).returns(T.nilable(Formula)) }
def self.find_openjdk_formula(version = nil)
can_be_newer = version&.end_with?("+")
version = version.to_i
openjdk = Formula["openjdk"]
[openjdk, *openjdk.versioned_formulae].find do |f|
next false unless f.any_version_installed?
unless version.zero?
major = T.must(f.any_installed_version).major
next false if major < version
next false if major > version && !can_be_newer
end
true
end
rescue FormulaUnavailableError
nil
end
private_class_method :find_openjdk_formula
# Returns the directory of the newest matching OpenJDK installation or
# `nil` if none is available. When used in a {Formula}, there should be
# a dependency and corresponding `version` for reproducible output.
#
# @api public
# @param version OpenJDK version constraint which can be specific
# (e.g. `"21"`) or a lower-bounded range (e.g. `"21+"`)
sig { params(version: T.nilable(String)).returns(T.nilable(Pathname)) }
def self.java_home(version = nil)
find_openjdk_formula(version)&.opt_libexec
end
sig { params(version: T.nilable(String)).returns(String) }
def self.java_home_shell(version = nil)
java_home(version).to_s
end
private_class_method :java_home_shell
# Returns a `JAVA_HOME` environment variable to use a specific OpenJDK.
# Usually combined with either {Pathname#write_env_script} or
# {Pathname#env_script_all_files}.
#
# ### Example
#
# Use `openjdk@21` for all commands:
#
# ```ruby
# bin.env_script_all_files libexec/"bin", Language::Java.java_home_env("21")
# ```
#
# @api public
sig { params(version: T.nilable(String)).returns({ JAVA_HOME: String }) }
def self.java_home_env(version = nil)
{ JAVA_HOME: java_home_shell(version) }
end
# Returns a `JAVA_HOME` environment variable to use a default OpenJDK.
# Unlike {.java_home_env} the OpenJDK can be overridden at runtime.
#
# ### Example
#
# Use latest `openjdk` as default:
#
# ```ruby
# bin.env_script_all_files libexec/"bin", Language::Java.overridable_java_home_env
# ```
#
# @api public
sig { params(version: T.nilable(String)).returns({ JAVA_HOME: String }) }
def self.overridable_java_home_env(version = nil)
{ JAVA_HOME: "${JAVA_HOME:-#{java_home_shell(version)}}" }
end
end
end
require "extend/os/language/java"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/startup/ruby_path.rb | Library/Homebrew/startup/ruby_path.rb | # typed: true
# frozen_string_literal: true
RUBY_PATH = Pathname.new(RbConfig.ruby).freeze
RUBY_BIN = RUBY_PATH.dirname.freeze
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/startup/bootsnap.rb | Library/Homebrew/startup/bootsnap.rb | # typed: true
# frozen_string_literal: true
module Homebrew
module Bootsnap
def self.key
@key ||= begin
require "digest/sha2"
checksum = Digest::SHA256.new
checksum << RUBY_VERSION
checksum << RUBY_PLATFORM
checksum << Dir.children(File.join(Gem.paths.path, "gems")).join(",")
checksum.hexdigest
end
end
private_class_method def self.cache_dir
cache = ENV.fetch("HOMEBREW_CACHE", nil) || ENV.fetch("HOMEBREW_DEFAULT_CACHE", nil)
raise "Needs `$HOMEBREW_CACHE` or `$HOMEBREW_DEFAULT_CACHE`!" if cache.nil? || cache.empty?
File.join(cache, "bootsnap", key)
end
private_class_method def self.ignore_directories
# We never do `require "vendor/bundle/ruby/..."` or `require "vendor/portable-ruby/..."`,
# so let's slim the cache a bit by excluding them.
# Note that gems within `bundle/ruby` will still be cached - these are when directory walking down from above.
[
(HOMEBREW_LIBRARY_PATH/"vendor/bundle/ruby").to_s,
(HOMEBREW_LIBRARY_PATH/"vendor/portable-ruby").to_s,
]
end
private_class_method def self.enabled?
!ENV["HOMEBREW_BOOTSNAP_GEM_PATH"].to_s.empty? && ENV["HOMEBREW_NO_BOOTSNAP"].nil?
end
def self.load!(compile_cache: true)
return unless enabled?
require ENV.fetch("HOMEBREW_BOOTSNAP_GEM_PATH")
::Bootsnap.setup(
cache_dir:,
ignore_directories:,
# In development environments the bootsnap compilation cache is
# generated on the fly when source files are loaded.
# https://github.com/Shopify/bootsnap?tab=readme-ov-file#precompilation
development_mode: true,
load_path_cache: true,
compile_cache_iseq: compile_cache,
compile_cache_yaml: compile_cache,
)
end
def self.reset!
return unless enabled?
::Bootsnap.unload_cache!
@key = nil
# The compile cache doesn't get unloaded so we don't need to load it again!
load!(compile_cache: false)
end
end
end
Homebrew::Bootsnap.load!
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/startup/config.rb | Library/Homebrew/startup/config.rb | # typed: true
# frozen_string_literal: true
raise "HOMEBREW_BREW_FILE was not exported! Please call bin/brew directly!" unless ENV["HOMEBREW_BREW_FILE"]
# The path to the executable that should be used to run `brew`.
# This may be HOMEBREW_ORIGINAL_BREW_FILE depending on the system configuration.
# Favour this instead of running `brew` and expecting it to be in the `PATH`.
# @api public
HOMEBREW_BREW_FILE = Pathname(ENV.fetch("HOMEBREW_BREW_FILE")).freeze
# Where Homebrew is installed and files are linked to.
# @api public
HOMEBREW_PREFIX = Pathname(ENV.fetch("HOMEBREW_PREFIX")).freeze
# Where Homebrew stores built formulae packages, linking (non-keg-only) ones
# back to `HOMEBREW_PREFIX`.
# @api public
HOMEBREW_CELLAR = Pathname(ENV.fetch("HOMEBREW_CELLAR")).freeze
# Where Homebrew downloads (bottles, source tarballs, casks etc.) are cached.
# @api public
HOMEBREW_CACHE = Pathname(ENV.fetch("HOMEBREW_CACHE")).freeze
# Where Homebrew stores temporary files.
# We use `/tmp` instead of `TMPDIR` because long paths break Unix domain
# sockets.
# @api public
HOMEBREW_TEMP = Pathname(ENV.fetch("HOMEBREW_TEMP")).then do |tmp|
tmp.mkpath unless tmp.exist?
tmp.realpath
end.freeze
# Path to `bin/brew` main executable in `HOMEBREW_PREFIX`
# Used for e.g. permissions checks.
HOMEBREW_ORIGINAL_BREW_FILE = Pathname(ENV.fetch("HOMEBREW_ORIGINAL_BREW_FILE")).freeze
# Where `.git` is found
HOMEBREW_REPOSITORY = Pathname(ENV.fetch("HOMEBREW_REPOSITORY")).freeze
# Where we store most of Homebrew, taps and various metadata
HOMEBREW_LIBRARY = Pathname(ENV.fetch("HOMEBREW_LIBRARY")).freeze
# Where shim scripts for various build and SCM tools are stored
HOMEBREW_SHIMS_PATH = (HOMEBREW_LIBRARY/"Homebrew/shims").freeze
# Where external data that has been incorporated into Homebrew is stored
HOMEBREW_DATA_PATH = (HOMEBREW_LIBRARY/"Homebrew/data").freeze
# Where we store symlinks to currently linked kegs
HOMEBREW_LINKED_KEGS = (HOMEBREW_PREFIX/"var/homebrew/linked").freeze
# Where we store symlinks to currently version-pinned kegs
HOMEBREW_PINNED_KEGS = (HOMEBREW_PREFIX/"var/homebrew/pinned").freeze
# Where we store lock files
HOMEBREW_LOCKS = (HOMEBREW_PREFIX/"var/homebrew/locks").freeze
# Where we store temporary cellar files that must be in the prefix
HOMEBREW_TEMP_CELLAR = (HOMEBREW_PREFIX/"var/homebrew/tmp/.cellar").freeze
# Where we store Casks
HOMEBREW_CASKROOM = Pathname(ENV.fetch("HOMEBREW_CASKROOM")).freeze
# Where formulae installed via URL are cached
HOMEBREW_CACHE_FORMULA = (HOMEBREW_CACHE/"Formula").freeze
# Where build, postinstall and test logs of formulae are written to
HOMEBREW_LOGS = Pathname(ENV.fetch("HOMEBREW_LOGS")).expand_path.freeze
# Where installed taps live
HOMEBREW_TAP_DIRECTORY = (HOMEBREW_LIBRARY/"Taps").freeze
# The Ruby path and args to use for forked Ruby calls
HOMEBREW_RUBY_EXEC_ARGS = [
RUBY_PATH,
ENV.fetch("HOMEBREW_RUBY_WARNINGS"),
ENV.fetch("HOMEBREW_RUBY_DISABLE_OPTIONS"),
].freeze
# Location for `brew alias` and `brew unalias` commands.
#
# Unix-Like systems store config in $HOME/.config whose location can be
# overridden by the XDG_CONFIG_HOME environment variable. Unfortunately
# Homebrew strictly filters environment variables in BuildEnvironment.
HOMEBREW_ALIASES = if (path = Pathname.new("~/.config/brew-aliases").expand_path).exist? ||
(path = Pathname.new("~/.brew-aliases").expand_path).exist?
path.realpath
else
path
end.freeze
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/compiler_test.rb | test/compiler_test.rb | require "test_helper"
class CompilerTest < Minitest::Test
def remove_compilation_digest_path
Webpacker.compiler.send(:compilation_digest_path).tap do |path|
path.delete if path.exist?
end
end
def setup
remove_compilation_digest_path
end
def teardown
remove_compilation_digest_path
end
def test_custom_environment_variables
assert_nil Webpacker.compiler.send(:webpack_env)["FOO"]
Webpacker.compiler.env["FOO"] = "BAR"
assert Webpacker.compiler.send(:webpack_env)["FOO"] == "BAR"
ensure
Webpacker.compiler.env = {}
end
def test_freshness
assert Webpacker.compiler.stale?
assert !Webpacker.compiler.fresh?
end
def test_compile
assert !Webpacker.compiler.compile
end
def test_freshness_on_compile_success
status = OpenStruct.new(success?: true)
assert Webpacker.compiler.stale?
Open3.stub :capture3, [:sterr, :stdout, status] do
Webpacker.compiler.compile
assert Webpacker.compiler.fresh?
end
end
def test_freshness_on_compile_fail
status = OpenStruct.new(success?: false)
assert Webpacker.compiler.stale?
Open3.stub :capture3, [:sterr, :stdout, status] do
Webpacker.compiler.compile
assert Webpacker.compiler.fresh?
end
end
def test_compilation_digest_path
assert_equal Webpacker.compiler.send(:compilation_digest_path).basename.to_s, "last-compilation-digest-#{Webpacker.env}"
end
def test_external_env_variables
assert_nil Webpacker.compiler.send(:webpack_env)["WEBPACKER_ASSET_HOST"]
assert_nil Webpacker.compiler.send(:webpack_env)["WEBPACKER_RELATIVE_URL_ROOT"]
ENV["WEBPACKER_ASSET_HOST"] = "foo.bar"
ENV["WEBPACKER_RELATIVE_URL_ROOT"] = "/baz"
assert_equal Webpacker.compiler.send(:webpack_env)["WEBPACKER_ASSET_HOST"], "foo.bar"
assert_equal Webpacker.compiler.send(:webpack_env)["WEBPACKER_RELATIVE_URL_ROOT"], "/baz"
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/engine_rake_tasks_test.rb | test/engine_rake_tasks_test.rb | require "test_helper"
class EngineRakeTasksTest < Minitest::Test
def setup
remove_webpack_binstubs
end
def teardown
remove_webpack_binstubs
end
def test_task_mounted
output = Dir.chdir(mounted_app_path) { `rake -T` }
assert_includes output, "app:webpacker"
end
def test_binstubs
Dir.chdir(mounted_app_path) { `bundle exec rake app:webpacker:binstubs` }
webpack_binstub_paths.each { |path| assert File.exist?(path) }
end
private
def mounted_app_path
File.expand_path("mounted_app", __dir__)
end
def webpack_binstub_paths
[
"#{mounted_app_path}/test/dummy/bin/webpacker",
"#{mounted_app_path}/test/dummy/bin/webpacker-dev-server",
]
end
def remove_webpack_binstubs
webpack_binstub_paths.each do |path|
File.delete(path) if File.exist?(path)
end
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/command_test.rb | test/command_test.rb | require "test_helper"
class CommandTest < Minitest::Test
def test_compile_command_returns_success_status_when_stale
Webpacker.compiler.stub :stale?, true do
Webpacker.compiler.stub :run_webpack, true do
assert_equal true, Webpacker.commands.compile
end
end
end
def test_compile_command_returns_success_status_when_fresh
Webpacker.compiler.stub :stale?, false do
Webpacker.compiler.stub :run_webpack, true do
assert_equal true, Webpacker.commands.compile
end
end
end
def test_compile_command_returns_failure_status_when_stale
Webpacker.compiler.stub :stale?, true do
Webpacker.compiler.stub :run_webpack, false do
assert_equal false, Webpacker.commands.compile
end
end
end
def test_clean_command_works_with_nested_hashes_and_without_any_compiled_files
File.stub :delete, true do
assert Webpacker.commands.clean
end
end
end
class ClearCommandVersioningTest < Minitest::Test
def setup
@now = Time.parse("2021-01-01 12:34:56 UTC")
# Test assets to be kept and deleted, path and mtime
@prev_files = {
# recent versions to be kept with Webpacker.commands.clean(count = 2)
"js/application-deadbeef.js" => @now - 4000,
"js/common-deadbeee.js" => @now - 4002,
"css/common-deadbeed.css" => @now - 4004,
"media/images/logo-deadbeeb.css" => @now - 4006,
"js/application-1eadbeef.js" => @now - 8000,
"js/common-1eadbeee.js" => @now - 8002,
"css/common-1eadbeed.css" => @now - 8004,
"media/images/logo-1eadbeeb.css" => @now - 8006,
# new files to be kept with Webpacker.commands.clean(age = 3600)
"js/brandnew-0001.js" => @now,
"js/brandnew-0002.js" => @now - 10,
"js/brandnew-0003.js" => @now - 20,
"js/brandnew-0004.js" => @now - 40,
}.transform_keys { |path| "#{Webpacker.config.public_output_path}/#{path}" }
@expired_files = {
# old files that are outside count = 2 or age = 3600 and to be deleted
"js/application-0eadbeef.js" => @now - 9000,
"js/common-0eadbeee.js" => @now - 9002,
"css/common-0eadbeed.css" => @now - 9004,
"js/brandnew-0005.js" => @now - 3640,
}.transform_keys { |path| "#{Webpacker.config.public_output_path}/#{path}" }
@all_files = @prev_files.merge(@expired_files)
@dir_glob_stub = Proc.new { |arg|
case arg
when "#{Webpacker.config.public_output_path}/**/*"
@all_files.keys
else
[]
end
}
@file_mtime_stub = Proc.new { |longpath|
@all_files[longpath]
}
@file_delete_mock = Minitest::Mock.new
@expired_files.keys.each do |longpath|
@file_delete_mock.expect(:delete, 1, [longpath])
end
@file_delete_stub = Proc.new { |longpath|
if @prev_files.has_key?(longpath)
flunk "#{longpath} should not be deleted"
else
@file_delete_mock.delete(longpath)
end
}
end
def time_and_files_stub(&proc)
Time.stub :now, @now do
Dir.stub :glob, @dir_glob_stub do
File.stub :directory?, false do
File.stub :file?, true do
File.stub :mtime, @file_mtime_stub do
File.stub :delete, @file_delete_stub do
yield proc
end
end
end
end
end
end
@file_delete_mock.verify
end
def test_clean_command_with_versioned_files
time_and_files_stub do
assert Webpacker.commands.clean
end
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/rake_tasks_test.rb | test/rake_tasks_test.rb | require "test_helper"
class RakeTasksTest < Minitest::Test
def test_rake_tasks
output = Dir.chdir(test_app_path) { `rake -T` }
assert_includes output, "webpacker"
assert_includes output, "webpacker:check_binstubs"
assert_includes output, "webpacker:check_node"
assert_includes output, "webpacker:check_yarn"
assert_includes output, "webpacker:clean"
assert_includes output, "webpacker:clobber"
assert_includes output, "webpacker:compile"
assert_includes output, "webpacker:install"
assert_includes output, "webpacker:verify_install"
end
def test_rake_task_webpacker_check_binstubs
output = Dir.chdir(test_app_path) { `rake webpacker:check_binstubs 2>&1` }
refute_includes output, "webpack binstub not found."
end
def test_check_node_version
output = Dir.chdir(test_app_path) { `rake webpacker:check_node 2>&1` }
refute_includes output, "Webpacker requires Node.js"
end
def test_check_yarn_version
output = Dir.chdir(test_app_path) { `rake webpacker:check_yarn 2>&1` }
refute_includes output, "Yarn not installed"
refute_includes output, "Webpacker requires Yarn"
end
def test_rake_webpacker_yarn_install_in_non_production_environments
assert_includes test_app_dev_dependencies, "right-pad"
Webpacker.with_node_env("test") do
Dir.chdir(test_app_path) do
`bundle exec rake webpacker:yarn_install`
end
end
assert_includes installed_node_module_names, "right-pad",
"Expected dev dependencies to be installed"
end
def test_rake_webpacker_yarn_install_in_production_environment
Webpacker.with_node_env("production") do
Dir.chdir(test_app_path) do
`bundle exec rake webpacker:yarn_install`
end
end
refute_includes installed_node_module_names, "right-pad",
"Expected only production dependencies to be installed"
end
private
def test_app_path
File.expand_path("test_app", __dir__)
end
def test_app_dev_dependencies
package_json = File.expand_path("package.json", test_app_path)
JSON.parse(File.read(package_json))["devDependencies"]
end
def installed_node_module_names
node_modules_path = File.expand_path("node_modules", test_app_path)
Dir.chdir(node_modules_path) { Dir.glob("*") }
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/dev_server_test.rb | test/dev_server_test.rb | require "test_helper"
class DevServerTest < Webpacker::Test
def test_running?
refute Webpacker.dev_server.running?
end
def test_host
with_rails_env("development") do
assert_equal Webpacker.dev_server.host, "localhost"
end
end
def test_port
with_rails_env("development") do
assert_equal Webpacker.dev_server.port, 3035
end
end
def test_https?
with_rails_env("development") do
assert_equal Webpacker.dev_server.https?, false
end
end
def test_protocol
with_rails_env("development") do
assert_equal Webpacker.dev_server.protocol, "http"
end
end
def test_host_with_port
with_rails_env("development") do
assert_equal Webpacker.dev_server.host_with_port, "localhost:3035"
end
end
def test_pretty?
with_rails_env("development") do
refute Webpacker.dev_server.pretty?
end
end
def test_default_env_prefix
assert_equal Webpacker::DevServer::DEFAULT_ENV_PREFIX, "WEBPACKER_DEV_SERVER"
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/test_helper.rb | test/test_helper.rb | # frozen_string_literal: true
require "minitest/autorun"
require "rails"
require "rails/test_help"
require "byebug"
require_relative "test_app/config/environment"
Rails.env = "production"
Webpacker.instance = ::Webpacker::Instance.new
class Webpacker::Test < Minitest::Test
private
def reloaded_config
Webpacker.instance.instance_variable_set(:@env, nil)
Webpacker.instance.instance_variable_set(:@config, nil)
Webpacker.instance.instance_variable_set(:@dev_server, nil)
Webpacker.env
Webpacker.config
Webpacker.dev_server
end
def with_rails_env(env)
original = Rails.env
Rails.env = ActiveSupport::StringInquirer.new(env)
reloaded_config
yield
ensure
Rails.env = ActiveSupport::StringInquirer.new(original)
reloaded_config
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/helper_test.rb | test/helper_test.rb | require "test_helper"
class HelperTest < ActionView::TestCase
tests Webpacker::Helper
attr_reader :request
def setup
@request = Class.new do
def send_early_hints(links) end
def base_url
"https://example.com"
end
end.new
end
def test_asset_pack_path
assert_equal "/packs/bootstrap-300631c4f0e0f9c865bc.js", asset_pack_path("bootstrap.js")
assert_equal "/packs/bootstrap-c38deda30895059837cf.css", asset_pack_path("bootstrap.css")
end
def test_asset_pack_url
assert_equal "https://example.com/packs/bootstrap-300631c4f0e0f9c865bc.js", asset_pack_url("bootstrap.js")
assert_equal "https://example.com/packs/bootstrap-c38deda30895059837cf.css", asset_pack_url("bootstrap.css")
end
def test_image_pack_path
assert_equal "/packs/application-k344a6d59eef8632c9d1.png", image_pack_path("application.png")
assert_equal "/packs/static/image-c38deda30895059837cf.jpg", image_pack_path("image.jpg")
assert_equal "/packs/static/image-c38deda30895059837cf.jpg", image_pack_path("static/image.jpg")
assert_equal "/packs/static/nested/image-c38deda30895059837cf.jpg", image_pack_path("nested/image.jpg")
assert_equal "/packs/static/nested/image-c38deda30895059837cf.jpg", image_pack_path("static/nested/image.jpg")
end
def test_image_pack_url
assert_equal "https://example.com/packs/application-k344a6d59eef8632c9d1.png", image_pack_url("application.png")
assert_equal "https://example.com/packs/static/image-c38deda30895059837cf.jpg", image_pack_url("image.jpg")
assert_equal "https://example.com/packs/static/image-c38deda30895059837cf.jpg", image_pack_url("static/image.jpg")
assert_equal "https://example.com/packs/static/nested/image-c38deda30895059837cf.jpg", image_pack_url("nested/image.jpg")
assert_equal "https://example.com/packs/static/nested/image-c38deda30895059837cf.jpg", image_pack_url("static/nested/image.jpg")
end
def test_image_pack_tag
assert_equal \
"<img alt=\"Edit Entry\" src=\"/packs/application-k344a6d59eef8632c9d1.png\" width=\"16\" height=\"10\" />",
image_pack_tag("application.png", size: "16x10", alt: "Edit Entry")
assert_equal \
"<img alt=\"Edit Entry\" src=\"/packs/static/image-c38deda30895059837cf.jpg\" width=\"16\" height=\"10\" />",
image_pack_tag("image.jpg", size: "16x10", alt: "Edit Entry")
assert_equal \
"<img alt=\"Edit Entry\" src=\"/packs/static/image-c38deda30895059837cf.jpg\" width=\"16\" height=\"10\" />",
image_pack_tag("static/image.jpg", size: "16x10", alt: "Edit Entry")
assert_equal \
"<img alt=\"Edit Entry\" src=\"/packs/static/nested/image-c38deda30895059837cf.jpg\" width=\"16\" height=\"10\" />",
image_pack_tag("nested/image.jpg", size: "16x10", alt: "Edit Entry")
assert_equal \
"<img alt=\"Edit Entry\" src=\"/packs/static/nested/image-c38deda30895059837cf.jpg\" width=\"16\" height=\"10\" />",
image_pack_tag("static/nested/image.jpg", size: "16x10", alt: "Edit Entry")
assert_equal \
"<img srcset=\"/packs/static/image-2x-7cca48e6cae66ec07b8e.jpg 2x\" src=\"/packs/static/image-c38deda30895059837cf.jpg\" />",
image_pack_tag("static/image.jpg", srcset: { "static/image-2x.jpg" => "2x" })
end
def test_favicon_pack_tag
assert_equal \
"<link rel=\"apple-touch-icon\" type=\"image/png\" href=\"/packs/application-k344a6d59eef8632c9d1.png\" />",
favicon_pack_tag("application.png", rel: "apple-touch-icon", type: "image/png")
assert_equal \
"<link rel=\"apple-touch-icon\" type=\"image/png\" href=\"/packs/static/mb-icon-c38deda30895059837cf.png\" />",
favicon_pack_tag("mb-icon.png", rel: "apple-touch-icon", type: "image/png")
assert_equal \
"<link rel=\"apple-touch-icon\" type=\"image/png\" href=\"/packs/static/mb-icon-c38deda30895059837cf.png\" />",
favicon_pack_tag("static/mb-icon.png", rel: "apple-touch-icon", type: "image/png")
assert_equal \
"<link rel=\"apple-touch-icon\" type=\"image/png\" href=\"/packs/static/nested/mb-icon-c38deda30895059837cf.png\" />",
favicon_pack_tag("nested/mb-icon.png", rel: "apple-touch-icon", type: "image/png")
assert_equal \
"<link rel=\"apple-touch-icon\" type=\"image/png\" href=\"/packs/static/nested/mb-icon-c38deda30895059837cf.png\" />",
favicon_pack_tag("static/nested/mb-icon.png", rel: "apple-touch-icon", type: "image/png")
end
def test_preload_pack_asset
if self.class.method_defined?(:preload_link_tag)
assert_equal \
%(<link rel="preload" href="/packs/fonts/fa-regular-400-944fb546bd7018b07190a32244f67dc9.woff2" as="font" type="font/woff2" crossorigin="anonymous">),
preload_pack_asset("fonts/fa-regular-400.woff2")
else
error = assert_raises do
preload_pack_asset("fonts/fa-regular-400.woff2")
end
assert_equal \
"You need Rails >= 5.2 to use this tag.",
error.message
end
end
def test_javascript_pack_tag
assert_equal \
%(<script src="/packs/vendors~application~bootstrap-c20632e7baf2c81200d3.chunk.js" defer="defer"></script>\n) +
%(<script src="/packs/vendors~application-e55f2aae30c07fb6d82a.chunk.js" defer="defer"></script>\n) +
%(<script src="/packs/application-k344a6d59eef8632c9d1.js" defer="defer"></script>\n) +
%(<script src="/packs/bootstrap-300631c4f0e0f9c865bc.js" defer="defer"></script>),
javascript_pack_tag("application", "bootstrap")
end
def test_javascript_pack_with_no_defer_tag
assert_equal \
%(<script src="/packs/vendors~application~bootstrap-c20632e7baf2c81200d3.chunk.js"></script>\n) +
%(<script src="/packs/vendors~application-e55f2aae30c07fb6d82a.chunk.js"></script>\n) +
%(<script src="/packs/application-k344a6d59eef8632c9d1.js"></script>\n) +
%(<script src="/packs/bootstrap-300631c4f0e0f9c865bc.js"></script>),
javascript_pack_tag("application", "bootstrap", defer: false)
end
def test_javascript_pack_tag_splat
assert_equal \
%(<script src="/packs/vendors~application~bootstrap-c20632e7baf2c81200d3.chunk.js" defer="defer"></script>\n) +
%(<script src="/packs/vendors~application-e55f2aae30c07fb6d82a.chunk.js" defer="defer"></script>\n) +
%(<script src="/packs/application-k344a6d59eef8632c9d1.js" defer="defer"></script>),
javascript_pack_tag("application", defer: true)
end
def test_javascript_pack_tag_symbol
assert_equal \
%(<script src="/packs/vendors~application~bootstrap-c20632e7baf2c81200d3.chunk.js" defer="defer"></script>\n) +
%(<script src="/packs/vendors~application-e55f2aae30c07fb6d82a.chunk.js" defer="defer"></script>\n) +
%(<script src="/packs/application-k344a6d59eef8632c9d1.js" defer="defer"></script>),
javascript_pack_tag(:application)
end
def application_stylesheet_chunks
%w[/packs/1-c20632e7baf2c81200d3.chunk.css /packs/application-k344a6d59eef8632c9d1.chunk.css]
end
def hello_stimulus_stylesheet_chunks
%w[/packs/hello_stimulus-k344a6d59eef8632c9d1.chunk.css]
end
def test_stylesheet_pack_tag
assert_equal \
(application_stylesheet_chunks + hello_stimulus_stylesheet_chunks)
.map { |chunk| stylesheet_link_tag(chunk) }.join("\n"),
stylesheet_pack_tag("application", "hello_stimulus")
end
def test_stylesheet_pack_tag_symbol
assert_equal \
(application_stylesheet_chunks + hello_stimulus_stylesheet_chunks)
.map { |chunk| stylesheet_link_tag(chunk) }.join("\n"),
stylesheet_pack_tag(:application, :hello_stimulus)
end
def test_stylesheet_pack_tag_splat
assert_equal \
(application_stylesheet_chunks).map { |chunk| stylesheet_link_tag(chunk, media: "all") }.join("\n"),
stylesheet_pack_tag("application", media: "all")
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/dev_server_runner_test.rb | test/dev_server_runner_test.rb | require "test_helper"
require "webpacker/dev_server_runner"
class DevServerRunnerTest < Webpacker::Test
def setup
@original_node_env, ENV["NODE_ENV"] = ENV["NODE_ENV"], "development"
@original_rails_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "development"
@original_webpacker_config = ENV["WEBPACKER_CONFIG"]
end
def teardown
ENV["NODE_ENV"] = @original_node_env
ENV["RAILS_ENV"] = @original_rails_env
ENV["WEBPACKER_CONFIG"] = @original_webpacker_config
end
def test_run_cmd_via_node_modules
cmd = ["#{test_app_path}/node_modules/.bin/webpack", "serve", "--config", "#{test_app_path}/config/webpack/development.js"]
verify_command(cmd, use_node_modules: true)
end
def test_run_cmd_via_yarn
cmd = ["yarn", "webpack", "serve", "--config", "#{test_app_path}/config/webpack/development.js"]
verify_command(cmd, use_node_modules: false)
end
def test_run_cmd_argv
cmd = ["#{test_app_path}/node_modules/.bin/webpack", "serve", "--config", "#{test_app_path}/config/webpack/development.js", "--quiet"]
verify_command(cmd, argv: ["--quiet"])
end
def test_run_cmd_argv_with_https
cmd = ["#{test_app_path}/node_modules/.bin/webpack", "serve", "--config", "#{test_app_path}/config/webpack/development.js", "--https"]
dev_server = Webpacker::DevServer.new({})
def dev_server.host; "localhost"; end
def dev_server.port; "3035"; end
def dev_server.pretty?; false; end
def dev_server.https?; true; end
def dev_server.hmr?; false; end
Webpacker::DevServer.stub(:new, dev_server) do
verify_command(cmd, argv: ["--https"])
end
end
def test_environment_variables
cmd = ["#{test_app_path}/node_modules/.bin/webpack", "serve", "--config", "#{test_app_path}/config/webpack/development.js"]
env = Webpacker::Compiler.env.dup
ENV["WEBPACKER_CONFIG"] = env["WEBPACKER_CONFIG"] = "#{test_app_path}/config/webpacker_other_location.yml"
env["WEBPACK_SERVE"] = "true"
verify_command(cmd, env: env)
end
private
def test_app_path
File.expand_path("test_app", __dir__)
end
def verify_command(cmd, use_node_modules: true, argv: [], env: Webpacker::Compiler.env)
cwd = Dir.pwd
Dir.chdir(test_app_path)
klass = Webpacker::DevServerRunner
instance = klass.new(argv)
mock = Minitest::Mock.new
mock.expect(:call, nil, [env, *cmd])
klass.stub(:new, instance) do
instance.stub(:node_modules_bin_exist?, use_node_modules) do
Kernel.stub(:exec, mock) { klass.run(argv) }
end
end
mock.verify
ensure
Dir.chdir(cwd)
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/manifest_test.rb | test/manifest_test.rb | require "test_helper"
class ManifestTest < Minitest::Test
def test_lookup_exception!
asset_file = "calendar.js"
error = assert_raises_manifest_missing_entry_error do
Webpacker.manifest.lookup!(asset_file)
end
assert_match "Webpacker can't find #{asset_file} in #{manifest_path}", error.message
end
def test_lookup_with_type_exception!
asset_file = "calendar"
error = assert_raises_manifest_missing_entry_error do
Webpacker.manifest.lookup!(asset_file, type: :javascript)
end
assert_match "Webpacker can't find #{asset_file}.js in #{manifest_path}", error.message
end
def test_lookup_success!
assert_equal Webpacker.manifest.lookup!("bootstrap.js"), "/packs/bootstrap-300631c4f0e0f9c865bc.js"
end
def test_lookup_with_chunks_without_extension_success!
assert_equal ["/packs/bootstrap-300631c4f0e0f9c865bc.js"], Webpacker.manifest.lookup_pack_with_chunks!("bootstrap", type: :javascript)
end
def test_lookup_with_chunks_with_extension_success!
assert_equal ["/packs/bootstrap-300631c4f0e0f9c865bc.js"], Webpacker.manifest.lookup_pack_with_chunks!("bootstrap.js", type: :javascript)
end
def test_lookup_with_chunks_without_extension_subdir_success!
assert_equal ["/packs/print/application-983b6c164a47f7ed49cd.css"], Webpacker.manifest.lookup_pack_with_chunks!("print/application", type: :css)
end
def test_lookup_with_chunks_with_extension_subdir_success!
assert_equal ["/packs/print/application-983b6c164a47f7ed49cd.css"], Webpacker.manifest.lookup_pack_with_chunks!("print/application.css", type: :css)
end
def test_lookup_nil
assert_nil Webpacker.manifest.lookup("foo.js")
end
def test_lookup_chunks_nil
assert_nil Webpacker.manifest.lookup_pack_with_chunks("foo.js")
end
def test_lookup_success
assert_equal Webpacker.manifest.lookup("bootstrap.js"), "/packs/bootstrap-300631c4f0e0f9c865bc.js"
end
def test_lookup_entrypoint_exception!
asset_file = "calendar"
error = assert_raises_manifest_missing_entry_error do
Webpacker.manifest.lookup_pack_with_chunks!(asset_file, type: :javascript)
end
assert_match "Webpacker can't find #{asset_file}.js in #{manifest_path}", error.message
end
def test_lookup_entrypoint
application_entrypoints = [
"/packs/vendors~application~bootstrap-c20632e7baf2c81200d3.chunk.js",
"/packs/vendors~application-e55f2aae30c07fb6d82a.chunk.js",
"/packs/application-k344a6d59eef8632c9d1.js"
]
assert_equal Webpacker.manifest.lookup_pack_with_chunks!("application", type: :javascript), application_entrypoints
end
private
def assert_raises_manifest_missing_entry_error(&block)
error = nil
Webpacker.config.stub :compile?, false do
error = assert_raises Webpacker::Manifest::MissingEntryError, &block
end
error
end
def manifest_path
File.expand_path File.join(File.dirname(__FILE__), "test_app/public/packs", "manifest.json").to_s
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/configuration_test.rb | test/configuration_test.rb | require "test_helper"
class ConfigurationTest < Webpacker::Test
def setup
@config = Webpacker::Configuration.new(
root_path: Pathname.new(File.expand_path("test_app", __dir__)),
config_path: Pathname.new(File.expand_path("./test_app/config/webpacker.yml", __dir__)),
env: "production"
)
end
def test_source_path
source_path = File.expand_path File.join(File.dirname(__FILE__), "test_app/app/packs").to_s
assert_equal source_path, @config.source_path.to_s
end
def test_source_entry_path
source_entry_path = File.expand_path File.join(File.dirname(__FILE__), "test_app/app/packs", "entrypoints").to_s
assert_equal @config.source_entry_path.to_s, source_entry_path
end
def test_public_root_path
public_root_path = File.expand_path File.join(File.dirname(__FILE__), "test_app/public").to_s
assert_equal @config.public_path.to_s, public_root_path
end
def test_public_output_path
public_output_path = File.expand_path File.join(File.dirname(__FILE__), "test_app/public/packs").to_s
assert_equal @config.public_output_path.to_s, public_output_path
@config = Webpacker::Configuration.new(
root_path: @config.root_path,
config_path: Pathname.new(File.expand_path("./test_app/config/webpacker_public_root.yml", __dir__)),
env: "production"
)
public_output_path = File.expand_path File.join(File.dirname(__FILE__), "public/packs").to_s
assert_equal @config.public_output_path.to_s, public_output_path
end
def test_public_manifest_path
public_manifest_path = File.expand_path File.join(File.dirname(__FILE__), "test_app/public/packs", "manifest.json").to_s
assert_equal @config.public_manifest_path.to_s, public_manifest_path
end
def test_cache_path
cache_path = File.expand_path File.join(File.dirname(__FILE__), "test_app/tmp/webpacker").to_s
assert_equal @config.cache_path.to_s, cache_path
end
def test_additional_paths
assert_equal @config.additional_paths, ["app/assets", "/etc/yarn", "some.config.js", "app/elm"]
end
def test_cache_manifest?
assert @config.cache_manifest?
with_rails_env("development") do
refute Webpacker.config.cache_manifest?
end
with_rails_env("test") do
refute Webpacker.config.cache_manifest?
end
end
def test_compile?
refute @config.compile?
with_rails_env("development") do
assert Webpacker.config.compile?
end
with_rails_env("test") do
assert Webpacker.config.compile?
end
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/webpack_runner_test.rb | test/webpack_runner_test.rb | require "test_helper"
require "webpacker/webpack_runner"
class WebpackRunnerTest < Webpacker::Test
def setup
@original_node_env, ENV["NODE_ENV"] = ENV["NODE_ENV"], "development"
@original_rails_env, ENV["RAILS_ENV"] = ENV["RAILS_ENV"], "development"
end
def teardown
ENV["NODE_ENV"] = @original_node_env
ENV["RAILS_ENV"] = @original_rails_env
end
def test_run_cmd_via_node_modules
cmd = ["#{test_app_path}/node_modules/.bin/webpack", "--config", "#{test_app_path}/config/webpack/development.js"]
verify_command(cmd, use_node_modules: true)
end
def test_run_cmd_via_yarn
cmd = ["yarn", "webpack", "--config", "#{test_app_path}/config/webpack/development.js"]
verify_command(cmd, use_node_modules: false)
end
def test_run_cmd_argv
cmd = ["#{test_app_path}/node_modules/.bin/webpack", "--config", "#{test_app_path}/config/webpack/development.js", "--watch"]
verify_command(cmd, argv: ["--watch"])
end
private
def test_app_path
File.expand_path("test_app", __dir__)
end
def verify_command(cmd, use_node_modules: true, argv: [])
cwd = Dir.pwd
Dir.chdir(test_app_path)
klass = Webpacker::WebpackRunner
instance = klass.new(argv)
mock = Minitest::Mock.new
mock.expect(:call, nil, [Webpacker::Compiler.env, *cmd])
klass.stub(:new, instance) do
instance.stub(:node_modules_bin_exist?, use_node_modules) do
Kernel.stub(:exec, mock) { klass.run(argv) }
end
end
mock.verify
ensure
Dir.chdir(cwd)
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/webpacker_test.rb | test/webpacker_test.rb | require "test_helper"
class WebpackerTest < Webpacker::Test
def test_config_params
assert_equal Rails.env, Webpacker.config.env
assert_equal Webpacker.instance.root_path, Webpacker.config.root_path
assert_equal Webpacker.instance.config_path, Webpacker.config.config_path
with_rails_env("test") do
assert_equal "test", Webpacker.config.env
end
end
def test_inline_css_no_dev_server
assert !Webpacker.inlining_css?
end
def test_inline_css_with_hmr
dev_server = Webpacker::DevServer.new({})
def dev_server.host; "localhost"; end
def dev_server.port; "3035"; end
def dev_server.pretty?; false; end
def dev_server.https?; true; end
def dev_server.hmr?; true; end
def dev_server.running?; true; end
Webpacker.instance.stub(:dev_server, dev_server) do
assert Webpacker.inlining_css?
end
end
def test_app_autoload_paths_cleanup
assert_empty $test_app_autoload_paths_in_initializer
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/env_test.rb | test/env_test.rb | require "test_helper"
class EnvTest < Webpacker::Test
def test_current
assert_equal Webpacker.env, Rails.env
end
def test_custom_without_config
with_rails_env("foo") do
assert_equal Webpacker.env, "production"
end
end
def test_custom_with_config
with_rails_env("staging") do
assert_equal Webpacker.env, "staging"
end
end
def test_default
assert_equal Webpacker::Env::DEFAULT, "production"
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/test_app/config/application.rb | test/test_app/config/application.rb | require "action_controller/railtie"
require "action_view/railtie"
require "webpacker"
module TestApp
class Application < ::Rails::Application
config.secret_key_base = "abcdef"
config.eager_load = true
config.active_support.test_order = :sorted
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/test_app/config/environment.rb | test/test_app/config/environment.rb | require_relative "application"
Rails.backtrace_cleaner.remove_silencers!
Rails.application.initialize!
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/test_app/config/initializers/inspect_autoload_paths.rb | test/test_app/config/initializers/inspect_autoload_paths.rb | $test_app_autoload_paths_in_initializer = ActiveSupport::Dependencies.autoload_paths
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/mounted_app/test/dummy/config/application.rb | test/mounted_app/test/dummy/config/application.rb | require "action_controller/railtie"
require "action_view/railtie"
require "webpacker"
module TestDummyApp
class Application < Rails::Application
config.secret_key_base = "abcdef"
config.eager_load = true
end
end
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/test/mounted_app/test/dummy/config/environment.rb | test/mounted_app/test/dummy/config/environment.rb | require_relative "application"
Rails.application.initialize!
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
rails/webpacker | https://github.com/rails/webpacker/blob/a715e055d937748c7cfd34b0450295348ca13ee6/lib/webpacker.rb | lib/webpacker.rb | require "active_support/core_ext/module/attribute_accessors"
require "active_support/core_ext/string/inquiry"
require "active_support/logger"
require "active_support/tagged_logging"
module Webpacker
extend self
def instance=(instance)
@instance = instance
end
def instance
@instance ||= Webpacker::Instance.new
end
def with_node_env(env)
original = ENV["NODE_ENV"]
ENV["NODE_ENV"] = env
yield
ensure
ENV["NODE_ENV"] = original
end
def ensure_log_goes_to_stdout
old_logger = Webpacker.logger
Webpacker.logger = Logger.new(STDOUT)
yield
ensure
Webpacker.logger = old_logger
end
delegate :logger, :logger=, :env, :inlining_css?, to: :instance
delegate :config, :compiler, :manifest, :commands, :dev_server, to: :instance
delegate :bootstrap, :clean, :clobber, :compile, to: :commands
end
require "webpacker/instance"
require "webpacker/env"
require "webpacker/configuration"
require "webpacker/manifest"
require "webpacker/compiler"
require "webpacker/commands"
require "webpacker/dev_server"
require "webpacker/railtie" if defined?(Rails)
| ruby | MIT | a715e055d937748c7cfd34b0450295348ca13ee6 | 2026-01-04T15:43:16.273438Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.