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/livecheck/strategy/page_match.rb | Library/Homebrew/livecheck/strategy/page_match.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {PageMatch} strategy fetches content at a URL and scans it for
# matching text using the provided regex.
#
# This strategy can be used in a `livecheck` block when no specific
# strategies apply to a given URL. Though {PageMatch} will technically
# match any HTTP URL, the strategy also requires a regex to function.
#
# The {find_versions} method can be used within other strategies, to
# handle the process of identifying version text in content.
#
# @api public
class PageMatch
extend Strategic
NICE_NAME = "Page match"
# A priority of zero causes livecheck to skip the strategy. We do this
# for {PageMatch} so we can selectively apply it only when a regex is
# provided in a `livecheck` block.
PRIORITY = 0
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{^https?://}i
# Whether the strategy can be applied to the provided URL.
# {PageMatch} will technically match any HTTP URL but is only
# usable with a `livecheck` block containing a regex.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Uses the regex to match text in the content or, if a block is
# provided, passes the page content to the block to handle matching.
# With either approach, an array of unique matches is returned.
#
# @param content [String] the page content to check
# @param regex [Regexp, nil] a regex used for matching versions in the
# content
# @return [Array]
sig {
params(
content: String,
regex: T.nilable(Regexp),
block: T.nilable(Proc),
).returns(T::Array[String])
}
def self.versions_from_content(content, regex, &block)
if block
block_return_value = regex.present? ? yield(content, regex) : yield(content)
return Strategy.handle_block_return(block_return_value)
end
return [] if regex.blank?
content.scan(regex).filter_map do |match|
case match
when String
match
when Array
match.first
end
end.uniq
end
# Checks the content at the URL for new versions, using the provided
# regex for matching.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp, nil] a regex used for matching versions
# @param provided_content [String, nil] page content to use in place of
# fetching via `Strategy#page_content`
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override.params(
url: String,
regex: T.nilable(Regexp),
provided_content: T.nilable(String),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.untyped])
}
def self.find_versions(url:, regex: nil, provided_content: nil, options: Options.new, &block)
if regex.blank? && !block_given?
raise ArgumentError, "#{Utils.demodulize(name)} requires a regex or `strategy` block"
end
match_data = { matches: {}, regex:, url: }
return match_data if url.blank?
content = if provided_content.is_a?(String)
match_data[:cached] = true
provided_content
else
match_data.merge!(Strategy.page_content(url, options:))
match_data[:content]
end
return match_data if content.blank?
versions_from_content(content, regex, &block).each do |match_text|
match_data[:matches][match_text] = Version.new(match_text)
end
match_data
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/livecheck/strategy/github_latest.rb | Library/Homebrew/livecheck/strategy/github_latest.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {GithubLatest} strategy identifies versions of software at
# github.com by checking a repository's "latest" release using the
# GitHub API.
#
# GitHub URLs take a few different formats:
#
# * `https://github.com/example/example/releases/download/1.2.3/example-1.2.3.tar.gz`
# * `https://github.com/example/example/archive/v1.2.3.tar.gz`
# * `https://github.com/downloads/example/example/example-1.2.3.tar.gz`
#
# {GithubLatest} should only be used when the upstream repository has a
# "latest" release for a suitable version and the strategy is necessary
# or appropriate (e.g. the formula/cask uses a release asset or the
# {Git} strategy returns an unreleased version). The strategy can only
# be applied by using `strategy :github_latest` in a `livecheck` block.
#
# The default regex identifies versions like `1.2.3`/`v1.2.3` in a
# release's tag or title. This is a common tag format but a modified
# regex can be provided in a `livecheck` block to override the default
# if a repository uses a different format (e.g. `1.2.3d`, `1.2.3-4`,
# etc.).
#
# @api public
class GithubLatest
extend Strategic
NICE_NAME = "GitHub - Latest"
# A priority of zero causes livecheck to skip the strategy. We do this
# for {GithubLatest} so we can selectively apply the strategy using
# `strategy :github_latest` in a `livecheck` block.
PRIORITY = 0
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
GithubReleases.match?(url)
end
# Extracts information from a provided URL and uses it to generate
# various input values used by the strategy to check for new versions.
# Some of these values act as defaults and can be overridden in a
# `livecheck` block.
#
# @param url [String] the URL used to generate values
# @return [Hash]
sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) }
def self.generate_input_values(url)
values = {}
match = url.delete_suffix(".git").match(GithubReleases::URL_MATCH_REGEX)
return values if match.blank?
values[:url] = "https://api.github.com/repos/#{match[:username]}/#{match[:repository]}/releases/latest"
values[:username] = match[:username]
values[:repository] = match[:repository]
values
end
# Generates the GitHub API URL for the repository's "latest" release
# and identifies the version from the JSON response.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp] a regex used for matching versions in content
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: Regexp,
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: GithubReleases::DEFAULT_REGEX, options: Options.new, &block)
match_data = { matches: {}, regex:, url: }
generated = generate_input_values(url)
return match_data if generated.blank?
match_data[:url] = generated[:url]
release = GitHub.get_latest_release(generated[:username], generated[:repository])
GithubReleases.versions_from_content(release, regex, &block).each do |match_text|
match_data[:matches][match_text] = Version.new(match_text)
end
match_data
end
end
end
GitHubLatest = Homebrew::Livecheck::Strategy::GithubLatest
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/livecheck/strategy/gnome.rb | Library/Homebrew/livecheck/strategy/gnome.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {Gnome} strategy identifies versions of software at gnome.org by
# checking the available downloads found in a project's `cache.json`
# file.
#
# GNOME URLs generally follow a standard format:
#
# * `https://download.gnome.org/sources/example/1.2/example-1.2.3.tar.xz`
#
# Before version 40, GNOME used a version scheme where unstable releases
# were indicated with a minor that's 90+ or odd. The newer version scheme
# uses trailing alpha/beta/rc text to identify unstable versions
# (e.g. `40.alpha`).
#
# When a regex isn't provided in a `livecheck` block, the strategy uses
# a default regex that matches versions which don't include trailing text
# after the numeric version (e.g. `40.0` instead of `40.alpha`) and it
# selectively filters out unstable versions below 40 using the rules for
# the older version scheme.
#
# @api public
class Gnome
extend Strategic
NICE_NAME = "GNOME"
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{
^https?://download\.gnome\.org
/sources
/(?<package_name>[^/]+)/ # The GNOME package name
}ix
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Extracts information from a provided URL and uses it to generate
# various input values used by the strategy to check for new versions.
# Some of these values act as defaults and can be overridden in a
# `livecheck` block.
#
# @param url [String] the URL used to generate values
# @return [Hash]
sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) }
def self.generate_input_values(url)
values = {}
match = url.match(URL_MATCH_REGEX)
return values if match.blank?
values[:url] = "https://download.gnome.org/sources/#{match[:package_name]}/cache.json"
regex_name = Regexp.escape(T.must(match[:package_name])).gsub("\\-", "-")
# GNOME archive files seem to use a standard filename format, so we
# count on the delimiter between the package name and numeric
# version being a hyphen and the file being a tarball.
values[:regex] = /#{regex_name}-(\d+(?:\.\d+)*)\.t/i
values
end
# Generates a URL and regex (if one isn't provided) and passes them
# to {PageMatch.find_versions} to identify versions in the content.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp] a regex used for matching versions in content
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: T.nilable(Regexp),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: nil, options: Options.new, &block)
generated = generate_input_values(url)
version_data = PageMatch.find_versions(
url: generated[:url],
regex: regex || generated[:regex],
options:,
&block
)
if regex.blank?
# Filter out unstable versions using the old version scheme where
# the major version is below 40.
version_data[:matches].reject! do |_, version|
next if version.major >= 40
next if version.minor.blank?
(version.minor.to_i.odd? || version.minor >= 90) ||
(version.patch.present? && version.patch >= 90)
end
end
version_data
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/livecheck/strategy/hackage.rb | Library/Homebrew/livecheck/strategy/hackage.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {Hackage} strategy identifies versions of software at
# hackage.haskell.org by checking directory listing pages.
#
# Hackage URLs take one of the following formats:
#
# * `https://hackage.haskell.org/package/example-1.2.3/example-1.2.3.tar.gz`
# * `https://downloads.haskell.org/~ghc/8.10.1/ghc-8.10.1-src.tar.xz`
#
# The default regex checks for the latest version in an `h3` heading element
# with a format like `<h3>example-1.2.3/</h3>`.
#
# @api public
class Hackage
extend Strategic
# A `Regexp` used in determining if the strategy applies to the URL and
# also as part of extracting the package name from the URL basename.
PACKAGE_NAME_REGEX = /(?<package_name>.+?)-\d+/i
# A `Regexp` used to extract the package name from the URL basename.
FILENAME_REGEX = /^#{PACKAGE_NAME_REGEX.source.strip}/i
# A `Regexp` used in determining if the strategy applies to the URL.
URL_MATCH_REGEX = %r{
^https?://(?:downloads|hackage)\.haskell\.org
(?:/[^/]+)+ # Path before the filename
#{PACKAGE_NAME_REGEX.source.strip}
}ix
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Extracts information from a provided URL and uses it to generate
# various input values used by the strategy to check for new versions.
# Some of these values act as defaults and can be overridden in a
# `livecheck` block.
#
# @param url [String] the URL used to generate values
# @return [Hash]
sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) }
def self.generate_input_values(url)
values = {}
match = File.basename(url).match(FILENAME_REGEX)
return values if match.blank?
# A page containing a directory listing of the latest source tarball
values[:url] = "https://hackage.haskell.org/package/#{match[:package_name]}/src/"
regex_name = Regexp.escape(T.must(match[:package_name])).gsub("\\-", "-")
# Example regex: `%r{<h3>example-(.*?)/?</h3>}i`
values[:regex] = %r{<h3>#{regex_name}-(.*?)/?</h3>}i
values
end
# Generates a URL and regex (if one isn't provided) and passes them
# to {PageMatch.find_versions} to identify versions in the content.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp] a regex used for matching versions in content
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: T.nilable(Regexp),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: nil, options: Options.new, &block)
generated = generate_input_values(url)
PageMatch.find_versions(
url: generated[:url],
regex: regex || generated[:regex],
options:,
&block
)
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/livecheck/strategy/cpan.rb | Library/Homebrew/livecheck/strategy/cpan.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {Cpan} strategy identifies versions of software at
# cpan.metacpan.org by checking directory listing pages.
#
# CPAN URLs take the following formats:
#
# * `https://cpan.metacpan.org/authors/id/H/HO/HOMEBREW/Brew-v1.2.3.tar.gz`
# * `https://cpan.metacpan.org/authors/id/H/HO/HOMEBREW/brew/brew-v1.2.3.tar.gz`
#
# In these examples, `HOMEBREW` is the author name and the preceding `H`
# and `HO` directories correspond to the first letter(s). Some authors
# also store files in subdirectories, as in the second example above.
#
# @api public
class Cpan
extend Strategic
NICE_NAME = "CPAN"
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{
^https?://(?:cpan\.metacpan\.org|www\.cpan\.org)
(?<path>/authors/id(?:/[^/]+){3,}/) # Path before the filename
(?<prefix>[^/]+) # Filename text before the version
-v?\d+(?:\.\d+)* # The numeric version
(?<suffix>[^/]+) # Filename text after the version
}ix
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Extracts information from a provided URL and uses it to generate
# various input values used by the strategy to check for new versions.
# Some of these values act as defaults and can be overridden in a
# `livecheck` block.
#
# @param url [String] the URL used to generate values
sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) }
def self.generate_input_values(url)
values = {}
match = url.match(URL_MATCH_REGEX)
return values if match.blank?
# The directory listing page where the archive files are found
values[:url] = "https://www.cpan.org#{match[:path]}"
regex_prefix = Regexp.escape(T.must(match[:prefix])).gsub("\\-", "-")
# Use `\.t` instead of specific tarball extensions (e.g. .tar.gz)
suffix = T.must(match[:suffix]).sub(Strategy::TARBALL_EXTENSION_REGEX, ".t")
regex_suffix = Regexp.escape(suffix).gsub("\\-", "-")
# Example regex: `/href=.*?Brew[._-]v?(\d+(?:\.\d+)*)\.t/i`
values[:regex] = /href=.*?#{regex_prefix}[._-]v?(\d+(?:\.\d+)*)#{regex_suffix}/i
values
end
# Generates a URL and regex (if one isn't provided) and passes them
# to {PageMatch.find_versions} to identify versions in the content.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp] a regex used for matching versions in content
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: T.nilable(Regexp),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: nil, options: Options.new, &block)
generated = generate_input_values(url)
PageMatch.find_versions(
url: generated[:url],
regex: regex || generated[:regex],
options:,
&block
)
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/livecheck/strategy/github_releases.rb | Library/Homebrew/livecheck/strategy/github_releases.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {GithubReleases} strategy identifies versions of software at
# github.com by checking a repository's recent releases using the
# GitHub API.
#
# GitHub URLs take a few different formats:
#
# * `https://github.com/example/example/releases/download/1.2.3/example-1.2.3.tar.gz`
# * `https://github.com/example/example/archive/v1.2.3.tar.gz`
# * `https://github.com/downloads/example/example/example-1.2.3.tar.gz`
#
# {GithubReleases} should only be used when the upstream repository has
# releases for suitable versions and the strategy is necessary or
# appropriate (e.g. the formula/cask uses a release asset and the
# {GithubLatest} strategy isn't sufficient to identify the newest version.
# The strategy can only be applied by using `strategy :github_releases`
# in a `livecheck` block.
#
# The default regex identifies versions like `1.2.3`/`v1.2.3` in each
# release's tag or title. This is a common tag format but a modified
# regex can be provided in a `livecheck` block to override the default
# if a repository uses a different format (e.g. `1.2.3d`, `1.2.3-4`,
# etc.).
#
# @api public
class GithubReleases
extend Strategic
NICE_NAME = "GitHub - Releases"
# A priority of zero causes livecheck to skip the strategy. We do this
# for {GithubReleases} so we can selectively apply the strategy using
# `strategy :github_releases` in a `livecheck` block.
PRIORITY = 0
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{
^https?://github\.com
/(?:downloads/)?(?<username>[^/]+) # The GitHub username
/(?<repository>[^/]+) # The GitHub repository name
}ix
# The default regex used to identify a version from a tag when a regex
# isn't provided.
DEFAULT_REGEX = /v?(\d+(?:\.\d+)+)/i
# Keys in the release JSON that could contain the version.
# The tag name is checked first, to better align with the {Git}
# strategy.
VERSION_KEYS = T.let(["tag_name", "name"].freeze, T::Array[String])
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Extracts information from a provided URL and uses it to generate
# various input values used by the strategy to check for new versions.
# Some of these values act as defaults and can be overridden in a
# `livecheck` block.
#
# @param url [String] the URL used to generate values
# @return [Hash]
sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) }
def self.generate_input_values(url)
values = {}
match = url.delete_suffix(".git").match(URL_MATCH_REGEX)
return values if match.blank?
values[:url] = "#{GitHub::API_URL}/repos/#{match[:username]}/#{match[:repository]}/releases"
values[:username] = match[:username]
values[:repository] = match[:repository]
values
end
# Uses a regex to match versions from release JSON or, if a block is
# provided, passes the JSON to the block to handle matching. With
# either approach, an array of unique matches is returned.
#
# @param content [Array, Hash] array of releases or a single release
# @param regex [Regexp] a regex used for matching versions in the
# content
# @param block [Proc, nil] a block to match the content
# @return [Array]
sig {
params(
content: T.any(T::Array[T::Hash[String, T.untyped]], T::Hash[String, T.untyped]),
regex: Regexp,
block: T.nilable(Proc),
).returns(T::Array[String])
}
def self.versions_from_content(content, regex, &block)
if block.present?
block_return_value = yield(content, regex)
return Strategy.handle_block_return(block_return_value)
end
content = [content] unless content.is_a?(Array)
content.compact_blank.filter_map do |release|
next if release["draft"] || release["prerelease"]
value = T.let(nil, T.nilable(String))
VERSION_KEYS.find do |key|
match = release[key]&.match(regex)
next if match.blank?
value = match[1]
end
value
end.uniq
end
# Generates the GitHub API URL for the repository's recent releases
# and identifies versions from the JSON response.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp] a regex used for matching versions in content
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: Regexp,
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: DEFAULT_REGEX, options: Options.new, &block)
match_data = { matches: {}, regex:, url: }
generated = generate_input_values(url)
return match_data if generated.blank?
match_data[:url] = generated[:url]
releases = GitHub::API.open_rest(generated[:url])
versions_from_content(releases, regex, &block).each do |match_text|
match_data[:matches][match_text] = Version.new(match_text)
end
match_data
end
end
end
GitHubReleases = Homebrew::Livecheck::Strategy::GithubReleases
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/livecheck/strategy/header_match.rb | Library/Homebrew/livecheck/strategy/header_match.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {HeaderMatch} strategy follows all URL redirections and scans
# the resulting headers for matching text using the provided regex.
#
# This strategy is not applied automatically and it's necessary to use
# `strategy :header_match` in a `livecheck` block to apply it.
class HeaderMatch
extend Strategic
NICE_NAME = "Header match"
# A priority of zero causes livecheck to skip the strategy. We do this
# for {HeaderMatch} so we can selectively apply it when appropriate.
PRIORITY = 0
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{^https?://}i
# The header fields to check when a `strategy` block isn't provided.
DEFAULT_HEADERS_TO_CHECK = T.let(["content-disposition", "location"].freeze, T::Array[String])
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Identify versions from HTTP headers.
#
# @param headers [Hash] a hash of HTTP headers to check for versions
# @param regex [Regexp, nil] a regex for matching versions
# @return [Array]
sig {
params(
headers: T::Hash[String, String],
regex: T.nilable(Regexp),
block: T.nilable(Proc),
).returns(T::Array[String])
}
def self.versions_from_headers(headers, regex = nil, &block)
if block
block_return_value = regex.present? ? yield(headers, regex) : yield(headers)
return Strategy.handle_block_return(block_return_value)
end
DEFAULT_HEADERS_TO_CHECK.filter_map do |header_name|
header_value = headers[header_name]
next if header_value.blank?
if regex
header_value[regex, 1]
else
v = Version.parse(header_value, detected_from_url: true)
v.null? ? nil : v.to_s
end
end.uniq
end
# Checks the final URL for new versions after following all redirections,
# using the provided regex for matching.
#
# @param url [String] the URL to fetch
# @param regex [Regexp, nil] a regex used for matching versions
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: T.nilable(Regexp),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: nil, options: Options.new, &block)
match_data = { matches: {}, regex:, url: }
headers = Strategy.page_headers(url, options:)
# Merge the headers from all responses into one hash
merged_headers = headers.reduce(&:merge)
return match_data if merged_headers.blank?
versions_from_headers(merged_headers, regex, &block).each do |version_text|
match_data[:matches][version_text] = Version.new(version_text)
end
match_data
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/livecheck/strategy/git.rb | Library/Homebrew/livecheck/strategy/git.rb | # typed: strict
# frozen_string_literal: true
require "addressable"
require "livecheck/strategic"
require "system_command"
module Homebrew
module Livecheck
module Strategy
# The {Git} strategy identifies versions of software in a Git repository
# by checking the tags using `git ls-remote --tags`.
#
# Livecheck has historically prioritized the {Git} strategy over others
# and this behavior was continued when the priority setup was created.
# This is partly related to Livecheck checking formula URLs in order of
# `head`, `stable` and then `homepage`. The higher priority here may
# be removed (or altered) in the future if we reevaluate this particular
# behavior.
#
# This strategy does not have a default regex. Instead, it simply removes
# any non-digit text from the start of tags and parses the rest as a
# {Version}. This works for some simple situations but even one unusual
# tag can cause a bad result. It's better to provide a regex in a
# `livecheck` block, so `livecheck` only matches what we really want.
#
# @api public
class Git
extend Strategic
extend SystemCommand::Mixin
# Used to cache processed URLs, to avoid duplicating effort.
@processed_urls = T.let({}, T::Hash[String, String])
# The priority of the strategy on an informal scale of 1 to 10 (from
# lowest to highest).
PRIORITY = 8
# The default regex used to naively identify versions from tags when a
# regex isn't provided.
DEFAULT_REGEX = /\D*(.+)/
GITEA_INSTANCES = T.let(%w[
codeberg.org
gitea.com
opendev.org
tildegit.org
].freeze, T::Array[String])
private_constant :GITEA_INSTANCES
GOGS_INSTANCES = T.let(%w[
lolg.it
].freeze, T::Array[String])
private_constant :GOGS_INSTANCES
# Processes and returns the URL used by livecheck.
sig { params(url: String).returns(String) }
def self.preprocess_url(url)
processed_url = @processed_urls[url]
return processed_url if processed_url
begin
uri = Addressable::URI.parse url
rescue Addressable::URI::InvalidURIError
return url
end
host = uri.host
path = uri.path
return url if host.nil? || path.nil?
host = "github.com" if host == "github.s3.amazonaws.com"
path = path.delete_prefix("/").delete_suffix(".git")
scheme = uri.scheme
if host == "github.com"
return url if path.match? %r{/releases/latest/?$}
owner, repo = path.delete_prefix("downloads/").split("/")
processed_url = "#{scheme}://#{host}/#{owner}/#{repo}.git"
elsif GITEA_INSTANCES.include?(host)
return url if path.match? %r{/releases/latest/?$}
owner, repo = path.split("/")
processed_url = "#{scheme}://#{host}/#{owner}/#{repo}.git"
elsif GOGS_INSTANCES.include?(host)
owner, repo = path.split("/")
processed_url = "#{scheme}://#{host}/#{owner}/#{repo}.git"
# sourcehut
elsif host == "git.sr.ht"
owner, repo = path.split("/")
processed_url = "#{scheme}://#{host}/#{owner}/#{repo}"
# GitLab (gitlab.com or self-hosted)
elsif path.include?("/-/archive/")
processed_url = url.sub(%r{/-/archive/.*$}i, ".git")
end
if processed_url && (processed_url != url)
@processed_urls[url] = processed_url
else
url
end
end
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
url = preprocess_url(url)
(DownloadStrategyDetector.detect(url) <= GitDownloadStrategy) == true
end
# Fetches a remote Git repository's tags using `git ls-remote --tags`
# and parses the command's output. If a regex is provided, it will be
# used to filter out any tags that don't match it.
#
# @param url [String] the URL of the Git repository to check
# @param regex [Regexp] the regex to use for filtering tags
# @return [Hash]
sig { params(url: String, regex: T.nilable(Regexp)).returns(T::Hash[Symbol, T.untyped]) }
def self.tag_info(url, regex = nil)
stdout, stderr, _status = system_command(
"git",
args: ["ls-remote", "--tags", url],
env: { "GIT_TERMINAL_PROMPT" => "0" },
print_stdout: false,
print_stderr: false,
debug: false,
verbose: false,
).to_a
tags_data = { tags: T.let([], T::Array[String]) }
tags_data[:messages] = stderr.split("\n") if stderr.present?
return tags_data if stdout.blank?
# Isolate tag strings and filter by regex
tags = stdout.gsub(%r{^.*\trefs/tags/|\^{}$}, "").split("\n").uniq.sort
tags.select! { |t| regex.match?(t) } if regex
tags_data[:tags] = tags
tags_data
end
# Identify versions from tag strings using a provided regex or the
# `DEFAULT_REGEX`. The regex is expected to use a capture group around
# the version text.
#
# @param tags [Array] the tags to identify versions from
# @param regex [Regexp, nil] a regex to identify versions
# @return [Array]
sig {
params(
tags: T::Array[String],
regex: T.nilable(Regexp),
block: T.nilable(Proc),
).returns(T::Array[String])
}
def self.versions_from_tags(tags, regex = nil, &block)
if block
block_return_value = if regex.present?
yield(tags, regex)
elsif block.arity == 2
yield(tags, DEFAULT_REGEX)
else
yield(tags)
end
return Strategy.handle_block_return(block_return_value)
end
tags.filter_map do |tag|
if regex
# Use the first capture group (the version)
# This code is not typesafe unless the regex includes a capture group
T.unsafe(tag.scan(regex).first)&.first
else
# Remove non-digits from the start of the tag and use that as the
# version text
tag[DEFAULT_REGEX, 1]
end
end.uniq
end
# Checks the Git tags for new versions. When a regex isn't provided,
# this strategy simply removes non-digits from the start of tag
# strings and parses the remaining text as a {Version}.
#
# @param url [String] the URL of the Git repository to check
# @param regex [Regexp, nil] a regex used for matching versions
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: T.nilable(Regexp),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: nil, options: Options.new, &block)
match_data = { matches: {}, regex:, url: }
tags_data = tag_info(url, regex)
tags = tags_data[:tags]
if tags_data.key?(:messages)
match_data[:messages] = tags_data[:messages]
return match_data if tags.blank?
end
versions_from_tags(tags, regex, &block).each do |version_text|
match_data[:matches][version_text] = Version.new(version_text)
rescue TypeError
next
end
match_data
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/livecheck/strategy/launchpad.rb | Library/Homebrew/livecheck/strategy/launchpad.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {Launchpad} strategy identifies versions of software at
# launchpad.net by checking the main page for a project.
#
# Launchpad URLs take a variety of formats but all the current formats
# contain the project name as the first part of the URL path:
#
# * `https://launchpad.net/example/1.2/1.2.3/+download/example-1.2.3.tar.gz`
# * `https://launchpad.net/example/trunk/1.2.3/+download/example-1.2.3.tar.gz`
# * `https://code.launchpad.net/example/1.2/1.2.3/+download/example-1.2.3.tar.gz`
#
# The default regex identifies the latest version within an HTML element
# found on the main page for a project:
#
# <pre><div class="version">
# Latest version is 1.2.3
# </div></pre>
#
# @api public
class Launchpad
extend Strategic
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{
^https?://(?:[^/]+?\.)*launchpad\.net
/(?<project_name>[^/]+) # The Launchpad project name
}ix
# The default regex used to identify the latest version when a regex
# isn't provided.
DEFAULT_REGEX = %r{class="[^"]*version[^"]*"[^>]*>\s*Latest version is (.+)\s*</}
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Extracts information from a provided URL and uses it to generate
# various input values used by the strategy to check for new versions.
# Some of these values act as defaults and can be overridden in a
# `livecheck` block.
#
# @param url [String] the URL used to generate values
# @return [Hash]
sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) }
def self.generate_input_values(url)
values = {}
match = url.match(URL_MATCH_REGEX)
return values if match.blank?
# The main page for the project on Launchpad
values[:url] = "https://launchpad.net/#{match[:project_name]}/"
values
end
# Generates a URL and regex (if one isn't provided) and passes them
# to {PageMatch.find_versions} to identify versions in the content.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp] a regex used for matching versions in content
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override(allow_incompatible: true).params(
url: String,
regex: Regexp,
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: DEFAULT_REGEX, options: Options.new, &block)
generated = generate_input_values(url)
PageMatch.find_versions(
url: generated[:url],
regex:,
options:,
&block
)
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/livecheck/strategy/npm.rb | Library/Homebrew/livecheck/strategy/npm.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {Npm} strategy identifies versions of software at
# registry.npmjs.org by checking the latest version for a package.
#
# npm URLs take one of the following formats:
#
# * `https://registry.npmjs.org/example/-/example-1.2.3.tgz`
# * `https://registry.npmjs.org/@example/example/-/example-1.2.3.tgz`
#
# @api public
class Npm
extend Strategic
NICE_NAME = "npm"
# The default `strategy` block used to extract version information when
# a `strategy` block isn't provided.
DEFAULT_BLOCK = T.let(proc do |json|
json["version"]
end.freeze, T.proc.params(
arg0: T::Hash[String, T.anything],
).returns(T.any(String, T::Array[String])))
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{
^https?://registry\.npmjs\.org
/(?<package_name>.+?)/-/ # The npm package name
}ix
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
# @return [Boolean]
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Extracts information from a provided URL and uses it to generate
# various input values used by the strategy to check for new versions.
#
# @param url [String] the URL used to generate values
# @return [Hash]
sig { params(url: String).returns(T::Hash[Symbol, T.untyped]) }
def self.generate_input_values(url)
values = {}
return values unless (match = url.match(URL_MATCH_REGEX))
values[:url] = "https://registry.npmjs.org/#{URI.encode_www_form_component(match[:package_name])}/latest"
values
end
# Generates a URL and checks the content at the URL for new versions
# using {Json.versions_from_content}.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp, nil] a regex for matching versions in content
# @param provided_content [String, nil] content to check instead of
# fetching
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override.params(
url: String,
regex: T.nilable(Regexp),
provided_content: T.nilable(String),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: nil, provided_content: nil, options: Options.new, &block)
match_data = { matches: {}, regex:, url: }
match_data[:cached] = true if provided_content.is_a?(String)
generated = generate_input_values(url)
return match_data if generated.blank?
match_data[:url] = generated[:url]
content = if provided_content
provided_content
else
match_data.merge!(Strategy.page_content(match_data[:url], options:))
match_data[:content]
end
return match_data unless content
Json.versions_from_content(content, regex, &block || DEFAULT_BLOCK).each do |match_text|
match_data[:matches][match_text] = Version.new(match_text)
end
match_data
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/livecheck/strategy/electron_builder.rb | Library/Homebrew/livecheck/strategy/electron_builder.rb | # typed: strict
# frozen_string_literal: true
require "livecheck/strategic"
module Homebrew
module Livecheck
module Strategy
# The {ElectronBuilder} strategy fetches content at a URL and parses it
# as an electron-builder appcast in YAML format.
#
# This strategy is not applied automatically and it's necessary to use
# `strategy :electron_builder` in a `livecheck` block to apply it.
class ElectronBuilder
extend Strategic
NICE_NAME = "electron-builder"
# A priority of zero causes livecheck to skip the strategy. We do this
# for {ElectronBuilder} so we can selectively apply it when appropriate.
PRIORITY = 0
# The `Regexp` used to determine if the strategy applies to the URL.
URL_MATCH_REGEX = %r{^https?://.+/[^/]+\.ya?ml(?:\?[^/?]+)?$}i
# Whether the strategy can be applied to the provided URL.
#
# @param url [String] the URL to match against
sig { override.params(url: String).returns(T::Boolean) }
def self.match?(url)
URL_MATCH_REGEX.match?(url)
end
# Checks the YAML content at the URL for new versions.
#
# @param url [String] the URL of the content to check
# @param regex [Regexp, nil] a regex used for matching versions
# @param provided_content [String, nil] content to use in place of
# fetching via `Strategy#page_content`
# @param options [Options] options to modify behavior
# @return [Hash]
sig {
override.params(
url: String,
regex: T.nilable(Regexp),
provided_content: T.nilable(String),
options: Options,
block: T.nilable(Proc),
).returns(T::Hash[Symbol, T.anything])
}
def self.find_versions(url:, regex: nil, provided_content: nil, options: Options.new, &block)
if regex.present? && !block_given?
raise ArgumentError,
"#{Utils.demodulize(name)} only supports a regex when using a `strategy` block"
end
Yaml.find_versions(
url:,
regex:,
provided_content:,
options:,
&block || proc { |yaml| yaml["version"] }
)
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/yard/docstring_parser.rb | Library/Homebrew/yard/docstring_parser.rb | # typed: strict
# frozen_string_literal: true
require "sorbet-runtime"
require_relative "../extend/module"
# from https://github.com/lsegal/yard/issues/484#issuecomment-442586899
module Homebrew
module YARD
class DocstringParser < ::YARD::DocstringParser
# Every `Object` has these methods.
unless const_defined?(:OVERRIDABLE_METHODS, false)
OVERRIDABLE_METHODS = [
:hash, :inspect, :to_s,
:<=>, :===, :!~, :eql?, :equal?, :!, :==, :!=
].freeze
private_constant :OVERRIDABLE_METHODS
end
unless const_defined?(:SELF_EXPLANATORY_METHODS, false)
SELF_EXPLANATORY_METHODS = [:to_yaml, :to_json, :to_str].freeze
private_constant :SELF_EXPLANATORY_METHODS
end
sig { params(content: T.nilable(String)).returns(String) }
def parse_content(content)
# Convert plain text to tags.
content = content&.gsub(/^\s*(TODO|FIXME):\s*/i, "@todo ")
content = content&.gsub(/^\s*NOTE:\s*/i, "@note ")
# Ignore non-documentation comments.
content = content&.sub(/\A(typed|.*rubocop):.*/m, "")
content = super
source = handler&.statement&.source
if object&.type == :method &&
(match = source&.match(/\so(deprecated|disabled)\s+"((?:\\"|[^"])*)"(?:\s*,\s*"((?:\\"|[^"])*))?"/m))
type = match[1]
method = match[2]
method = method.sub(/\#{self(\.class)?}/, object.namespace.to_s)
replacement = match[3]
replacement = replacement.sub(/\#{self(\.class)?}/, object.namespace.to_s)
# Only match `odeprecated`/`odisabled` for this method.
if method.match?(/(.|#|`)#{Regexp.escape(object.name.to_s)}`/)
if (method_name = method[/\A`([^`]*)`\Z/, 1]) && (
(method_name.count(".") + method_name.count("#")) <= 1
)
method_name = method_name.delete_prefix(object.namespace.to_s)
method = (method_name.delete_prefix(".") == object.name(true).to_s) ? nil : "{#{method_name}}"
end
if replacement &&
(replacement_method_name = replacement[/\A`([^`]*)`\Z/, 1]) && (
(replacement_method_name.count(".") + replacement_method_name.count("#")) <= 1
)
replacement_method_name = replacement_method_name.delete_prefix(object.namespace.to_s)
replacement = "{#{replacement_method_name}}"
end
if method && !method.include?('#{')
description = "Calling #{method} is #{type}"
description += ", use #{replacement} instead" if replacement && !replacement.include?('#{')
description += "."
elsif replacement && !replacement.include?('#{')
description = "Use #{replacement} instead."
else
description = ""
end
tags << create_tag("deprecated", description)
end
end
api = tags.find { |tag| tag.tag_name == "api" }&.text
is_private = tags.any? { |tag| tag.tag_name == "private" }
visibility = directives.find { |d| d.tag.tag_name == "visibility" }&.tag&.text
# Hide `#hash`, `#inspect` and `#to_s`.
if visibility.nil? && OVERRIDABLE_METHODS.include?(object&.name)
create_directive("visibility", "private")
visibility = "private"
end
# Mark everything as `@api private` by default.
if api.nil? && !is_private
tags << create_tag("api", "private")
api = "private"
end
# Warn about undocumented non-private APIs.
if handler && api && api != "private" && visibility != "private" &&
content.chomp.empty? && !SELF_EXPLANATORY_METHODS.include?(object&.name)
stmt = handler.statement
log.warn "#{api.capitalize} API should be documented:\n " \
"in `#{handler.parser.file}`:#{stmt.line}:\n\n#{stmt.show}\n"
end
content
end
end
end
end
YARD::Docstring.default_parser = Homebrew::YARD::DocstringParser
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/yard/templates/default/docstring/html/setup.rb | Library/Homebrew/yard/templates/default/docstring/html/setup.rb | # typed: strict
# frozen_string_literal: true
# This follows the docs at https://github.com/lsegal/yard/blob/main/docs/Templates.md#setuprb
# rubocop:disable Style/TopLevelMethodDefinition
sig { void }
def init
# `sorbet` is available transitively through the `yard-sorbet` plugin, but we're
# outside of the standalone sorbet config, so `checked` is enabled by default
T.bind(self, T.all(T::Class[T.anything], YARD::Templates::Template), checked: false)
super
return if sections.empty?
sections[:index].place(:internal).before(:private)
end
sig { returns(T.nilable(String)) }
def internal
T.bind(self, YARD::Templates::Template, checked: false)
erb(:internal) if object.has_tag?(:api) && object.tag(:api).text == "internal"
end
# rubocop:enable Style/TopLevelMethodDefinition
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/version/parser.rb | Library/Homebrew/version/parser.rb | # typed: strict
# frozen_string_literal: true
class Version
class Parser
extend T::Helpers
abstract!
sig { abstract.params(spec: Pathname).returns(T.nilable(String)) }
def parse(spec); end
end
class RegexParser < Parser
extend T::Helpers
abstract!
sig { params(regex: Regexp, block: T.nilable(T.proc.params(arg0: String).returns(String))).void }
def initialize(regex, &block)
super()
@regex = regex
@block = block
end
sig { override.params(spec: Pathname).returns(T.nilable(String)) }
def parse(spec)
match = @regex.match(self.class.process_spec(spec))
return if match.blank?
version = match.captures.first
return if version.blank?
return @block.call(version) if @block.present?
version
end
sig { abstract.params(spec: Pathname).returns(String) }
def self.process_spec(spec); end
end
class UrlParser < RegexParser
sig { override.params(spec: Pathname).returns(String) }
def self.process_spec(spec)
spec.to_s
end
end
class StemParser < RegexParser
SOURCEFORGE_DOWNLOAD_REGEX = %r{(?:sourceforge\.net|sf\.net)/.*/download$}
NO_FILE_EXTENSION_REGEX = /\.[^a-zA-Z]+$/
sig { override.params(spec: Pathname).returns(String) }
def self.process_spec(spec)
return spec.basename.to_s if spec.directory?
spec_s = spec.to_s
return spec.dirname.stem if spec_s.match?(SOURCEFORGE_DOWNLOAD_REGEX)
return spec.basename.to_s if spec_s.match?(NO_FILE_EXTENSION_REGEX)
spec.stem
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/sorbet/tapioca/prerequire.rb | Library/Homebrew/sorbet/tapioca/prerequire.rb | # typed: strict
# frozen_string_literal: true
# Don't start coverage tracking automatically
ENV["SIMPLECOV_NO_DEFAULTS"] = "1"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/sorbet/tapioca/utils.rb | Library/Homebrew/sorbet/tapioca/utils.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module Tapioca
module Utils
sig { params(klass: T::Class[T.anything]).returns(T::Module[T.anything]) }
def self.named_object_for(klass)
return klass if klass.name
attached_object = klass.attached_object
case attached_object
when Module then attached_object
else raise "Unsupported attached object for: #{klass}"
end
end
# @param class_methods [Boolean] whether to get class methods or instance methods
# @return the `module` methods that are defined in the given file
sig {
params(mod: T::Module[T.anything], file_name: String,
class_methods: T::Boolean).returns(T::Array[T.any(Method, UnboundMethod)])
}
def self.methods_from_file(mod, file_name, class_methods: false)
methods = if class_methods
mod.methods(false).map { mod.method(it) }
else
mod.instance_methods(false).map { mod.instance_method(it) }
end
methods.select { it.source_location&.first&.end_with?(file_name) }
end
sig { params(mod: T::Module[T.anything]).returns(T::Array[T::Module[T.anything]]) }
def self.named_objects_with_module(mod)
ObjectSpace.each_object(mod).map do |obj|
case obj
when Class then named_object_for(obj)
when Module then obj
else raise "Unsupported object: #{obj}"
end
end.uniq
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/sorbet/tapioca/require.rb | Library/Homebrew/sorbet/tapioca/require.rb | # typed: strict
# frozen_string_literal: true
# These should not be made constants or Tapioca will think they are part of a gem.
dependency_require_map = {
"ruby-macho" => "macho",
}.freeze
additional_requires_map = {
"parser" => ["parser/current"],
"rubocop-rspec" => ["rubocop/rspec/expect_offense"],
}.freeze
# Freeze lockfile
Bundler.settings.set_command_option(:frozen, "1")
definition = Bundler.definition
definition.resolve.for(definition.current_dependencies).each do |spec|
name = spec.name
# These sorbet gems do not contain any library files
next if name == "sorbet"
next if name == "sorbet-static"
next if name == "sorbet-static-and-runtime"
name = dependency_require_map[name] if dependency_require_map.key?(name)
require name
additional_requires_map[name]&.each { require(it) }
rescue LoadError
raise unless name.include?("-")
name = name.tr("-", "/")
require name
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/sorbet/tapioca/compilers/rubocop.rb | Library/Homebrew/sorbet/tapioca/compilers/rubocop.rb | # typed: strict
# frozen_string_literal: true
require "method_source"
require "rubocop"
require_relative "../../../rubocops"
module Tapioca
module Compilers
class RuboCop < Tapioca::Dsl::Compiler
# This should be a module whose singleton class contains RuboCop::AST::NodePattern::Macros,
# but I don't know how to express that in Sorbet.
ConstantType = type_member { { fixed: T::Module[T.anything] } }
sig { override.returns(T::Enumerable[T::Module[T.anything]]) }
def self.gather_constants
all_modules.select do |klass|
next unless klass.singleton_class < ::RuboCop::AST::NodePattern::Macros
path = T.must(Object.const_source_location(klass.to_s)).fetch(0).to_s
# exclude vendored code, to avoid contradicting their RBI files
!path.include?("/vendor/bundle/ruby/") &&
# exclude source code that already has an RBI file
!File.exist?("#{path}i") &&
# exclude source code that doesn't use the DSLs
File.readlines(path).any?(/def_node_/)
end
end
sig { override.void }
def decorate
root.create_path(constant) do |klass|
constant.instance_methods(false).each do |method_name|
source = constant.instance_method(method_name).source.lstrip
# For more info on these DSLs:
# https://www.rubydoc.info/gems/rubocop-ast/RuboCop/AST/NodePattern/Macros
# https://github.com/rubocop/rubocop-ast/blob/HEAD/lib/rubocop/ast/node_pattern.rb
# https://github.com/rubocop/rubocop-ast/blob/HEAD/lib/rubocop/ast/node_pattern/method_definer.rb
# The type signatures below could maybe be stronger, but I only wanted to avoid errors:
case source
when /\Adef_node_matcher/
# https://github.com/Shopify/tapioca/blob/3341a9b/lib/tapioca/rbi_ext/model.rb#L89
klass.create_method(
method_name.to_s,
parameters: [
create_param("node", type: "RuboCop::AST::Node"),
create_kw_rest_param("kwargs", type: "T.untyped"),
create_block_param("block", type: "T.untyped"),
],
return_type: "T.untyped",
)
when /\Adef_node_search/
klass.create_method(
method_name.to_s,
parameters: [
create_param("node", type: "RuboCop::AST::Node"),
create_rest_param("pattern", type: "T.any(String, Symbol)"),
create_kw_rest_param("kwargs", type: "T.untyped"),
create_block_param("block", type: "T.untyped"),
],
return_type: method_name.to_s.end_with?("?") ? "T::Boolean" : "T.untyped",
)
end
end
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/sorbet/tapioca/compilers/api_structs.rb | Library/Homebrew/sorbet/tapioca/compilers/api_structs.rb | # typed: strict
# frozen_string_literal: true
require_relative "../../../global"
require "api/formula_struct"
require "api/cask_struct"
module Tapioca
module Compilers
class ApiStructs < Tapioca::Dsl::Compiler
ConstantType = type_member { { fixed: T.class_of(T::Struct) } }
sig { override.returns(T::Enumerable[T::Module[T.anything]]) }
def self.gather_constants = [::Homebrew::API::FormulaStruct, ::Homebrew::API::CaskStruct]
sig { override.void }
def decorate
root.create_class(T.must(constant.name)) do |klass|
constant.const_get(:PREDICATES).each do |predicate_name|
klass.create_method("#{predicate_name}?", return_type: "T::Boolean")
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/sorbet/tapioca/compilers/tty.rb | Library/Homebrew/sorbet/tapioca/compilers/tty.rb | # typed: strict
# frozen_string_literal: true
require_relative "../../../global"
require "utils/tty"
module Tapioca
module Compilers
class Tty < Tapioca::Dsl::Compiler
ConstantType = type_member { { fixed: T::Module[T.anything] } }
sig { override.returns(T::Enumerable[T::Module[T.anything]]) }
def self.gather_constants = [::Tty]
sig { override.void }
def decorate
root.create_module(T.must(constant.name)) do |mod|
dynamic_methods = ::Tty::COLOR_CODES.keys + ::Tty::STYLE_CODES.keys + ::Tty::SPECIAL_CODES.keys
dynamic_methods.each do |method|
mod.create_method(method.to_s, return_type: "String", class_method: true)
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/sorbet/tapioca/compilers/args.rb | Library/Homebrew/sorbet/tapioca/compilers/args.rb | # typed: strict
# frozen_string_literal: true
require_relative "../../../global"
require "cli/parser"
module Tapioca
module Compilers
class Args < Tapioca::Dsl::Compiler
GLOBAL_OPTIONS = T.let(
Homebrew::CLI::Parser.global_options.map do |short_option, long_option, _|
[short_option, long_option].map { "#{Homebrew::CLI::Parser.option_to_name(it)}?" }
end.flatten.freeze, T::Array[String]
)
Parsable = T.type_alias { T.any(T.class_of(Homebrew::CLI::Args), T.class_of(Homebrew::AbstractCommand)) }
ConstantType = type_member { { fixed: Parsable } }
sig { override.returns(T::Enumerable[Parsable]) }
def self.gather_constants
# require all the commands to ensure the command subclasses are defined
["cmd", "dev-cmd"].each do |dir|
Dir[File.join(__dir__, "../../../#{dir}", "*.rb")].each { require(it) }
end
Homebrew::AbstractCommand.subclasses
end
sig { override.void }
def decorate
cmd = T.cast(constant, T.class_of(Homebrew::AbstractCommand))
# This is a dummy class to make the `brew` command parsable
return if cmd == Homebrew::Cmd::Brew
args_class_name = T.must(T.must(cmd.args_class).name)
root.create_class(args_class_name, superclass_name: "Homebrew::CLI::Args") do |klass|
create_args_methods(klass, cmd.parser)
end
root.create_path(constant) do |klass|
klass.create_method("args", return_type: args_class_name)
end
end
sig { params(parser: Homebrew::CLI::Parser).returns(T::Array[Symbol]) }
def args_table(parser) = parser.args.methods(false)
sig { params(parser: Homebrew::CLI::Parser).returns(T::Array[Symbol]) }
def comma_arrays(parser)
parser.instance_variable_get(:@non_global_processed_options)
.filter_map { |k, v| parser.option_to_name(k).to_sym if v == :comma_array }
end
sig { params(method_name: Symbol, comma_array_methods: T::Array[Symbol]).returns(String) }
def get_return_type(method_name, comma_array_methods)
if comma_array_methods.include?(method_name)
"T.nilable(T::Array[String])"
elsif method_name.end_with?("?")
"T::Boolean"
else
"T.nilable(String)"
end
end
private
sig { params(klass: RBI::Scope, parser: Homebrew::CLI::Parser).void }
def create_args_methods(klass, parser)
comma_array_methods = comma_arrays(parser)
args_table(parser).each do |method_name|
method_name_str = method_name.to_s
next if GLOBAL_OPTIONS.include?(method_name_str)
return_type = get_return_type(method_name, comma_array_methods)
klass.create_method(method_name_str, return_type:)
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/sorbet/tapioca/compilers/rubocop_cask_ast_stanza.rb | Library/Homebrew/sorbet/tapioca/compilers/rubocop_cask_ast_stanza.rb | # typed: strict
# frozen_string_literal: true
require "method_source"
require "rubocop"
require_relative "../../../rubocops"
module Tapioca
module Compilers
class Stanza < Tapioca::Dsl::Compiler
ConstantType = type_member { { fixed: T::Module[T.anything] } }
sig { override.returns(T::Enumerable[T::Module[T.anything]]) }
def self.gather_constants = [::RuboCop::Cask::AST::Stanza]
sig { override.void }
def decorate
root.create_module(T.must(constant.name)) do |mod|
::RuboCop::Cask::Constants::STANZA_ORDER.each do |stanza|
mod.create_method("#{stanza}?", return_type: "T::Boolean", class_method: false)
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/sorbet/tapioca/compilers/forwardables.rb | Library/Homebrew/sorbet/tapioca/compilers/forwardables.rb | # typed: strict
# frozen_string_literal: true
require_relative "../../../global"
require "sorbet/tapioca/utils"
require "utils/ast"
module Tapioca
module Compilers
class Forwardables < Tapioca::Dsl::Compiler
FORWARDABLE_FILENAME = "forwardable.rb"
ARRAY_METHODS = T.let(["to_a", "to_ary"].freeze, T::Array[String])
HASH_METHODS = T.let(["to_h", "to_hash"].freeze, T::Array[String])
STRING_METHODS = T.let(["to_s", "to_str", "to_json"].freeze, T::Array[String])
# Use this to override the default return type of a forwarded method:
RETURN_TYPE_OVERRIDES = T.let({
"::Cask::Cask" => {
"on_system_block_min_os" => "T.nilable(MacOSVersion)",
"url" => "T.nilable(::Cask::URL)",
},
}.freeze, T::Hash[String, T::Hash[String, String]])
ConstantType = type_member { { fixed: T::Module[T.anything] } }
sig { override.returns(T::Enumerable[T::Module[T.anything]]) }
def self.gather_constants
Homebrew::Tapioca::Utils.named_objects_with_module(Forwardable).reject do |obj|
# Avoid duplicate stubs for forwardables that are defined in vendored gems
Object.const_source_location(T.must(obj.name))&.first&.include?("vendor/bundle/ruby")
end
end
sig { override.void }
def decorate
root.create_path(constant) do |klass|
Homebrew::Tapioca::Utils.methods_from_file(constant, FORWARDABLE_FILENAME)
.each { |method| compile_forwardable_method(klass, method) }
Homebrew::Tapioca::Utils.methods_from_file(constant, FORWARDABLE_FILENAME, class_methods: true)
.each { |method| compile_forwardable_method(klass, method, class_method: true) }
end
end
private
sig { params(klass: RBI::Scope, method: T.any(Method, UnboundMethod), class_method: T::Boolean).void }
def compile_forwardable_method(klass, method, class_method: false)
name = method.name.to_s
return_type = return_type(klass.to_s, name)
klass.create_method(
name,
parameters: [
create_rest_param("args", type: "T.untyped"),
create_block_param("block", type: "T.untyped"),
],
return_type:,
class_method:,
)
end
sig { params(klass: String, name: String).returns(String) }
def return_type(klass, name)
if (override = RETURN_TYPE_OVERRIDES.dig(klass, name)) then override
elsif name.end_with?("?") then "T::Boolean"
elsif ARRAY_METHODS.include?(name) then "Array"
elsif HASH_METHODS.include?(name) then "Hash"
elsif STRING_METHODS.include?(name) then "String"
else
"T.untyped"
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/sorbet/tapioca/compilers/env_config.rb | Library/Homebrew/sorbet/tapioca/compilers/env_config.rb | # typed: strict
# frozen_string_literal: true
require_relative "../../../global"
require "env_config"
module Tapioca
module Compilers
class EnvConfig < Tapioca::Dsl::Compiler
ConstantType = type_member { { fixed: T::Module[T.anything] } }
sig { override.returns(T::Enumerable[T::Module[T.anything]]) }
def self.gather_constants = [Homebrew::EnvConfig]
sig { override.void }
def decorate
root.create_module(T.must(constant.name)) do |mod|
dynamic_methods = {}
Homebrew::EnvConfig::ENVS.each do |env, hash|
next if Homebrew::EnvConfig::CUSTOM_IMPLEMENTATIONS.include?(env)
name = Homebrew::EnvConfig.env_method_name(env, hash)
dynamic_methods[name] = hash[:default]
end
dynamic_methods.each do |method, default|
return_type = if method.end_with?("?")
T::Boolean
elsif default
default.class
else
T.nilable(String)
end
mod.create_method(method, return_type:, class_method: true)
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/sorbet/tapioca/compilers/cask/config.rb | Library/Homebrew/sorbet/tapioca/compilers/cask/config.rb | # typed: strict
# frozen_string_literal: true
require_relative "../../../../global"
require "cask/config"
module Tapioca
module Compilers
class CaskConfig < Tapioca::Dsl::Compiler
ConstantType = type_member { { fixed: T::Module[T.anything] } }
sig { override.returns(T::Enumerable[T::Module[T.anything]]) }
def self.gather_constants = [Cask::Config]
sig { override.void }
def decorate
root.create_module("Cask") do |mod|
mod.create_class("Config") do |klass|
Cask::Config.defaults.each do |key, value|
return_type = if key == :languages
# :languages is a `LazyObject`, so it lazily evaluates to an
# array of strings when a method is called on it.
"T::Array[String]"
elsif key.end_with?("?")
"T::Boolean"
else
value.class.to_s
end
klass.create_method(key.to_s, return_type:, class_method: false)
end
end
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/update-license-data.rb | Library/Homebrew/dev-cmd/update-license-data.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "utils/spdx"
require "system_command"
module Homebrew
module DevCmd
class UpdateLicenseData < AbstractCommand
include SystemCommand::Mixin
cmd_args do
description <<~EOS
Update SPDX license data in the Homebrew repository.
EOS
named_args :none
end
sig { override.void }
def run
SPDX.download_latest_license_data!
diff = system_command "git", args: [
"-C", HOMEBREW_REPOSITORY, "diff", "--exit-code", SPDX::DATA_PATH
]
if diff.status.success?
ofail "No changes to SPDX license data."
else
puts "SPDX license data updated."
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/dev-cmd/unbottled.rb | Library/Homebrew/dev-cmd/unbottled.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "api"
require "os/mac/xcode"
module Homebrew
module DevCmd
class Unbottled < AbstractCommand
PORTABLE_FORMULAE = T.let(%w[
portable-libffi
portable-libxcrypt
portable-libyaml
portable-openssl
portable-ruby
portable-zlib
].freeze, T::Array[String])
cmd_args do
description <<~EOS
Show the unbottled dependents of formulae.
EOS
flag "--tag=",
description: "Use the specified bottle tag (e.g. `big_sur`) instead of the current OS."
switch "--dependents",
description: "Skip getting analytics data and sort by number of dependents instead."
switch "--total",
description: "Print the number of unbottled and total formulae."
switch "--lost",
description: "Print the `homebrew/core` commits where bottles were lost in the last week."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to check them.",
env: :eval_all
conflicts "--dependents", "--total", "--lost"
named_args :formula
end
sig { override.void }
def run
Formulary.enable_factory_cache!
@bottle_tag = T.let(
if (tag = args.tag)
Utils::Bottles::Tag.from_symbol(tag.to_sym)
else
Utils::Bottles.tag
end,
T.nilable(Utils::Bottles::Tag),
)
return unless @bottle_tag
if args.lost?
if args.named.present?
raise UsageError, "`brew unbottled --lost` cannot be used with formula arguments!"
elsif !CoreTap.instance.installed?
raise UsageError, "`brew unbottled --lost` requires `homebrew/core` to be tapped locally!"
else
output_lost_bottles
return
end
end
os = @bottle_tag.system
arch = if Hardware::CPU::INTEL_ARCHS.include?(@bottle_tag.arch)
:intel
elsif Hardware::CPU::ARM_ARCHS.include?(@bottle_tag.arch)
:arm
else
raise "Unknown arch #{@bottle_tag.arch}."
end
Homebrew::SimulateSystem.with(os:, arch:) do
eval_all = args.eval_all?
if args.total? && !eval_all
raise UsageError, "`brew unbottled --total` needs `--eval-all` passed or `HOMEBREW_EVAL_ALL=1` set!"
end
if args.named.blank?
ohai "Getting formulae..."
elsif eval_all
raise UsageError, "Cannot specify formulae when using `--eval-all`/`--total`."
end
formulae, all_formulae, formula_installs = formulae_all_installs_from_args(eval_all)
deps_hash, uses_hash = deps_uses_from_formulae(all_formulae)
if args.dependents?
formula_dependents = {}
formulae = formulae.sort_by do |f|
dependents = uses_hash[f.name]&.length || 0
formula_dependents[f.name] ||= dependents
end.reverse
elsif eval_all
output_total(formulae)
return
end
noun, hash = if args.named.present?
[nil, {}]
elsif args.dependents?
["dependents", formula_dependents]
else
["installs", formula_installs]
end
return if hash.nil?
output_unbottled(formulae, deps_hash, noun, hash, args.named.present?)
end
end
private
sig {
params(eval_all: T::Boolean).returns([T::Array[Formula], T::Array[Formula],
T.nilable(T::Hash[Symbol, Integer])])
}
def formulae_all_installs_from_args(eval_all)
if args.named.present?
formulae = all_formulae = args.named.to_formulae
elsif args.dependents?
unless eval_all
raise UsageError, "`brew unbottled --dependents` needs `--eval-all` passed or `HOMEBREW_EVAL_ALL=1` set!"
end
formulae = all_formulae = Formula.all(eval_all:)
@sort = T.let(" (sorted by number of dependents)", T.nilable(String))
elsif eval_all
formulae = all_formulae = Formula.all(eval_all:)
else
formula_installs = {}
ohai "Getting analytics data..."
analytics = Homebrew::API::Analytics.fetch "install", 90
if analytics.blank?
raise UsageError,
"default sort by analytics data requires " \
"`$HOMEBREW_NO_GITHUB_API` and `$HOMEBREW_NO_ANALYTICS` to be unset."
end
formulae = analytics["items"].filter_map do |i|
f = i["formula"].split.first
next if f.include?("/")
next if formula_installs[f].present?
formula_installs[f] = i["count"]
begin
Formula[f]
rescue FormulaUnavailableError
nil
end
end
@sort = T.let(" (sorted by installs in the last 90 days; top 10,000 only)", T.nilable(String))
all_formulae = Formula.all(eval_all:)
end
# Remove deprecated and disabled formulae as we do not care if they are unbottled
formulae = Array(formulae).reject { |f| f.deprecated? || f.disabled? } if formulae.present?
all_formulae = Array(all_formulae).reject { |f| f.deprecated? || f.disabled? } if all_formulae.present?
# Remove portable formulae as they are are handled differently
formulae = formulae.reject { |f| PORTABLE_FORMULAE.include?(f.name) } if formulae.present?
all_formulae = all_formulae.reject { |f| PORTABLE_FORMULAE.include?(f.name) } if all_formulae.present?
[T.let(formulae, T::Array[Formula]), T.let(all_formulae, T::Array[Formula]),
T.let(formula_installs, T.nilable(T::Hash[Symbol, Integer]))]
end
sig {
params(all_formulae: T::Array[Formula]).returns([T::Hash[String, T.untyped], T::Hash[String, T.untyped]])
}
def deps_uses_from_formulae(all_formulae)
ohai "Populating dependency tree..."
deps_hash = {}
uses_hash = {}
all_formulae.each do |f|
deps = Dependency.expand(f, cache_key: "unbottled") do |_, dep|
Dependency.prune if dep.optional?
end.map(&:to_formula)
deps_hash[f.name] = deps
deps.each do |dep|
uses_hash[dep.name] ||= []
uses_hash[dep.name] << f
end
end
[deps_hash, uses_hash]
end
sig { params(formulae: T::Array[Formula]).void }
def output_total(formulae)
return unless @bottle_tag
ohai "Unbottled :#{@bottle_tag} formulae"
unbottled_formulae = formulae.count do |f|
!f.bottle_specification.tag?(@bottle_tag, no_older_versions: true)
end
puts "#{unbottled_formulae}/#{formulae.length} remaining."
end
sig {
params(formulae: T::Array[Formula], deps_hash: T::Hash[T.any(Symbol, String), T.untyped],
noun: T.nilable(String), hash: T::Hash[T.any(Symbol, String), T.untyped],
any_named_args: T::Boolean).void
}
def output_unbottled(formulae, deps_hash, noun, hash, any_named_args)
return unless @bottle_tag
ohai ":#{@bottle_tag} bottle status#{@sort}"
any_found = T.let(false, T::Boolean)
formulae.each do |f|
name = f.name.downcase
if f.disabled?
puts "#{Tty.bold}#{Tty.green}#{name}#{Tty.reset}: formula disabled" if any_named_args
next
end
requirements = f.recursive_requirements
if @bottle_tag.linux?
if requirements.any? { |r| r.is_a?(MacOSRequirement) && !r.version }
puts "#{Tty.bold}#{Tty.red}#{name}#{Tty.reset}: requires macOS" if any_named_args
next
elsif requirements.any? { |r| r.is_a?(ArchRequirement) && r.arch != @bottle_tag.arch }
if any_named_args
puts "#{Tty.bold}#{Tty.red}#{name}#{Tty.reset}: doesn't support #{@bottle_tag.arch} Linux"
end
next
end
elsif requirements.any?(LinuxRequirement)
puts "#{Tty.bold}#{Tty.red}#{name}#{Tty.reset}: requires Linux" if any_named_args
next
else
macos_version = @bottle_tag.to_macos_version
macos_satisfied = requirements.all? do |r|
case r
when MacOSRequirement
next true unless r.version_specified?
macos_version.compare(r.comparator, r.version)
when XcodeRequirement
next true unless r.version
Version.new(::OS::Mac::Xcode.latest_version(macos: macos_version)) >= r.version
when ArchRequirement
r.arch == @bottle_tag.arch
else
true
end
end
unless macos_satisfied
puts "#{Tty.bold}#{Tty.red}#{name}#{Tty.reset}: doesn't support this macOS" if any_named_args
next
end
end
if f.bottle_specification.tag?(@bottle_tag, no_older_versions: true)
puts "#{Tty.bold}#{Tty.green}#{name}#{Tty.reset}: already bottled" if any_named_args
next
end
deps = Array(deps_hash[f.name]).reject do |dep|
dep.bottle_specification.tag?(@bottle_tag, no_older_versions: true)
end
if deps.blank?
count = " (#{hash[f.name]} #{noun})" if noun
puts "#{Tty.bold}#{Tty.green}#{name}#{Tty.reset}#{count}: ready to bottle"
next
end
any_found ||= true
count = " (#{hash[f.name]} #{noun})" if noun
puts "#{Tty.bold}#{Tty.yellow}#{name}#{Tty.reset}#{count}: unbottled deps: #{deps.join(" ")}"
end
return if any_found
return if any_named_args
puts "No unbottled dependencies found!"
end
sig { void }
def output_lost_bottles
ohai ":#{@bottle_tag} lost bottles"
bottle_tag_regex_fragment = " +sha256.* #{@bottle_tag}: "
# $ git log --patch --no-ext-diff -G'^ +sha256.* sonoma:' --since=@{'1 week ago'}
git_log = %w[git log --patch --no-ext-diff]
git_log << "-G^#{bottle_tag_regex_fragment}"
git_log << "--since=@{'1 week ago'}"
bottle_tag_sha_regex = /^[+-]#{bottle_tag_regex_fragment}/
processed_formulae = Set.new
commit = T.let(nil, T.nilable(String))
formula = T.let(nil, T.nilable(String))
lost_bottles = 0
CoreTap.instance.path.cd do
Utils.safe_popen_read(*git_log) do |io|
io.each_line do |line|
case line
when /^commit [0-9a-f]{40}$/
# Example match: `commit 7289b409b96a752540befef1a56b8a818baf1db7`
if commit && formula && lost_bottles.positive? && processed_formulae.exclude?(formula)
puts "#{commit}: bottle lost for #{formula}"
end
processed_formulae << formula
commit = line.split.last
formula = nil
when %r{^diff --git a/Formula/}
# Example match: `diff --git a/Formula/a/aws-cdk.rb b/Formula/a/aws-cdk.rb`
formula = line.split("/").last.chomp(".rb\n")
formula = CoreTap.instance.formula_renames.fetch(formula, formula)
lost_bottles = 0
when bottle_tag_sha_regex
# Example match: `- sha256 cellar: :any_skip_relocation, sonoma: "f0a4..."`
next if processed_formulae.include?(formula)
case line.chr
when "+" then lost_bottles -= 1
when "-" then lost_bottles += 1
end
when /^[+] +sha256.* all: /
# Example match: `+ sha256 cellar: :any_skip_relocation, all: "9e35..."`
lost_bottles -= 1
end
end
end
end
return if !commit || !formula || !lost_bottles.positive? || processed_formulae.include?(formula)
puts "#{commit}: bottle lost for #{formula}"
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/dev-cmd/rubocop.rb | Library/Homebrew/dev-cmd/rubocop.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "shell_command"
module Homebrew
module DevCmd
class Rubocop < AbstractCommand
include ShellCommand
cmd_args do
description <<~EOS
Installs, configures and runs Homebrew's `rubocop`.
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/test.rb | Library/Homebrew/dev-cmd/test.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "extend/ENV"
require "sandbox"
require "timeout"
module Homebrew
module DevCmd
class Test < AbstractCommand
cmd_args do
description <<~EOS
Run the test method provided by an installed formula.
There is no standard output or return code, but generally it should notify the
user if something is wrong with the installed formula.
*Example:* `brew install jruby && brew test jruby`
EOS
switch "-f", "--force",
description: "Test formulae even if they are unlinked."
switch "--HEAD",
description: "Test the HEAD version of a formula."
switch "--keep-tmp",
description: "Retain the temporary files created for the test."
switch "--retry",
description: "Retry if a testing fails."
named_args :installed_formula, min: 1, without_api: true
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["formula_test"], setup_path: false)
require "formula_assertions"
require "formula_free_port"
require "utils/fork"
args.named.to_resolved_formulae.each do |f|
# Cannot test uninstalled formulae
unless f.latest_version_installed?
ofail "Testing requires the latest version of #{f.full_name}"
next
end
# Cannot test formulae without a test method
unless f.test_defined?
ofail "#{f.full_name} defines no test"
next
end
# Don't test unlinked formulae
if !args.force? && !f.keg_only? && !f.linked?
ofail "#{f.full_name} is not linked"
next
end
# Don't test formulae missing test dependencies
missing_test_deps = f.recursive_dependencies do |dependent, dependency|
Dependency.prune if dependency.installed?
next if dependency.test? && dependent == f
Dependency.prune unless dependency.required?
end.map(&:to_s)
unless missing_test_deps.empty?
ofail "#{f.full_name} is missing test dependencies: #{missing_test_deps.join(" ")}"
next
end
oh1 "Testing #{f.full_name}"
env = ENV.to_hash
begin
exec_args = HOMEBREW_RUBY_EXEC_ARGS + %W[
--
#{HOMEBREW_LIBRARY_PATH}/test.rb
#{f.path}
].concat(args.options_only)
exec_args << "--HEAD" if f.head?
if Sandbox.available?
sandbox = Sandbox.new
f.logs.mkpath
sandbox.record_log(f.logs/"test.sandbox.log")
sandbox.allow_write_temp_and_cache
sandbox.allow_write_log(f)
sandbox.allow_write_xcode
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/cache")
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/homebrew/locks")
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/log")
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/run")
sandbox.deny_all_network unless f.class.network_access_allowed?(:test)
sandbox.run(*exec_args)
else
Utils.safe_fork do
exec(*exec_args)
end
end
# Rescue any possible exception types.
rescue Exception => e # rubocop:disable Lint/RescueException
retry if retry_test?(f)
require "utils/backtrace"
ofail "#{f.full_name}: failed"
$stderr.puts e, Utils::Backtrace.clean(e)
ensure
ENV.replace(env)
end
end
end
private
sig { params(formula: Formula).returns(T::Boolean) }
def retry_test?(formula)
@test_failed ||= T.let(Set.new, T.nilable(T::Set[T.untyped]))
if args.retry? && @test_failed.add?(formula)
oh1 "Testing #{formula.full_name} (again)"
formula.clear_cache
ENV["RUST_BACKTRACE"] = "full"
true
else
Homebrew.failed = true
false
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/dev-cmd/extract.rb | Library/Homebrew/dev-cmd/extract.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "utils/git"
require "formulary"
require "software_spec"
require "tap"
module Homebrew
module DevCmd
class Extract < AbstractCommand
BOTTLE_BLOCK_REGEX = / bottle (?:do.+?end|:[a-z]+)\n\n/m
cmd_args do
usage_banner "`extract` [`--version=`] [`--git-revision=`] [`--force`] <formula> <tap>"
description <<~EOS
Look through repository history to find the most recent version of <formula> and
create a copy in <tap>. Specifically, the command will create the new
formula file at <tap>`/Formula/`<formula>`@`<version>`.rb`. If the tap is not
installed yet, attempt to install/clone the tap before continuing. To extract
a formula from a tap that is not `homebrew/core` use its fully-qualified form of
<user>`/`<repo>`/`<formula>.
EOS
flag "--git-revision=",
description: "Search for the specified <version> of <formula> starting at <revision> instead of HEAD."
flag "--version=",
description: "Extract the specified <version> of <formula> instead of the most recent."
switch "-f", "--force",
description: "Overwrite the destination formula if it already exists."
named_args [:formula, :tap], number: 2, without_api: true
end
sig { override.void }
def run
if (tap_with_name = args.named.first&.then { Tap.with_formula_name(it) })
source_tap, name = tap_with_name
else
name = args.named.fetch(0).downcase
source_tap = CoreTap.instance
end
raise TapFormulaUnavailableError.new(source_tap, name) unless source_tap.installed?
destination_tap = Tap.fetch(args.named.fetch(1))
unless Homebrew::EnvConfig.developer?
odie "Cannot extract formula to homebrew/core!" if destination_tap.core_tap?
odie "Cannot extract formula to homebrew/cask!" if destination_tap.core_cask_tap?
odie "Cannot extract formula to the same tap!" if destination_tap == source_tap
end
destination_tap.install unless destination_tap.installed?
repo = source_tap.path
start_rev = args.git_revision || "HEAD"
pattern = if source_tap.core_tap?
[source_tap.new_formula_path(name), repo/"Formula/#{name}.rb"].uniq
else
# A formula can technically live in the root directory of a tap or in any of its subdirectories
[repo/"#{name}.rb", repo/"**/#{name}.rb"]
end
rev = T.let(nil, T.nilable(String))
if args.version
ohai "Searching repository history"
version = args.version
version_segments = Gem::Version.new(version).segments if Gem::Version.correct?(version)
test_formula = T.let(nil, T.nilable(Formula))
result = ""
loop do
rev = rev.nil? ? start_rev : "#{rev}~1"
rev, (path,) = Utils::Git.last_revision_commit_of_files(repo, pattern, before_commit: rev)
if rev.nil? && source_tap.shallow?
odie <<~EOS
Could not find #{name} but #{source_tap} is a shallow clone!
Try again after running:
git -C "#{source_tap.path}" fetch --unshallow
EOS
elsif rev.nil?
odie "Could not find #{name}! The formula or version may not have existed."
end
file = repo/T.must(path)
result = Utils::Git.last_revision_of_file(repo, file, before_commit: rev)
if result.empty?
odebug "Skipping revision #{rev} - file is empty at this revision"
next
end
test_formula = formula_at_revision(repo, name, file, rev)
break if test_formula.nil? || test_formula.version == version
if version_segments && Gem::Version.correct?(test_formula.version)
test_formula_version_segments = Gem::Version.new(test_formula.version).segments
if version_segments.length < test_formula_version_segments.length
odebug "Apply semantic versioning with #{test_formula_version_segments}"
break if version_segments == test_formula_version_segments.first(version_segments.length)
end
end
odebug "Trying #{test_formula.version} from revision #{rev} against desired #{version}"
end
odie "Could not find #{name}! The formula or version may not have existed." if test_formula.nil?
else
# Search in the root directory of `repository` as well as recursively in all of its subdirectories.
files = if start_rev == "HEAD"
Dir[repo/"{,**/}"].filter_map do |dir|
Pathname.glob("#{dir}/#{name}.rb").find(&:file?)
end
else
[]
end
if files.empty?
ohai "Searching repository history"
rev, (path,) = Utils::Git.last_revision_commit_of_files(repo, pattern, before_commit: start_rev)
odie "Could not find #{name}! The formula or version may not have existed." if rev.nil?
file = repo/T.must(path)
version = T.must(formula_at_revision(repo, name, file, rev)).version
result = Utils::Git.last_revision_of_file(repo, file)
else
file = files.fetch(0).realpath
rev = T.let("HEAD", T.nilable(String))
version = Formulary.factory(file).version
result = File.read(file)
end
end
# The class name has to be renamed to match the new filename,
# e.g. Foo version 1.2.3 becomes FooAT123 and resides in Foo@1.2.3.rb.
class_name = Formulary.class_s(name)
# The version can only contain digits with decimals in between.
version_string = version.to_s
.sub(/\D*(.+?)\D*$/, "\\1")
.gsub(/\D+/, ".")
# Remove any existing version suffixes, as a new one will be added later.
name.sub!(/\b@(.*)\z\b/i, "")
versioned_name = Formulary.class_s("#{name}@#{version_string}")
result.sub!("class #{class_name} < Formula", "class #{versioned_name} < Formula")
# Remove bottle blocks, as they won't work.
result.sub!(BOTTLE_BLOCK_REGEX, "")
path = destination_tap.path/"Formula/#{name}@#{version_string}.rb"
if path.exist?
unless args.force?
odie <<~EOS
Destination formula already exists: #{path}
To overwrite it and continue anyways, run:
brew extract --force --version=#{version} #{name} #{destination_tap.name}
EOS
end
odebug "Overwriting existing formula at #{path}"
path.delete
end
ohai "Writing formula for #{name} at #{version} from revision #{rev} to:", path
path.dirname.mkpath
path.write result
end
private
sig { params(repo: Pathname, name: String, file: Pathname, rev: String).returns(T.nilable(Formula)) }
def formula_at_revision(repo, name, file, rev)
return if rev.empty?
contents = Utils::Git.last_revision_of_file(repo, file, before_commit: rev)
contents.gsub!("@url=", "url ")
contents.gsub!("require 'brewkit'", "require 'formula'")
contents.sub!(BOTTLE_BLOCK_REGEX, "")
with_monkey_patch { Formulary.from_contents(name, file, contents, ignore_errors: true) }
end
sig { params(_block: T.proc.void).returns(T.untyped) }
def with_monkey_patch(&_block)
# Since `method_defined?` is not a supported type guard, the use of `alias_method` below is not typesafe:
BottleSpecification.class_eval do
T.unsafe(self).alias_method :old_method_missing, :method_missing if method_defined?(:method_missing)
define_method(:method_missing) do |*_|
# do nothing
end
end
Module.class_eval do
T.unsafe(self).alias_method :old_method_missing, :method_missing if method_defined?(:method_missing)
define_method(:method_missing) do |*_|
# do nothing
end
end
Resource.class_eval do
T.unsafe(self).alias_method :old_method_missing, :method_missing if method_defined?(:method_missing)
define_method(:method_missing) do |*_|
# do nothing
end
end
DependencyCollector.class_eval do
if method_defined?(:parse_symbol_spec)
T.unsafe(self).alias_method :old_parse_symbol_spec,
:parse_symbol_spec
end
define_method(:parse_symbol_spec) do |*_|
# do nothing
end
end
yield
ensure
BottleSpecification.class_eval do
if method_defined?(:old_method_missing)
T.unsafe(self).alias_method :method_missing, :old_method_missing
T.unsafe(self).undef :old_method_missing
end
end
Module.class_eval do
if method_defined?(:old_method_missing)
T.unsafe(self).alias_method :method_missing, :old_method_missing
T.unsafe(self).undef :old_method_missing
end
end
Resource.class_eval do
if method_defined?(:old_method_missing)
T.unsafe(self).alias_method :method_missing, :old_method_missing
T.unsafe(self).undef :old_method_missing
end
end
DependencyCollector.class_eval do
if method_defined?(:old_parse_symbol_spec)
T.unsafe(self).alias_method :parse_symbol_spec, :old_parse_symbol_spec
T.unsafe(self).undef :old_parse_symbol_spec
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/dev-cmd/install-bundler-gems.rb | Library/Homebrew/dev-cmd/install-bundler-gems.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module DevCmd
class InstallBundlerGems < AbstractCommand
cmd_args do
description <<~EOS
Install Homebrew's Bundler gems.
EOS
comma_array "--groups",
description: "Installs the specified comma-separated list of gem groups (default: last used). " \
"Replaces any previously installed groups."
comma_array "--add-groups",
description: "Installs the specified comma-separated list of gem groups, " \
"in addition to those already installed."
conflicts "--groups", "--add-groups"
named_args :none
end
sig { override.void }
def run
groups = args.groups || args.add_groups || []
if groups.delete("all")
groups |= Homebrew.valid_gem_groups
elsif args.groups # if we have been asked to replace
Homebrew.forget_user_gem_groups!
end
Homebrew.install_bundler_gems!(groups:)
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/dev-cmd/contributions.rb | Library/Homebrew/dev-cmd/contributions.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module DevCmd
class Contributions < AbstractCommand
PRIMARY_REPOS = T.let(%w[
Homebrew/brew
Homebrew/homebrew-core
Homebrew/homebrew-cask
].freeze, T::Array[String])
CONTRIBUTION_TYPES = T.let({
merged_pr_author: "merged PR author",
approved_pr_review: "approved PR reviewer",
committer: "commit author or committer",
coauthor: "commit coauthor",
}.freeze, T::Hash[Symbol, String])
MAX_COMMITS = T.let(1000, Integer)
MAX_PR_SEARCH = T.let(100, Integer)
cmd_args do
usage_banner "`contributions` [`--user=`] [`--repositories=`] [`--quarter=`] [`--from=`] [`--to=`] [`--csv`]"
description <<~EOS
Summarise contributions to Homebrew repositories.
EOS
comma_array "--user=",
description: "Specify a comma-separated list of GitHub usernames or email addresses to find " \
"contributions from. Omitting this flag searches Homebrew maintainers."
comma_array "--repositories",
description: "Specify a comma-separated list of repositories to search. " \
"All repositories must be under the same user or organisation. " \
"Omitting this flag, or specifying `--repositories=primary`, searches only the " \
"main repositories: `Homebrew/brew`, `Homebrew/homebrew-core`, " \
"`Homebrew/homebrew-cask`."
flag "--organisation=", "--organization=", "--org=",
description: "Specify the organisation to populate sources repositories from. " \
"Omitting this flag searches the Homebrew primary repositories."
flag "--team=",
description: "Specify the team to populate users from. " \
"The first part of the team name will be used as the organisation."
flag "--quarter=",
description: "Homebrew contributions quarter to search (1-4). " \
"Omitting this flag searches the past year. " \
"If `--from` or `--to` are set, they take precedence."
flag "--from=",
description: "Date (ISO 8601 format) to start searching contributions. " \
"Omitting this flag searches the past year."
flag "--to=",
description: "Date (ISO 8601 format) to stop searching contributions."
switch "--csv",
description: "Print a CSV of contributions across repositories over the time period."
conflicts "--organisation", "--repositories"
conflicts "--organisation", "--team"
conflicts "--user", "--team"
end
sig { override.void }
def run
odie "Cannot get contributions as `$HOMEBREW_NO_GITHUB_API` is set!" if Homebrew::EnvConfig.no_github_api?
Homebrew.install_bundler_gems!(groups: ["contributions"]) if args.csv?
require "utils/github"
results = {}
grand_totals = {}
quarter = args.quarter.presence.to_i
odie "Value for `--quarter` must be between 1 and 4." if args.quarter.present? && !quarter.between?(1, 4)
from = args.from.presence || quarter_dates[quarter]&.first || Date.today.prev_year.iso8601
to = args.to.presence || quarter_dates[quarter]&.last || (Date.today + 1).iso8601
puts "Date range is #{time_period(from:, to:)}." if args.verbose?
organisation = nil
users = if (team = args.team.presence)
team_sections = team.split("/")
organisation = team_sections.first.presence
team_name = team_sections.last.presence
if team_sections.length != 2 || organisation.nil? || team_name.nil?
odie "Team must be in the format `organisation/team`!"
end
puts "Getting members for #{organisation}/#{team_name}..." if args.verbose?
GitHub.members_by_team(organisation, team_name).keys
elsif (users = args.user.presence)
users
else
puts "Getting members for Homebrew/maintainers..." if args.verbose?
GitHub.members_by_team("Homebrew", "maintainers").keys
end
repositories = if (org = organisation.presence) || (org = args.organisation.presence)
organisation = org
puts "Getting repositories for #{organisation}..." if args.verbose?
GitHub.organisation_repositories(organisation, from, to, args.verbose?)
elsif (repos = args.repositories.presence) && repos.length == 1 && (first_repository = repos.first)
case first_repository
when "primary"
PRIMARY_REPOS
else
Array(first_repository)
end
elsif (repos = args.repositories.presence)
organisations = repos.map { |repository| repository.split("/").first }.uniq
odie "All repositories must be under the same user or organisation!" if organisations.length > 1
repos
else
PRIMARY_REPOS
end
organisation ||= T.must(repositories.fetch(0).split("/").first)
users.each do |username|
# TODO: Using the GitHub username to scan the `git log` undercounts some
# contributions as people might not always have configured their Git
# committer details to match the ones on GitHub.
# TODO: Switch to using the GitHub APIs instead of `git log` if
# they ever support trailers.
results[username] = scan_repositories(organisation, repositories, username, from:, to:)
grand_totals[username] = total(results[username])
search_types = [:merged_pr_author, :approved_pr_review].freeze
greater_than_total = T.let(false, T::Boolean)
contributions = CONTRIBUTION_TYPES.keys.filter_map do |type|
type_count = grand_totals[username][type]
next if type_count.nil? || type_count.zero?
count_prefix = ""
if (search_types.include?(type) && type_count == MAX_PR_SEARCH) ||
(type == :committer && type_count == MAX_COMMITS)
greater_than_total ||= true
count_prefix = ">="
end
pretty_type = CONTRIBUTION_TYPES.fetch(type)
"#{count_prefix}#{Utils.pluralize("time", type_count, include_count: true)} (#{pretty_type})"
end
total = Utils.pluralize("time", grand_totals[username].values.sum, include_count: true)
total_prefix = ">=" if greater_than_total
contributions << "#{total_prefix}#{total} (total)"
contributions_string = [
"#{username} contributed",
*contributions.to_sentence,
"#{time_period(from:, to:)}.",
].join(" ")
if args.csv?
$stderr.puts contributions_string
else
puts contributions_string
end
end
return unless args.csv?
$stderr.puts
puts generate_csv(grand_totals)
end
private
sig { params(repository: String).returns([T.nilable(Pathname), T.nilable(Tap)]) }
def repository_path_and_tap(repository)
return [HOMEBREW_REPOSITORY, nil] if repository == "Homebrew/brew"
return [nil, nil] if repository.exclude?("/homebrew-")
require "tap"
tap = Tap.fetch(repository)
return [nil, nil] if tap.user == "Homebrew" && DEPRECATED_OFFICIAL_TAPS.include?(tap.repository)
[tap.path, tap]
end
sig { params(from: T.nilable(String), to: T.nilable(String)).returns(String) }
def time_period(from:, to:)
if from && to
"between #{from} and #{to}"
elsif from
"after #{from}"
elsif to
"before #{to}"
else
"in all time"
end
end
sig { params(totals: T::Hash[String, T::Hash[Symbol, Integer]]).returns(String) }
def generate_csv(totals)
require "csv"
CSV.generate do |csv|
csv << ["user", "repository", *CONTRIBUTION_TYPES.keys, "total"]
totals.sort_by { |_, v| -v.values.sum }.each do |user, total|
csv << grand_total_row(user, total)
end
end
end
sig { params(user: String, grand_total: T::Hash[Symbol, Integer]).returns(T::Array[T.any(String, T.nilable(Integer))]) }
def grand_total_row(user, grand_total)
grand_totals = grand_total.slice(*CONTRIBUTION_TYPES.keys).values
[user, "all", *grand_totals, grand_totals.sum]
end
sig {
params(
organisation: String,
repositories: T::Array[String],
person: String,
from: String,
to: String,
).returns(T::Hash[Symbol, T.untyped])
}
def scan_repositories(organisation, repositories, person, from:, to:)
data = {}
return data if repositories.blank?
require "utils/github"
max = MAX_COMMITS
verbose = args.verbose?
puts "Querying pull requests for #{person} in #{organisation}..." if args.verbose?
organisation_merged_prs =
GitHub.search_merged_pull_requests_in_user_or_organisation(organisation, person, from:, to:)
organisation_approved_reviews =
GitHub.search_approved_pull_requests_in_user_or_organisation(organisation, person, from:, to:)
require "utils/git"
repositories.each do |repository|
repository_path, tap = repository_path_and_tap(repository)
if repository_path && tap && !repository_path.exist?
opoo "Repository #{repository} not yet tapped! Tapping it now..."
tap.install(force: true)
end
repository_full_name = tap&.full_name
repository_full_name ||= repository
repository_api_url = "#{GitHub::API_URL}/repos/#{repository_full_name}"
puts "Determining contributions for #{person} on #{repository_full_name}..." if args.verbose?
merged_pr_author = organisation_merged_prs.count do |pr|
pr.fetch("repository_url") == repository_api_url
end
approved_pr_review = organisation_approved_reviews.count do |pr|
pr.fetch("repository_url") == repository_api_url
end
committer = GitHub.count_repository_commits(repository_full_name, person, max:, verbose:, from:, to:)
coauthor = Utils::Git.count_coauthors(repository_path, person, from:, to:)
data[repository] = { merged_pr_author:, approved_pr_review:, committer:, coauthor: }
rescue GitHub::API::RateLimitExceededError => e
sleep_seconds = e.reset - Time.now.to_i
opoo "GitHub rate limit exceeded, sleeping for #{sleep_seconds} seconds..."
sleep sleep_seconds
retry
end
data
end
sig { params(results: T::Hash[Symbol, T.untyped]).returns(T::Hash[Symbol, Integer]) }
def total(results)
totals = {}
results.each_value do |counts|
counts.each do |kind, count|
totals[kind] ||= 0
totals[kind] += count
end
end
totals
end
sig { returns(T::Hash[Integer, T::Array[String]]) }
def quarter_dates
# These aren't standard quarterly dates. We've chosen our own so that we
# can use recent maintainer activity stats as part of checking
# eligibility for expensed attendance at the AGM in February each year.
current_year = Date.today.year
last_year = current_year - 1
{
1 => [Date.new(last_year, 12, 1).iso8601, Date.new(current_year, 3, 1).iso8601],
2 => [Date.new(current_year, 3, 1).iso8601, Date.new(current_year, 6, 1).iso8601],
3 => [Date.new(current_year, 6, 1).iso8601, Date.new(current_year, 9, 1).iso8601],
4 => [Date.new(current_year, 9, 1).iso8601, Date.new(current_year, 12, 1).iso8601],
}
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/dev-cmd/bump-cask-pr.rb | Library/Homebrew/dev-cmd/bump-cask-pr.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "bump_version_parser"
require "cask"
require "cask/download"
require "utils/tar"
module Homebrew
module DevCmd
class BumpCaskPr < AbstractCommand
cmd_args do
description <<~EOS
Create a pull request to update <cask> with a new version.
A best effort to determine the <SHA-256> will be made if the value is not
supplied by the user.
EOS
switch "-n", "--dry-run",
description: "Print what would be done rather than doing it."
switch "--write-only",
description: "Make the expected file modifications without taking any Git actions."
switch "--commit",
depends_on: "--write-only",
description: "When passed with `--write-only`, generate a new commit after writing changes " \
"to the cask file."
switch "--no-audit",
description: "Don't run `brew audit` before opening the PR."
switch "--no-style",
description: "Don't run `brew style --fix` before opening the PR."
switch "--no-browse",
description: "Print the pull request URL instead of opening in a browser."
switch "--no-fork",
description: "Don't try to fork the repository."
flag "--version=",
description: "Specify the new <version> for the cask."
flag "--version-arm=",
description: "Specify the new cask <version> for the ARM architecture."
flag "--version-intel=",
description: "Specify the new cask <version> for the Intel architecture."
flag "--message=",
description: "Prepend <message> to the default pull request message."
flag "--url=",
description: "Specify the <URL> for the new download."
flag "--sha256=",
description: "Specify the <SHA-256> checksum of the new download."
flag "--fork-org=",
description: "Use the specified GitHub organization for forking."
conflicts "--dry-run", "--write"
conflicts "--version", "--version-arm"
conflicts "--version", "--version-intel"
named_args :cask, number: 1, without_api: true
end
sig { override.void }
def run
# This will be run by `brew audit` or `brew style` later so run it first to
# not start spamming during normal output.
gem_groups = []
gem_groups << "style" if !args.no_audit? || !args.no_style?
gem_groups << "audit" unless args.no_audit?
Homebrew.install_bundler_gems!(groups: gem_groups) unless gem_groups.empty?
# As this command is simplifying user-run commands then let's just use a
# user path, too.
ENV["PATH"] = PATH.new(ORIGINAL_PATHS).to_s
# Use the user's browser, too.
ENV["BROWSER"] = EnvConfig.browser
@cask_retried = T.let(false, T.nilable(T::Boolean))
cask = begin
args.named.to_casks.fetch(0)
rescue Cask::CaskUnavailableError
raise if @cask_retried
CoreCaskTap.instance.install(force: true)
@cask_retried = true
retry
end
odie "This cask is not in a tap!" if cask.tap.blank?
odie "This cask's tap is not a Git repository!" unless cask.tap.git?
odie <<~EOS unless cask.tap.allow_bump?(cask.token)
Whoops, the #{cask.token} cask has its version update
pull requests automatically opened by BrewTestBot every ~3 hours!
We'd still love your contributions, though, so try another one
that is excluded from autobump list (i.e. it has 'no_autobump!'
method or 'livecheck' block with 'skip'.)
EOS
if !args.write_only? && GitHub.too_many_open_prs?(cask.tap)
odie "You have too many PRs open: close or merge some first!"
end
new_version = BumpVersionParser.new(
general: args.version,
intel: args.version_intel,
arm: args.version_arm,
)
new_hash = unless (new_hash = args.sha256).nil?
raise UsageError, "`--sha256` must not be empty." if new_hash.blank?
["no_check", ":no_check"].include?(new_hash) ? :no_check : new_hash
end
new_base_url = unless (new_base_url = args.url).nil?
raise UsageError, "`--url` must not be empty." if new_base_url.blank?
begin
URI(new_base_url)
rescue URI::InvalidURIError
raise UsageError, "`--url` is not valid."
end
end
if new_version.blank? && new_base_url.nil? && new_hash.nil?
raise UsageError, "No `--version`, `--url` or `--sha256` argument specified!"
end
check_pull_requests(cask, new_version:) unless args.write_only?
replacement_pairs ||= []
branch_name = "bump-#{cask.token}"
commit_message = nil
old_contents = File.read(cask.sourcefile_path)
if new_base_url
commit_message ||= "#{cask.token}: update URL"
m = /^ +url "(.+?)"\n/m.match(old_contents)
odie "Could not find old URL in cask!" if m.nil?
old_base_url = m.captures.fetch(0)
replacement_pairs << [
/#{Regexp.escape(old_base_url)}/,
new_base_url.to_s,
]
end
if new_version.present?
# For simplicity, our naming defers to the arm version if multiple architectures are specified
branch_version = new_version.arm || new_version.general
if branch_version.is_a?(Cask::DSL::Version)
commit_version = shortened_version(branch_version, cask:)
branch_name = "bump-#{cask.token}-#{branch_version.tr(",:", "-")}"
commit_message ||= "#{cask.token} #{commit_version}"
end
replacement_pairs = replace_version_and_checksum(cask, new_hash, new_version, replacement_pairs)
end
# Now that we have all replacement pairs, we will replace them further down
commit_message ||= "#{cask.token}: update checksum" if new_hash
# Remove nested arrays where elements are identical
replacement_pairs = replacement_pairs.reject { |pair| pair[0] == pair[1] }.uniq.compact
Utils::Inreplace.inreplace_pairs(cask.sourcefile_path,
replacement_pairs,
read_only_run: args.dry_run?,
silent: args.quiet?)
audit_exceptions = []
audit_exceptions << "min_os" if ENV["HOMEBREW_TEST_BOT_AUTOBUMP"].present?
run_cask_audit(cask, old_contents, audit_exceptions)
run_cask_style(cask, old_contents)
pr_info = {
commits: [{
commit_message:,
old_contents:,
sourcefile_path: cask.sourcefile_path,
}],
branch_name:,
pr_message: "Created with `brew bump-cask-pr`.",
tap: cask.tap,
pr_title: commit_message,
}
GitHub.create_bump_pr(pr_info, args:)
end
private
sig { params(version: Cask::DSL::Version, cask: Cask::Cask).returns(Cask::DSL::Version) }
def shortened_version(version, cask:)
if version.before_comma == cask.version.before_comma
version
else
version.before_comma
end
end
sig { params(cask: Cask::Cask).returns(T::Array[[Symbol, Symbol]]) }
def generate_system_options(cask)
current_os = Homebrew::SimulateSystem.current_os
current_os_is_macos = MacOSVersion::SYMBOLS.include?(current_os)
newest_macos = MacOSVersion.new(HOMEBREW_MACOS_NEWEST_SUPPORTED).to_sym
depends_on_archs = cask.depends_on.arch&.filter_map { |arch| arch[:type] }&.uniq
# NOTE: We substitute the newest macOS (e.g. `:sequoia`) in place of
# `:macos` values (when used), as a generic `:macos` value won't apply
# to on_system blocks referencing macOS versions.
os_values = []
arch_values = depends_on_archs.presence || []
if cask.on_system_blocks_exist?
OnSystem::BASE_OS_OPTIONS.each do |os|
os_values << if os == :macos
(current_os_is_macos ? current_os : newest_macos)
else
os
end
end
arch_values = OnSystem::ARCH_OPTIONS if arch_values.empty?
else
# Architecture is only relevant if on_system blocks are present or
# the cask uses `depends_on arch`, otherwise we default to ARM for
# consistency.
os_values << (current_os_is_macos ? current_os : newest_macos)
arch_values << :arm if arch_values.empty?
end
os_values.product(arch_values)
end
sig {
params(
cask: Cask::Cask,
new_hash: T.nilable(T.any(String, Symbol)),
new_version: BumpVersionParser,
replacement_pairs: T::Array[[T.any(Regexp, String), T.any(Pathname, String)]],
).returns(T::Array[[T.any(Regexp, String), T.any(Pathname, String)]])
}
def replace_version_and_checksum(cask, new_hash, new_version, replacement_pairs)
generate_system_options(cask).each do |os, arch|
SimulateSystem.with(os:, arch:) do
# Handle the cask being invalid for specific os/arch combinations
old_cask = begin
Cask::CaskLoader.load(cask.sourcefile_path)
rescue Cask::CaskInvalidError, Cask::CaskUnreadableError
raise unless cask.on_system_blocks_exist?
end
next if old_cask.nil?
old_version = old_cask.version
next unless old_version
bump_version = new_version.send(arch) || new_version.general
old_version_regex = old_version.latest? ? ":latest" : %Q(["']#{Regexp.escape(old_version.to_s)}["'])
replacement_pairs << [/version\s+#{old_version_regex}/m,
"version #{bump_version.latest? ? ":latest" : %Q("#{bump_version}")}"]
# We are replacing our version here so we can get the new hash
tmp_contents = Utils::Inreplace.inreplace_pairs(cask.sourcefile_path,
replacement_pairs.uniq.compact,
read_only_run: true,
silent: true)
tmp_cask = Cask::CaskLoader::FromContentLoader.new(tmp_contents)
.load(config: nil)
old_hash = tmp_cask.sha256
if tmp_cask.version.latest? || new_hash == :no_check
opoo "Ignoring specified `--sha256=` argument." if new_hash.is_a?(String)
replacement_pairs << [/"#{old_hash}"/, ":no_check"] if old_hash != :no_check
elsif old_hash == :no_check && new_hash != :no_check
replacement_pairs << [":no_check", "\"#{new_hash}\""] if new_hash.is_a?(String)
elsif new_hash && !cask.on_system_blocks_exist? && cask.languages.empty?
replacement_pairs << [old_hash.to_s, new_hash.to_s]
elsif old_hash != :no_check
opoo "Multiple checksum replacements required; ignoring specified `--sha256` argument." if new_hash
languages = if cask.languages.empty?
[nil]
else
cask.languages
end
languages.each do |language|
new_cask = Cask::CaskLoader.load(tmp_contents)
next unless new_cask.url
new_cask.config = if language.blank?
tmp_cask.config
else
tmp_cask.config.merge(Cask::Config.new(explicit: { languages: [language] }))
end
download = Cask::Download.new(new_cask, quarantine: true).fetch(verify_download_integrity: false)
Utils::Tar.validate_file(download)
if new_cask.sha256.to_s != download.sha256
replacement_pairs << [new_cask.sha256.to_s,
download.sha256]
end
end
end
end
end
replacement_pairs
end
sig { params(cask: Cask::Cask, new_version: BumpVersionParser).void }
def check_pull_requests(cask, new_version:)
tap_remote_repo = cask.tap.full_name || cask.tap.remote_repository
file = cask.sourcefile_path.relative_path_from(cask.tap.path).to_s
quiet = args.quiet?
official_tap = cask.tap.official?
GitHub.check_for_duplicate_pull_requests(cask.token, tap_remote_repo,
state: "open", file:, quiet:, official_tap:)
# if we haven't already found open requests, try for an exact match across all pull requests
new_version.instance_variables.each do |version_type|
version_type_version = new_version.instance_variable_get(version_type)
next if version_type_version.blank?
version = shortened_version(version_type_version, cask:)
GitHub.check_for_duplicate_pull_requests(cask.token, tap_remote_repo, version:,
file:, quiet:, official_tap:)
end
end
sig { params(cask: Cask::Cask, old_contents: String, audit_exceptions: T::Array[String]).void }
def run_cask_audit(cask, old_contents, audit_exceptions = [])
if args.dry_run?
if args.no_audit?
ohai "Skipping `brew audit`"
else
ohai "brew audit --cask --online #{cask.full_name}"
end
return
end
failed_audit = false
if args.no_audit?
ohai "Skipping `brew audit`"
else
system HOMEBREW_BREW_FILE, "audit", "--cask", "--online", cask.full_name,
"--except=#{audit_exceptions.join(",")}"
failed_audit = !$CHILD_STATUS.success?
end
return unless failed_audit
cask.sourcefile_path.atomic_write(old_contents)
odie "`brew audit` failed!"
end
sig { params(cask: Cask::Cask, old_contents: String).void }
def run_cask_style(cask, old_contents)
if args.dry_run?
if args.no_style?
ohai "Skipping `brew style --fix`"
else
ohai "brew style --fix #{cask.sourcefile_path.basename}"
end
return
end
failed_style = false
if args.no_style?
ohai "Skipping `brew style --fix`"
else
system HOMEBREW_BREW_FILE, "style", "--fix", cask.sourcefile_path
failed_style = !$CHILD_STATUS.success?
end
return unless failed_style
cask.sourcefile_path.atomic_write(old_contents)
odie "`brew style --fix` failed!"
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/rubydoc.rb | Library/Homebrew/dev-cmd/rubydoc.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module DevCmd
class Rubydoc < AbstractCommand
cmd_args do
description <<~EOS
Generate Homebrew's RubyDoc documentation.
EOS
switch "--only-public",
description: "Only generate public API documentation."
switch "--open",
description: "Open generated documentation in a browser."
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["doc"])
HOMEBREW_LIBRARY_PATH.cd do |dir|
no_api_args = if args.only_public?
["--hide-api", "private", "--hide-api", "internal"]
else
[]
end
output_dir = dir/"doc"
safe_system "bundle", "exec", "yard", "doc", "--fail-on-warning", *no_api_args, "--output", output_dir
exec_browser "file://#{output_dir}/index.html" if args.open?
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/dev-cmd/generate-analytics-api.rb | Library/Homebrew/dev-cmd/generate-analytics-api.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module DevCmd
class GenerateAnalyticsApi < AbstractCommand
CATEGORIES = %w[
build-error install install-on-request
core-build-error core-install core-install-on-request
cask-install core-cask-install os-version
homebrew-devcmdrun-developer homebrew-os-arch-ci
homebrew-prefixes homebrew-versions
brew-command-run brew-command-run-options brew-test-bot-test
].freeze
# TODO: add brew-command-run-options brew-test-bot-test to above when working.
DAYS = %w[30 90 365].freeze
MAX_RETRIES = 3
cmd_args do
description <<~EOS
Generates analytics API data files for <#{HOMEBREW_API_WWW}>.
The generated files are written to the current directory.
EOS
named_args :none
end
sig { params(category_name: String, data_source: T.nilable(String)).returns(String) }
def analytics_json_template(category_name, data_source: nil)
data_source = "#{data_source}: true" if data_source
<<~EOS
---
layout: analytics_json
category: #{category_name}
#{data_source}
---
{{ content }}
EOS
end
sig { params(args: String).returns(String) }
def run_formula_analytics(*args)
puts "brew formula-analytics #{args.join(" ")}"
retries = 0
result = Utils.popen_read(HOMEBREW_BREW_FILE, "formula-analytics", *args, err: :err)
while !$CHILD_STATUS.success? && retries < MAX_RETRIES
# Give InfluxDB some more breathing room.
sleep 4**(retries+2)
retries += 1
puts "Retrying #{args.join(" ")} (#{retries}/#{MAX_RETRIES})..."
result = Utils.popen_read(HOMEBREW_BREW_FILE, "formula-analytics", *args, err: :err)
end
odie "`brew formula-analytics #{args.join(" ")}` failed: #{result}" unless $CHILD_STATUS.success?
result
end
sig { override.void }
def run
safe_system HOMEBREW_BREW_FILE, "formula-analytics", "--setup"
directories = ["_data/analytics", "api/analytics"]
FileUtils.rm_rf directories
FileUtils.mkdir_p directories
root_dir = Pathname.pwd
analytics_data_dir = root_dir/"_data/analytics"
analytics_api_dir = root_dir/"api/analytics"
analytics_output_queue = Queue.new
CATEGORIES.each do |category|
formula_analytics_args = []
case category
when "core-build-error"
formula_analytics_args << "--all-core-formulae-json"
formula_analytics_args << "--build-error"
category_name = "build-error"
data_source = "homebrew-core"
when "core-install"
formula_analytics_args << "--all-core-formulae-json"
formula_analytics_args << "--install"
category_name = "install"
data_source = "homebrew-core"
when "core-install-on-request"
formula_analytics_args << "--all-core-formulae-json"
formula_analytics_args << "--install-on-request"
category_name = "install-on-request"
data_source = "homebrew-core"
when "core-cask-install"
formula_analytics_args << "--all-core-formulae-json"
formula_analytics_args << "--cask-install"
category_name = "cask-install"
data_source = "homebrew-cask"
else
formula_analytics_args << "--#{category}"
category_name = category
end
path_suffix = File.join(category_name, data_source || "")
analytics_data_path = analytics_data_dir/path_suffix
analytics_api_path = analytics_api_dir/path_suffix
FileUtils.mkdir_p analytics_data_path
FileUtils.mkdir_p analytics_api_path
# The `--json` and `--all-core-formulae-json` flags are mutually
# exclusive, but we need to explicitly set `--json` sometimes,
# so only set it if we've not already set
# `--all-core-formulae-json`.
formula_analytics_args << "--json" unless formula_analytics_args.include? "--all-core-formulae-json"
DAYS.each do |days|
next if days != "30" && category_name == "build-error" && !data_source.nil?
analytics_output_queue << {
formula_analytics_args: formula_analytics_args.dup,
days: days,
analytics_data_path: analytics_data_path,
analytics_api_path: analytics_api_path,
category_name: category_name,
data_source: data_source,
}
end
end
workers = []
4.times do
workers << Thread.new do
until analytics_output_queue.empty?
analytics_output_type = begin
analytics_output_queue.pop(true)
rescue ThreadError
break
end
days = analytics_output_type[:days]
args = ["--days-ago=#{days}"]
(analytics_output_type[:analytics_data_path]/"#{days}d.json").write \
run_formula_analytics(*analytics_output_type[:formula_analytics_args], *args)
data_source = analytics_output_type[:data_source]
(analytics_output_type[:analytics_api_path]/"#{days}d.json").write \
analytics_json_template(analytics_output_type[:category_name], data_source:)
end
end
end
workers.each(&:join)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/release.rb | Library/Homebrew/dev-cmd/release.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module DevCmd
class Release < AbstractCommand
cmd_args do
description <<~EOS
Create a new draft Homebrew/brew release with the appropriate version number and release notes.
By default, `brew release` will bump the patch version number. Pass
`--major` or `--minor` to bump the major or minor version numbers, respectively.
The command will fail if the previous major or minor release was made less than
one month ago.
Without `--force`, this command will just output the release notes without creating
the release or triggering the workflow.
*Note:* Requires write access to the Homebrew/brew repository.
EOS
switch "--major",
description: "Create a major release."
switch "--minor",
description: "Create a minor release."
switch "--force",
description: "Actually create the release and trigger the workflow. Without this, just show " \
"what would be done."
conflicts "--major", "--minor"
named_args :none
end
sig { override.void }
def run
safe_system "git", "-C", HOMEBREW_REPOSITORY, "fetch", "origin" if Homebrew::EnvConfig.no_auto_update?
require "utils/github"
begin
latest_release = GitHub.get_latest_release "Homebrew", "brew"
rescue GitHub::API::HTTPNotFoundError
odie "No existing releases found!"
end
latest_version = Version.new latest_release["tag_name"]
if args.major? || args.minor?
one_month_ago = Date.today << 1
latest_major_minor_release = begin
GitHub.get_release "Homebrew", "brew", "#{latest_version.major_minor}.0"
rescue GitHub::API::HTTPNotFoundError
nil
end
if latest_major_minor_release.blank?
opoo "Unable to determine the release date of the latest major/minor release."
elsif Date.parse(latest_major_minor_release["published_at"]) > one_month_ago
odie "The latest major/minor release was less than one month ago."
end
end
new_version = if args.major?
Version.new "#{latest_version.major.to_i + 1}.0.0"
elsif args.minor?
Version.new "#{latest_version.major}.#{latest_version.minor.to_i + 1}.0"
else
Version.new "#{latest_version.major}.#{latest_version.minor}.#{latest_version.patch.to_i + 1}"
end.to_s
if args.major? || args.minor?
latest_major_minor_version = "#{latest_version.major}.#{latest_version.minor.to_i}.0"
ohai "Release notes since #{latest_major_minor_version} for #{new_version} blog post:"
# release notes without usernames, new contributors, or extra lines
blog_post_notes = GitHub.generate_release_notes("Homebrew", "brew", new_version,
previous_tag: latest_major_minor_version)["body"]
blog_post_notes = blog_post_notes.lines.filter_map do |line|
next unless (match = line.match(/^\* (.*) by @[\w-]+ in (.*)$/))
"- [#{match[1]}](#{match[2]})"
end.sort
puts blog_post_notes
end
ohai "Generating release notes for #{new_version}"
release_notes = if args.major? || args.minor?
"Release notes for this release can be found on the [Homebrew blog](https://brew.sh/blog/#{new_version}).\n"
else
""
end
release_notes += GitHub.generate_release_notes("Homebrew", "brew", new_version,
previous_tag: latest_version)["body"]
puts release_notes
puts
unless args.force?
opoo "Use `brew release --force` to trigger the release workflow and create the draft release."
return
end
# Get the current commit SHA
current_sha = Utils.safe_popen_read("git", "-C", HOMEBREW_REPOSITORY, "rev-parse", "origin/main").strip
release_workflow = "release.yml"
dispatch_time = Time.now
ohai "Triggering release workflow for #{new_version}..."
begin
GitHub.workflow_dispatch_event("Homebrew", "brew", release_workflow, "main", tag: new_version)
# Cannot use `e` as Sorbet needs it used below instead.
# rubocop:disable Naming/RescuedExceptionsVariableName
rescue *GitHub::API::ERRORS => error
odie "Unable to trigger workflow: #{error.message}!"
end
# rubocop:enable Naming/RescuedExceptionsVariableName
# Poll for workflow completion
initial_sleep_time = 15
sleep_time = 5
max_attempts = 180 # 15 minutes (5 seconds * 180 attempts)
attempt = 0
run_conclusion = T.let(nil, T.nilable(String))
while attempt < max_attempts
sleep attempt.zero? ? initial_sleep_time : sleep_time
attempt += 1
# Check workflow runs for the commit SHA
begin
runs_url = "#{GitHub::API_URL}/repos/Homebrew/brew/actions/workflows/#{release_workflow}/runs"
response = GitHub::API.open_rest("#{runs_url}?event=workflow_dispatch&per_page=5")
run = response["workflow_runs"]&.find do |r|
r["head_sha"] == current_sha && Time.parse(r["created_at"]) >= dispatch_time
end
if run
if run["status"] == "completed"
run_conclusion = run["conclusion"]
puts if attempt > 1
break
end
if attempt == 1
puts "This will take a few minutes. You can monitor progress at:"
puts " #{Formatter.url(run["html_url"])}"
print "Waiting for workflow to complete..."
else
print "."
end
else
puts
odie "Unable to find workflow for commit: #{current_sha}!"
end
rescue *GitHub::API::ERRORS => e
puts
odie "Unable to check workflow status: #{e.message}!"
end
end
odie "Workflow completed with status: #{run_conclusion}!" if run_conclusion != "success"
puts
ohai "Release created at:"
release_url = "https://github.com/Homebrew/brew/releases"
puts " #{Formatter.url(release_url)}"
exec_browser release_url
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/dev-cmd/verify.rb | Library/Homebrew/dev-cmd/verify.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "attestation"
module Homebrew
module DevCmd
class Verify < AbstractCommand
cmd_args do
description <<~EOS
Verify the build provenance of bottles using GitHub's attestation tools.
This is done by first fetching the given bottles and then verifying
their provenance.
Note that this command depends on the GitHub CLI. Run `brew install gh`.
EOS
flag "--os=",
description: "Download for the given operating system. " \
"(Pass `all` to download for all operating systems.)"
flag "--arch=",
description: "Download for the given CPU architecture. " \
"(Pass `all` to download for all architectures.)"
flag "--bottle-tag=",
description: "Download a bottle for given tag."
switch "--deps",
description: "Also download dependencies for any listed <formula>."
switch "-f", "--force",
description: "Remove a previously cached version and re-fetch."
switch "-j", "--json",
description: "Return JSON for the attestation data for each bottle."
conflicts "--os", "--bottle-tag"
conflicts "--arch", "--bottle-tag"
named_args [:formula], min: 1
end
sig { override.void }
def run
bucket = if args.deps?
args.named.to_formulae.flat_map do |formula|
[formula, *formula.recursive_dependencies.map(&:to_formula)]
end
else
args.named.to_formulae
end.uniq
os_arch_combinations = args.os_arch_combinations
json_results = []
bucket.each do |formula|
os_arch_combinations.each do |os, arch|
SimulateSystem.with(os:, arch:) do
bottle_tag = if (bottle_tag = args.bottle_tag&.to_sym)
Utils::Bottles::Tag.from_symbol(bottle_tag)
else
Utils::Bottles::Tag.new(system: os, arch:)
end
bottle = formula.bottle_for_tag(bottle_tag)
if bottle
bottle.clear_cache if args.force?
bottle.fetch
begin
attestation = Homebrew::Attestation.check_core_attestation bottle
oh1 "#{bottle.filename} has a valid attestation"
json_results.push(attestation)
rescue Homebrew::Attestation::InvalidAttestationError => e
ofail <<~ERR
Failed to verify #{bottle.filename} with tag #{bottle_tag} due to error:
#{e}
ERR
end
else
opoo "Bottle for tag #{bottle_tag.to_sym.inspect} is unavailable."
end
end
end
end
puts json_results.to_json if args.json?
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/dev-cmd/update-python-resources.rb | Library/Homebrew/dev-cmd/update-python-resources.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module DevCmd
class UpdatePythonResources < AbstractCommand
cmd_args do
description <<~EOS
Update versions for PyPI resource blocks in <formula>.
EOS
switch "-p", "--print-only",
description: "Print the updated resource blocks instead of changing <formula>."
switch "-s", "--silent",
description: "Suppress any output."
switch "--ignore-errors",
description: "Record all discovered resources, even those that can't be resolved successfully. " \
"This option is ignored for homebrew/core formulae."
switch "--ignore-non-pypi-packages",
description: "Don't fail if <formula> is not a PyPI package."
switch "--install-dependencies",
description: "Install missing dependencies required to update resources."
flag "--version=",
description: "Use the specified <version> when finding resources for <formula>. " \
"If no version is specified, the current version for <formula> will be used."
flag "--package-name=",
description: "Use the specified <package-name> when finding resources for <formula>. " \
"If no package name is specified, it will be inferred from the formula's stable URL."
comma_array "--extra-packages",
description: "Include these additional packages when finding resources."
comma_array "--exclude-packages",
description: "Exclude these packages when finding resources."
named_args :formula, min: 1, without_api: true
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["ast"])
require "utils/pypi"
args.named.to_formulae.each do |formula|
ignore_errors = if formula.tap&.official?
false
else
args.ignore_errors?
end
PyPI.update_python_resources! formula,
version: args.version,
package_name: args.package_name,
extra_packages: args.extra_packages,
exclude_packages: args.exclude_packages,
install_dependencies: args.install_dependencies?,
print_only: args.print_only?,
silent: args.silent?,
verbose: args.verbose?,
ignore_errors: ignore_errors,
ignore_non_pypi_packages: args.ignore_non_pypi_packages?
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/dev-cmd/generate-man-completions.rb | Library/Homebrew/dev-cmd/generate-man-completions.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "completions"
require "manpages"
require "system_command"
module Homebrew
module DevCmd
class GenerateManCompletions < AbstractCommand
include SystemCommand::Mixin
cmd_args do
description <<~EOS
Generate Homebrew's manpages and shell completions.
EOS
named_args :none
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["man"])
Commands.rebuild_internal_commands_completion_list
Manpages.regenerate_man_pages(quiet: args.quiet?)
Completions.update_shell_completions!
diff = system_command "git", args: [
"-C", HOMEBREW_REPOSITORY,
"diff", "--shortstat", "--patch", "--exit-code", "docs/Manpage.md", "manpages", "completions"
]
if diff.status.success?
ofail "No changes to manpage or completions."
elsif /1 file changed, 1 insertion\(\+\), 1 deletion\(-\).*-\.TH "BREW" "1" "\w+ \d+"/m.match?(diff.stdout)
ofail "No changes to manpage or completions other than the date."
else
puts "Manpage and completions updated."
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/dev-cmd/pr-upload.rb | Library/Homebrew/dev-cmd/pr-upload.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "github_packages"
require "github_releases"
require "extend/hash/deep_merge"
module Homebrew
module DevCmd
class PrUpload < AbstractCommand
cmd_args do
description <<~EOS
Apply the bottle commit and publish bottles to a host.
EOS
switch "--keep-old",
description: "If the formula specifies a rebuild version, " \
"attempt to preserve its value in the generated DSL. " \
"When using GitHub Packages, this also appends the manifest to the existing list."
switch "-n", "--dry-run",
description: "Print what would be done rather than doing it."
switch "--no-commit",
description: "Do not generate a new commit before uploading."
switch "--warn-on-upload-failure",
description: "Warn instead of raising an error if the bottle upload fails. " \
"Useful for repairing bottle uploads that previously failed."
switch "--upload-only",
description: "Skip running `brew bottle` before uploading."
flag "--committer=",
description: "Specify a committer name and email in `git`'s standard author format."
flag "--root-url=",
description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default."
flag "--root-url-using=",
description: "Use the specified download strategy class for downloading the bottle's URL instead of " \
"Homebrew's default."
conflicts "--upload-only", "--no-commit"
named_args :none
end
sig { override.void }
def run
json_files = Dir["*.bottle.json"]
odie "No bottle JSON files found in the current working directory" if json_files.blank?
Homebrew.install_bundler_gems!(groups: ["pr_upload"])
bottles_hash = bottles_hash_from_json_files(json_files, args)
unless args.upload_only?
bottle_args = ["bottle", "--merge", "--write"]
bottle_args << "--verbose" if args.verbose?
bottle_args << "--debug" if args.debug?
bottle_args << "--keep-old" if args.keep_old?
bottle_args << "--root-url=#{args.root_url}" if args.root_url
bottle_args << "--committer=#{args.committer}" if args.committer
bottle_args << "--no-commit" if args.no_commit?
bottle_args << "--root-url-using=#{args.root_url_using}" if args.root_url_using
bottle_args += json_files
if args.dry_run?
dry_run_service = if github_packages?(bottles_hash)
# GitHub Packages has its own --dry-run handling.
nil
elsif github_releases?(bottles_hash)
"GitHub Releases"
else
odie "Service specified by root_url is not recognized"
end
if dry_run_service
puts <<~EOS
brew #{bottle_args.join " "}
Upload bottles described by these JSON files to #{dry_run_service}:
#{json_files.join("\n ")}
EOS
return
end
end
check_bottled_formulae!(bottles_hash)
safe_system HOMEBREW_BREW_FILE, *bottle_args
json_files = Dir["*.bottle.json"]
if json_files.blank?
puts "No bottle JSON files after merge, no upload needed!"
return
end
# Reload the JSON files (in case `brew bottle --merge` generated
# `all: $SHA256` bottles)
bottles_hash = bottles_hash_from_json_files(json_files, args)
# Check the bottle commits did not break `brew audit`
unless args.no_commit?
audit_args = ["audit", "--skip-style"]
audit_args << "--verbose" if args.verbose?
audit_args << "--debug" if args.debug?
audit_args += bottles_hash.keys
safe_system HOMEBREW_BREW_FILE, *audit_args
end
end
if github_releases?(bottles_hash)
github_releases = GitHubReleases.new
github_releases.upload_bottles(bottles_hash)
elsif github_packages?(bottles_hash)
github_packages = GitHubPackages.new
github_packages.upload_bottles(bottles_hash,
keep_old: args.keep_old?,
dry_run: args.dry_run?,
warn_on_error: args.warn_on_upload_failure?)
else
odie "Service specified by root_url is not recognized"
end
end
private
sig { params(bottles_hash: T::Hash[String, T.untyped]).void }
def check_bottled_formulae!(bottles_hash)
bottles_hash.each do |name, bottle_hash|
formula_path = HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]
formula_version = Formulary.factory(formula_path).pkg_version
bottle_version = PkgVersion.parse bottle_hash["formula"]["pkg_version"]
next if formula_version == bottle_version
odie "Bottles are for #{name} #{bottle_version} but formula is version #{formula_version}!"
end
end
sig { params(bottles_hash: T::Hash[String, T.untyped]).returns(T::Boolean) }
def github_releases?(bottles_hash)
@github_releases ||= T.let(bottles_hash.values.all? do |bottle_hash|
root_url = bottle_hash["bottle"]["root_url"]
url_match = root_url.match GitHubReleases::URL_REGEX
_, _, _, tag = *url_match
tag
end, T.nilable(T::Boolean))
end
sig { params(bottles_hash: T::Hash[String, T.untyped]).returns(T::Boolean) }
def github_packages?(bottles_hash)
@github_packages ||= T.let(bottles_hash.values.all? do |bottle_hash|
bottle_hash["bottle"]["root_url"].match? GitHubPackages::URL_REGEX
end, T.nilable(T::Boolean))
end
sig { params(json_files: T::Array[String], args: T.untyped).returns(T::Hash[String, T.untyped]) }
def bottles_hash_from_json_files(json_files, args)
puts "Reading JSON files: #{json_files.join(", ")}" if args.verbose?
bottles_hash = json_files.reduce({}) do |hash, json_file|
hash.deep_merge(JSON.parse(File.read(json_file)))
end
if args.root_url
bottles_hash.each_value do |bottle_hash|
bottle_hash["bottle"]["root_url"] = args.root_url
end
end
bottles_hash
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/debugger.rb | Library/Homebrew/dev-cmd/debugger.rb | # typed: strict
# frozen_string_literal: true
module Homebrew
module DevCmd
class Debugger < AbstractCommand
cmd_args do
description <<~EOS
Run the specified Homebrew command in debug mode.
To pass flags to the command, use `--` to separate them from the `brew` flags.
For example: `brew debugger -- list --formula`.
EOS
switch "-O", "--open",
description: "Start remote debugging over a Unix socket."
named_args :command, min: 1
end
sig { override.void }
def run
raise UsageError, "Debugger is only supported with portable Ruby!" unless HOMEBREW_USING_PORTABLE_RUBY
unless Commands.valid_ruby_cmd?(T.must(args.named.first))
raise UsageError, "`#{args.named.first}` is not a valid Ruby command!"
end
brew_rb = (HOMEBREW_LIBRARY_PATH/"brew.rb").resolved_path
debugger_method = if args.open?
"open"
else
"start"
end
env = {}
env[:RUBY_DEBUG_FORK_MODE] = "parent"
env[:RUBY_DEBUG_NONSTOP] = "1" unless ENV["HOMEBREW_RDBG"]
with_env(**env) do
system(*HOMEBREW_RUBY_EXEC_ARGS,
"-I", $LOAD_PATH.join(File::PATH_SEPARATOR),
"-rdebug/#{debugger_method}",
brew_rb, *args.named)
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/dev-cmd/livecheck.rb | Library/Homebrew/dev-cmd/livecheck.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "livecheck/livecheck"
require "livecheck/strategy"
module Homebrew
module DevCmd
class LivecheckCmd < AbstractCommand
cmd_args do
description <<~EOS
Check for newer versions of formulae and/or casks from upstream.
If no formula or cask argument is passed, the list of formulae and
casks to check is taken from `$HOMEBREW_LIVECHECK_WATCHLIST` or
`~/.homebrew/livecheck_watchlist.txt`.
EOS
switch "--full-name",
description: "Print formulae and casks with fully-qualified names."
flag "--tap=",
description: "Check formulae and casks within the given tap, specified as <user>`/`<repo>."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to check them."
switch "--installed",
description: "Check formulae and casks that are currently installed."
switch "--newer-only",
description: "Show the latest version only if it's newer than the current formula or cask version."
switch "--json",
description: "Output information in JSON format."
switch "-r", "--resources",
description: "Also check resources for formulae."
switch "-q", "--quiet",
description: "Suppress warnings, don't print a progress bar for JSON output."
switch "--formula", "--formulae",
description: "Only check formulae."
switch "--cask", "--casks",
description: "Only check casks."
switch "--extract-plist",
description: "Enable checking multiple casks with ExtractPlist strategy."
switch "--autobump",
description: "Include packages that are autobumped by BrewTestBot. By default these are skipped."
conflicts "--tap", "--installed", "--eval-all"
conflicts "--json", "--debug"
conflicts "--formula", "--cask"
conflicts "--formula", "--extract-plist"
named_args [:formula, :cask], without_api: true
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["livecheck"])
eval_all = args.eval_all?
if args.debug? && args.verbose?
puts args
puts Homebrew::EnvConfig.livecheck_watchlist if Homebrew::EnvConfig.livecheck_watchlist.present?
end
formulae_and_casks_to_check = Homebrew.with_no_api_env do
if args.tap
tap = Tap.fetch(args.tap)
formulae = args.cask? ? [] : tap.formula_files.map { |path| Formulary.factory(path) }
casks = args.formula? ? [] : tap.cask_files.map { |path| Cask::CaskLoader.load(path) }
formulae + casks
elsif args.installed?
formulae = args.cask? ? [] : Formula.installed
casks = args.formula? ? [] : Cask::Caskroom.casks
formulae + casks
elsif args.named.present?
args.named.to_formulae_and_casks_with_taps
elsif eval_all
formulae = args.cask? ? [] : Formula.all(eval_all:)
casks = args.formula? ? [] : Cask::Cask.all(eval_all:)
formulae + casks
elsif File.exist?(watchlist_path)
begin
# This removes blank lines, comment lines, and trailing comments
names = Pathname.new(watchlist_path).read.lines
.filter_map do |line|
comment_index = line.index("#")
next if comment_index&.zero?
line = line[0...comment_index] if comment_index
line&.strip.presence
end
named_args = CLI::NamedArgs.new(*names, parent: args)
named_args.to_formulae_and_casks(ignore_unavailable: true)
rescue Errno::ENOENT => e
onoe e
end
else
raise UsageError,
"`brew livecheck` with no arguments needs a watchlist file to be present or `--eval-all` passed!"
end
end
skipped_autobump = T.let(false, T::Boolean)
if skip_autobump?
autobump_lists = {}
formulae_and_casks_to_check = formulae_and_casks_to_check.reject do |formula_or_cask|
tap = formula_or_cask.tap
next false if tap.nil?
autobump_lists[tap] ||= tap.autobump
name = formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name
next unless autobump_lists[tap].include?(name)
odebug "Skipping #{name} as it is autobumped in #{tap}."
skipped_autobump = true
true
end
end
formulae_and_casks_to_check = formulae_and_casks_to_check.sort_by do |formula_or_cask|
formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name
end
raise UsageError, "No formulae or casks to check." if formulae_and_casks_to_check.blank? && !skipped_autobump
return if formulae_and_casks_to_check.blank?
options = {
json: args.json?,
full_name: args.full_name?,
handle_name_conflict: !args.formula? && !args.cask?,
check_resources: args.resources?,
newer_only: args.newer_only?,
extract_plist: args.extract_plist?,
quiet: args.quiet?,
debug: args.debug?,
verbose: args.verbose?,
}.compact
Livecheck.run_checks(formulae_and_casks_to_check, **options)
end
private
sig { returns(String) }
def watchlist_path
@watchlist_path ||= T.let(File.expand_path(Homebrew::EnvConfig.livecheck_watchlist), T.nilable(String))
end
sig { returns(T::Boolean) }
def skip_autobump?
!(args.autobump? || Homebrew::EnvConfig.livecheck_autobump?)
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/dev-cmd/pr-pull.rb | Library/Homebrew/dev-cmd/pr-pull.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
require "utils/github"
require "utils/github/artifacts"
require "tmpdir"
require "formula"
module Homebrew
module DevCmd
class PrPull < AbstractCommand
include FileUtils
cmd_args do
description <<~EOS
Download and publish bottles and apply the bottle commit from a
pull request with artifacts generated by GitHub Actions.
Requires write access to the repository.
EOS
switch "--no-upload",
description: "Download the bottles but don't upload them."
switch "--no-commit",
description: "Do not generate a new commit before uploading."
switch "--no-cherry-pick",
description: "Do not cherry-pick commits from the pull request branch."
switch "-n", "--dry-run",
description: "Print what would be done rather than doing it."
switch "--clean",
description: "Do not amend the commits from pull requests."
switch "--keep-old",
description: "If the formula specifies a rebuild version, " \
"attempt to preserve its value in the generated DSL."
switch "--autosquash",
description: "Automatically reformat and reword commits in the pull request to our " \
"preferred format."
switch "--branch-okay",
description: "Do not warn if pulling to a branch besides the repository default (useful for testing)."
switch "--resolve",
description: "When a patch fails to apply, leave in progress and allow user to resolve, " \
"instead of aborting."
switch "--warn-on-upload-failure",
description: "Warn instead of raising an error if the bottle upload fails. " \
"Useful for repairing bottle uploads that previously failed."
switch "--retain-bottle-dir",
description: "Does not clean up the tmp directory for the bottle so it can be used later."
flag "--committer=",
description: "Specify a committer name and email in `git`'s standard author format."
flag "--message=",
depends_on: "--autosquash",
description: "Message to include when autosquashing revision bumps, deletions and rebuilds."
flag "--artifact-pattern=", "--artifact=",
description: "Download artifacts with the specified pattern (default: `bottles{,_*}`)."
flag "--tap=",
description: "Target tap repository (default: `homebrew/core`)."
flag "--root-url=",
description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default."
flag "--root-url-using=",
description: "Use the specified download strategy class for downloading the bottle's URL instead of " \
"Homebrew's default."
comma_array "--workflows",
description: "Retrieve artifacts from the specified workflow (default: `tests.yml`). " \
"Can be a comma-separated list to include multiple workflows."
comma_array "--ignore-missing-artifacts",
description: "Comma-separated list of workflows which can be ignored if they have not been run."
conflicts "--clean", "--autosquash"
named_args :pull_request, min: 1
end
sig { override.void }
def run
# Needed when extracting the CI artifact.
ensure_executable!("unzip", reason: "extracting CI artifacts")
workflows = args.workflows.presence || ["tests.yml"]
artifact_pattern = args.artifact_pattern || "bottles{,_*}"
tap = Tap.fetch(args.tap || CoreTap.instance.name)
raise TapUnavailableError, tap.name unless tap.installed?
Utils::Git.set_name_email!(committer: args.committer.blank?)
Utils::Git.setup_gpg!
if (committer = args.committer)
committer = Utils.parse_author!(committer)
ENV["GIT_COMMITTER_NAME"] = committer[:name]
ENV["GIT_COMMITTER_EMAIL"] = committer[:email]
end
args.named.uniq.each do |arg|
arg = "#{tap.default_remote}/pull/#{arg}" if arg.to_i.positive?
url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX
_, user, repo, pr = *url_match
odie "Not a GitHub pull request: #{arg}" if !user || !repo || !pr
git_repo = tap.git_repository
if !git_repo.default_origin_branch? && !args.branch_okay? && !args.no_commit? && !args.no_cherry_pick?
origin_branch_name = git_repo.origin_branch_name
opoo "Current branch is #{git_repo.branch_name}: do you need to pull inside #{origin_branch_name}?"
end
pr_labels = GitHub.pull_request_labels(user, repo, pr)
if pr_labels.include?("autosquash") && !args.autosquash?
opoo "Pull request is labelled `autosquash`: do you need to pass `--autosquash`?"
end
pr_check_conflicts("#{user}/#{repo}", pr)
ohai "Fetching #{tap} pull request ##{pr}"
dir = Dir.mktmpdir("pr-pull-#{pr}-", HOMEBREW_TEMP)
begin
cd dir do
current_branch_head = ENV["GITHUB_SHA"] || tap.git_head
original_commit = if args.no_cherry_pick?
# TODO: Handle the case where `merge-base` returns multiple commits.
Utils.safe_popen_read("git", "-C", tap.path, "merge-base", "origin/HEAD",
current_branch_head).strip
else
current_branch_head
end
odebug "Pull request merge-base: #{original_commit}"
unless args.no_commit?
cherry_pick_pr!(user, repo, pr, path: tap.path) unless args.no_cherry_pick?
if args.autosquash? && !args.dry_run?
autosquash!(original_commit, tap:, cherry_picked: !args.no_cherry_pick?,
verbose: args.verbose?, resolve: args.resolve?, reason: args.message)
end
signoff!(git_repo, pull_request: pr, dry_run: args.dry_run?) unless args.clean?
end
unless formulae_need_bottles?(tap, original_commit, pr_labels)
ohai "Skipping artifacts for ##{pr} as the formulae don't need bottles"
next
end
workflows.each do |workflow|
workflow_run = GitHub.get_workflow_run(
user, repo, pr, workflow_id: workflow, artifact_pattern:
)
if args.ignore_missing_artifacts.present? &&
args.ignore_missing_artifacts&.include?(workflow) &&
workflow_run.first.blank?
# Ignore that workflow as it was not executed and we specified
# that we could skip it.
ohai "Ignoring workflow #{workflow} as requested by `--ignore-missing-artifacts`"
next
end
ohai "Downloading bottles for workflow: #{workflow}"
urls = GitHub.get_artifact_urls(workflow_run)
urls.each { |url| GitHub.download_artifact(url, pr) }
end
next if args.no_upload?
upload_args = ["pr-upload"]
upload_args << "--debug" if args.debug?
upload_args << "--verbose" if args.verbose?
upload_args << "--no-commit" if args.no_commit?
upload_args << "--dry-run" if args.dry_run?
upload_args << "--keep-old" if args.keep_old?
upload_args << "--warn-on-upload-failure" if args.warn_on_upload_failure?
upload_args << "--committer=#{args.committer}" if args.committer
upload_args << "--root-url=#{args.root_url}" if args.root_url
upload_args << "--root-url-using=#{args.root_url_using}" if args.root_url_using
safe_system HOMEBREW_BREW_FILE, *upload_args
end
ensure
if args.retain_bottle_dir? && GitHub::Actions.env_set?
ohai "Bottle files retained at:", dir
File.open(ENV.fetch("GITHUB_OUTPUT"), "a") do |f|
f.puts "bottle_path=#{dir}"
end
else
FileUtils.remove_entry dir
end
end
end
end
# Separates a commit message into subject, body and trailers.
sig { params(message: String).returns([String, String, String]) }
def separate_commit_message(message)
first_line = message.lines.first
return ["", "", ""] unless first_line
# Skip the subject and separate lines that look like trailers (e.g. "Co-authored-by")
# from lines that look like regular body text.
trailers, body = message.lines.drop(1).partition { |s| s.match?(/^[a-z-]+-by:/i) }
trailers = trailers.uniq.join.strip
body = body.join.strip.gsub(/\n{3,}/, "\n\n")
[first_line.strip, body, trailers]
end
sig { params(git_repo: GitRepository, pull_request: T.nilable(String), dry_run: T::Boolean).void }
def signoff!(git_repo, pull_request: nil, dry_run: false)
msg = git_repo.commit_message
return if msg.blank?
subject, body, trailers = separate_commit_message(msg)
if pull_request
# This is a tap pull request and approving reviewers should also sign-off.
tap = T.must(Tap.from_path(git_repo.pathname))
review_trailers = GitHub.repository_approved_reviews(tap.user, tap.full_repository, pull_request).map do |r|
"Signed-off-by: #{r["name"]} <#{r["email"]}>"
end
trailers = trailers.lines.concat(review_trailers).map(&:strip).uniq.join("\n")
# Append the close message as well, unless the commit body already includes it.
close_message = "Closes ##{pull_request}."
body.concat("\n\n#{close_message}") unless body.include?(close_message)
end
git_args = Utils::Git.git, "-C", git_repo.pathname, "commit", "--amend", "--signoff", "--allow-empty",
"--quiet", "--message", subject, "--message", body, "--message", trailers
if dry_run
puts(*git_args)
else
safe_system(*git_args)
end
end
sig { params(tap: Tap, subject_name: String, subject_path: Pathname, content: String).returns(T.untyped) }
def get_package(tap, subject_name, subject_path, content)
if subject_path.to_s.start_with?("#{tap.cask_dir}/")
cask = begin
Cask::CaskLoader.load(content.dup)
rescue Cask::CaskUnavailableError
nil
end
return cask
end
begin
Formulary.from_contents(subject_name, subject_path, content, :stable)
rescue FormulaUnavailableError
nil
end
end
sig {
params(old_contents: String, new_contents: String, subject_path: T.any(String, Pathname),
reason: T.nilable(String)).returns(String)
}
def determine_bump_subject(old_contents, new_contents, subject_path, reason: nil)
subject_path = Pathname(subject_path)
tap = T.must(Tap.from_path(subject_path))
subject_name = subject_path.basename.to_s.chomp(".rb")
is_cask = subject_path.to_s.start_with?("#{tap.cask_dir}/")
name = is_cask ? "cask" : "formula"
new_package = get_package(tap, subject_name, subject_path, new_contents)
return "#{subject_name}: delete #{reason}".strip if new_package.blank?
old_package = get_package(tap, subject_name, subject_path, old_contents)
if old_package.blank?
"#{subject_name} #{new_package.version} (new #{name})"
elsif old_package.version != new_package.version
"#{subject_name} #{new_package.version}"
elsif !is_cask && old_package.revision != new_package.revision
"#{subject_name}: revision #{reason}".strip
elsif is_cask && old_package.sha256 != new_package.sha256
"#{subject_name}: checksum update #{reason}".strip
else
"#{subject_name}: #{reason || "rebuild"}".strip
end
end
# Cherry picks a single commit that modifies a single file.
# Potentially rewords this commit using {determine_bump_subject}.
sig {
params(commit: String, file: String, git_repo: GitRepository, reason: T.nilable(String), verbose: T::Boolean,
resolve: T::Boolean).void
}
def reword_package_commit(commit, file, git_repo:, reason: "", verbose: false, resolve: false)
package_file = git_repo.pathname / file
package_name = package_file.basename.to_s.chomp(".rb")
odebug "Cherry-picking #{package_file}: #{commit}"
Utils::Git.cherry_pick!(git_repo.to_s, commit, verbose:, resolve:)
old_package = Utils::Git.file_at_commit(git_repo.to_s, file, "HEAD^")
new_package = Utils::Git.file_at_commit(git_repo.to_s, file, "HEAD")
bump_subject = determine_bump_subject(old_package, new_package, package_file, reason:).strip
msg = git_repo.commit_message
return if msg.blank?
subject, body, trailers = separate_commit_message(msg)
if subject != bump_subject && !subject.start_with?("#{package_name}:")
safe_system("git", "-C", git_repo.pathname, "commit", "--amend", "-q",
"-m", bump_subject, "-m", subject, "-m", body, "-m", trailers)
ohai bump_subject
else
ohai subject
end
end
# Cherry picks multiple commits that each modify a single file.
# Words the commit according to {determine_bump_subject} with the body
# corresponding to all the original commit messages combined.
sig {
params(commits: T::Array[String], file: String, git_repo: GitRepository, reason: T.nilable(String),
verbose: T::Boolean, resolve: T::Boolean).void
}
def squash_package_commits(commits, file, git_repo:, reason: "", verbose: false, resolve: false)
odebug "Squashing #{file}: #{commits.join " "}"
# Format commit messages into something similar to `git fmt-merge-message`.
# * subject 1
# * subject 2
# optional body
# * subject 3
messages = []
trailers = []
commits.each do |commit|
msg = git_repo.commit_message(commit)
next if msg.blank?
subject, body, trailer = separate_commit_message(msg)
body = body.lines.map { |line| " #{line.strip}" }.join("\n")
messages << "* #{subject}\n#{body}".strip
trailers << trailer
end
# Get the set of authors in this series.
authors = Utils.safe_popen_read("git", "-C", git_repo.pathname, "show",
"--no-patch", "--pretty=%an <%ae>", *commits).lines.map(&:strip).uniq.compact
# Get the author and date of the first commit of this series, which we use for the squashed commit.
original_author = authors.shift
original_date = Utils.safe_popen_read "git", "-C", git_repo.pathname, "show", "--no-patch", "--pretty=%ad",
commits.first
# Generate trailers for coauthors and combine them with the existing trailers.
co_author_trailers = authors.map { |au| "Co-authored-by: #{au}" }
trailers = [trailers + co_author_trailers].flatten.uniq.compact
# Apply the patch series but don't commit anything yet.
Utils::Git.cherry_pick!(git_repo.pathname, "--no-commit", *commits, verbose:, resolve:)
# Determine the bump subject by comparing the original state of the tree to its current state.
package_file = git_repo.pathname / file
old_package = Utils::Git.file_at_commit(git_repo.pathname, file, "#{commits.first}^")
new_package = package_file.read
bump_subject = determine_bump_subject(old_package, new_package, package_file, reason:)
# Commit with the new subject, body and trailers.
safe_system("git", "-C", git_repo.pathname, "commit", "--quiet",
"-m", bump_subject, "-m", messages.join("\n"), "-m", trailers.join("\n"),
"--author", original_author, "--date", original_date, "--", file)
ohai bump_subject
end
# TODO: fix test in `test/dev-cmd/pr-pull_spec.rb` and assume `cherry_picked: false`.
sig {
params(original_commit: String, tap: Tap, reason: T.nilable(String), verbose: T::Boolean, resolve: T::Boolean,
cherry_picked: T::Boolean).void
}
def autosquash!(original_commit, tap:, reason: "", verbose: false, resolve: false, cherry_picked: true)
git_repo = tap.git_repository
commits = Utils.safe_popen_read("git", "-C", tap.path, "rev-list",
"--reverse", "#{original_commit}..HEAD").lines.map(&:strip)
# Generate a bidirectional mapping of commits <=> formula/cask files.
files_to_commits = {}
commits_to_files = commits.to_h do |commit|
files = Utils.safe_popen_read("git", "-C", tap.path, "diff-tree", "--diff-filter=AMD",
"-r", "--name-only", "#{commit}^", commit).lines.map(&:strip)
files.each do |file|
files_to_commits[file] ||= []
files_to_commits[file] << commit
tap_file = (tap.path/file).to_s
if tap_file.start_with?("#{tap.formula_dir}/", "#{tap.cask_dir}/") &&
File.extname(file) == ".rb"
next
end
odie <<~EOS
Autosquash can only squash commits that modify formula or cask files.
File: #{file}
Commit: #{commit}
EOS
end
[commit, files]
end
# Reset to state before cherry-picking.
safe_system "git", "-C", tap.path, "reset", "--hard", original_commit
# Iterate over every commit in the pull request series, but if we have to squash
# multiple commits into one, ensure that we skip over commits we've already squashed.
processed_commits = T.let([], T::Array[String])
commits.each do |commit|
next if processed_commits.include? commit
files = commits_to_files[commit]
if files.length == 1 && files_to_commits[files.first].length == 1
# If there's a 1:1 mapping of commits to files, just cherry pick and (maybe) reword.
reword_package_commit(
commit, files.first, git_repo:, reason:, verbose:, resolve:
)
processed_commits << commit
elsif files.length == 1 && files_to_commits[files.first].length > 1
# If multiple commits modify a single file, squash them down into a single commit.
file = files.first
commits = files_to_commits[file]
squash_package_commits(commits, file, git_repo:, reason:, verbose:, resolve:)
processed_commits += commits
else
# We can't split commits (yet) so just raise an error.
odie <<~EOS
Autosquash can't split commits that modify multiple files.
Commit: #{commit}
Files: #{files.join " "}
EOS
end
end
rescue
original_head = git_repo&.head_ref
return if original_head.nil?
opoo "Autosquash encountered an error; resetting to original state at #{original_head}"
system "git", "-C", tap.path.to_s, "reset", "--hard", original_head
system "git", "-C", tap.path.to_s, "cherry-pick", "--abort" if cherry_picked
raise
end
private
sig { params(user: String, repo: String, pull_request: String, path: T.any(String, Pathname)).void }
def cherry_pick_pr!(user, repo, pull_request, path: ".")
if args.dry_run?
puts <<~EOS
git fetch --force origin +refs/pull/#{pull_request}/head
git merge-base HEAD FETCH_HEAD
git cherry-pick --ff --allow-empty $merge_base..FETCH_HEAD
EOS
return
end
commits = GitHub.pull_request_commits(user, repo, pull_request)
safe_system "git", "-C", path, "fetch", "--quiet", "--force", "origin", commits.last
ohai "Using #{commits.count} commit#{"s" if commits.count != 1} from ##{pull_request}"
Utils::Git.cherry_pick!(path, "--ff", "--allow-empty", *commits, verbose: args.verbose?,
resolve: args.resolve?)
end
sig { params(tap: Tap, original_commit: String, labels: T::Array[String]).returns(T::Boolean) }
def formulae_need_bottles?(tap, original_commit, labels)
return false if args.dry_run?
return false if labels.include?("CI-syntax-only") || labels.include?("CI-no-bottles")
changed_packages(tap, original_commit).any? do |f|
!f.instance_of?(Cask::Cask)
end
end
sig { params(tap: Tap, original_commit: String).returns(T::Array[String]) }
def changed_packages(tap, original_commit)
formulae = Utils.popen_read("git", "-C", tap.path, "diff-tree",
"-r", "--name-only", "--diff-filter=AM",
original_commit, "HEAD", "--", tap.formula_dir)
.lines
.filter_map do |line|
next unless line.end_with? ".rb\n"
name = "#{tap.name}/#{File.basename(line.chomp, ".rb")}"
if Homebrew::EnvConfig.disable_load_formula?
opoo "Can't check if updated bottles are necessary as `$HOMEBREW_DISABLE_LOAD_FORMULA` is set!"
break
end
begin
Formulary.resolve(name)
rescue FormulaUnavailableError
nil
end
end
casks = Utils.popen_read("git", "-C", tap.path, "diff-tree",
"-r", "--name-only", "--diff-filter=AM",
original_commit, "HEAD", "--", tap.cask_dir)
.lines
.filter_map do |line|
next unless line.end_with? ".rb\n"
name = "#{tap.name}/#{File.basename(line.chomp, ".rb")}"
begin
Cask::CaskLoader.load(name)
rescue Cask::CaskUnavailableError
nil
end
end
formulae + casks
end
sig { params(repo: String, pull_request: String).void }
def pr_check_conflicts(repo, pull_request)
long_build_pr_files = GitHub.issues(
repo:, state: "open", labels: "no long build conflict",
).each_with_object({}) do |long_build_pr, hash|
next unless long_build_pr.key?("pull_request")
number = long_build_pr["number"]
next if number == pull_request.to_i
GitHub.get_pull_request_changed_files(repo, number).each do |file|
key = file["filename"]
hash[key] ||= []
hash[key] << number
end
end
return if long_build_pr_files.blank?
this_pr_files = GitHub.get_pull_request_changed_files(repo, pull_request)
conflicts = this_pr_files.each_with_object({}) do |file, hash|
filename = file["filename"]
next unless long_build_pr_files.key?(filename)
long_build_pr_files[filename].each do |pr_number|
key = "#{repo}/pull/#{pr_number}"
hash[key] ||= []
hash[key] << filename
end
end
return if conflicts.blank?
# Raise an error, display the conflicting PR. For example:
# Error: You are trying to merge a pull request that conflicts with a long running build in:
# {
# "homebrew-core/pull/98809": [
# "Formula/icu4c.rb",
# "Formula/node@10.rb"
# ]
# }
odie <<~EOS
You are trying to merge a pull request that conflicts with a long running build in:
#{JSON.pretty_generate(conflicts)}
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/update-sponsors.rb | Library/Homebrew/dev-cmd/update-sponsors.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "utils/github"
require "system_command"
module Homebrew
module DevCmd
class UpdateSponsors < AbstractCommand
include SystemCommand::Mixin
NAMED_MONTHLY_AMOUNT = 100
URL_MONTHLY_AMOUNT = 1000
cmd_args do
description <<~EOS
Update the list of GitHub Sponsors in the `Homebrew/brew` README.
EOS
named_args :none
end
sig { override.void }
def run
named_sponsors = []
logo_sponsors = []
largest_monthly_amount = T.let(0, Integer)
GitHub.sponsorships("Homebrew").each do |s|
largest_monthly_amount = [s[:monthly_amount], s[:closest_tier_monthly_amount]].max
if largest_monthly_amount >= NAMED_MONTHLY_AMOUNT
named_sponsors << "[#{sponsor_name(s)}](#{sponsor_url(s)})"
end
next if largest_monthly_amount < URL_MONTHLY_AMOUNT
logo_sponsors << "[})](#{sponsor_url(s)})"
end
odie "No sponsorships amounts found! Ensure you have sufficient permissions!" if largest_monthly_amount.zero?
named_sponsors << "many other users and organisations via [GitHub Sponsors](https://github.com/sponsors/Homebrew)"
readme = HOMEBREW_REPOSITORY/"README.md"
content = readme.read
content.gsub!(/(Homebrew is generously supported by) .*\Z/m, "\\1 #{named_sponsors.to_sentence}.\n")
content << "\n#{logo_sponsors.join}\n" if logo_sponsors.presence
File.write(readme, content)
diff = system_command "git", args: [
"-C", HOMEBREW_REPOSITORY, "diff", "--exit-code", "README.md"
]
if diff.status.success?
ofail "No changes to list of sponsors."
else
puts "List of sponsors updated in the README."
end
end
private
sig { params(sponsor: T::Hash[Symbol, String]).returns(T.nilable(String)) }
def sponsor_name(sponsor)
sponsor[:name] || sponsor[:login]
end
sig { params(sponsor: T::Hash[Symbol, String]).returns(String) }
def sponsor_logo(sponsor)
"https://github.com/#{sponsor[:login]}.png?size=64"
end
sig { params(sponsor: T::Hash[Symbol, String]).returns(String) }
def sponsor_url(sponsor)
"https://github.com/#{sponsor[:login]}"
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/dev-cmd/which-update.rb | Library/Homebrew/dev-cmd/which-update.rb | # typed: strict
# frozen_string_literal: true
# License: MIT
# The license text can be found in Library/Homebrew/command-not-found/LICENSE
require "abstract_command"
require "executables_db"
module Homebrew
module DevCmd
class WhichUpdate < AbstractCommand
cmd_args do
description <<~EOS
Database update for `brew which-formula`.
EOS
switch "--stats",
description: "Print statistics about the database contents (number of commands and formulae, " \
"list of missing formulae)."
switch "--commit",
description: "Commit the changes using `git`."
switch "--update-existing",
description: "Update database entries with outdated formula versions."
switch "--install-missing",
description: "Install and update formulae that are missing from the database and don't have bottles."
switch "--eval-all",
description: "Evaluate all installed taps, rather than just the core tap."
flag "--max-downloads=",
description: "Specify a maximum number of formulae to download and update."
flag "--summary-file=",
description: "Output a summary of the changes to a file."
conflicts "--stats", "--commit"
conflicts "--stats", "--install-missing"
conflicts "--stats", "--update-existing"
conflicts "--stats", "--max-downloads"
named_args :database, number: 1
end
sig { override.void }
def run
if args.stats?
stats source: args.named.fetch(0)
else
update_and_save! source: args.named.fetch(0),
commit: args.commit?,
update_existing: args.update_existing?,
install_missing: args.install_missing?,
max_downloads: args.max_downloads&.to_i,
eval_all: args.eval_all?,
summary_file: args.summary_file
end
end
sig { params(source: String).void }
def stats(source:)
opoo "The DB file doesn't exist." unless File.exist? source
db = ExecutablesDB.new source
formulae = db.formula_names
core = Formula.core_names
cmds_count = db.exes.values.reduce(0) { |s, exs| s + exs.binaries.size }
core_percentage = ((formulae & core).size * 1000 / core.size.to_f).round / 10.0
missing = (core - formulae).reject { |f| Formula[f].disabled? }
puts <<~EOS
#{formulae.size} formulae
#{cmds_count} commands
#{core_percentage}% (missing: #{missing * " "})
EOS
unknown = formulae - Formula.full_names
puts "\nUnknown formulae: #{unknown * ", "}." if unknown.any?
nil
end
sig {
params(
source: String,
commit: T::Boolean,
update_existing: T::Boolean,
install_missing: T::Boolean,
max_downloads: T.nilable(Integer),
eval_all: T::Boolean,
summary_file: T.nilable(String),
).void
}
def update_and_save!(source:, commit: false, update_existing: false, install_missing: false,
max_downloads: nil, eval_all: false, summary_file: nil)
db = ExecutablesDB.new source
db.update!(update_existing:, install_missing:,
max_downloads:, eval_all:)
db.save!
if summary_file
msg = summary_file_message(db.changes)
File.open(summary_file, "a") do |file|
file.puts(msg)
end
end
return if !commit || !db.changed?
msg = git_commit_message(db.changes)
safe_system "git", "-C", db.root.to_s, "commit", "-m", msg, source
end
sig { params(els: T::Array[String], verb: String).returns(String) }
def english_list(els, verb)
msg = +""
msg << els.slice(0, 3)&.join(", ")
msg << " and #{els.length - 3} more" if msg.length < 40 && els.length > 3
"#{verb.capitalize} #{msg}"
end
sig { params(changes: ExecutablesDB::Changes).returns(String) }
def git_commit_message(changes)
msg = []
ExecutablesDB::Changes::TYPES.each do |action|
names = changes.send(action)
next if names.empty?
action = "bump version for" if action == :version_bump
msg << english_list(names.to_a.sort, action.to_s)
break
end
msg.join
end
sig { params(changes: ExecutablesDB::Changes).returns(String) }
def summary_file_message(changes)
msg = []
ExecutablesDB::Changes::TYPES.each do |action|
names = changes.send(action)
next if names.empty?
action_heading = action.to_s.split("_").map(&:capitalize).join(" ")
msg << "### #{action_heading}"
msg << ""
names.to_a.sort.each do |name|
msg << "- [`#{name}`](https://formulae.brew.sh/formula/#{name})"
end
end
msg << "No changes" if msg.empty?
<<~MESSAGE
## Database Update Summary
#{msg.join("\n")}
MESSAGE
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/generate-cask-api.rb | Library/Homebrew/dev-cmd/generate-cask-api.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "cask/cask"
require "fileutils"
require "formula"
module Homebrew
module DevCmd
class GenerateCaskApi < AbstractCommand
CASK_JSON_TEMPLATE = <<~EOS
---
layout: cask_json
---
{{ content }}
EOS
cmd_args do
description <<~EOS
Generate `homebrew/cask` API data files for <#{HOMEBREW_API_WWW}>.
The generated files are written to the current directory.
EOS
switch "-n", "--dry-run",
description: "Generate API data without writing it to files."
named_args :none
end
sig { override.void }
def run
tap = CoreCaskTap.instance
raise TapUnavailableError, tap.name unless tap.installed?
unless args.dry_run?
directories = ["_data/cask", "api/cask", "api/cask-source", "cask", "api/internal"].freeze
FileUtils.rm_rf directories
FileUtils.mkdir_p directories
end
Homebrew.with_no_api_env do
tap_migrations_json = JSON.dump(tap.tap_migrations)
File.write("api/cask_tap_migrations.json", tap_migrations_json) unless args.dry_run?
Cask::Cask.generating_hash!
all_casks = {}
latest_macos = MacOSVersion.new(HOMEBREW_MACOS_NEWEST_SUPPORTED).to_sym
Homebrew::SimulateSystem.with(os: latest_macos, arch: :arm) do
tap.cask_files.each do |path|
cask = Cask::CaskLoader.load(path)
name = cask.token
all_casks[name] = cask.to_hash_with_variations
json = JSON.pretty_generate(all_casks[name])
cask_source = path.read
html_template_name = html_template(name)
unless args.dry_run?
File.write("_data/cask/#{name.tr("+", "_")}.json", "#{json}\n")
File.write("api/cask/#{name}.json", CASK_JSON_TEMPLATE)
File.write("api/cask-source/#{name}.rb", cask_source)
File.write("cask/#{name}.html", html_template_name)
end
rescue
onoe "Error while generating data for cask '#{path.stem}'."
raise
end
end
canonical_json = JSON.pretty_generate(tap.cask_renames)
File.write("_data/cask_canonical.json", "#{canonical_json}\n") unless args.dry_run?
OnSystem::VALID_OS_ARCH_TAGS.each do |bottle_tag|
renames = {}
variation_casks = all_casks.to_h do |token, cask|
cask = Homebrew::API.merge_variations(cask, bottle_tag:)
cask["old_tokens"]&.each do |old_token|
renames[old_token] = token
end
[token, cask]
end
json_contents = {
casks: variation_casks,
renames: renames,
tap_migrations: CoreCaskTap.instance.tap_migrations,
}
File.write("api/internal/cask.#{bottle_tag}.json", JSON.generate(json_contents)) unless args.dry_run?
end
end
end
private
sig { params(title: String).returns(String) }
def html_template(title)
<<~EOS
---
title: '#{title}'
layout: cask
---
{{ content }}
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/bump-unversioned-casks.rb | Library/Homebrew/dev-cmd/bump-unversioned-casks.rb | # typed: strict
# frozen_string_literal: true
require "timeout"
require "cask/download"
require "cask/installer"
require "cask/cask_loader"
require "system_command"
require "tap"
require "unversioned_cask_checker"
module Homebrew
module DevCmd
class BumpUnversionedCasks < AbstractCommand
include SystemCommand::Mixin
cmd_args do
description <<~EOS
Check all casks with unversioned URLs in a given <tap> for updates.
EOS
switch "-n", "--dry-run",
description: "Do everything except caching state and opening pull requests."
flag "--limit=",
description: "Maximum runtime in minutes."
flag "--state-file=",
description: "File for caching state."
named_args [:cask, :tap], min: 1, without_api: true
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["bump_unversioned_casks"])
state_file = if args.state_file.present?
Pathname(T.must(args.state_file)).expand_path
else
HOMEBREW_CACHE/"bump_unversioned_casks.json"
end
state_file.dirname.mkpath
state = state_file.exist? ? JSON.parse(state_file.read) : {}
casks = args.named.to_paths(only: :cask, recurse_tap: true).map { |path| Cask::CaskLoader.load(path) }
unversioned_casks = casks.select do |cask|
cask.url&.unversioned? && !cask.livecheck_defined?
end
ohai "Unversioned Casks: #{unversioned_casks.count} (#{state.size} cached)"
checked, unchecked = unversioned_casks.partition { |c| state.key?(c.full_name) }
queue = Queue.new
# Start with random casks which have not been checked.
unchecked.shuffle.each do |c|
queue.enq c
end
# Continue with previously checked casks, ordered by when they were last checked.
checked.sort_by { |c| state.dig(c.full_name, "check_time") }.each do |c|
queue.enq c
end
limit = args.limit.presence&.to_i
end_time = Time.now + (limit * 60) if limit
until queue.empty? || (end_time && end_time < Time.now)
cask = queue.deq
key = cask.full_name
new_state = bump_unversioned_cask(cask, state: state.fetch(key, {}))
next unless new_state
state[key] = new_state
state_file.atomic_write JSON.pretty_generate(state) unless args.dry_run?
end
end
private
sig {
params(cask: Cask::Cask, state: T::Hash[String, T.untyped])
.returns(T.nilable(T::Hash[String, T.untyped]))
}
def bump_unversioned_cask(cask, state:)
ohai "Checking #{cask.full_name}"
unversioned_cask_checker = UnversionedCaskChecker.new(cask)
if !unversioned_cask_checker.single_app_cask? &&
!unversioned_cask_checker.single_pkg_cask? &&
!unversioned_cask_checker.single_qlplugin_cask?
opoo "Skipping, not a single-app or PKG cask."
return
end
last_check_time = state["check_time"]&.then { |t| Time.parse(t) }
check_time = Time.now
if last_check_time && (check_time - last_check_time) / 3600 < 24
opoo "Skipping, already checked within the last 24 hours."
return
end
last_sha256 = state["sha256"]
last_time = state["time"]&.then { |t| Time.parse(t) }
last_file_size = state["file_size"]
download = Cask::Download.new(cask)
time, file_size = begin
download.time_file_size
rescue
[nil, nil]
end
if last_time != time || last_file_size != file_size
sha256 = begin
Timeout.timeout(5 * 60) do
unversioned_cask_checker.installer.download.sha256
end
rescue => e
onoe e
nil
end
if sha256.present? && last_sha256 != sha256
version = begin
Timeout.timeout(60) do
unversioned_cask_checker.guess_cask_version
end
rescue Timeout::Error
onoe "Timed out guessing version for cask '#{cask}'."
nil
end
if version
if cask.version == version
oh1 "Cask #{cask} is up-to-date at #{version}"
else
bump_cask_pr_args = [
"bump-cask-pr",
"--version", version.to_s,
"--sha256", ":no_check",
"--message", "Automatic update via `brew bump-unversioned-casks`.",
cask.sourcefile_path
]
if args.dry_run?
bump_cask_pr_args << "--dry-run"
oh1 "Would bump #{cask} from #{cask.version} to #{version}"
else
oh1 "Bumping #{cask} from #{cask.version} to #{version}"
end
begin
system_command! HOMEBREW_BREW_FILE, args: bump_cask_pr_args
rescue ErrorDuringExecution => e
onoe e
end
end
end
end
end
{
"sha256" => sha256,
"check_time" => check_time.iso8601,
"time" => time&.iso8601,
"file_size" => file_size,
}
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/dev-cmd/pr-automerge.rb | Library/Homebrew/dev-cmd/pr-automerge.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "tap"
require "utils/github"
module Homebrew
module DevCmd
class PrAutomerge < AbstractCommand
cmd_args do
description <<~EOS
Find pull requests that can be automatically merged using `brew pr-publish`.
EOS
flag "--tap=",
description: "Target tap repository (default: `homebrew/core`)."
flag "--workflow=",
description: "Workflow file to use with `brew pr-publish`."
flag "--with-label=",
description: "Pull requests must have this label."
comma_array "--without-labels",
description: "Pull requests must not have these labels (default: " \
"`do not merge`, `new formula`, `automerge-skip`, " \
"`pre-release`, `CI-published-bottle-commits`)."
switch "--without-approval",
description: "Pull requests do not require approval to be merged."
switch "--publish",
description: "Run `brew pr-publish` on matching pull requests."
switch "--autosquash",
description: "Instruct `brew pr-publish` to automatically reformat and reword commits " \
"in the pull request to the preferred format."
switch "--ignore-failures",
description: "Include pull requests that have failing status checks."
named_args :none
end
sig { override.void }
def run
without_labels = args.without_labels || [
"do not merge",
"new formula",
"automerge-skip",
"pre-release",
"CI-published-bottle-commits",
]
tap = Tap.fetch(args.tap || CoreTap.instance.name)
query = "is:pr is:open repo:#{tap.full_name} draft:false"
query += args.ignore_failures? ? " -status:pending" : " status:success"
query += " review:approved" unless args.without_approval?
query += " label:\"#{args.with_label}\"" if args.with_label
without_labels.each { |label| query += " -label:\"#{label}\"" }
odebug "Searching: #{query}"
prs = GitHub.search_issues query
if prs.blank?
ohai "No matching pull requests!"
return
end
ohai "#{prs.count} matching pull #{Utils.pluralize("request", prs.count)}:"
pr_urls = []
prs.each do |pr|
puts "#{tap.full_name unless tap.core_tap?}##{pr["number"]}: #{pr["title"]}"
pr_urls << pr["html_url"]
end
publish_args = ["pr-publish"]
publish_args << "--tap=#{tap}" if tap
publish_args << "--workflow=#{args.workflow}" if args.workflow
publish_args << "--autosquash" if args.autosquash?
if args.publish?
safe_system HOMEBREW_BREW_FILE, *publish_args, *pr_urls
else
ohai "Now run:", " brew #{publish_args.join " "} \\\n #{pr_urls.join " \\\n "}"
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/dev-cmd/generate-formula-api.rb | Library/Homebrew/dev-cmd/generate-formula-api.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
require "formula"
module Homebrew
module DevCmd
class GenerateFormulaApi < AbstractCommand
FORMULA_JSON_TEMPLATE = <<~EOS
---
layout: formula_json
---
{{ content }}
EOS
cmd_args do
description <<~EOS
Generate `homebrew/core` API data files for <#{HOMEBREW_API_WWW}>.
The generated files are written to the current directory.
EOS
switch "-n", "--dry-run",
description: "Generate API data without writing it to files."
named_args :none
end
sig { override.void }
def run
tap = CoreTap.instance
raise TapUnavailableError, tap.name unless tap.installed?
unless args.dry_run?
directories = ["_data/formula", "api/formula", "formula", "api/internal"]
FileUtils.rm_rf directories + ["_data/formula_canonical.json"]
FileUtils.mkdir_p directories
end
Homebrew.with_no_api_env do
tap_migrations_json = JSON.dump(tap.tap_migrations)
File.write("api/formula_tap_migrations.json", tap_migrations_json) unless args.dry_run?
Formulary.enable_factory_cache!
Formula.generating_hash!
all_formulae = {}
latest_macos = MacOSVersion.new((HOMEBREW_MACOS_NEWEST_UNSUPPORTED.to_i - 1).to_s).to_sym
Homebrew::SimulateSystem.with(os: latest_macos, arch: :arm) do
tap.formula_names.each do |name|
formula = Formulary.factory(name)
name = formula.name
all_formulae[name] = formula.to_hash_with_variations
json = JSON.pretty_generate(all_formulae[name])
html_template_name = html_template(name)
unless args.dry_run?
File.write("_data/formula/#{name.tr("+", "_")}.json", "#{json}\n")
File.write("api/formula/#{name}.json", FORMULA_JSON_TEMPLATE)
File.write("formula/#{name}.html", html_template_name)
end
rescue
onoe "Error while generating data for formula '#{name}'."
raise
end
end
canonical_json = JSON.pretty_generate(tap.formula_renames.merge(tap.alias_table))
File.write("_data/formula_canonical.json", "#{canonical_json}\n") unless args.dry_run?
OnSystem::VALID_OS_ARCH_TAGS.each do |bottle_tag|
macos_version = bottle_tag.to_macos_version if bottle_tag.macos?
aliases = {}
renames = {}
variation_formulae = all_formulae.to_h do |name, formula|
formula = Homebrew::API.merge_variations(formula, bottle_tag:)
formula["aliases"]&.each do |alias_name|
aliases[alias_name] = name
end
formula["oldnames"]&.each do |oldname|
renames[oldname] = name
end
version = Version.new(formula.dig("versions", "stable"))
pkg_version = PkgVersion.new(version, formula["revision"])
version_scheme = formula.fetch("version_scheme", 0)
rebuild = formula.dig("bottle", "stable", "rebuild") || 0
bottle_collector = Utils::Bottles::Collector.new
formula.dig("bottle", "stable", "files")&.each do |tag, data|
tag = Utils::Bottles::Tag.from_symbol(tag)
bottle_collector.add tag, checksum: Checksum.new(data["sha256"]), cellar: :any
end
sha256 = bottle_collector.specification_for(bottle_tag)&.checksum&.to_s
dependencies = Set.new(formula["dependencies"])
if macos_version
uses_from_macos = formula["uses_from_macos"].zip(formula["uses_from_macos_bounds"])
dependencies += uses_from_macos.filter_map do |dep, bounds|
next if bounds.blank?
since = bounds[:since]
next if since.blank?
since_macos_version = MacOSVersion.from_symbol(since)
next if since_macos_version <= macos_version
dep
end
else
dependencies += formula["uses_from_macos"]
end
[name, [pkg_version.to_s, version_scheme, rebuild, sha256, dependencies.to_a]]
end
json_contents = {
formulae: variation_formulae,
casks: [],
aliases: aliases,
renames: renames,
tap_migrations: CoreTap.instance.tap_migrations,
}
File.write("api/internal/formula.#{bottle_tag}.json", JSON.generate(json_contents)) unless args.dry_run?
end
end
end
private
sig { params(title: String).returns(String) }
def html_template(title)
<<~EOS
---
title: '#{title}'
layout: formula
redirect_from: /formula-linux/#{title}
---
{{ content }}
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/update-perl-resources.rb | Library/Homebrew/dev-cmd/update-perl-resources.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "utils/cpan"
module Homebrew
module DevCmd
class UpdatePerlResources < AbstractCommand
cmd_args do
description <<~EOS
Update versions for CPAN resource blocks in <formula>.
EOS
switch "-p", "--print-only",
description: "Print the updated resource blocks instead of changing <formula>."
switch "-s", "--silent",
description: "Suppress any output."
switch "--ignore-errors",
description: "Continue processing even if some resources can't be resolved."
named_args :formula, min: 1, without_api: true
end
sig { override.void }
def run
args.named.to_formulae.each do |formula|
CPAN.update_perl_resources! formula,
print_only: args.print_only?,
silent: args.silent?,
verbose: args.verbose?,
ignore_errors: args.ignore_errors?
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/dev-cmd/update-test.rb | Library/Homebrew/dev-cmd/update-test.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module DevCmd
class UpdateTest < AbstractCommand
include FileUtils
cmd_args do
description <<~EOS
Run a test of `brew update` with a new repository clone.
If no options are passed, use `origin/main` as the start commit.
EOS
switch "--to-tag",
description: "Set `$HOMEBREW_UPDATE_TO_TAG` to test updating between tags."
switch "--keep-tmp",
description: "Retain the temporary directory containing the new repository clone."
flag "--commit=",
description: "Use the specified <commit> as the start commit."
flag "--before=",
description: "Use the commit at the specified <date> as the start commit."
named_args :none
end
sig { override.void }
def run
# Avoid `update-report.rb` tapping Homebrew/homebrew-core
ENV["HOMEBREW_UPDATE_TEST"] = "1"
# Avoid accidentally updating when we don't expect it.
ENV["HOMEBREW_NO_AUTO_UPDATE"] = "1"
# Use default behaviours
ENV["HOMEBREW_AUTO_UPDATE_SECS"] = nil
ENV["HOMEBREW_DEVELOPER"] = nil
ENV["HOMEBREW_DEV_CMD_RUN"] = nil
ENV["HOMEBREW_MERGE"] = nil
ENV["HOMEBREW_NO_UPDATE_CLEANUP"] = nil
ENV["HOMEBREW_UPDATE_TO_TAG"] = nil
branch = if args.to_tag?
ENV["HOMEBREW_UPDATE_TO_TAG"] = "1"
"stable"
else
ENV["HOMEBREW_DEV_CMD_RUN"] = "1"
"main"
end
# Utils.popen_read returns a String without a block argument, but that isn't easily typed. We thus label this
# as untyped for now.
start_commit = T.let("", T.untyped)
end_commit = "HEAD"
cd HOMEBREW_REPOSITORY do
start_commit = if (commit = args.commit)
commit
elsif (date = args.before)
Utils.popen_read("git", "rev-list", "-n1", "--before=#{date}", "origin/main").chomp
elsif args.to_tag?
tags = git_tags
current_tag, previous_tag, = tags.lines
current_tag = current_tag.to_s.chomp
odie "Could not find current tag in:\n#{tags}" if current_tag.empty?
# ^0 ensures this points to the commit rather than the tag object.
end_commit = "#{current_tag}^0"
previous_tag = previous_tag.to_s.chomp
odie "Could not find previous tag in:\n#{tags}" if previous_tag.empty?
# ^0 ensures this points to the commit rather than the tag object.
"#{previous_tag}^0"
else
Utils.popen_read("git", "merge-base", "origin/main", end_commit).chomp
end
odie "Could not find start commit!" if start_commit.empty?
start_commit = Utils.popen_read("git", "rev-parse", start_commit).chomp
odie "Could not find start commit!" if start_commit.empty?
end_commit = T.cast(Utils.popen_read("git", "rev-parse", end_commit).chomp, String)
odie "Could not find end commit!" if end_commit.empty?
if Utils.popen_read("git", "branch", "--list", "main").blank?
safe_system "git", "branch", "main", "origin/HEAD"
end
end
puts <<~EOS
Start commit: #{start_commit}
End commit: #{end_commit}
EOS
mkdir "update-test"
chdir "update-test" do
curdir = Pathname.new(Dir.pwd)
oh1 "Preparing test environment..."
# copy Homebrew installation
safe_system "git", "clone", "#{HOMEBREW_REPOSITORY}/.git", ".",
"--branch", "main", "--single-branch"
# set git origin to another copy
safe_system "git", "clone", "#{HOMEBREW_REPOSITORY}/.git", "remote.git",
"--bare", "--branch", "main", "--single-branch"
safe_system "git", "config", "remote.origin.url", "#{curdir}/remote.git"
ENV["HOMEBREW_BREW_GIT_REMOTE"] = "#{curdir}/remote.git"
# force push origin to end_commit
safe_system "git", "checkout", "-B", "main", end_commit
safe_system "git", "push", "--force", "origin", "main"
# set test copy to start_commit
safe_system "git", "reset", "--hard", start_commit
# update ENV["PATH"]
ENV["PATH"] = PATH.new(ENV.fetch("PATH")).prepend(curdir/"bin").to_s
# Run `brew help` to install `portable-ruby` (if needed).
quiet_system "brew", "help"
# run brew update
oh1 "Running `brew update`..."
safe_system "brew", "update", "--verbose", "--debug"
actual_end_commit = Utils.popen_read("git", "rev-parse", branch).chomp
if actual_end_commit != end_commit
start_log = Utils.popen_read("git", "log", "-1", "--decorate", "--oneline", start_commit).chomp
end_log = Utils.popen_read("git", "log", "-1", "--decorate", "--oneline", end_commit).chomp
actual_log = Utils.popen_read("git", "log", "-1", "--decorate", "--oneline", actual_end_commit).chomp
odie <<~EOS
`brew update` didn't update #{branch}!
Start commit: #{start_log}
Expected end commit: #{end_log}
Actual end commit: #{actual_log}
EOS
end
end
ensure
FileUtils.rm_rf "update-test" unless args.keep_tmp?
end
private
sig { returns(String) }
def git_tags
tags = Utils.popen_read("git", "tag", "--list", "--sort=-version:refname")
if tags.blank?
tags = if (HOMEBREW_REPOSITORY/".git/shallow").exist?
safe_system "git", "fetch", "--tags", "--depth=1"
Utils.popen_read("git", "tag", "--list", "--sort=-version:refname")
end
end
tags
end
end
end
end
require "extend/os/dev-cmd/update-test"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/irb.rb | Library/Homebrew/dev-cmd/irb.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "formulary"
require "cask/cask_loader"
class String
# @!visibility private
sig { params(args: Integer).returns(Formula) }
def f(*args)
Formulary.factory(self, *args)
end
# @!visibility private
sig { params(config: T.nilable(T::Hash[Symbol, T.untyped])).returns(Cask::Cask) }
def c(config: nil)
Cask::CaskLoader.load(self, config:)
end
end
class Symbol
# @!visibility private
sig { params(args: Integer).returns(Formula) }
def f(*args)
to_s.f(*args)
end
# @!visibility private
sig { params(config: T.nilable(T::Hash[Symbol, T.untyped])).returns(Cask::Cask) }
def c(config: nil)
to_s.c(config:)
end
end
module Homebrew
module DevCmd
class Irb < AbstractCommand
cmd_args do
description <<~EOS
Enter the interactive Homebrew Ruby shell.
EOS
switch "--examples",
description: "Show several examples."
switch "--pry",
description: "Use Pry instead of IRB.",
env: :pry
end
# work around IRB modifying ARGV.
sig { params(argv: T.nilable(T::Array[String])).void }
def initialize(argv = nil) = super(argv || ARGV.dup.freeze)
sig { override.void }
def run
clean_argv
if args.examples?
puts <<~EOS
'v8'.f # => instance of the v8 formula
:hub.f.latest_version_installed?
:lua.f.methods - 1.methods
:mpd.f.recursive_dependencies.reject(&:installed?)
'vlc'.c # => instance of the vlc cask
:tsh.c.livecheck_defined?
EOS
return
end
if args.pry?
Homebrew.install_bundler_gems!(groups: ["pry"])
require "pry"
else
require "irb"
end
require "keg"
require "cask"
ohai "Interactive Homebrew Shell", "Example commands available with: `brew irb --examples`"
if args.pry?
Pry.config.should_load_rc = false # skip loading .pryrc
Pry.config.history_file = "#{Dir.home}/.brew_pry_history"
Pry.config.prompt_name = "brew"
Pry.start
else
ENV["IRBRC"] = (HOMEBREW_LIBRARY_PATH/"brew_irbrc").to_s
IRB.start
end
end
private
# Remove the `--debug`, `--verbose` and `--quiet` options which cause problems
# for IRB and have already been parsed by the CLI::Parser.
sig { returns(T.nilable(T::Array[Symbol])) }
def clean_argv
global_options = Homebrew::CLI::Parser
.global_options
.flat_map { |options| options[0..1] }
ARGV.reject! { |arg| global_options.include?(arg) }
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/dev-cmd/prof.rb | Library/Homebrew/dev-cmd/prof.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module DevCmd
class Prof < AbstractCommand
cmd_args do
description <<~EOS
Run Homebrew with a Ruby profiler. For example, `brew prof readall`.
EOS
switch "--stackprof",
description: "Use `stackprof` instead of `ruby-prof` (the default)."
switch "--vernier",
description: "Use `vernier` instead of `ruby-prof` (the default)."
named_args :command, min: 1
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["prof"], setup_path: false)
brew_rb = (HOMEBREW_LIBRARY_PATH/"brew.rb").resolved_path
FileUtils.mkdir_p "prof"
cmd = T.must(args.named.first)
case Commands.path(cmd)&.extname
when ".rb"
# expected file extension so we do nothing
when ".sh"
raise UsageError, <<~EOS
`#{cmd}` is a Bash command!
Try `hyperfine` for benchmarking instead.
EOS
else
raise UsageError, "`#{cmd}` is an unknown command!"
end
Homebrew.setup_gem_environment!
if args.stackprof?
with_env HOMEBREW_STACKPROF: "1" do
system(*HOMEBREW_RUBY_EXEC_ARGS, brew_rb, *args.named)
end
output_filename = "prof/d3-flamegraph.html"
safe_system "stackprof --d3-flamegraph prof/stackprof.dump > #{output_filename}"
exec_browser output_filename
elsif args.vernier?
output_filename = "prof/vernier.json"
Process::UID.change_privilege(Process.euid) if Process.euid != Process.uid
safe_system "vernier", "run", "--output=#{output_filename}", "--allocation_interval=500", "--",
RUBY_PATH, brew_rb, *args.named
ohai "Profiling complete!"
puts "Upload the results from #{output_filename} to:"
puts " #{Formatter.url("https://vernier.prof")}"
else
output_filename = "prof/call_stack.html"
safe_system "ruby-prof", "--printer=call_stack", "--file=#{output_filename}", brew_rb, "--", *args.named
exec_browser output_filename
end
rescue OptionParser::InvalidOption => e
ofail e
# The invalid option could have been meant for the subcommand.
# Suggest `brew prof list -r` -> `brew prof -- list -r`
args = ARGV - ["--"]
puts "Try `brew prof -- #{args.join(" ")}` instead."
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/dev-cmd/update-maintainers.rb | Library/Homebrew/dev-cmd/update-maintainers.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "utils/github"
require "manpages"
require "system_command"
module Homebrew
module DevCmd
class UpdateMaintainers < AbstractCommand
include SystemCommand::Mixin
cmd_args do
description <<~EOS
Update the list of maintainers in the `Homebrew/brew` README.
EOS
named_args :none
end
sig { override.void }
def run
# Needed for Manpages.regenerate_man_pages below
Homebrew.install_bundler_gems!(groups: ["man"])
lead_maintainers = GitHub.members_by_team("Homebrew", "lead-maintainers")
maintainers = GitHub.members_by_team("Homebrew", "maintainers")
.reject { |login, _| lead_maintainers.key?(login) }
members = { lead_maintainers:, maintainers: }
sentences = {}
members.each do |group, hash|
hash.each { |login, name| hash[login] = "[#{name}](https://github.com/#{login})" }
sentences[group] = hash.values.sort_by { |s| s.unicode_normalize(:nfd).gsub(/\P{L}+/, "") }.to_sentence
end
readme = HOMEBREW_REPOSITORY/"README.md"
content = readme.read
content.gsub!(/(Homebrew's \[Lead Maintainers.* (are|is)) .*\./,
"\\1 #{sentences[:lead_maintainers]}.")
content.gsub!(/(Homebrew's other Maintainers (are|is)) .*\./,
"\\1 #{sentences[:maintainers]}.")
File.write(readme, content)
diff = system_command "git", args: ["-C", HOMEBREW_REPOSITORY, "diff", "--exit-code", "README.md"]
if diff.status.success?
ofail "No changes to list of maintainers."
else
Manpages.regenerate_man_pages(quiet: true)
puts "List of maintainers updated in the README and the generated man pages."
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/dev-cmd/tap-new.rb | Library/Homebrew/dev-cmd/tap-new.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "erb"
require "fileutils"
require "tap"
require "utils/uid"
module Homebrew
module DevCmd
class TapNew < AbstractCommand
include FileUtils
cmd_args do
usage_banner "`tap-new` [<options>] <user>`/`<repo>"
description <<~EOS
Generate the template files for a new tap.
EOS
switch "--no-git",
description: "Don't initialize a Git repository for the tap."
flag "--pull-label=",
description: "Label name for pull requests ready to be pulled (default: `pr-pull`)."
flag "--branch=",
description: "Initialize Git repository and setup GitHub Actions workflows with the " \
"specified branch name (default: `main`)."
switch "--github-packages",
description: "Upload bottles to GitHub Packages."
named_args :tap, number: 1
end
sig { override.void }
def run
label = args.pull_label || "pr-pull"
branch = args.branch || "main"
tap = args.named.to_taps.fetch(0)
odie "Invalid tap name '#{tap}'" unless tap.path.to_s.match?(HOMEBREW_TAP_PATH_REGEX)
odie "Tap is already installed!" if tap.installed?
titleized_user = tap.user.dup
titleized_repository = tap.repository.dup
titleized_user[0] = T.must(titleized_user[0]).upcase
titleized_repository[0] = T.must(titleized_repository[0]).upcase
# Duplicate assignment to silence `assigned but unused variable` warning
root_url = root_url = GitHubPackages.root_url(tap.user, "homebrew-#{tap.repository}") if args.github_packages?
(tap.path/"Formula").mkpath
readme = <<~MARKDOWN
# #{titleized_user} #{titleized_repository}
## How do I install these formulae?
`brew install #{tap}/<formula>`
Or `brew tap #{tap}` and then `brew install <formula>`.
Or, in a `brew bundle` `Brewfile`:
```ruby
tap "#{tap}"
brew "<formula>"
```
## Documentation
`brew help`, `man brew` or check [Homebrew's documentation](https://docs.brew.sh).
MARKDOWN
write_path(tap, "README.md", readme)
tests_yml = <<~ERB
name: brew test-bot
on:
push:
branches:
- <%= branch %>
pull_request:
jobs:
test-bot:
strategy:
matrix:
os: [ ubuntu-22.04, macos-15-intel, macos-26 ]
runs-on: ${{ matrix.os }}
permissions:
actions: read
checks: read
contents: read
<% if args.github_packages? -%>
packages: read
<% end -%>
pull-requests: read
steps:
- name: Set up Homebrew
id: set-up-homebrew
uses: Homebrew/actions/setup-homebrew@main
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Cache Homebrew Bundler RubyGems
uses: actions/cache@v4
with:
path: ${{ steps.set-up-homebrew.outputs.gems-path }}
key: ${{ matrix.os }}-rubygems-${{ steps.set-up-homebrew.outputs.gems-hash }}
restore-keys: ${{ matrix.os }}-rubygems-
- run: brew test-bot --only-cleanup-before
- run: brew test-bot --only-setup
- run: brew test-bot --only-tap-syntax
<% if args.github_packages? -%>
- name: Base64-encode GITHUB_TOKEN for HOMEBREW_DOCKER_REGISTRY_TOKEN
id: base64-encode
if: github.event_name == 'pull_request'
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
base64_token=$(echo -n "${TOKEN}" | base64 | tr -d "\\n")
echo "::add-mask::${base64_token}"
echo "token=${base64_token}" >> "${GITHUB_OUTPUT}"
<% end -%>
- run: brew test-bot --only-formulae#{" --root-url=#{root_url}" if root_url}
if: github.event_name == 'pull_request'
<% if args.github_packages? -%>
env:
HOMEBREW_DOCKER_REGISTRY_TOKEN: ${{ steps.base64-encode.outputs.token }}
<% end -%>
- name: Upload bottles as artifact
if: always() && github.event_name == 'pull_request'
uses: actions/upload-artifact@v4
with:
name: bottles_${{ matrix.os }}
path: '*.bottle.*'
ERB
publish_yml = <<~ERB
name: brew pr-pull
on:
pull_request_target:
types:
- labeled
jobs:
pr-pull:
if: contains(github.event.pull_request.labels.*.name, '<%= label %>')
runs-on: ubuntu-22.04
permissions:
actions: read
checks: read
contents: write
issues: read
<% if args.github_packages? -%>
packages: write
<% end -%>
pull-requests: write
steps:
- name: Set up Homebrew
uses: Homebrew/actions/setup-homebrew@main
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Set up git
uses: Homebrew/actions/git-user-config@main
- name: Pull bottles
env:
HOMEBREW_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
<% if args.github_packages? -%>
HOMEBREW_GITHUB_PACKAGES_TOKEN: ${{ secrets.GITHUB_TOKEN }}
HOMEBREW_GITHUB_PACKAGES_USER: ${{ github.repository_owner }}
<% end -%>
PULL_REQUEST: ${{ github.event.pull_request.number }}
run: brew pr-pull --debug --tap="$GITHUB_REPOSITORY" "$PULL_REQUEST"
- name: Push commits
uses: Homebrew/actions/git-try-push@main
with:
branch: <%= branch %>
- name: Delete branch
if: github.event.pull_request.head.repo.fork == false
env:
BRANCH: ${{ github.event.pull_request.head.ref }}
run: git push --delete origin "$BRANCH"
ERB
(tap.path/".github/workflows").mkpath
write_path(tap, ".github/workflows/tests.yml", ERB.new(tests_yml, trim_mode: "-").result(binding))
write_path(tap, ".github/workflows/publish.yml", ERB.new(publish_yml, trim_mode: "-").result(binding))
unless args.no_git?
cd tap.path do |path|
Utils::Git.set_name_email!
Utils::Git.setup_gpg!
# Would be nice to use --initial-branch here but it's not available in
# older versions of Git that we support.
safe_system "git", "-c", "init.defaultBranch=#{branch}", "init"
args = []
git_owner = File.stat(File.join(path, ".git")).uid
if git_owner != Process.uid && git_owner == Process.euid
# Under Homebrew user model, EUID is permitted to execute commands under the UID.
# Root users are never allowed (see brew.sh).
args << "-c" << "safe.directory=#{path}"
end
# Use the configuration of the original user, which will have author information and signing keys.
Utils::UID.drop_euid do
env = { HOME: Utils::UID.uid_home }.compact
env[:TMPDIR] = nil if (tmpdir = ENV.fetch("TMPDIR", nil)) && !File.writable?(tmpdir)
with_env(env) do
safe_system "git", *args, "add", "--all"
safe_system "git", *args, "commit", "-m", "Create #{tap} tap"
safe_system "git", *args, "branch", "-m", branch
end
end
end
end
ohai "Created #{tap}"
puts <<~EOS
#{tap.path}
When a pull request making changes to a formula (or formulae) becomes green
(all checks passed), then you can publish the built bottles.
To do so, label your PR as `#{label}` and the workflow will be triggered.
EOS
end
private
sig { params(tap: Tap, filename: T.any(String, Pathname), content: String).void }
def write_path(tap, filename, content)
path = tap.path/filename
tap.path.mkpath
odie "#{path} already exists" if path.exist?
path.write content
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/generate-cask-ci-matrix.rb | Library/Homebrew/dev-cmd/generate-cask-ci-matrix.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "tap"
require "utils/github/api"
require "cli/parser"
require "system_command"
module Homebrew
module DevCmd
class GenerateCaskCiMatrix < AbstractCommand
MAX_JOBS = 256
# Weight for each arch must add up to 1.0.
X86_MACOS_RUNNERS = T.let({
{ symbol: :sequoia, name: "macos-15-intel", arch: :intel } => 1.0,
}.freeze, T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float])
X86_LINUX_RUNNERS = T.let({
{ symbol: :linux, name: "ubuntu-22.04", arch: :intel } => 1.0,
}.freeze, T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float])
ARM_MACOS_RUNNERS = T.let({
{ symbol: :sonoma, name: "macos-14", arch: :arm } => 0.0,
{ symbol: :sequoia, name: "macos-15", arch: :arm } => 0.0,
{ symbol: :tahoe, name: "macos-26", arch: :arm } => 1.0,
}.freeze, T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float])
ARM_LINUX_RUNNERS = T.let({
{ symbol: :linux, name: "ubuntu-22.04-arm", arch: :arm } => 1.0,
}.freeze, T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float])
MACOS_RUNNERS = T.let(X86_MACOS_RUNNERS.merge(ARM_MACOS_RUNNERS).freeze,
T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float])
LINUX_RUNNERS = T.let(X86_LINUX_RUNNERS.merge(ARM_LINUX_RUNNERS).freeze,
T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float])
RUNNERS = T.let(MACOS_RUNNERS.merge(LINUX_RUNNERS).freeze,
T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float])
cmd_args do
description <<~EOS
Generate a GitHub Actions matrix for a given pull request URL or list of cask names.
For internal use in Homebrew taps.
EOS
switch "--url",
description: "Treat named argument as a pull request URL."
switch "--cask", "--casks",
description: "Treat all named arguments as cask tokens."
switch "--skip-install",
description: "Skip installing casks."
switch "--new",
description: "Run new cask checks."
switch "--syntax-only",
description: "Only run syntax checks."
conflicts "--url", "--cask"
conflicts "--syntax-only", "--skip-install"
conflicts "--syntax-only", "--new"
named_args [:cask, :url], min: 0
hide_from_man_page!
end
sig { override.void }
def run
skip_install = args.skip_install?
new_cask = args.new?
casks = args.named if args.casks?
pr_url = args.named if args.url?
syntax_only = args.syntax_only?
repository = ENV.fetch("GITHUB_REPOSITORY", nil)
raise UsageError, "The `$GITHUB_REPOSITORY` environment variable must be set." if repository.blank?
tap = T.let(Tap.fetch(repository), Tap)
unless syntax_only
raise UsageError, "Either `--cask` or `--url` must be specified." if !args.casks? && !args.url?
raise UsageError, "Please provide a `--cask` or `--url` argument." if casks.blank? && pr_url.blank?
end
raise UsageError, "Only one `--url` can be specified." if pr_url&.count&.> 1
labels = if pr_url && (first_pr_url = pr_url.first)
pr = GitHub::API.open_rest(first_pr_url)
pr.fetch("labels").map { |l| l.fetch("name") }
else
[]
end
runner = random_runner[:name]
syntax_job = {
name: "syntax",
tap: tap.name,
runner:,
}
matrix = [syntax_job]
if !syntax_only && !labels&.include?("ci-syntax-only")
cask_jobs = if casks&.any?
generate_matrix(tap, labels:, cask_names: casks, skip_install:, new_cask:)
else
generate_matrix(tap, labels:, skip_install:, new_cask:)
end
if cask_jobs.any?
# If casks were changed, skip `audit` for whole tap.
syntax_job[:skip_audit] = true
# The syntax job only runs `style` at this point, which should work on Linux.
# Running on macOS is currently faster though, since `homebrew/cask` and
# `homebrew/core` are already tapped on macOS CI machines.
# syntax_job[:runner] = "ubuntu-latest"
end
matrix += cask_jobs
end
syntax_job[:name] += " (#{syntax_job[:runner]})"
puts JSON.pretty_generate(matrix)
github_output = ENV.fetch("GITHUB_OUTPUT", nil)
return unless github_output
File.open(ENV.fetch("GITHUB_OUTPUT"), "a") do |f|
f.puts "matrix=#{JSON.generate(matrix)}"
end
end
sig { params(cask: Cask::Cask).returns(T::Hash[T::Hash[Symbol, T.any(Symbol, String)], Float]) }
def filter_runners(cask)
filtered_macos_runners = RUNNERS.select do |runner, _|
runner[:symbol] != :linux &&
cask.depends_on.macos.present? &&
cask.depends_on.macos.allows?(MacOSVersion.from_symbol(T.must(runner[:symbol]).to_sym))
end
filtered_runners = if filtered_macos_runners.any?
filtered_macos_runners
else
RUNNERS.dup
end
filtered_runners = filtered_runners.merge(LINUX_RUNNERS) if cask.supports_linux?
archs = architectures(cask:)
filtered_runners.select! do |runner, _|
archs.include?(runner.fetch(:arch))
end
filtered_runners
end
sig { params(cask: Cask::Cask).returns(T::Array[Symbol]) }
def architectures(cask:)
return RUNNERS.keys.map { |r| r.fetch(:arch).to_sym }.uniq.sort if cask.depends_on.arch.blank?
cask.depends_on.arch.map { |arch| arch[:type] }.uniq.sort
end
sig {
params(available_runners: T::Hash[T::Hash[Symbol, T.any(Symbol, String)],
Float]).returns(T::Hash[Symbol, T.any(Symbol, String)])
}
def random_runner(available_runners = ARM_MACOS_RUNNERS)
T.must(available_runners.max_by { |(_, weight)| rand ** (1.0 / weight) })
.first
end
sig { params(cask: Cask::Cask).returns([T::Array[T::Hash[Symbol, T.any(Symbol, String)]], T::Boolean]) }
def runners(cask:)
filtered_runners = filter_runners(cask)
filtered_macos_found = filtered_runners.keys.any? do |runner|
cask.to_hash_with_variations["variations"].key?(T.must(runner[:symbol]).to_sym)
end
if filtered_macos_found
# If the cask varies on a MacOS version, test it on every possible macOS version.
[filtered_runners.keys, true]
else
# Otherwise, select a runner from each architecture based on weighted random sample.
grouped_runners = filtered_runners.group_by { |runner, _| runner.fetch(:arch) }
selected_runners = grouped_runners.map do |_, runners|
random_runner(runners.to_h)
end
[selected_runners, false]
end
end
sig {
params(tap: T.nilable(Tap), labels: T::Array[String], cask_names: T::Array[String], skip_install: T::Boolean,
new_cask: T::Boolean).returns(T::Array[T::Hash[Symbol,
T.any(String, T::Boolean, T::Array[String])]])
}
def generate_matrix(tap, labels: [], cask_names: [], skip_install: false, new_cask: false)
odie "This command must be run from inside a tap directory." unless tap
changed_files = find_changed_files(tap)
ruby_files_in_wrong_directory =
T.must(changed_files[:modified_ruby_files]) - (
T.must(changed_files[:modified_cask_files]) +
T.must(changed_files[:modified_command_files]) +
T.must(changed_files[:modified_github_actions_files])
)
if ruby_files_in_wrong_directory.any?
ruby_files_in_wrong_directory.each do |path|
puts "::error file=#{path}::File is in wrong directory."
end
odie "Found Ruby files in wrong directory:\n#{ruby_files_in_wrong_directory.join("\n")}"
end
cask_files_to_check = if cask_names.any?
cask_names.map do |cask_name|
Cask::CaskLoader.find_cask_in_tap(cask_name, tap).relative_path_from(tap.path)
end
else
T.must(changed_files[:modified_cask_files])
end
jobs = cask_files_to_check.count
odie "Maximum job matrix size exceeded: #{jobs}/#{MAX_JOBS}" if jobs > MAX_JOBS
cask_files_to_check.flat_map do |path|
cask_token = path.basename(".rb")
audit_args = ["--online", "--signing"]
audit_args << "--new" if T.must(changed_files[:added_files]).include?(path) || new_cask
audit_exceptions = []
audit_exceptions << %w[homepage_https_availability] if labels.include?("ci-skip-homepage")
if labels.include?("ci-skip-livecheck")
audit_exceptions << %w[hosting_with_livecheck livecheck_https_availability livecheck_version min_os]
end
audit_exceptions << "min_os" if labels.include?("ci-skip-livecheck-min-os")
if labels.include?("ci-skip-repository")
audit_exceptions << %w[github_repository github_prerelease_version
gitlab_repository gitlab_prerelease_version
bitbucket_repository]
end
audit_exceptions << %w[token_valid token_bad_words] if labels.include?("ci-skip-token")
audit_args << "--except" << audit_exceptions.join(",") if audit_exceptions.any?
cask = Cask::CaskLoader.load(path.expand_path)
runners, multi_os = runners(cask:)
runners.product(architectures(cask:)).filter_map do |runner, arch|
native_runner_arch = arch == runner.fetch(:arch)
# we don't need to run simulated archs on Linux
next if runner.fetch(:symbol) == :linux && !native_runner_arch
# we don't need to run simulated archs on macOS
next if runner.fetch(:symbol) == :sequoia && !native_runner_arch
# If it's just a single OS test then we can just use the two real arch runners.
next if !native_runner_arch && !multi_os
arch_args = native_runner_arch ? [] : ["--arch=#{arch}"]
runner_output = {
name: "test #{cask_token} (#{runner.fetch(:name)}, #{arch})",
tap: tap.name,
cask: {
token: cask_token,
path: "./#{path}",
},
audit_args: audit_args + arch_args,
fetch_args: arch_args,
skip_install: labels.include?("ci-skip-install") || !native_runner_arch || skip_install,
runner: runner.fetch(:name),
}
if runner.fetch(:symbol) == :linux
runner_output[:container] = {
image: "ghcr.io/homebrew/ubuntu22.04:main",
options: "--user=linuxbrew",
}
end
runner_output
end
end
end
sig { params(tap: Tap).returns(T::Hash[Symbol, T::Array[String]]) }
def find_changed_files(tap)
commit_range_start = Utils.safe_popen_read("git", "rev-parse", "origin").chomp
commit_range_end = Utils.safe_popen_read("git", "rev-parse", "HEAD").chomp
commit_range = "#{commit_range_start}...#{commit_range_end}"
modified_files = Utils.safe_popen_read("git", "diff", "--name-only", "--diff-filter=AMR", commit_range)
.split("\n")
.map do |path|
Pathname(path)
end
added_files = Utils.safe_popen_read("git", "diff", "--name-only", "--diff-filter=A", commit_range)
.split("\n")
.map do |path|
Pathname(path)
end
modified_ruby_files = modified_files.select { |path| path.extname == ".rb" }
modified_command_files = modified_files.select { |path| path.ascend.to_a.last.to_s == "cmd" }
modified_github_actions_files = modified_files.select do |path|
path.to_s.start_with?(".github/actions/")
end
modified_cask_files = modified_files.select { |path| tap.cask_file?(path.to_s) }
{
modified_files:,
added_files:,
modified_ruby_files:,
modified_command_files:,
modified_github_actions_files:,
modified_cask_files:,
}
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/dev-cmd/bump.rb | Library/Homebrew/dev-cmd/bump.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "bump_version_parser"
require "livecheck/livecheck"
require "utils/repology"
module Homebrew
module DevCmd
class Bump < AbstractCommand
NEWER_THAN_UPSTREAM_MSG = " (newer than upstream)"
class VersionBumpInfo < T::Struct
const :type, Symbol
const :multiple_versions, T::Boolean
const :version_name, String
const :current_version, BumpVersionParser
const :repology_latest, T.any(String, Version)
const :new_version, BumpVersionParser
const :newer_than_upstream, T::Hash[Symbol, T::Boolean], default: {}
const :duplicate_pull_requests, T.nilable(T.any(T::Array[String], String))
const :maybe_duplicate_pull_requests, T.nilable(T.any(T::Array[String], String))
end
cmd_args do
description <<~EOS
Displays out-of-date packages and the latest version available. If the
returned current and livecheck versions differ or when querying specific
packages, also displays whether a pull request has been opened with the URL.
EOS
switch "--full-name",
description: "Print formulae/casks with fully-qualified names."
switch "--no-pull-requests",
description: "Do not retrieve pull requests from GitHub."
switch "--auto",
description: "Read the list of formulae/casks from the tap autobump list.",
hidden: true
switch "--no-autobump",
description: "Ignore formulae/casks in autobump list (official repositories only)."
switch "--formula", "--formulae",
description: "Check only formulae."
switch "--cask", "--casks",
description: "Check only casks."
switch "--eval-all",
description: "Evaluate all formulae and casks.",
env: :eval_all
switch "--repology",
description: "Use Repology to check for outdated packages."
flag "--tap=",
description: "Check formulae and casks within the given tap, specified as <user>`/`<repo>."
switch "--installed",
description: "Check formulae and casks that are currently installed."
switch "--no-fork",
description: "Don't try to fork the repository."
switch "--open-pr",
description: "Open a pull request for the new version if none have been opened yet."
flag "--start-with=",
description: "Letter or word that the list of package results should alphabetically follow."
switch "--bump-synced",
description: "Bump additional formulae marked as synced with the given formulae."
conflicts "--formula", "--cask"
conflicts "--tap", "--installed"
conflicts "--tap", "--no-autobump"
conflicts "--installed", "--eval-all"
conflicts "--installed", "--auto"
conflicts "--no-pull-requests", "--open-pr"
named_args [:formula, :cask], without_api: true
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["livecheck"])
Homebrew.with_no_api_env do
eval_all = args.eval_all?
excluded_autobump = []
if args.no_autobump? && eval_all
excluded_autobump.concat(autobumped_formulae_or_casks(CoreTap.instance)) if args.formula?
excluded_autobump.concat(autobumped_formulae_or_casks(CoreCaskTap.instance, casks: true)) if args.cask?
end
formulae_and_casks = if args.auto?
raise UsageError, "`--formula` or `--cask` must be passed with `--auto`." if !args.formula? && !args.cask?
tap_arg = args.tap
raise UsageError, "`--tap=` must be passed with `--auto`." if tap_arg.blank?
tap = Tap.fetch(tap_arg)
autobump_list = tap.autobump
what = args.cask? ? "casks" : "formulae"
raise UsageError, "No autobumped #{what} found." if autobump_list.blank?
# Only run bump on the first formula in each synced group
if args.bump_synced? && args.formula?
synced_formulae = Set.new(tap.synced_versions_formulae.flat_map { it.drop(1) })
end
autobump_list.filter_map do |name|
qualified_name = "#{tap.name}/#{name}"
next Cask::CaskLoader.load(qualified_name) if args.cask?
next if synced_formulae&.include?(name)
Formulary.factory(qualified_name)
end
elsif args.tap
tap = Tap.fetch(args.tap)
raise UsageError, "`--tap` requires `--auto` for official taps." if tap.official?
formulae = args.cask? ? [] : tap.formula_files.map { |path| Formulary.factory(path) }
casks = args.formula? ? [] : tap.cask_files.map { |path| Cask::CaskLoader.load(path) }
formulae + casks
elsif args.installed?
formulae = args.cask? ? [] : Formula.installed
casks = args.formula? ? [] : Cask::Caskroom.casks
formulae + casks
elsif args.named.present?
args.named.to_formulae_and_casks_with_taps
elsif eval_all
formulae = args.cask? ? [] : Formula.all(eval_all:)
casks = args.formula? ? [] : Cask::Cask.all(eval_all:)
formulae + casks
else
raise UsageError,
"`brew bump` without named arguments needs `--installed` or `--eval-all` passed or " \
"`HOMEBREW_EVAL_ALL=1` set!"
end
if args.start_with
formulae_and_casks.select! do |formula_or_cask|
name = formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name
name.start_with?(args.start_with)
end
end
formulae_and_casks = formulae_and_casks.sort_by do |formula_or_cask|
formula_or_cask.respond_to?(:token) ? formula_or_cask.token : formula_or_cask.name
end
formulae_and_casks -= excluded_autobump
if args.repology? && !Utils::Curl.curl_supports_tls13?
begin
Formula["curl"].ensure_installed!(reason: "Repology queries") unless HOMEBREW_BREWED_CURL_PATH.exist?
rescue FormulaUnavailableError
opoo "A newer `curl` is required for Repology queries."
end
end
handle_formulae_and_casks(formulae_and_casks)
end
end
private
sig { params(formula_or_cask: T.any(Formula, Cask::Cask)).returns(T::Boolean) }
def skip_repology?(formula_or_cask)
return true unless args.repology?
(ENV["CI"].present? && args.open_pr? && formula_or_cask.livecheck_defined?) ||
(formula_or_cask.is_a?(Formula) && formula_or_cask.versioned_formula?)
end
sig { params(formulae_and_casks: T::Array[T.any(Formula, Cask::Cask)]).void }
def handle_formulae_and_casks(formulae_and_casks)
Livecheck.load_other_tap_strategies(formulae_and_casks)
ambiguous_casks = []
if !args.formula? && !args.cask?
ambiguous_casks = formulae_and_casks
.group_by { |item| Livecheck.package_or_resource_name(item, full_name: true) }
.values
.select { |items| items.length > 1 }
.flatten
.select { |item| item.is_a?(Cask::Cask) }
end
ambiguous_names = []
unless args.full_name?
ambiguous_names = (formulae_and_casks - ambiguous_casks)
.group_by { |item| Livecheck.package_or_resource_name(item) }
.values
.select { |items| items.length > 1 }
.flatten
end
formulae_and_casks.each_with_index do |formula_or_cask, i|
puts if i.positive?
next if skip_ineligible_formulae!(formula_or_cask)
use_full_name = args.full_name? || ambiguous_names.include?(formula_or_cask)
name = Livecheck.package_or_resource_name(formula_or_cask, full_name: use_full_name)
repository = if formula_or_cask.is_a?(Formula)
Repology::HOMEBREW_CORE
else
Repology::HOMEBREW_CASK
end
package_data = Repology.single_package_query(name, repository:) unless skip_repology?(formula_or_cask)
retrieve_and_display_info_and_open_pr(
formula_or_cask,
name,
package_data&.values&.first || [],
ambiguous_cask: ambiguous_casks.include?(formula_or_cask),
)
end
end
sig {
params(formula_or_cask: T.any(Formula, Cask::Cask)).returns(T::Boolean)
}
def skip_ineligible_formulae!(formula_or_cask)
if formula_or_cask.is_a?(Formula)
skip = formula_or_cask.disabled? || formula_or_cask.head_only?
name = formula_or_cask.name
text = "Formula is #{formula_or_cask.disabled? ? "disabled" : "HEAD-only"} so not accepting updates.\n"
else
skip = formula_or_cask.disabled?
name = formula_or_cask.token
text = "Cask is disabled so not accepting updates.\n"
end
if (tap = formula_or_cask.tap) && !tap.allow_bump?(name)
skip = true
text = "#{text.split.first} is autobumped so will have bump PRs opened by BrewTestBot every ~3 hours.\n"
end
return false unless skip
ohai name
puts text
true
end
sig {
params(formula_or_cask: T.any(Formula, Cask::Cask)).returns(T.any(Version, String))
}
def livecheck_result(formula_or_cask)
name = Livecheck.package_or_resource_name(formula_or_cask)
referenced_formula_or_cask, = Livecheck.resolve_livecheck_reference(
formula_or_cask,
full_name: false,
debug: false,
)
# Check skip conditions for a referenced formula/cask
if referenced_formula_or_cask
skip_info = Livecheck::SkipConditions.referenced_skip_information(
referenced_formula_or_cask,
name,
full_name: false,
verbose: false,
)
end
skip_info ||= Livecheck::SkipConditions.skip_information(
formula_or_cask,
full_name: false,
verbose: false,
)
if skip_info.present?
return "#{skip_info[:status]}" \
"#{" - #{skip_info[:messages].join(", ")}" if skip_info[:messages].present?}"
end
version_info = Livecheck.latest_version(
formula_or_cask,
referenced_formula_or_cask:,
json: true, full_name: false, verbose: true, debug: false
)
return "unable to get versions" if version_info.blank?
if !version_info.key?(:latest_throttled)
Version.new(version_info[:latest])
elsif version_info[:latest_throttled].nil?
"unable to get throttled versions"
else
Version.new(version_info[:latest_throttled])
end
rescue => e
"error: #{e}"
end
sig {
params(
formula_or_cask: T.any(Formula, Cask::Cask),
name: String,
version: T.nilable(String),
).returns T.nilable(T.any(T::Array[String], String))
}
def retrieve_pull_requests(formula_or_cask, name, version: nil)
tap_remote_repo = formula_or_cask.tap&.remote_repository || formula_or_cask.tap&.full_name
pull_requests = begin
GitHub.fetch_pull_requests(name, tap_remote_repo, version:)
rescue GitHub::API::ValidationFailedError => e
odebug "Error fetching pull requests for #{formula_or_cask} #{name}: #{e}"
nil
end
return if pull_requests.blank?
pull_requests.map { |pr| "#{pr["title"]} (#{Formatter.url(pr["html_url"])})" }.join(", ")
end
sig {
params(
formula_or_cask: T.any(Formula, Cask::Cask),
repositories: T::Array[String],
name: String,
).returns(VersionBumpInfo)
}
def retrieve_versions_by_arch(formula_or_cask:, repositories:, name:)
is_cask_with_blocks = formula_or_cask.is_a?(Cask::Cask) && formula_or_cask.on_system_blocks_exist?
type, version_name = if formula_or_cask.is_a?(Formula)
[:formula, "formula version:"]
else
[:cask, "cask version: "]
end
old_versions = {}
new_versions = {}
repology_latest = repositories.present? ? Repology.latest_version(repositories) : "not found"
repology_latest_is_a_version = repology_latest.is_a?(Version)
# When blocks are absent, arch is not relevant. For consistency, we simulate the arm architecture.
arch_options = is_cask_with_blocks ? OnSystem::ARCH_OPTIONS : [:arm]
arch_options.each do |arch|
SimulateSystem.with(arch:) do
version_key = is_cask_with_blocks ? arch : :general
# We reload the formula/cask here to ensure we're getting the correct version for the current arch
if formula_or_cask.is_a?(Formula)
loaded_formula_or_cask = formula_or_cask
current_version_value = T.must(loaded_formula_or_cask.stable).version
else
loaded_formula_or_cask = Cask::CaskLoader.load(formula_or_cask.sourcefile_path)
current_version_value = Version.new(loaded_formula_or_cask.version)
end
formula_or_cask_has_livecheck = loaded_formula_or_cask.livecheck_defined?
livecheck_latest = livecheck_result(loaded_formula_or_cask)
livecheck_latest_is_a_version = livecheck_latest.is_a?(Version)
new_version_value = if (livecheck_latest_is_a_version &&
Livecheck::LivecheckVersion.create(formula_or_cask, livecheck_latest) >=
Livecheck::LivecheckVersion.create(formula_or_cask, current_version_value)) ||
current_version_value == "latest"
livecheck_latest
elsif livecheck_latest.is_a?(String) && livecheck_latest.start_with?("skipped")
"skipped"
elsif repology_latest_is_a_version &&
!formula_or_cask_has_livecheck &&
repology_latest > current_version_value &&
current_version_value != "latest"
repology_latest
end.presence
# Fall back to the upstream version if there isn't a new version
# value at this point, as this will allow us to surface an upstream
# version that's lower than the current version.
new_version_value ||= livecheck_latest if livecheck_latest_is_a_version
new_version_value ||= repology_latest if repology_latest_is_a_version && !formula_or_cask_has_livecheck
# Store old and new versions
old_versions[version_key] = current_version_value
new_versions[version_key] = new_version_value
end
end
# If arm and intel versions are identical, as it happens with casks where only the checksums differ,
# we consolidate them into a single version.
if old_versions[:arm].present? && old_versions[:arm] == old_versions[:intel]
old_versions = { general: old_versions[:arm] }
end
if new_versions[:arm].present? && new_versions[:arm] == new_versions[:intel]
new_versions = { general: new_versions[:arm] }
end
multiple_versions = old_versions.values_at(:arm, :intel).all?(&:present?) ||
new_versions.values_at(:arm, :intel).all?(&:present?)
current_version = BumpVersionParser.new(general: old_versions[:general],
arm: old_versions[:arm],
intel: old_versions[:intel])
begin
new_version = BumpVersionParser.new(general: new_versions[:general],
arm: new_versions[:arm],
intel: new_versions[:intel])
rescue
# When livecheck fails, we fail gracefully. Otherwise VersionParser will
# raise a usage error
new_version = BumpVersionParser.new(general: "unable to get versions")
end
newer_than_upstream = {}
BumpVersionParser::VERSION_SYMBOLS.each do |version_type|
new_version_value = new_version.send(version_type)
next unless new_version_value.is_a?(Version)
newer_than_upstream[version_type] =
(current_version_value = current_version.send(version_type)).is_a?(Version) &&
(Livecheck::LivecheckVersion.create(formula_or_cask, current_version_value) >
Livecheck::LivecheckVersion.create(formula_or_cask, new_version_value))
end
if !args.no_pull_requests? &&
(new_version.general != "unable to get versions") &&
(new_version.general != "skipped") &&
(new_version != current_version) &&
!newer_than_upstream.all? { |_k, v| v == true }
# We use the ARM version for the pull request version. This is
# consistent with the behavior of bump-cask-pr.
pull_request_version = if multiple_versions
new_version.arm.to_s
else
new_version.general.to_s
end
duplicate_pull_requests = retrieve_pull_requests(
formula_or_cask,
name,
version: pull_request_version,
)
maybe_duplicate_pull_requests = if duplicate_pull_requests.nil?
retrieve_pull_requests(formula_or_cask, name)
end
end
VersionBumpInfo.new(
type:,
multiple_versions:,
version_name:,
current_version:,
repology_latest:,
new_version:,
newer_than_upstream:,
duplicate_pull_requests:,
maybe_duplicate_pull_requests:,
)
end
sig {
params(
formula_or_cask: T.any(Formula, Cask::Cask),
name: String,
repositories: T::Array[String],
ambiguous_cask: T::Boolean,
).void
}
def retrieve_and_display_info_and_open_pr(formula_or_cask, name, repositories, ambiguous_cask: false)
version_info = retrieve_versions_by_arch(formula_or_cask:,
repositories:,
name:)
current_version = version_info.current_version
new_version = version_info.new_version
repology_latest = version_info.repology_latest
versions_equal = (new_version == current_version)
all_newer_than_upstream = version_info.newer_than_upstream.all? { |_k, v| v == true }
title_name = ambiguous_cask ? "#{name} (cask)" : name
title = if (repology_latest == current_version.general || !repology_latest.is_a?(Version)) && versions_equal
"#{title_name} #{Tty.green}is up to date!#{Tty.reset}"
else
title_name
end
# Conditionally format output based on type of formula_or_cask
current_versions = if version_info.multiple_versions
"arm: #{current_version.arm}" \
"#{NEWER_THAN_UPSTREAM_MSG if version_info.newer_than_upstream[:arm]}" \
"\n intel: #{current_version.intel}" \
"#{NEWER_THAN_UPSTREAM_MSG if version_info.newer_than_upstream[:intel]}"
else
newer_than_upstream_general = version_info.newer_than_upstream[:general]
"#{current_version.general}#{NEWER_THAN_UPSTREAM_MSG if newer_than_upstream_general}"
end
current_versions << " (deprecated)" if formula_or_cask.deprecated?
new_versions = if version_info.multiple_versions && new_version.arm && new_version.intel
"arm: #{new_version.arm}
intel: #{new_version.intel}"
else
new_version.general
end
version_label = version_info.version_name
duplicate_pull_requests = version_info.duplicate_pull_requests
maybe_duplicate_pull_requests = version_info.maybe_duplicate_pull_requests
ohai title
puts <<~EOS
Current #{version_label} #{current_versions}
Latest livecheck version: #{new_versions}#{" (throttled)" if formula_or_cask.livecheck.throttle}
EOS
puts <<~EOS unless skip_repology?(formula_or_cask)
Latest Repology version: #{repology_latest}
EOS
if formula_or_cask.is_a?(Formula) && formula_or_cask.synced_with_other_formulae?
outdated_synced_formulae = synced_with(formula_or_cask, new_version.general)
if !args.bump_synced? && outdated_synced_formulae.present?
puts <<~EOS
Version syncing: #{title_name} version should be kept in sync with
#{outdated_synced_formulae.join(", ")}.
EOS
end
end
if !args.no_pull_requests? &&
(new_version.general != "unable to get versions") &&
(new_version.general != "skipped") &&
!versions_equal &&
!all_newer_than_upstream
if duplicate_pull_requests
duplicate_pull_requests_text = duplicate_pull_requests
elsif maybe_duplicate_pull_requests
duplicate_pull_requests_text = "none"
maybe_duplicate_pull_requests_text = maybe_duplicate_pull_requests
else
duplicate_pull_requests_text = "none"
maybe_duplicate_pull_requests_text = "none"
end
puts "Duplicate pull requests: #{duplicate_pull_requests_text}"
if maybe_duplicate_pull_requests_text
puts "Maybe duplicate pull requests: #{maybe_duplicate_pull_requests_text}"
end
end
if !args.open_pr? ||
(new_version.general == "unable to get versions") ||
(new_version.general == "skipped") ||
all_newer_than_upstream
return
end
if GitHub.too_many_open_prs?(formula_or_cask.tap)
odie "You have too many PRs open: close or merge some first!"
end
if repology_latest.is_a?(Version) &&
repology_latest > current_version.general &&
repology_latest > new_version.general &&
formula_or_cask.livecheck_defined?
puts "#{title_name} was not bumped to the Repology version because it has a `livecheck` block."
end
if new_version.blank? || versions_equal ||
(!new_version.general.is_a?(Version) && !version_info.multiple_versions)
return
end
return if duplicate_pull_requests.present?
version_args = if version_info.multiple_versions
%W[--version-arm=#{new_version.arm} --version-intel=#{new_version.intel}]
else
"--version=#{new_version.general}"
end
bump_pr_args = [
"bump-#{version_info.type}-pr",
name,
*version_args,
"--no-browse",
"--message=Created by `brew bump`",
]
bump_pr_args << "--no-fork" if args.no_fork?
if args.bump_synced? && outdated_synced_formulae.present?
bump_pr_args << "--bump-synced=#{outdated_synced_formulae.join(",")}"
end
result = system HOMEBREW_BREW_FILE, *bump_pr_args
Homebrew.failed = true unless result
end
sig {
params(
formula: Formula,
new_version: T.nilable(T.any(Version, Cask::DSL::Version)),
).returns(T::Array[String])
}
def synced_with(formula, new_version)
synced_with = []
formula.tap&.synced_versions_formulae&.each do |synced_formulae|
next unless synced_formulae.include?(formula.name)
synced_formulae.each do |synced_formula|
synced_formula = Formulary.factory(synced_formula)
next if synced_formula == formula.name
synced_with << synced_formula.name if synced_formula.version != new_version
end
end
synced_with
end
sig { params(tap: Tap, casks: T::Boolean).returns(T::Array[T.any(Formula, Cask::Cask)]) }
def autobumped_formulae_or_casks(tap, casks: false)
autobump_list = tap.autobump
autobump_list.map do |name|
qualified_name = "#{tap.name}/#{name}"
if casks
Cask::CaskLoader.load(qualified_name)
else
Formulary.factory(qualified_name)
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/dev-cmd/bottle.rb | Library/Homebrew/dev-cmd/bottle.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
require "formula"
require "utils/bottles"
require "tab"
require "sbom"
require "keg"
require "formula_versions"
require "utils/inreplace"
require "erb"
require "utils/gzip"
require "api"
require "extend/hash/deep_merge"
require "metafiles"
module Homebrew
module DevCmd
class Bottle < AbstractCommand
include FileUtils
BOTTLE_ERB = T.let(<<-EOS.freeze, String)
bottle do
<% if [HOMEBREW_BOTTLE_DEFAULT_DOMAIN.to_s,
"#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}/bottles"].exclude?(root_url) %>
root_url "<%= root_url %>"<% if root_url_using.present? %>,
using: <%= root_url_using %>
<% end %>
<% end %>
<% if rebuild.positive? %>
rebuild <%= rebuild %>
<% end %>
<% sha256_lines.each do |line| %>
<%= line %>
<% end %>
end
EOS
MAXIMUM_STRING_MATCHES = 100
ALLOWABLE_HOMEBREW_REPOSITORY_LINKS = T.let([
%r{#{Regexp.escape(HOMEBREW_LIBRARY)}/Homebrew/os/(mac|linux)/pkgconfig},
].freeze, T::Array[Regexp])
cmd_args do
description <<~EOS
Generate a bottle (binary package) from a formula that was installed with
`--build-bottle`.
If the formula specifies a rebuild version, it will be incremented in the
generated DSL. Passing `--keep-old` will attempt to keep it at its original
value, while `--no-rebuild` will remove it.
EOS
switch "--skip-relocation",
description: "Do not check if the bottle can be marked as relocatable."
switch "--force-core-tap",
description: "Build a bottle even if <formula> is not in `homebrew/core` or any installed taps."
switch "--no-rebuild",
description: "If the formula specifies a rebuild version, remove it from the generated DSL."
switch "--keep-old",
description: "If the formula specifies a rebuild version, attempt to preserve its value in the " \
"generated DSL."
switch "--json",
description: "Write bottle information to a JSON file, which can be used as the value for " \
"`--merge`."
switch "--merge",
description: "Generate an updated bottle block for a formula and optionally merge it into the " \
"formula file. Instead of a formula name, requires the path to a JSON file generated " \
"with `brew bottle --json` <formula>."
switch "--write",
depends_on: "--merge",
description: "Write changes to the formula file. A new commit will be generated unless " \
"`--no-commit` is passed."
switch "--no-commit",
depends_on: "--write",
description: "When passed with `--write`, a new commit will not generated after writing changes " \
"to the formula file."
switch "--only-json-tab",
depends_on: "--json",
description: "When passed with `--json`, the tab will be written to the JSON file but not the bottle."
switch "--no-all-checks",
depends_on: "--merge",
description: "Don't try to create an `all` bottle or stop a no-change upload."
flag "--committer=",
description: "Specify a committer name and email in `git`'s standard author format."
flag "--root-url=",
description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default."
flag "--root-url-using=",
description: "Use the specified download strategy class for downloading the bottle's URL instead of " \
"Homebrew's default."
conflicts "--no-rebuild", "--keep-old"
named_args [:installed_formula, :file], min: 1, without_api: true
end
sig { override.void }
def run
if args.merge?
Homebrew.install_bundler_gems!(groups: ["ast"])
return merge
end
Homebrew.install_bundler_gems!(groups: ["bottle"])
gnu_tar_formula_ensure_installed_if_needed! if args.only_json_tab?
args.named.to_resolved_formulae(uniq: false).each do |formula|
bottle_formula formula
end
end
sig {
params(tag: Symbol, digest: T.any(Checksum, String), cellar: T.nilable(T.any(String, Symbol)),
tag_column: Integer, digest_column: Integer).returns(String)
}
def generate_sha256_line(tag, digest, cellar, tag_column, digest_column)
line = "sha256 "
tag_column += line.length
digest_column += line.length
if cellar.is_a?(Symbol)
line += "cellar: :#{cellar},"
elsif cellar_parameter_needed?(cellar)
line += %Q(cellar: "#{cellar}",)
end
line += " " * (tag_column - line.length)
line += "#{tag}:"
line += " " * (digest_column - line.length)
%Q(#{line}"#{digest}")
end
sig { params(bottle: BottleSpecification, root_url_using: T.nilable(String)).returns(String) }
def bottle_output(bottle, root_url_using)
cellars = bottle.checksums.filter_map do |checksum|
cellar = checksum["cellar"]
next unless cellar_parameter_needed? cellar
case cellar
when String
%Q("#{cellar}")
when Symbol
":#{cellar}"
end
end
tag_column = cellars.empty? ? 0 : "cellar: #{cellars.max_by(&:length)}, ".length
tags = bottle.checksums.map { |checksum| checksum["tag"] }
# Start where the tag ends, add the max length of the tag, add two for the `: `
digest_column = tag_column + tags.max_by(&:length).length + 2
sha256_lines = bottle.checksums.map do |checksum|
generate_sha256_line(checksum["tag"], checksum["digest"], checksum["cellar"], tag_column, digest_column)
end
erb_binding = bottle.instance_eval { binding }
erb_binding.local_variable_set(:sha256_lines, sha256_lines)
erb_binding.local_variable_set(:root_url_using, root_url_using)
erb = ERB.new BOTTLE_ERB
erb.result(erb_binding).gsub(/^\s*$\n/, "")
end
sig { params(filenames: T::Array[String]).returns(T::Array[T::Hash[String, T.untyped]]) }
def parse_json_files(filenames)
filenames.map do |filename|
JSON.parse(File.read(filename))
end
end
sig { params(json_files: T::Array[T::Hash[String, T.untyped]]).returns(T::Hash[String, T.untyped]) }
def merge_json_files(json_files)
json_files.reduce({}) do |hash, json_file|
json_file.each_value do |json_hash|
json_bottle = json_hash["bottle"]
cellar = json_bottle.delete("cellar")
json_bottle["tags"].each_value do |json_platform|
json_platform["cellar"] ||= cellar
end
end
hash.deep_merge(json_file)
end
end
sig {
params(old_keys: T::Array[Symbol], old_bottle_spec: BottleSpecification,
new_bottle_hash: T::Hash[String, T.untyped])
.returns([T::Array[String], T::Array[T::Hash[Symbol, T.any(String, Symbol)]]])
}
def merge_bottle_spec(old_keys, old_bottle_spec, new_bottle_hash)
mismatches = []
checksums = []
new_values = {
root_url: new_bottle_hash["root_url"],
rebuild: new_bottle_hash["rebuild"],
}
skip_keys = [:sha256, :cellar]
old_keys.each do |key|
next if skip_keys.include?(key)
old_value = old_bottle_spec.send(key).to_s
new_value = new_values[key].to_s
next if old_value.present? && new_value == old_value
mismatches << "#{key}: old: #{old_value.inspect}, new: #{new_value.inspect}"
end
return [mismatches, checksums] if old_keys.exclude? :sha256
old_bottle_spec.collector.each_tag do |tag|
old_tag_spec = old_bottle_spec.collector.specification_for(tag)
old_hexdigest = old_tag_spec.checksum.hexdigest
old_cellar = old_tag_spec.cellar
new_value = new_bottle_hash.dig("tags", tag.to_s)
if new_value.present? && new_value["sha256"] != old_hexdigest
mismatches << "sha256 #{tag}: old: #{old_hexdigest.inspect}, new: #{new_value["sha256"].inspect}"
elsif new_value.present? && new_value["cellar"] != old_cellar.to_s
mismatches << "cellar #{tag}: old: #{old_cellar.to_s.inspect}, new: #{new_value["cellar"].inspect}"
else
checksums << { cellar: old_cellar, tag.to_sym => old_hexdigest }
end
end
[mismatches, checksums]
end
private
sig {
params(string: String, keg: Keg, ignores: T::Array[Regexp],
formula_and_runtime_deps_names: T.nilable(T::Array[String])).returns(T::Boolean)
}
def keg_contain?(string, keg, ignores, formula_and_runtime_deps_names = nil)
@put_string_exists_header, @put_filenames = nil
print_filename = lambda do |str, filename|
unless @put_string_exists_header
opoo "String '#{str}' still exists in these files:"
@put_string_exists_header = T.let(true, T.nilable(T::Boolean))
end
@put_filenames ||= T.let([], T.nilable(T::Array[T.any(String, Pathname)]))
return false if @put_filenames.include?(filename)
puts Formatter.error(filename.to_s)
@put_filenames << filename
end
result = T.let(false, T::Boolean)
keg.each_unique_file_matching(string) do |file|
next if Metafiles::EXTENSIONS.include?(file.extname) # Skip document files.
linked_libraries = Keg.file_linked_libraries(file, string)
result ||= !linked_libraries.empty?
if args.verbose?
print_filename.call(string, file) unless linked_libraries.empty?
linked_libraries.each do |lib|
puts " #{Tty.bold}-->#{Tty.reset} links to #{lib}"
end
end
text_matches = Keg.text_matches_in_file(file, string, ignores, linked_libraries,
formula_and_runtime_deps_names)
result = true if text_matches.any?
next if !args.verbose? || text_matches.empty?
print_filename.call(string, file)
text_matches.first(MAXIMUM_STRING_MATCHES).each do |match, offset|
puts " #{Tty.bold}-->#{Tty.reset} match '#{match}' at offset #{Tty.bold}0x#{offset}#{Tty.reset}"
end
if text_matches.size > MAXIMUM_STRING_MATCHES
puts "Only the first #{MAXIMUM_STRING_MATCHES} matches were output."
end
end
keg_contain_absolute_symlink_starting_with?(string, keg) || result
end
sig { params(string: String, keg: Keg).returns(T::Boolean) }
def keg_contain_absolute_symlink_starting_with?(string, keg)
absolute_symlinks_start_with_string = []
keg.find do |pn|
next if !pn.symlink? || !(link = pn.readlink).absolute?
absolute_symlinks_start_with_string << pn if link.to_s.start_with?(string)
end
if args.verbose? && absolute_symlinks_start_with_string.present?
opoo "Absolute symlink starting with #{string}:"
absolute_symlinks_start_with_string.each do |pn|
puts " #{pn} -> #{pn.resolved_path}"
end
end
!absolute_symlinks_start_with_string.empty?
end
sig { params(cellar: T.nilable(T.any(String, Symbol))).returns(T::Boolean) }
def cellar_parameter_needed?(cellar)
default_cellars = [
Homebrew::DEFAULT_MACOS_CELLAR,
Homebrew::DEFAULT_MACOS_ARM_CELLAR,
Homebrew::DEFAULT_LINUX_CELLAR,
]
cellar.present? && default_cellars.exclude?(cellar)
end
sig { returns(T.nilable(T::Boolean)) }
def sudo_purge
return unless ENV["HOMEBREW_BOTTLE_SUDO_PURGE"]
system "/usr/bin/sudo", "--non-interactive", "/usr/sbin/purge"
end
sig { returns(T::Array[String]) }
def tar_args
[].freeze
end
sig { params(gnu_tar_formula: Formula).returns(String) }
def gnu_tar(gnu_tar_formula)
"#{gnu_tar_formula.opt_bin}/tar"
end
sig { params(mtime: String).returns(T::Array[String]) }
def reproducible_gnutar_args(mtime)
# Ensure gnu tar is set up for reproducibility.
# https://reproducible-builds.org/docs/archives/
[
# File modification times
"--mtime=#{mtime}",
# File ordering
"--sort=name",
# Users, groups and numeric ids
"--owner=0", "--group=0", "--numeric-owner",
# PAX headers
"--format=pax",
# Set exthdr names to exclude PID (for GNU tar <1.33). Also don't store atime and ctime.
"--pax-option=globexthdr.name=/GlobalHead.%n,exthdr.name=%d/PaxHeaders/%f,delete=atime,delete=ctime"
].freeze
end
sig { returns(T.nilable(Formula)) }
def gnu_tar_formula_ensure_installed_if_needed!
gnu_tar_formula = begin
Formula["gnu-tar"]
rescue FormulaUnavailableError
nil
end
return if gnu_tar_formula.blank?
gnu_tar_formula.ensure_installed!(reason: "bottling")
end
sig { params(mtime: String, default_tar: T::Boolean).returns([String, T::Array[String]]) }
def setup_tar_and_args!(mtime, default_tar: false)
# Without --only-json-tab bottles are never reproducible
default_tar_args = ["tar", tar_args].freeze
return default_tar_args if !args.only_json_tab? || default_tar
# Use gnu-tar as it can be set up for reproducibility better than libarchive
# and to be consistent between macOS and Linux.
gnu_tar_formula = gnu_tar_formula_ensure_installed_if_needed!
return default_tar_args if gnu_tar_formula.blank?
[gnu_tar(gnu_tar_formula), reproducible_gnutar_args(mtime)].freeze
end
sig { params(formula: Formula).returns(T::Array[Regexp]) }
def formula_ignores(formula)
# Ignore matches to go keg, because all go binaries are statically linked.
any_go_deps = formula.deps.any? do |dep|
Version.formula_optionally_versioned_regex(:go).match?(dep.name)
end
return [] unless any_go_deps
cellar_regex = Regexp.escape(HOMEBREW_CELLAR)
go_regex = Version.formula_optionally_versioned_regex(:go, full: false)
Array(%r{#{cellar_regex}/#{go_regex}/[\d.]+/libexec})
end
sig { params(formula: Formula).void }
def bottle_formula(formula)
local_bottle_json = args.json? && formula.local_bottle_path.present?
unless local_bottle_json
unless formula.latest_version_installed?
return ofail "Formula not installed or up-to-date: #{formula.full_name}"
end
unless Utils::Bottles.built_as? formula
return ofail "Formula was not installed with `--build-bottle`: #{formula.full_name}"
end
end
tap = formula.tap
if tap.nil?
return ofail "Formula not from core or any installed taps: #{formula.full_name}" unless args.force_core_tap?
tap = CoreTap.instance
end
raise TapUnavailableError, tap.name unless tap.installed?
return ofail "Formula has no stable version: #{formula.full_name}" unless formula.stable
bottle_tag, rebuild = if local_bottle_json
_, tag_string, rebuild_string = Utils::Bottles.extname_tag_rebuild(formula.local_bottle_path.to_s)
[T.must(tag_string).to_sym, rebuild_string.to_i]
end
bottle_tag = if bottle_tag
Utils::Bottles::Tag.from_symbol(bottle_tag)
else
Utils::Bottles.tag
end
rebuild ||= if args.no_rebuild? || !tap
0
elsif args.keep_old?
formula.bottle_specification.rebuild
else
ohai "Determining #{formula.full_name} bottle rebuild..."
FormulaVersions.new(formula).formula_at_revision("origin/HEAD") do |upstream_formula|
if formula.pkg_version == upstream_formula.pkg_version
upstream_formula.bottle_specification.rebuild + 1
else
0
end
end || 0
end
filename = ::Bottle::Filename.create(formula, bottle_tag, rebuild)
local_filename = filename.to_s
bottle_path = Pathname.pwd/local_filename
tab = nil
keg = nil
tap_path = tap.path
tap_git_revision = tap.git_head
tap_git_remote = tap.remote
root_url = args.root_url
relocatable = T.let(false, T::Boolean)
skip_relocation = T.let(false, T::Boolean)
prefix = HOMEBREW_PREFIX.to_s
cellar = HOMEBREW_CELLAR.to_s
if local_bottle_json
bottle_path = formula.local_bottle_path
return if bottle_path.blank?
local_filename = bottle_path.basename.to_s
tab_path = Utils::Bottles.receipt_path(bottle_path)
raise "This bottle does not contain the file INSTALL_RECEIPT.json: #{bottle_path}" unless tab_path
tab_json = Utils::Bottles.file_from_bottle(bottle_path, tab_path)
tab = Tab.from_file_content(tab_json, tab_path)
tag_spec = Formula[formula.name].bottle_specification
.tag_specification_for(bottle_tag, no_older_versions: true)
relocatable = [:any, :any_skip_relocation].include?(tag_spec.cellar)
skip_relocation = tag_spec.cellar == :any_skip_relocation
prefix = bottle_tag.default_prefix
cellar = bottle_tag.default_cellar
else
tar_filename = filename.to_s.sub(/.gz$/, "")
tar_path = Pathname.pwd/tar_filename
return if tar_path.blank?
keg = Keg.new(formula.prefix)
end
ohai "Bottling #{local_filename}..."
formula_and_runtime_deps_names = [formula.name] + formula.runtime_dependencies.map(&:name)
# this will be nil when using a local bottle
keg&.lock do
original_tab = nil
changed_files = nil
begin
keg.delete_pyc_files!
changed_files = keg.replace_locations_with_placeholders unless args.skip_relocation?
Formula.clear_cache
Keg.clear_cache
Tab.clear_cache
Dependency.clear_cache
Requirement.clear_cache
tab = keg.tab
original_tab = tab.dup
tab.poured_from_bottle = false
tab.time = nil
tab.changed_files = changed_files.dup
if args.only_json_tab?
tab.changed_files&.delete(Pathname.new(AbstractTab::FILENAME))
tab.tabfile.unlink
else
tab.write
end
sbom = SBOM.create(formula, tab)
sbom.write(bottling: true)
keg.consistent_reproducible_symlink_permissions!
cd cellar do
sudo_purge
# Tar then gzip for reproducible bottles.
# GNU tar fails to create a bottle if modification time is unsigned integer
# (i.e. before 1970)
time_at_epoch = Time.at(1)
tab_source_modified_time = [time_at_epoch, tab.source_modified_time].max
tar_mtime = tab_source_modified_time.strftime("%Y-%m-%d %H:%M:%S")
tar, tar_args = setup_tar_and_args!(tar_mtime, default_tar: formula.name == "gnu-tar")
safe_system tar, "--create", "--numeric-owner",
*tar_args,
"--file", tar_path, "#{formula.name}/#{formula.pkg_version}"
sudo_purge
# Set filename as it affects the tarball checksum.
relocatable_tar_path = "#{formula}-bottle.tar"
mv T.must(tar_path), relocatable_tar_path
# Use gzip, faster to compress than bzip2, faster to uncompress than bzip2
# or an uncompressed tarball (and more bandwidth friendly).
Utils::Gzip.compress_with_options(relocatable_tar_path,
mtime: tab.source_modified_time,
orig_name: relocatable_tar_path,
output: bottle_path)
sudo_purge
end
ohai "Detecting if #{local_filename} is relocatable..." if bottle_path.size > 1 * 1024 * 1024
is_usr_local_prefix = prefix == "/usr/local"
prefix_check = if is_usr_local_prefix
"#{prefix}/opt"
else
prefix
end
# Ignore matches to source code, which is not required at run time.
# These matches may be caused by debugging symbols.
ignores = [%r{/include/|\.(c|cc|cpp|h|hpp)$}]
# Add additional workarounds to ignore
ignores += formula_ignores(formula)
repository_reference = if HOMEBREW_PREFIX == HOMEBREW_REPOSITORY
HOMEBREW_LIBRARY
else
HOMEBREW_REPOSITORY
end.to_s
if keg_contain?(repository_reference, keg, ignores + ALLOWABLE_HOMEBREW_REPOSITORY_LINKS)
odie "Bottle contains non-relocatable reference to #{repository_reference}!"
end
relocatable = true
if args.skip_relocation?
skip_relocation = true
else
relocatable = false if keg_contain?(prefix_check, keg, ignores, formula_and_runtime_deps_names)
relocatable = false if keg_contain?(cellar, keg, ignores, formula_and_runtime_deps_names)
relocatable = false if keg_contain?(HOMEBREW_LIBRARY.to_s, keg, ignores, formula_and_runtime_deps_names)
if is_usr_local_prefix
relocatable = false if keg_contain_absolute_symlink_starting_with?(prefix, keg)
if tap.disabled_new_usr_local_relocation_formulae.exclude?(formula.name)
keg.new_usr_local_replacement_pairs.each_value do |value|
relocatable = false if keg_contain?(value.fetch(:old), keg, ignores)
end
else
relocatable = false if keg_contain?("#{prefix}/etc", keg, ignores)
relocatable = false if keg_contain?("#{prefix}/var", keg, ignores)
relocatable = false if keg_contain?("#{prefix}/share/vim", keg, ignores)
end
end
skip_relocation = relocatable && !keg.require_relocation?
end
puts if !relocatable && args.verbose?
rescue Interrupt
ignore_interrupts { bottle_path.unlink if bottle_path.exist? }
raise
ensure
ignore_interrupts do
original_tab&.write
keg.replace_placeholders_with_locations(changed_files) if changed_files && !args.skip_relocation?
end
end
end
bottle = BottleSpecification.new
bottle.tap = tap
bottle.root_url(root_url) if root_url
bottle_cellar = if relocatable
if skip_relocation
:any_skip_relocation
else
:any
end
else
cellar
end
bottle.rebuild rebuild
sha256 = bottle_path.sha256
bottle.sha256 cellar: bottle_cellar, bottle_tag.to_sym => sha256
old_spec = formula.bottle_specification
if args.keep_old? && !old_spec.checksums.empty?
mismatches = [:root_url, :rebuild].reject do |key|
old_spec.send(key) == bottle.send(key)
end
unless mismatches.empty?
bottle_path.unlink if bottle_path.exist?
mismatches.map! do |key|
old_value = old_spec.send(key).inspect
value = bottle.send(key).inspect
"#{key}: old: #{old_value}, new: #{value}"
end
odie <<~EOS
`--keep-old` was passed but there are changes in:
#{mismatches.join("\n")}
EOS
end
end
output = bottle_output(bottle, args.root_url_using)
puts "./#{local_filename}"
puts output
return unless args.json?
if keg
keg_prefix = "#{keg}/"
path_exec_files = [keg/"bin", keg/"sbin"].select(&:exist?)
.flat_map(&:children)
.select(&:executable?)
.map { |path| path.to_s.delete_prefix(keg_prefix) }
all_files = keg.find
.select(&:file?)
.map { |path| path.to_s.delete_prefix(keg_prefix) }
installed_size = keg.disk_usage
end
json = {
formula.full_name => {
"formula" => {
"name" => formula.name,
"pkg_version" => formula.pkg_version.to_s,
"path" => formula.tap_path.to_s.delete_prefix("#{HOMEBREW_REPOSITORY}/"),
"tap_git_path" => formula.tap_path.to_s.delete_prefix("#{tap_path}/"),
"tap_git_revision" => tap_git_revision,
"tap_git_remote" => tap_git_remote,
# descriptions can contain emoji. sigh.
"desc" => formula.desc.to_s.encode(
Encoding.find("ASCII"),
invalid: :replace, undef: :replace, replace: "",
).strip,
"license" => SPDX.license_expression_to_string(formula.license),
"homepage" => formula.homepage,
},
"bottle" => {
"root_url" => bottle.root_url,
"cellar" => bottle_cellar.to_s,
"rebuild" => bottle.rebuild,
# date is used for org.opencontainers.image.created which is an RFC 3339 date-time.
# Time#iso8601 produces an XML Schema date-time that meets RFC 3339 ABNF.
"date" => Pathname(filename.to_s).mtime.utc.iso8601,
"tags" => {
bottle_tag.to_s => {
"filename" => filename.url_encode,
"local_filename" => filename.to_s,
"sha256" => sha256,
"tab" => T.must(tab).to_bottle_hash,
"path_exec_files" => path_exec_files,
"all_files" => all_files,
"installed_size" => installed_size,
},
},
},
},
}
puts "Writing #{filename.json}" if args.verbose?
json_path = Pathname(filename.json)
json_path.unlink if json_path.exist?
json_path.write(JSON.pretty_generate(json))
end
sig { returns(T::Hash[String, T.untyped]) }
def merge
bottles_hash = merge_json_files(parse_json_files(args.named))
any_cellars = ["any", "any_skip_relocation"]
bottles_hash.each do |formula_name, bottle_hash|
ohai formula_name
bottle = BottleSpecification.new
bottle.root_url bottle_hash["bottle"]["root_url"]
bottle.rebuild bottle_hash["bottle"]["rebuild"]
path = HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]
formula = Formulary.factory(path)
old_bottle_spec = formula.bottle_specification
old_pkg_version = formula.pkg_version
FormulaVersions.new(formula).formula_at_revision("origin/HEAD") do |upstream_formula|
old_pkg_version = upstream_formula.pkg_version
end
old_bottle_spec_matches = old_bottle_spec &&
bottle_hash["formula"]["pkg_version"] == old_pkg_version.to_s &&
bottle.root_url == old_bottle_spec.root_url &&
old_bottle_spec.collector.tags.present?
# if all the cellars and checksums are the same: we can create an
# `all: $SHA256` bottle.
tag_hashes = bottle_hash["bottle"]["tags"].values
all_bottle = !args.no_all_checks? &&
(!old_bottle_spec_matches || bottle.rebuild != old_bottle_spec.rebuild) &&
tag_hashes.count > 1 &&
tag_hashes.uniq { |tag_hash| "#{tag_hash["cellar"]}-#{tag_hash["sha256"]}" }.one?
old_all_bottle = old_bottle_spec.tag?(Utils::Bottles.tag(:all))
if !all_bottle && old_all_bottle && !args.no_all_checks?
odie <<~ERROR
#{formula} should have an `:all` bottle but one cannot be created:
#{JSON.pretty_generate(tag_hashes)}
ERROR
end
bottle_hash["bottle"]["tags"].each do |tag, tag_hash|
cellar = tag_hash["cellar"]
cellar = cellar.to_sym if any_cellars.include?(cellar)
tag_sym = if all_bottle
:all
else
tag.to_sym
end
sha256_hash = { cellar:, tag_sym => tag_hash["sha256"] }
bottle.sha256 sha256_hash
break if all_bottle
end
unless args.write?
puts bottle_output(bottle, args.root_url_using)
next
end
no_bottle_changes = if !args.no_all_checks? && old_bottle_spec_matches &&
bottle.rebuild != old_bottle_spec.rebuild
bottle.collector.tags.all? do |tag|
tag_spec = bottle.collector.specification_for(tag)
next false if tag_spec.blank?
old_tag_spec = old_bottle_spec.collector.specification_for(tag)
next false if old_tag_spec.blank?
next false if tag_spec.cellar != old_tag_spec.cellar
tag_spec.checksum.hexdigest == old_tag_spec.checksum.hexdigest
end
end
all_bottle_hash = T.let(nil, T.nilable(T::Hash[String, T.untyped]))
bottle_hash["bottle"]["tags"].each do |tag, tag_hash|
filename = ::Bottle::Filename.new(
formula_name,
PkgVersion.parse(bottle_hash["formula"]["pkg_version"]),
Utils::Bottles::Tag.from_symbol(tag.to_sym),
bottle_hash["bottle"]["rebuild"],
)
if all_bottle && all_bottle_hash.nil?
all_bottle_tag_hash = tag_hash.dup
all_filename = ::Bottle::Filename.new(
formula_name,
PkgVersion.parse(bottle_hash["formula"]["pkg_version"]),
Utils::Bottles::Tag.from_symbol(:all),
bottle_hash["bottle"]["rebuild"],
)
all_bottle_tag_hash["filename"] = all_filename.url_encode
all_bottle_tag_hash["local_filename"] = all_filename.to_s
cellar = all_bottle_tag_hash.delete("cellar")
all_bottle_formula_hash = bottle_hash.dup
all_bottle_formula_hash["bottle"]["cellar"] = cellar
all_bottle_formula_hash["bottle"]["tags"] = { all: all_bottle_tag_hash }
all_bottle_hash = { formula_name => all_bottle_formula_hash }
puts "Copying #{filename} to #{all_filename}" if args.verbose?
FileUtils.cp filename.to_s, all_filename.to_s
puts "Writing #{all_filename.json}" if args.verbose?
all_local_json_path = Pathname(all_filename.json)
all_local_json_path.unlink if all_local_json_path.exist?
all_local_json_path.write(JSON.pretty_generate(all_bottle_hash))
end
if all_bottle || no_bottle_changes
puts "Removing #{filename} and #{filename.json}" if args.verbose?
FileUtils.rm_f [filename.to_s, filename.json]
end
end
next if no_bottle_changes
require "utils/ast"
formula_ast = Utils::AST::FormulaAST.new(path.read)
checksums = old_checksums(formula, formula_ast, bottle_hash)
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/typecheck.rb | Library/Homebrew/dev-cmd/typecheck.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module DevCmd
class Typecheck < AbstractCommand
include FileUtils
cmd_args do
description <<~EOS
Check for typechecking errors using Sorbet.
EOS
switch "--fix",
description: "Automatically fix type errors."
switch "-q", "--quiet",
description: "Silence all non-critical errors."
switch "--update",
description: "Update RBI files."
switch "--update-all",
description: "Update all RBI files rather than just updated gems."
switch "--suggest-typed",
depends_on: "--update",
description: "Try upgrading `typed` sigils."
switch "--lsp",
description: "Start the Sorbet LSP server."
flag "--dir=",
description: "Typecheck all files in a specific directory."
flag "--file=",
description: "Typecheck a single file."
flag "--ignore=",
description: "Ignores input files that contain the given string " \
"in their paths (relative to the input path passed to Sorbet)."
conflicts "--dir", "--file"
conflicts "--lsp", "--update"
conflicts "--lsp", "--update-all"
conflicts "--lsp", "--fix"
named_args :tap
end
sig { override.void }
def run
if (args.dir.present? || args.file.present?) && args.named.present?
raise UsageError, "Cannot use `--dir` or `--file` when specifying a tap."
elsif args.fix? && args.named.present?
raise UsageError, "Cannot use `--fix` when specifying a tap."
end
update = args.update? || args.update_all?
groups = update ? Homebrew.valid_gem_groups : ["typecheck"]
Homebrew.install_bundler_gems!(groups:)
# Sorbet doesn't use bash privileged mode so we align EUID and UID here.
Process::UID.change_privilege(Process.euid) if Process.euid != Process.uid
HOMEBREW_LIBRARY_PATH.cd do
if update
workers = args.debug? ? ["--workers=1"] : []
safe_system "bundle", "exec", "tapioca", "annotations"
safe_system "bundle", "exec", "tapioca", "dsl", *workers
# Prefer adding args here: Library/Homebrew/sorbet/tapioca/config.yml
tapioca_args = args.update_all? ? ["--all"] : []
ohai "Updating Tapioca RBI files..."
safe_system "bundle", "exec", "tapioca", "gem", *tapioca_args
ohai "Trimming RuboCop RBI because by default it's massive..."
trim_rubocop_rbi
if args.suggest_typed?
ohai "Checking if we can bump Sorbet `typed` sigils..."
# --sorbet needed because of https://github.com/Shopify/spoom/issues/488
system "bundle", "exec", "spoom", "srb", "bump", "--from", "false", "--to", "true",
"--sorbet", "#{Gem.bin_path("sorbet", "srb")} tc"
system "bundle", "exec", "spoom", "srb", "bump", "--from", "true", "--to", "strict",
"--sorbet", "#{Gem.bin_path("sorbet", "srb")} tc"
end
return
end
srb_exec = %w[bundle exec srb tc]
srb_exec << "--quiet" if args.quiet?
if args.fix?
# Auto-correcting method names is almost always wrong.
srb_exec << "--suppress-error-code" << "7003"
srb_exec << "--autocorrect"
end
if args.lsp?
srb_exec << "--lsp"
if (watchman = which("watchman", ORIGINAL_PATHS))
srb_exec << "--watchman-path" << watchman.to_s
else
srb_exec << "--disable-watchman"
end
end
srb_exec += ["--ignore", args.ignore] if args.ignore.present?
if args.file.present? || args.dir.present? || (tap_dir = args.named.to_paths(only: :tap).first).present?
cd("sorbet") do
srb_exec += ["--file", "../#{args.file}"] if args.file
srb_exec += ["--dir", "../#{args.dir}"] if args.dir
srb_exec += ["--dir", tap_dir.to_s] if tap_dir
end
end
success = system(*srb_exec)
return if success
$stderr.puts "Check #{Formatter.url("https://docs.brew.sh/Typechecking")} for " \
"more information on how to resolve these errors."
Homebrew.failed = true
end
end
sig { params(path: T.any(String, Pathname)).void }
def trim_rubocop_rbi(path: HOMEBREW_LIBRARY_PATH/"sorbet/rbi/gems/rubocop@*.rbi")
rbi_file = Dir.glob(path).first
return unless rbi_file.present?
return unless (rbi_path = Pathname.new(rbi_file)).exist?
require "prism"
original_content = rbi_path.read
parsed = Prism.parse(original_content)
return unless parsed.success?
allowlist = %w[
Parser::Source
RuboCop::AST::Node
RuboCop::AST::NodePattern
RuboCop::AST::ProcessedSource
RuboCop::CLI
RuboCop::Config
RuboCop::Cop::AllowedPattern
RuboCop::Cop::AllowedMethods
RuboCop::Cop::AutoCorrector
RuboCop::Cop::AutocorrectLogic
RuboCop::Cop::Base
RuboCop::Cop::CommentsHelp
RuboCop::Cop::ConfigurableFormatting
RuboCop::Cop::ConfigurableNaming
RuboCop::Cop::Corrector
RuboCop::Cop::IgnoredMethods
RuboCop::Cop::IgnoredNode
RuboCop::Cop::IgnoredPattern
RuboCop::Cop::MethodPreference
RuboCop::Cop::Offense
RuboCop::Cop::RangeHelp
RuboCop::Cop::Registry
RuboCop::Cop::Util
RuboCop::DirectiveComment
RuboCop::Error
RuboCop::ExcludeLimit
RuboCop::Ext::Comment
RuboCop::Ext::ProcessedSource
RuboCop::Ext::Range
RuboCop::FileFinder
RuboCop::Formatter::TextUtil
RuboCop::Formatter::PathUtil
RuboCop::Options
RuboCop::ResultCache
RuboCop::Runner
RuboCop::TargetFinder
RuboCop::Version
].freeze
nodes_to_keep = Set.new
parsed.value.statements.body.each do |node|
case node
when Prism::ModuleNode, Prism::ClassNode
# Keep if it's in our allowlist or is a top-level essential node.
full_name = extract_full_name(node)
nodes_to_keep << node if full_name.blank? || allowlist.any? { |name| full_name.start_with?(name) }
when Prism::ConstantWriteNode # Keep essential constants.
nodes_to_keep << node if node.name.to_s.match?(/^[[:digit:][:upper:]_]+$/)
else # Keep other top-level nodes (comments, etc.)
nodes_to_keep << node
end
end
new_content = generate_trimmed_rbi(original_content, nodes_to_keep, parsed)
rbi_path.write(new_content)
end
private
sig { params(node: Prism::Node).returns(String) }
def extract_full_name(node)
case node
when Prism::ModuleNode, Prism::ClassNode
parts = []
constant_path = node.constant_path
if constant_path.is_a?(Prism::ConstantReadNode)
parts << constant_path.name.to_s
elsif constant_path.is_a?(Prism::ConstantPathNode)
parts.concat(extract_constant_path_parts(constant_path))
end
parts.join("::")
else
""
end
end
sig { params(constant_path: T.any(Prism::ConstantPathNode, Prism::Node)).returns(T::Array[String]) }
def extract_constant_path_parts(constant_path)
parts = []
current = T.let(constant_path, T.nilable(Prism::Node))
while current
case current
when Prism::ConstantPathNode
parts.unshift(current.name.to_s)
current = current.parent
when Prism::ConstantReadNode
parts.unshift(current.name.to_s)
break
else
break
end
end
parts
end
sig {
params(
original_content: String,
nodes_to_keep: T::Set[Prism::Node],
parsed: Prism::ParseResult,
).returns(String)
}
def generate_trimmed_rbi(original_content, nodes_to_keep, parsed)
lines = original_content.lines
output_lines = []
first_node = parsed.value.statements.body.first
if first_node
first_line = first_node.location.start_line - 1
(0...first_line).each { |i| output_lines << lines[i] if lines[i] }
end
parsed.value.statements.body.each do |node|
next unless nodes_to_keep.include?(node)
start_line = node.location.start_line - 1
end_line = node.location.end_line - 1
(start_line..end_line).each { |i| output_lines << lines[i] if lines[i] }
output_lines << "\n"
end
header = <<~EOS.chomp
# typed: true
# This file is autogenerated. Do not edit it by hand.
# To regenerate, run `brew typecheck --update rubocop`.
EOS
return header if output_lines.empty?
output_lines.join
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/formula-analytics.rb | Library/Homebrew/dev-cmd/formula-analytics.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module DevCmd
class FormulaAnalytics < AbstractCommand
cmd_args do
usage_banner <<~EOS
`formula-analytics`
Query Homebrew's analytics.
EOS
flag "--days-ago=",
description: "Query from the specified days ago until the present. The default is 30 days."
switch "--install",
description: "Output the number of specifically requested installations or installation as " \
"dependencies of formulae. This is the default."
switch "--install-on-request",
description: "Output the number of specifically requested installations of formulae."
switch "--cask-install",
description: "Output the number of installations of casks."
switch "--build-error",
description: "Output the number of build errors for formulae."
switch "--os-version",
description: "Output the number of events by OS name and version."
switch "--homebrew-devcmdrun-developer",
description: "Output the number of devcmdrun/HOMEBREW_DEVELOPER events."
switch "--homebrew-os-arch-ci",
description: "Output the number of OS/Architecture/CI events."
switch "--homebrew-prefixes",
description: "Output Homebrew prefixes."
switch "--homebrew-versions",
description: "Output Homebrew versions."
switch "--brew-command-run",
description: "Output `brew` commands run."
switch "--brew-command-run-options",
description: "Output `brew` commands run with options."
switch "--brew-test-bot-test",
description: "Output `brew test-bot` steps run."
switch "--json",
description: "Output JSON. This is required: plain text support has been removed."
switch "--all-core-formulae-json",
description: "Output a different JSON format containing the JSON data for all " \
"Homebrew/homebrew-core formulae."
switch "--setup",
description: "Install the necessary gems, require them and exit without running a query."
conflicts "--install", "--cask-install", "--install-on-request", "--build-error", "--os-version",
"--homebrew-devcmdrun-developer", "--homebrew-os-arch-ci", "--homebrew-prefixes",
"--homebrew-versions", "--brew-command-run", "--brew-command-run-options", "--brew-test-bot-test"
conflicts "--json", "--all-core-formulae-json", "--setup"
named_args :none
end
FIRST_INFLUXDB_ANALYTICS_DATE = T.let(Date.new(2023, 03, 27).freeze, Date)
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["formula_analytics"])
setup_python
influx_analytics(args)
end
sig { void }
def setup_python
formula_analytics_root = HOMEBREW_LIBRARY/"Homebrew/formula-analytics"
vendor_python = Pathname.new("~/.brew-formula-analytics/vendor/python").expand_path
python_version = (formula_analytics_root/".python-version").read.chomp
which_python = which("python#{python_version}", ORIGINAL_PATHS)
odie <<~EOS if which_python.nil?
Python #{python_version} is required. Try:
brew install python@#{python_version}
EOS
venv_root = vendor_python/python_version
vendor_python.children.reject { |path| path == venv_root }.each(&:rmtree) if vendor_python.exist?
venv_python = venv_root/"bin/python"
repo_requirements = HOMEBREW_LIBRARY/"Homebrew/formula-analytics/requirements.txt"
venv_requirements = venv_root/"requirements.txt"
if !venv_requirements.exist? || !FileUtils.identical?(repo_requirements, venv_requirements)
safe_system which_python, "-I", "-m", "venv", "--clear", venv_root, out: :err
safe_system venv_python, "-m", "pip", "install",
"--disable-pip-version-check",
"--require-hashes",
"--requirement", repo_requirements,
out: :err
FileUtils.cp repo_requirements, venv_requirements
end
ENV["PATH"] = "#{venv_root}/bin:#{ENV.fetch("PATH")}"
ENV["__PYVENV_LAUNCHER__"] = venv_python.to_s # support macOS framework Pythons
require "pycall"
PyCall.init(venv_python)
require formula_analytics_root/"pycall-setup"
end
sig { params(args: Homebrew::DevCmd::FormulaAnalytics::Args).void }
def influx_analytics(args)
require "utils/analytics"
require "json"
return if args.setup?
odie "`$HOMEBREW_NO_ANALYTICS` is set!" if ENV["HOMEBREW_NO_ANALYTICS"]
token = ENV.fetch("HOMEBREW_INFLUXDB_TOKEN", nil)
odie "No InfluxDB credentials found in `$HOMEBREW_INFLUXDB_TOKEN`!" unless token
client = InfluxDBClient3.new(
token:,
host: URI.parse(Utils::Analytics::INFLUX_HOST).host,
org: Utils::Analytics::INFLUX_ORG,
database: Utils::Analytics::INFLUX_BUCKET,
)
max_days_ago = (Date.today - FIRST_INFLUXDB_ANALYTICS_DATE).to_s.to_i
days_ago = (args.days_ago || 30).to_i
if days_ago > max_days_ago
opoo "Analytics started #{FIRST_INFLUXDB_ANALYTICS_DATE}. `--days-ago` set to maximum value."
days_ago = max_days_ago
end
if days_ago > 365
opoo "Analytics are only retained for 1 year, setting `--days-ago=365`."
days_ago = 365
end
all_core_formulae_json = args.all_core_formulae_json?
categories = []
categories << :build_error if args.build_error?
categories << :cask_install if args.cask_install?
categories << :formula_install if args.install?
categories << :formula_install_on_request if args.install_on_request?
categories << :homebrew_devcmdrun_developer if args.homebrew_devcmdrun_developer?
categories << :homebrew_os_arch_ci if args.homebrew_os_arch_ci?
categories << :homebrew_prefixes if args.homebrew_prefixes?
categories << :homebrew_versions if args.homebrew_versions?
categories << :os_versions if args.os_version?
categories << :command_run if args.brew_command_run?
categories << :command_run_options if args.brew_command_run_options?
categories << :test_bot_test if args.brew_test_bot_test?
category_matching_buckets = [:build_error, :cask_install, :command_run, :test_bot_test]
categories.each do |category|
additional_where = all_core_formulae_json ? " AND tap_name ~ '^homebrew/(core|cask)$'" : ""
bucket = if category_matching_buckets.include?(category)
category
elsif category == :command_run_options
:command_run
else
:formula_install
end
case category
when :homebrew_devcmdrun_developer
dimension_key = "devcmdrun_developer"
groups = [:devcmdrun, :developer]
when :homebrew_os_arch_ci
dimension_key = "os_arch_ci"
groups = [:os, :arch, :ci]
when :homebrew_prefixes
dimension_key = "prefix"
groups = [:prefix, :os, :arch]
when :homebrew_versions
dimension_key = "version"
groups = [:version]
when :os_versions
dimension_key = :os_version
groups = [:os_name_and_version]
when :command_run
dimension_key = "command_run"
groups = [:command]
when :command_run_options
dimension_key = "command_run_options"
groups = [:command, :options, :devcmdrun, :developer]
additional_where += " AND ci = 'false'"
when :test_bot_test
dimension_key = "test_bot_test"
groups = [:command, :passed, :arch, :os]
when :cask_install
dimension_key = :cask
groups = [:package, :tap_name]
else
dimension_key = :formula
additional_where += " AND on_request = 'true'" if category == :formula_install_on_request
groups = [:package, :tap_name, :options]
end
sql_groups = groups.map { |e| "\"#{e}\"" }.join(",")
query = <<~EOS
SELECT #{sql_groups}, COUNT(*) AS "count" FROM "#{bucket}" WHERE time >= now() - INTERVAL '#{days_ago} day'#{additional_where} GROUP BY #{sql_groups}
EOS
batches = begin
client.query(query:, language: "sql").to_batches
rescue PyCall::PyError => e
if e.message.include?("message: unauthenticated")
odie "Could not authenticate with InfluxDB! Please check your `$HOMEBREW_INFLUXDB_TOKEN`!"
end
raise
end
json = T.let({
category:,
total_items: 0,
start_date: Date.today - days_ago.to_i,
end_date: Date.today,
total_count: 0,
items: [],
}, T::Hash[Symbol, T.untyped])
batches.each do |batch|
batch.to_pylist.each do |record|
dimension = case category
when :homebrew_devcmdrun_developer
"devcmdrun=#{record["devcmdrun"]} HOMEBREW_DEVELOPER=#{record["developer"]}"
when :homebrew_os_arch_ci
if record["ci"] == "true"
"#{record["os"]} #{record["arch"]} (CI)"
else
"#{record["os"]} #{record["arch"]}"
end
when :homebrew_prefixes
if record["prefix"] == "custom-prefix"
"#{record["prefix"]} (#{record["os"]} #{record["arch"]})"
else
record["prefix"].to_s
end
when :os_versions
format_os_version_dimension(record["os_name_and_version"])
when :command_run_options
options = record["options"].split
# Cleanup bad data before TODO
# Can delete this code after 18th July 2025.
options.reject! { |option| option.match?(/^--with(out)?-/) }
next if options.any? { |option| option.match?(/^TMPDIR=/) }
"#{record["command"]} #{options.sort.join(" ")}"
when :test_bot_test
command_and_package, options = record["command"].split.partition { |arg| !arg.start_with?("-") }
# Cleanup bad data before https://github.com/Homebrew/homebrew-test-bot/pull/1043
# Can delete this code after 27th April 2025.
next if %w[audit install linkage style test].exclude?(command_and_package.first)
next if command_and_package.last.include?("/")
next if options.include?("--tap=")
next if options.include?("--only-dependencies")
next if options.include?("--cached")
command_and_options = (command_and_package + options.sort).join(" ")
passed = (record["passed"] == "true") ? "PASSED" : "FAILED"
"#{command_and_options} (#{record["os"]} #{record["arch"]}) (#{passed})"
else
record[groups.first.to_s]
end
next if dimension.blank?
if (tap_name = record["tap_name"].presence) &&
((tap_name != "homebrew/cask" && dimension_key == :cask) ||
(tap_name != "homebrew/core" && dimension_key == :formula))
dimension = "#{tap_name}/#{dimension}"
end
if (all_core_formulae_json || category == :build_error) &&
(options = record["options"].presence)
# homebrew/core formulae don't have non-HEAD options but they ended up in our analytics anyway.
if all_core_formulae_json
options = options.split.include?("--HEAD") ? "--HEAD" : ""
end
dimension = "#{dimension} #{options}"
end
dimension = dimension.strip
next if dimension.match?(/[<>]/)
count = record["count"]
json[:total_items] += 1
json[:total_count] += count
json[:items] << {
number: nil,
dimension_key => dimension,
count:,
}
end
end
odie "No data returned" if json[:total_count].zero?
# Combine identical values
deduped_items = {}
json[:items].each do |item|
key = item[dimension_key]
if deduped_items.key?(key)
deduped_items[key][:count] += item[:count]
else
deduped_items[key] = item
end
end
json[:items] = deduped_items.values
if all_core_formulae_json
core_formula_items = {}
json[:items].each do |item|
item.delete(:number)
formula_name, = item[dimension_key].split.first
next if formula_name.include?("/")
core_formula_items[formula_name] ||= []
core_formula_items[formula_name] << item
end
json.delete(:items)
core_formula_items.each_value do |items|
items.sort_by! { |item| -item[:count] }
items.each do |item|
item[:count] = format_count(item[:count])
end
end
json[:formulae] = core_formula_items.sort_by { |name, _| name }.to_h
else
json[:items].sort_by! do |item|
-item[:count]
end
json[:items].each_with_index do |item, index|
item[:number] = index + 1
percent = (item[:count].to_f / json[:total_count]) * 100
item[:percent] = format_percent(percent)
item[:count] = format_count(item[:count])
end
end
puts JSON.pretty_generate json
end
end
sig { params(count: Integer).returns(String) }
def format_count(count)
count.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end
sig { params(percent: Float).returns(String) }
def format_percent(percent)
format("%<percent>.2f", percent:).gsub(/\.00$/, "")
end
sig { params(dimension: T.nilable(String)).returns(T.nilable(String)) }
def format_os_version_dimension(dimension)
return if dimension.blank?
require "macos_version"
dimension = dimension.gsub(/^Intel ?/, "")
.gsub(/^macOS ?/, "")
.gsub(/ \(.+\)$/, "")
begin
macos_version = ::MacOSVersion.new(dimension)
if macos_version.pretty_name.presence && macos_version.to_sym != :dunno
return "macOS #{macos_version.pretty_name} (#{macos_version.strip_patch})"
end
rescue MacOSVersion::Error
nil
end
case dimension
when /Ubuntu(-Server)? (14|16|18|20|22|24)\.04/ then "Ubuntu #{Regexp.last_match(2)}.04 LTS"
when /Ubuntu(-Server)? (\d+\.\d+).\d ?(LTS)?/
"Ubuntu #{Regexp.last_match(2)} #{Regexp.last_match(3)}".strip
when %r{Debian GNU/Linux (\d+)\.\d+} then "Debian #{Regexp.last_match(1)} #{Regexp.last_match(2)}"
when /CentOS (\w+) (\d+)/ then "CentOS #{Regexp.last_match(1)} #{Regexp.last_match(2)}"
when /Fedora Linux (\d+)[.\d]*/ then "Fedora Linux #{Regexp.last_match(1)}"
when /KDE neon .*?([\d.]+)/ then "KDE neon #{Regexp.last_match(1)}"
when /Amazon Linux (\d+)\.[.\d]*/ then "Amazon Linux #{Regexp.last_match(1)}"
when /Fedora Linux Rawhide[.\dn]*/ then "Fedora Linux Rawhide"
when /Red Hat Enterprise Linux CoreOS (\d+\.\d+)[-.\d]*/
"Red Hat Enterprise Linux CoreOS #{Regexp.last_match(1)}"
when /([A-Za-z ]+)\s+(\d+)\.\d{8}[.\d]*/ then "#{Regexp.last_match(1)} #{Regexp.last_match(2)}"
# odisabled: add new entries when removing support, remove entries when no longer in the data
when /^10\.14[.\d]*/ then "macOS Mojave (10.14)"
when /^10\.13[.\d]*/ then "macOS High Sierra (10.13)"
when /^10\.12[.\d]*/ then "macOS Sierra (10.12)"
when /^10\.(\d+)/ then "macOS 10.#{Regexp.last_match(1)}"
else dimension
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/dev-cmd/create.rb | Library/Homebrew/dev-cmd/create.rb | # typed: strict
# frozen_string_literal: true
require "formula"
require "formula_creator"
require "missing_formula"
require "cask/cask_loader"
module Homebrew
module DevCmd
class Create < AbstractCommand
cmd_args do
description <<~EOS
Generate a formula or, with `--cask`, a cask for the downloadable file at <URL>
and open it in the editor. Homebrew will attempt to automatically derive the
formula name and version, but if it fails, you'll have to make your own template.
The `wget` formula serves as a simple example. For the complete API, see:
<https://docs.brew.sh/rubydoc/Formula>
EOS
switch "--autotools",
description: "Create a basic template for an Autotools-style build."
switch "--cabal",
description: "Create a basic template for a Cabal build."
switch "--cask",
description: "Create a basic template for a cask."
switch "--cmake",
description: "Create a basic template for a CMake-style build."
switch "--crystal",
description: "Create a basic template for a Crystal build."
switch "--go",
description: "Create a basic template for a Go build."
switch "--meson",
description: "Create a basic template for a Meson-style build."
switch "--node",
description: "Create a basic template for a Node build."
switch "--perl",
description: "Create a basic template for a Perl build."
switch "--python",
description: "Create a basic template for a Python build."
switch "--ruby",
description: "Create a basic template for a Ruby build."
switch "--rust",
description: "Create a basic template for a Rust build."
switch "--zig",
description: "Create a basic template for a Zig build."
switch "--no-fetch",
description: "Homebrew will not download <URL> to the cache and will thus not add its SHA-256 " \
"to the formula for you, nor will it check the GitHub API for GitHub projects " \
"(to fill out its description and homepage)."
switch "--HEAD",
description: "Indicate that <URL> points to the package's repository rather than a file."
flag "--set-name=",
description: "Explicitly set the <name> of the new formula or cask."
flag "--set-version=",
description: "Explicitly set the <version> of the new formula or cask."
flag "--set-license=",
description: "Explicitly set the <license> of the new formula."
flag "--tap=",
description: "Generate the new formula within the given tap, specified as <user>`/`<repo>."
switch "-f", "--force",
description: "Ignore errors for disallowed formula names and names that shadow aliases."
conflicts "--autotools", "--cabal", "--cmake", "--crystal", "--go", "--meson", "--node",
"--perl", "--python", "--ruby", "--rust", "--zig", "--cask"
conflicts "--cask", "--HEAD"
conflicts "--cask", "--set-license"
named_args :url, number: 1
end
# Create a formula from a tarball URL.
sig { override.void }
def run
path = if args.cask?
create_cask
else
create_formula
end
exec_editor path
end
private
sig { returns(Pathname) }
def create_cask
url = args.named.fetch(0)
name = if args.set_name.blank?
stem = Pathname.new(url).stem.rpartition("=").last
print "Cask name [#{stem}]: "
__gets || stem
else
args.set_name
end
token = Cask::Utils.token_from(T.must(name))
cask_tap = Tap.fetch(args.tap || "homebrew/cask")
raise TapUnavailableError, cask_tap.name unless cask_tap.installed?
cask_path = cask_tap.new_cask_path(token)
cask_path.dirname.mkpath unless cask_path.dirname.exist?
raise Cask::CaskAlreadyCreatedError, token if cask_path.exist?
version = if args.set_version
Version.new(T.must(args.set_version))
else
Version.detect(url.gsub(token, "").gsub(/x86(_64)?/, ""))
end
interpolated_url, sha256 = if version.null?
[url, ""]
else
sha256 = if args.no_fetch?
""
else
strategy = DownloadStrategyDetector.detect(url)
downloader = strategy.new(url, token, version.to_s, cache: Cask::Cache.path)
downloader.fetch
downloader.cached_location.sha256
end
[url.gsub(version.to_s, "\#{version}"), sha256]
end
cask_path.atomic_write <<~RUBY
# Documentation: https://docs.brew.sh/Cask-Cookbook
# https://docs.brew.sh/Adding-Software-to-Homebrew#cask-stanzas
# PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
cask "#{token}" do
version "#{version}"
sha256 "#{sha256}"
url "#{interpolated_url}"
name "#{name}"
desc ""
homepage ""
# Documentation: https://docs.brew.sh/Brew-Livecheck
livecheck do
url ""
strategy ""
end
depends_on macos: ""
app ""
# Documentation: https://docs.brew.sh/Cask-Cookbook#stanza-zap
zap trash: ""
end
RUBY
puts "Please run `brew audit --cask --new #{token}` before submitting, thanks."
cask_path
end
sig { returns(Pathname) }
def create_formula
mode = if args.autotools?
:autotools
elsif args.cmake?
:cmake
elsif args.crystal?
:crystal
elsif args.go?
:go
elsif args.cabal?
:cabal
elsif args.meson?
:meson
elsif args.node?
:node
elsif args.perl?
:perl
elsif args.python?
:python
elsif args.ruby?
:ruby
elsif args.rust?
:rust
elsif args.zig?
:zig
end
formula_creator = FormulaCreator.new(
url: args.named.fetch(0),
name: args.set_name,
version: args.set_version,
tap: args.tap,
mode:,
license: args.set_license,
fetch: !args.no_fetch?,
head: args.HEAD?,
)
# ask for confirmation if name wasn't passed explicitly
if args.set_name.blank?
print "Formula name [#{formula_creator.name}]: "
confirmed_name = __gets
formula_creator.name = confirmed_name if confirmed_name.present?
end
formula_creator.verify_tap_available!
# Check for disallowed formula, or names that shadow aliases,
# unless --force is specified.
unless args.force?
if (reason = MissingFormula.disallowed_reason(formula_creator.name))
odie <<~EOS
The formula '#{formula_creator.name}' is not allowed to be created.
#{reason}
If you really want to create this formula use `--force`.
EOS
end
Homebrew.with_no_api_env do
if Formula.aliases.include?(formula_creator.name)
realname = Formulary.canonical_name(formula_creator.name)
odie <<~EOS
The formula '#{realname}' is already aliased to '#{formula_creator.name}'.
Please check that you are not creating a duplicate.
To force creation use `--force`.
EOS
end
end
end
path = formula_creator.write_formula!
formula = Homebrew.with_no_api_env do
CoreTap.instance.clear_cache
Formula[formula_creator.name]
end
if args.python?
Homebrew.install_bundler_gems!(groups: ["ast"])
require "utils/pypi"
PyPI.update_python_resources! formula, ignore_non_pypi_packages: true
end
puts <<~EOS
Please audit and test formula before submitting:
HOMEBREW_NO_INSTALL_FROM_API=1 brew audit --new #{formula_creator.name}
HOMEBREW_NO_INSTALL_FROM_API=1 brew install --build-from-source --verbose --debug #{formula_creator.name}
HOMEBREW_NO_INSTALL_FROM_API=1 brew test #{formula_creator.name}
EOS
path
end
sig { returns(T.nilable(String)) }
def __gets
$stdin.gets&.presence&.chomp
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/dev-cmd/unpack.rb | Library/Homebrew/dev-cmd/unpack.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
require "stringio"
require "formula"
require "cask/download"
require "unpack_strategy"
module Homebrew
module DevCmd
class Unpack < AbstractCommand
include FileUtils
cmd_args do
description <<~EOS
Unpack the files for the <formula> or <cask> into subdirectories of the current
working directory.
EOS
flag "--destdir=",
description: "Create subdirectories in the directory named by <path> instead."
switch "--patch",
description: "Patches for <formula> will be applied to the unpacked source."
switch "-g", "--git",
description: "Initialise a Git repository in the unpacked source. This is useful for creating " \
"patches for the software."
switch "-f", "--force",
description: "Overwrite the destination directory if it already exists."
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--git", "--patch"
conflicts "--formula", "--cask"
conflicts "--cask", "--patch"
conflicts "--cask", "--git"
named_args [:formula, :cask], min: 1
end
sig { override.void }
def run
formulae_and_casks = if args.casks?
args.named.to_formulae_and_casks(only: :cask)
elsif args.formulae?
args.named.to_formulae_and_casks(only: :formula)
else
args.named.to_formulae_and_casks
end
if (dir = args.destdir)
unpack_dir = Pathname.new(dir).expand_path
unpack_dir.mkpath
else
unpack_dir = Pathname.pwd
end
odie "Cannot write to #{unpack_dir}" unless unpack_dir.writable?
formulae_and_casks.each do |formula_or_cask|
if formula_or_cask.is_a?(Cask::Cask)
unpack_cask(formula_or_cask, unpack_dir)
elsif (formula = T.cast(formula_or_cask, Formula))
unpack_formula(formula, unpack_dir)
end
end
end
private
sig { params(formula: Formula, unpack_dir: Pathname).void }
def unpack_formula(formula, unpack_dir)
stage_dir = unpack_dir/"#{formula.name}-#{formula.version}"
if stage_dir.exist?
odie "Destination #{stage_dir} already exists!" unless args.force?
rm_rf stage_dir
end
oh1 "Unpacking #{Formatter.identifier(formula.full_name)} to: #{stage_dir}"
# show messages about tar
with_env VERBOSE: "1" do
formula.brew do
formula.patch if args.patch?
cp_r getwd, stage_dir, preserve: true
end
end
return unless args.git?
ohai "Setting up Git repository"
cd(stage_dir) do
system "git", "init", "-q"
system "git", "add", "-A"
system "git", "commit", "-q", "-m", "brew-unpack"
end
end
sig { params(cask: Cask::Cask, unpack_dir: Pathname).void }
def unpack_cask(cask, unpack_dir)
stage_dir = unpack_dir/"#{cask.token}-#{cask.version}"
if stage_dir.exist?
odie "Destination #{stage_dir} already exists!" unless args.force?
rm_rf stage_dir
end
oh1 "Unpacking #{Formatter.identifier(cask.full_name)} to: #{stage_dir}"
download = Cask::Download.new(cask, quarantine: true)
downloaded_path = if download.downloaded?
download.cached_download
else
download.fetch(quiet: false)
end
stage_dir.mkpath
UnpackStrategy.detect(downloaded_path).extract_nestedly(to: stage_dir, verbose: true)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/dispatch-build-bottle.rb | Library/Homebrew/dev-cmd/dispatch-build-bottle.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "tap"
require "utils/bottles"
require "utils/github"
module Homebrew
module DevCmd
class DispatchBuildBottle < AbstractCommand
cmd_args do
description <<~EOS
Build bottles for these formulae with GitHub Actions.
EOS
flag "--tap=",
description: "Target tap repository (default: `homebrew/core`)."
flag "--timeout=",
description: "Build timeout (in minutes, default: 60)."
flag "--issue=",
description: "If specified, post a comment to this issue number if the job fails."
comma_array "--macos",
description: "macOS version (or comma-separated list of versions) the bottle should be built for."
flag "--workflow=",
description: "Dispatch specified workflow (default: `dispatch-build-bottle.yml`)."
switch "--upload",
description: "Upload built bottles."
switch "--linux",
description: "Dispatch bottle for Linux x86_64 (using GitHub runners)."
switch "--linux-arm64",
description: "Dispatch bottle for Linux arm64 (using GitHub runners)."
switch "--linux-self-hosted",
description: "Dispatch bottle for Linux x86_64 (using self-hosted runner)."
switch "--linux-wheezy",
description: "Use Debian Wheezy container for building the bottle on Linux."
conflicts "--linux", "--linux-self-hosted"
named_args :formula, min: 1
end
sig { override.void }
def run
tap = Tap.fetch(args.tap || CoreTap.instance.name)
user, repo = tap.full_name.split("/")
ref = "main"
workflow = args.workflow || "dispatch-build-bottle.yml"
runners = []
if (macos = args.macos&.compact_blank) && macos.present?
runners += macos.map do |element|
# We accept runner name syntax (11-arm64) or bottle syntax (arm64_big_sur)
os, arch = element.then do |s|
tag = Utils::Bottles::Tag.from_symbol(s.to_sym)
[tag.to_macos_version, tag.arch]
rescue ArgumentError, MacOSVersion::Error
os, arch = s.split("-", 2)
[MacOSVersion.new(os), arch&.to_sym]
end
if arch.present? && arch != :x86_64
"#{os}-#{arch}"
else
os.to_s
end
end
end
if args.linux?
runners << "ubuntu-22.04"
elsif args.linux_self_hosted?
runners << "linux-self-hosted-1"
end
runners << "ubuntu-22.04-arm" if args.linux_arm64?
if runners.empty?
raise UsageError, "Must specify `--macos`, `--linux`, `--linux-arm64`, or `--linux-self-hosted` option."
end
args.named.to_resolved_formulae.each do |formula|
# Required inputs
inputs = {
runner: runners.join(","),
formula: formula.name,
}
# Optional inputs
# These cannot be passed as nil to GitHub API
inputs[:timeout] = args.timeout if args.timeout
inputs[:issue] = args.issue if args.issue
inputs[:upload] = args.upload?
ohai "Dispatching #{tap} bottling request of formula \"#{formula.name}\" for #{runners.join(", ")}"
GitHub.workflow_dispatch_event(user, repo, workflow, ref, **inputs)
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/dev-cmd/audit.rb | Library/Homebrew/dev-cmd/audit.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
require "formula_versions"
require "utils/curl"
require "utils/github/actions"
require "utils/shared_audits"
require "utils/spdx"
require "extend/ENV"
require "formula_cellar_checks"
require "cmd/search"
require "style"
require "date"
require "missing_formula"
require "digest"
require "json"
require "formula_auditor"
require "tap_auditor"
module Homebrew
module DevCmd
class Audit < AbstractCommand
cmd_args do
description <<~EOS
Check <formula> or <cask> for Homebrew coding style violations. This should be run
before submitting a new formula or cask. If no <formula> or <cask> are provided, check
all locally available formulae and casks and skip style checks. Will exit with a
non-zero status if any errors are found.
EOS
flag "--os=",
description: "Audit the given operating system. (Pass `all` to audit all operating systems.)"
flag "--arch=",
description: "Audit the given CPU architecture. (Pass `all` to audit all architectures.)"
switch "--strict",
description: "Run additional, stricter style checks."
switch "--git",
description: "Run additional, slower style checks that navigate the Git repository."
switch "--online",
description: "Run additional, slower style checks that require a network connection."
switch "--installed",
description: "Only check formulae and casks that are currently installed."
switch "--eval-all",
description: "Evaluate all available formulae and casks, whether installed or not, to audit them.",
env: :eval_all
switch "--new",
description: "Run various additional style checks to determine if a new formula or cask is eligible " \
"for Homebrew. This should be used when creating new formulae or casks and implies " \
"`--strict` and `--online`."
switch "--[no-]signing",
description: "Audit for app signatures, which are required by macOS on ARM."
switch "--token-conflicts",
description: "Audit for token conflicts.",
hidden: true
switch "--changed",
description: "Check files that were changed from the `main` branch."
flag "--tap=",
description: "Check formulae and casks within the given tap, specified as <user>`/`<repo>."
switch "--fix",
description: "Fix style violations automatically using RuboCop's auto-correct feature."
switch "--display-cop-names",
description: "Include the RuboCop cop name for each violation in the output. This is the default.",
hidden: true
switch "--display-filename",
description: "Prefix every line of output with the file or formula name being audited, to " \
"make output easy to grep."
switch "--skip-style",
description: "Skip running non-RuboCop style checks. Useful if you plan on running " \
"`brew style` separately. Enabled by default unless a formula is specified by name."
switch "-D", "--audit-debug",
description: "Enable debugging and profiling of audit methods."
comma_array "--only",
description: "Specify a comma-separated <method> list to only run the methods named " \
"`audit_`<method>."
comma_array "--except",
description: "Specify a comma-separated <method> list to skip running the methods named " \
"`audit_`<method>."
comma_array "--only-cops",
description: "Specify a comma-separated <cops> list to check for violations of only the listed " \
"RuboCop cops."
comma_array "--except-cops",
description: "Specify a comma-separated <cops> list to skip checking for violations of the " \
"listed RuboCop cops."
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--installed", "--eval-all", "--changed", "--tap"
conflicts "--only", "--except"
conflicts "--only-cops", "--except-cops", "--strict"
conflicts "--only-cops", "--except-cops", "--only"
conflicts "--formula", "--cask"
named_args [:formula, :cask], without_api: true
end
sig { override.void }
def run
odisabled "`brew audit --token-conflicts`" if args.token_conflicts?
Formulary.enable_factory_cache!
os_arch_combinations = args.os_arch_combinations
Homebrew.auditing = true
Homebrew.inject_dump_stats!(FormulaAuditor, /^audit_/) if args.audit_debug?
strict = args.new? || args.strict?
online = args.new? || args.online?
tap_audit = args.tap.present?
skip_style = args.skip_style? || args.no_named? || tap_audit
no_named_args = T.let(false, T::Boolean)
gem_groups = ["audit"]
gem_groups << "style" unless skip_style
Homebrew.install_bundler_gems!(groups: gem_groups)
ENV.activate_extensions!
ENV.setup_build_environment
audit_formulae, audit_casks = Homebrew.with_no_api_env do # audit requires full Ruby source
if args.changed?
tap = Tap.from_path(Dir.pwd)
odie "`brew audit --changed` must be run inside a tap!" if tap.blank?
no_named_args = true
audit_formulae = []
audit_casks = []
changed_files = Utils.popen_read("git", "diff", "--name-only", "--no-relative", "main")
changed_files.split("\n").each do |file|
next unless file.end_with?(".rb")
absolute_file = File.expand_path(file, tap.path)
next unless File.exist?(absolute_file)
if tap.formula_file?(file)
audit_formulae << Formulary.factory(absolute_file)
elsif tap.cask_file?(file)
audit_casks << Cask::CaskLoader.load(absolute_file)
end
end
[audit_formulae, audit_casks]
elsif args.tap
Tap.fetch(args.tap).then do |tap|
[
tap.formula_files.map { |path| Formulary.factory(path) },
tap.cask_files.map { |path| Cask::CaskLoader.load(path) },
]
end
elsif args.installed?
no_named_args = true
[Formula.installed, Cask::Caskroom.casks]
elsif args.no_named?
eval_all = args.eval_all?
unless eval_all
# This odisabled should probably stick around indefinitely.
odisabled "`brew audit`",
"`brew audit --eval-all` or set `HOMEBREW_EVAL_ALL=1`"
end
no_named_args = true
[
Formula.all(eval_all:),
Cask::Cask.all(eval_all:),
]
else
if args.named.any? { |named_arg| named_arg.end_with?(".rb") }
# This odisabled should probably stick around indefinitely,
# until at least we have a way to exclude error on these in the CLI parser.
odisabled "`brew audit [path ...]`",
"`brew audit [name ...]`"
end
args.named.to_formulae_and_casks_with_taps
.partition { |formula_or_cask| formula_or_cask.is_a?(Formula) }
end
end
if audit_formulae.empty? && audit_casks.empty? && !args.tap
ofail "No matching formulae or casks to audit!"
return
end
style_files = args.named.to_paths unless skip_style
only_cops = args.only_cops
except_cops = args.except_cops
style_options = { fix: args.fix?, debug: args.debug?, verbose: args.verbose? }
if only_cops
style_options[:only_cops] = only_cops
elsif args.new?
nil
elsif except_cops
style_options[:except_cops] = except_cops
elsif !strict
style_options[:except_cops] = [:FormulaAuditStrict]
end
# Run tap audits first
named_arg_taps = [*audit_formulae, *audit_casks].map(&:tap).uniq if !args.tap && !no_named_args
tap_problems = Tap.installed.each_with_object({}) do |tap, problems|
next if args.tap && tap != args.tap
next if named_arg_taps&.exclude?(tap)
ta = TapAuditor.new(tap, strict: args.strict?)
ta.audit
problems[[tap.name, tap.path]] = ta.problems if ta.problems.any?
end
# Check style in a single batch run up front for performance
style_offenses = Style.check_style_json(style_files, **style_options) if style_files
# load licenses
spdx_license_data = SPDX.license_data
spdx_exception_data = SPDX.exception_data
formula_problems = audit_formulae.sort.each_with_object({}) do |f, problems|
path = f.path
only = only_cops ? ["style"] : args.only
options = {
new_formula: args.new?,
strict:,
online:,
git: args.git?,
only:,
except: args.except,
spdx_license_data:,
spdx_exception_data:,
style_offenses: style_offenses&.for_path(f.path),
tap_audit:,
}.compact
errors = os_arch_combinations.flat_map do |os, arch|
SimulateSystem.with(os:, arch:) do
odebug "Auditing Formula #{f} on os #{os} and arch #{arch}"
audit_proc = proc { FormulaAuditor.new(Formulary.factory(path), **options).tap(&:audit) }
# Audit requires full Ruby source so disable API. We shouldn't do this for taps however so that we
# don't unnecessarily require a full Homebrew/core clone.
fa = if f.core_formula?
Homebrew.with_no_api_env(&audit_proc)
else
audit_proc.call
end
fa.problems + fa.new_formula_problems
end
end.uniq
problems[[f.full_name, path]] = errors if errors.any?
end
require "cask/auditor" if audit_casks.any?
cask_problems = audit_casks.each_with_object({}) do |cask, problems|
path = cask.sourcefile_path
errors = os_arch_combinations.flat_map do |os, arch|
next [] if os == :linux
SimulateSystem.with(os:, arch:) do
odebug "Auditing Cask #{cask} on os #{os} and arch #{arch}"
Cask::Auditor.audit(
Cask::CaskLoader.load(path),
# For switches, we add `|| nil` so that `nil` will be passed
# instead of `false` if they aren't set.
# This way, we can distinguish between "not set" and "set to false".
audit_online: args.online? || nil,
audit_strict: args.strict? || nil,
# No need for `|| nil` for `--[no-]signing`
# because boolean switches are already `nil` if not passed
audit_signing: args.signing?,
audit_new_cask: args.new? || nil,
quarantine: true,
any_named_args: !no_named_args,
only: args.only || [],
except: args.except || [],
).to_a
end
end.uniq
problems[[cask.full_name, path]] = errors if errors.any?
end
print_problems(tap_problems)
print_problems(formula_problems)
print_problems(cask_problems)
tap_count = tap_problems.keys.count
formula_count = formula_problems.keys.count
cask_count = cask_problems.keys.count
corrected_problem_count = (formula_problems.values + cask_problems.values)
.sum { |problems| problems.count { |problem| problem.fetch(:corrected) } }
tap_problem_count = tap_problems.sum { |_, problems| problems.count }
formula_problem_count = formula_problems.sum { |_, problems| problems.count }
cask_problem_count = cask_problems.sum { |_, problems| problems.count }
total_problems_count = formula_problem_count + cask_problem_count + tap_problem_count
if total_problems_count.positive?
errors_summary = Utils.pluralize("problem", total_problems_count, include_count: true)
error_sources = []
error_sources << Utils.pluralize("formula", formula_count, include_count: true) if formula_count.positive?
error_sources << Utils.pluralize("cask", cask_count, include_count: true) if cask_count.positive?
error_sources << Utils.pluralize("tap", tap_count, include_count: true) if tap_count.positive?
errors_summary += " in #{error_sources.to_sentence}" if error_sources.any?
errors_summary += " detected"
if corrected_problem_count.positive?
errors_summary +=
", #{Utils.pluralize("problem", corrected_problem_count, include_count: true)} corrected"
end
ofail "#{errors_summary}."
end
return unless GitHub::Actions.env_set?
annotations = formula_problems.merge(cask_problems).flat_map do |(_, path), problems|
problems.map do |problem|
GitHub::Actions::Annotation.new(
:error,
problem[:message],
file: path,
line: problem[:location]&.line,
column: problem[:location]&.column,
)
end
end.compact
annotations.each do |annotation|
puts annotation if annotation.relevant?
end
end
private
sig { params(results: T::Hash[[Symbol, Pathname], T::Array[T::Hash[Symbol, T.untyped]]]).void }
def print_problems(results)
results.each do |(name, path), problems|
problem_lines = format_problem_lines(problems)
if args.display_filename?
problem_lines.each do |l|
puts "#{path}: #{l}"
end
else
puts name, problem_lines.map { |l| l.dup.prepend(" ") }
end
end
end
sig { params(problems: T::Array[T::Hash[Symbol, T.untyped]]).returns(T::Array[String]) }
def format_problem_lines(problems)
problems.map do |problem|
status = " #{Formatter.success("[corrected]")}" if problem.fetch(:corrected)
location = problem.fetch(:location)
if location
location = "#{location.line&.to_s&.prepend("line ")}#{location.column&.to_s&.prepend(", col ")}: "
end
message = problem.fetch(:message)
"* #{location}#{message.chomp.gsub("\n", "\n ")}#{status}"
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/dev-cmd/lgtm.rb | Library/Homebrew/dev-cmd/lgtm.rb | # typed: strict
# frozen_string_literal: true
require "tap"
module Homebrew
module DevCmd
class Lgtm < AbstractCommand
include SystemCommand::Mixin
cmd_args do
description <<~EOS
Run `brew typecheck`, `brew style --changed` and `brew tests --changed` in one go.
EOS
switch "--online",
description: "Run additional, slower checks that require a network connection."
named_args :none
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: Homebrew.valid_gem_groups - ["sorbet"])
tap = Tap.from_path(Dir.pwd)
typecheck_args = ["typecheck", tap&.name].compact
ohai "brew #{typecheck_args.join(" ")}"
safe_system HOMEBREW_BREW_FILE, *typecheck_args
puts
ohai "brew style --changed --fix"
safe_system HOMEBREW_BREW_FILE, "style", "--changed", "--fix"
puts
audit_or_tests_args = ["--changed"]
audit_or_tests_args << "--online" if args.online?
if tap
audit_or_tests_args << "--skip-style"
ohai "brew audit #{audit_or_tests_args.join(" ")}"
safe_system HOMEBREW_BREW_FILE, "audit", *audit_or_tests_args
else
ohai "brew tests #{audit_or_tests_args.join(" ")}"
safe_system HOMEBREW_BREW_FILE, "tests", *audit_or_tests_args
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/formula.rb | Library/Homebrew/dev-cmd/formula.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module DevCmd
class FormulaCmd < AbstractCommand
cmd_args do
description <<~EOS
Display the path where <formula> is located.
EOS
named_args :formula, min: 1, without_api: true
end
sig { override.void }
def run
formula_paths = args.named.to_paths(only: :formula).select(&:exist?)
if formula_paths.blank? && args.named
.to_paths(only: :cask)
.any?(&:exist?)
odie "Found casks but did not find formulae!"
end
formula_paths.each { puts it }
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/dev-cmd/bump-formula-pr.rb | Library/Homebrew/dev-cmd/bump-formula-pr.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
require "formula"
require "utils/inreplace"
require "utils/tar"
module Homebrew
module DevCmd
class BumpFormulaPr < AbstractCommand
cmd_args do
description <<~EOS
Create a pull request to update <formula> with a new URL or a new tag.
If a <URL> is specified, the <SHA-256> checksum of the new download should also
be specified. A best effort to determine the <SHA-256> will be made if not supplied
by the user.
If a <tag> is specified, the Git commit <revision> corresponding to that tag
should also be specified. A best effort to determine the <revision> will be made
if the value is not supplied by the user.
If a <version> is specified, a best effort to determine the <URL> and <SHA-256> or
the <tag> and <revision> will be made if both values are not supplied by the user.
*Note:* this command cannot be used to transition a formula from a
URL-and-SHA-256 style specification into a tag-and-revision style specification,
nor vice versa. It must use whichever style specification the formula already uses.
EOS
switch "-n", "--dry-run",
description: "Print what would be done rather than doing it."
switch "--write-only",
description: "Make the expected file modifications without taking any Git actions."
switch "--commit",
depends_on: "--write-only",
description: "When passed with `--write-only`, generate a new commit after writing changes " \
"to the formula file."
switch "--no-audit",
description: "Don't run `brew audit` before opening the PR."
switch "--strict",
description: "Run `brew audit --strict` before opening the PR."
switch "--online",
description: "Run `brew audit --online` before opening the PR."
switch "--no-browse",
description: "Print the pull request URL instead of opening in a browser."
switch "--no-fork",
description: "Don't try to fork the repository."
comma_array "--mirror",
description: "Use the specified <URL> as a mirror URL. If <URL> is a comma-separated list " \
"of URLs, multiple mirrors will be added."
flag "--fork-org=",
description: "Use the specified GitHub organization for forking."
flag "--version=",
description: "Use the specified <version> to override the value parsed from the URL or tag. Note " \
"that `--version=0` can be used to delete an existing version override from a " \
"formula if it has become redundant."
flag "--message=",
description: "Prepend <message> to the default pull request message."
flag "--url=",
description: "Specify the <URL> for the new download. If a <URL> is specified, the <SHA-256> " \
"checksum of the new download should also be specified."
flag "--sha256=",
depends_on: "--url=",
description: "Specify the <SHA-256> checksum of the new download."
flag "--tag=",
description: "Specify the new git commit <tag> for the formula."
flag "--revision=",
description: "Specify the new commit <revision> corresponding to the specified git <tag> " \
"or specified <version>."
switch "-f", "--force",
description: "Remove all mirrors if `--mirror` was not specified."
switch "--install-dependencies",
description: "Install missing dependencies required to update resources."
flag "--python-package-name=",
description: "Use the specified <package-name> when finding Python resources for <formula>. " \
"If no package name is specified, it will be inferred from the formula's stable URL."
comma_array "--python-extra-packages=",
description: "Include these additional Python packages when finding resources."
comma_array "--python-exclude-packages=",
description: "Exclude these Python packages when finding resources."
comma_array "--bump-synced=",
hidden: true
conflicts "--dry-run", "--write-only"
conflicts "--no-audit", "--strict"
conflicts "--no-audit", "--online"
conflicts "--url", "--tag"
named_args :formula, max: 1, without_api: true
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["ast"])
require "utils/pypi"
if args.revision.present? && args.tag.nil? && args.version.nil?
raise UsageError, "`--revision` must be passed with either `--tag` or `--version`!"
end
# As this command is simplifying user-run commands then let's just use a
# user path, too.
ENV["PATH"] = PATH.new(ORIGINAL_PATHS).to_s
# Use the user's browser, too.
ENV["BROWSER"] = Homebrew::EnvConfig.browser
@tap_retried = T.let(false, T.nilable(T::Boolean))
begin
formula = args.named.to_formulae.first
raise FormulaUnspecifiedError if formula.blank?
raise ArgumentError, "This formula is disabled!" if formula.disabled?
if formula.deprecation_reason == :does_not_build
raise ArgumentError, "This formula is deprecated and does not build!"
end
tap = formula.tap
raise ArgumentError, "This formula is not in a tap!" if tap.blank?
raise ArgumentError, "This formula's tap is not a Git repository!" unless tap.git?
formula
rescue ArgumentError => e
odie e.message if @tap_retried
CoreTap.instance.install(force: true)
@tap_retried = true
retry
end
odie <<~EOS unless tap.allow_bump?(formula.name)
Whoops, the #{formula.name} formula has its version update
pull requests automatically opened by BrewTestBot every ~3 hours!
We'd still love your contributions, though, so try another one
that is excluded from autobump list (i.e. it has 'no_autobump!'
method or 'livecheck' block with 'skip'.)
EOS
if !args.write_only? && GitHub.too_many_open_prs?(tap)
odie "You have too many PRs open: close or merge some first!"
end
formula_spec = formula.stable
odie "#{formula}: no stable specification found!" if formula_spec.blank?
# This will be run by `brew audit` later so run it first to not start
# spamming during normal output.
Homebrew.install_bundler_gems!(groups: ["audit", "style"]) unless args.no_audit?
tap_remote_repo = T.must(tap.remote_repository)
remote = "origin"
remote_branch = tap.git_repository.origin_branch_name
previous_branch = "-"
check_pull_requests(formula, tap_remote_repo, state: "open") unless args.write_only?
all_formulae = []
if args.bump_synced.present?
Array(args.bump_synced).each do |formula_name|
all_formulae << formula_name
end
else
all_formulae << args.named.first.to_s
end
return if all_formulae.empty?
commits = all_formulae.filter_map do |formula_name|
commit_formula = Formula[formula_name]
raise FormulaUnspecifiedError if commit_formula.blank?
commit_formula_spec = commit_formula.stable
odie "#{commit_formula}: no stable specification found!" if commit_formula_spec.blank?
formula_pr_message = ""
new_url = args.url
new_version = args.version
check_new_version(commit_formula, tap_remote_repo, version: new_version) if new_version.present?
opoo "This formula has patches that may be resolved upstream." if commit_formula.patchlist.present?
if commit_formula.resources.any? { |resource| !resource.name.start_with?("homebrew-") }
opoo "This formula has resources that may need to be updated."
end
old_mirrors = commit_formula_spec.mirrors
new_mirrors ||= args.mirror
if new_url.present? && (new_mirror = determine_mirror(new_url))
new_mirrors ||= [new_mirror]
check_for_mirrors(commit_formula.name, old_mirrors, new_mirrors)
end
old_hash = commit_formula_spec.checksum&.hexdigest
new_hash = args.sha256
new_tag = args.tag
new_revision = args.revision
old_url = T.must(commit_formula_spec.url)
old_tag = commit_formula_spec.specs[:tag]
old_formula_version = formula_version(commit_formula)
old_version = old_formula_version.to_s
forced_version = new_version.present?
new_url_hash = if new_url.present? && new_hash.present?
check_new_version(commit_formula, tap_remote_repo, url: new_url) if new_version.blank?
true
elsif new_tag.present? && new_revision.present?
check_new_version(commit_formula, tap_remote_repo, url: old_url, tag: new_tag) if new_version.blank?
false
elsif old_hash.blank?
if new_tag.blank? && new_version.blank? && new_revision.blank?
raise UsageError, "#{formula}: no `--tag` or `--version` argument specified!"
end
if old_tag.present?
new_tag ||= old_tag.gsub(old_version, new_version)
if new_tag == old_tag
odie <<~EOS
You need to bump this formula manually since the new tag
and old tag are both #{new_tag}.
EOS
end
check_new_version(commit_formula, tap_remote_repo, url: old_url, tag: new_tag) if new_version.blank?
resource_path, forced_version = fetch_resource_and_forced_version(commit_formula, new_version, old_url,
tag: new_tag)
new_revision = Utils.popen_read("git", "-C", resource_path.to_s, "rev-parse", "-q", "--verify", "HEAD")
new_revision = new_revision.strip
elsif new_revision.blank?
odie "#{commit_formula}: the current URL requires specifying a `--revision=` argument."
end
false
elsif new_url.blank? && new_version.blank?
raise UsageError, "#{commit_formula}: no `--url` or `--version` argument specified!"
else
new_url ||= PyPI.update_pypi_url(old_url, new_version) if new_version.present?
if new_url.blank? && new_version.present?
new_url = update_url(old_url, old_version, new_version)
if new_mirrors.blank? && old_mirrors.present?
new_mirrors = old_mirrors.map do |old_mirror|
update_url(old_mirror, old_version, new_version)
end
end
end
if new_url == old_url
odie <<~EOS
You need to bump this formula manually since the new URL
and old URL are both:
#{new_url}
EOS
end
if new_url.blank?
odie "There was an issue generating the updated url, you may need to create the PR manually"
end
check_new_version(commit_formula, tap_remote_repo, url: new_url) if new_version.blank?
resource_path, forced_version = fetch_resource_and_forced_version(commit_formula, new_version, new_url)
Utils::Tar.validate_file(resource_path)
new_hash = resource_path.sha256
end
replacement_pairs = []
if commit_formula.revision.nonzero?
replacement_pairs << [
/^ revision \d+\n(\n( head "))?/m,
"\\2",
]
end
replacement_pairs += commit_formula_spec.mirrors.map do |mirror|
[
/ +mirror "#{Regexp.escape(mirror)}"\n/m,
"",
]
end
replacement_pairs += if new_url_hash.present?
[
[
/#{Regexp.escape(T.must(commit_formula_spec.url))}/,
new_url,
],
[
old_hash,
new_hash,
],
]
elsif new_tag.present?
[
[
/tag:(\s+")#{commit_formula_spec.specs[:tag]}(?=")/,
"tag:\\1#{new_tag}\\2",
],
[
commit_formula_spec.specs[:revision],
new_revision,
],
]
elsif new_url.present?
[
[
/#{Regexp.escape(T.must(commit_formula_spec.url))}/,
new_url,
],
[
commit_formula_spec.specs[:revision],
new_revision,
],
]
else
[
[
commit_formula_spec.specs[:revision],
new_revision,
],
]
end
old_contents = commit_formula.path.read
if new_mirrors.present? && new_url.present?
replacement_pairs << [
/^( +)(url "#{Regexp.escape(new_url)}"[^\n]*?\n)/m,
"\\1\\2\\1mirror \"#{new_mirrors.join("\"\n\\1mirror \"")}\"\n",
]
end
if forced_version && new_version != "0"
replacement_pairs << if old_contents.include?("version \"#{old_formula_version}\"")
[
"version \"#{old_formula_version}\"",
"version \"#{new_version}\"",
]
elsif new_mirrors.present?
[
/^( +)(mirror "#{Regexp.escape(new_mirrors.last)}"\n)/m,
"\\1\\2\\1version \"#{new_version}\"\n",
]
elsif new_url.present?
[
/^( +)(url "#{Regexp.escape(new_url)}"[^\n]*?\n)/m,
"\\1\\2\\1version \"#{new_version}\"\n",
]
elsif new_revision.present?
[
/^( {2})( +)(:revision => "#{new_revision}"\n)/m,
"\\1\\2\\3\\1version \"#{new_version}\"\n",
]
end
elsif forced_version && new_version == "0"
replacement_pairs << [
/^ version "[\w.\-+]+"\n/m,
"",
]
end
new_contents = Utils::Inreplace.inreplace_pairs(commit_formula.path,
replacement_pairs.uniq.compact,
read_only_run: args.dry_run?,
silent: args.quiet?)
new_formula_version = formula_version(commit_formula, new_contents)
if new_formula_version < old_formula_version
commit_formula.path.atomic_write(old_contents) unless args.dry_run?
odie <<~EOS
You need to bump this formula manually since changing the version
from #{old_formula_version} to #{new_formula_version} would be a downgrade.
EOS
elsif new_formula_version == old_formula_version
commit_formula.path.atomic_write(old_contents) unless args.dry_run?
odie <<~EOS
You need to bump this formula manually since the new version
and old version are both #{new_formula_version}.
EOS
end
alias_rename = alias_update_pair(commit_formula, new_formula_version)
if alias_rename.present?
ohai "Renaming alias #{alias_rename.first} to #{alias_rename.last}"
alias_rename.map! { |a| tap.alias_dir/a }
end
unless args.dry_run?
resources_checked = PyPI.update_python_resources! formula,
version: new_formula_version.to_s,
package_name: args.python_package_name,
extra_packages: args.python_extra_packages,
exclude_packages: args.python_exclude_packages,
install_dependencies: args.install_dependencies?,
silent: args.quiet?,
ignore_non_pypi_packages: true
update_matching_version_resources! commit_formula,
version: new_formula_version.to_s
end
if resources_checked.nil? && commit_formula.resources.any? do |resource|
resource.livecheck.formula != :parent && !resource.name.start_with?("homebrew-")
end
formula_pr_message += <<~EOS
- [ ] `resource` blocks have been checked for updates.
EOS
end
if new_url =~ %r{^https://github\.com/([\w-]+)/([\w-]+)/archive/refs/tags/(v?[.0-9]+)\.tar\.}
owner = Regexp.last_match(1)
repo = Regexp.last_match(2)
tag = Regexp.last_match(3)
github_release_data = begin
GitHub::API.open_rest("#{GitHub::API_URL}/repos/#{owner}/#{repo}/releases/tags/#{tag}")
rescue GitHub::API::HTTPNotFoundError
# If this is a 404: we can't do anything.
nil
end
if github_release_data.present? && github_release_data["body"].present?
pre = "pre" if github_release_data["prerelease"].present?
# maximum length of PR body is 65,536 characters so let's truncate release notes to half of that.
body = Formatter.truncate(github_release_data["body"], max: 32_768)
# Ensure the URL is properly HTML encoded to handle any quotes or other special characters
html_url = CGI.escapeHTML(github_release_data["html_url"])
formula_pr_message += <<~XML
<details>
<summary>#{pre}release notes</summary>
<pre>#{body}</pre>
<p>View the full release notes at <a href="#{html_url}">#{html_url}</a>.</p>
</details>
XML
end
end
{
sourcefile_path: commit_formula.path,
old_contents:,
commit_message: "#{commit_formula.name} #{new_formula_version}",
additional_files: alias_rename,
formula_pr_message:,
formula_name: commit_formula.name,
new_version: new_formula_version,
}
end
commits.each do |commit|
commit_formula = Formula[commit[:formula_name]]
# For each formula, run `brew audit` to check for any issues.
audit_result = run_audit(commit_formula, commit[:additional_files],
skip_synced_versions: args.bump_synced.present?)
next unless audit_result
# If `brew audit` fails, revert the changes made to any formula.
commits.each do |revert|
revert_formula = Formula[revert[:formula_name]]
revert_formula.path.atomic_write(revert[:old_contents]) if !args.dry_run? && !args.write_only?
revert_alias_rename = revert[:additional_files]
if revert_alias_rename && (source = revert_alias_rename.first) && (destination = revert_alias_rename.last)
FileUtils.mv source, destination
end
end
odie "`brew audit` failed for #{commit[:formula_name]}!"
end
new_formula_version = commits.fetch(0)[:new_version]
pr_title = if args.bump_synced.nil?
"#{formula.name} #{new_formula_version}"
else
maximum_characters_in_title = 72
max = maximum_characters_in_title - new_formula_version.to_s.length - 1
"#{Formatter.truncate(Array(args.bump_synced).join(" "), max:)} #{new_formula_version}"
end
pr_message = "Created with `brew bump-formula-pr`."
commits.each do |commit|
next if commit[:formula_pr_message].empty?
pr_message += "<h4>#{commit[:formula_name]}</h4>" if commits.length != 1
pr_message += "#{commit[:formula_pr_message]}<hr>"
end
pr_info = {
commits:,
remote:,
remote_branch:,
branch_name: "bump-#{formula.name}-#{new_formula_version}",
pr_title:,
previous_branch:,
tap: tap,
tap_remote_repo:,
pr_message:,
}
GitHub.create_bump_pr(pr_info, args:)
end
private
sig { params(url: String).returns(T.nilable(String)) }
def determine_mirror(url)
case url
when %r{.*ftp\.gnu\.org/gnu.*}
url.sub "ftp.gnu.org/gnu", "ftpmirror.gnu.org"
when %r{.*download\.savannah\.gnu\.org/*}
url.sub "download.savannah.gnu.org", "download-mirror.savannah.gnu.org"
when %r{.*www\.apache\.org/dyn/closer\.lua\?path=.*}
url.sub "www.apache.org/dyn/closer.lua?path=", "archive.apache.org/dist/"
when %r{.*mirrors\.ocf\.berkeley\.edu/debian.*}
url.sub "mirrors.ocf.berkeley.edu/debian", "mirrorservice.org/sites/ftp.debian.org/debian"
end
end
sig { params(formula: String, old_mirrors: T::Array[String], new_mirrors: T::Array[String]).void }
def check_for_mirrors(formula, old_mirrors, new_mirrors)
return if new_mirrors.present? || old_mirrors.empty?
if args.force?
opoo "#{formula}: Removing all mirrors because a `--mirror=` argument was not specified."
else
odie <<~EOS
#{formula}: a `--mirror=` argument for updating the mirror URL(s) was not specified.
Use `--force` to remove all mirrors.
EOS
end
end
sig { params(old_url: String, old_version: String, new_version: String).returns(String) }
def update_url(old_url, old_version, new_version)
new_url = old_url.gsub(old_version, new_version)
return new_url if (old_version_parts = old_version.split(".")).length < 2
return new_url if (new_version_parts = new_version.split(".")).length != old_version_parts.length
partial_old_version = old_version_parts[0..-2]&.join(".")
partial_new_version = new_version_parts[0..-2]&.join(".")
return new_url if partial_old_version.blank? || partial_new_version.blank?
new_url.gsub(%r{/(v?)#{Regexp.escape(partial_old_version)}/}, "/\\1#{partial_new_version}/")
end
sig {
params(formula_or_resource: T.any(Formula, Resource), new_version: T.nilable(String), url: String,
specs: String).returns(T::Array[T.untyped])
}
def fetch_resource_and_forced_version(formula_or_resource, new_version, url, **specs)
resource = Resource.new
resource.url(url, **specs)
resource.owner = if formula_or_resource.is_a?(Formula)
Resource.new(formula_or_resource.name)
else
Resource.new(formula_or_resource.owner.name)
end
forced_version = new_version && new_version != resource.version.to_s
resource.version(new_version) if forced_version
odie "Couldn't identify version, specify it using `--version=`." if resource.version.blank?
[resource.fetch, forced_version]
end
sig {
params(
formula: Formula,
version: String,
).void
}
def update_matching_version_resources!(formula, version:)
formula.resources.select { |r| r.livecheck.formula == :parent }.each do |resource|
new_url = update_url(resource.url, resource.version.to_s, version)
if new_url == resource.url
opoo <<~EOS
You need to bump resource "#{resource.name}" manually since the new URL
and old URL are both:
#{new_url}
EOS
next
end
new_mirrors = resource.mirrors.map do |mirror|
update_url(mirror, resource.version.to_s, version)
end
resource_path, forced_version = fetch_resource_and_forced_version(resource, version, new_url)
Utils::Tar.validate_file(resource_path)
new_hash = resource_path.sha256
inreplace_regex = /
[ ]+resource\ "#{resource.name}"\ do\s+
url\ .*\s+
(mirror\ .*\s+)*
sha256\ .*\s+
(version\ .*\s+)?
(\#.*\s+)*
livecheck\ do\s+
formula\ :parent\s+
end\s+
((\#.*\s+)*
patch\ (.*\ )?do\s+
url\ .*\s+
sha256\ .*\s+
end\s+)*
end\s
/x
leading_spaces = T.must(formula.path.read.match(/^( +)resource "#{resource.name}"/)).captures.first
new_resource_block = <<~EOS
#{leading_spaces}resource "#{resource.name}" do
#{leading_spaces} url "#{new_url}"#{new_mirrors.map { |m| "\n#{leading_spaces} mirror \"#{m}\"" }.join}
#{leading_spaces} sha256 "#{new_hash}"
#{"#{leading_spaces} version \"#{version}\"\n" if forced_version}
#{leading_spaces} livecheck do
#{leading_spaces} formula :parent
#{leading_spaces} end
#{leading_spaces}end
EOS
Utils::Inreplace.inreplace formula.path do |s|
s.sub! inreplace_regex, new_resource_block
end
end
end
sig { params(formula: Formula, contents: T.nilable(String)).returns(Version) }
def formula_version(formula, contents = nil)
spec = :stable
name = formula.name
path = formula.path
if contents.present?
Formulary.from_contents(name, path, contents, spec).version
else
Formulary::FormulaLoader.new(name, path).get_formula(spec).version
end
end
sig {
params(formula: Formula, tap_remote_repo: String, state: T.nilable(String),
version: T.nilable(String)).void
}
def check_pull_requests(formula, tap_remote_repo, state: nil, version: nil)
tap = formula.tap
return if tap.nil?
# if we haven't already found open requests, try for an exact match across all pull requests
GitHub.check_for_duplicate_pull_requests(
formula.name, tap_remote_repo,
version:,
state:,
file: formula.path.relative_path_from(tap.path).to_s,
quiet: args.quiet?,
official_tap: tap.official?
)
end
sig {
params(formula: Formula, tap_remote_repo: String, version: T.nilable(String), url: T.nilable(String),
tag: T.nilable(String)).void
}
def check_new_version(formula, tap_remote_repo, version: nil, url: nil, tag: nil)
if version.nil?
specs = {}
specs[:tag] = tag if tag.present?
return if url.blank?
version = Version.detect(url, **specs).to_s
return if version.blank?
end
check_throttle(formula, version)
check_pull_requests(formula, tap_remote_repo, version:) unless args.write_only?
end
sig { params(formula: Formula, new_version: String).void }
def check_throttle(formula, new_version)
tap = formula.tap
return if tap.nil?
throttled_rate = formula.livecheck.throttle
return if throttled_rate.blank?
formula_suffix = Version.new(new_version).patch.to_i
return if formula_suffix.modulo(throttled_rate).zero?
odie "#{formula} should only be updated every #{throttled_rate} releases on multiples of #{throttled_rate}"
end
sig { params(formula: Formula, new_formula_version: Version).returns(T.nilable(T::Array[String])) }
def alias_update_pair(formula, new_formula_version)
versioned_alias = formula.aliases.grep(/^.*@\d+(\.\d+)?$/).first
return if versioned_alias.nil?
name, old_alias_version = versioned_alias.split("@")
return if old_alias_version.blank?
new_alias_regex = (old_alias_version.split(".").length == 1) ? /^\d+/ : /^\d+\.\d+/
new_alias_version, = *new_formula_version.to_s.match(new_alias_regex)
return if new_alias_version.blank?
return if Version.new(new_alias_version) <= Version.new(old_alias_version)
[versioned_alias, "#{name}@#{new_alias_version}"]
end
sig {
params(formula: Formula, alias_rename: T.nilable(T::Array[String]),
skip_synced_versions: T::Boolean).returns(T::Boolean)
}
def run_audit(formula, alias_rename, skip_synced_versions: false)
audit_args = ["--formula"]
audit_args << "--strict" if args.strict?
audit_args << "--online" if args.online?
audit_args << "--except=synced_versions_formulae" if skip_synced_versions
if args.dry_run?
if args.no_audit?
ohai "Skipping `brew audit`"
elsif audit_args.present?
ohai "brew audit #{audit_args.join(" ")} #{formula.path.basename}"
else
ohai "brew audit #{formula.path.basename}"
end
return true
end
if alias_rename && (source = alias_rename.first) && (destination = alias_rename.last)
FileUtils.mv source, destination
end
failed_audit = false
if args.no_audit?
ohai "Skipping `brew audit`"
elsif audit_args.present?
system HOMEBREW_BREW_FILE, "audit", *audit_args, formula.full_name
failed_audit = !$CHILD_STATUS.success?
else
system HOMEBREW_BREW_FILE, "audit", formula.full_name
failed_audit = !$CHILD_STATUS.success?
end
failed_audit
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/dev-cmd/bump-revision.rb | Library/Homebrew/dev-cmd/bump-revision.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module DevCmd
class BumpRevision < AbstractCommand
cmd_args do
description <<~EOS
Create a commit to increment the revision of <formula>. If no revision is
present, "revision 1" will be added.
EOS
switch "-n", "--dry-run",
description: "Print what would be done rather than doing it."
switch "--remove-bottle-block",
description: "Remove the bottle block in addition to bumping the revision."
switch "--write-only",
description: "Make the expected file modifications without taking any Git actions."
flag "--message=",
description: "Append <message> to the default commit message."
conflicts "--dry-run", "--write-only"
named_args :formula, min: 1, without_api: true
end
sig { override.void }
def run
# As this command is simplifying user-run commands then let's just use a
# user path, too.
ENV["PATH"] = PATH.new(ORIGINAL_PATHS).to_s
Homebrew.install_bundler_gems!(groups: ["ast"]) unless args.dry_run?
args.named.to_formulae.each do |formula|
current_revision = formula.revision
new_revision = current_revision + 1
if args.dry_run?
unless args.quiet?
old_text = "revision #{current_revision}"
new_text = "revision #{new_revision}"
if current_revision.zero?
ohai "add #{new_text.inspect}"
else
ohai "replace #{old_text.inspect} with #{new_text.inspect}"
end
end
else
require "utils/ast"
formula_ast = Utils::AST::FormulaAST.new(formula.path.read)
if current_revision.zero?
formula_ast.add_stanza(:revision, new_revision)
else
formula_ast.replace_stanza(:revision, new_revision)
end
formula_ast.remove_stanza(:bottle) if args.remove_bottle_block?
formula.path.atomic_write(formula_ast.process)
end
message = "#{formula.name}: revision bump #{args.message}"
if args.dry_run?
ohai "git commit --no-edit --verbose --message=#{message} -- #{formula.path}"
elsif !args.write_only?
formula.path.parent.cd do
safe_system "git", "commit", "--no-edit", "--verbose",
"--message=#{message}", "--", formula.path
end
end
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/vendor-gems.rb | Library/Homebrew/dev-cmd/vendor-gems.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "utils/git"
require "fileutils"
require "utils/github"
module Homebrew
module DevCmd
class VendorGems < AbstractCommand
cmd_args do
description <<~EOS
Install and commit Homebrew's vendored gems.
EOS
comma_array "--update",
description: "Update the specified list of vendored gems to the latest version."
switch "--no-commit",
description: "Do not generate a new commit upon completion."
switch "--non-bundler-gems",
description: "Update vendored gems that aren't using Bundler.",
hidden: true
named_args :none
end
sig { override.void }
def run
Homebrew.setup_gem_environment!
ENV["BUNDLE_WITH"] = Homebrew.valid_gem_groups.join(":")
ohai "cd #{HOMEBREW_LIBRARY_PATH}"
HOMEBREW_LIBRARY_PATH.cd do
if args.update
ohai "bundle update"
run_bundle "update", *args.update
unless args.no_commit?
ohai "git add Gemfile.lock"
system "git", "add", "Gemfile.lock"
end
end
ohai "bundle install --standalone"
run_bundle "install", "--standalone"
if GitHub::Actions.env_set? && HOMEBREW_PREFIX.to_s == HOMEBREW_LINUX_DEFAULT_PREFIX
ohai "chmod +t -R /home/linuxbrew/"
system "sudo", "chmod", "+t", "-R", "/home/linuxbrew/"
end
ohai "bundle pristine"
run_bundle "pristine"
ohai "bundle clean"
run_bundle "clean"
# Workaround Bundler 2.4.21 issue where platforms may be removed.
# Although we don't use 2.4.21, Dependabot does as it currently ignores your lockfile version.
# https://github.com/rubygems/rubygems/issues/7169
run_bundle "lock", "--add-platform", "aarch64-linux"
system "git", "add", "Gemfile.lock" unless args.no_commit?
if args.non_bundler_gems?
%w[
mechanize
].each do |gem|
(HOMEBREW_LIBRARY_PATH/"vendor/gems").cd do
Pathname.glob("#{gem}-*/").each { |path| FileUtils.rm_r(path) }
end
ohai "gem install #{gem}"
safe_system "gem", "install", gem, "--install-dir", "vendor",
"--no-document", "--no-wrappers", "--ignore-dependencies", "--force"
(HOMEBREW_LIBRARY_PATH/"vendor/gems").cd do
source = Pathname.glob("#{gem}-*/").first
next if source.blank?
# We cannot use `#ln_sf` here because that has unintended consequences when
# the symlink we want to create exists and points to an existing directory.
FileUtils.rm_f gem
FileUtils.ln_s source, gem
end
end
end
unless args.no_commit?
ohai "git add vendor"
system "git", "add", "vendor"
Utils::Git.set_name_email!
Utils::Git.setup_gpg!
ohai "git commit"
system "git", "commit", "--message", "brew vendor-gems: commit updates."
end
end
end
sig { params(args: String).void }
def run_bundle(*args)
Process.wait(fork do
# Native build scripts fail if EUID != UID
Process::UID.change_privilege(Process.euid) if Process.euid != Process.uid
exec "bundle", *args
end)
raise ErrorDuringExecution.new(["bundle", *args], status: $CHILD_STATUS) unless $CHILD_STATUS.success?
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/dev-cmd/test-bot.rb | Library/Homebrew/dev-cmd/test-bot.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "test_bot"
module Homebrew
module Cmd
class TestBotCmd < AbstractCommand
cmd_args do
usage_banner <<~EOS
`test-bot` [<options>] [<formula>]
Tests the full lifecycle of a Homebrew change to a tap (Git repository). For example, for a GitHub Actions pull request that changes a formula `brew test-bot` will ensure the system is cleaned and set up to test the formula, install the formula, run various tests and checks on it, bottle (package) the binaries and test formulae that depend on it to ensure they aren't broken by these changes.
Only supports GitHub Actions as a CI provider. This is because Homebrew uses GitHub Actions and it's freely available for public and private use with macOS and Linux workers.
EOS
switch "--dry-run",
description: "Print what would be done rather than doing it."
switch "--cleanup",
description: "Clean all state from the Homebrew directory. Use with care!"
switch "--skip-setup",
description: "Don't check if the local system is set up correctly."
switch "--build-from-source",
description: "Build from source rather than building bottles."
switch "--build-dependents-from-source",
description: "Build dependents from source rather than testing bottles."
switch "--junit",
description: "generate a JUnit XML test results file."
switch "--keep-old",
description: "Run `brew bottle --keep-old` to build new bottles for a single platform."
switch "--skip-relocation",
description: "Run `brew bottle --skip-relocation` to build new bottles that don't require relocation."
switch "--only-json-tab",
description: "Run `brew bottle --only-json-tab` to build new bottles that do not contain a tab."
switch "--local",
description: "Ask Homebrew to write verbose logs under `./logs/` and set `$HOME` to `./home/`"
flag "--tap=",
description: "Use the Git repository of the given tap. Defaults to the core tap for syntax checking."
switch "--fail-fast",
description: "Immediately exit on a failing step."
switch "-v", "--verbose",
description: "Print test step output in real time. Has the side effect of " \
"passing output as raw bytes instead of re-encoding in UTF-8."
switch "--test-default-formula",
description: "Use a default testing formula when not building " \
"a tap and no other formulae are specified."
flag "--root-url=",
description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default."
flag "--git-name=",
description: "Set the Git author/committer names to the given name."
flag "--git-email=",
description: "Set the Git author/committer email to the given email."
switch "--publish",
description: "Publish the uploaded bottles."
switch "--skip-online-checks",
description: "Don't pass `--online` to `brew audit` and skip `brew livecheck`."
switch "--skip-new",
description: "Don't pass `--new` to `brew audit` for new formulae."
switch "--skip-new-strict",
depends_on: "--skip-new",
description: "Don't pass `--strict` to `brew audit` for new formulae."
switch "--skip-dependents",
description: "Don't test any dependents."
switch "--skip-livecheck",
description: "Don't test livecheck."
switch "--skip-recursive-dependents",
description: "Only test the direct dependents."
switch "--skip-checksum-only-audit",
description: "Don't audit checksum-only changes."
switch "--skip-stable-version-audit",
description: "Don't audit the stable version."
switch "--skip-revision-audit",
description: "Don't audit the revision."
switch "--only-cleanup-before",
description: "Only run the pre-cleanup step. Needs `--cleanup`, except in GitHub Actions."
switch "--only-setup",
description: "Only run the local system setup check step."
switch "--only-tap-syntax",
description: "Only run the tap syntax check step."
switch "--stable",
depends_on: "--only-tap-syntax",
description: "Only run the tap syntax checks needed on stable brew."
switch "--only-formulae",
description: "Only run the formulae steps."
switch "--only-formulae-detect",
description: "Only run the formulae detection steps."
switch "--only-formulae-dependents",
description: "Only run the formulae dependents steps."
switch "--only-bottles-fetch",
description: "Only run the bottles fetch steps. This optional post-upload test checks that all " \
"the bottles were uploaded correctly. It is not run unless requested and only needs " \
"to be run on a single machine. The bottle commit to be tested must be on the tested " \
"branch."
switch "--only-cleanup-after",
description: "Only run the post-cleanup step. Needs `--cleanup`, except in GitHub Actions."
comma_array "--testing-formulae=",
description: "Use these testing formulae rather than running the formulae detection steps."
comma_array "--added-formulae=",
description: "Use these added formulae rather than running the formulae detection steps."
comma_array "--deleted-formulae=",
description: "Use these deleted formulae rather than running the formulae detection steps."
comma_array "--skipped-or-failed-formulae=",
description: "Use these skipped or failed formulae from formulae steps for a " \
"formulae dependents step."
comma_array "--tested-formulae=",
description: "Use these tested formulae from formulae steps for a formulae dependents step."
conflicts "--only-formulae-detect", "--testing-formulae"
conflicts "--only-formulae-detect", "--added-formulae"
conflicts "--only-formulae-detect", "--deleted-formulae"
conflicts "--skip-dependents", "--only-formulae-dependents"
conflicts "--only-cleanup-before", "--only-setup", "--only-tap-syntax",
"--only-formulae", "--only-formulae-detect", "--only-formulae-dependents",
"--only-cleanup-after", "--skip-setup"
end
sig { override.void }
def run
if GitHub::Actions.env_set?
ENV["HOMEBREW_COLOR"] = "1"
ENV["HOMEBREW_GITHUB_ACTIONS"] = "1"
end
ENV["HOMEBREW_TEST_BOT"] = "1"
TestBot.run!(args)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/pr-publish.rb | Library/Homebrew/dev-cmd/pr-publish.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "tap"
require "utils/github"
module Homebrew
module DevCmd
class PrPublish < AbstractCommand
cmd_args do
description <<~EOS
Publish bottles for a pull request with GitHub Actions.
Requires write access to the repository.
EOS
switch "--autosquash",
description: "If supported on the target tap, automatically reformat and reword commits " \
"to our preferred format."
switch "--large-runner",
description: "Run the upload job on a large runner."
flag "--branch=",
description: "Branch to use the workflow from (default: `main`)."
flag "--message=",
depends_on: "--autosquash",
description: "Message to include when autosquashing revision bumps, deletions and rebuilds."
flag "--tap=",
description: "Target tap repository (default: `homebrew/core`)."
flag "--workflow=",
description: "Target workflow filename (default: `publish-commit-bottles.yml`)."
named_args :pull_request, min: 1
end
sig { override.void }
def run
tap = Tap.fetch(args.tap || CoreTap.instance.name)
workflow = args.workflow || "publish-commit-bottles.yml"
ref = args.branch || "main"
inputs = {
autosquash: args.autosquash?,
large_runner: args.large_runner?,
}
inputs[:message] = args.message if args.message.presence
args.named.uniq.each do |arg|
arg = "#{tap.default_remote}/pull/#{arg}" if arg.to_i.positive?
url_match = arg.match HOMEBREW_PULL_OR_COMMIT_URL_REGEX
_, user, repo, issue = *url_match
odie "Not a GitHub pull request: #{arg}" unless issue
inputs[:pull_request] = issue
pr_labels = GitHub.pull_request_labels(user, repo, issue)
if pr_labels.include?("autosquash")
oh1 "Found `autosquash` label on ##{issue}. Requesting autosquash."
inputs[:autosquash] = true
end
if pr_labels.include?("large-bottle-upload")
oh1 "Found `large-bottle-upload` label on ##{issue}. Requesting upload on large runner."
inputs[:large_runner] = true
end
if args.tap.present? && !T.must("#{user}/#{repo}".casecmp(tap.full_name)).zero?
odie "Pull request URL is for #{user}/#{repo} but `--tap=#{tap.full_name}` was specified!"
end
ohai "Dispatching #{tap} pull request ##{issue}"
GitHub.workflow_dispatch_event(user, repo, workflow, ref, **inputs)
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/dev-cmd/tests.rb | Library/Homebrew/dev-cmd/tests.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
require "hardware"
require "system_command"
module Homebrew
module DevCmd
class Tests < AbstractCommand
include SystemCommand::Mixin
cmd_args do
description <<~EOS
Run Homebrew's unit and integration tests.
EOS
switch "--coverage",
description: "Generate code coverage reports."
switch "--generic",
description: "Run only OS-agnostic tests."
switch "--online",
description: "Include tests that use the GitHub API and tests that use any of the taps for " \
"official external commands."
switch "--debug",
description: "Enable debugging using `ruby/debug`, or surface the standard `odebug` output."
switch "--changed",
description: "Only runs tests on files that were changed from the `main` branch."
switch "--fail-fast",
description: "Exit early on the first failing test."
switch "--no-parallel",
description: "Run tests serially."
switch "--stackprof",
description: "Use `stackprof` to profile tests."
switch "--vernier",
description: "Use `vernier` to profile tests."
switch "--ruby-prof",
description: "Use `ruby-prof` to profile tests."
flag "--only=",
description: "Run only `<test_script>_spec.rb`. Appending `:<line_number>` will start at a " \
"specific line."
flag "--profile=",
description: "Output the <n> slowest tests. When run without `--no-parallel` this will output " \
"the slowest tests for each parallel test process."
flag "--seed=",
description: "Randomise tests with the specified <value> instead of a random seed."
conflicts "--changed", "--only"
conflicts "--stackprof", "--vernier", "--ruby-prof"
named_args :none
end
sig { override.void }
def run
# Given we might be testing various commands, we probably want everything (except sorbet-static)
groups = Homebrew.valid_gem_groups - ["sorbet"]
groups << "prof" if args.stackprof? || args.vernier? || args.ruby_prof?
Homebrew.install_bundler_gems!(groups:)
HOMEBREW_LIBRARY_PATH.cd do
setup_environment!
# Needs required here, after `setup_environment!`, so that
# `HOMEBREW_TEST_GENERIC_OS` is set and `OS.linux?` and `OS.mac?` both
# `return false`.
require "extend/os/dev-cmd/tests"
parallel = !args.no_parallel?
only = args.only
files = if only
only.split(",").flat_map do |test|
test_name, line = test.split(":", 2)
tests = if line.present?
parallel = false
["test/#{test_name}_spec.rb:#{line}"]
else
Dir.glob("test/{#{test_name},#{test_name}/**/*}_spec.rb")
end
raise UsageError, "Invalid `--only` argument: #{test}" if tests.blank?
tests
end
elsif args.changed?
changed_test_files
else
Dir.glob("test/**/*_spec.rb")
end
if files.blank?
raise UsageError, "The `--only` argument requires a valid file or folder name!" if only
if args.changed?
opoo "No tests are directly associated with the changed files!"
return
end
end
# We use `ParallelTests.last_process?` in `test/spec_helper.rb` to
# handle SimpleCov output but, due to how the method is implemented,
# it doesn't work as expected if the number of processes is greater
# than one but lower than the number of CPU cores in the execution
# environment. Coverage information isn't saved in that scenario,
# so we disable parallel testing as a workaround in this case.
parallel = false if args.coverage? && files.length < Hardware::CPU.cores
parallel_rspec_log_name = "parallel_runtime_rspec"
parallel_rspec_log_name = "#{parallel_rspec_log_name}.generic" if args.generic?
parallel_rspec_log_name = "#{parallel_rspec_log_name}.online" if args.online?
parallel_rspec_log_name = "#{parallel_rspec_log_name}.log"
parallel_rspec_log_path = if ENV["CI"]
"tests/#{parallel_rspec_log_name}"
else
"#{HOMEBREW_CACHE}/#{parallel_rspec_log_name}"
end
ENV["PARALLEL_RSPEC_LOG_PATH"] = parallel_rspec_log_path
parallel_args = if ENV["CI"]
%W[
--combine-stderr
--serialize-stdout
--runtime-log #{parallel_rspec_log_path}
]
else
%w[
--nice
]
end
# Generate seed ourselves and output later to avoid multiple different
# seeds being output when running parallel tests.
seed = args.seed || rand(0xFFFF).to_i
bundle_args = ["-I", (HOMEBREW_LIBRARY_PATH/"test").to_s]
bundle_args += %W[
--seed #{seed}
--color
--require spec_helper
]
bundle_args << "--fail-fast" if args.fail_fast?
bundle_args << "--profile" << args.profile if args.profile
bundle_args << "--tag" << "~needs_arm" unless Hardware::CPU.arm?
bundle_args << "--tag" << "~needs_intel" unless Hardware::CPU.intel?
bundle_args << "--tag" << "~needs_network" unless args.online?
bundle_args << "--tag" << "~needs_ci" unless ENV["CI"]
bundle_args = os_bundle_args(bundle_args)
files = os_files(files)
puts "Randomized with seed #{seed}"
ENV["HOMEBREW_DEBUG"] = "1" if args.debug? # Used in spec_helper.rb to require the "debug" gem.
# Workaround for:
#
# ```
# ruby: no -r allowed while running setuid (SecurityError)
# ```
Process::UID.change_privilege(Process.euid) if Process.euid != Process.uid
test_prof = "#{HOMEBREW_LIBRARY_PATH}/tmp/test_prof"
if args.stackprof?
ENV["TEST_STACK_PROF"] = "1"
prof_input_filename = "#{test_prof}/stack-prof-report-wall-raw-total.dump"
prof_filename = "#{test_prof}/stack-prof-report-wall-raw-total.html"
elsif args.vernier?
ENV["TEST_VERNIER"] = "1"
elsif args.ruby_prof?
ENV["TEST_RUBY_PROF"] = "call_stack"
prof_filename = "#{test_prof}/ruby-prof-report-call_stack-wall-total.html"
end
if parallel
system "bundle", "exec", "parallel_rspec", *parallel_args, "--", *bundle_args, "--", *files
else
system "bundle", "exec", "rspec", *bundle_args, "--", *files
end
success = $CHILD_STATUS.success?
safe_system "stackprof --d3-flamegraph #{prof_input_filename} > #{prof_filename}" if args.stackprof?
exec_browser prof_filename if prof_filename
return if success
Homebrew.failed = true
end
end
private
sig { params(bundle_args: T::Array[String]).returns(T::Array[String]) }
def os_bundle_args(bundle_args)
# for generic tests, remove macOS or Linux specific tests
non_linux_bundle_args(non_macos_bundle_args(bundle_args))
end
sig { params(bundle_args: T::Array[String]).returns(T::Array[String]) }
def non_macos_bundle_args(bundle_args)
bundle_args << "--tag" << "~needs_homebrew_core" if ENV["CI"]
bundle_args << "--tag" << "~needs_svn" unless args.online?
bundle_args << "--tag" << "~needs_macos" << "--tag" << "~cask"
end
sig { params(bundle_args: T::Array[String]).returns(T::Array[String]) }
def non_linux_bundle_args(bundle_args)
bundle_args << "--tag" << "~needs_linux" << "--tag" << "~needs_systemd"
end
sig { params(files: T::Array[String]).returns(T::Array[String]) }
def os_files(files)
# for generic tests, remove macOS or Linux specific files
non_linux_files(non_macos_files(files))
end
sig { params(files: T::Array[String]).returns(T::Array[String]) }
def non_macos_files(files)
files.grep_v(%r{^test/(os/mac|cask)(/.*|_spec\.rb)$})
end
sig { params(files: T::Array[String]).returns(T::Array[String]) }
def non_linux_files(files)
files.grep_v(%r{^test/os/linux(/.*|_spec\.rb)$})
end
sig { returns(T::Array[String]) }
def changed_test_files
changed_files = Utils.popen_read("git", "diff", "--name-only", "main")
raise UsageError, "No files have been changed from the `main` branch!" if changed_files.blank?
filestub_regex = %r{Library/Homebrew/([\w/-]+).rb}
changed_files.scan(filestub_regex).map(&:last).filter_map do |filestub|
if filestub.start_with?("test/")
# Only run tests on *_spec.rb files in test/ folder
filestub.end_with?("_spec") ? Pathname("#{filestub}.rb") : nil
else
# For all other changed .rb files guess the associated test file name
Pathname("test/#{filestub}_spec.rb")
end
end.select(&:exist?)
end
sig { returns(T::Array[String]) }
def setup_environment!
# Cleanup any unwanted user configuration.
allowed_test_env = %w[
HOMEBREW_GITHUB_API_TOKEN
HOMEBREW_CACHE
HOMEBREW_LOGS
HOMEBREW_TEMP
]
allowed_test_env << "HOMEBREW_USE_RUBY_FROM_PATH" if Homebrew::EnvConfig.developer?
Homebrew::EnvConfig::ENVS.keys.map(&:to_s).each do |env|
next if allowed_test_env.include?(env)
ENV.delete(env)
end
# Fetch JSON API files if needed.
require "api"
Homebrew::API.fetch_api_files!
# Codespaces HOMEBREW_PREFIX and /tmp are mounted 755 which makes Ruby warn constantly.
if (ENV["HOMEBREW_CODESPACES"] == "true") && (HOMEBREW_TEMP.to_s == "/tmp")
# Need to keep this fairly short to avoid socket paths being too long in tests.
homebrew_prefix_tmp = "/home/linuxbrew/tmp"
ENV["HOMEBREW_TEMP"] = homebrew_prefix_tmp
FileUtils.mkdir_p homebrew_prefix_tmp
system "chmod", "-R", "g-w,o-w", HOMEBREW_PREFIX, homebrew_prefix_tmp
end
ENV["HOMEBREW_TESTS"] = "1"
ENV["HOMEBREW_NO_AUTO_UPDATE"] = "1"
ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"] = "1"
ENV["HOMEBREW_TEST_GENERIC_OS"] = "1" if args.generic?
ENV["HOMEBREW_TEST_ONLINE"] = "1" if args.online?
ENV["HOMEBREW_SORBET_RUNTIME"] = "1"
ENV["HOMEBREW_SORBET_RECURSIVE"] = "1"
ENV["USER"] ||= system_command!("id", args: ["-nu"]).stdout.chomp
# Avoid local configuration messing with tests, e.g. git being configured
# to use GPG to sign by default
ENV["HOME"] = "#{HOMEBREW_LIBRARY_PATH}/test"
# Print verbose output when requesting debug or verbose output.
ENV["HOMEBREW_VERBOSE_TESTS"] = "1" if args.debug? || args.verbose?
if args.coverage?
ENV["HOMEBREW_TESTS_COVERAGE"] = "1"
FileUtils.rm_f "test/coverage/.resultset.json"
end
# Override author/committer as global settings might be invalid and thus
# will cause silent failure during the setup of dummy Git repositories.
%w[AUTHOR COMMITTER].each do |role|
ENV["GIT_#{role}_NAME"] = "brew tests"
ENV["GIT_#{role}_EMAIL"] = "brew-tests@localhost"
ENV["GIT_#{role}_DATE"] = "Sun Jan 22 19:59:13 2017 +0000"
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/dev-cmd/ruby.rb | Library/Homebrew/dev-cmd/ruby.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
module Homebrew
module DevCmd
class Ruby < AbstractCommand
cmd_args do
usage_banner "`ruby` [<options>] (`-e` <text>|<file>)"
description <<~EOS
Run a Ruby instance with Homebrew's libraries loaded. For example,
`brew ruby -e "puts :gcc.f.deps"` or `brew ruby script.rb`.
Run e.g. `brew ruby -- --version` to pass arbitrary arguments to `ruby`.
EOS
flag "-r=",
description: "Load a library using `require`."
flag "-e=",
description: "Execute the given text string as a script."
named_args :file
end
sig { override.void }
def run
ruby_sys_args = []
ruby_sys_args << "-r#{args.r}" if args.r
ruby_sys_args << "-e #{args.e}" if args.e
ruby_sys_args += args.named
exec(*HOMEBREW_RUBY_EXEC_ARGS,
"-I", $LOAD_PATH.join(File::PATH_SEPARATOR),
"-rglobal", "-rdev-cmd/irb",
*ruby_sys_args)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/sh.rb | Library/Homebrew/dev-cmd/sh.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "extend/ENV"
require "formula"
require "utils/gems"
require "utils/shell"
module Homebrew
module DevCmd
class Sh < AbstractCommand
cmd_args do
description <<~EOS
Enter an interactive shell for Homebrew's build environment. Use years-battle-hardened
build logic to help your `./configure && make && make install`
and even your `gem install` succeed. Especially handy if you run Homebrew
in an Xcode-only configuration since it adds tools like `make` to your `$PATH`
which build systems would not find otherwise.
With `--ruby`, enter an interactive shell for Homebrew's Ruby environment.
This sets up the correct Ruby paths, `$GEM_HOME` and bundle
configuration used by Homebrew's development tools.
The environment includes gems from the installed groups,
making tools like RuboCop, Sorbet and RSpec available via `bundle exec`.
EOS
switch "-r", "--ruby",
description: "Set up Homebrew's Ruby environment."
flag "--env=",
description: "Use the standard `$PATH` instead of superenv's when `std` is passed."
flag "-c=", "--cmd=",
description: "Execute commands in a non-interactive shell."
conflicts "--ruby", "--env="
named_args :file, max: 1
end
sig { override.void }
def run
prompt, notice = if args.ruby?
setup_ruby_environment!
else
setup_build_environment!
end
preferred_path = Utils::Shell.preferred_path(default: "/bin/bash")
if args.cmd.present?
safe_system(preferred_path, "-c", args.cmd)
elsif args.named.present?
safe_system(preferred_path, args.named.first)
else
system Utils::Shell.shell_with_prompt(prompt, preferred_path:, notice:)
end
end
private
sig { returns([String, T.nilable(String)]) }
def setup_ruby_environment!
Homebrew.install_bundler_gems!(setup_path: true)
notice = unless Homebrew::EnvConfig.no_env_hints?
<<~EOS
Your shell has been configured to use Homebrew's Ruby environment.
This includes the correct Ruby version, GEM_HOME, and bundle configuration.
Tools like RuboCop, Sorbet, and RSpec are available via `bundle exec`.
Hide these hints with `HOMEBREW_NO_ENV_HINTS=1` (see `man brew`).
When done, type `exit`.
EOS
end
["brew ruby", notice]
end
sig { returns([String, T.nilable(String)]) }
def setup_build_environment!
ENV.activate_extensions!(env: args.env)
if superenv?(args.env)
ENV.deps = Formula.installed.select do |f|
f.keg_only? && f.opt_prefix.directory?
end
end
ENV.setup_build_environment
if superenv?(args.env)
# superenv stopped adding brew's bin but generally users will want it
ENV["PATH"] = PATH.new(ENV.fetch("PATH")).insert(1, HOMEBREW_PREFIX/"bin").to_s
end
ENV["VERBOSE"] = "1" if args.verbose?
notice = unless Homebrew::EnvConfig.no_env_hints?
<<~EOS
Your shell has been configured to use Homebrew's build environment;
this should help you build stuff. Notably though, the system versions of
gem and pip will ignore our configuration and insist on using the
environment they were built under (mostly). Sadly, scons will also
ignore our configuration.
Hide these hints with `HOMEBREW_NO_ENV_HINTS=1` (see `man brew`).
When done, type `exit`.
EOS
end
["brew", notice]
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/dev-cmd/linkage.rb | Library/Homebrew/dev-cmd/linkage.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "cache_store"
require "linkage_checker"
module Homebrew
module DevCmd
class Linkage < AbstractCommand
cmd_args do
description <<~EOS
Check the library links from the given <formula> kegs. If no <formula> are
provided, check all kegs. Raises an error if run on uninstalled formulae.
EOS
switch "--test",
description: "Show only missing libraries and exit with a non-zero status if any missing " \
"libraries are found."
switch "--strict",
depends_on: "--test",
description: "Exit with a non-zero status if any undeclared dependencies with linkage are found."
switch "--reverse",
description: "For every library that a keg references, print its dylib path followed by the " \
"binaries that link to it."
switch "--cached",
description: "Print the cached linkage values stored in `$HOMEBREW_CACHE`, set by a previous " \
"`brew linkage` run."
named_args :installed_formula
end
sig { override.void }
def run
CacheStoreDatabase.use(:linkage) do |db|
kegs = if args.named.to_default_kegs.empty?
Formula.installed.filter_map(&:any_installed_keg)
else
args.named.to_default_kegs
end
kegs.each do |keg|
ohai "Checking #{keg.name} linkage" if kegs.size > 1
result = LinkageChecker.new(keg, cache_db: db)
if args.test?
result.display_test_output(strict: args.strict?)
Homebrew.failed = true if result.broken_library_linkage?(test: true, strict: args.strict?)
elsif args.reverse?
result.display_reverse_output
else
result.display_normal_output
end
end
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/style.rb | Library/Homebrew/dev-cmd/style.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "json"
require "open3"
require "style"
module Homebrew
module DevCmd
class StyleCmd < AbstractCommand
cmd_args do
description <<~EOS
Check formulae or files for conformance to Homebrew style guidelines.
Lists of <file>, <tap> and <formula> may not be combined. If none are
provided, `style` will run style checks on the whole Homebrew library,
including core code and all formulae.
EOS
switch "--fix",
description: "Fix style violations automatically using RuboCop's auto-correct feature."
switch "--display-cop-names",
description: "Include the RuboCop cop name for each violation in the output.",
hidden: true
switch "--reset-cache",
description: "Reset the RuboCop cache."
switch "--changed",
description: "Check files that were changed from the `main` branch."
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
comma_array "--only-cops",
description: "Specify a comma-separated <cops> list to check for violations of only the " \
"listed RuboCop cops."
comma_array "--except-cops",
description: "Specify a comma-separated <cops> list to skip checking for violations of the " \
"listed RuboCop cops."
conflicts "--formula", "--cask"
conflicts "--only-cops", "--except-cops"
named_args [:file, :tap, :formula, :cask], without_api: true
end
sig { override.void }
def run
Homebrew.install_bundler_gems!(groups: ["style"])
if args.changed? && !args.no_named?
raise UsageError, "`--changed` and named arguments are mutually exclusive!"
end
target = if args.changed?
changed_ruby_or_shell_files
elsif args.no_named?
nil
else
args.named.to_paths
end
if target.blank? && args.changed?
opoo "No style checks are available for the changed files!"
return
end
only_cops = args.only_cops
except_cops = args.except_cops
options = {
fix: args.fix?,
reset_cache: args.reset_cache?,
debug: args.debug?,
verbose: args.verbose?,
}
if only_cops
options[:only_cops] = only_cops
elsif except_cops
options[:except_cops] = except_cops
else
options[:except_cops] = %w[FormulaAuditStrict]
end
Homebrew.failed = !Style.check_style_and_print(target, **options)
end
sig { returns(T::Array[Pathname]) }
def changed_ruby_or_shell_files
repo = Utils.popen_read("git", "rev-parse", "--show-toplevel").chomp
odie "`brew style --changed` must be run inside a git repository!" unless $CHILD_STATUS.success?
changed_files = Utils.popen_read("git", "diff", "--name-only", "--no-relative", "main")
changed_files.split("\n").filter_map do |file|
next if !file.end_with?(".rb", ".sh", ".yml", ".rbi") && file != "bin/brew"
Pathname(file).expand_path(repo)
end.select(&:exist?)
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/dev-cmd/determine-test-runners.rb | Library/Homebrew/dev-cmd/determine-test-runners.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "test_runner_formula"
require "github_runner_matrix"
module Homebrew
module DevCmd
class DetermineTestRunners < AbstractCommand
cmd_args do
usage_banner <<~EOS
`determine-test-runners` {<testing-formulae> [<deleted-formulae>]|--all-supported}
Determines the runners used to test formulae or their dependents. For internal use in Homebrew taps.
EOS
switch "--all-supported",
description: "Instead of selecting runners based on the chosen formula, return all supported runners."
switch "--eval-all",
description: "Evaluate all available formulae, whether installed or not, to determine testing " \
"dependents.",
env: :eval_all
switch "--dependents",
description: "Determine runners for testing dependents. " \
"Requires `--eval-all` or `HOMEBREW_EVAL_ALL=1` to be set.",
depends_on: "--eval-all"
named_args max: 2
conflicts "--all-supported", "--dependents"
hide_from_man_page!
end
sig { override.void }
def run
if args.no_named? && !args.all_supported?
raise Homebrew::CLI::MinNamedArgumentsError, 1
elsif args.all_supported? && !args.no_named?
raise UsageError, "`--all-supported` is mutually exclusive to other arguments."
end
testing_formulae = args.named.first&.split(",").to_a.map do |name|
TestRunnerFormula.new(Formulary.factory(name), eval_all: args.eval_all?)
end.freeze
deleted_formulae = args.named.second&.split(",").to_a.freeze
runner_matrix = GitHubRunnerMatrix.new(testing_formulae, deleted_formulae,
all_supported: args.all_supported?,
dependent_matrix: args.dependents?)
runners = runner_matrix.active_runner_specs_hash
ohai "Runners", JSON.pretty_generate(runners)
# gracefully handle non-GitHub Actions environments
github_output = if ENV.key?("GITHUB_ACTIONS")
ENV.fetch("GITHUB_OUTPUT")
else
ENV.fetch("GITHUB_OUTPUT", nil)
end
return unless github_output
File.open(github_output, "a") do |f|
f.puts("runners=#{runners.to_json}")
f.puts("runners_present=#{runners.present?}")
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/dev-cmd/cat.rb | Library/Homebrew/dev-cmd/cat.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "fileutils"
module Homebrew
module DevCmd
class Cat < AbstractCommand
include FileUtils
cmd_args do
description <<~EOS
Display the source of a <formula> or <cask>.
EOS
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
conflicts "--formula", "--cask"
named_args [:formula, :cask], min: 1, without_api: true
end
sig { override.void }
def run
cd HOMEBREW_REPOSITORY do
pager = if Homebrew::EnvConfig.bat?
ENV["BAT_CONFIG_PATH"] = Homebrew::EnvConfig.bat_config_path
ENV["BAT_THEME"] = Homebrew::EnvConfig.bat_theme
require "formula"
Formula["bat"].ensure_installed!(
reason: "displaying <formula>/<cask> source",
# The user might want to capture the output of `brew cat ...`
# Redirect stdout to stderr
output_to_stderr: true,
).opt_bin/"bat"
else
"cat"
end
args.named.to_paths.each do |path|
next path if path.exist?
path = path.basename(".rb") if args.cask?
ofail "#{path}'s source doesn't exist on disk."
end
if Homebrew.failed?
$stderr.puts "The name may be wrong, or the tap hasn't been tapped. Instead try:"
treat_as = "--cask " if args.cask?
treat_as = "--formula " if args.formula?
$stderr.puts " brew info --github #{treat_as}#{args.named.join(" ")}"
return
end
safe_system pager, *args.named.to_paths
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/dev-cmd/edit.rb | Library/Homebrew/dev-cmd/edit.rb | # typed: strict
# frozen_string_literal: true
require "abstract_command"
require "formula"
module Homebrew
module DevCmd
class Edit < AbstractCommand
cmd_args do
description <<~EOS
Open a <formula>, <cask> or <tap> in the editor set by `$EDITOR` or `$HOMEBREW_EDITOR`,
or open the Homebrew repository for editing if no argument is provided.
EOS
switch "--formula", "--formulae",
description: "Treat all named arguments as formulae."
switch "--cask", "--casks",
description: "Treat all named arguments as casks."
switch "--print-path",
description: "Print the file path to be edited, without opening an editor."
conflicts "--formula", "--cask"
named_args [:formula, :cask, :tap], without_api: true
end
sig { override.void }
def run
ENV["COLORTERM"] = ENV.fetch("HOMEBREW_COLORTERM", nil)
# Recover $TMPDIR for emacsclient
ENV["TMPDIR"] = ENV.fetch("HOMEBREW_TMPDIR", nil)
# VS Code remote development relies on this env var to work
if which_editor(silent: true) == "code" && ENV.include?("HOMEBREW_VSCODE_IPC_HOOK_CLI")
ENV["VSCODE_IPC_HOOK_CLI"] = ENV.fetch("HOMEBREW_VSCODE_IPC_HOOK_CLI", nil)
end
unless (HOMEBREW_REPOSITORY/".git").directory?
odie <<~EOS
Changes will be lost!
The first time you `brew update`, all local changes will be lost; you should
thus `brew update` before you `brew edit`!
EOS
end
paths = if args.named.empty?
# Sublime requires opting into the project editing path,
# as opposed to VS Code which will infer from the .vscode path
if which_editor(silent: true) == "subl"
["--project", HOMEBREW_REPOSITORY/".sublime/homebrew.sublime-project"]
else
# If no formulae are listed, open the project root in an editor.
[HOMEBREW_REPOSITORY]
end
else
expanded_paths = args.named.to_paths
expanded_paths.each do |path|
raise_with_message!(path, args.cask?) unless path.exist?
end
expanded_paths
end
if args.print_path?
paths.each { puts it }
return
end
exec_editor(*paths)
is_formula = T.let(false, T::Boolean)
if !Homebrew::EnvConfig.no_env_hints? && paths.any? do |path|
next if path == "--project"
is_formula = core_formula_path?(path)
is_formula || core_cask_path?(path) || core_formula_tap?(path) || core_cask_tap?(path)
end
from_source = " --build-from-source" if is_formula
no_api = "HOMEBREW_NO_INSTALL_FROM_API=1 " unless Homebrew::EnvConfig.no_install_from_api?
puts <<~EOS
To test your local edits, run:
#{no_api}brew install#{from_source} --verbose --debug #{args.named.join(" ")}
EOS
end
end
private
sig { params(path: Pathname).returns(T::Boolean) }
def core_formula_path?(path)
path.fnmatch?("**/homebrew-core/Formula/**.rb", File::FNM_DOTMATCH)
end
sig { params(path: Pathname).returns(T::Boolean) }
def core_cask_path?(path)
path.fnmatch?("**/homebrew-cask/Casks/**.rb", File::FNM_DOTMATCH)
end
sig { params(path: Pathname).returns(T::Boolean) }
def core_formula_tap?(path)
path == CoreTap.instance.path
end
sig { params(path: Pathname).returns(T::Boolean) }
def core_cask_tap?(path)
path == CoreCaskTap.instance.path
end
sig { params(path: Pathname, cask: T::Boolean).returns(T.noreturn) }
def raise_with_message!(path, cask)
name = path.basename(".rb").to_s
if (tap_match = Regexp.new("#{HOMEBREW_TAP_DIR_REGEX.source}$").match(path.to_s))
raise TapUnavailableError, CoreTap.instance.name if core_formula_tap?(path)
raise TapUnavailableError, CoreCaskTap.instance.name if core_cask_tap?(path)
raise TapUnavailableError, "#{tap_match[:user]}/#{tap_match[:repo]}"
elsif cask || core_cask_path?(path)
if !CoreCaskTap.instance.installed? && Homebrew::API.cask_tokens.include?(name)
command = "brew tap --force #{CoreCaskTap.instance.name}"
action = "tap #{CoreCaskTap.instance.name}"
else
command = "brew create --cask --set-name #{name} $URL"
action = "create a new cask"
end
elsif core_formula_path?(path) &&
!CoreTap.instance.installed? &&
Homebrew::API.formula_names.include?(name)
command = "brew tap --force #{CoreTap.instance.name}"
action = "tap #{CoreTap.instance.name}"
else
command = "brew create --set-name #{name} $URL"
action = "create a new formula"
end
raise UsageError, <<~EOS
#{name} doesn't exist on disk.
Run #{Formatter.identifier(command)} to #{action}!
EOS
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/debrew/irb.rb | Library/Homebrew/debrew/irb.rb | # typed: strict
# frozen_string_literal: true
require "irb"
module IRB
sig { params(binding: Binding).void }
def self.start_within(binding)
old_stdout_sync = $stdout.sync
$stdout.sync = true
@setup_done ||= T.let(false, T.nilable(T::Boolean))
unless @setup_done
setup(nil, argv: [])
@setup_done = true
end
workspace = WorkSpace.new(binding)
irb = Irb.new(workspace)
irb.run(conf)
ensure
$stdout.sync = old_stdout_sync
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/download.rb | Library/Homebrew/cask/download.rb | # typed: strict
# frozen_string_literal: true
require "downloadable"
require "fileutils"
require "cask/cache"
require "cask/quarantine"
module Cask
# A download corresponding to a {Cask}.
class Download
include Downloadable
include Context
sig { returns(::Cask::Cask) }
attr_reader :cask
sig { params(cask: ::Cask::Cask, quarantine: T.nilable(T::Boolean)).void }
def initialize(cask, quarantine: nil)
super()
@cask = cask
@quarantine = quarantine
end
sig { override.returns(T.nilable(::URL)) }
def url
return if (cask_url = cask.url).nil?
@url ||= ::URL.new(cask_url.to_s, cask_url.specs)
end
sig { override.returns(T.nilable(::Checksum)) }
def checksum
@checksum ||= cask.sha256 if cask.sha256 != :no_check
end
sig { override.returns(T.nilable(Version)) }
def version
return if cask.version.nil?
@version ||= Version.new(cask.version)
end
sig {
override
.params(quiet: T.nilable(T::Boolean),
verify_download_integrity: T::Boolean,
timeout: T.nilable(T.any(Integer, Float)))
.returns(Pathname)
}
def fetch(quiet: nil, verify_download_integrity: true, timeout: nil)
downloader.quiet! if quiet
begin
super(verify_download_integrity: false, timeout:)
rescue DownloadError => e
error = CaskError.new("Download failed on Cask '#{cask}' with message: #{e.cause}")
error.set_backtrace e.backtrace
raise error
end
downloaded_path = cached_download
quarantine(downloaded_path)
self.verify_download_integrity(downloaded_path) if verify_download_integrity
downloaded_path
end
sig { params(timeout: T.nilable(T.any(Float, Integer))).returns([T.nilable(Time), Integer]) }
def time_file_size(timeout: nil)
raise ArgumentError, "not supported for this download strategy" unless downloader.is_a?(CurlDownloadStrategy)
T.cast(downloader, CurlDownloadStrategy).resolved_time_file_size(timeout:)
end
sig { returns(Pathname) }
def basename
downloader.basename
end
sig { override.params(filename: Pathname).void }
def verify_download_integrity(filename)
if no_checksum_defined? && !official_cask_tap?
opoo "No checksum defined for cask '#{@cask}', skipping verification."
return
end
super
end
sig { override.returns(String) }
def download_queue_name = "#{cask.token} (#{version})"
sig { override.returns(String) }
def download_queue_type = "Cask"
private
sig { params(path: Pathname).void }
def quarantine(path)
return if @quarantine.nil?
return unless Quarantine.available?
if @quarantine
Quarantine.cask!(cask: @cask, download_path: path)
else
Quarantine.release!(download_path: path)
end
end
sig { returns(T::Boolean) }
def official_cask_tap?
tap = @cask.tap
return false if tap.blank?
tap.official?
end
sig { returns(T::Boolean) }
def no_checksum_defined?
@cask.sha256 == :no_check
end
sig { override.returns(T::Boolean) }
def silence_checksum_missing_error?
no_checksum_defined? && official_cask_tap?
end
sig { override.returns(T.nilable(::URL)) }
def determine_url
url
end
sig { override.returns(Pathname) }
def cache
Cache.path
end
sig { override.returns(String) }
def download_name
url_basename = super
version = self.version
url = self.url
return url_basename if version.nil? || url.nil?
temp_downloader = download_strategy.new(url.to_s, url_basename, version, mirrors: [], cache:, **url.specs)
return url_basename unless temp_downloader.is_a?(AbstractFileDownloadStrategy)
potential_symlink_length = temp_downloader.symlink_location.basename.to_s.length
max_filesystem_symlink_length = 255
return url_basename if potential_symlink_length < max_filesystem_symlink_length
cask.full_token.gsub("/", "--")
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/cask/exceptions.rb | Library/Homebrew/cask/exceptions.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
module Cask
# General cask error.
class CaskError < RuntimeError; end
# Cask error containing multiple other errors.
class MultipleCaskErrors < CaskError
def initialize(errors)
super()
@errors = errors
end
sig { returns(String) }
def to_s
<<~EOS
Problems with multiple casks:
#{@errors.map(&:to_s).join("\n")}
EOS
end
end
# Abstract cask error containing a cask token.
class AbstractCaskErrorWithToken < CaskError
sig { returns(String) }
attr_reader :token
sig { returns(String) }
attr_reader :reason
def initialize(token, reason = nil)
super()
@token = token.to_s
@reason = reason.to_s
end
end
# Error when a cask is not installed.
class CaskNotInstalledError < AbstractCaskErrorWithToken
sig { returns(String) }
def to_s
"Cask '#{token}' is not installed."
end
end
# Error when a cask cannot be installed.
class CaskCannotBeInstalledError < AbstractCaskErrorWithToken
attr_reader :message
def initialize(token, message)
super(token)
@message = message
end
sig { returns(String) }
def to_s
"Cask '#{token}' has been #{message}"
end
end
# Error when a cask conflicts with another cask.
class CaskConflictError < AbstractCaskErrorWithToken
attr_reader :conflicting_cask
def initialize(token, conflicting_cask)
super(token)
@conflicting_cask = conflicting_cask
end
sig { returns(String) }
def to_s
"Cask '#{token}' conflicts with '#{conflicting_cask}'."
end
end
# Error when a cask is not available.
class CaskUnavailableError < AbstractCaskErrorWithToken
sig { returns(String) }
def to_s
"Cask '#{token}' is unavailable#{reason.empty? ? "." : ": #{reason}"}"
end
end
# Error when a cask is unreadable.
class CaskUnreadableError < CaskUnavailableError
sig { returns(String) }
def to_s
"Cask '#{token}' is unreadable#{reason.empty? ? "." : ": #{reason}"}"
end
end
# Error when a cask in a specific tap is not available.
class TapCaskUnavailableError < CaskUnavailableError
attr_reader :tap
def initialize(tap, token)
super("#{tap}/#{token}")
@tap = tap
end
sig { returns(String) }
def to_s
s = super
s += "\nPlease tap it and then try again: brew tap #{tap}" unless tap.installed?
s
end
end
# Error when a cask with the same name is found in multiple taps.
class TapCaskAmbiguityError < CaskError
sig { returns(String) }
attr_reader :token
sig { returns(T::Array[CaskLoader::FromNameLoader]) }
attr_reader :loaders
sig { params(token: String, loaders: T::Array[CaskLoader::FromNameLoader]).void }
def initialize(token, loaders)
@loaders = loaders
taps = loaders.map(&:tap)
casks = taps.map { |tap| "#{tap}/#{token}" }
cask_list = casks.sort.map { |f| "\n * #{f}" }.join
super <<~EOS
Cask #{token} exists in multiple taps:#{cask_list}
Please use the fully-qualified name (e.g. #{casks.first}) to refer to a specific Cask.
EOS
end
end
# Error when a cask already exists.
class CaskAlreadyCreatedError < AbstractCaskErrorWithToken
sig { returns(String) }
def to_s
%Q(Cask '#{token}' already exists. Run #{Formatter.identifier("brew edit --cask #{token}")} to edit it.)
end
end
# Error when there is a cyclic cask dependency.
class CaskCyclicDependencyError < AbstractCaskErrorWithToken
sig { returns(String) }
def to_s
"Cask '#{token}' includes cyclic dependencies on other Casks#{reason.empty? ? "." : ": #{reason}"}"
end
end
# Error when a cask depends on itself.
class CaskSelfReferencingDependencyError < CaskCyclicDependencyError
sig { returns(String) }
def to_s
"Cask '#{token}' depends on itself."
end
end
# Error when no cask is specified.
class CaskUnspecifiedError < CaskError
sig { returns(String) }
def to_s
"This command requires a Cask token."
end
end
# Error when a cask is invalid.
class CaskInvalidError < AbstractCaskErrorWithToken
sig { returns(String) }
def to_s
"Cask '#{token}' definition is invalid#{reason.empty? ? "." : ": #{reason}"}"
end
end
# Error when a cask token does not match the file name.
class CaskTokenMismatchError < CaskInvalidError
def initialize(token, header_token)
super(token, "Token '#{header_token}' in header line does not match the file name.")
end
end
# Error during quarantining of a file.
class CaskQuarantineError < CaskError
attr_reader :path, :reason
def initialize(path, reason)
super()
@path = path
@reason = reason
end
sig { returns(String) }
def to_s
s = "Failed to quarantine #{path}."
unless reason.empty?
s << " Here's the reason:\n"
s << Formatter.error(reason)
s << "\n" unless reason.end_with?("\n")
end
s.freeze
end
end
# Error while propagating quarantine information to subdirectories.
class CaskQuarantinePropagationError < CaskQuarantineError
sig { returns(String) }
def to_s
s = "Failed to quarantine one or more files within #{path}."
unless reason.empty?
s << " Here's the reason:\n"
s << Formatter.error(reason)
s << "\n" unless reason.end_with?("\n")
end
s.freeze
end
end
# Error while removing quarantine information.
class CaskQuarantineReleaseError < CaskQuarantineError
sig { returns(String) }
def to_s
s = "Failed to release #{path} from quarantine."
unless reason.empty?
s << " Here's the reason:\n"
s << Formatter.error(reason)
s << "\n" unless reason.end_with?("\n")
end
s.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/denylist.rb | Library/Homebrew/cask/denylist.rb | # typed: strict
# frozen_string_literal: true
module Cask
# List of casks which are not allowed in official taps.
module Denylist
sig { params(name: String).returns(T.nilable(String)) }
def self.reason(name)
case name
when /^adobe-(after|illustrator|indesign|photoshop|premiere)/
"Adobe casks were removed because they are too difficult to maintain."
when /^pharo$/
"Pharo developers maintain their own tap."
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/reinstall.rb | Library/Homebrew/cask/reinstall.rb | # typed: strict
# frozen_string_literal: true
require "utils/output"
module Cask
class Reinstall
extend ::Utils::Output::Mixin
sig {
params(
casks: ::Cask::Cask, verbose: T::Boolean, force: T::Boolean, skip_cask_deps: T::Boolean, binaries: T::Boolean,
require_sha: T::Boolean, quarantine: T::Boolean, zap: T::Boolean
).void
}
def self.reinstall_casks(
*casks,
verbose: false,
force: false,
skip_cask_deps: false,
binaries: false,
require_sha: false,
quarantine: false,
zap: false
)
require "cask/installer"
quarantine = true if quarantine.nil?
download_queue = Homebrew::DownloadQueue.new_if_concurrency_enabled(pour: true)
cask_installers = casks.map do |cask|
Installer.new(cask, binaries:, verbose:, force:, skip_cask_deps:, require_sha:, reinstall: true,
quarantine:, zap:, download_queue:)
end
if download_queue
cask_installers.each(&:prelude)
oh1 "Fetching downloads for: #{casks.map { |cask| Formatter.identifier(cask.full_name) }.to_sentence}",
truncate: false
cask_installers.each(&:enqueue_downloads)
download_queue.fetch
end
exit 1 if Homebrew.failed?
cask_installers.each(&:install)
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/cask/uninstall.rb | Library/Homebrew/cask/uninstall.rb | # typed: strict
# frozen_string_literal: true
require "cask_dependent"
require "dependents_message"
require "utils/output"
module Cask
class Uninstall
extend ::Utils::Output::Mixin
sig { params(casks: ::Cask::Cask, binaries: T::Boolean, force: T::Boolean, verbose: T::Boolean).void }
def self.uninstall_casks(*casks, binaries: false, force: false, verbose: false)
require "cask/installer"
casks.each do |cask|
odebug "Uninstalling Cask #{cask}"
raise CaskNotInstalledError, cask if !cask.installed? && !force
Installer.new(cask, binaries:, force:, verbose:).uninstall
end
end
sig { params(casks: ::Cask::Cask, named_args: T::Array[String]).void }
def self.check_dependent_casks(*casks, named_args: [])
dependents = []
all_requireds = casks.map(&:token)
requireds = Set.new
caskroom = ::Cask::Caskroom.casks
caskroom.each do |dependent|
d = CaskDependent.new(dependent)
dependencies = d.recursive_requirements.filter_map { |r| r.cask if r.is_a?(CaskDependent::Requirement) }
found_dependents = dependencies.intersection(all_requireds)
next if found_dependents.empty?
requireds += found_dependents
dependents << dependent.token
end
return if dependents.empty?
DependentsMessage.new(requireds.to_a, dependents, named_args:).output
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/cask/utils.rb | Library/Homebrew/cask/utils.rb | # typed: strict
# frozen_string_literal: true
require "utils/user"
require "open3"
require "utils/output"
module Cask
# Helper functions for various cask operations.
module Utils
extend ::Utils::Output::Mixin
BUG_REPORTS_URL = "https://github.com/Homebrew/homebrew-cask#reporting-bugs"
sig { params(path: Pathname, command: T.class_of(SystemCommand)).void }
def self.gain_permissions_mkpath(path, command: SystemCommand)
dir = path.ascend.find(&:directory?)
return if path == dir
if dir&.writable?
path.mkpath
else
command.run!("mkdir", args: ["-p", "--", path], sudo: true, print_stderr: false)
end
end
sig { params(path: Pathname, command: T.class_of(SystemCommand)).void }
def self.gain_permissions_rmdir(path, command: SystemCommand)
gain_permissions(path, [], command) do |p|
if p.parent.writable?
FileUtils.rmdir p
else
command.run!("rmdir", args: ["--", p], sudo: true, print_stderr: false)
end
end
end
sig { params(path: Pathname, command: T.class_of(SystemCommand)).void }
def self.gain_permissions_remove(path, command: SystemCommand)
directory = false
permission_flags = if path.symlink?
["-h"]
elsif path.directory?
directory = true
["-R"]
elsif path.exist?
[]
else
# Nothing to remove.
return
end
gain_permissions(path, permission_flags, command) do |p|
if p.parent.writable?
if directory
FileUtils.rm_r p
else
FileUtils.rm_f p
end
else
recursive_flag = directory ? ["-R"] : []
command.run!("/bin/rm", args: recursive_flag + ["-f", "--", p], sudo: true, print_stderr: false)
end
end
end
sig {
params(
path: Pathname,
command_args: T::Array[String],
command: T.class_of(SystemCommand),
_block: T.proc.params(path: Pathname).void,
).void
}
def self.gain_permissions(path, command_args, command, &_block)
tried_permissions = false
tried_ownership = false
begin
yield path
rescue
# in case of permissions problems
unless tried_permissions
print_stderr = Context.current.debug? || Context.current.verbose?
# TODO: Better handling for the case where path is a symlink.
# The `-h` and `-R` flags cannot be combined and behavior is
# dependent on whether the file argument has a trailing
# slash. This should do the right thing, but is fragile.
command.run("/usr/bin/chflags",
print_stderr:,
args: command_args + ["--", "000", path])
command.run("chmod",
print_stderr:,
args: command_args + ["--", "u+rwx", path])
command.run("chmod",
print_stderr:,
args: command_args + ["-N", path])
tried_permissions = true
retry # rmtree
end
unless tried_ownership
# in case of ownership problems
# TODO: Further examine files to see if ownership is the problem
# before using `sudo` and `chown`.
ohai "Using sudo to gain ownership of path '#{path}'"
command.run("chown",
args: command_args + ["--", User.current, path],
sudo: true)
tried_ownership = true
# retry chflags/chmod after chown
tried_permissions = false
retry # rmtree
end
raise
end
end
sig { params(path: Pathname).returns(T::Boolean) }
def self.path_occupied?(path)
path.exist? || path.symlink?
end
sig { params(name: String).returns(String) }
def self.token_from(name)
name.downcase
.gsub("+", "-plus-")
.gsub(/[ _·•]/, "-")
.gsub(/[^\w@-]/, "")
.gsub(/--+/, "-")
.delete_prefix("-")
.delete_suffix("-")
end
sig { returns(String) }
def self.error_message_with_suggestions
<<~EOS
Follow the instructions here:
#{Formatter.url(BUG_REPORTS_URL)}
EOS
end
sig { params(method: Symbol, token: String, section: T.nilable(String)).void }
def self.method_missing_message(method, token, section = nil)
message = "Unexpected method '#{method}' called "
message << "during #{section} " if section
message << "on Cask #{token}."
ofail "#{message}\n#{error_message_with_suggestions}"
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/cask/artifact_set.rb | Library/Homebrew/cask/artifact_set.rb | # typed: strict
# frozen_string_literal: true
module Cask
# Sorted set containing all cask artifacts.
class ArtifactSet < ::Set
extend T::Generic
Elem = type_member(:out) { { fixed: Artifact::AbstractArtifact } }
sig { params(block: T.nilable(T.proc.params(arg0: Elem).returns(T.untyped))).void }
def each(&block)
return enum_for(T.must(__method__)) { size } unless block
to_a.each(&block)
self
end
sig { returns(T::Array[Artifact::AbstractArtifact]) }
def to_a
super.sort
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/cask/macos.rb | Library/Homebrew/cask/macos.rb | # typed: strict
# frozen_string_literal: true
module OS
module Mac
SYSTEM_DIRS = T.let([
"/",
"/Applications",
"/Applications/Utilities",
"/Incompatible Software",
"/Library",
"/Library/Application Support",
"/Library/Audio",
"/Library/Caches",
"/Library/ColorPickers",
"/Library/ColorSync",
"/Library/Components",
"/Library/Compositions",
"/Library/Contextual Menu Items",
"/Library/CoreMediaIO",
"/Library/Desktop Pictures",
"/Library/Developer",
"/Library/Dictionaries",
"/Library/DirectoryServices",
"/Library/Documentation",
"/Library/Extensions",
"/Library/Filesystems",
"/Library/Fonts",
"/Library/Frameworks",
"/Library/Graphics",
"/Library/Image Capture",
"/Library/Input Methods",
"/Library/Internet Plug-Ins",
"/Library/Java",
"/Library/Java/Extensions",
"/Library/Java/JavaVirtualMachines",
"/Library/Keyboard Layouts",
"/Library/Keychains",
"/Library/LaunchAgents",
"/Library/LaunchDaemons",
"/Library/Logs",
"/Library/Messages",
"/Library/Modem Scripts",
"/Library/OpenDirectory",
"/Library/PDF Services",
"/Library/Perl",
"/Library/PreferencePanes",
"/Library/Preferences",
"/Library/Printers",
"/Library/PrivilegedHelperTools",
"/Library/Python",
"/Library/QuickLook",
"/Library/QuickTime",
"/Library/Receipts",
"/Library/Ruby",
"/Library/Sandbox",
"/Library/Screen Savers",
"/Library/ScriptingAdditions",
"/Library/Scripts",
"/Library/Security",
"/Library/Speech",
"/Library/Spelling",
"/Library/Spotlight",
"/Library/StartupItems",
"/Library/SystemProfiler",
"/Library/Updates",
"/Library/User Pictures",
"/Library/Video",
"/Library/WebServer",
"/Library/Widgets",
"/Library/iTunes",
"/Network",
"/System",
"/System/Library",
"/System/Library/Accessibility",
"/System/Library/Accounts",
"/System/Library/Address Book Plug-Ins",
"/System/Library/Assistant",
"/System/Library/Automator",
"/System/Library/BridgeSupport",
"/System/Library/Caches",
"/System/Library/ColorPickers",
"/System/Library/ColorSync",
"/System/Library/Colors",
"/System/Library/Components",
"/System/Library/Compositions",
"/System/Library/CoreServices",
"/System/Library/DTDs",
"/System/Library/DirectoryServices",
"/System/Library/Displays",
"/System/Library/Extensions",
"/System/Library/Filesystems",
"/System/Library/Filters",
"/System/Library/Fonts",
"/System/Library/Frameworks",
"/System/Library/Graphics",
"/System/Library/IdentityServices",
"/System/Library/Image Capture",
"/System/Library/Input Methods",
"/System/Library/InternetAccounts",
"/System/Library/Java",
"/System/Library/KerberosPlugins",
"/System/Library/Keyboard Layouts",
"/System/Library/Keychains",
"/System/Library/LaunchAgents",
"/System/Library/LaunchDaemons",
"/System/Library/LinguisticData",
"/System/Library/LocationBundles",
"/System/Library/LoginPlugins",
"/System/Library/Messages",
"/System/Library/Metadata",
"/System/Library/MonitorPanels",
"/System/Library/OpenDirectory",
"/System/Library/OpenSSL",
"/System/Library/Password Server Filters",
"/System/Library/PerformanceMetrics",
"/System/Library/Perl",
"/System/Library/PreferencePanes",
"/System/Library/Printers",
"/System/Library/PrivateFrameworks",
"/System/Library/QuickLook",
"/System/Library/QuickTime",
"/System/Library/QuickTimeJava",
"/System/Library/Recents",
"/System/Library/SDKSettingsPlist",
"/System/Library/Sandbox",
"/System/Library/Screen Savers",
"/System/Library/ScreenReader",
"/System/Library/ScriptingAdditions",
"/System/Library/ScriptingDefinitions",
"/System/Library/Security",
"/System/Library/Services",
"/System/Library/Sounds",
"/System/Library/Speech",
"/System/Library/Spelling",
"/System/Library/Spotlight",
"/System/Library/StartupItems",
"/System/Library/SyncServices",
"/System/Library/SystemConfiguration",
"/System/Library/SystemProfiler",
"/System/Library/Tcl",
"/System/Library/TextEncodings",
"/System/Library/User Template",
"/System/Library/UserEventPlugins",
"/System/Library/Video",
"/System/Library/WidgetResources",
"/User Information",
"/Users",
"/Volumes",
"/bin",
"/boot",
"/cores",
"/dev",
"/etc",
"/etc/X11",
"/etc/opt",
"/etc/sgml",
"/etc/xml",
"/home",
"/libexec",
"/lost+found",
"/media",
"/mnt",
"/net",
"/opt",
"/private",
"/private/etc",
"/private/tftpboot",
"/private/tmp",
"/private/var",
"/proc",
"/root",
"/sbin",
"/srv",
"/tmp",
"/usr",
"/usr/X11R6",
"/usr/bin",
"/usr/etc",
"/usr/include",
"/usr/lib",
"/usr/libexec",
"/usr/libexec/cups",
"/usr/local",
"/usr/local/Cellar",
"/usr/local/Frameworks",
"/usr/local/Library",
"/usr/local/bin",
"/usr/local/etc",
"/usr/local/include",
"/usr/local/lib",
"/usr/local/libexec",
"/usr/local/opt",
"/usr/local/share",
"/usr/local/share/man",
"/usr/local/share/man/man1",
"/usr/local/share/man/man2",
"/usr/local/share/man/man3",
"/usr/local/share/man/man4",
"/usr/local/share/man/man5",
"/usr/local/share/man/man6",
"/usr/local/share/man/man7",
"/usr/local/share/man/man8",
"/usr/local/share/man/man9",
"/usr/local/share/man/mann",
"/usr/local/var",
"/usr/local/var/lib",
"/usr/local/var/lock",
"/usr/local/var/run",
"/usr/sbin",
"/usr/share",
"/usr/share/man",
"/usr/share/man/man1",
"/usr/share/man/man2",
"/usr/share/man/man3",
"/usr/share/man/man4",
"/usr/share/man/man5",
"/usr/share/man/man6",
"/usr/share/man/man7",
"/usr/share/man/man8",
"/usr/share/man/man9",
"/usr/share/man/mann",
"/usr/src",
"/var",
"/var/cache",
"/var/lib",
"/var/lock",
"/var/log",
"/var/mail",
"/var/run",
"/var/spool",
"/var/spool/mail",
"/var/tmp",
]
.to_set { |path| ::Pathname.new(path) }
.freeze, T::Set[::Pathname])
private_constant :SYSTEM_DIRS
# TODO: There should be a way to specify a containing
# directory under which nothing can be deleted.
UNDELETABLE_PATHS = T.let([
"~/",
"~/Applications",
"~/Applications/.localized",
"~/Desktop",
"~/Desktop/.localized",
"~/Documents",
"~/Documents/.localized",
"~/Downloads",
"~/Downloads/.localized",
"~/Mail",
"~/Movies",
"~/Movies/.localized",
"~/Music",
"~/Music/.localized",
"~/Music/iTunes",
"~/Music/iTunes/iTunes Music",
"~/Music/iTunes/Album Artwork",
"~/News",
"~/Pictures",
"~/Pictures/.localized",
"~/Pictures/Desktops",
"~/Pictures/Photo Booth",
"~/Pictures/iChat Icons",
"~/Pictures/iPhoto Library",
"~/Public",
"~/Public/.localized",
"~/Sites",
"~/Sites/.localized",
"~/Library",
"~/Library/.localized",
"~/Library/Accessibility",
"~/Library/Accounts",
"~/Library/Address Book Plug-Ins",
"~/Library/Application Scripts",
"~/Library/Application Support",
"~/Library/Application Support/Apple",
"~/Library/Application Support/com.apple.AssistiveControl",
"~/Library/Application Support/com.apple.QuickLook",
"~/Library/Application Support/com.apple.TCC",
"~/Library/Assistants",
"~/Library/Audio",
"~/Library/Automator",
"~/Library/Autosave Information",
"~/Library/Caches",
"~/Library/Calendars",
"~/Library/ColorPickers",
"~/Library/ColorSync",
"~/Library/Colors",
"~/Library/Components",
"~/Library/Compositions",
"~/Library/Containers",
"~/Library/Contextual Menu Items",
"~/Library/Cookies",
"~/Library/DTDs",
"~/Library/Desktop Pictures",
"~/Library/Developer",
"~/Library/Dictionaries",
"~/Library/DirectoryServices",
"~/Library/Displays",
"~/Library/Documentation",
"~/Library/Extensions",
"~/Library/Favorites",
"~/Library/FileSync",
"~/Library/Filesystems",
"~/Library/Filters",
"~/Library/FontCollections",
"~/Library/Fonts",
"~/Library/Frameworks",
"~/Library/GameKit",
"~/Library/Graphics",
"~/Library/Group Containers",
"~/Library/Icons",
"~/Library/IdentityServices",
"~/Library/Image Capture",
"~/Library/Images",
"~/Library/Input Methods",
"~/Library/Internet Plug-Ins",
"~/Library/InternetAccounts",
"~/Library/iTunes",
"~/Library/KeyBindings",
"~/Library/Keyboard Layouts",
"~/Library/Keychains",
"~/Library/LaunchAgents",
"~/Library/LaunchDaemons",
"~/Library/LocationBundles",
"~/Library/LoginPlugins",
"~/Library/Logs",
"~/Library/Mail",
"~/Library/Mail Downloads",
"~/Library/Messages",
"~/Library/Metadata",
"~/Library/Mobile Documents",
"~/Library/MonitorPanels",
"~/Library/OpenDirectory",
"~/Library/PDF Services",
"~/Library/PhonePlugins",
"~/Library/Phones",
"~/Library/PreferencePanes",
"~/Library/Preferences",
"~/Library/Printers",
"~/Library/PrivateFrameworks",
"~/Library/PubSub",
"~/Library/QuickLook",
"~/Library/QuickTime",
"~/Library/Receipts",
"~/Library/Recent Servers",
"~/Library/Recents",
"~/Library/Safari",
"~/Library/Saved Application State",
"~/Library/Screen Savers",
"~/Library/ScreenReader",
"~/Library/ScriptingAdditions",
"~/Library/ScriptingDefinitions",
"~/Library/Scripts",
"~/Library/Security",
"~/Library/Services",
"~/Library/Sounds",
"~/Library/Speech",
"~/Library/Spelling",
"~/Library/Spotlight",
"~/Library/StartupItems",
"~/Library/StickiesDatabase",
"~/Library/Sync Services",
"~/Library/SyncServices",
"~/Library/SyncedPreferences",
"~/Library/TextEncodings",
"~/Library/User Pictures",
"~/Library/Video",
"~/Library/Voices",
"~/Library/WebKit",
"~/Library/WidgetResources",
"~/Library/Widgets",
"~/Library/Workflows",
]
.to_set { |path| ::Pathname.new(path.sub(%r{^~(?=(/|$))}, Dir.home)).expand_path }
.union(SYSTEM_DIRS)
.freeze, T::Set[::Pathname])
private_constant :UNDELETABLE_PATHS
sig { params(dir: T.any(::Pathname, String)).returns(T::Boolean) }
def self.system_dir?(dir)
SYSTEM_DIRS.include?(::Pathname.new(dir).expand_path)
end
sig { params(path: T.any(::Pathname, String)).returns(T::Boolean) }
def self.undeletable?(path)
UNDELETABLE_PATHS.include?(::Pathname.new(path).expand_path)
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/cask/tab.rb | Library/Homebrew/cask/tab.rb | # typed: strict
# frozen_string_literal: true
require "tab"
module Cask
class Tab < ::AbstractTab
sig { returns(T.nilable(T::Boolean)) }
attr_accessor :uninstall_flight_blocks
sig { returns(T.nilable(T::Array[T.untyped])) }
attr_accessor :uninstall_artifacts
sig { params(attributes: T.any(T::Hash[String, T.untyped], T::Hash[Symbol, T.untyped])).void }
def initialize(attributes = {})
@uninstall_flight_blocks = T.let(nil, T.nilable(T::Boolean))
@uninstall_artifacts = T.let(nil, T.nilable(T::Array[T.untyped]))
super
end
# Instantiates a {Tab} for a new installation of a cask.
sig { override.params(formula_or_cask: T.any(Formula, Cask)).returns(T.attached_class) }
def self.create(formula_or_cask)
cask = T.cast(formula_or_cask, Cask)
tab = super
tab.tabfile = cask.metadata_main_container_path/FILENAME
tab.uninstall_flight_blocks = cask.uninstall_flight_blocks?
tab.runtime_dependencies = Tab.runtime_deps_hash(cask)
tab.source["version"] = cask.version.to_s
tab.source["path"] = cask.sourcefile_path.to_s
tab.uninstall_artifacts = cask.artifacts_list(uninstall_only: true)
tab
end
# Returns a {Tab} for an already installed cask,
# or a fake one if the cask is not installed.
sig { params(cask: Cask).returns(T.attached_class) }
def self.for_cask(cask)
path = cask.metadata_main_container_path/FILENAME
return from_file(path) if path.exist?
tab = empty
tab.source = {
"path" => cask.sourcefile_path.to_s,
"tap" => cask.tap&.name,
"tap_git_head" => cask.tap_git_head,
"version" => cask.version.to_s,
}
tab.uninstall_artifacts = cask.artifacts_list(uninstall_only: true)
tab
end
sig { returns(T.attached_class) }
def self.empty
tab = super
tab.uninstall_flight_blocks = false
tab.uninstall_artifacts = []
tab.source["version"] = nil
tab
end
sig { params(cask: Cask).returns(T::Hash[Symbol, T::Array[T::Hash[String, T.untyped]]]) }
def self.runtime_deps_hash(cask)
cask_and_formula_dep_graph = ::Utils::TopologicalHash.graph_package_dependencies(cask)
cask_deps, formula_deps = cask_and_formula_dep_graph.values.flatten.uniq.partition do |dep|
dep.is_a?(Cask)
end
runtime_deps = {}
if cask_deps.any?
runtime_deps[:cask] = cask_deps.map do |dep|
{
"full_name" => dep.full_name,
"version" => dep.version.to_s,
"declared_directly" => cask.depends_on.cask.include?(dep.full_name),
}
end
end
if formula_deps.any?
runtime_deps[:formula] = formula_deps.map do |dep|
formula_to_dep_hash(dep, cask.depends_on.formula)
end
end
runtime_deps
end
sig { returns(T.nilable(String)) }
def version
source["version"]
end
sig { params(_args: T.untyped).returns(String) }
def to_json(*_args)
attributes = {
"homebrew_version" => homebrew_version,
"loaded_from_api" => loaded_from_api,
"uninstall_flight_blocks" => uninstall_flight_blocks,
"installed_as_dependency" => installed_as_dependency,
"installed_on_request" => installed_on_request,
"time" => time,
"runtime_dependencies" => runtime_dependencies,
"source" => source,
"arch" => arch,
"uninstall_artifacts" => uninstall_artifacts,
"built_on" => built_on,
}
JSON.pretty_generate(attributes)
end
sig { returns(String) }
def to_s
s = ["Installed"]
s << "using the formulae.brew.sh API" if loaded_from_api
s << Time.at(time).strftime("on %Y-%m-%d at %H:%M:%S") if time
s.join(" ")
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/cask/staged.rb | Library/Homebrew/cask/staged.rb | # typed: strict
# frozen_string_literal: true
require "utils/user"
require "utils/output"
module Cask
# Helper functions for staged casks.
module Staged
include ::Utils::Output::Mixin
extend T::Helpers
requires_ancestor { ::Cask::DSL::Base }
Paths = T.type_alias { T.any(String, Pathname, T::Array[T.any(String, Pathname)]) }
sig { params(paths: Paths, permissions_str: String).void }
def set_permissions(paths, permissions_str)
full_paths = remove_nonexistent(paths)
return if full_paths.empty?
command.run!("chmod", args: ["-R", "--", permissions_str, *full_paths],
sudo: false)
end
sig { params(paths: Paths, user: T.any(String, User), group: String).void }
def set_ownership(paths, user: T.must(User.current), group: "staff")
full_paths = remove_nonexistent(paths)
return if full_paths.empty?
ohai "Changing ownership of paths required by #{cask} with `sudo` (which may request your password)..."
command.run!("chown", args: ["-R", "--", "#{user}:#{group}", *full_paths],
sudo: true)
end
private
sig { params(paths: Paths).returns(T::Array[Pathname]) }
def remove_nonexistent(paths)
Array(paths).map { |p| Pathname(p).expand_path }.select(&:exist?)
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/cask/dsl.rb | Library/Homebrew/cask/dsl.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "autobump_constants"
require "locale"
require "lazy_object"
require "livecheck"
require "utils/output"
require "cask/artifact"
require "cask/artifact_set"
require "cask/caskroom"
require "cask/exceptions"
require "cask/dsl/base"
require "cask/dsl/caveats"
require "cask/dsl/conflicts_with"
require "cask/dsl/container"
require "cask/dsl/depends_on"
require "cask/dsl/postflight"
require "cask/dsl/preflight"
require "cask/dsl/rename"
require "cask/dsl/uninstall_postflight"
require "cask/dsl/uninstall_preflight"
require "cask/dsl/version"
require "cask/url"
require "cask/utils"
require "on_system"
module Cask
# Class representing the domain-specific language used for casks.
class DSL
include ::Utils::Output::Mixin
ORDINARY_ARTIFACT_CLASSES = [
Artifact::Installer,
Artifact::App,
Artifact::Artifact,
Artifact::AudioUnitPlugin,
Artifact::Binary,
Artifact::Colorpicker,
Artifact::Dictionary,
Artifact::Font,
Artifact::InputMethod,
Artifact::InternetPlugin,
Artifact::KeyboardLayout,
Artifact::Manpage,
Artifact::Pkg,
Artifact::Prefpane,
Artifact::Qlplugin,
Artifact::Mdimporter,
Artifact::ScreenSaver,
Artifact::Service,
Artifact::StageOnly,
Artifact::Suite,
Artifact::VstPlugin,
Artifact::Vst3Plugin,
Artifact::ZshCompletion,
Artifact::FishCompletion,
Artifact::BashCompletion,
Artifact::Uninstall,
Artifact::Zap,
].freeze
ACTIVATABLE_ARTIFACT_CLASSES = (ORDINARY_ARTIFACT_CLASSES - [Artifact::StageOnly]).freeze
ARTIFACT_BLOCK_CLASSES = [
Artifact::PreflightBlock,
Artifact::PostflightBlock,
].freeze
DSL_METHODS = Set.new([
:arch,
:artifacts,
:auto_updates,
:caveats,
:conflicts_with,
:container,
:desc,
:depends_on,
:homepage,
:language,
:name,
:os,
:rename,
:sha256,
:staged_path,
:url,
:version,
:appdir,
:deprecate!,
:deprecated?,
:deprecation_date,
:deprecation_reason,
:deprecation_replacement_cask,
:deprecation_replacement_formula,
:deprecate_args,
:disable!,
:disabled?,
:disable_date,
:disable_reason,
:disable_replacement_cask,
:disable_replacement_formula,
:disable_args,
:livecheck,
:livecheck_defined?,
:no_autobump!,
:autobump?,
:no_autobump_message,
:on_system_blocks_exist?,
:on_system_block_min_os,
:depends_on_set_in_block?,
*ORDINARY_ARTIFACT_CLASSES.map(&:dsl_key),
*ACTIVATABLE_ARTIFACT_CLASSES.map(&:dsl_key),
*ARTIFACT_BLOCK_CLASSES.flat_map { |klass| [klass.dsl_key, klass.uninstall_dsl_key] },
]).freeze
include OnSystem::MacOSAndLinux
attr_reader :cask, :token, :no_autobump_message, :artifacts, :deprecation_date, :deprecation_reason,
:deprecation_replacement_cask, :deprecation_replacement_formula, :deprecate_args,
:disable_date, :disable_reason, :disable_replacement_cask,
:disable_replacement_formula, :disable_args, :on_system_block_min_os
sig { params(cask: Cask).void }
def initialize(cask)
# NOTE: `:"@#{stanza}"` variables set by `set_unique_stanza` must be
# initialized to `nil`.
@arch = T.let(nil, T.nilable(String))
@arch_set_in_block = T.let(false, T::Boolean)
@artifacts = T.let(ArtifactSet.new, ArtifactSet)
@auto_updates = T.let(nil, T.nilable(T::Boolean))
@auto_updates_set_in_block = T.let(false, T::Boolean)
@autobump = T.let(true, T::Boolean)
@called_in_on_system_block = T.let(false, T::Boolean)
@cask = T.let(cask, Cask)
@caveats = T.let(DSL::Caveats.new(cask), DSL::Caveats)
@conflicts_with = T.let(nil, T.nilable(DSL::ConflictsWith))
@conflicts_with_set_in_block = T.let(false, T::Boolean)
@container = T.let(nil, T.nilable(DSL::Container))
@container_set_in_block = T.let(false, T::Boolean)
@depends_on = T.let(DSL::DependsOn.new, DSL::DependsOn)
@depends_on_set_in_block = T.let(false, T::Boolean)
@deprecated = T.let(false, T::Boolean)
@deprecation_date = T.let(nil, T.nilable(Date))
@deprecation_reason = T.let(nil, T.nilable(T.any(String, Symbol)))
@deprecation_replacement_cask = T.let(nil, T.nilable(String))
@deprecation_replacement_formula = T.let(nil, T.nilable(String))
@deprecate_args = T.let(nil, T.nilable(T::Hash[Symbol, T.nilable(T.any(String, Symbol))]))
@desc = T.let(nil, T.nilable(String))
@desc_set_in_block = T.let(false, T::Boolean)
@disable_date = T.let(nil, T.nilable(Date))
@disable_reason = T.let(nil, T.nilable(T.any(String, Symbol)))
@disable_replacement_cask = T.let(nil, T.nilable(String))
@disable_replacement_formula = T.let(nil, T.nilable(String))
@disable_args = T.let(nil, T.nilable(T::Hash[Symbol, T.nilable(T.any(String, Symbol))]))
@disabled = T.let(false, T::Boolean)
@homepage = T.let(nil, T.nilable(String))
@homepage_set_in_block = T.let(false, T::Boolean)
@language_blocks = T.let({}, T::Hash[T::Array[String], Proc])
@language_eval = T.let(nil, T.nilable(String))
@livecheck = T.let(Livecheck.new(cask), Livecheck)
@livecheck_defined = T.let(false, T::Boolean)
@name = T.let([], T::Array[String])
@no_autobump_defined = T.let(false, T::Boolean)
@on_system_blocks_exist = T.let(false, T::Boolean)
@on_system_block_min_os = T.let(nil, T.nilable(MacOSVersion))
@os = T.let(nil, T.nilable(String))
@os_set_in_block = T.let(false, T::Boolean)
@rename = T.let([], T::Array[DSL::Rename])
@sha256 = T.let(nil, T.nilable(T.any(Checksum, Symbol)))
@sha256_set_in_block = T.let(false, T::Boolean)
@staged_path = T.let(nil, T.nilable(Pathname))
@token = T.let(cask.token, String)
@url = T.let(nil, T.nilable(URL))
@url_set_in_block = T.let(false, T::Boolean)
@version = T.let(nil, T.nilable(DSL::Version))
@version_set_in_block = T.let(false, T::Boolean)
end
sig { returns(T::Boolean) }
def depends_on_set_in_block? = @depends_on_set_in_block
sig { returns(T::Boolean) }
def deprecated? = @deprecated
sig { returns(T::Boolean) }
def disabled? = @disabled
sig { returns(T::Boolean) }
def livecheck_defined? = @livecheck_defined
sig { returns(T::Boolean) }
def on_system_blocks_exist? = @on_system_blocks_exist
# Specifies the cask's name.
#
# NOTE: Multiple names can be specified.
#
# ### Example
#
# ```ruby
# name "Visual Studio Code"
# ```
#
# @api public
def name(*args)
return @name if args.empty?
@name.concat(args.flatten)
end
# Describes the cask.
#
# ### Example
#
# ```ruby
# desc "Open-source code editor"
# ```
#
# @api public
def desc(description = nil)
set_unique_stanza(:desc, description.nil?) { description }
end
def set_unique_stanza(stanza, should_return)
return instance_variable_get(:"@#{stanza}") if should_return
unless @cask.allow_reassignment
if !instance_variable_get(:"@#{stanza}").nil? && !@called_in_on_system_block
raise CaskInvalidError.new(cask, "'#{stanza}' stanza may only appear once.")
end
if instance_variable_get(:"@#{stanza}_set_in_block") && @called_in_on_system_block
raise CaskInvalidError.new(cask, "'#{stanza}' stanza may only be overridden once.")
end
end
instance_variable_set(:"@#{stanza}_set_in_block", true) if @called_in_on_system_block
instance_variable_set(:"@#{stanza}", yield)
rescue CaskInvalidError
raise
rescue => e
raise CaskInvalidError.new(cask, "'#{stanza}' stanza failed with: #{e}")
end
# Sets the cask's homepage.
#
# ### Example
#
# ```ruby
# homepage "https://code.visualstudio.com/"
# ```
#
# @api public
def homepage(homepage = nil)
set_unique_stanza(:homepage, homepage.nil?) { homepage }
end
def language(*args, default: false, &block)
if args.empty?
language_eval
elsif block
@language_blocks[args] = block
return unless default
if !@cask.allow_reassignment && @language_blocks.default.present?
raise CaskInvalidError.new(cask, "Only one default language may be defined.")
end
@language_blocks.default = block
else
raise CaskInvalidError.new(cask, "No block given to language stanza.")
end
end
def language_eval
return @language_eval unless @language_eval.nil?
return @language_eval = nil if @language_blocks.empty?
if (language_blocks_default = @language_blocks.default).nil?
raise CaskInvalidError.new(cask, "No default language specified.")
end
locales = cask.config.languages
.filter_map do |language|
Locale.parse(language)
rescue Locale::ParserError
nil
end
locales.each do |locale|
key = locale.detect(@language_blocks.keys)
next if key.nil? || (language_block = @language_blocks[key]).nil?
return @language_eval = language_block.call
end
@language_eval = language_blocks_default.call
end
def languages
@language_blocks.keys.flatten
end
# Sets the cask's download URL.
#
# ### Example
#
# ```ruby
# url "https://update.code.visualstudio.com/#{version}/#{arch}/stable"
# ```
#
# @api public
def url(*args, **options)
caller_location = T.must(caller_locations).fetch(0)
set_unique_stanza(:url, args.empty? && options.empty?) do
URL.new(*args, **options, caller_location:)
end
end
# Sets the cask's container type or nested container path.
#
# ### Examples
#
# The container is a nested disk image:
#
# ```ruby
# container nested: "orca-#{version}.dmg"
# ```
#
# The container should not be unarchived:
#
# ```ruby
# container type: :naked
# ```
#
# @api public
def container(**kwargs)
set_unique_stanza(:container, kwargs.empty?) do
DSL::Container.new(**kwargs)
end
end
# Renames files after extraction.
#
# This is useful when the downloaded file has unpredictable names
# that need to be normalized for proper artifact installation.
#
# ### Example
#
# ```ruby
# rename "RØDECaster App*.pkg", "RØDECaster App.pkg"
# ```
#
# @api public
sig {
params(from: String,
to: String).returns(T::Array[DSL::Rename])
}
def rename(from = T.unsafe(nil), to = T.unsafe(nil))
return @rename if from.nil?
@rename << DSL::Rename.new(T.must(from), T.must(to))
end
# Sets the cask's version.
#
# ### Example
#
# ```ruby
# version "1.88.1"
# ```
#
# @see DSL::Version
# @api public
sig { params(arg: T.nilable(T.any(String, Symbol))).returns(T.nilable(DSL::Version)) }
def version(arg = nil)
set_unique_stanza(:version, arg.nil?) do
if !arg.is_a?(String) && arg != :latest
raise CaskInvalidError.new(cask, "invalid 'version' value: #{arg.inspect}")
end
no_autobump! because: :latest_version if arg == :latest
DSL::Version.new(arg)
end
end
# Sets the cask's download checksum.
#
# ### Example
#
# For universal or single-architecture downloads:
#
# ```ruby
# sha256 "7bdb497080ffafdfd8cc94d8c62b004af1be9599e865e5555e456e2681e150ca"
# ```
#
# For architecture-dependent downloads:
#
# ```ruby
# sha256 arm: "7bdb497080ffafdfd8cc94d8c62b004af1be9599e865e5555e456e2681e150ca",
# x86_64: "b3c1c2442480a0219b9e05cf91d03385858c20f04b764ec08a3fa83d1b27e7b2"
# x86_64_linux: "1a2aee7f1ddc999993d4d7d42a150c5e602bc17281678050b8ed79a0500cc90f"
# arm64_linux: "bd766af7e692afceb727a6f88e24e6e68d9882aeb3e8348412f6c03d96537c75"
# ```
#
# @api public
sig {
params(
arg: T.nilable(T.any(String, Symbol)),
arm: T.nilable(String),
intel: T.nilable(String),
x86_64: T.nilable(String),
x86_64_linux: T.nilable(String),
arm64_linux: T.nilable(String),
).returns(T.nilable(T.any(Symbol, Checksum)))
}
def sha256(arg = nil, arm: nil, intel: nil, x86_64: nil, x86_64_linux: nil, arm64_linux: nil)
should_return = arg.nil? && arm.nil? && (intel.nil? || x86_64.nil?) && x86_64_linux.nil? && arm64_linux.nil?
x86_64 ||= intel if intel.present? && x86_64.nil?
set_unique_stanza(:sha256, should_return) do
if arm.present? || x86_64.present? || x86_64_linux.present? || arm64_linux.present?
@on_system_blocks_exist = true
end
val = arg || on_system_conditional(
macos: on_arch_conditional(arm:, intel: x86_64),
linux: on_arch_conditional(arm: arm64_linux, intel: x86_64_linux),
)
case val
when :no_check
val
when String
Checksum.new(val)
else
raise CaskInvalidError.new(cask, "invalid 'sha256' value: #{val.inspect}")
end
end
end
# Sets the cask's architecture strings.
#
# ### Example
#
# ```ruby
# arch arm: "darwin-arm64", intel: "darwin"
# ```
#
# @api public
def arch(arm: nil, intel: nil)
should_return = arm.nil? && intel.nil?
set_unique_stanza(:arch, should_return) do
@on_system_blocks_exist = true
on_arch_conditional(arm:, intel:)
end
end
# Sets the cask's os strings.
#
# ### Example
#
# ```ruby
# os macos: "darwin", linux: "tux"
# ```
#
# @api public
sig {
params(
macos: T.nilable(String),
linux: T.nilable(String),
).returns(T.nilable(String))
}
def os(macos: nil, linux: nil)
should_return = macos.nil? && linux.nil?
set_unique_stanza(:os, should_return) do
@on_system_blocks_exist = true
on_system_conditional(macos:, linux:)
end
end
# Declare dependencies and requirements for a cask.
#
# NOTE: Multiple dependencies can be specified.
#
# @api public
def depends_on(**kwargs)
@depends_on_set_in_block = true if @called_in_on_system_block
return @depends_on if kwargs.empty?
begin
@depends_on.load(**kwargs)
rescue RuntimeError => e
raise CaskInvalidError.new(cask, e)
end
@depends_on
end
# @api private
def add_implicit_macos_dependency
return if (cask_depends_on = @depends_on).present? && cask_depends_on.macos.present?
depends_on macos: ">= #{MacOSVersion.new(HOMEBREW_MACOS_OLDEST_ALLOWED).to_sym.inspect}"
end
# Declare conflicts that keep a cask from installing or working correctly.
#
# @api public
def conflicts_with(**kwargs)
# TODO: Remove this constraint and instead merge multiple `conflicts_with` stanzas
set_unique_stanza(:conflicts_with, kwargs.empty?) { DSL::ConflictsWith.new(**kwargs) }
end
sig { returns(Pathname) }
def caskroom_path
cask.caskroom_path
end
# The staged location for this cask, including version number.
#
# @api public
sig { returns(Pathname) }
def staged_path
return @staged_path if @staged_path
cask_version = version || :unknown
@staged_path = caskroom_path.join(cask_version.to_s)
end
# Provide the user with cask-specific information at install time.
#
# @api public
def caveats(*strings, &block)
if block
@caveats.eval_caveats(&block)
elsif strings.any?
strings.each do |string|
@caveats.eval_caveats { string }
end
else
return @caveats.to_s
end
@caveats
end
# Asserts that the cask artifacts auto-update.
#
# @api public
def auto_updates(auto_updates = nil)
set_unique_stanza(:auto_updates, auto_updates.nil?) { auto_updates }
end
# Automatically fetch the latest version of a cask from changelogs.
#
# @api public
def livecheck(&block)
return @livecheck unless block
if !@cask.allow_reassignment && @livecheck_defined
raise CaskInvalidError.new(cask, "'livecheck' stanza may only appear once.")
end
@livecheck_defined = true
@livecheck.instance_eval(&block)
no_autobump! because: :extract_plist if @livecheck.strategy == :extract_plist
@livecheck
end
# Excludes the cask from autobump list.
#
# TODO: limit this method to the official taps only
# (e.g. raise an error if `!tap.official?`)
#
# @api public
sig { params(because: T.any(String, Symbol)).void }
def no_autobump!(because:)
if because.is_a?(Symbol) && !NO_AUTOBUMP_REASONS_LIST.key?(because)
raise ArgumentError, "'because' argument should use valid symbol or a string!"
end
if !@cask.allow_reassignment && @no_autobump_defined
raise CaskInvalidError.new(cask, "'no_autobump_defined' stanza may only appear once.")
end
@no_autobump_defined = true
@no_autobump_message = because
@autobump = false
end
# Is the cask in autobump list?
def autobump?
@autobump == true
end
# Is no_autobump! method defined?
def no_autobump_defined?
@no_autobump_defined == true
end
# Declare that a cask is no longer functional or supported.
#
# NOTE: A warning will be shown when trying to install this cask.
#
# @api public
def deprecate!(date:, because:, replacement: nil, replacement_formula: nil, replacement_cask: nil)
if [replacement, replacement_formula, replacement_cask].filter_map(&:presence).length > 1
raise ArgumentError, "more than one of replacement, replacement_formula and/or replacement_cask specified!"
end
if replacement
odeprecated(
"deprecate!(:replacement)",
"deprecate!(:replacement_formula) or deprecate!(:replacement_cask)",
)
end
@deprecate_args = { date:, because:, replacement_formula:, replacement_cask: }
@deprecation_date = Date.parse(date)
return if @deprecation_date > Date.today
@deprecation_reason = because
@deprecation_replacement_formula = replacement_formula.presence || replacement
@deprecation_replacement_cask = replacement_cask.presence || replacement
@deprecated = true
end
# Declare that a cask is no longer functional or supported.
#
# NOTE: An error will be thrown when trying to install this cask.
#
# @api public
def disable!(date:, because:, replacement: nil, replacement_formula: nil, replacement_cask: nil)
if [replacement, replacement_formula, replacement_cask].filter_map(&:presence).length > 1
raise ArgumentError, "more than one of replacement, replacement_formula and/or replacement_cask specified!"
end
# odeprecate: remove this remapping when the :unsigned reason is removed
because = :fails_gatekeeper_check if because == :unsigned
if replacement
odeprecated(
"disable!(:replacement)",
"disable!(:replacement_formula) or disable!(:replacement_cask)",
)
end
@disable_args = { date:, because:, replacement_formula:, replacement_cask: }
@disable_date = Date.parse(date)
if @disable_date > Date.today
@deprecation_reason = because
@deprecation_replacement_formula = replacement_formula.presence || replacement
@deprecation_replacement_cask = replacement_cask.presence || replacement
@deprecated = true
return
end
@disable_reason = because
@disable_replacement_formula = replacement_formula.presence || replacement
@disable_replacement_cask = replacement_cask.presence || replacement
@disabled = true
end
ORDINARY_ARTIFACT_CLASSES.each do |klass|
define_method(klass.dsl_key) do |*args, **kwargs|
T.bind(self, DSL)
if [*artifacts.map(&:class), klass].include?(Artifact::StageOnly) &&
artifacts.map(&:class).intersect?(ACTIVATABLE_ARTIFACT_CLASSES)
raise CaskInvalidError.new(cask, "'stage_only' must be the only activatable artifact.")
end
artifacts.add(klass.from_args(cask, *args, **kwargs))
rescue CaskInvalidError
raise
rescue => e
raise CaskInvalidError.new(cask, "invalid '#{klass.dsl_key}' stanza: #{e}")
end
end
ARTIFACT_BLOCK_CLASSES.each do |klass|
[klass.dsl_key, klass.uninstall_dsl_key].each do |dsl_key|
define_method(dsl_key) do |&block|
T.bind(self, DSL)
artifacts.add(klass.new(cask, dsl_key => block))
end
end
end
def method_missing(method, *)
if method
Utils.method_missing_message(method, token)
nil
else
super
end
end
def respond_to_missing?(*)
true
end
sig { returns(T.nilable(MacOSVersion)) }
def os_version
nil
end
# The directory `app`s are installed into.
#
# @api public
sig { returns(T.any(Pathname, String)) }
def appdir
return HOMEBREW_CASK_APPDIR_PLACEHOLDER if Cask.generating_hash?
cask.config.appdir
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/cask/info.rb | Library/Homebrew/cask/info.rb | # typed: strict
# frozen_string_literal: true
require "json"
require "cmd/info"
require "utils/output"
module Cask
class Info
extend ::Utils::Output::Mixin
sig { params(cask: Cask).returns(String) }
def self.get_info(cask)
require "cask/installer"
output = "#{title_info(cask)}\n"
output << "#{Formatter.url(cask.homepage)}\n" if cask.homepage
deprecate_disable = DeprecateDisable.message(cask)
if deprecate_disable.present?
deprecate_disable.tap { |message| message[0] = message[0].upcase }
output << "#{deprecate_disable}\n"
end
output << "#{installation_info(cask)}\n"
repo = repo_info(cask)
output << "#{repo}\n" if repo
output << name_info(cask)
output << desc_info(cask)
deps = deps_info(cask)
output << deps if deps
language = language_info(cask)
output << language if language
output << "#{artifact_info(cask)}\n"
caveats = Installer.caveats(cask)
output << caveats if caveats
output
end
sig { params(cask: Cask, args: Homebrew::Cmd::Info::Args).void }
def self.info(cask, args:)
puts get_info(cask)
return unless cask.tap.core_cask_tap?
require "utils/analytics"
::Utils::Analytics.cask_output(cask, args:)
end
sig { params(cask: Cask).returns(String) }
def self.title_info(cask)
title = "#{oh1_title(cask.token)}: #{cask.version}"
title += " (auto_updates)" if cask.auto_updates
title
end
sig { params(cask: Cask).returns(String) }
def self.installation_info(cask)
return "Not installed" unless cask.installed?
return "No installed version" unless (installed_version = cask.installed_version).present?
versioned_staged_path = cask.caskroom_path.join(installed_version)
return "Installed\n#{versioned_staged_path} (#{Formatter.error("does not exist")})\n" unless versioned_staged_path.exist?
path_details = versioned_staged_path.children.sum(&:disk_usage)
tab = Tab.for_cask(cask)
info = ["Installed"]
info << "#{versioned_staged_path} (#{disk_usage_readable(path_details)})"
info << " #{tab}" if tab.tabfile&.exist?
info.join("\n")
end
sig { params(cask: Cask).returns(String) }
def self.name_info(cask)
<<~EOS
#{ohai_title((cask.name.size > 1) ? "Names" : "Name")}
#{cask.name.empty? ? Formatter.error("None") : cask.name.join("\n")}
EOS
end
sig { params(cask: Cask).returns(String) }
def self.desc_info(cask)
<<~EOS
#{ohai_title("Description")}
#{cask.desc.nil? ? Formatter.error("None") : cask.desc}
EOS
end
sig { params(cask: Cask).returns(T.nilable(String)) }
def self.deps_info(cask)
depends_on = cask.depends_on
formula_deps = Array(depends_on[:formula]).map do |dep|
name = dep.to_s
installed = begin
Formula[name].any_version_installed?
rescue FormulaUnavailableError
false
end
decorate_dependency(name, installed:)
end
cask_deps = Array(depends_on[:cask]).map do |dep|
name = dep.to_s
installed = begin
CaskLoader.load(name).installed?
rescue CaskUnavailableError
false
end
decorate_dependency("#{name} (cask)", installed:)
end
all_deps = formula_deps + cask_deps
return if all_deps.empty?
<<~EOS
#{ohai_title("Dependencies")}
#{all_deps.join(", ")}
EOS
end
sig { params(dep: String, installed: T::Boolean).returns(String) }
def self.decorate_dependency(dep, installed:)
installed ? pretty_installed(dep) : pretty_uninstalled(dep)
end
sig { params(cask: Cask).returns(T.nilable(String)) }
def self.language_info(cask)
return if cask.languages.empty?
<<~EOS
#{ohai_title("Languages")}
#{cask.languages.join(", ")}
EOS
end
sig { params(cask: Cask).returns(T.nilable(String)) }
def self.repo_info(cask)
return if cask.tap.nil?
url = if cask.tap.custom_remote? && !cask.tap.remote.nil?
cask.tap.remote
else
"#{cask.tap.default_remote}/blob/HEAD/#{cask.tap.relative_cask_path(cask.token)}"
end
"From: #{Formatter.url(url)}"
end
sig { params(cask: Cask).returns(String) }
def self.artifact_info(cask)
artifact_output = ohai_title("Artifacts").dup
cask.artifacts.each do |artifact|
next unless artifact.respond_to?(:install_phase)
next unless DSL::ORDINARY_ARTIFACT_CLASSES.include?(artifact.class)
artifact_output << "\n" << artifact.to_s
end
artifact_output.freeze
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/url.rb | Library/Homebrew/cask/url.rb | # typed: strict
# frozen_string_literal: true
require "source_location"
require "utils/curl"
module Cask
# Class corresponding to the `url` stanza.
class URL
sig { returns(URI::Generic) }
attr_reader :uri
sig { returns(T.nilable(T::Hash[T.any(Symbol, String), String])) }
attr_reader :revisions
sig { returns(T.nilable(T::Boolean)) }
attr_reader :trust_cert
sig { returns(T.nilable(T::Hash[String, String])) }
attr_reader :cookies, :data
sig { returns(T.nilable(T.any(String, T::Array[String]))) }
attr_reader :header
sig { returns(T.nilable(T.any(URI::Generic, String))) }
attr_reader :referer
sig { returns(T::Hash[Symbol, T.untyped]) }
attr_reader :specs
sig { returns(T.nilable(T.any(Symbol, String))) }
attr_reader :user_agent
sig { returns(T.nilable(T.any(T::Class[AbstractDownloadStrategy], Symbol))) }
attr_reader :using
sig { returns(T.nilable(String)) }
attr_reader :tag, :branch, :revision, :only_path, :verified
extend Forwardable
def_delegators :uri, :path, :scheme, :to_s
# Creates a `url` stanza.
#
# @api public
sig {
params(
uri: T.any(URI::Generic, String),
verified: T.nilable(String),
using: T.nilable(T.any(T::Class[AbstractDownloadStrategy], Symbol)),
tag: T.nilable(String),
branch: T.nilable(String),
revisions: T.nilable(T::Hash[T.any(Symbol, String), String]),
revision: T.nilable(String),
trust_cert: T.nilable(T::Boolean),
cookies: T.nilable(T::Hash[T.any(String, Symbol), String]),
referer: T.nilable(T.any(URI::Generic, String)),
header: T.nilable(T.any(String, T::Array[String])),
user_agent: T.nilable(T.any(Symbol, String)),
data: T.nilable(T::Hash[String, String]),
only_path: T.nilable(String),
caller_location: Thread::Backtrace::Location,
).void
}
def initialize(
uri, verified: nil, using: nil, tag: nil, branch: nil, revisions: nil, revision: nil, trust_cert: nil,
cookies: nil, referer: nil, header: nil, user_agent: nil, data: nil, only_path: nil,
caller_location: caller_locations.fetch(0)
)
@uri = T.let(URI(uri), URI::Generic)
header = Array(header) unless header.nil?
specs = {}
specs[:verified] = @verified = T.let(verified, T.nilable(String))
specs[:using] = @using = T.let(using, T.nilable(T.any(T::Class[AbstractDownloadStrategy], Symbol)))
specs[:tag] = @tag = T.let(tag, T.nilable(String))
specs[:branch] = @branch = T.let(branch, T.nilable(String))
specs[:revisions] = @revisions = T.let(revisions, T.nilable(T::Hash[T.any(Symbol, String), String]))
specs[:revision] = @revision = T.let(revision, T.nilable(String))
specs[:trust_cert] = @trust_cert = T.let(trust_cert, T.nilable(T::Boolean))
specs[:cookies] =
@cookies = T.let(cookies&.transform_keys(&:to_s), T.nilable(T::Hash[String, String]))
specs[:referer] = @referer = T.let(referer, T.nilable(T.any(URI::Generic, String)))
specs[:headers] = @header = T.let(header, T.nilable(T.any(String, T::Array[String])))
specs[:user_agent] = @user_agent = T.let(user_agent || :default, T.nilable(T.any(Symbol, String)))
specs[:data] = @data = T.let(data, T.nilable(T::Hash[String, String]))
specs[:only_path] = @only_path = T.let(only_path, T.nilable(String))
@specs = T.let(specs.compact, T::Hash[Symbol, T.untyped])
@caller_location = caller_location
end
sig { returns(Homebrew::SourceLocation) }
def location
Homebrew::SourceLocation.new(@caller_location.lineno, raw_url_line&.index("url"))
end
sig { params(ignore_major_version: T::Boolean).returns(T::Boolean) }
def unversioned?(ignore_major_version: false)
interpolated_url = raw_url_line&.then { |line| line[/url\s+"([^"]+)"/, 1] }
return false unless interpolated_url
interpolated_url = interpolated_url.gsub(/\#{\s*arch\s*}/, "")
interpolated_url = interpolated_url.gsub(/\#{\s*version\s*\.major\s*}/, "") if ignore_major_version
interpolated_url.exclude?('#{')
end
private
sig { returns(T.nilable(String)) }
def raw_url_line
return @raw_url_line if defined?(@raw_url_line)
@raw_url_line = T.let(Pathname(T.must(@caller_location.path))
.each_line
.drop(@caller_location.lineno - 1)
.first, T.nilable(String))
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/artifact.rb | Library/Homebrew/cask/artifact.rb | # typed: strict
# frozen_string_literal: true
require "cask/artifact/app"
require "cask/artifact/artifact" # generic 'artifact' stanza
require "cask/artifact/audio_unit_plugin"
require "cask/artifact/binary"
require "cask/artifact/colorpicker"
require "cask/artifact/dictionary"
require "cask/artifact/font"
require "cask/artifact/input_method"
require "cask/artifact/installer"
require "cask/artifact/internet_plugin"
require "cask/artifact/keyboard_layout"
require "cask/artifact/manpage"
require "cask/artifact/vst_plugin"
require "cask/artifact/vst3_plugin"
require "cask/artifact/pkg"
require "cask/artifact/postflight_block"
require "cask/artifact/preflight_block"
require "cask/artifact/prefpane"
require "cask/artifact/qlplugin"
require "cask/artifact/mdimporter"
require "cask/artifact/screen_saver"
require "cask/artifact/bashcompletion"
require "cask/artifact/fishcompletion"
require "cask/artifact/zshcompletion"
require "cask/artifact/service"
require "cask/artifact/stage_only"
require "cask/artifact/suite"
require "cask/artifact/uninstall"
require "cask/artifact/zap"
module Cask
# Module containing all cask artifact classes.
module Artifact
MACOS_ONLY_ARTIFACTS = [
::Cask::Artifact::App,
::Cask::Artifact::AudioUnitPlugin,
::Cask::Artifact::Colorpicker,
::Cask::Artifact::Dictionary,
::Cask::Artifact::InputMethod,
::Cask::Artifact::InternetPlugin,
::Cask::Artifact::KeyboardLayout,
::Cask::Artifact::Mdimporter,
::Cask::Artifact::Pkg,
::Cask::Artifact::Prefpane,
::Cask::Artifact::Qlplugin,
::Cask::Artifact::ScreenSaver,
::Cask::Artifact::Service,
::Cask::Artifact::Suite,
::Cask::Artifact::VstPlugin,
::Cask::Artifact::Vst3Plugin,
].freeze
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/caskroom.rb | Library/Homebrew/cask/caskroom.rb | # typed: strict
# frozen_string_literal: true
require "utils/user"
require "utils/output"
module Cask
# Helper functions for interacting with the `Caskroom` directory.
#
# @api internal
module Caskroom
extend ::Utils::Output::Mixin
sig { returns(Pathname) }
def self.path
@path ||= T.let(HOMEBREW_PREFIX/"Caskroom", T.nilable(Pathname))
end
# Return all paths for installed casks.
sig { returns(T::Array[Pathname]) }
def self.paths
return [] unless path.exist?
path.children.select { |p| p.directory? && !p.symlink? }
end
private_class_method :paths
# Return all tokens for installed casks.
sig { returns(T::Array[String]) }
def self.tokens
paths.map { |path| path.basename.to_s }
end
sig { returns(T::Boolean) }
def self.any_casks_installed?
paths.any?
end
sig { void }
def self.ensure_caskroom_exists
return if path.exist?
sudo = !path.parent.writable?
if sudo && !ENV.key?("SUDO_ASKPASS") && $stdout.tty?
ohai "Creating Caskroom directory: #{path}",
"We'll set permissions properly so we won't need sudo in the future."
end
SystemCommand.run("mkdir", args: ["-p", path], sudo:)
SystemCommand.run("chmod", args: ["g+rwx", path], sudo:)
SystemCommand.run("chown", args: [User.current.to_s, path], sudo:)
chgrp_path(path, sudo)
end
sig { params(path: Pathname, sudo: T::Boolean).void }
def self.chgrp_path(path, sudo)
SystemCommand.run("chgrp", args: ["admin", path], sudo:)
end
# Get all installed casks.
#
# @api internal
sig { params(config: T.nilable(Config)).returns(T::Array[Cask]) }
def self.casks(config: nil)
tokens.sort.filter_map do |token|
CaskLoader.load_prefer_installed(token, config:, warn: false)
rescue TapCaskAmbiguityError => e
e.loaders.fetch(0).load(config:)
rescue
# Don't blow up because of a single unavailable cask.
nil
end
end
end
end
require "extend/os/cask/caskroom"
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/upgrade.rb | Library/Homebrew/cask/upgrade.rb | # typed: strict
# frozen_string_literal: true
require "env_config"
require "cask/config"
require "utils/output"
module Cask
class Upgrade
extend ::Utils::Output::Mixin
sig { returns(T::Array[String]) }
def self.greedy_casks
if (upgrade_greedy_casks = Homebrew::EnvConfig.upgrade_greedy_casks.presence)
upgrade_greedy_casks.split
else
[]
end
end
sig {
params(
casks: T::Array[Cask],
args: Homebrew::CLI::Args,
force: T.nilable(T::Boolean),
quiet: T.nilable(T::Boolean),
greedy: T.nilable(T::Boolean),
greedy_latest: T.nilable(T::Boolean),
greedy_auto_updates: T.nilable(T::Boolean),
).returns(T::Array[Cask])
}
def self.outdated_casks(casks, args:, force:, quiet:,
greedy: false, greedy_latest: false, greedy_auto_updates: false)
greedy = true if Homebrew::EnvConfig.upgrade_greedy?
if casks.empty?
Caskroom.casks(config: Config.from_args(args)).select do |cask|
cask_greedy = greedy || greedy_casks.include?(cask.token)
cask.outdated?(greedy: cask_greedy, greedy_latest:,
greedy_auto_updates:)
end
else
casks.select do |cask|
raise CaskNotInstalledError, cask if !cask.installed? && !force
if cask.outdated?(greedy: true)
true
elsif cask.version.latest?
opoo "Not upgrading #{cask.token}, the downloaded artifact has not changed" unless quiet
false
else
opoo "Not upgrading #{cask.token}, the latest version is already installed" unless quiet
false
end
end
end
end
sig {
params(
casks: Cask,
args: Homebrew::CLI::Args,
force: T.nilable(T::Boolean),
greedy: T.nilable(T::Boolean),
greedy_latest: T.nilable(T::Boolean),
greedy_auto_updates: T.nilable(T::Boolean),
dry_run: T.nilable(T::Boolean),
skip_cask_deps: T.nilable(T::Boolean),
verbose: T.nilable(T::Boolean),
quiet: T.nilable(T::Boolean),
binaries: T.nilable(T::Boolean),
quarantine: T.nilable(T::Boolean),
require_sha: T.nilable(T::Boolean),
).returns(T::Boolean)
}
def self.upgrade_casks!(
*casks,
args:,
force: false,
greedy: false,
greedy_latest: false,
greedy_auto_updates: false,
dry_run: false,
skip_cask_deps: false,
verbose: false,
quiet: false,
binaries: nil,
quarantine: nil,
require_sha: nil
)
quarantine = true if quarantine.nil?
outdated_casks =
self.outdated_casks(casks, args:, greedy:, greedy_latest:, greedy_auto_updates:, force:, quiet:)
manual_installer_casks = outdated_casks.select do |cask|
cask.artifacts.any? do |artifact|
artifact.is_a?(Artifact::Installer) && artifact.manual_install
end
end
if manual_installer_casks.present?
count = manual_installer_casks.count
ofail "Not upgrading #{count} `installer manual` #{::Utils.pluralize("cask", count)}."
puts manual_installer_casks.map(&:to_s)
outdated_casks -= manual_installer_casks
end
return false if outdated_casks.empty?
if casks.empty? && !greedy && greedy_casks.empty?
if !greedy_auto_updates && !greedy_latest
ohai "Casks with 'auto_updates true' or 'version :latest' " \
"will not be upgraded; pass `--greedy` to upgrade them."
end
if greedy_auto_updates && !greedy_latest
ohai "Casks with 'version :latest' will not be upgraded; pass `--greedy-latest` to upgrade them."
end
if !greedy_auto_updates && greedy_latest
ohai "Casks with 'auto_updates true' will not be upgraded; pass `--greedy-auto-updates` to upgrade them."
end
end
upgradable_casks = outdated_casks.map do |c|
unless c.installed?
odie <<~EOS
The cask '#{c.token}' was affected by a bug and cannot be upgraded as-is. To fix this, run:
brew reinstall --cask --force #{c.token}
EOS
end
[CaskLoader.load(c.installed_caskfile), c]
end
return false if upgradable_casks.empty?
if !dry_run && Homebrew::EnvConfig.download_concurrency > 1
download_queue = Homebrew::DownloadQueue.new(pour: true)
fetchable_casks = upgradable_casks.map(&:last)
fetchable_cask_installers = fetchable_casks.map do |cask|
# This is significantly easier given the weird difference in Sorbet signatures here.
# rubocop:disable Style/DoubleNegation
Installer.new(cask, binaries: !!binaries, verbose: !!verbose, force: !!force,
skip_cask_deps: !!skip_cask_deps, require_sha: !!require_sha,
upgrade: true, quarantine:, download_queue:)
# rubocop:enable Style/DoubleNegation
end
fetchable_cask_installers.each(&:prelude)
fetchable_casks_sentence = fetchable_casks.map { |cask| Formatter.identifier(cask.full_name) }.to_sentence
oh1 "Fetching downloads for: #{fetchable_casks_sentence}", truncate: false
fetchable_cask_installers.each(&:enqueue_downloads)
download_queue.fetch
end
verb = dry_run ? "Would upgrade" : "Upgrading"
oh1 "#{verb} #{upgradable_casks.count} outdated #{::Utils.pluralize("package", upgradable_casks.count)}:"
caught_exceptions = []
puts upgradable_casks
.map { |(old_cask, new_cask)| "#{new_cask.full_name} #{old_cask.version} -> #{new_cask.version}" }
.join("\n")
return true if dry_run
upgradable_casks.each do |(old_cask, new_cask)|
upgrade_cask(
old_cask, new_cask,
binaries:, force:, skip_cask_deps:, verbose:,
quarantine:, require_sha:, download_queue:
)
rescue => e
new_exception = e.exception("#{new_cask.full_name}: #{e}")
new_exception.set_backtrace(e.backtrace)
caught_exceptions << new_exception
next
end
return true if caught_exceptions.empty?
raise MultipleCaskErrors, caught_exceptions if caught_exceptions.count > 1
raise caught_exceptions.fetch(0) if caught_exceptions.one?
false
end
sig {
params(
old_cask: Cask,
new_cask: Cask,
binaries: T.nilable(T::Boolean),
force: T.nilable(T::Boolean),
quarantine: T.nilable(T::Boolean),
require_sha: T.nilable(T::Boolean),
skip_cask_deps: T.nilable(T::Boolean),
verbose: T.nilable(T::Boolean),
download_queue: T.nilable(Homebrew::DownloadQueue),
).void
}
def self.upgrade_cask(
old_cask, new_cask,
binaries:, force:, quarantine:, require_sha:, skip_cask_deps:, verbose:, download_queue:
)
require "cask/installer"
start_time = Time.now
odebug "Started upgrade process for Cask #{old_cask}"
old_config = old_cask.config
old_options = {
binaries:,
verbose:,
force:,
upgrade: true,
}.compact
old_cask_installer =
Installer.new(old_cask, **old_options)
new_cask.config = new_cask.default_config.merge(old_config)
new_options = {
binaries:,
verbose:,
force:,
skip_cask_deps:,
require_sha:,
upgrade: true,
quarantine:,
download_queue:,
}.compact
new_cask_installer =
Installer.new(new_cask, **new_options)
started_upgrade = false
new_artifacts_installed = false
begin
oh1 "Upgrading #{Formatter.identifier(old_cask)}"
# Start new cask's installation steps
new_cask_installer.check_conflicts
if (caveats = new_cask_installer.caveats)
puts caveats
end
new_cask_installer.fetch
# Move the old cask's artifacts back to staging
old_cask_installer.start_upgrade(successor: new_cask)
# And flag it so in case of error
started_upgrade = true
# Install the new cask
new_cask_installer.stage
new_cask_installer.install_artifacts(predecessor: old_cask)
new_artifacts_installed = true
# If successful, wipe the old cask from staging.
old_cask_installer.finalize_upgrade
rescue => e
new_cask_installer.uninstall_artifacts(successor: old_cask) if new_artifacts_installed
new_cask_installer.purge_versioned_files
old_cask_installer.revert_upgrade(predecessor: new_cask) if started_upgrade
raise e
end
end_time = Time.now
Homebrew.messages.package_installed(new_cask.token, end_time - start_time)
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/cask/installer.rb | Library/Homebrew/cask/installer.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "formula_installer"
require "unpack_strategy"
require "utils/topological_hash"
require "utils/analytics"
require "utils/output"
require "cask/config"
require "cask/download"
require "cask/migrator"
require "cask/quarantine"
require "cask/tab"
module Cask
# Installer for a {Cask}.
class Installer
extend ::Utils::Output::Mixin
include ::Utils::Output::Mixin
sig {
params(
cask: ::Cask::Cask, command: T.class_of(SystemCommand), force: T::Boolean, adopt: T::Boolean,
skip_cask_deps: T::Boolean, binaries: T::Boolean, verbose: T::Boolean, zap: T::Boolean,
require_sha: T::Boolean, upgrade: T::Boolean, reinstall: T::Boolean, installed_as_dependency: T::Boolean,
installed_on_request: T::Boolean, quarantine: T::Boolean, verify_download_integrity: T::Boolean,
quiet: T::Boolean, download_queue: T.nilable(Homebrew::DownloadQueue)
).void
}
def initialize(cask, command: SystemCommand, force: false, adopt: false,
skip_cask_deps: false, binaries: true, verbose: false,
zap: false, require_sha: false, upgrade: false, reinstall: false,
installed_as_dependency: false, installed_on_request: true,
quarantine: true, verify_download_integrity: true, quiet: false, download_queue: nil)
@cask = cask
@command = command
@force = force
@adopt = adopt
@skip_cask_deps = skip_cask_deps
@binaries = binaries
@verbose = verbose
@zap = zap
@require_sha = require_sha
@reinstall = reinstall
@upgrade = upgrade
@installed_as_dependency = installed_as_dependency
@installed_on_request = installed_on_request
@quarantine = quarantine
@verify_download_integrity = verify_download_integrity
@quiet = quiet
@download_queue = download_queue
@ran_prelude = T.let(false, T::Boolean)
end
sig { returns(T::Boolean) }
def adopt? = @adopt
sig { returns(T::Boolean) }
def binaries? = @binaries
sig { returns(T::Boolean) }
def force? = @force
sig { returns(T::Boolean) }
def installed_as_dependency? = @installed_as_dependency
sig { returns(T::Boolean) }
def installed_on_request? = @installed_on_request
sig { returns(T::Boolean) }
def quarantine? = @quarantine
sig { returns(T::Boolean) }
def quiet? = @quiet
sig { returns(T::Boolean) }
def reinstall? = @reinstall
sig { returns(T::Boolean) }
def require_sha? = @require_sha
sig { returns(T::Boolean) }
def skip_cask_deps? = @skip_cask_deps
sig { returns(T::Boolean) }
def upgrade? = @upgrade
sig { returns(T::Boolean) }
def verbose? = @verbose
sig { returns(T::Boolean) }
def zap? = @zap
def self.caveats(cask)
odebug "Printing caveats"
caveats = cask.caveats
return if caveats.empty?
Homebrew.messages.record_caveats(cask.token, caveats)
<<~EOS
#{ohai_title "Caveats"}
#{caveats}
EOS
end
sig { params(quiet: T.nilable(T::Boolean), timeout: T.nilable(T.any(Integer, Float))).void }
def fetch(quiet: nil, timeout: nil)
odebug "Cask::Installer#fetch"
load_cask_from_source_api! if cask_from_source_api?
verify_has_sha if require_sha? && !force?
check_requirements
forbidden_tap_check
forbidden_cask_and_formula_check
forbidden_cask_artifacts_check
download(quiet:, timeout:) if @download_queue.nil?
satisfy_cask_and_formula_dependencies
end
sig { void }
def stage
odebug "Cask::Installer#stage"
Caskroom.ensure_caskroom_exists
extract_primary_container
process_rename_operations
save_caskfile
rescue => e
purge_versioned_files
raise e
end
sig { void }
def install
start_time = Time.now
odebug "Cask::Installer#install"
Migrator.migrate_if_needed(@cask)
old_config = @cask.config
predecessor = @cask if reinstall? && @cask.installed?
prelude
print caveats
fetch
uninstall_existing_cask if reinstall?
backup if force? && @cask.staged_path.exist? && @cask.metadata_versioned_path.exist?
oh1 "Installing Cask #{Formatter.identifier(@cask)}"
# GitHub Actions globally disables Gatekeeper.
unless quarantine?
opoo_outside_github_actions "--no-quarantine bypasses macOS’s Gatekeeper, reducing system security. " \
"Do not use this flag unless you understand the risks."
end
stage
@cask.config = @cask.default_config.merge(old_config)
install_artifacts(predecessor:)
tab = Tab.create(@cask)
tab.installed_as_dependency = installed_as_dependency?
tab.installed_on_request = installed_on_request?
tab.write
if (tap = @cask.tap) && tap.should_report_analytics?
::Utils::Analytics.report_package_event(:cask_install, package_name: @cask.token, tap_name: tap.name,
on_request: true)
end
purge_backed_up_versioned_files
puts summary
end_time = Time.now
Homebrew.messages.package_installed(@cask.token, end_time - start_time)
rescue
restore_backup
raise
end
sig { void }
def check_deprecate_disable
deprecate_disable_type = DeprecateDisable.type(@cask)
return if deprecate_disable_type.nil?
message = DeprecateDisable.message(@cask).to_s
message_full = "#{@cask.token} has been #{message}"
case deprecate_disable_type
when :deprecated
opoo message_full
when :disabled
GitHub::Actions.puts_annotation_if_env_set!(:error, message)
raise CaskCannotBeInstalledError.new(@cask, message)
end
end
sig { void }
def check_conflicts
return unless @cask.conflicts_with
@cask.conflicts_with[:cask].each do |conflicting_cask|
if (conflicting_cask_tap_with_token = Tap.with_cask_token(conflicting_cask))
conflicting_cask_tap, = conflicting_cask_tap_with_token
next unless conflicting_cask_tap.installed?
end
conflicting_cask = CaskLoader.load(conflicting_cask)
raise CaskConflictError.new(@cask, conflicting_cask) if conflicting_cask.installed?
rescue CaskUnavailableError
next # Ignore conflicting Casks that do not exist.
end
end
sig { void }
def uninstall_existing_cask
return unless @cask.installed?
# Always force uninstallation, ignore method parameter
cask_installer = Installer.new(@cask, verbose: verbose?, force: true, upgrade: upgrade?, reinstall: true)
zap? ? cask_installer.zap : cask_installer.uninstall(successor: @cask)
end
sig { returns(String) }
def summary
s = +""
s << "#{Homebrew::EnvConfig.install_badge} " unless Homebrew::EnvConfig.no_emoji?
s << "#{@cask} was successfully #{upgrade? ? "upgraded" : "installed"}!"
s.freeze
end
sig { returns(Download) }
def downloader
@downloader ||= Download.new(@cask, quarantine: quarantine?)
end
sig { params(quiet: T.nilable(T::Boolean), timeout: T.nilable(T.any(Integer, Float))).returns(Pathname) }
def download(quiet: nil, timeout: nil)
# Store cask download path in cask to prevent multiple downloads in a row when checking if it's outdated
@cask.download ||= downloader.fetch(quiet:, verify_download_integrity: @verify_download_integrity,
timeout:)
end
sig { void }
def verify_has_sha
odebug "Checking cask has checksum"
return if @cask.sha256 != :no_check
raise CaskError, <<~EOS
Cask '#{@cask}' does not have a sha256 checksum defined and was not installed.
This means you have the #{Formatter.identifier("--require-sha")} option set, perhaps in your `$HOMEBREW_CASK_OPTS`.
EOS
end
def primary_container
@primary_container ||= begin
downloaded_path = download(quiet: true)
UnpackStrategy.detect(downloaded_path, type: @cask.container&.type, merge_xattrs: true)
end
end
sig { returns(ArtifactSet) }
def artifacts
@cask.artifacts
end
sig { params(to: Pathname).void }
def extract_primary_container(to: @cask.staged_path)
odebug "Extracting primary container"
odebug "Using container class #{primary_container.class} for #{primary_container.path}"
basename = downloader.basename
if (nested_container = @cask.container&.nested)
Dir.mktmpdir("cask-installer", HOMEBREW_TEMP) do |tmpdir|
tmpdir = Pathname(tmpdir)
primary_container.extract(to: tmpdir, basename:, verbose: verbose?)
FileUtils.chmod_R "+rw", tmpdir/nested_container, force: true, verbose: verbose?
UnpackStrategy.detect(tmpdir/nested_container, merge_xattrs: true)
.extract_nestedly(to:, verbose: verbose?)
end
else
primary_container.extract_nestedly(to:, basename:, verbose: verbose?)
end
return unless quarantine?
return unless Quarantine.available?
Quarantine.propagate(from: primary_container.path, to:)
end
sig { params(target_dir: T.nilable(Pathname)).void }
def process_rename_operations(target_dir: nil)
return if @cask.rename.empty?
working_dir = target_dir || @cask.staged_path
odebug "Processing rename operations in #{working_dir}"
@cask.rename.each do |rename_operation|
odebug "Renaming #{rename_operation.from} to #{rename_operation.to}"
rename_operation.perform_rename(working_dir)
end
end
sig { params(predecessor: T.nilable(Cask)).void }
def install_artifacts(predecessor: nil)
already_installed_artifacts = []
odebug "Installing artifacts"
artifacts.each do |artifact|
next unless artifact.respond_to?(:install_phase)
odebug "Installing artifact of class #{artifact.class}"
next if artifact.is_a?(Artifact::Binary) && !binaries?
artifact = T.cast(
artifact,
T.any(
Artifact::AbstractFlightBlock,
Artifact::Installer,
Artifact::KeyboardLayout,
Artifact::Mdimporter,
Artifact::Moved,
Artifact::Pkg,
Artifact::Qlplugin,
Artifact::Symlinked,
),
)
artifact.install_phase(
command: @command, verbose: verbose?, adopt: adopt?, auto_updates: @cask.auto_updates,
force: force?, predecessor:
)
already_installed_artifacts.unshift(artifact)
end
save_config_file
save_download_sha if @cask.version.latest?
rescue => e
begin
already_installed_artifacts&.each do |artifact|
if artifact.respond_to?(:uninstall_phase)
odebug "Reverting installation of artifact of class #{artifact.class}"
artifact.uninstall_phase(command: @command, verbose: verbose?, force: force?)
end
next unless artifact.respond_to?(:post_uninstall_phase)
odebug "Reverting installation of artifact of class #{artifact.class}"
artifact.post_uninstall_phase(command: @command, verbose: verbose?, force: force?)
end
ensure
purge_versioned_files
raise e
end
end
sig { void }
def check_requirements
check_stanza_os_requirements
check_macos_requirements
check_arch_requirements
end
sig { void }
def check_stanza_os_requirements
nil
end
def check_macos_requirements
return unless @cask.depends_on.macos
return if @cask.depends_on.macos.satisfied?
raise CaskError, @cask.depends_on.macos.message(type: :cask)
end
sig { void }
def check_arch_requirements
return if @cask.depends_on.arch.nil?
@current_arch ||= { type: Hardware::CPU.type, bits: Hardware::CPU.bits }
return if @cask.depends_on.arch.any? do |arch|
arch[:type] == @current_arch[:type] &&
Array(arch[:bits]).include?(@current_arch[:bits])
end
raise CaskError,
"Cask #{@cask} depends on hardware architecture being one of " \
"[#{@cask.depends_on.arch.map(&:to_s).join(", ")}], " \
"but you are running #{@current_arch}."
end
sig { returns(T::Array[T.untyped]) }
def cask_and_formula_dependencies
return @cask_and_formula_dependencies if @cask_and_formula_dependencies
graph = ::Utils::TopologicalHash.graph_package_dependencies(@cask)
raise CaskSelfReferencingDependencyError, @cask.token if graph.fetch(@cask).include?(@cask)
::Utils::TopologicalHash.graph_package_dependencies(primary_container.dependencies, graph)
begin
@cask_and_formula_dependencies = graph.tsort - [@cask]
rescue TSort::Cyclic
strongly_connected_components = graph.strongly_connected_components.sort_by(&:count)
cyclic_dependencies = strongly_connected_components.last - [@cask]
raise CaskCyclicDependencyError.new(@cask.token, cyclic_dependencies.to_sentence)
end
end
def missing_cask_and_formula_dependencies
cask_and_formula_dependencies.reject do |cask_or_formula|
case cask_or_formula
when Formula
cask_or_formula.any_version_installed? && cask_or_formula.optlinked?
when Cask
cask_or_formula.installed?
end
end
end
def satisfy_cask_and_formula_dependencies
return if installed_as_dependency?
formulae_and_casks = cask_and_formula_dependencies
return if formulae_and_casks.empty?
missing_formulae_and_casks = missing_cask_and_formula_dependencies
if missing_formulae_and_casks.empty?
puts "All dependencies satisfied."
return
end
ohai "Installing dependencies: #{missing_formulae_and_casks.map(&:to_s).join(", ")}"
cask_installers = T.let([], T::Array[Installer])
formula_installers = T.let([], T::Array[FormulaInstaller])
missing_formulae_and_casks.each do |cask_or_formula|
if cask_or_formula.is_a?(Cask)
if skip_cask_deps?
opoo "`--skip-cask-deps` is set; skipping installation of #{cask_or_formula}."
next
end
cask_installers << Installer.new(
cask_or_formula,
adopt: adopt?,
binaries: binaries?,
force: false,
installed_as_dependency: true,
installed_on_request: false,
quarantine: quarantine?,
quiet: quiet?,
require_sha: require_sha?,
verbose: verbose?,
)
else
formula_installers << FormulaInstaller.new(
cask_or_formula,
**{
show_header: true,
installed_as_dependency: true,
installed_on_request: false,
verbose: verbose?,
}.compact,
)
end
end
cask_installers.each(&:install)
return if formula_installers.blank?
Homebrew::Install.perform_preinstall_checks_once
valid_formula_installers = Homebrew::Install.fetch_formulae(formula_installers)
valid_formula_installers.each do |formula_installer|
formula_installer.install
formula_installer.finish
end
end
def caveats
self.class.caveats(@cask)
end
def metadata_subdir
@metadata_subdir ||= @cask.metadata_subdir("Casks", timestamp: :now, create: true)
end
def save_caskfile
old_savedir = @cask.metadata_timestamped_path
return if @cask.source.blank?
extension = @cask.loaded_from_api? ? "json" : "rb"
(metadata_subdir/"#{@cask.token}.#{extension}").write @cask.source
FileUtils.rm_r(old_savedir) if old_savedir
end
def save_config_file
@cask.config_path.atomic_write(@cask.config.to_json)
end
def save_download_sha
@cask.download_sha_path.atomic_write(@cask.new_download_sha) if @cask.checksumable?
end
sig { params(successor: T.nilable(Cask)).void }
def uninstall(successor: nil)
load_installed_caskfile!
oh1 "Uninstalling Cask #{Formatter.identifier(@cask)}"
uninstall_artifacts(clear: true, successor:)
if !reinstall? && !upgrade?
remove_tabfile
remove_download_sha
remove_config_file
end
purge_versioned_files
purge_caskroom_path if force?
end
def remove_tabfile
tabfile = @cask.tab.tabfile
FileUtils.rm_f tabfile if tabfile
@cask.config_path.parent.rmdir_if_possible
end
def remove_config_file
FileUtils.rm_f @cask.config_path
@cask.config_path.parent.rmdir_if_possible
end
def remove_download_sha
FileUtils.rm_f @cask.download_sha_path
@cask.download_sha_path.parent.rmdir_if_possible
end
sig { params(successor: T.nilable(Cask)).void }
def start_upgrade(successor:)
uninstall_artifacts(successor:)
backup
end
def backup
@cask.staged_path.rename backup_path
@cask.metadata_versioned_path.rename backup_metadata_path
end
def restore_backup
return if !backup_path.directory? || !backup_metadata_path.directory?
FileUtils.rm_r(@cask.staged_path) if @cask.staged_path.exist?
FileUtils.rm_r(@cask.metadata_versioned_path) if @cask.metadata_versioned_path.exist?
backup_path.rename @cask.staged_path
backup_metadata_path.rename @cask.metadata_versioned_path
end
sig { params(predecessor: Cask).void }
def revert_upgrade(predecessor:)
opoo "Reverting upgrade for Cask #{@cask}"
restore_backup
install_artifacts(predecessor:)
end
def finalize_upgrade
ohai "Purging files for version #{@cask.version} of Cask #{@cask}"
purge_backed_up_versioned_files
puts summary
end
sig { params(clear: T::Boolean, successor: T.nilable(Cask)).void }
def uninstall_artifacts(clear: false, successor: nil)
odebug "Uninstalling artifacts"
odebug "#{::Utils.pluralize("artifact", artifacts.length, include_count: true)} defined", artifacts
artifacts.each do |artifact|
if artifact.respond_to?(:uninstall_phase)
artifact = T.cast(
artifact,
T.any(
Artifact::AbstractFlightBlock,
Artifact::KeyboardLayout,
Artifact::Moved,
Artifact::Qlplugin,
Artifact::Symlinked,
Artifact::Uninstall,
),
)
odebug "Uninstalling artifact of class #{artifact.class}"
artifact.uninstall_phase(
command: @command,
verbose: verbose?,
skip: clear,
force: force?,
successor:,
upgrade: upgrade?,
reinstall: reinstall?,
)
end
next unless artifact.respond_to?(:post_uninstall_phase)
artifact = T.cast(artifact, Artifact::Uninstall)
odebug "Post-uninstalling artifact of class #{artifact.class}"
artifact.post_uninstall_phase(
command: @command,
verbose: verbose?,
skip: clear,
force: force?,
successor:,
)
end
end
def zap
load_installed_caskfile!
uninstall_artifacts
if (zap_stanzas = @cask.artifacts.select { |a| a.is_a?(Artifact::Zap) }).empty?
opoo "No zap stanza present for Cask '#{@cask}'"
else
ohai "Dispatching zap stanza"
zap_stanzas.each do |stanza|
stanza.zap_phase(command: @command, verbose: verbose?, force: force?)
end
end
ohai "Removing all staged versions of Cask '#{@cask}'"
purge_caskroom_path
end
def backup_path
return if @cask.staged_path.nil?
Pathname("#{@cask.staged_path}.upgrading")
end
def backup_metadata_path
return if @cask.metadata_versioned_path.nil?
Pathname("#{@cask.metadata_versioned_path}.upgrading")
end
def gain_permissions_remove(path)
Utils.gain_permissions_remove(path, command: @command)
end
def purge_backed_up_versioned_files
# versioned staged distribution
gain_permissions_remove(backup_path) if backup_path&.exist?
# Homebrew Cask metadata
return unless backup_metadata_path.directory?
backup_metadata_path.children.each do |subdir|
gain_permissions_remove(subdir)
end
backup_metadata_path.rmdir_if_possible
end
def purge_versioned_files
ohai "Purging files for version #{@cask.version} of Cask #{@cask}"
# versioned staged distribution
gain_permissions_remove(@cask.staged_path) if @cask.staged_path&.exist?
# Homebrew Cask metadata
if @cask.metadata_versioned_path.directory?
@cask.metadata_versioned_path.children.each do |subdir|
gain_permissions_remove(subdir)
end
@cask.metadata_versioned_path.rmdir_if_possible
end
@cask.metadata_main_container_path.rmdir_if_possible unless upgrade?
# toplevel staged distribution
@cask.caskroom_path.rmdir_if_possible unless upgrade?
# Remove symlinks for renamed casks if they are now broken.
@cask.old_tokens.each do |old_token|
old_caskroom_path = Caskroom.path/old_token
FileUtils.rm old_caskroom_path if old_caskroom_path.symlink? && !old_caskroom_path.exist?
end
end
def purge_caskroom_path
odebug "Purging all staged versions of Cask #{@cask}"
gain_permissions_remove(@cask.caskroom_path)
end
sig { void }
def forbidden_tap_check
return if Tap.allowed_taps.blank? && Tap.forbidden_taps.blank?
owner = Homebrew::EnvConfig.forbidden_owner
owner_contact = if (contact = Homebrew::EnvConfig.forbidden_owner_contact.presence)
"\n#{contact}"
end
unless skip_cask_deps?
cask_and_formula_dependencies.each do |cask_or_formula|
dep_tap = cask_or_formula.tap
next if dep_tap.blank? || (dep_tap.allowed_by_env? && !dep_tap.forbidden_by_env?)
dep_full_name = cask_or_formula.full_name
error_message = "The installation of #{@cask} has a dependency #{dep_full_name}\n" \
"from the #{dep_tap} tap but #{owner} "
error_message << "has not allowed this tap in `$HOMEBREW_ALLOWED_TAPS`" unless dep_tap.allowed_by_env?
error_message << " and\n" if !dep_tap.allowed_by_env? && dep_tap.forbidden_by_env?
error_message << "has forbidden this tap in `$HOMEBREW_FORBIDDEN_TAPS`" if dep_tap.forbidden_by_env?
error_message << ".#{owner_contact}"
raise CaskCannotBeInstalledError.new(@cask, error_message)
end
end
cask_tap = @cask.tap
return if cask_tap.blank? || (cask_tap.allowed_by_env? && !cask_tap.forbidden_by_env?)
error_message = "The installation of #{@cask.full_name} has the tap #{cask_tap}\n" \
"but #{owner} "
error_message << "has not allowed this tap in `$HOMEBREW_ALLOWED_TAPS`" unless cask_tap.allowed_by_env?
error_message << " and\n" if !cask_tap.allowed_by_env? && cask_tap.forbidden_by_env?
error_message << "has forbidden this tap in `$HOMEBREW_FORBIDDEN_TAPS`" if cask_tap.forbidden_by_env?
error_message << ".#{owner_contact}"
raise CaskCannotBeInstalledError.new(@cask, error_message)
end
sig { void }
def forbidden_cask_and_formula_check
forbid_casks = Homebrew::EnvConfig.forbid_casks?
forbidden_formulae = Set.new(Homebrew::EnvConfig.forbidden_formulae.to_s.split)
forbidden_casks = Set.new(Homebrew::EnvConfig.forbidden_casks.to_s.split)
return if !forbid_casks && forbidden_formulae.blank? && forbidden_casks.blank?
owner = Homebrew::EnvConfig.forbidden_owner
owner_contact = if (contact = Homebrew::EnvConfig.forbidden_owner_contact.presence)
"\n#{contact}"
end
unless skip_cask_deps?
cask_and_formula_dependencies.each do |dep_cask_or_formula|
dep_name, dep_type, variable = if dep_cask_or_formula.is_a?(Cask) && forbidden_casks.present?
dep_cask = dep_cask_or_formula
env_variable = "HOMEBREW_FORBIDDEN_CASKS"
dep_cask_name = if forbid_casks
env_variable = "HOMEBREW_FORBID_CASKS"
dep_cask.token
elsif forbidden_casks.include?(dep_cask.full_name)
dep_cask.token
elsif dep_cask.tap.present? &&
forbidden_casks.include?(dep_cask.full_name)
dep_cask.full_name
end
[dep_cask_name, "cask", env_variable]
elsif dep_cask_or_formula.is_a?(Formula) && forbidden_formulae.present?
dep_formula = dep_cask_or_formula
formula_name = if forbidden_formulae.include?(dep_formula.name)
dep_formula.name
elsif dep_formula.tap.present? &&
forbidden_formulae.include?(dep_formula.full_name)
dep_formula.full_name
end
[formula_name, "formula", "HOMEBREW_FORBIDDEN_FORMULAE"]
end
next if dep_name.blank?
raise CaskCannotBeInstalledError.new(@cask, <<~EOS
has a dependency #{dep_name} but the
#{dep_name} #{dep_type} was forbidden for installation by #{owner} in `#{variable}`.#{owner_contact}
EOS
)
end
end
return if !forbid_casks && forbidden_casks.blank?
variable = "HOMEBREW_FORBIDDEN_CASKS"
if forbid_casks
variable = "HOMEBREW_FORBID_CASKS"
@cask.token
elsif forbidden_casks.include?(@cask.token)
@cask.token
elsif forbidden_casks.include?(@cask.full_name)
@cask.full_name
else
return
end
raise CaskCannotBeInstalledError.new(@cask, <<~EOS
forbidden for installation by #{owner} in `#{variable}`.#{owner_contact}
EOS
)
end
sig { void }
def forbidden_cask_artifacts_check
forbidden_artifacts = Set.new(Homebrew::EnvConfig.forbidden_cask_artifacts.to_s.split)
return if forbidden_artifacts.blank?
owner = Homebrew::EnvConfig.forbidden_owner
owner_contact = if (contact = Homebrew::EnvConfig.forbidden_owner_contact.presence)
"\n#{contact}"
end
artifacts.each do |artifact|
# Get the artifact class name (e.g., "Pkg", "Installer", "App")
artifact_name = artifact.class.name
next if artifact_name.nil?
artifact_type = artifact_name.split("::").last&.downcase
next if artifact_type.nil?
next unless forbidden_artifacts.include?(artifact_type)
raise CaskCannotBeInstalledError.new(@cask, <<~EOS
contains a '#{artifact_type}' artifact, which is forbidden for installation by #{owner} in `HOMEBREW_FORBIDDEN_CASK_ARTIFACTS`.#{owner_contact}
EOS
)
end
end
sig { void }
def prelude
return if @ran_prelude
check_deprecate_disable
check_conflicts
@ran_prelude = true
end
sig { void }
def enqueue_downloads
download_queue = @download_queue
return if download_queue.nil?
# FIXME: We need to load Cask source before enqueuing to support
# language-specific URLs, but this will block the main process.
if cask_from_source_api?
if @cask.languages.any?
load_cask_from_source_api!
else
Homebrew::API::Cask.source_download(@cask, download_queue:)
end
end
download_queue.enqueue(downloader)
end
private
# load the same cask file that was used for installation, if possible
sig { void }
def load_installed_caskfile!
Migrator.migrate_if_needed(@cask)
installed_caskfile = @cask.installed_caskfile
if installed_caskfile&.exist?
begin
@cask = CaskLoader.load_from_installed_caskfile(installed_caskfile)
return
rescue CaskInvalidError, CaskUnavailableError
# could be caused by trying to load outdated or deleted caskfile
end
end
load_cask_from_source_api! if cask_from_source_api?
# otherwise we default to the current cask
end
sig { void }
def load_cask_from_source_api!
@cask = Homebrew::API::Cask.source_download_cask(@cask)
end
sig { returns(T::Boolean) }
def cask_from_source_api?
@cask.loaded_from_api? && @cask.caskfile_only?
end
end
end
require "extend/os/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/cask/audit.rb | Library/Homebrew/cask/audit.rb | # typed: strict
# frozen_string_literal: true
require "cask/denylist"
require "cask/download"
require "cask/installer"
require "cask/quarantine"
require "digest"
require "livecheck/livecheck"
require "source_location"
require "system_command"
require "utils/backtrace"
require "formula_name_cask_token_auditor"
require "utils/curl"
require "utils/git"
require "utils/shared_audits"
require "utils/output"
module Cask
# Audit a cask for various problems.
class Audit
include SystemCommand::Mixin
include ::Utils::Curl
include ::Utils::Output::Mixin
Error = T.type_alias do
{
message: T.nilable(String),
location: T.nilable(Homebrew::SourceLocation),
corrected: T::Boolean,
}
end
sig { returns(Cask) }
attr_reader :cask
sig { returns(T.nilable(Download)) }
attr_reader :download
sig {
params(
cask: ::Cask::Cask, download: T::Boolean, quarantine: T::Boolean,
online: T.nilable(T::Boolean), strict: T.nilable(T::Boolean), signing: T.nilable(T::Boolean),
new_cask: T.nilable(T::Boolean), only: T::Array[String], except: T::Array[String]
).void
}
def initialize(
cask,
download: false, quarantine: false,
online: nil, strict: nil, signing: nil,
new_cask: nil, only: [], except: []
)
# `new_cask` implies `online`, `strict` and `signing`
online = new_cask if online.nil?
strict = new_cask if strict.nil?
signing = new_cask if signing.nil?
# `online` and `signing` imply `download`
download ||= online || signing
@cask = cask
@download = T.let(nil, T.nilable(Download))
@download = Download.new(cask, quarantine:) if download
@online = online
@strict = strict
@signing = signing
@new_cask = new_cask
@only = only
@except = except
@livecheck_result = T.let(nil, T.nilable(T.any(T::Boolean, Symbol)))
end
sig { returns(T::Boolean) }
def new_cask? = !!@new_cask
sig { returns(T::Boolean) }
def online? =!!@online
sig { returns(T::Boolean) }
def signing? = !!@signing
sig { returns(T::Boolean) }
def strict? = !!@strict
sig { returns(::Cask::Audit) }
def run!
only_audits = @only
except_audits = @except
private_methods.map(&:to_s).grep(/^audit_/).each do |audit_method_name|
name = audit_method_name.delete_prefix("audit_")
next if !only_audits.empty? && only_audits.exclude?(name)
next if except_audits.include?(name)
send(audit_method_name)
end
self
rescue => e
odebug e, ::Utils::Backtrace.clean(e)
add_error "exception while auditing #{cask}: #{e.message}"
self
end
sig { returns(T::Array[Error]) }
def errors
@errors ||= T.let([], T.nilable(T::Array[Error]))
end
sig { returns(T::Boolean) }
def errors?
errors.any?
end
sig { returns(T::Boolean) }
def success?
!errors?
end
sig {
params(
message: T.nilable(String),
location: T.nilable(Homebrew::SourceLocation),
strict_only: T::Boolean,
).void
}
def add_error(message, location: nil, strict_only: false)
# Only raise non-critical audits if the user specified `--strict`.
return if strict_only && !@strict
errors << { message:, location:, corrected: false }
end
sig { returns(T.nilable(String)) }
def result
Formatter.error("failed") if errors?
end
sig { returns(T.nilable(String)) }
def summary
return if success?
summary = ["audit for #{cask}: #{result}"]
errors.each do |error|
summary << " #{Formatter.error("-")} #{error[:message]}"
end
summary.join("\n")
end
private
sig { void }
def audit_untrusted_pkg
odebug "Auditing pkg stanza: allow_untrusted"
return if @cask.sourcefile_path.nil?
tap = @cask.tap
return if tap.nil?
return if tap.user != "Homebrew"
return if cask.artifacts.none? { |k| k.is_a?(Artifact::Pkg) && k.stanza_options.key?(:allow_untrusted) }
add_error "allow_untrusted is not permitted in official Homebrew Cask taps"
end
sig { void }
def audit_stanza_requires_uninstall
odebug "Auditing stanzas which require an uninstall"
return if cask.artifacts.none? { |k| k.is_a?(Artifact::Pkg) || k.is_a?(Artifact::Installer) }
return if cask.artifacts.any?(Artifact::Uninstall)
add_error "installer and pkg stanzas require an uninstall stanza"
end
sig { void }
def audit_single_pre_postflight
odebug "Auditing preflight and postflight stanzas"
if cask.artifacts.count { |k| k.is_a?(Artifact::PreflightBlock) && k.directives.key?(:preflight) } > 1
add_error "only a single preflight stanza is allowed"
end
count = cask.artifacts.count do |k|
k.is_a?(Artifact::PostflightBlock) &&
k.directives.key?(:postflight)
end
return if count <= 1
add_error "only a single postflight stanza is allowed"
end
sig { void }
def audit_single_uninstall_zap
odebug "Auditing single uninstall_* and zap stanzas"
count = cask.artifacts.count do |k|
k.is_a?(Artifact::PreflightBlock) &&
k.directives.key?(:uninstall_preflight)
end
add_error "only a single uninstall_preflight stanza is allowed" if count > 1
count = cask.artifacts.count do |k|
k.is_a?(Artifact::PostflightBlock) &&
k.directives.key?(:uninstall_postflight)
end
add_error "only a single uninstall_postflight stanza is allowed" if count > 1
return if cask.artifacts.count { |k| k.is_a?(Artifact::Zap) } <= 1
add_error "only a single zap stanza is allowed"
end
sig { void }
def audit_required_stanzas
odebug "Auditing required stanzas"
[:version, :sha256, :url, :homepage].each do |sym|
add_error "a #{sym} stanza is required" unless cask.send(sym)
end
add_error "at least one name stanza is required" if cask.name.empty?
# TODO: specific DSL knowledge should not be spread around in various files like this
rejected_artifacts = [:uninstall, :zap]
installable_artifacts = cask.artifacts.reject { |k| rejected_artifacts.include?(k) }
add_error "at least one activatable artifact stanza is required" if installable_artifacts.empty?
end
sig { void }
def audit_description
# Fonts seldom benefit from descriptions and requiring them disproportionately
# increases the maintenance burden.
return if cask.tap == "homebrew/cask" && cask.token.include?("font-")
add_error("Cask should have a description. Please add a `desc` stanza.", strict_only: true) if cask.desc.blank?
end
sig { void }
def audit_version_special_characters
return unless cask.version
return if cask.version.latest?
raw_version = cask.version.raw_version
return if raw_version.exclude?(":") && raw_version.exclude?("/")
add_error "version should not contain colons or slashes"
end
sig { void }
def audit_no_string_version_latest
return unless cask.version
odebug "Auditing version :latest does not appear as a string ('latest')"
return if cask.version.raw_version != "latest"
add_error "you should use version :latest instead of version 'latest'"
end
sig { void }
def audit_sha256_no_check_if_latest
return unless cask.sha256
return unless cask.version
odebug "Auditing sha256 :no_check with version :latest"
return unless cask.version.latest?
return if cask.sha256 == :no_check
add_error "you should use sha256 :no_check when version is :latest"
end
sig { void }
def audit_sha256_no_check_if_unversioned
return unless cask.sha256
return if cask.sha256 == :no_check
return unless cask.url&.unversioned?
add_error "Use `sha256 :no_check` when URL is unversioned."
end
sig { void }
def audit_sha256_actually_256
return unless cask.sha256
odebug "Auditing sha256 string is a legal SHA-256 digest"
return unless cask.sha256.is_a?(Checksum)
return if cask.sha256.length == 64 && cask.sha256[/^[0-9a-f]+$/i]
add_error "sha256 string must be of 64 hexadecimal characters"
end
sig { void }
def audit_sha256_invalid
return unless cask.sha256
odebug "Auditing sha256 is not a known invalid value"
empty_sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
return if cask.sha256 != empty_sha256
add_error "cannot use the sha256 for an empty string: #{empty_sha256}"
end
sig { void }
def audit_latest_with_livecheck
return unless cask.version&.latest?
return unless cask.livecheck_defined?
return if cask.livecheck.skip?
add_error "Casks with a `livecheck` should not use `version :latest`."
end
sig { void }
def audit_latest_with_auto_updates
return unless cask.version&.latest?
return unless cask.auto_updates
add_error "Casks with `version :latest` should not use `auto_updates`."
end
LIVECHECK_REFERENCE_URL = "https://docs.brew.sh/Cask-Cookbook#stanza-livecheck"
private_constant :LIVECHECK_REFERENCE_URL
sig { void }
def audit_hosting_with_livecheck
return if cask.deprecated? || cask.disabled?
return if cask.version&.latest?
return if (url = cask.url).nil?
return if cask.livecheck_defined?
return if audit_livecheck_version == :auto_detected
add_livecheck = "please add a livecheck. See #{Formatter.url(LIVECHECK_REFERENCE_URL)}"
case url.to_s
when %r{sourceforge.net/(\S+)}
return unless online?
add_error "Download is hosted on SourceForge, #{add_livecheck}", location: url.location
when %r{dl.devmate.com/(\S+)}
add_error "Download is hosted on DevMate, #{add_livecheck}", location: url.location
when %r{rink.hockeyapp.net/(\S+)}
add_error "Download is hosted on HockeyApp, #{add_livecheck}", location: url.location
end
end
SOURCEFORGE_OSDN_REFERENCE_URL = "https://docs.brew.sh/Cask-Cookbook#sourceforgeosdn-urls"
private_constant :SOURCEFORGE_OSDN_REFERENCE_URL
sig { void }
def audit_download_url_format
return if (url = cask.url).nil?
odebug "Auditing URL format"
return unless bad_sourceforge_url?
add_error "SourceForge URL format incorrect. See #{Formatter.url(SOURCEFORGE_OSDN_REFERENCE_URL)}",
location: url.location
end
sig { void }
def audit_download_url_is_osdn
return if (url = cask.url).nil?
return unless bad_osdn_url?
add_error "OSDN download urls are disabled.", location: url.location, strict_only: true
end
VERIFIED_URL_REFERENCE_URL = "https://docs.brew.sh/Cask-Cookbook#when-url-and-homepage-domains-differ-add-verified"
private_constant :VERIFIED_URL_REFERENCE_URL
sig { void }
def audit_unnecessary_verified
return unless cask.url
return unless verified_present?
return unless url_match_homepage?
return unless verified_matches_url?
add_error "The URL's domain #{Formatter.url(domain)} matches the homepage domain " \
"#{Formatter.url(homepage)}, the 'verified' parameter of the 'url' stanza is unnecessary. " \
"See #{Formatter.url(VERIFIED_URL_REFERENCE_URL)}"
end
sig { void }
def audit_missing_verified
return unless cask.url
return if file_url?
return if url_match_homepage?
return if verified_present?
add_error "The URL's domain #{Formatter.url(domain)} does not match the homepage domain " \
"#{Formatter.url(homepage)}, a 'verified' parameter has to be added to the 'url' stanza. " \
"See #{Formatter.url(VERIFIED_URL_REFERENCE_URL)}"
end
sig { void }
def audit_no_match
return if (url = cask.url).nil?
return unless verified_present?
return if verified_matches_url?
add_error "Verified URL #{Formatter.url(url_from_verified)} does not match URL " \
"#{Formatter.url(strip_url_scheme(url.to_s))}. " \
"See #{Formatter.url(VERIFIED_URL_REFERENCE_URL)}",
location: url.location
end
sig { void }
def audit_generic_artifacts
cask.artifacts.select { |a| a.is_a?(Artifact::Artifact) }.each do |artifact|
unless artifact.target.absolute?
add_error "target must be absolute path for #{artifact.class.english_name} #{artifact.source}"
end
end
end
sig { void }
def audit_languages
@cask.languages.each do |language|
Locale.parse(language)
rescue Locale::ParserError
add_error "Locale '#{language}' is invalid."
end
end
sig { void }
def audit_token
token_auditor = Homebrew::FormulaNameCaskTokenAuditor.new(cask.token)
return if (errors = token_auditor.errors).none?
add_error "Cask token '#{cask.token}' must not contain #{errors.to_sentence(two_words_connector: " or ",
last_word_connector: " or ")}."
end
sig { void }
def audit_token_conflicts
Homebrew.with_no_api_env do
return unless core_formula_names.include?(cask.token)
add_error("cask token conflicts with an existing homebrew/core formula: #{Formatter.url(core_formula_url)}")
end
end
sig { void }
def audit_token_bad_words
return unless new_cask?
token = cask.token
add_error "cask token contains .app" if token.end_with? ".app"
match_data = /-(?<designation>alpha|beta|rc|release-candidate)$/.match(cask.token)
if match_data && cask.tap&.official?
add_error "cask token contains version designation '#{match_data[:designation]}'"
end
add_error("cask token mentions launcher", strict_only: true) if token.end_with? "launcher"
add_error("cask token mentions desktop", strict_only: true) if token.end_with? "desktop"
add_error("cask token mentions platform", strict_only: true) if token.end_with? "mac", "osx", "macos"
add_error("cask token mentions architecture", strict_only: true) if token.end_with? "x86", "32_bit", "x86_64",
"64_bit"
frameworks = %w[cocoa qt gtk wx java]
return if frameworks.include?(token) || !token.end_with?(*frameworks)
add_error("cask token mentions framework", strict_only: true)
end
sig { void }
def audit_download
return if (download = self.download).blank? || (url = cask.url).nil?
begin
download.fetch
rescue => e
add_error "download not possible: #{e}", location: url.location
end
end
sig { void }
def audit_livecheck_unneeded_long_version
return if cask.version.nil? || (url = cask.url).nil?
return if cask.livecheck.strategy != :sparkle
return unless cask.version.csv.second
return if cask.url.to_s.include? cask.version.csv.second
return if cask.version.csv.third.present? && cask.url.to_s.include?(cask.version.csv.third)
add_error "Download does not require additional version components. Use `&:short_version` in the livecheck",
location: url.location,
strict_only: true
end
sig { void }
def audit_signing
return if download.blank?
url = cask.url
return if url.nil?
return if !cask.tap.official? && !signing?
return if cask.deprecated? && cask.deprecation_reason != :fails_gatekeeper_check
unless Quarantine.available?
odebug "Quarantine support is not available, skipping signing audit"
return
end
odebug "Auditing signing"
is_in_skiplist = cask.tap&.audit_exception(:signing_audit_skiplist, cask.token)
extract_artifacts do |artifacts, tmpdir|
is_container = artifacts.any? { |a| a.is_a?(Artifact::App) || a.is_a?(Artifact::Pkg) }
any_signing_failure = artifacts.any? do |artifact|
next false if artifact.is_a?(Artifact::Binary) && is_container == true
artifact_path = artifact.is_a?(Artifact::Pkg) ? artifact.path : artifact.source
path = tmpdir/artifact_path.relative_path_from(cask.staged_path)
unless Quarantine.detect(path)
odebug "#{path} does not have quarantine attributes, skipping signing audit"
next false
end
result = case artifact
when Artifact::Pkg
system_command("spctl", args: ["--assess", "--type", "install", path], print_stderr: false)
when Artifact::App
next opoo "gktool not found, skipping app signing audit" unless which("gktool")
system_command("gktool", args: ["scan", path], print_stderr: false)
when Artifact::Binary
# Shell scripts cannot be signed, so we skip them
next false if path.text_executable?
system_command("codesign", args: ["--verify", "-R=notarized", "--check-notarization", path],
print_stderr: false)
else
add_error "Unknown artifact type: #{artifact.class}", location: url.location
next
end
next false if result.success?
next true if cask.deprecated? && cask.deprecation_reason == :fails_gatekeeper_check
next true if is_in_skiplist
signing_failure_message = <<~EOS
Signature verification failed:
#{result.merged_output}
EOS
if cask.tap.official?
signing_failure_message += <<~EOS
The homebrew/cask tap requires all casks to be signed and notarized by Apple.
Please contact the upstream developer and ask them to sign and notarize their software.
EOS
end
add_error signing_failure_message
true
end
return if any_signing_failure
add_error "Cask is in the signing audit skiplist, but does not need to be skipped!" if is_in_skiplist
return unless cask.deprecated?
return if cask.deprecation_reason != :fails_gatekeeper_check
add_error <<~EOS
Cask is deprecated because it failed Gatekeeper checks but all artifacts now pass!
Remove the deprecate/disable stanza or update the deprecate/disable reason.
EOS
end
end
sig {
params(
_block: T.nilable(T.proc.params(
arg0: T::Array[T.any(Artifact::Pkg, Artifact::Relocated)],
arg1: Pathname,
).void),
).void
}
def extract_artifacts(&_block)
return unless online?
return if (download = self.download).nil?
artifacts = cask.artifacts.select do |artifact|
artifact.is_a?(Artifact::Pkg) || artifact.is_a?(Artifact::App) || artifact.is_a?(Artifact::Binary)
end
if @artifacts_extracted && @tmpdir
yield artifacts, @tmpdir if block_given?
return
end
return if artifacts.empty?
@tmpdir ||= T.let(Pathname(Dir.mktmpdir("cask-audit", HOMEBREW_TEMP)), T.nilable(Pathname))
# Clean up tmp dir when @tmpdir object is destroyed
ObjectSpace.define_finalizer(
@tmpdir,
proc { FileUtils.remove_entry(@tmpdir) },
)
ohai "Downloading and extracting artifacts"
downloaded_path = download.fetch
primary_container = UnpackStrategy.detect(downloaded_path, type: @cask.container&.type, merge_xattrs: true)
return if primary_container.nil?
# If the container has any dependencies we need to install them or unpacking will fail.
if primary_container.dependencies.any?
install_options = {
show_header: true,
installed_as_dependency: true,
installed_on_request: false,
verbose: false,
}.compact
Homebrew::Install.perform_preinstall_checks_once
formula_installers = primary_container.dependencies.filter_map do |dep|
next unless dep.is_a?(Formula)
FormulaInstaller.new(
dep,
**install_options,
)
end
valid_formula_installers = Homebrew::Install.fetch_formulae(formula_installers)
formula_installers.each do |fi|
next unless valid_formula_installers.include?(fi)
fi.install
fi.finish
end
end
# Extract the container to the temporary directory.
primary_container.extract_nestedly(to: @tmpdir, basename: downloaded_path.basename, verbose: false)
if (nested_container = @cask.container&.nested)
FileUtils.chmod_R "+rw", @tmpdir/nested_container, force: true, verbose: false
UnpackStrategy.detect(@tmpdir/nested_container, merge_xattrs: true)
.extract_nestedly(to: @tmpdir, verbose: false)
end
# Process rename operations after extraction
# Create a temporary installer to process renames in the audit directory
temp_installer = Installer.new(@cask)
temp_installer.process_rename_operations(target_dir: @tmpdir)
# Set the flag to indicate that extraction has occurred.
@artifacts_extracted = T.let(true, T.nilable(TrueClass))
# Yield the artifacts and temp directory to the block if provided.
yield artifacts, @tmpdir if block_given?
end
sig { void }
def audit_rosetta
return if (url = cask.url).nil?
return unless online?
# Rosetta 2 is only for ARM-capable macOS versions, which are Big Sur (11.x) and later
return if Homebrew::SimulateSystem.current_arch != :arm
return if MacOSVersion::SYMBOLS.fetch(Homebrew::SimulateSystem.current_os, "10") < "11"
return if cask.depends_on.macos&.maximum_version.to_s < "11"
odebug "Auditing Rosetta 2 requirement"
extract_artifacts do |artifacts, tmpdir|
is_container = artifacts.any? { |a| a.is_a?(Artifact::App) || a.is_a?(Artifact::Pkg) }
mentions_rosetta = cask.caveats.include?("requires Rosetta 2")
requires_intel = cask.depends_on.arch&.any? { |arch| arch[:type] == :intel }
artifacts_to_test = artifacts.filter do |artifact|
next false if !artifact.is_a?(Artifact::App) && !artifact.is_a?(Artifact::Binary)
next false if artifact.is_a?(Artifact::Binary) && is_container
true
end
next if artifacts_to_test.blank?
any_requires_rosetta = artifacts_to_test.any? do |artifact|
artifact = T.cast(artifact, T.any(Artifact::App, Artifact::Binary))
path = tmpdir/artifact.source.relative_path_from(cask.staged_path)
result = case artifact
when Artifact::App
files = Dir[path/"Contents/MacOS/*"].select do |f|
File.executable?(f) && !File.directory?(f) && !f.end_with?(".dylib")
end
add_error "No binaries in App: #{artifact.source}", location: url.location if files.empty?
main_binary = get_plist_main_binary(path)
main_binary ||= files.fetch(0)
system_command("lipo", args: ["-archs", main_binary], print_stderr: false)
when Artifact::Binary
binary_path = path.to_s.gsub(cask.appdir, tmpdir.to_s)
system_command("lipo", args: ["-archs", binary_path], print_stderr: true)
else
T.absurd(artifact)
end
# binary stanza can contain shell scripts, so we just continue if lipo fails.
next false unless result.success?
odebug "Architectures: #{result.merged_output}"
unless /arm64|x86_64/.match?(result.merged_output)
add_error "Artifacts architecture is no longer supported by macOS!",
location: url.location
next
end
result.merged_output.exclude?("arm64") && result.merged_output.include?("x86_64")
end
if any_requires_rosetta
if !mentions_rosetta && !requires_intel
add_error "At least one artifact requires Rosetta 2 but this is not indicated by the caveats!",
location: url.location
end
elsif mentions_rosetta
add_error "No artifacts require Rosetta 2 but the caveats say otherwise!",
location: url.location
end
end
end
sig { returns(T.nilable(T.any(T::Boolean, Symbol))) }
def audit_livecheck_version
return @livecheck_result unless @livecheck_result.nil?
return unless online?
return unless cask.version
odebug "Auditing livecheck version"
referenced_cask, = Homebrew::Livecheck.resolve_livecheck_reference(cask)
# Respect skip conditions for a referenced cask
if referenced_cask
skip_info = Homebrew::Livecheck::SkipConditions.referenced_skip_information(
referenced_cask,
Homebrew::Livecheck.package_or_resource_name(cask),
)
end
# Respect cask skip conditions (e.g. deprecated, disabled, latest, unversioned)
skip_info ||= Homebrew::Livecheck::SkipConditions.skip_information(cask)
if skip_info.present?
@livecheck_result = :skip
return @livecheck_result
end
latest_version = Homebrew::Livecheck.latest_version(
cask,
referenced_formula_or_cask: referenced_cask,
)&.fetch(:latest, nil)
if latest_version && (cask.version.to_s == latest_version.to_s)
@livecheck_result = :auto_detected
return @livecheck_result
end
add_error "Version '#{cask.version}' differs from '#{latest_version}' retrieved by livecheck."
@livecheck_result = false
end
sig { void }
def audit_min_os
return unless online?
odebug "Auditing minimum macOS version"
bundle_min_os = cask_bundle_min_os
sparkle_min_os = cask_sparkle_min_os
app_min_os = bundle_min_os || sparkle_min_os
debug_messages = []
debug_messages << "from artifact: #{bundle_min_os.to_sym}" if bundle_min_os
debug_messages << "from upstream: #{sparkle_min_os.to_sym}" if sparkle_min_os
odebug "Detected minimum macOS: #{app_min_os.to_sym} (#{debug_messages.join(" | ")})" if app_min_os
return if app_min_os.nil? || app_min_os <= HOMEBREW_MACOS_OLDEST_ALLOWED
on_system_block_min_os = cask.on_system_block_min_os
depends_on_min_os = cask.depends_on.macos&.minimum_version
cask_min_os = [on_system_block_min_os, depends_on_min_os].compact.max
debug_messages = []
debug_messages << "from on_system block: #{on_system_block_min_os.to_sym}" if on_system_block_min_os
if depends_on_min_os > HOMEBREW_MACOS_OLDEST_ALLOWED
debug_messages << "from depends_on stanza: #{depends_on_min_os.to_sym}"
end
odebug "Declared minimum macOS: #{cask_min_os.to_sym} (#{debug_messages.join(" | ").presence || "default"})"
return if cask_min_os.to_sym == app_min_os.to_sym
# ignore declared minimum OS < 11.x when auditing as ARM a cask with arch-specific artifacts
return if OnSystem.arch_condition_met?(:arm) &&
cask.on_system_blocks_exist? &&
cask_min_os.present? &&
app_min_os < MacOSVersion.new("11") &&
app_min_os < cask_min_os
min_os_definition = if cask_min_os > HOMEBREW_MACOS_OLDEST_ALLOWED
definition = if T.must(on_system_block_min_os.to_s <=> depends_on_min_os.to_s).positive?
"an on_system block"
else
"a depends_on stanza"
end
"#{definition} with a minimum macOS version of #{cask_min_os.to_sym.inspect}"
else
"no minimum macOS version"
end
source = T.must(bundle_min_os.to_s <=> sparkle_min_os.to_s).positive? ? "Artifact" : "Upstream"
add_error "#{source} defined #{app_min_os.to_sym.inspect} as the minimum macOS version " \
"but the cask declared #{min_os_definition}"
end
sig { returns(T.nilable(MacOSVersion)) }
def cask_sparkle_min_os
return unless online?
return unless cask.livecheck_defined?
return if cask.livecheck.strategy != :sparkle
# `Sparkle` strategy blocks that use the `items` argument (instead of
# `item`) contain arbitrary logic that ignores/overrides the strategy's
# sorting, so we can't identify which item would be first/newest here.
return if cask.livecheck.strategy_block.present? &&
cask.livecheck.strategy_block.parameters[0] == [:opt, :items]
content = Homebrew::Livecheck::Strategy.page_content(cask.livecheck.url)[:content]
return if content.blank?
begin
items = Homebrew::Livecheck::Strategy::Sparkle.sort_items(
Homebrew::Livecheck::Strategy::Sparkle.filter_items(
Homebrew::Livecheck::Strategy::Sparkle.items_from_content(content),
),
)
rescue
return
end
return if items.blank?
min_os = items[0]&.minimum_system_version&.strip_patch
# Big Sur is sometimes identified as 10.16, so we override it to the
# expected macOS version (11).
min_os = MacOSVersion.new("11") if min_os == "10.16"
min_os
end
sig { returns(T.nilable(MacOSVersion)) }
def cask_bundle_min_os
return unless online?
min_os = T.let(nil, T.untyped)
@staged_path ||= T.let(cask.staged_path, T.nilable(Pathname))
extract_artifacts do |artifacts, tmpdir|
artifacts.each do |artifact|
artifact_path = artifact.is_a?(Artifact::Pkg) ? artifact.path : artifact.source
path = tmpdir/artifact_path.relative_path_from(cask.staged_path)
info_plist_paths = Dir.glob("#{path}/**/Contents/Info.plist")
# Ensure the main `Info.plist` file is checked first, as this can
# sometimes use the min_os version from a framework instead
if info_plist_paths.delete("#{path}/Contents/Info.plist")
info_plist_paths.insert(0, "#{path}/Contents/Info.plist")
end
info_plist_paths.each do |plist_path|
next unless File.exist?(plist_path)
plist = system_command!("plutil", args: ["-convert", "xml1", "-o", "-", plist_path]).plist
min_os = plist["LSMinimumSystemVersion"].presence
break if min_os
# Get the app bundle path from the plist path
app_bundle_path = Pathname(plist_path).dirname.dirname
next unless (main_binary = get_plist_main_binary(app_bundle_path))
next if !File.exist?(main_binary) || File.open(main_binary, "rb") { |f| f.read(2) == "#!" }
macho = MachO.open(main_binary)
min_os = case macho
when MachO::MachOFile
[
macho[:LC_VERSION_MIN_MACOSX].first&.version_string,
macho[:LC_BUILD_VERSION].first&.minos_string,
]
when MachO::FatFile
# Collect requirements by architecture
arch_min_os = { arm: [], intel: [] }
macho.machos.each do |slice|
macos_reqs = [
slice[:LC_VERSION_MIN_MACOSX].first&.version_string,
slice[:LC_BUILD_VERSION].first&.minos_string,
]
case slice.cputype
when *Hardware::CPU::ARM_ARCHS
arch_min_os[:arm].concat(macos_reqs)
when *Hardware::CPU::INTEL_ARCHS
arch_min_os[:intel].concat(macos_reqs)
end
end
# Only use the requirements for the current architecture
arch_min_os.fetch(Homebrew::SimulateSystem.current_arch, [])
end.compact.max
break if min_os
end
break if min_os
end
end
begin
MacOSVersion.new(min_os).strip_patch
rescue MacOSVersion::Error
nil
end
end
sig { params(path: Pathname).returns(T.nilable(String)) }
def get_plist_main_binary(path)
return unless online?
plist_path = "#{path}/Contents/Info.plist"
return unless File.exist?(plist_path)
plist = system_command!("plutil", args: ["-convert", "xml1", "-o", "-", plist_path]).plist
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/cask_loader.rb | Library/Homebrew/cask/cask_loader.rb | # typed: true # rubocop:todo Sorbet/StrictSigil
# frozen_string_literal: true
require "cask/cache"
require "cask/cask"
require "uri"
require "utils/curl"
require "utils/output"
require "utils/path"
require "extend/hash/keys"
require "api"
module Cask
# Loads a cask from various sources.
module CaskLoader
extend Context
extend ::Utils::Output::Mixin
ALLOWED_URL_SCHEMES = %w[file].freeze
private_constant :ALLOWED_URL_SCHEMES
module ILoader
extend T::Helpers
include ::Utils::Output::Mixin
interface!
sig { abstract.params(config: T.nilable(Config)).returns(Cask) }
def load(config:); end
end
# Loads a cask from a string.
class AbstractContentLoader
include ILoader
extend T::Helpers
abstract!
sig { returns(String) }
attr_reader :content
sig { returns(T.nilable(Tap)) }
attr_reader :tap
private
sig {
overridable.params(
header_token: String,
options: T.untyped,
block: T.nilable(T.proc.bind(DSL).void),
).returns(Cask)
}
def cask(header_token, **options, &block)
Cask.new(header_token, source: content, tap:, **options, config: @config, &block)
end
end
# Loads a cask from a string.
class FromContentLoader < AbstractContentLoader
sig {
params(ref: T.any(Pathname, String, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
return if ref.is_a?(Cask)
content = ref.to_str
# Cache compiled regex
@regex ||= begin
token = /(?:"[^"]*"|'[^']*')/
curly = /\(\s*#{token.source}\s*\)\s*\{.*\}/
do_end = /\s+#{token.source}\s+do(?:\s*;\s*|\s+).*end/
/\A\s*cask(?:#{curly.source}|#{do_end.source})\s*\Z/m
end
return unless content.match?(@regex)
new(content)
end
sig { params(content: String, tap: Tap).void }
def initialize(content, tap: T.unsafe(nil))
super()
@content = content.dup.force_encoding("UTF-8")
@tap = tap
end
def load(config:)
@config = config
instance_eval(content, __FILE__, __LINE__)
end
end
# Loads a cask from a path.
class FromPathLoader < AbstractContentLoader
sig {
overridable.params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
path = case ref
when String
Pathname(ref)
when Pathname
ref
else
return
end
return unless path.expand_path.exist?
return if invalid_path?(path)
return unless ::Utils::Path.loadable_package_path?(path, :cask)
new(path)
end
sig { params(pathname: Pathname, valid_extnames: T::Array[String]).returns(T::Boolean) }
def self.invalid_path?(pathname, valid_extnames: %w[.rb .json])
return true if valid_extnames.exclude?(pathname.extname)
@invalid_basenames ||= %w[INSTALL_RECEIPT.json sbom.spdx.json].freeze
@invalid_basenames.include?(pathname.basename.to_s)
end
attr_reader :token, :path
sig { params(path: T.any(Pathname, String), token: String).void }
def initialize(path, token: T.unsafe(nil))
super()
path = Pathname(path).expand_path
@token = path.basename(path.extname).to_s
@path = path
@tap = Tap.from_path(path) || Homebrew::API.tap_from_source_download(path)
end
sig { override.params(config: T.nilable(Config)).returns(Cask) }
def load(config:)
raise CaskUnavailableError.new(token, "'#{path}' does not exist.") unless path.exist?
raise CaskUnavailableError.new(token, "'#{path}' is not readable.") unless path.readable?
raise CaskUnavailableError.new(token, "'#{path}' is not a file.") unless path.file?
@content = path.read(encoding: "UTF-8")
@config = config
if !self.class.invalid_path?(path, valid_extnames: %w[.json]) &&
(from_json = JSON.parse(@content).presence) &&
from_json.is_a?(Hash)
return FromAPILoader.new(token, from_json:, path:).load(config:)
end
begin
instance_eval(content, path).tap do |cask|
raise CaskUnreadableError.new(token, "'#{path}' does not contain a cask.") unless cask.is_a?(Cask)
end
rescue NameError, ArgumentError, ScriptError => e
error = CaskUnreadableError.new(token, e.message)
error.set_backtrace e.backtrace
raise error
end
end
private
def cask(header_token, **options, &block)
raise CaskTokenMismatchError.new(token, header_token) if token != header_token
super(header_token, **options, sourcefile_path: path, &block)
end
end
# Loads a cask from a URI.
class FromURILoader < FromPathLoader
sig {
override.params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
return if Homebrew::EnvConfig.forbid_packages_from_paths?
# Cache compiled regex
@uri_regex ||= begin
uri_regex = ::URI::RFC2396_PARSER.make_regexp
Regexp.new("\\A#{uri_regex.source}\\Z", uri_regex.options)
end
uri = ref.to_s
return unless uri.match?(@uri_regex)
uri = URI(uri)
return unless uri.path
new(uri)
end
attr_reader :url, :name
sig { params(url: T.any(URI::Generic, String)).void }
def initialize(url)
@url = URI(url)
@name = File.basename(T.must(@url.path))
super Cache.path/name
end
def load(config:)
path.dirname.mkpath
if ALLOWED_URL_SCHEMES.exclude?(url.scheme)
raise UnsupportedInstallationMethod,
"Non-checksummed download of #{name} formula file from an arbitrary URL is unsupported! " \
"`brew extract` or `brew create` and `brew tap-new` to create a formula file in a tap " \
"on GitHub instead."
end
begin
ohai "Downloading #{url}"
::Utils::Curl.curl_download url.to_s, to: path
rescue ErrorDuringExecution
raise CaskUnavailableError.new(token, "Failed to download #{Formatter.url(url)}.")
end
super
end
end
# Loads a cask from a specific tap.
class FromTapLoader < FromPathLoader
sig { returns(Tap) }
attr_reader :tap
sig {
override(allow_incompatible: true) # rubocop:todo Sorbet/AllowIncompatibleOverride
.params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.any(T.attached_class, FromAPILoader)))
}
def self.try_new(ref, warn: false)
ref = ref.to_s
return unless (token_tap_type = CaskLoader.tap_cask_token_type(ref, warn:))
token, tap, type = token_tap_type
if type == :migration && tap.core_cask_tap? && (loader = FromAPILoader.try_new(token))
loader
else
new("#{tap}/#{token}")
end
end
sig { params(tapped_token: String).void }
def initialize(tapped_token)
tap, token = Tap.with_cask_token(tapped_token)
cask = CaskLoader.find_cask_in_tap(token, tap)
super cask
end
sig { override.params(config: T.nilable(Config)).returns(Cask) }
def load(config:)
raise TapCaskUnavailableError.new(tap, token) unless T.must(tap).installed?
super
end
end
# Loads a cask from an existing {Cask} instance.
class FromInstanceLoader
include ILoader
sig {
params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
new(ref) if ref.is_a?(Cask)
end
sig { params(cask: Cask).void }
def initialize(cask)
@cask = cask
end
def load(config:)
@cask
end
end
# Loads a cask from the JSON API.
class FromAPILoader
include ILoader
sig { returns(String) }
attr_reader :token
sig { returns(Pathname) }
attr_reader :path
sig { returns(T.nilable(T::Hash[String, T.untyped])) }
attr_reader :from_json
sig {
params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
return if Homebrew::EnvConfig.no_install_from_api?
return unless ref.is_a?(String)
return unless (token = ref[HOMEBREW_DEFAULT_TAP_CASK_REGEX, :token])
if Homebrew::API.cask_tokens.exclude?(token) &&
!Homebrew::API.cask_renames.key?(token)
return
end
ref = "#{CoreCaskTap.instance}/#{token}"
token, tap, = CaskLoader.tap_cask_token_type(ref, warn:)
new("#{tap}/#{token}")
end
sig {
params(
token: String,
from_json: T.nilable(T::Hash[String, T.untyped]),
path: T.nilable(Pathname),
).void
}
def initialize(token, from_json: T.unsafe(nil), path: nil)
@token = token.sub(%r{^homebrew/(?:homebrew-)?cask/}i, "")
@sourcefile_path = path || Homebrew::API.cached_cask_json_file_path
@path = path || CaskLoader.default_path(@token)
@from_json = from_json
end
def load(config:)
json_cask = from_json
json_cask ||= if Homebrew::EnvConfig.use_internal_api?
Homebrew::API::Internal.cask_hashes.fetch(token)
else
Homebrew::API::Cask.all_casks.fetch(token)
end
cask_struct = Homebrew::API::Cask.generate_cask_struct_hash(json_cask)
cask_options = {
loaded_from_api: true,
api_source: json_cask,
sourcefile_path: @sourcefile_path,
source: JSON.pretty_generate(json_cask),
config:,
loader: self,
tap: Tap.fetch(cask_struct.tap_string),
}
api_cask = Cask.new(token, **cask_options) do
version cask_struct.version
sha256 cask_struct.sha256
url(*cask_struct.url_args, **cask_struct.url_kwargs)
cask_struct.names.each do |cask_name|
name cask_name
end
desc cask_struct.desc if cask_struct.desc?
homepage cask_struct.homepage
deprecate!(**cask_struct.deprecate_args) if cask_struct.deprecate?
disable!(**cask_struct.disable_args) if cask_struct.disable?
auto_updates cask_struct.auto_updates if cask_struct.auto_updates?
conflicts_with(**cask_struct.conflicts_with_args) if cask_struct.conflicts?
cask_struct.renames.each do |from, to|
rename from, to
end
if cask_struct.depends_on?
args = cask_struct.depends_on_args
begin
depends_on(**args)
rescue MacOSVersion::Error => e
odebug "Ignored invalid macOS version dependency in cask '#{token}': #{args.inspect} (#{e.message})"
nil
end
end
container(**cask_struct.container_args) if cask_struct.container?
cask_struct.artifacts(appdir:).each do |key, args, kwargs, block|
send(key, *args, **kwargs, &block)
end
caveats cask_struct.caveats(appdir:) if cask_struct.caveats?
end
api_cask.populate_from_api!(cask_struct)
api_cask
end
end
# Loader which tries loading casks from tap paths, failing
# if the same token exists in multiple taps.
class FromNameLoader < FromTapLoader
sig {
override.params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.any(T.attached_class, FromAPILoader)))
}
def self.try_new(ref, warn: false)
return unless ref.is_a?(String)
return unless ref.match?(/\A#{HOMEBREW_TAP_CASK_TOKEN_REGEX}\Z/o)
token = ref
# If it exists in the default tap, never treat it as ambiguous with another tap.
if (core_cask_tap = CoreCaskTap.instance).installed? &&
(core_cask_loader = super("#{core_cask_tap}/#{token}", warn:))&.path&.exist?
return core_cask_loader
end
loaders = Tap.select { |tap| tap.installed? && !tap.core_cask_tap? }
.filter_map { |tap| super("#{tap}/#{token}", warn:) }
.uniq(&:path)
.select { |loader| loader.is_a?(FromAPILoader) || loader.path.exist? }
case loaders.count
when 1
loaders.first
when 2..Float::INFINITY
raise TapCaskAmbiguityError.new(token, loaders)
end
end
end
# Loader which loads a cask from the installed cask file.
class FromInstalledPathLoader < FromPathLoader
sig {
override.params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
token = if ref.is_a?(String)
ref
elsif ref.is_a?(Pathname)
ref.basename(ref.extname).to_s
end
return unless token
possible_installed_cask = Cask.new(token)
return unless (installed_caskfile = possible_installed_cask.installed_caskfile)
new(installed_caskfile)
end
sig { params(path: T.any(Pathname, String), token: String).void }
def initialize(path, token: "")
super
installed_tap = Cask.new(@token).tab.tap
@tap = installed_tap if installed_tap
end
end
# Pseudo-loader which raises an error when trying to load the corresponding cask.
class NullLoader < FromPathLoader
sig {
override.params(ref: T.any(String, Pathname, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
return if ref.is_a?(Cask)
return if ref.is_a?(URI::Generic)
new(ref)
end
sig { params(ref: T.any(String, Pathname)).void }
def initialize(ref)
token = File.basename(ref, ".rb")
super CaskLoader.default_path(token)
end
def load(config:)
raise CaskUnavailableError.new(token, "No Cask with this name exists.")
end
end
def self.path(ref)
self.for(ref, need_path: true).path
end
def self.load(ref, config: nil, warn: true)
self.for(ref, warn:).load(config:)
end
sig { params(tapped_token: String, warn: T::Boolean).returns(T.nilable([String, Tap, T.nilable(Symbol)])) }
def self.tap_cask_token_type(tapped_token, warn:)
return unless (tap_with_token = Tap.with_cask_token(tapped_token))
tap, token = tap_with_token
type = nil
if (new_token = tap.cask_renames[token].presence)
old_token = tap.core_cask_tap? ? token : tapped_token
token = new_token
new_token = tap.core_cask_tap? ? token : "#{tap}/#{token}"
type = :rename
elsif (new_tap_name = tap.tap_migrations[token].presence)
new_tap, new_token = Tap.with_cask_token(new_tap_name)
unless new_tap
if new_tap_name.include?("/")
new_tap = Tap.fetch(new_tap_name)
new_token = token
else
new_tap = tap
new_token = new_tap_name
end
end
new_tap.ensure_installed!
new_tapped_token = "#{new_tap}/#{new_token}"
if tapped_token != new_tapped_token
old_token = tap.core_cask_tap? ? token : tapped_token
return unless (token_tap_type = tap_cask_token_type(new_tapped_token, warn: false))
token, tap, = token_tap_type
new_token = new_tap.core_cask_tap? ? token : "#{tap}/#{token}"
type = :migration
end
end
opoo "Cask #{old_token} was renamed to #{new_token}." if warn && old_token && new_token
[token, tap, type]
end
def self.for(ref, need_path: false, warn: true)
[
FromInstanceLoader,
FromContentLoader,
FromURILoader,
FromAPILoader,
FromTapLoader,
FromNameLoader,
FromPathLoader,
FromInstalledPathLoader,
NullLoader,
].each do |loader_class|
if (loader = loader_class.try_new(ref, warn:))
$stderr.puts "#{$PROGRAM_NAME} (#{loader.class}): loading #{ref}" if verbose? && debug?
return loader
end
end
end
sig { params(ref: String, config: T.nilable(Config), warn: T::Boolean).returns(Cask) }
def self.load_prefer_installed(ref, config: nil, warn: true)
tap, token = Tap.with_cask_token(ref)
token ||= ref
tap ||= Cask.new(ref).tab.tap
if tap.nil?
self.load(token, config:, warn:)
else
begin
self.load("#{tap}/#{token}", config:, warn:)
rescue CaskUnavailableError
# cask may be migrated to different tap. Try to search in all taps.
self.load(token, config:, warn:)
end
end
end
sig { params(path: Pathname, config: T.nilable(Config), warn: T::Boolean).returns(Cask) }
def self.load_from_installed_caskfile(path, config: nil, warn: true)
loader = FromInstalledPathLoader.try_new(path, warn:)
loader ||= NullLoader.new(path)
loader.load(config:)
end
def self.default_path(token)
find_cask_in_tap(token.to_s.downcase, CoreCaskTap.instance)
end
def self.find_cask_in_tap(token, tap)
filename = "#{token}.rb"
tap.cask_files_by_name.fetch(token, tap.cask_dir/filename)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/cask/list.rb | Library/Homebrew/cask/list.rb | # typed: strict
# frozen_string_literal: true
require "cask/artifact/relocated"
require "utils/output"
module Cask
class List
extend ::Utils::Output::Mixin
sig { params(casks: Cask, one: T::Boolean, full_name: T::Boolean, versions: T::Boolean).void }
def self.list_casks(*casks, one: false, full_name: false, versions: false)
output = if casks.any?
casks.each do |cask|
raise CaskNotInstalledError, cask unless cask.installed?
end
else
Caskroom.casks
end
if one
puts output.map(&:to_s)
elsif full_name
puts output.map(&:full_name).sort(&tap_and_name_comparison)
elsif versions
puts output.map { format_versioned(it) }
elsif !output.empty? && casks.any?
output.map { list_artifacts(it) }
elsif !output.empty?
puts Formatter.columns(output.map(&:to_s))
end
end
sig { params(cask: Cask).void }
def self.list_artifacts(cask)
cask.artifacts.group_by(&:class).sort_by { |klass, _| klass.english_name }.each do |klass, artifacts|
next if [Artifact::Uninstall, Artifact::Zap].include? klass
ohai klass.english_name
artifacts.each do |artifact|
puts artifact.summarize_installed if artifact.respond_to?(:summarize_installed)
next if artifact.respond_to?(:summarize_installed)
puts artifact
end
end
end
sig { params(cask: Cask).returns(String) }
def self.format_versioned(cask)
"#{cask}#{cask.installed_version&.prepend(" ")}"
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.